if (typeof logError == "undefined") {
  logError = function(){};
}
if (typeof logLoaded == "undefined") {
	logLoaded = function(){};
}
if (typeof logDebug == "undefined") {
	logDebug = function(){};
}
var jsName = "cookieFunctionshome.js";
logDebug(jsName + "@start");

// R42 - SR97503082 - Session Time Out

var timerSecs;
var timerID = null;
var timerRunning = false;
var delay = 1000;
var clearCookies;

function initializeTimer() {
    // Set the length of the timer, in seconds
    // alert("InitializeTimer");
    clearCookies = false;
    timerSecs = 600;
    StopTheClock();
    StartTheTimer();
}

initializeTimer();

function StopTheClock() {
    if(timerRunning);
    clearTimeout(timerID);
    timerRunning = false;
}

function StartTheTimer() {
    if (timerSecs==0) {
        StopTheClock();
	   clearCookies = true;
    }
    else
    {
        // self.status = timerSecs;
        timerSecs = timerSecs - 1;
        timerRunning = true;
        timerID = self.setTimeout("StartTheTimer()", delay);
    }
}

function checkCookieStatus() {
	return clearCookies;
}

function initSessionTimeOut(processFacade, selectedMonth) {
	var countrycookie = getCookie("country_pref");
	if(countrycookie== COUNTRY_POS.toString().match(countrycookie))
	  	checkFlightType(false,false,true,true);
	else
		checkFlightType(false,false,false,true);

	var cityCookie = getCookie("cityCookie");	  
}

// Cookie handling function for IE
function delete_IE_Cookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function checkFlightSearchCookieStatus(){
	if (checkCookieStatus()) {
		delete_IE_Cookie('AC-Signon-Cookie');
		delete_IE_Cookie('AC-Session-Cookie');
		deleteCookie("AC-Session-Cookie");
	   	deleteCookie("AC-Signon-Cookie");
		initSessionTimeOut();
	}
}

function checkBookingsCookieStatus() {
	if (checkCookieStatus()) {
		delete_IE_Cookie('AC-Signon-Cookie');
		delete_IE_Cookie('AC-Session-Cookie');
		deleteCookie("AC-Session-Cookie");
	   	deleteCookie("AC-Signon-Cookie");
	}
}

// NBM4 Phase 3 - This figures out the image paths to be used for common english jsps

var countryCookieArray = new Array(new Array("GB","en"),
new Array("FR","fr","en"),new Array("HK","en"),
new Array("AU","en"),new Array("IL","en"),
new Array("DE","de","en"),new Array("IT","it","en"),
new Array("CH","en","de","fr"),new Array("IE","en"),
new Array("NL","en"),new Array("NO","en"),
new Array("SE","en"),new Array("DK","en"));

// This is the format for adding more POS countries
// Make sure to have that options added to the country_residence.html
var COUNTRY_POS = new Array ("GB","FR","HK","AU","IL","DE","IT","CH","IE","NL","NO","SE","DK");
// The below is without CH - commented on Nov 6
//var COUNTRY_POS = new Array ("GB","FR","HK","AU","IL","DE","IT","IE","NL","NO","SE","DK");

// This determines the ETV parameter values -- for Flight searches.
// format for the ETV parameter array: COUNTRY,MARKET,POS,POT,CURRENCY,SITE
var ETVparameters = new Array(
new Array("UK","UK","LON","LON","GBP","SAAVSAAV"),
new Array("FR","FR","CDG","CDG","EUR","SAAXSAAX"),
new Array("HK","HK","HKG","HKG","HKD","SAAZSAAZ"),
new Array("AU","AU","SYD","SYD","AUD","SABASABA"),
new Array("IL","IL","TLV","TLV","ILS","SABBSABB"),
new Array("DE","DE","FRA","FRA","DEM","SAADSAAD"),
new Array("IT","IT","ROM","ROM","ITL","SAADSAAD"),
new Array("CH","CH","ZRH","ZRH","CHF","SAADSAAD"),
new Array("IE","IE","DUB","DUB","EUR","SAADSAAD"),
new Array("NL","NL","AMS","AMS","EUR","SAADSAAD"),
new Array("NO","NO","OSL","OSL","NOK","SAADSAAD"),
new Array("SE","SE","STO","STO","SEK","SAADSAAD"),
new Array("DK","DK","CPH","CPH","DKK","SAADSAAD"));

