function isAgency() {
   sessionCookie = getCookie("AC-Session-Cookie");
   
   if (sessionCookie) {
		cookieValue = sessionCookie.split ('^');
		role = cookieValue[2];
		if ( role == "A") {
		   return true;
		}
		else {
		   return false;
		}
   }
   else {
   	  return false;
   }
}		


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 showPopup(url,width,height){
    window.open(url,'PopupContent','width='+width+',height='+height+',top=50,left=50,scrollbars=yes');
  }

function popupInfo(url,title){
if(title == 'Class')
	window.open(url,title,'width=400,height=400');
else if(title == 'MulticityReservation')
	window.open(url,title,'width=730,height=230,top=40,left=50');
else if(title == 'CalendarHelp')
	window.open(url,title,'width=530,height=180,top=40,left=50');
else if(title == 'ShopBy')
	window.open(url,title,'width=600,height=220,top=40,left=50');
else if(title == 'SignInHelp')
	window.open(url,title,'width=490,height=630,top=40,left=50');
else if(title == 'PinHelp')
	window.open(url,title,'width=400,height=350,top=50,left=50');
else if(title == 'PassengerHelp')
	window.open(url,title,'width=400,height=240,top=50,left=50');
else if(title == 'RememberHelp')
	window.open(url,title,'width=500,height=285,top=50,left=50');	
else if(title == 'CreditcardHelp' || title == 'CCHelp')
	window.open(url,title,'width=750,height=200,top=50,left=50');		
else if(title == 'ChangePasswordHelp')
	window.open(url,title,'width=450,height=350,top=50,left=50');
else 
	window.open(url,title,'width=400,height=500');
	
}

function initLeftMenu(){
	highlightMenu();
}	
   
//=====================================   
//displays agent login info  
//currentTimeGMT is a Date object; is the server time in GMT
//=====================================   
function initAgentLoginData(currentTimeGMT) {
//alert("start initAgentLoginData");
 var sessionCookie = getCookie("AC-Session-Cookie");
 if (currentTimeGMT ) { 
    //alert("static page");
    if (!isAgencySessionExpired(currentTimeGMT)) {   	
      	var cookieValue = sessionCookie.split ('^');
	    iataNum = cookieValue[1];
      	agencySubId = cookieValue[3];
	    cAgencyName = cookieValue[4];
	    
	    updateSessionLastAccessTime(currentTimeGMT);
    }
    else {
    	deleteCookie("AC-Session-Cookie");
    	location.replace("http://"+location.hostname+"/splash/agents");
    }
  }
  else {
	//   alert("dynamic page");
      	var cookieValue = sessionCookie.split ('^');
	    iataNum = cookieValue[1];
      	agencySubId = cookieValue[3];
	    cAgencyName = cookieValue[4];
  }
}

//rollover function for top nav bar buttons
function changeImages() {
        if (document.images) {
                for (var i=0; i<changeImages.arguments.length; i+=2) {
                        document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
                }
        }
}

function setCookie(cookie_name, cookie_value, cookie_life, cookie_path) {
  var today = new Date()
  var expiry = new Date(today.getTime() + cookie_life * 24*60*60*1000)
  if (cookie_value != null && cookie_value != ""){
    var cookie_string =cookie_name + "=" + escape(cookie_value)
    if(cookie_life){ cookie_string += "; expires=" + expiry.toGMTString()}
    if(cookie_path){ cookie_string += "; path=" + cookie_path}
    document.cookie = cookie_string
  }
}

function getCookie(name) {
  var index = document.cookie.indexOf(name + "=")
  if (index == -1) { return null}
  index = document.cookie.indexOf("=", index) + 1
  var end_string = document.cookie.indexOf(";", index)
  if (end_string == -1) { end_string = document.cookie.length }
  return unescape(document.cookie.substring(index, end_string))
} 

function cookieEnable(){
    var testout = "";
    var cookie_enable = false;
    setCookie('cookietest', 'yes', '1', '/');
    testout = getCookie('cookietest');
    if (testout != null ) {
      cookie_enable = true; 
    }
  return cookie_enable 
}

