/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

 var ci_CLIPHost = '<%= Request.Url.Scheme %>' + '://' + '<%= Request.Url.Host %>' + '/' + '<%= Request.Url.Segments[1] %>';
 
var Base64 = {
 
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = Base64._utf8_encode(input);
 
        while (i < input.length) {
 
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
 
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
 
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
 
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
        }
 
        return output;
    },
 
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
        while (i < input.length) {
 
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
 
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
 
            output = output + String.fromCharCode(chr1);
 
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
 
        }
 
        output = Base64._utf8_decode(output);
 
        return output;
 
    },
 
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
 
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    },
 
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
 
        while ( i < utftext.length ) {
 
            c = utftext.charCodeAt(i);
 
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
 
        }
 
        return string;
    }
 
}

function processString(varString)
{
    var rawString = varString;
    var encodedString = Base64.encode(rawString);
    tsTrackAJAX(encodedString);
}

function tsTrackAJAX(encodedString)
{
    if (encodedString != '')
    {
        var soapBody = '<StoreEvents xmlns="http:/www.coupons.com/CouponWeb/">'            
        + '<ClientEntities>'        
        + '<ClientEntity>'
        + '<ClientID>412</ClientID>'
        + '<AttribValues>'+encodedString+'</AttribValues>'
        + '<ChildAttribValues></ChildAttribValues>'        
        + '</ClientEntity>'
        + '</ClientEntities>'
        + '</StoreEvents>';
        
        sendSoapPostRequest( '../../MS2Bridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/StoreEvents', soapBody, processTrackAJAX);
    }
}

function processTrackAJAX()
{
    //return nothing
}

function tsGetQueryStringValue(name)
{
   var value = "";
   var location = window.location.toString();	    
   if( location.indexOf(name+"=") > -1 )
   {
      value = location.substring(location.indexOf(name+"=")+name.length+1);
   }
   return ( value.indexOf("&") > -1 ? decodeURI(value.substring(0,value.indexOf("&"))) : decodeURI(value));
}

function tsTrk(lnk)
{
    var mainFrame = document.getElementById("main");
    if( mainFrame != null )
    {
        var tsURL = window.location.pathname;
        tsURL = tsURL.toLowerCase();
        var tsFrameURL = mainFrame.src;
        tsFrameURL = tsFrameURL.toLowerCase();
    	if (tsFrameURL.indexOf('?') <= 0) tsFrameURL += '?';
        var tsPage = tsFrameURL.substring(tsFrameURL.lastIndexOf('/') + 1, tsFrameURL.indexOf('?'));
    }
    else
    {
        var tsURL = window.location.pathname;
        tsURL = tsURL.toLowerCase();
        var tsPage = tsURL.substring(tsURL.lastIndexOf('/') + 1);
    }
    var tsTabPage = tsMapPage(tsPage);
    var tsPID = tsGetQueryStringValue('pid');
    var tsVAR = tsGetQueryStringValue('var');
    var tsSID = tsGetQueryStringValue('sid');
    var tsDID = tsGetQueryStringValue('did');
    var tsDate = new Date();
    var tsDateText = tsMapDate(tsDate);
    var tsTimeText = tsMapTime(tsDate);
    var tsLink = lnk.toLowerCase();
    if (tsLink.indexOf('?') <= 0) tsLink += '?';
    tsLink = tsLink.substring(tsLink.lastIndexOf('/') + 1, tsLink.indexOf('?'));
    var tsShortLink = tsMapPage(tsLink);
    var tsUserAgent = tsParseUserAgent();
    // If no var parameter passed in, get the referrer URL for tsVAR.
    if (tsVAR.length == 0)
    {
        var tsRefer = document.referrer;
        //alert(tsRefer);
        if (tsRefer.lastIndexOf('?') <= 0) tsRefer += '?';
        tsVAR = tsRefer.substring(tsRefer.lastIndexOf('/') + 1, tsRefer.indexOf('?'));
    }
    // If no Session ID is passed in, create a timestamp for SID.
    if (tsSID.length == 0) tsSID = tsDate.getTime();
    // If no PID, set to 99999.
    if (tsPID.length == 0) tsPID = 99999;
    // if no device ID, set to zero.
    if (tsDID.length == 0) tsDID = 0;
    var varString = tsPID+'|'+tsVAR+'|'+tsTabPage+'|'+tsShortLink+'|'+tsDID+'|'+tsSID+'|'+tsDateText+tsTimeText+'|'+tsUserAgent+' ';
    //alert(varString);
    processString(varString);
}