// remove the following from the above array for CH: - it should go back in -- same order as in POS
// new Array("CH","CH","ZRH","ZRH","CHF","SAADSAAD"),

function PopExternal( url, title ) {
	window.open(url,title,'width=600,height=400,menubar=no,scrollbars=yes,toolbar=yes,location=yes,directories=no,resizable=yes,top=0,left=0');
  }

function popupInfo(url,title){
if(title == 'Class')
	window.open(url,title,'width=400,height=400,scrollbars=yes');
else if(title == 'MulticityReservation')
	window.open(url,title,'width=730,height=230,top=40,left=50,scrollbars=yes');
else if(title == 'CalendarHelp')
	window.open(url,title,'width=530,height=180,top=40,left=50,scrollbars=yes');
else if(title == 'ShopBy')
	window.open(url,title,'width=600,height=220,top=40,left=50,scrollbars=yes');
else if(title == 'SignInHelp')
	window.open(url,title,'width=490,height=630,top=40,left=50,scrollbars=yes');
else if(title == 'PinHelp')
	window.open(url,title,'width=400,height=350,top=50,left=50,scrollbars=yes');
else if(title == 'PassengerHelp')
	window.open(url,title,'width=400,height=240,top=50,left=50,scrollbars=yes');
else if(title == 'RememberHelp')
	window.open(url,title,'width=500,height=285,top=50,left=50,scrollbars=yes');
else if(title == 'CreditcardHelp' || title == 'CCHelp')
	window.open(url,title,'width=750,height=200,top=50,left=50,scrollbars=yes');
else if(title == 'ChangePasswordHelp')
	window.open(url,title,'width=450,height=350,top=50,left=50,scrollbars=yes');
else
	window.open(url,title,'width=400,height=500,scrollbars=yes');
}

function isCookiesEnabled(){
    setCookie('cookietest', 'yes', '1', '/');
    return getCookie('cookietest') != null;
}

//======================================
// will check if there is a session cookie;
// will return false if session is not expired
// will return true if there is a session cookie and is expired or there is no session cookie
// expiry time is 10 min for consumer
// currentTimeGMT is a Date object
//======================================
function isConsumerSessionExpired(currentTimeGMT) {
   //alert("start isConsumerSessionExpired");
   sessionCookie = getCookie("AC-Session-Cookie");

   if (sessionCookie) {
    	//get the last access time in sec
		cookieValue = sessionCookie.split ('^');
		role = cookieValue[2];
		if ( role != "C") {
		   return true;
		}

		sessLastAccess = cookieValue[5];
		//alert("last access time="+sessLastAccess);

    	//get the current time in sec
    	var gmtTimeMillisec = currentTimeGMT.getTime();
  	   	var gmtTimeInSec = parseInt(gmtTimeMillisec/1000);

		var lastAccessTime = new Date();
		lastAccessTime.setYear(sessLastAccess.substring(0,4));
		lastAccessTime.setMonth(sessLastAccess.substring(4,6)-1);
		lastAccessTime.setDate(sessLastAccess.substring(6,8));
		lastAccessTime.setHours(sessLastAccess.substring(8,10));
		lastAccessTime.setMinutes(sessLastAccess.substring(10,12));
		lastAccessTime.setSeconds(sessLastAccess.substring(12,14));

		lastAccessTimeInSec = parseInt(lastAccessTime.getTime()/1000);
		timediff = gmtTimeInSec-lastAccessTimeInSec;

		//
		//alert ("lastAccessTime ="+ lastAccessTime.toLocaleString());
		//alert ("time diff (sec)=" + timediff);

   	    //expiry time is 10 minutes for ACO
   	    expiry = 10*60;

		if (lastAccessTimeInSec+expiry < gmtTimeInSec) {
	    	//alert("expired");
			deleteCookie("AC_country_site");
	    	return true;
		}
		else {
		   	//alert("not expired");
	 	 	return false;
		}
	}
	else {
	  	//alert("expired - cookie does not exist");
	   	return true;
    }
}

