petzl.controllers.MobileLangSelector = function (urlPrefix)
{
	//dropbox Efraim
		var language = '';
		
		var refreshPage = function (c){
					var num = Math.floor(Math.random()*9999)
					if (language != ''){
						var translatedUrl = $('body link[rel="alternate"][hreflang="'+language+'"]').attr('href');
						if (translatedUrl){
							window.location.href = translatedUrl + '?l=' +c;
						}
						
						else {
							window.location.href= '/'+ urlPrefix + '?upd=' +num;
						}
					}
					else
						window.location.href= '/' + urlPrefix +'?upd=' +num;
		}

		var redirectWithTranslatedURL = function(country, language)
		{
			var num = Math.floor(Math.random()*9999)
			var newLocation = urlPrefix;
			var hasTranslatedURL = false;
			var flag = language + "-" +country.toLowerCase();
			if (country != '' && language != '')
			{
				var translatedUrl = $('body link[rel="alternate"][hreflang="'+flag+'"]').attr('href');
				if (translatedUrl && translatedUrl != '/')
				{
					newLocation += translatedUrl;
					hasTranslatedURL = true;
				}
				else{
					//var allAvailableHREFLANG = Array.from(document.querySelectorAll('link[rel="alternate"]')).map(a=>a.getAttribute('hreflang'));
					//var hreflangForINTLanguage = allAvailableHREFLANG.filter(function(value){return value.indexOf(language) >= 0;})[0];
					
					var hreflangForINTLanguage = ''; 
					$('link[rel=alternate]').each(function()
					{ 
						if ($(this).attr('hreflang').indexOf(language) >= 0) 
							hreflangForINTLanguage = $(this).attr('hreflang'); 
					});
					
					
					translatedUrl = $('link[rel="alternate"][hreflang="'+hreflangForINTLanguage+'"]').attr('href');
					if(translatedUrl)
					{
						var countryCode = hreflangForINTLanguage.split('-')[1].toUpperCase();
						translatedUrl = translatedUrl.replace(countryCode , "INT");
						newLocation += translatedUrl;
						hasTranslatedURL = true;
					}
				}
			}

			if(hasTranslatedURL == false)
			{
				newLocation += '/' + country + '/' + language + '?upd=' + num;
			}
			window.location.href = newLocation;
		}
		
					   
		var updateCookie = function(country, lang)
		{ 
			var date = new Date();
			
			date.setTime(date.getTime()+(365*10*24*60*60*1000)); 
			if(country){
					document.cookie = 'apex__country='+country + ';' + 'path=/; expires=' +date.toGMTString(); +';'
					
			}
			if(lang){
					document.cookie = 'apex__language='+lang + ';' + 'path=/;  expires=' +date.toGMTString(); +';'
					language = lang;
			}
			
			redirectWithTranslatedURL(country, lang);
					//Web_Template.redirectToHome(refreshPage(country));	//remote action, callback to refreshPage
		}
		
		$('.countryLang').click(function() {
				var countryCode = $(this).attr("data-country-code");
				var lanCode = $(this).attr("data-lang-code");
           		updateCookie(countryCode,lanCode);
		});			    

}