function checkForCookie(CookieName)
{
        var CookieString = document.cookie;
        var CookieSet = CookieString.split (';');
        var SetSize = CookieSet.length;
        var CookiePieces;
        var ReturnValue = "";
        var x = 0;
        var domain=location.hostname;

        for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++)
        {
                CookiePieces = CookieSet[x].split ('=');

                if (CookiePieces[0].substring (0,1) == ' ') {
                        CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
                }
                if (CookiePieces[0] == CookieName)
                {
                        ReturnValue = CookiePieces[1];
                }
        }
        if (ReturnValue == ""){
            //setTimeout('location.replace(\"http://www.aircanada.com/index.html\")', 2000);
        }
}

//write a cookie and sets its life time to 5 years
function writeCookie(cookieName, cookieValue)
{
//alert('in');
	var expDate = new Date();
    var expiry = 5 * 365 * 1000 * 60 * 60 * 24;
	expDate.setTime (expDate.getTime() + expiry);
  	var domain = ".aircanada.com";
  	var cookiePath = "/";
    document.cookie = cookieName + "=" + escape (cookieValue) + "; path=" + cookiePath + "; expires=" + expDate.toGMTString() + "; domain=" + domain;
//alert('set');
    return;
}

function checkAeroplanCookie(CookieName){
	var domain=".aircanada.com";
	
    var CookieString = document.cookie;
    var CookieSet = CookieString.split (';');
    var SetSize = CookieSet.length;
    var CookiePieces;
    var ReturnValue = "";
    var x = 0;

    for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++)
    {
          CookiePieces = CookieSet[x].split ('=');
          if (CookiePieces[0].substring (0,1) == ' ') {
                CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
          }
		  //alert(CookiePieces[0]);
          if (CookiePieces[0] == CookieName){
               ReturnValue = CookiePieces[1];
           }
    }
    //alert(ReturnValue);
    if (ReturnValue == "")
    {
	    //setcookie
	    document.cookie = CookieName + "=" + escape ("true") + "; path=/" + "; domain="+ domain;
	
		if (checkLangCookie('new_lang_pref')=="french")
			document.location.href="http://www.aircanada.com/fr/aeroplan/";
		else 
			document.location.href="http://www.aircanada.com/en/aeroplan/";
		return;
	} else { 
		if(checkLangCookie('new_lang_pref')=="french")   	
    			document.location.href="https://www.aeroplan.com/fr/home/index.jsp";
		else
			document.location.href = "https://www.aeroplan.com/en/home/index.jsp";
		return;
	}
}

// ======================================
//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");
	    	return true;
		}
		else {
		   	//alert("not expired");
	 	 	return false;
		}		
	}
	else {
	  	//alert("expired - cookie does not exist");
	   	return true;
    }
    
}

// ======================================
//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 25 min for agency
//currentTimeGMT is a Date object
// ======================================
function isAgencySessionExpired(currentTimeGMT) {
   //alert("start isAgencySessionExpiredfor "+currentTimeGMT);
   sessionCookie = getCookie("AC-Session-Cookie");
   
   if (sessionCookie) {    
    	//get the last access time in sec    
		cookieValue = sessionCookie.split ('^');
		role = cookieValue[2];
		if ( role != "A") {
		   return true;
		}
		
		sessLastAccess = cookieValue[5];
		
		//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 25 minutes for ADO
   	    expiry = 25*60; 
        				
		if (lastAccessTimeInSec+expiry < gmtTimeInSec) {
	    	//alert("expired");
	    	return true;
		}
		else {
		   	//alert("not expired");
	 	 	return false;
		}		
	}
	else {
	  	//alert("expired - cookie does not exist");
	   	return true;
    }
    
}

//delete a cookie by stting its expiry date in the past
function deleteCookie(cookieName) {
    //alert("start deleteCookie:"+cookieName);
    
    cookieValue = getCookie(cookieName);
    if (cookieValue) {
		var expDate = new Date();
		expDate.setYear(expDate.getYear() - 1);
		
	  	var domain = ".aircanada.com";
  		var cookiePath = "/";
	    document.cookie = cookieName + "=" + escape (cookieValue) + "; path=" + cookiePath + "; expires=" + expDate.toGMTString() + "; domain=" + domain;    
    }

 
}

