
//  International Portal / Region Preference JavaScript Document
//  Author: AM
//  Copyright 2010 All rights reserved.

// Script settings
var hostName = 'loccitane'; //String to indentify in the refferer URL's domain name
var listID = 'tabs'; // ID of the container of the country links

var cookieName = 'regionPref';
var regex = new RegExp('^http://[^/]*' + hostName + '[^/]*'); 
var testMode = false;


function readRegionPref()
{
	// Look at all the cookies and find the region preference
	var nameEQ = cookieName + "=";
	var ca = document.cookie.split(';');
	if (testMode) {console.log(ca); }

	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)===' ') { c = c.substring(1,c.length); }
		if (c.indexOf(nameEQ) === 0)
		{
			if (testMode) { console.log('Preference read : ' + cookieName + ' = ' + c.substring(nameEQ.length,c.length)); }

			// Return the value of the region preference cookie
			return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}


function createRegionPref(prefSite)
{
	// If the preference is specified, set the time-to-live to 30 days
	// else prepare to delete the preference cookie
	var days = null;
	if (prefSite !== null) { days = 30; }
	else { days = -1; }

	// Get the correct date format
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = '; expires='+date.toGMTString();
	
	// Create the region preference cookie
	document.cookie = cookieName + '=' + prefSite + expires + '; path=/';
	if (testMode) { console.log('Preference created : ' + cookieName  + ' = ' + prefSite); }
}


function erasePref()
{
	if (testMode) { console.log('Deleting preference : ' + cookieName ); }
	// Delete the region preference cookie
	createRegionPref(null);
}


function initPref()
{

	// Attaches the create-region-preference function to each link in the region list.
	$('#' + listID + ' a').click(function (){ createRegionPref(this.href);return true; });
	if (testMode) { console.log('Initialising region preference script... '); }

	// If the refferer hostname has our keyword, remove the region preference
	// else redirect to the preference
	if (regex.test(document.referrer)) { erasePref(); }
	else if (readRegionPref() !== null) 
	{
		if (testMode) { console.log('Redirect to Preference :' + readRegionPref()); }
		else { window.location = readRegionPref(); return true; }
	}
	$('body').fadeIn(625);
}


$(document).ready(function() { initPref(); });


