$(function() 
{
	getURLparameters();
});

function getURLparameters()
{
	var b2cServerDomainPrefix = $("#b2cServerDomainPrefix").attr("href");
	var mobileString = $("#mobileString").attr("href");
	if (!mobileString)
		b2cServerDomainPrefix = $("#mobileString").length > 0 ? '' : b2cServerDomainPrefix;

	if (isExcludedPage(b2cServerDomainPrefix))
		return;

	var urlPath = window.location.pathname;
	var isB2C = (urlPath.split(b2cServerDomainPrefix).length > 1 && b2cServerDomainPrefix) ? true : false;
	var pathWithoutB2C = (isB2C) ? urlPath.split(b2cServerDomainPrefix)[1] : urlPath;

	var countryFromQuery = getParameterByName('l');
	var pathParams = pathWithoutB2C.split('/');
	var countryCode = !!countryFromQuery ? countryFromQuery : pathParams[1];
	var languageCode = pathParams[!!countryFromQuery ? 1 : 2];  
	
	verifyCountryAndLanguage(countryCode, (languageCode || '').toLowerCase(), isB2C, countryFromQuery);
}

function isExcludedPage(b2cServerDomainPrefix){
	var b2cPrefix = (b2cServerDomainPrefix || "").toLowerCase();
	var excludedPages = [	b2cPrefix + '/web_petzlbook', 
							b2cPrefix + '/web_catalogpro', 
							b2cPrefix + '/web_contact', 
							b2cPrefix + '/web_contact_os', 
							b2cPrefix + '/web_newsletter',  
							b2cPrefix + '/webpress_login',  
							b2cPrefix + '/webpress_request',  
							'/apex/'];
	var path = window.location.pathname.toLowerCase();
	var flag = false;
	excludedPages.forEach(function(item){
		if (path.indexOf(item) >= 0) 
			flag = true;
	});
	return flag;
}

function verifyCountryAndLanguage(countryCode, languageCode, isB2C, countryFromQuery)
{	
	countryCode = countryCode.toUpperCase();

	var countryCodeSet = $("#countryCodeSet").attr("data-value");

	if(countryCodeSet && countryCodeSet != 'undefined')
	{
		countryCodeSet = buildAnArray(countryCodeSet);
	}
	
	var countryLanguageList = $("#countryLanguageList").attr("data-value");

	var languageCountry = languageCode +'-'+ countryCode; 
	var isLanguageCountryValid = !!countryLanguageList && countryLanguageList.toLowerCase().indexOf(languageCountry.toLowerCase()) >= 0
										|| !countryLanguageList;

	// Country & language codes are valid
	if(!!countryCodeSet && countryCodeSet.indexOf(countryCode) >= 0 && isLanguageCountryValid
						|| !!countryCode && countryCode.toLowerCase() == 'int'  && !countryFromQuery)
		
	{
		updateCookies('country', countryCode);
		updateCookies('language', languageCode);
		
		if (!!countryFromQuery){
			replaceCountryCode(isB2C, true, countryCode, languageCode);
		}
	}

	// Country value/language pair is not valid - call max-mind server if needed
	else if (!!countryCodeSet && countryCodeSet.indexOf(countryCode) == -1 || !isLanguageCountryValid) 
	{
		// get default country/language pairs
		var defaultCountryLanguageList = $('#defaultCountryLanguageList').attr('data-value');
		var availableCountries = {};
		defaultCountryLanguageList.split(',').forEach(function(country){
			var params = country.trim().replace(']', '').replace('[', '').split('/');
			availableCountries[params[0]] = params[1];
		});


		// country value is not valid - need maxmind
		updateCookie ('country','');

		callGeoIPService().then(function(){
			var countryCode = $.cookie('apex__country');	
			var languageCode = availableCountries[countryCode];
			updateCookies('language', languageCode);
			replaceCountryCode(isB2C, !!countryFromQuery, countryCode, languageCode);
		});
	}
	
}

function updateCookies(cookieName , cookieValue)
{ 
	var date = new Date();
	
	//set expire 10 years
	date.setTime(date.getTime()+(365*10*24*60*60*1000));   
	document.cookie = 'apex__' + cookieName + '=' + cookieValue + ';' + 'path=/; expires=' + date.toGMTString() + ';';

}


function replaceCountryCodeFromHrefLang(isB2C, countryCode, languageCode)
{
	var indexes = getAllIndexes(window.location.pathname, '/'); 
	var countryCodeStartIndex = isB2C ? indexes[1] : indexes[0];
	var replaceWith = countryCode + '/' + languageCode; 
	var newpathname = window.location.pathname;
	$('link[hreflang]').each(function(){
		var url = $(this).attr('href');
		if (url.indexOf(replaceWith) >= 0){ //Normal country code (FR, US..)
			newpathname = newpathname.substring(0, countryCodeStartIndex) + url;
		} else if (countryCode == 'INT') { // INT country code, 
											 // so we find href with appropriate language like /FR/fr/Sport 
											 // and it become /INT/fr/Sport
			var index = (url + '/').indexOf('/' + languageCode + '/');
			if (index >= 0){
				newpathname = newpathname.substring(0, countryCodeStartIndex) + '/INT' + url.substring(index);
			}
		}
	});

	var newUrl = removeParameter(newpathname + window.location.search, 'l');
	if (newpathname != window.location.pathname)
		window.location.href = newUrl;
}


function replaceCountryCode(isB2C, isOldUrlFormat, countryCode, languageCode)
{
	// if hreflang  exist - new redirect logic
	if ($('link[hreflang]').length > 0){
		replaceCountryCodeFromHrefLang(isB2C, countryCode, languageCode);
		return;
	}
	
	var replaceWith = countryCode + '/' + languageCode; 

	// olf redirect logic 
	var indexes = getAllIndexes(window.location.pathname, '/'); 
	var countryCodeStartIndex = isB2C ? indexes[1] + 1 : indexes[0] + 1;
	var isLandingPage = isB2C ? indexes.length <= 3 : indexes.length <= 2;
	var countryCodeEndIndex = isLandingPage && indexes.length <= 2 ? indexes[1] : (isOldUrlFormat ? indexes[2] : indexes[3]);
	
	var newPathName = window.location.pathname.replaceBetween(countryCodeStartIndex, countryCodeEndIndex, replaceWith);
	var newUrl = removeParameter(newPathName + window.location.search, 'l');
	if (newPathName != window.location.pathname)
		window.location.href = newUrl; 
	

}

function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes;
}


String.prototype.replaceBetween = function(start, end, what) {
    return this.substring(0, start) + what + (!!end ? this.substring(end) : '');
};

function buildAnArray(countryCodeSet)
{
	var result;
	result = countryCodeSet.substring(1,countryCodeSet.length-1);
	result = result.split(", ");
	return result;
}

function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


function removeParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}