/*
PSEUDOCODE

detect language
	if language cookied
		do nothing
	else
		store in cookie
		redirect to page
		
	if language cookied but user changes language
		update cookie stored
		
*/
function LanguageDetector(name, days) {

	//we detect the language
	if (navigator.appName == 'Netscape')
		this.browserLanguage = navigator.language;
	else
		this.browserLanguage = navigator.browserLanguage;

	this.browserLanguage = this.browserLanguage.split('-')[0];	//get the first part to determine the language
	this.userLanguage;											//fill this in only if there is a user language
	
	this.name = name;											//set the name of the cookie holder
	this.days = days;											//set the days to remember lamnguage selection
	this.redirect_array = new Array();							//this holds all the languages and their corresponding urls
	
	/*THIS IS JUST FOR COOKIES*/
	this.createCookie = function (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+"; path=/";
	};

	this.readCookie = function (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;
	};

	this.eraseCookie = function (name) {
		createCookie(name,"",-1);
	};
	/*END COOKIE STUFF */
	
	this.goToURL = function (redirection_url) {
		window.location.href = redirection_url;
		//console.log(redirection_url);
	};

	this.redirectUser = function () {
		/*
			cases
			if user chooses a language it should be remembered in cookie
			if user doesnt choose a language we check broser language store it in a cookie and redirect them
			if user has cookie we check if they are on correct version. Otherwise redirect them.		
		*/

		if(this.userLanguage) { //if a user language is set we should not redirect them
			this.createCookie(this.name, this.userLanguage, this.days);
			return;
		} else if (this.readCookie(this.name) != null){
			this.goToURL(this.redirect_array[this.readCookie(this.name)]);
			return;
		} else {
			this.createCookie(this.name, this.browserLanguage, this.days); //store the brower language
			this.goToURL(this.redirect_array[this.readCookie(this.name)]);
			return;
		}
	};

}