/* Simple functions to handle the locale selector */

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return null;
  else
    return results[1];
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	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) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function inArray(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) return true;
    }
    return false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";

	document.cookie = name+"="+value+expires+"; domain=.mindjet.com; path=/";
}

function setLocale(locale) {

  // append the new locale to the request and reload the page
  // NOTE: This will override all other locale selection
  // processes.
  // @requires jquery.url plugin
  
  createCookie("language",locale); 
  var redirect = window.location.pathname + "?lang=" + locale;
  window.location = redirect;
} 



// fixes pages cached in the wrong language by comparing localeCode js variable to cookie
function localizr () {

	// if there is a ?lang= then locale is already covered.
	var loc_param = gup('lang');
	if (loc_param != null) {return;}
	
	// if there is no global javascript variable to compare to, then abort
       	if (typeof localeCode == 'undefined'){return;}
       	
       	// get language cookie value and make sure it is a valid locale
       	var locales = ['en','en_US','en_GB','en_UK','en_EU','de','fr','ja'];
       	var loc_cookie = readCookie("language");
    	
       	if (inArray(locales,loc_cookie)) {
       	       	if (loc_cookie == "en") {      	
       			var loc_country = readCookie("country"); 
       			   		
       			if        (loc_country == "GB") {loc_cookie = "en_GB";
       		        } else if (loc_country == "EU") {loc_cookie = "en_EU";
       			} else                          {loc_cookie = "en_US";
       			}
       		}
       	
       		// if the pagecode and cookie don't match, browser is serving cached version, which we now destroy with setLocale.
     		if (loc_cookie != localeCode){
     			setLocale(loc_cookie);
     		}
   	
       	}
}

