/** 
 * change locale of the url and redirect 
 * 
 * it needs to have one input in the page called footerLanguageSelect with the list of
 * different locale in the form xx_XX
 */
function changeLocale(currentUrl, jsonActionUrl) {
	var selectedLocaleOptionEl = $$('#footerLanguageSelect option')[$("footerLanguageSelect").selectedIndex];
	
	// pattern to find locale in the url				
	loExp = new RegExp("[a-z]{2}_[A-Z]{2}/.*$","g");

	// replace the url locale with the new one specified in the
	// select input
	var newUrl = currentUrl.replace(loExp, selectedLocaleOptionEl.value + "/home");

	//console.log(newUrl.substring(0, 12) + ", " + currentUrl.substring(0, 12));
	
	if(newUrl.substring(0, 12)!=currentUrl.substring(0, 12)) {
		var myXHR = new Request.JSON({url:jsonActionUrl, async: false}).send();
		document.location.href = newUrl;
	}
}

/**
 * Display an applicative message in a smoothbox. The general message div id is
 * the first parameter which is a string.
 * 
 * @param psDivId
 *            div id
 * @param psTitle
 *            title of the box
 * @param pnWidth
 *            width of the box
 * @param pnHeight
 *            height of the box
 * @return nothing
 */
function displayGeneralMessage(psDivId, psMessages, psTitle, pnWidth, pnHeight) {
	new Asset.css('/eshop/css/smoothbox/smoothem.css', {
		id :'smoothbox'
	});

	$(psDivId).innerHTML = psMessages;
	TB_show(psTitle, "#TB_inline?height=" + pnHeight + "&width=" + pnWidth
			+ "&inlineId=" + psDivId, false);
}

/**
 * Display an waiting message in a smoothbox. The waiting message
 * is inside a div called ftw
 * 
 * @param psDivId div id of the div to display with the waiting message content
 * @param psTitle title of the box
 * @param pnWidth width of the box
 * @param pnHeight height of the box
 * @return nothing
 */
function displayWaitingMessage(psDivId, psTitle, pnWidth, pnHeight) {
	new Asset.css("/eshop/css/smoothbox/smoothem.css", { id:'smoothbox' });
	TB_show(psTitle, "#TB_inline?height=" + pnHeight + "&width=" + pnWidth + "&inlineId=" + psDivId, true);
}

function closeMessage() {
	TB_remove();
}

/**
 * Display an error message in a smoothbox. The error message div id is the
 * first parameter which is a string.
 * 
 * @param psDivId
 *            div id
 * @param psTitle
 *            title of the box
 * @param pnWidth
 *            width of the box
 * @param pnHeight
 *            height of the box
 * @return nothing
 */
function displayErrorMessage(psDivId, psMessages, psTitle, pnWidth, pnHeight) {
	new Asset.css('/eshop/css/smoothbox/smootherror.css', {
		id :'smoothbox'
	});
	$(psDivId).innerHTML = psMessages;
	TB_show(psTitle, "#TB_inline?height=" + pnHeight + "&width=" + pnWidth
			+ "&inlineId=" + psDivId, false);
}

/**
 * Display an help message in a smoothbox. The error message div id is the
 * first parameter which is a string.
 * 
 * @param psDivId
 *            div id
 * @param psTitle
 *            title of the box
 * @param pnWidth
 *            width of the box
 * @param pnHeight
 *            height of the box
 * @return nothing
 */
function displayHelpMessage(psDivId, psTitle, pnWidth, pnHeight) {
	new Asset.css('/eshop/css/smoothbox/smoothhelp.css', {
		id :'smoothbox'
	});

	// If the help system is disabled, we don't show it
	if($(psDivId)!=null && gbHelpSystemFlag) {
		TB_show(psTitle, "#TB_inline?height=" + pnHeight + "&width=" + pnWidth
				+ "&inlineId=" + psDivId, false);
	}
}