function tsMapPage(lnk)
{
    var tsName = "";
    switch (lnk)
    {
        case "index.html":
            tsName = "Home - Landing Page";
            break;
        case "install.html":
        case "couponprinter.html":
            tsName = "Help Me Install - Coupon Printer";
            break;
        case "print.html":
        case "howtoprint.html":
            tsName = "Help Me Print - How to Print Coupons";
            break;
        case "faqs.html":
        case "faqswin.html":
            tsName = "FAQs - Windows FAQ";
            break;
        case "resources.html":
            tsName = "Resources - Information";
            break;
        case "couponbar.html":
            tsName = "Help Me Install - Coupon Bar";
            break;
        case "installquestionswin.html":
            tsName = "Help Me Install - Windows FAQ";
            break;
        case "installquestionsmac.html":
            tsName = "Help Me Install - Macintosh FAQ";
            break;
        case "systemrequirements.html":
        case "install_sys.html":
            tsName = "Help Me Install - System Requirements";
            break;
        case "printquestionswin.html":
            tsName = "Help Me Print - Windows FAQ";
            break;
        case "printquestionsmac.html":
            tsName = "Help Me Print - Macintosh FAQ";
            break;
        case "faqsmac.html":
            tsName = "FAQs - Macintosh FAQ";
            break;
        case "resources2.html":
        case "contactus.html":
            tsName = "Resources - Contact Us";
            break;
        default:
            tsName = lnk;
            break;
    }
    return tsName;
}

function tsMapDate(oDate)
{
    // Format the Date as yyyy-mm-dd
    var tsDate = oDate.getFullYear()+'-';
    var tsNum = oDate.getMonth()+1;
    if (tsNum<10) tsDate+='0'+tsNum;
    else tsDate+=tsNum;
    tsNum = oDate.getDate();
    if (tsNum<10) tsDate+='-0'+tsNum;
    else tsDate+='-'+tsNum;
    return tsDate;
}

function tsMapTime(oDate)
{
    // Format the Date as yyyy-mm-dd
    var tsTime;
    // Format the Time as hh:mm:ss
    var tsNum = oDate.getHours();
    if (tsNum<10) tsTime=' 0'+tsNum+':';
    else tsTime=' '+tsNum+':';
    tsNum = oDate.getMinutes();
    if (tsNum<10) tsTime+='0'+tsNum+':';
    else tsTime+=tsNum+':';
    tsNum = oDate.getSeconds();
    if (tsNum<10) tsTime+='0'+tsNum;
    else tsTime+=tsNum;
    return tsTime;
}

function tsAppendQueryString(lnkid)
{
    var urlString = document.URL;
    var startPos = urlString.lastIndexOf("?");
    // Append the query string to the link identified by the id
    if (startPos > 0) document.getElementById(lnkid).href += urlString.substr(startPos,urlString.length);
}