// ======================================
//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 = ".aircanada.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 = "";
 
 if(signOnCookie) {
	cookieValue = signOnCookie.split ('^');
	
	title = cookieValue[1];
	firstName = cookieValue[2];
	middleName = cookieValue[3];
	lastName = cookieValue[4];
	maxLength = 44;
	
	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;
	
}

function checkForValidBrowser() {
		var browser_enable = false;
        var agent = navigator.userAgent.toLowerCase(); 
        
        // Browser version
        var versionMajor = parseInt(navigator.appVersion); 
        var versionMinor = parseFloat(navigator.appVersion); 

        // Browser name
        var ns    = (agent.indexOf('mozilla')!=-1 && agent.indexOf('spoofer')==-1 && agent.indexOf('compatible') == -1 && agent.indexOf('opera')==-1 && agent.indexOf('webtv')==-1); 
        var ns2   = (ns && versionMajor == 2); 
        var ns3   = (ns && versionMajor == 3); 
        var ns4   = (ns && versionMajor == 4); 
        var ns4up = (ns && versionMajor >= 4); 
        var ns6   = (ns && versionMajor == 5); 
        var ns6up = (ns && versionMajor >= 5);
        var ns7   = (ns && versionMajor == 5 && agent.indexOf("netscape/7.") != -1); 
        var ie    = (agent.indexOf("msie") != -1); 
        var ie3   = (ie && versionMajor < 4); 
        var ie4   = (ie && versionMajor == 4 && agent.indexOf("msie 4.0") != -1); 
        var ie4up = (ie && versionMajor >= 4); 
        var ie5   = (ie && versionMajor == 4 && agent.indexOf("msie 5.0") != -1); 
        var ie55  = (ie && versionMajor == 4 && agent.indexOf("msie 5.5") != -1);
        var ie5up = (ie && !ie3 && !ie4);
        var ie55up = (ie && !ie3 && !ie4 && !ie5);  
        var ie6   = (ie && versionMajor == 4 && agent.indexOf("msie 6.0") != -1);
        var ie6up = (ie && !ie3 && !ie4 && !ie5 && !ie55); 
        var opera = (agent.indexOf("opera") != -1); 
        var webtv = (agent.indexOf("webtv") != -1); 
        var aol   = (agent.indexOf("aol") != -1); 
        
        // Javascript version
//        var js = 0.0;
//        if (ns2 || ie3) js = 1.0 
//        else if (ns3 || opera || (document.images && ie && !ie4up)) js = 1.1 
//        else if ((ns4 && versionMinor <= 4.05) || ie4) js = 1.2 
//        else if ((ns4 && versionMinor > 4.05) || ie5up) js = 1.3 
//        else if (ns6up) js = 1.4 

		// java enabled;
		var jvm_enabled = navigator.javaEnabled();

        // Platform type
        var win   = (agent.indexOf("win")!=-1 || agent.indexOf("16bit")!=-1);
        var win32 = (agent.indexOf("win95")!=-1 || agent.indexOf("windows 95")!=-1 || agent.indexOf("win98")!=-1 || agent.indexOf("windows 98")!=-1 || agent.indexOf("winnt")!=-1 || agent.indexOf("windows nt")!=-1 || (versionMajor >= 4 && navigator.platform == "win32") || agent.indexOf("win32")!=-1 || agent.indexOf("32bit")!=-1);
        var mac   = (agent.indexOf("mac")!=-1);
        
//        alert("net7 "+ns7 +"ie55up "+ie55up+"win "+win+"win32 "+win32+"mac "+mac+"ie5up "+ie5up);
        if(((win || win32) && (ns7 || ie55up)) || (mac && ie5up)){
			if(jvm_enabled)
			   	browser_enable = true;
	       }
        
        return browser_enable
        
}

// ======================================
//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 {
   	    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
// ======================================
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();
	serverTime.setDate(date[0]);
	serverTime.setMonth(parseInt(date[1])-1);
	serverTime.setYear(date[2]);
	serverTime.setHours(time[0]);
	serverTime.setMinutes(time[1]);
	serverTime.setSeconds(time[2]);
	
	//alert("serverTime = "+ serverTime.toLocaleString());
	
	return serverTime;
}

