var xmlHttp;

function currentPage()
{
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

	return sPage.replace(/#/, "");
}

function currentPageNoParams(newReg)
{
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	
	return sPage + '?region=' + newReg;
}

function currentPageNoReg(newReg)
{
	var sPath = window.location.href;
	var param = "region";
	var regex = new RegExp( "\\?" + param + "=[^&]*&?", "gi");
	
	sPath = sPath.replace(regex,'?');
	regex = new RegExp( "\\&" + param + "=[^&]*&?", "gi");
	sPath = sPath.replace(regex,'&');
	sPath = sPath.replace(/(\?|&)$/,'');
	regex = null;
	
	sPath = sPath.replace(/#/, "");
	if(sPath.indexOf('?') == -1)
		return  sPath + '?region=' + newReg;
	else
		return  sPath + '&region=' + newReg;
}

function stateChangedToggleRegion() { 
	if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		if(xmlHttp.status == 200)
		{
			if (xmlHttp.responseText != null)
			{
				if(xmlHttp.responseText != 0)
				{
					var type = "";
					var newregion= "";
					if (xmlHttp.responseText.substring(0,6) == "reload")
					{
						type = xmlHttp.responseText.substring(0,6);
						newReg = xmlHttp.responseText.substring(6,8);
					}
					else if(xmlHttp.responseText.substring(0,9) == "startOver")
					{
						type = xmlHttp.responseText.substring(0,9);
						newReg = xmlHttp.responseText.substring(9,11);
					}
					
					// Switch a US -> reload sans params
					if(type == "startOver")
					{
						// On evite les prob de differences dans les produits
						window.location = currentPageNoParams(newReg);
					}
					else // Switch Ca-Fr ou Ca-En, garde les params, sauf reg
					{
						window.location = currentPageNoReg(newReg);
					}
				}
			}
			// else 'Erreur : Le transfert du fichier du serveur a echouee - fichier introuvable.'	
		// else 'Erreur: Code de staut retourn&eacute; : ' + xmlHttp.status + ' ' + xmlHttp.statusText
		}				
	}
}

function GetXmlHttpObject()	{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function toggleRegion(region) {
	xmlHttp=GetXmlHttpObject();

	if (xmlHttp==null)
	{
		return;
	}
	
	var url="scripts/updateToggleRegionTool.php";
	url=url+"?region=" + region;
	url=url+"&page=" + currentPage();
	url=url+"&sid="+Math.random();
	
	xmlHttp.onreadystatechange=stateChangedToggleRegion;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}