function tsParseUserAgent() 
{
    var startPos;
    var UAstring = navigator.userAgent;
    // Check for the platforms we support
    var platformName, browserName, systemType;
    if (UAstring.indexOf("NT 6.1") != -1) platformName = "Windows 7";
    else if (UAstring.indexOf("NT 6.0") != -1) platformName = "Windows Vista";
    else if (UAstring.indexOf("NT 5.2") != -1) platformName = "Windows Server 2003";
    else if (UAstring.indexOf("NT 5.1") != -1) platformName = "Windows XP";
    else if (UAstring.indexOf("NT 5.0") != -1) platformName = "Windows 2000";
    else if (UAstring.indexOf("NT 4.0") != -1) platformName = "Windows NT 4";
    else if (UAstring.indexOf("Win 9x") != -1) platformName = "Windows ME";
    else if (UAstring.indexOf("Win98") != -1) platformName = "Windows 98";
    else if (UAstring.indexOf("10_7") != -1) platformName = "Mac OS X 10.7";
    else if (UAstring.indexOf("10_6") != -1) platformName = "Mac OS X 10.6";
    else if (UAstring.indexOf("10_5") != -1) platformName = "Mac OS X 10.5";
    else if (UAstring.indexOf("10_4") != -1) platformName = "Mac OS X 10.4";
    else if (UAstring.indexOf("10_3") != -1) platformName = "Mac OS X 10.3";
    else if (UAstring.indexOf("10.7") != -1) platformName = "Mac OS X 10.7";
    else if (UAstring.indexOf("10.6") != -1) platformName = "Mac OS X 10.6";
    else if (UAstring.indexOf("10.5") != -1) platformName = "Mac OS X 10.5";
    else if (UAstring.indexOf("10.4") != -1) platformName = "Mac OS X 10.4";
    else if (UAstring.indexOf("10.3") != -1) platformName = "Mac OS X 10.3";
    else if (UAstring.indexOf("Mac OS X") != -1) platformName = "Mac OS X";
    else if (UAstring.indexOf("iPad") != -1) platformName = "iPad";
    else if (UAstring.indexOf("iPod") != -1) platformName = "iPod";
    else if (UAstring.indexOf("iPhone") != -1) platformName = "iPhone";
    else if (UAstring.indexOf("CrOS i686") != -1) platformName = "Chrome OS";
    else if (UAstring.indexOf("Android") != -1) platformName = "Android";
    else if (UAstring.indexOf("Linux") != -1) platformName = "Linux";
    else platformName = "Unknown";
    // Check for the browser
    if (UAstring.indexOf("MSIE") != -1) browserName = "Internet Explorer";
    else if (UAstring.indexOf("Firefox") != -1) browserName = "Firefox";
    else if (UAstring.indexOf("Opera") != -1) browserName = "Opera";
    else if (UAstring.indexOf("Chrome") != -1) browserName = "Chrome";
    else if (UAstring.indexOf("Safari") != -1) browserName = "Safari";
    else if (UAstring.indexOf("verssion/5.1") != -1) browserName = "Safari 5.1";
    else if (UAstring.indexOf("Netscape") != -1) browserName = "Netscape";
    else if (UAstring.indexOf("Camino") != -1) browserName = "Camino";
    else if (UAstring.indexOf("Seamonkey") != -1) browserName = "SeaMonkey";
    else browserName = "Unknown";
    //Check for 64 bit processor
    if (UAstring.indexOf("Win64") != -1) systemType = "(64-bit)";
    else if (UAstring.indexOf("WOW64") != -1) systemType = "(WOW64)";
    else if (UAstring.indexOf("PPC") != -1) systemType = "(PPC)";
    else systemType = "";
    // Write the results to the document
    UAstring = platformName+'|'+browserName + ' ' + systemType;
    return UAstring;
}

function tsCreateHelpURL(DeviceIDName)
{
    var ci_thisPID = GetQueryStringValue ('pid');
    var ci_thisSID = ci_sObj.sessionid;
    var ci_thisDID = 0;
    if (document.getElementById(DeviceIDName) != null) ci_thisDID = document.getElementById(DeviceIDName).value;
    var ci_thisURL = window.location.pathname;
    ci_thisURL = ci_thisURL.toLowerCase();
    var ci_thisPage = ci_thisURL.substring(ci_thisURL.indexOf('couponweb') + 10, ci_thisURL.indexOf('aspx') - 1);
    var TSguideURL = '/CouponWeb/help/print/index.html?pid='+ci_thisPID+'&var='+ci_thisPage+'&sid='+ci_thisSID+'&did='+ci_thisDID+'';
    return TSguideURL;
}