/**
 * Display a message in a smoothbox. The error message div id is the
 * first parameter which is a string.
 * 
 * @param psDivId
 *            div id
 * @param psTitle
 *            title of the box
 * @param pnWidth
 *            width of the box
 * @param pnHeight
 *            height of the box
 * @return nothing
 */
function displayDivMessage(psDivId, psTitle, pnWidth, pnHeight) {
	new Asset.css('/eshop/css/smoothbox/smoothhelp.css', {
		id :'smoothbox'
	});

	if($(psDivId)!=null) {
		TB_show(psTitle, "#TB_inline?height=" + pnHeight + "&width=" + pnWidth
				+ "&inlineId=" + psDivId, false);
	}
}

/*******************************************************************************
 * Function printf(format_string,arguments...) Javascript emulation of the C
 * printf function (modifiers and argument types "p" and "n" are not supported
 * due to language restrictions)
 * 
 ******************************************************************************/
function printf(fstring) {
	var pad = function(str, ch, len) {
		var ps = '';
		for ( var i = 0; i < Math.abs(len); i++)
			ps += ch;
		return len > 0 ? str + ps : ps + str;
	}
	var processFlags = function(flags, width, rs, arg) {
		var pn = function(flags, arg, rs) {
			if (arg >= 0) {
				if (flags.indexOf(' ') >= 0)
					rs = ' ' + rs;
				else if (flags.indexOf('+') >= 0)
					rs = '+' + rs;
			} else
				rs = '-' + rs;
			return rs;
		}
		var iWidth = parseInt(width, 10);
		if (width.charAt(0) == '0') {
			var ec = 0;
			if (flags.indexOf(' ') >= 0 || flags.indexOf('+') >= 0)
				ec++;
			if (rs.length < (iWidth - ec))
				rs = pad(rs, '0', rs.length - (iWidth - ec));
			return pn(flags, arg, rs);
		}
		rs = pn(flags, arg, rs);
		if (rs.length < iWidth) {
			if (flags.indexOf('-') < 0)
				rs = pad(rs, ' ', rs.length - iWidth);
			else
				rs = pad(rs, ' ', iWidth - rs.length);
		}
		return rs;
	}
	var converters = new Array();
	converters['c'] = function(flags, width, precision, arg) {
		if (typeof (arg) == 'number')
			return String.fromCharCode(arg);
		if (typeof (arg) == 'string')
			return arg.charAt(0);
		return '';
	}
	converters['d'] = function(flags, width, precision, arg) {
		return converters['i'](flags, width, precision, arg);
	}
	converters['u'] = function(flags, width, precision, arg) {
		return converters['i'](flags, width, precision, Math.abs(arg));
	}
	converters['i'] = function(flags, width, precision, arg) {
		var iPrecision = parseInt(precision);
		var rs = ((Math.abs(arg)).toString().split('.'))[0];
		if (rs.length < iPrecision)
			rs = pad(rs, ' ', iPrecision - rs.length);
		return processFlags(flags, width, rs, arg);
	}
	converters['E'] = function(flags, width, precision, arg) {
		return (converters['e'](flags, width, precision, arg)).toUpperCase();
	}
	converters['e'] = function(flags, width, precision, arg) {
		iPrecision = parseInt(precision);
		if (isNaN(iPrecision))
			iPrecision = 6;
		rs = (Math.abs(arg)).toExponential(iPrecision);
		if (rs.indexOf('.') < 0 && flags.indexOf('#') >= 0)
			rs = rs.replace(/^(.*)(e.*)$/, '$1.$2');
		return processFlags(flags, width, rs, arg);
	}
	converters['f'] = function(flags, width, precision, arg) {
		iPrecision = parseInt(precision);
		if (isNaN(iPrecision))
			iPrecision = 6;
		rs = (Math.abs(arg)).toFixed(iPrecision);
		if (rs.indexOf('.') < 0 && flags.indexOf('#') >= 0)
			rs = rs + '.';
		return processFlags(flags, width, rs, arg);
	}
	converters['G'] = function(flags, width, precision, arg) {
		return (converters['g'](flags, width, precision, arg)).toUpperCase();
	}
	converters['g'] = function(flags, width, precision, arg) {
		iPrecision = parseInt(precision);
		absArg = Math.abs(arg);
		rse = absArg.toExponential();
		rsf = absArg.toFixed(6);
		if (!isNaN(iPrecision)) {
			rsep = absArg.toExponential(iPrecision);
			rse = rsep.length < rse.length ? rsep : rse;
			rsfp = absArg.toFixed(iPrecision);
			rsf = rsfp.length < rsf.length ? rsfp : rsf;
		}
		if (rse.indexOf('.') < 0 && flags.indexOf('#') >= 0)
			rse = rse.replace(/^(.*)(e.*)$/, '$1.$2');
		if (rsf.indexOf('.') < 0 && flags.indexOf('#') >= 0)
			rsf = rsf + '.';
		rs = rse.length < rsf.length ? rse : rsf;
		return processFlags(flags, width, rs, arg);
	}
	converters['o'] = function(flags, width, precision, arg) {
		var iPrecision = parseInt(precision);
		var rs = Math.round(Math.abs(arg)).toString(8);
		if (rs.length < iPrecision)
			rs = pad(rs, ' ', iPrecision - rs.length);
		if (flags.indexOf('#') >= 0)
			rs = '0' + rs;
		return processFlags(flags, width, rs, arg);
	}
	converters['X'] = function(flags, width, precision, arg) {
		return (converters['x'](flags, width, precision, arg)).toUpperCase();
	}
	converters['x'] = function(flags, width, precision, arg) {
		var iPrecision = parseInt(precision);
		arg = Math.abs(arg);
		var rs = Math.round(arg).toString(16);
		if (rs.length < iPrecision)
			rs = pad(rs, ' ', iPrecision - rs.length);
		if (flags.indexOf('#') >= 0)
			rs = '0x' + rs;
		return processFlags(flags, width, rs, arg);
	}
	converters['s'] = function(flags, width, precision, arg) {
		var iPrecision = parseInt(precision);
		var rs = arg;
		if (rs.length > iPrecision)
			rs = rs.substring(0, iPrecision);
		return processFlags(flags, width, rs, 0);
	}
	farr = fstring.split('%');
	retstr = farr[0];
	fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
	for ( var i = 1; i < farr.length; i++) {
		fps = fpRE.exec(farr[i]);
		if (!fps)
			continue;
		if (arguments[i] != null)
			retstr += converters[fps[4]](fps[1], fps[2], fps[3], arguments[i]);
		retstr += fps[5];
	}
	return retstr;
}

