//**********************************************************************
// NOTE:  AjaxCommon.js is required for some of the functions defined
// in this file to run.
//**********************************************************************


//**********************************************************************
// Name			: trackLandingView
// Description	: Records a view of a landing page.
// Input		: N/A
// Output		: N/A
//**********************************************************************
function trackLandingView(promoID) {
    var partialReqParamsString; 
    var reqParamsString;
    var pageURL = window.location;
    var pageTitle = window.document.title;
        
    //Execute the logic required to extract the browser ID and determine
    //whether cookies are accepted
    partialReqParamsString = processBrowserID();

    if (promoID != undefined && promoID != null && promoID.replace(/\s/g, "") != "") {
    	partialReqParamsString += "&promoID=" + promoID.replace(/\s/g, "");
    }
        
    reqParamsString = "target=landingView&" + partialReqParamsString + 
    	"&pageURL=" + escape(pageURL) + "&pageTitle=" + escape(pageTitle);
       
    sendAnalyticsData(reqParamsString);
}



//**********************************************************************
// Name			: trackPricingView
// Description	: Records a view of a pricing page.
// Input		: tripID - The ID assigned to the trip being priced
// Output		: N/A
//**********************************************************************
function trackPricingView(tripID) {
    var partialReqParamsString;
    var reqParamsString;                
    
    //Execute the logic required to extract the browser ID and determine
    //whether cookies are accepted
    partialReqParamsString = processBrowserID();    
    
    reqParamsString = "target=pricingView&" + partialReqParamsString + 
    	"&tripID=" + tripID;
            
    sendAnalyticsData(reqParamsString);
}



//**********************************************************************
// Name			: trackBookingView
// Description	: Records a view of a booking page.
// Input		: tripID - The ID assigned to the trip
//				  bookingNumber - The booking number assigned to the trip
// Output		: N/A
//**********************************************************************
function trackBookingView(tripID, bookingNumber) {
    var partialReqParamsString;
    var reqParamsString;                
    
    //Execute the logic required to extract the browser ID and determine
    //whether cookies are accepted
    partialReqParamsString = processBrowserID();
       
    reqParamsString = "target=bookingView&" + partialReqParamsString + 
    	"&tripID=" + tripID + "&bookingNumber=" + bookingNumber;
    
    sendAnalyticsData(reqParamsString);
}



//**********************************************************************
// Name			: sendAnalyticsData
// Description	: If the browser supports Ajax, invokes logic to send
//				  the provided analytics data to the server.
// Input		: reqParamsString - the request parameter string to be
//				  					passed in the call
// Output		: N/A
//**********************************************************************
function sendAnalyticsData(reqParamsString) {    
    var targetURL = "/aev/analytics";  
    var xmlHttpRequest = createXMLHttpRequest();
    
    if (xmlHttpRequest != null) {
	    xmlHttpRequest.open("POST", targetURL, true);
	    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    xmlHttpRequest.send(reqParamsString);	    
    }    
}
 


//**********************************************************************
// Name			: getCookie
// Description	: Attempts to retrieve a cookie with the specified name 
//				  and return its value.  If a cookie by this name has not
//				  been set, this function will return null. 
// Input		: name - the name of the cookie whose values is to be 
//				  	     retrieved
// Output		: The value of the cookie, or null if it does not exist.
//**********************************************************************
function getCookie(name) {
    var begin;
    var end;
    var nameValuePair;
            
    begin = document.cookie.indexOf(name + "=");
    
    if (begin == -1) {
        return null;
    }
    else {
        end = document.cookie.indexOf(";", begin);
        
        if (end == -1) {
            nameValuePair = document.cookie.substring(begin);           
        }
        else {
            nameValuePair = document.cookie.substring(begin, end);
        }
        
        return unescape(nameValuePair.substring(nameValuePair.indexOf("=") + 1));
    }
}