//======================================
// updates the session cookie last access time
// lastAccessTimeGMT is a Date object and is the lastAccessTime
//======================================
function updateSessionLastAccessTime(lastAccessTimeGMT) {
   //alert("start updateSessionLastAccessTime");

   cookieName = "AC-Session-Cookie";
   sessionCookie = getCookie(cookieName);

    if (sessionCookie) {
        var gmtTime = lastAccessTimeGMT;

	    //build the last access time value
	    month = gmtTime.getMonth()+1;
	    year = new String(gmtTime.getFullYear());

	    var lastAccessTime = year + leftPad(month, 2, "0") + leftPad(gmtTime.getDate(), 2, "0")+leftPad(gmtTime.getHours(), 2, "0")+leftPad(gmtTime.getMinutes(), 2, "0")+leftPad(gmtTime.getSeconds(), 2, "0");

		//alert ("last access time  ="+ lastAccessTime);

		var cookieValue = sessionCookie.split ('^');
		updatedCookieValue = cookieValue[0]+"^"+cookieValue[1]+"^"+cookieValue[2]+"^"+cookieValue[3]+"^"+cookieValue[4]+"^"+lastAccessTime;

		//alert ("updatedCookieValue  ="+ updatedCookieValue);

		var domain = ".swiregroupinc.com";
	  	var cookiePath = "/";
    	document.cookie = cookieName + "=" + updatedCookieValue + "; path=" + cookiePath + "; domain=" + domain;
   }
}

//======================================
// adds the 'paddingChar' to the left of 'value' until the length of value is 'newLength'
// value is converted always to a string
//======================================
function leftPad(value, newLength, paddingChar) {
  var pad = "";
  var string = new String(value);
  var len = newLength-string.length;
  var i;
  for (i = 0; i<len; i++) {
    pad += paddingChar;
  }
  return pad+string;
}

//======================================
// returns the full name of the user formated for a max length
// of 44 for the welcome message
//======================================
function getNameForWelcomeDisplay() {
 signOnCookie = getCookie("AC-Signon-Cookie");
 userName = "";

 /*
  #German code,German display value,English code
MR,Herr,MR
DR,Dr.,DR
MS,Frau,MS
CAPT,Capt,CAPT
FATHER,Father,FATHER
HON,Hon,HON
JUDGE,Judge,JUDGE
MSTR,Mstr,MSTR
PROF,Prof.,PROF
RABBI,Rabbi,RABBI
REV,Rev,REV
SEN,Sen,SEN
SIR,Sir,SIR
SISTER,Sister,SISTER
 */

 /*
 #Italian code, Italian Display Value, English code
MR,Sig.,MR
MISS,Sig.na,MISS
DR,Dott.,DR
MS,Sig.ra,MS
CAPT,Cap.,CAPT
FATHER,Padre,FATHER
HON,On.,HON
JUDGE,Giudice,JUDGE
MSTR,Maestro,MSTR
PROF,Prof.,PROF
RABBI,Rabbino,RABBI
REV,Rev.,REV
SEN,Sen.,SEN
SIR,Sir,SIR
SISTER,Sorella,SISTER
 */
// To support German and Italian sites - Title codes are English
var TITLE_TEXT=new Array(new Array("en","MR","MS","MRS","DR","MISS","CAPT","FATHER","HON","JUDGE","MSTR","PROF","RABBI","REV","SEN","SIR","SISTER"),
new Array("de","HERR","FRAU","FRAU","DR.","FRAU","CAPT","FATHER","HON","JUDGE","MSTR","PROF.","RABBI","REV","SEN","SIR","SISTER"),
new Array("it","SIG.","SIG.RA","SIG.RA","DOTT.","SIG.NA","CAP.","PADRE","ON.","GIUDICE","MAESTRO","PROF.","RABBINO","REV.","SEN.","SIR","SORELLA"));

 if(signOnCookie) {
	cookieValue = signOnCookie.split ('^');

	title = cookieValue[1];
	firstName = cookieValue[2];
	middleName = cookieValue[3];
	lastName = cookieValue[4];
	maxLength = 44;
	rowIndex = 0;
	if (lang == "de" || lang == "it"){
		var rowIndex = 0;
		for(i=1;i<TITLE_TEXT.length;i++){
			if (lang == TITLE_TEXT[i][0]){
				rowIndex = i;
				break;
			}
		}
		for(j=1;j<TITLE_TEXT[0].length;j++){
			if(title == TITLE_TEXT[0][j]){
				title = TITLE_TEXT[rowIndex][j];
				break;
			}
		}
	}

	if (middleName == "") {
	   noSpaces = 2;
	   namelength = title.length + firstName.length + lastName.length +noSpaces;

	   if( namelength > maxLength) {
		 userName = title+" "+firstName.substring(0,1)+" "+lastName;
	     if(userName.length > maxLength) {
	        userName = userName.substring(0, maxLength);
	     }
	   }
	   else {
		  userName = title+" "+firstName+" "+lastName;
	   }
	}
	else {
	   noSpaces = 3;
	   namelength = title.length + firstName.length + middleName.length + lastName.length +noSpaces;

	   if( namelength > maxLength) {
	     namelengthlength = title.length + firstName.length + 1 + lastName.length +noSpaces;
	     if ( namelength > maxLength) {
	        userName = title+" "+firstName.substring(0,1)+" "+middleName.substring(0,1)+" "+lastName;
	        if(userName.length > maxLength) {
	          userName = userName.substring(0, maxLength);
	        }
	     }
	     else {
	        userName = title+" "+firstName+" "+middleName.substring(0,1)+" "+lastName;
	     }
	   }
	   else {
		  userName = title+" "+firstName+" "+middleName+" "+lastName;
	   }
	}
 }
 return userName;
}


