﻿/*
 * Return the module name from the "m" parameter if preset or the entire query string
 * @param URL The URL to parse
 * @return The module name
 */
function getModule(URL) {
	var s = getFragmentOrQuery(URL);
	var fields = getFields(s);
	if (fields['m']) return fields['m'];
	else return s;
}

/*
 * Return the section name of the module name (used in frame labels) as the lowercase version of the first part of the module
 */
function getSection(moduleName) {
	var i = moduleName.indexOf('/');
	if (i < 0) return moduleName.toLowerCase();
	else return moduleName.substring(0, i).toLowerCase();
}

/*
 * Return the UI name of the module name (used in magic) as the lowercase version of the last part of the module
 */
function getUI(moduleName) {
	var i = moduleName.lastIndexOf('/');
	if (i < 0) return moduleName.toLowerCase();
	else return moduleName.substring(i + 1).toLowerCase();
}

/*
 * Get the query parameters from a URL
 * @param URL The URL to parse
 * @return An array of query parameters
 */
function getParameters(URL) {
	return getFields(getFragmentOrQuery(URL));
}

/*
 * Return the query string or the URL fragment acting as a query string (overriding the true query string if present)
 * @param URI The URL to parse
 * @return The effective query string to use
 */
function getFragmentOrQuery(URI) {
	var i = URI.indexOf('?');
	var j = URI.indexOf('#');
	if (j > -1) return URI.substring(j + 1);
	if (i < 0) return '';
	return URI.substring(i + 1);
}

/*
 * Return fields from a query string (could be a fragment acting as a query string)
 * @param query The query string to parse for fields
 * @return An associative array of field values keyed by field name
 */
function getFields(query) {
	var queryPieces = query.split('&');
	var fields = [];
	for (var i = 0; i < queryPieces.length; i++) {
		var j = queryPieces[i].indexOf('=');
		// if the field is not a name & value pair, create a named member with empty string value
		if (j < 0) fields[unescape(queryPieces[i])] = '';
		// otherwise create the member with associated value
		else fields[unescape(queryPieces[i].substring(0, j))] = unescape(queryPieces[i].substring(j + 1));
	}
	return fields;
}
