/**
 * This script assumes that items available are from
 * 0 (inclusive) ~ total (exclusive). It also assumes
 * that the given url accepts "start", and "range" as
 * the _GET variables to control the start position
 * and the range.
 * 
 * 
 * @param cmd == first | prev | next | last | refresh | reload
 * @param url == The URL for the .get() function
 * @param id  == The id of the container to put the
 *               data in, the container should have
 *               containers with the:
 *                - <id>_paging_start
 *                - <id>_paging_range
 *                - <id>_paging_total
 *               so the paging function can calculate the
 *               new from using the command
 * @param data     == Extra data to be sent with the paging command
 * @param callback == The function to be called after the
 *                    data has been inserted
 */
function paging(cmd, url, id, data, callback) {
	// Get the from position, the range and the total
	var start = parseInt($('#'+id+'_paging_start').html());
	var range = parseInt($('#'+id+'_paging_range').html());
	var total = parseInt($('#'+id+'_paging_total').html());
	
	// Calculate the new start position
	var newStart = start;
	if( cmd == 'first' || cmd == 'refresh' ) newStart = 0;
	if( cmd == 'prev' )   newStart = newStart - range > 0     ? newStart - range : 0;
	if( cmd == 'next' )   newStart = newStart + range < total ? newStart + range : newStart;
	if( cmd == 'last' )   while( newStart + range < total ) newStart += range;
	if( cmd == 'reload' ); // do nothing as reloading this page
	// if the command is refresh or the new start is different to the current start
	if( cmd == 'refresh' || cmd == 'reload' || (newStart != start) ) {
		adminscreen = (document.getElementById('adminscreen')) ? document.getElementById('adminscreen').innerHTML : 0;
		var o = {
			'start': newStart,
			'range': range,
			'adminscreen': adminscreen
		};
		if( (data = data || null) != null ) {
			if( typeof data == 'object' ) {
				o = $.extend(o, data);
				if( (callback = callback || null) != null ) {
					return $('#'+id).load(url,o,callback);
				} else {
					return $('#'+id).load(url,o);
				}
			} else {
				return $('#'+id).load(url,o, data);
			}
		} else {
			return $('#'+id).load(url,o);
		}
	}
}

/**
 * Redirects the page to the specified url.
 * @param url The url to be redirected to
 */
function goTo(url, target) {
	target = target || 'self';
	if( typeof url == 'boolean' && !url ) {
		// do nothing
	} else if( url == 'self' ) {
		window.location.reload(true);
	} else {
		if( target == 'new' ) {
			window.open(url, '', '');
		} else {
			window.location = url;
		}
		
	}
	void(0);
}

/**
 * Converts a string to a number of the specified number of decimals
 * @param val      The value to convert
 * @param decimals The number of decimals
 * @return 0 => "0.00", '0.0268' => '2.68', etc
 */
function makeValidNumber(val, decimals) {
	val = val.replace(/[^0-9]/g, '');
	val = parseFloat(empty(val) ? '0' : val);
	return (val/Math.pow(10, decimals)).toFixed(decimals);
}



/**
 * Clones the specified object, if deep is true this will
 * perform a deep clone.
 * Note:	that this function does not check for recursion
 * 			in the specified object and will cause an error
 * 			if such an object is provided.
 * @return A clone of the specified object
 */
function clone(obj, deep) {
	deep = deep || false;
	var newObj = (obj instanceof Array) ? [] : {};
    for( var i in obj ) {
        if( deep && obj[i] && (typeof obj[i] == "object") ) {
            newObj[i] = clone(obj[i], deep);
        } else {
            newObj[i] = obj[i];
        }
    }
    return newObj;
}

/**
 * Parses the query string a returns it in the form of a JSON object.
 * @return A JSON object containing the parsed query string
 */
function parseQueryString() {
	var q = window.location.search.substring(1).split("&");
	var queryString = {};
	for( var i = 0; i < q.length; i++ ) {
		var parts = q[i].split("=",2);
		queryString[parts[0]] = parts[1];
	}
	
	return queryString;
}


/**
 * Shows a map if connected to the internet
 * @param includeDir The relative path the include directory
 * @param wid        The wholesaler id
 * @param postcode   Postcode of the destination (optional)
 */
function showMap(includeDir, wid, postcode) {
	// perform internet connectivity
	internetConnectivityTest(includeDir, function(){
		// if passes the internet connection test
		postcode = postcode || null;
		var title = 'Google Maps&trade;',
			qStr  = 'id=' + wid;
		if( postcode != null ) {
			postcode = postcode.replace(/ /g, '').toUpperCase();
			title += ' to ' + postcode;
			qStr  += '&t='  + postcode;
		}
		
		$.shadowbox.loadIframe('http://www.feedmeonline.co.uk/maps/?fromShop&width=945&height=620&'+qStr,
				true, {'width': 940, 'height': 610, 'title': title});
	});
}



function showAboutUs(rootDir) {
	changeNavClass ('about_us');
	$.shadowbox.load(rootDir+'/about.php', {shadowbox: true},
			true, {title: 'About Us', width: 580, height:430});
	void(0);
	return false;
}
function showTerms(rootDir) {
	changeNavClass ('show_terms');
	$.shadowbox.load(rootDir+'/terms.php', {shadowbox: true},
			true, {title: 'Terms &amp; Conditions', width: 580, height:480});
	void(0);
	return false;
}
function showFeedback(rootDir, id) {
	changeNavClass (id);
	$.shadowbox.load(rootDir+'/feedback.php', {shadowbox: true, 'dir' : rootDir},
			true, {title: 'Give Us Feedback', width: 580, height:570});
	void(0);
	return false;
}
function showSignup(rootDir, id) {
	//changeNavClass (id);
	$.shadowbox.load(rootDir+'/register_form.php', {shadowbox: true,  'dir' : rootDir, signup: true},
			true, {title: 'Sign Up', width: 580, height:680});
	void(0);
	return false;
}
function showSignin(rootDir, id) {
	//changeNavClass (id);
	$.shadowbox.load(rootDir+'/login.php', {shadowbox: true,  'dir' : rootDir},
			true, {title: 'Sign In', width: 610, height: 160});
            
	void(0);
	return false;
}  

function changeNavClass (id) {
	//document.getElementById("welcome").setAttribute("class", "button-off");
	document.getElementById("about_us").setAttribute("class", "button-off");
	//document.getElementById("show_terms").setAttribute("class", "button-off");
	document.getElementById("feedback").setAttribute("class", "button-off");
	//document.getElementById("signup").setAttribute("class", "button-off");
	//document.getElementById("show_feedback").setAttribute("class", "button-off");
	document.getElementById(id).setAttribute("class", "button-on");
}

function alertHelpMessage(msg){

	$.shadowbox.alert(msg + '\r\n\r\n' + 

			'Please wait a couple of minutes and try again.\r\n' +

			'If the problem persists please contact\r\n' +

			'Action Prompt on: 0845 5333453.',

			'Unexcepted Error');

}