/** 
 * function to format a number with separators. returns formatted number.
 * num - the number to be formatted
 * decpoint - the decimal point character. if skipped, "." is used
 * sep - the separator character. if skipped, "," is used 
 */
function formatNumberBy3(num, decpoint, sep) {
	// check for missing parameters and use defaults if so
	if (arguments.length == 2) {
		sep = ",";
	}
	if (arguments.length == 1) {
		sep = ",";
		decpoint = ".";
	}
	// need a string for operations
	num = num.toString();
	// separate the whole number and the fraction if possible
	a = num.split(decpoint);
	x = a[0]; // decimal
	y = a[1]; // fraction
	z = "";
	
	
	if (typeof(x) != "undefined") {
	// reverse the digits. regexp works from left to right.
	for (i=x.length-1;i>=0;i--)
		z += x.charAt(i);
	// add seperators. but undo the trailing one, if there
	z = z.replace(/(\d{3})/g, "$1" + sep);
	if (z.slice(-sep.length) == sep)
		z = z.slice(0, -sep.length);
	x = "";
	// reverse again to get back the number
	for (i=z.length-1;i>=0;i--)
		x += z.charAt(i);
	// add the fraction back in, if it was there
	if (typeof(y) != "undefined" && y.length > 0)
		x += decpoint + y;
	}
	return x;
}