//======================================
// return the planitGo request link
// from a txt file that includes both secure and nonsecure PG URLs
// in the format nonSecureUrl|secureUrl
//======================================
function getPGUrl(linkArray) {
  signOnCookie = getCookie("AC-Signon-Cookie");
  urls = linkArray.split ('|');
  if (signOnCookie){
    return urls[1];
  }
  else {
    return urls[0];
  }
}


//======================================
// Puts some nice comma's into a number
// to make it more readable,
//	eg,	1000 turns into 1,000
//		1000000.32 turns into 1,000,000.32
//		9999999.8888888 turns into 9,999,999.8888888
// and so on. Change sSep into the seperator/delimeter of
// your choice, otherwise "," is the default.
//======================================
function numberDelimit ( n, sSep ) {
 	n = n.toString ( );
	var p1, p2, p3;
	var sSep = ( sSep == null ? ',' : sSep );

	n = n.split ( '.' );
	p1 = n [ 0 ];
	p2 = ( n [ 1 ] == null ? '' : '.' + n [ 1 ] );
	p3 = '';

	for ( var i = p1.length-1 ; i >= 0; i -- ) {
		p3 += p1.charAt ( p1.length - i - 1 );
		if ( i % 3 == 0 && i != 0 ) p3 += sSep;
	}

	return p3 + p2;
}

//======================================
// returns true if we are navigating the static pages
// any URL that does not end in .do is considered to be static content
//======================================
function isStaticContent() {
   	var currentURL = location.pathname;
   	var jsessionidIndex = currentURL.indexOf(";jsessionid=");

   	if (jsessionidIndex >-1) {
   		currentURL = currentURL.substring(0,jsessionidIndex);
   	}

    var URLEnding = currentURL.substring(currentURL.length - 3, currentURL.length);

   	if (URLEnding == ".do") {
	    return false;
   	}
   	else {
	    var URLwallet = currentURL.substring(0, 16);
	    if (URLwallet == "/wallet/servlet/") {
		return false;
	    }
	    else {
		return true;
	    }
   	}
}

