// Store facets selected for ad targetting
var facetsTargetParams = "";

//regular expressions for replacement variable names to be used
var pageurlKey = /(!PAGEURL)/g;
var zipKey = /(!ZIP)/g;
var dmaKey = /(!DMA)/g;
var edmundsKey = /(!EDMUNDSID)/g;
var resisegKey = /(!RSISEG)/g;
var edwKey = /(!EDW)/g;
var edwTimestampKey = /(!TIMESTAMP)/g;
var stateKey = /(!STATE)/g;
var countyFipKey = /(!COUNTYFIP)/g;

// Replaces Ad variables using client's cookie values
function replaceAdVariables(targetParams, requestPageUrl){

    // Backward compatible with systems that haven't yet switched to the new UserTrack object in Edmunds UI
    var usertrack = window.userTrack || YAHOO.Edmunds.UserTrack;
    
    //if target parameters has content then check for replacement variables
    if(targetParams!=''){
    
        //replace the page url with value from the request
        if(requestPageUrl!='null'){
            //replace all instances of PAGEURL variable
            targetParams = targetParams.replace(pageurlKey, requestPageUrl);
        }
    
        //check to see if zip cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(zipKey))){
            var zipValue = usertrack.getZipCookie();
            if(zipValue !=""){
                //replace all instances of ZIP variable
                targetParams = targetParams.replace(zipKey, zipValue);
            }
        }
        
        //check to see if state cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(stateKey))){
            var stateValue = usertrack.getCookieValue(usertrack.state_cookie_name);
            if(stateValue != "") {
              //replace all instances of ZIP variable
              targetParams = targetParams.replace(stateKey, stateValue);
            }
        }
        
        //check to see if county fip cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(countyFipKey))){
            var countyFipValue = usertrack.getCookieValue(usertrack.countyfips_cookie_name);
            if(countyFipValue != "") {
              //replace all instances of ZIP variable
              targetParams = targetParams.replace(countyFipKey, stateValue + countyFipValue);
            }
        }
        
        //check to see if edmunds id cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(edmundsKey))){
            var edmundsIdValue = usertrack.getEdmundsCookie();
            if(edmundsIdValue !="" && !YAHOO.lang.isNull(edmundsIdValue)){
                //replace all instances of EDMUNDSID variable
                targetParams = targetParams.replace(edmundsKey, edmundsIdValue);
            }
        }

        //check to see if rsi_segs cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(resisegKey))){
            var resisegValue = usertrack.getCookie("rsi_segs");
            if(resisegValue!="" && !YAHOO.lang.isNull(resisegValue)) {
                //reformat the resiseg value
                resisegValue = resisegValue.replace(/B05501_(\d+)\|?/g, "rs=$1;");
                resisegValue = resisegValue.replace(/((rs=\d+;){10}).*/, "$1");
                targetParams = targetParams.replace(resisegKey, resisegValue);
            } else {
    
                //check to see if DMSEG cookie exists
                resisegValue = usertrack.getCookie("DMSEG");
                if(resisegValue !="" && !YAHOO.lang.isNull(resisegValue)){
                    //reformat the resiseg value
                    resisegValue = reformatResisegCookie(resisegValue);
                    //replace all instances of RESISEG variable
                    targetParams = targetParams.replace(resisegKey, resisegValue);
                }
            }
        }

        //check to see if edw cookie exists
        if (!YAHOO.lang.isNull(targetParams.match(edwKey))){
            var edwValue = usertrack.getCookie("edw");
            if(edwValue !="" && !YAHOO.lang.isNull(edwValue)){
                //replace all instances of EDW variable
                targetParams = targetParams.replace(edwKey, edwValue);
            }
        }

        //check to see if edw timestamp cookie exists
        //var edwTimestampValue = getCookieValue("edwtimestamp");
        if (!YAHOO.lang.isNull(targetParams.match(edwTimestampKey))){
            var edwTimestampValue = usertrack.getEdwTimestamp();
            if(edwTimestampValue !=""){
                //replace all instances of TIMESTAMP variable
                targetParams = targetParams.replace(edwTimestampKey, edwTimestampValue);
            }
        }


        // Replace all instances of DMA variable, even if dmaValue
        // is an empty string.
        if (!YAHOO.lang.isNull(targetParams.match(dmaKey))){
            var dmaValue = usertrack.getDmaCookie();
            targetParams = targetParams.replace(dmaKey, dmaValue);
        }
    }

    return targetParams;

}

// Utility function to creates a doubleclick tracking pixel
function createTrackingImage(targetParams, siteName){
    targetParams = replaceAdVariables(targetParams, window.location.href);
    var randNum = globalRandNum;
    var paramKey = targetParams + "sz=1x1;";
    paramKey += "ord=" + randNum;
    var href = 'http://ad.doubleclick.net/jump/'+siteName + '/;' + paramKey;
    var imgSrc = 'http://ad.doubleclick.net/ad/'+siteName + '/;' + paramKey;
    document.write('<a href="'+href+'"><img src="'+imgSrc+'" border="0" width="1" height="1"></a>');
}

// Revenue Science cookie reformatting
function reformatResisegCookie(resisegValue){
    
    var newResisegValue="";
    var regsisegArray = new Array();
    var limit=10;
    regsisegArray = resisegValue.split("&");
    
    if(regsisegArray.length < 6){
        //if the array is less then six return empty string
        return newResisegValue;
    } else {
        for(var i = 5; i<regsisegArray.length; i++){
            var regsisegToken = regsisegArray[i];
            var tokenArray = new Array();
            tokenArray = regsisegToken.split(",");
            if (tokenArray.length < limit){
                limit = tokenArray.length;
                }
            for(var j=0; j<limit; j++){
                if(tokenArray[j] != ""){
                    newResisegValue = newResisegValue + "rs=" + tokenArray[j] + ";";
                }
            }//end for 
          i = regsisegArray.length; 
        }
    }//end else
    return newResisegValue;
}