//**********************************************************************
// Name			: setCookie
// Description	: Sets a cookie with the specified value and properties.
// Input		: name - the cookie name
//				  unescapedValue - the cookie value
//				  expDateTimeString - the cookie expiration date-time
//				  path - the cookie path
// Output		: N/A
//**********************************************************************
function setCookie(name, unescapedValue, expDateTimeString, path) {
    document.cookie = name + "=" + escape(unescapedValue) + "; expires=" + 
    	expDateTimeString + "; path=" + path;        
}



//**********************************************************************
// Name			: generateExpDateTimeString
// Description	: Generates a standard cookie expiration date-time string 
//				  (specified in GMT) representing a date-time that is
//				  the specified number of days in the future.
// Input		: numDays - the number of days in the future that the 
//				  		    cookie should expire
// Output		: The generated date-time string
//**********************************************************************
function generateExpDateTimeString(numDays) {
    var expDateTime = new Date();
    expDateTime.setTime(expDateTime.getTime() + 1000 * 60 * 60 * 24 * numDays);  
    return expDateTime.toGMTString();
}



//**********************************************************************
// Name			: generateBrowserID
// Description	: Generates a unique ID value to be set in a cookie as
//				  the browser ID.  This value will consist of a UTC 
//				  millisecond value constructed from the current date-time
//				  which represents an offset from the Epoch, followed by
//				  a randomly generated number between 1 and 1,000,000.
//				  (specified in GMT) representing a date-time that is
//				  the specified number of days in the future.
// Input		: N/A
// Output		: The generated browser ID
//**********************************************************************
function generateBrowserID() {
    var currentDateTime;
    var utcEpochMillis;
    var randomNumber;
    
    currentDateTime = new Date();
    
    utcEpochMillis = Date.UTC(currentDateTime.getUTCFullYear(), 
    	currentDateTime.getUTCMonth(), currentDateTime.getUTCDate(),
    	currentDateTime.getUTCHours(), currentDateTime.getUTCMinutes(),
    	currentDateTime.getUTCSeconds(), currentDateTime.getUTCMilliseconds());
    
    randomNumber = generateRandomNumber(1000000);
    
    return utcEpochMillis + "" + randomNumber;
}    



//**********************************************************************
// Name			: generateRandomNumber
// Description	: Generates a random number between 1 and the specified
//				  upper limit.
// Input		: upperLimit - the upper limit of the random number value
//				  range
// Output		: The generated random number
//**********************************************************************
function generateRandomNumber(upperLimit) {
    return Math.floor((Math.random() * upperLimit) + 1);        
}



//**********************************************************************
// Name			: processBrowserID
// Description	: Executes the logic required to extract or generate the
//				  browser ID and determine whether this browser accepts
//				  cookies.
// Input		: N/A
// Output		: A partial request parameters string which includes the
//				  browserID and cookiesAccepted parameters
//**********************************************************************
function processBrowserID() {    
    var browserID;
    var expDateTimeString;
    var cookiesAccepted;
    var cookieName = "atrk";
	var cookiePath = "/";

    browserID = getCookie(cookieName);    
    expDateTimeString = generateExpDateTimeString(365);   
    
    if (browserID != null) {
        //If the browser ID cookie already exists, we can assume that cookies
        //are enabled.
        cookiesAccepted = true;
        
        //Reset cookie with new expiration date-time of one year in the future
        //to essentially create a non-expiring cookie.
        setCookie(cookieName, browserID, expDateTimeString, cookiePath);
    }
    else {        
        //Generate a browser ID
        browserID = generateBrowserID();
        
        //Set cookie with expiration date-time of one year in the future.
        setCookie(cookieName, browserID, expDateTimeString, cookiePath);
        
        //In order to determine whether the browser accepts cookies, check to
        //see if the browser ID cookie was successfully set.
        var retrievedBrowserID = getCookie(cookieName);
        if (retrievedBrowserID != null) {
            cookiesAccepted = true;    
        }
        else {
            cookiesAccepted = false;
        }        
    }
    
    //Return a partial request parameters string which includes the
    //appropriate values for the browserID and cookiesAccepted parameters
    return "browserID=" + browserID + "&cookiesAccepted=" + cookiesAccepted;    
}