//======================================
// returns a Date object as a representation of
// the current time obtained via a SSI
// timefmt="%d-%m-%Y %H:%M:%S"
// eg : 16-11-2004 00:04:45
//======================================
// SR97501934 CALENDAR - USE SERVER DATE INSTEAD OF PC DATE
var SERVER_DATE;
//
function getServerTime(ssiDate) {

	var dateTime = ssiDate.split(" ");
	var date = dateTime[0].split("-");
	var time = dateTime[1].split(":");

	//alert("getSErverTime for "+ssiDate);
	//alert("date = "+dateTime[0]);
	//alert("time  = "+dateTime[1]);

	var serverTime = new Date();
	//alert("server time 1 = "+serverTime);
	serverTime.setDate(date[0]);
	serverTime.setMonth(parseInt(date[1],10)-1);
	serverTime.setYear(date[2]);
	serverTime.setHours(time[0]);
	serverTime.setMinutes(time[1]);
	serverTime.setSeconds(time[2]);

	//alert("serverTime = "+ serverTime.toLocaleString());

	// SR97501934 *********** code start
	SERVER_DATE = new Date();
	SERVER_DATE.setDate(serverTime.getDate());
	SERVER_DATE.setMonth(serverTime.getMonth());
	SERVER_DATE.setYear(serverTime.getFullYear());
	SERVER_DATE.setHours(serverTime.getHours());
	SERVER_DATE.setMinutes(serverTime.getMinutes());
	SERVER_DATE.setSeconds(serverTime.getSeconds());

	LocalDate = new Date();

	currentTimeZoneOffsetInMinutes = LocalDate.getTimezoneOffset();
	currentTimeZoneOffsetInHours = parseInt(currentTimeZoneOffsetInMinutes/60, 10);
	currentTimeZoneOffsetInMinutes = currentTimeZoneOffsetInMinutes - currentTimeZoneOffsetInHours*60;

	newHours = parseInt(time[0],10)-currentTimeZoneOffsetInHours;

	SERVER_DATE.setHours(newHours);
	SERVER_DATE.setMinutes(parseInt(time[1],10)+currentTimeZoneOffsetInMinutes);
	// SR97501934 ***** code end
	return serverTime;
}

function getGMTServerDate(){

	newDate = new Date();
	if(SERVER_DATE){
		newDate.setDate(SERVER_DATE.getDate());
		newDate.setMonth(SERVER_DATE.getMonth());
		newDate.setYear(SERVER_DATE.getFullYear());
		newDate.setHours(SERVER_DATE.getHours());
		newDate.setMinutes(SERVER_DATE.getMinutes());
		newDate.setSeconds(SERVER_DATE.getSeconds());
	}
	return newDate;
}

//===================================
// Locale setting functions
//===================================

// Added for TR95008913

function checkChangeHome(country) {
	
	country = country.toUpperCase();
	var sessionCookie = getCookie("AC-Session-Cookie");
	var signOnCookie = getCookie("AC-Signon-Cookie");
	
	if(signOnCookie != null) {
		var signOnPieces = signOnCookie.split('^');			
		signOnCountry = signOnPieces[6];
	
	}


	var isSignedIn = (sessionCookie && signOnCookie);
	    
	// Don't redirect if agency user or not signed in.
	if (isAgency(sessionCookie) || !isSignedIn)
		return;
	
	var countryCookie = getCountryCookie();
	if (countryCookie == country || signOnCountry == country)
		return;
     var langCookie = getLangCookie();

  //  Redirect to login country Home page.
		  	
	document.location = '/' + getSitePath(langCookie + "_" + signOnCountry) + "/home.html";

} 
//------------end------------


function isAgency(sessionCookie) {
	if (! sessionCookie)
		return false;

	var cookieValue = sessionCookie.split('^');
	if (cookieValue.length < 3)
		return false;

	var role = cookieValue[2];
	return role == "A";
}


// Stub for obsolete function still called from headerFunctions.js
function setCountry_path() {}

function checkLangCookie(cookieName)
{
        if (!isCookiesEnabled()) {
	        var address = location.href;
                return (address.search("en/us/") != -1) ? "us" : ((siteLang == "fr") ? "french" : "english");
        }
        var value = getCookie(cookieName);
        return value != null ? value : "";
}

// Script loader indicator.
logLoaded(jsName);


