﻿// Add an onload handler
function setOnloadEvent() {
    if (window.addEventListener) { window.addEventListener("load", appendCellCode, false); }
    else { window.attachEvent("onload", appendCellCode); }
}

// If there is a Cell Code in the URL append it to the link
function appendCellCode() {
    
    // Get the Cell Code
    var cellCode = queryStringParamSafeValue("CR_CC", true, "");

    // If the Cell Code is not in the URL we can return
    if ((cellCode == null) || (cellCode.toString().length == 0)) {
        return;
    }

    // Get the anchor tag and the URL. If the URL has a "?" it already has parameters, so append the Cell Code
    // with a "&". If there is no "?" already in the URL then we append the Cell Code with "?".
    var anchorTag = document.getElementById("offerLink");
    var url = anchorTag.getAttribute("href");

    if (url.indexOf("?") == -1) {
        url += "?";
    }
    else {
        url += "&";
    }
    
    url += "CR_CC=" + cellCode;
 
    // Set the anchor tag's HREF to the URL with the Cell Code appended.
    anchorTag.setAttribute("href", url);
}

// Read the query string for a specific parameter, otherwise return the default value.
function queryStringParamSafeValue(name, caseInsensitive, defaultValueIfNull) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var r = "[?&]" + name + "=([^&#]*)";
    var rmod = ""
    if (caseInsensitive) rmod += "i";
    var s = new RegExp(r, rmod);
    var res = s.exec(window.location.href.toString());
    if (!res && defaultValueIfNull) return defaultValueIfNull;
    else if (!res) return null;
    else return res[1];
}

// Initialize
setOnloadEvent();