// HK 24/05/2016 - Set timeout for maxmind service
if (navigator.appName === 'Microsoft Internet Explorer' && XDomainRequest && navigator.appVersion.indexOf("MSIE 1") === -1) {
	window.XRequest = XDomainRequest;
}
else {
    window.XRequest = XMLHttpRequest;
}

(function(send) {
	XRequest.prototype.send = function(data) {
		// Set a timeout only if request to maxmind.com 
		if (this._url.indexOf('maxmind.com') >= 0)
			this.timeout = 2000;
		send.call(this, data); 
	};
})(XRequest.prototype.send);   

(function(open) {
	XRequest.prototype.open = function(method, url, data) {
		this._url = url;
		open.call(this, method, url, data);
	};
})(XRequest.prototype.open);   


if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

if (typeof console === "undefined" || typeof console.log === "undefined") {
     console = {};
     console.log = function() {};
}

// HK W-000085 Maxmind/INT - Improvement of migration from old geoip service
function callGeoIPService(){
	//debugger;
	var deferred = $.Deferred();

	var b2cServerDomainPrefix = '/' + $('#b2cServerDomainPrefix').attr('href');

	var localCookie = {
		country:	$.cookie("apex__country"),
		state:		$.cookie("apex__state"),
		isUnknownLocaleUrl:  !!b2cServerDomainPrefix && window.location.pathname.endsWith(b2cServerDomainPrefix)
							|| window.location.pathname.endsWith(b2cServerDomainPrefix + '/')
	};

	if (!localCookie.country 
		|| localCookie.country == 'INT' && localCookie.isUnknownLocaleUrl){	
		
		var set = {};

		
		$('#contryLang .CountryCode').each(
		   function(index, elem){
			  var cc = $(elem).text();
			  set[cc]= true;
		   });
		
		
		// Set the Country-code by the user IP address (maxmind)
		var onSuccess = function(location){
			//debugger;
			if (location.country.iso_code && location.country.iso_code in set ){
				updateCookie('country', location.country.iso_code);	
				if (Array.isArray(location.subdivisions) && location.country.iso_code == 'US'){
					updateCookie('state', location.subdivisions[0].names['en']);	
				}
			}
			else{
				updateCookie ('country', 'INT');	
			}
			deferred.resolve();
		};

		var onError = function(error){
			updateCookie ('country','INT');
			updateCookie ('language', 'en');	
			deferred.resolve();
		};
		
		geoip2.country(onSuccess, onError);	

		return deferred.promise();

	}

	return $.when();

}

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


