
var IpLocaleCheck = Class.create(
{
	initialize: function()
	{
		if ($('localeAlertContainer'))
		{
			this.container = $('localeAlertContainer').hide();
			this.cookieName = 'grippleLocalePreference';
			
			this.defaultLocale = LabelEdSystemVars.SITE_DEFAULT_LOCALE;
			this.localeSpecified = LabelEdSystemVars.LOCALE_SPECIFIED;
			this.currentLocale = LabelEdSystemVars.LOCALE;
			this.localeLanguage = LabelEdSystemVars.LOCALE_LANGUAGE;
			this.ipLocale = LabelEdSystemVars.IP_LOCALE;
			this.ipCountry = LabelEdSystemVars.IP_COUNTRY;
			this.ipLanguage = LabelEdSystemVars.IP_LANGUAGE;
			
			this.setupLocaleStrings();
			
			this.start();
		}
	},
	
	setupLocaleStrings: function()
	{
		this.localeStrings = new Array();
		
		this.localeStrings['DE'] = {
			'question'	: 
				"Sie befinden sich auf einer Seite, die für Ihre Region nicht verfügbar ist. " +
				"Möchten Sie auf Ihre regionale Seite weitergeleitet werden und dies für zukünftige Anwendungen speichern?",
			'buttonNo'	: 'Ich möchte auf dieser Seite bleiben',
			'buttonYes'	: 'Diese Seite auf ' + this.ipLanguage + ' anzeigen'
		};
		
		this.localeStrings['ES'] = {
			'question'	: 
				"Estás accediendo al contenido que no se corresponde con tu región. " +
				"¿Quieres acceder ahora, y por defecto en el futuro, a la página de tu región?",
			'buttonNo' 	: 'Quiero seguir en la página en la que estoy',
			'buttonYes'	: 'Cambiar a la página en ' + this.ipLanguage
		};
		
		this.localeStrings['FR'] = {
			'question' 	: 
				"Souhaitez-vous être redirigé(e) vers la version française du site maintenant, " +
				"et de façon automatique lors de toute future consultation ?",
			'buttonNo' 	: 'Je souhaite consulter cette version du site',
			'buttonYes'	: 'Je souhaite être redirigé(e) vers le site ' + this.ipLanguage
		};
		
		this.localeStrings['IT'] = {
			'question' 	: 
				"Sembra che vi navigate un contenuto non progettato per la tua regione. " +
				"Volete passare adesso al tuo sito locale e fare questo automaticamente nel futuro?",
			'buttonNo' 	: 'Voglio stare dove sono',
			'buttonYes'	: 'Passare al sito in ' + this.ipLanguage
		};
		
		this.localeStrings['NL'] = {
			'question' 	: 
				"U bevindt zich op een pagina die niet beschikbaar is voor uw regio. " +
				"Wilt u nu naar uw regionale website worden doorgeschakeld zodat voortaan direct de juiste website automatisch wordt geopend?",
			'buttonNo' 	: 'Ik wil op deze site blijven',
			'buttonYes'	: 'Ik wil naar de ' + this.ipLanguage + ' site'
		};
		
		this.localeStrings['PL'] = {
			'question' 	: 
				"Wydają się Państwo przeglądać zawartość nie przeznaczoną dla waszego regionu. " +
				"Czy chcą państwo przejść teraz do lokalnej strony i zachować tą informację automatycznie na przyszłość?",
			'buttonNo' 	: 'Chcę pozostać na tej stronie',
			'buttonYes'	: 'Przejdź na stronę w języku ' + this.ipLanguage
		};
		
		this.localeStrings['PT'] = {
			'question' 	: 
				"Está a navegar numa página cujo conteúdo não é o correspondente à sua região. " +
				"Pretende ir agora para a página correspondente e fazer isso automáticamente no futuro?",
			'buttonNo' 	: 'Eu pretendo continuar nesta página',
			'buttonYes'	: 'Mudar para a página em ' + this.ipLanguage
		};
		
		this.localeStrings['GB'] = {
			'question' 	: 
				"You appear to be browsing content not intended for your region. " +
				"Do you want to go to your local site now and do this automatically in the future?",
			'buttonNo' 	: 'I want to stay where i am',
			'buttonYes'	: 'Switch to the site in ' + this.ipLanguage
		};
		
		this.localeStrings['US'] = {
			'question' 	: 
				"You appear to be browsing content not intended for your region. " +
				"Do you want to go to your local site now and do this automatically in the future?",
			'buttonNo' 	: 'I want to stay where i am',
			'buttonYes'	: 'Switch to the site in ' + this.ipLanguage
		};
		
		this.localeStrings['RU'] = {
			'question'	: 
				"Вы, кажется, просматриваете содержание, не предназначенное для Вашей области. " +
				"Вы хотите пойти в Вашу местную веб-страницу теперь и сделать это автоматически в будущем?",
			'buttonNo' 	: 'Я хочу остаться, где я',
			'buttonYes'	: 'Переключитесь на страницу на ' + this.ipLanguage
		};
	},
	
	start: function()
	{
		if (!this.localeSpecified && this.ipLanguage)
		{
			var cookieLocale = this.getCookie(this.cookieName);
			
			if (this.currentLocale != this.ipLocale)
			{
				if (cookieLocale)
				{
					this.redirect(cookieLocale);
				}
				else
				{
					this.container.setStyle(
					{
						background: '#ffd553 url(/images/localeAlertBg.png) no-repeat', 
						height: '55px',
						padding: '10px 45px 10px 70px',
						marginBottom: '10px',
						position: 'relative'
					});
					
					this.introContainer = new Element('div').setStyle({margin: '10px 0 0 0'});
					this.container.appendChild(this.introContainer);
					
					this.introContainer.update(this.localeStrings[this.ipLocale].question);
					
					this.buttonsContainer = new Element('div').setStyle({position: 'absolute', bottom: '10px', right: '20px'});
					this.container.appendChild(this.buttonsContainer);
					
					var noButton = new Element('button')
						.store('locale', this.currentLocale)
						.update(this.localeStrings[this.ipLocale].buttonNo)
						.observe('click', this.setLocaleCookie.bind(this));
					
					var yesButton = new Element('button')
						.store('locale', this.ipLocale)
						.setStyle({marginLeft: '5px'})
						.update(this.localeStrings[this.ipLocale].buttonYes)
						.observe('click', this.setLocaleCookie.bind(this));
					
					this.buttonsContainer.appendChild(noButton);
					this.buttonsContainer.appendChild(yesButton);
					
					this.container.appendChild(new Element('div', {className: 'clear'}));
					
					this.container.show();
				}
			}
		}
	},
	
	redirect: function(locale)
	{
		this.container.hide();
		
		if (locale != this.currentLocale)
		{
			window.location = '/' + locale.toLowerCase() + '/';
		}
	},
	
	setLocaleCookie: function(event)
	{
		var locale = event.element().retrieve('locale');
		
		if (locale)
		{
			this.setRawCookie(this.cookieName, locale, 2629743, '/'); // 1 month
			this.redirect(locale);
		}
	},
	
	setRawCookie: function(name, value, expires, path, domain, secure)
	{
	    if (expires instanceof Date)
	    {
	        expires = expires.toGMTString();
	    }
	    else if (typeof(expires) == 'number')
	    {
	        expires = (new Date(+(new Date()) + expires * 1e3)).toGMTString();
	    }

	    var r = [name + "=" + value], s={}, i='';
	    var s = {expires: expires, path: path, domain: domain};
	    
	    for (i in s)
	    {
	        s[i] && r.push(i + "=" + s[i]);
	    }
	    
	    return secure && r.push("secure"), document.cookie = r.join(";"), true;
	},
	
	getCookie: function(cookieName)
	{
		if (document.cookie.length > 0)
		{
			var cookieStart=document.cookie.indexOf(cookieName + "=");
			
			if (cookieStart!=-1)
			{
				cookieStart = cookieStart + cookieName.length+1;
				var cookieEnd = document.cookie.indexOf(";", cookieStart);
				
				if (cookieEnd==-1)
				{
					cookieEnd=document.cookie.length;
				}
				
				return unescape(document.cookie.substring(cookieStart,cookieEnd));
			}
		}
		
		return '';
	}
});

