//regular expressions for replacement variable names to be used
var pageurlKey = /(!PAGEURL)/g;
var zipKey = /(!ZIP)/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;

function replaceAdVariables(targetParams, requestPageUrl){

    //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
        var zipValue = userTrack.getZipCookie();
        if(zipValue !=""){
            //replace all instances of ZIP variable
            targetParams = targetParams.replace(zipKey, zipValue);
        }
    //check to see if state cookie exists
    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
    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
        var edmundsIdValue = getCookieValue("edmunds");
        if(edmundsIdValue !=""){
            //replace all instances of EDMUNDSID variable
            targetParams = targetParams.replace(edmundsKey, edmundsIdValue);
        }

        //check to see if rsi_segs cookie exists
        var resisegValue = getCookieValue("rsi_segs");
        if(resisegValue != null && 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 = getCookieValue("DMSEG");
            if(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
        var edwValue = getCookieValue("edw");
        if(edwValue !=""){
            //replace all instances of EDW variable
            targetParams = targetParams.replace(edwKey, edwValue);
        }

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


        //check to see if geo cookie exists
    
    
    }

    return targetParams;
        
}

function createAdDisplayString(paramKey, format, styleClass, width, height, target, styleName) {
  var src = "http://ad.doubleclick.net/" + ((format == "iframe")? "adi/":"adj/") + paramKey;
  if(styleName != null && styleName != "") {
    styleName = "name=\"" + styleName + "\"";
  } else {
    styleName = "";
  }
  if(format == "iframe") {
    return "<iframe " + styleName + " class=\"" + styleClass + "\"src=\"" + src
            + "\" border=\"0\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"no\" height=\"" +
           height + "\" width=\"" + width + "\" scrolling=\"no\">"
            + "<a " + target + "href=\"" + src + "\">"
            + "<img src=\"" + src + "\" border=\"0\" height=\"" + height + "\" width=\"" + width + "\"/>"
            + "</a> </iframe>";
  } else {
    document.write("<script language=\"Javascript1.1\" SRC=\"" + src + "\" class=\"" + styleClass +
                   "\" width=\"" + width + "\" height=\"" + height
            + "\" frameborder=\"no\" border=\"0\" MARGINWIDTH=\"0\" MARGINHEIGHT=\"0\" SCROLLING=\"no\">" +
                   "</script> <noscript>" +
                   "<A HREF=\"" + src + "\">" +
                   "<IMG SRC=\"" + src + "\" width=\"" + width + "\" height=\"" + height + "\" border=\"0\">" +
                   "</A> </noscript>");
    return;
  }
}

function getAdParamKey(targetParams, width, height, addRandomNum, requestPageUrl, siteName) {
  targetParams = replaceAdVariables(targetParams, requestPageUrl);
  var randNum = globalRandNum;
  var paramKey = targetParams + ";sz=" + width + "x" + height + ";";
  if(addRandomNum) paramKey += "ord=" + randNum;
  return siteName + "/;" + paramKey;
}

function _genAdParamKey(targetParams, width, height, requestPageUrl, siteName){
  return siteName + "/;" + replaceAdVariables(targetParams, requestPageUrl) + ";sz=" + width + "x" + height + ";";
}

function _getAdUrl(paramKey, addRandomNum){
  return "http://ad.doubleclick.net/adi/" + paramKey + ((addRandomNum)? "ord=" + globalRandNum : "");
}

function createAdDisplay(format, targetParams, width, height, target, siteName, addRandomNum, requestPageUrl,
                         styleName, styleClass) {
  var paramKey = getAdParamKey(targetParams, width, height, addRandomNum, requestPageUrl, siteName);
  var content = createAdDisplayString(paramKey, format, styleClass, width, height, target, styleName);
  if(format == "iframe") {
    document.write(content);
  }
}
//end createAdDisplay

function pingAdServer(paramKey, iframeid) {
  var start = window.location.href.indexOf("//");
  var end = window.location.href.indexOf("/", start+2);
  var url = window.location.href.slice(0, end) + "/adi/" + paramKey + "ord=" + globalRandNum;
  var opt = {
    method:'get',
    onSuccess: function (t) {
      var exists = t.responseText.indexOf("displayAdUnit");
      if(exists != -1) {
        $(iframeid).src = url;
      }
    },
    on404: function() {},
    onFailure: function() {},
    onException: function(request, exception) {}
  }
  new Ajax.Request(url, opt);
}

function getCookieValue(cookieName){
    
    var cookieValue="";
    var cookies = document.cookie;
    
    if(cookies == null || cookies.length <0){
        //if no cookies exist then return empty string
        return cookieValue
    }else{
        var totalLength = cookies.length;
        var beginning = 0;
        while (beginning < cookies.length){
            
            middle = cookies.indexOf('=', beginning);
            end = cookies.indexOf(';', beginning);
            if (end == -1) end = totalLength;

            if ((middle < end) && (middle != -1)) {
                name = cookies.substring(beginning, middle);
                if (name == cookieName) {
                    cookieValue = unescape(cookies.substring(middle+1, end));
                    
                }
            }
            beginning = end + 2;
    
        }
        
    }

    return cookieValue;
}

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;
}
