﻿var ci_pageID=""; //global PageID string containing PageName
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
 var ci_CLIPHost = '<%= Request.Url.Scheme %>' + '://' + '<%= Request.Url.Host %>' + '/' + '<%= Request.Url.Segments[1] %>';

// -------
function GetDocElement(id)
{
   var element = document.getElementById(id);
   return ( element != null ? element : document.getElementsByName(id)[0]);
}

// -------
function GetNumericValue(str)
{
    if( str == null ) return "";
    
    var numVal = "";
    for( var i=0; i<str.length; i++ )
    {
        if( str.charAt(i) >= '0' && str.charAt(i) <= '9' )
        {
            numVal += str.charAt(i);
        }
    }
    return numVal;   
}

// -------
function PopInfo(Link)
{
   window.open(Link,"","scrollbars=1,resizable=yes");
}

function PopClickInfo(couponId,couponType,Link)
{
   var remString = GetQueryString();
   var cidLoc = remString.indexOf ("cid=") ;
   if (cidLoc >0 )
    remString = remString.replace("cid="+GetQueryStringValue("cid"), '');
   window.open("RecordClick.aspx?cid=" + couponId + "&ctype=" + couponType + "&" + remString + "&link=" + Link, "", "scrollbars=1,resizable=yes");
   
}

// -------
function GetFlashVersion()
{

   var flashVer = 0;
   if ( navigator.plugins && navigator.plugins.length > 0)
   {
      for (var i=0; i < navigator.plugins.length; i++) {
         if ( navigator.plugins[i].name.toLowerCase().indexOf("shockwave flash") >= 0
              && navigator.plugins[i].description.toLowerCase().indexOf("flash ") > -1 ) {
            flashVer = navigator.plugins[i].description.substring(navigator.plugins[i].description.toLowerCase().lastIndexOf("flash ") + 6, navigator.plugins[i].description.toLowerCase().lastIndexOf("flash ") + 7);
         }
      }
   }
  


  if (flashVer == 0)
  {
      for(var i=10; i>0; i--){
	       // flashVersion = 0;
	        try{
		        var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
		        flashVer = i;
		        break;
	           }
		catch(e){
		        
	         }
	}
       
   }
    
   return  flashVer;
}

// -------
function GetQueryStringValue(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 GetQueryString()
{

   var value = "";
   var location = window.location.toString();	    
   if( location.indexOf("?") > -1 )
   {
      value = location.substring(location.indexOf("?")+1);
   }
   return ( decodeURI(value));
}

// -------
function GetQueryStringWithModule(mod)
{
    var qstring = GetQueryString();
    if(qstring.toLowerCase().indexOf('mod=') > -1)
    {
        qstring = qstring.replace("&mod="+GetQueryStringValue("mod"), '')
        qstring = qstring.replace("mod="+GetQueryStringValue("mod") + "&", '')
    }
    if(mod.length > 0)
        qstring = qstring + '&mod=' + mod;
    return qstring;
}

// -------
function GetOffersURL()
{
   window.location.href = "Offers.aspx?" + GetQueryString();
}

// --------------------------------------------------------
function ReplaceCustomFieldsData()
{

   CustomFldsData = new Array;   
   if(typeof(ReturnCustomFieldsData) != 'undefined')
   {
   CustomFldsData = ReturnCustomFieldsData();
       var i=0;
        
        while (true)
        {
            var obj = CustomFldsData[i];
            if (obj==undefined)
                  break;
               
            if ((typeof(obj.FieldName)!= "undefined") && (document.getElementById(obj.FieldName)!=null)) 
            {
                switch (document.getElementById(obj.FieldName).type)
                {            
                case "checkbox":
                case "radio":
                        document.getElementById(obj.FieldName).checked = (obj.FieldValue==1?true:(obj.FieldValue=="on"?true:false));
                        break; 
                case "select":
                        for (var i = 0; i < document.getElementById(obj.FieldName).options.length; i++)                    
                            if (document.getElementById(obj.FieldName).options[i].value == obj.FieldValue) 
                                document.getElementById(obj.FieldName).selectedIndex = i;                    
                                        
                        break; 
                default:
                        document.getElementById(obj.FieldName).value = obj.FieldValue;
                        break;            
                }    
            }  
           
             
            i++;   
        }     
   } 
}

// --------------------------------------------------------
function SetCookie( name, value, expDays, path, domain, secure ) 
{
    // set expiration
    var expDate = new Date();
    expDate.setTime( expDate.getTime() + (expDays * 1000 * 60 * 60 * 24) );

    document.cookie = name + "=" + value +
        ( ( expDays > 0 ) ? ";expires=" + expDate.toGMTString() : "" ) + 
        ( ( path ) ? ";path=" + path : "" ) + 
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );        
}

// --------------------------------------------------------
function DeleteCookie( name, path, domain ) 
{
    document.cookie = name + "=" +
          ( ( path ) ? ";path=" + path : "") +
          ( ( domain ) ? ";domain=" + domain : "" ) +
          ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// --------------------------------------------------------
function GetCookie(name) 
{ 
    var arg = name + "="; 
    var alen = arg.length; 
    var clen = document.cookie.length; 
    var i = 0; 
    while (i < clen) 
    { 
        var j = i + alen; 
        if (document.cookie.substring(i, j) == arg) 
        {
           var eCookieIx = document.cookie.indexOf (";", j); 
           if (eCookieIx == -1) { eCookieIx = document.cookie.length; }
           return unescape(document.cookie.substring(j, eCookieIx));
        }
        i = document.cookie.indexOf(" ", i) + 1; 
        if (i == 0) break; 
    } 
    return null;
}

// --------------------------------------------------------
function GetCookieVal(cookie,name) 
{ 
    var value = "";
    var sValIx = cookie.indexOf(name+"=");
    if( sValIx >= 0 )
    {
       eValIx = cookie.indexOf("&",sValIx+name.length+1);
       if( eValIx == -1 ) { eValIx = cookie.length; }
       value = cookie.substring(sValIx+name.length+1,eValIx);
    }
    
    return value;
}

// --------------------------------------------------------
function GetCookieWithNewVal(cname,name,newval) 
{ 
    cookie = GetCookie(cname);
    if(cookie != null)
    {
        var sValIx = cookie.indexOf(name+"=");
        if( sValIx >= 0 )
        {
           eValIx = cookie.indexOf("&",sValIx+name.length+1);
           cookie = cookie.substring(0,sValIx+name.length+1) + newval + (eValIx > -1? cookie.substring(eValIx) : ""); 
        }
    }
    return cookie;
}

function SetCategoryInMarkerCookie(cat)
{
    cat = cat.replace("^#","'"); //to avoid js error if brand/cat has single quote
    var cookie = GetCookie("CCRCookie");
    if(cookie == null)
        SetCookie("CCRCookie","Markers=defsrt=" + cat,0,"/",null,null);
    else if(cookie.indexOf("defsrt=") > -1)
    {
        var sValIx = cookie.indexOf("defsrt=");
        eValIx = cookie.indexOf("|",sValIx+7);
        cookie = cookie.substring(0,sValIx+7) + cat + (eValIx > -1? cookie.substring(eValIx) : ""); 
        SetCookie("CCRCookie",cookie,0,"/",null,null);
    }
    else
        SetCookie("CCRCookie",cookie + "|defsrt=" + cat,0,"/",null,null);
    
}

// --------------------------------------------------------
function GetClientSessionCookieValue(key,cookieAltValue)
{
    var sessionCookie = GetCookie("ClientSessionInfoCookie");   
    if( sessionCookie != null && sessionCookie.indexOf("CLIENTCOOKIE") > -1 )
    {
        var clientCookie = sessionCookie.substring(sessionCookie.indexOf("CLIENTCOOKIE"));        
        clientCookie = clientCookie.replace(/&/g,"\\").replace(/:/g,"&");               
        
        var clientCookieVal = GetCookieVal(clientCookie,key);               
        if( clientCookieVal != null && clientCookieVal.length > 0 )
        {
            return clientCookieVal;
        }
    }
    
    // use the server side session cookie
    if( cookieAltValue == null )
    {
        return "";
    }
    else if( typeof(ci_sessionCookie) == "undefined" || ci_sessionCookie == null )
    {
        if (typeof(ci_regObj) != "undefined")
        {
             switch (cookieAltValue.toUpperCase())
                {            
                case "EMAIL": return (ci_regObj.email != null && ci_regObj.email.length > 0 ? ci_regObj.email : "");
                case "FIRSTNAME": return (ci_regObj.user != null && ci_regObj.user.length > 0 ? ci_regObj.user : "");                        
                default: return "";
                }        
        }
        else
            return "";      
      
    
    }
    else
    {
        return GetCookieVal(ci_sessionCookie,cookieAltValue);
    }
}

//---------------------------------------------------------
function ci_GetWSDate()
{
  var ci_now = new Date();
  var hour = ci_now.getHours();
  hour = (hour <=9 ? "0" + hour : hour);
  var min = ci_now.getMinutes();
  min = (min <=9 ? "0" + min : min);
  var sec = ci_now.getSeconds();
  sec = (sec <=9 ? "0" + sec : sec);
  var month = ci_now.getMonth() + 1;
  month = (month <=9 ? "0" + month : month);
  var date = ci_now.getDate();
  date = (date <=9 ? "0" + date : date);  
  return ci_now.getFullYear () + '-'+ month + '-' + date + 'T' + hour + ':' + min + ':' + sec;  
}

// --------------------------------------------------------
function state(scd,sdesc)
{
    this.stateCD = scd;
    this.stateDesc = sdesc;
}
// --------------------------------------------------------
// check for existence of double UserRestr cookie
// delete the second cookie if it exists

if((document.cookie.indexOf(" UserRestr=")) > -1)
{

    var l = document.cookie.indexOf(" UserRestr=");
   
    if (document.cookie.indexOf(" UserRestr=",l+1) > -1)
    {
      DeleteCookie("UserRestr","/",null);           
    }
}

// --------------------------------------------------------
// check for existence of double userinfo cookie
// delete the second cookie if it exists
var dblcck = 0;
if((document.cookie.indexOf(" UserInfo=")) > -1)
{
    var l = document.cookie.indexOf(" UserInfo=");
    if (document.cookie.indexOf(" UserInfo=",l+1) > -1)
    { 
	  dblcck = 1;
//      DeleteCookie("UserInfo","/",null);           
    }
}

// --------------------------------------------------------
if(document.cookie.indexOf("SessionInfo") > -1)
{
    var ci_perCookie = (typeof(ci_sObj) != "undefined" ? ci_sObj.ispercookie : "1" );
    
    if (dblcck == 1 && document.cookie.indexOf("=mac=H") > -1)
        var ci_userInfoCookie = GetCookieWithNewVal("UserInfo","mac","H");
    else
        var ci_userInfoCookie = GetCookie("UserInfo");    
    var ci_userRestrictionCookie = GetCookie("UserRestr");
    if (ci_userInfoCookie != null && window.location.href.toLowerCase().indexOf("coupons.com") == -1)
    {  
         // set user user cookie expiration 100 days from now
      //  SetCookie('UserInfo',ci_userInfoCookie, 1095, '/', '', '');
        // set user restriction cookie expiration 100 days from now
        SetCookie('UserRestr',ci_userRestrictionCookie, .12, '/', '', '');
    }
  /*  else if(ci_userInfoCookie != null && ci_perCookie != null && ci_perCookie == "1")
    {
        // set user user cookie expiration 100 days from now
        SetCookie('UserInfo',ci_userInfoCookie, 1095, '/', '', '');
    }
    */
    
    if( ci_userRestrictionCookie != null && ci_perCookie != null && ci_perCookie == "1")
    {
        // set user restriction cookie expiration 100 days from now
        SetCookie('UserRestr',ci_userRestrictionCookie, .12, '/', '', '');
    }
}


//-----------------------
function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}


// JScript File

var Convert = {

    // 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 = Convert._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 = Convert._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 ValidateKeyIsNumeric(key)
{
    return ( key >= 48 && key <= 57 ) || ( key >= 96 && key <= 105 ) || (key == 8) || (key == 37) || (key == 39) || (key == 46);
}

// -----------------------------------------------
function RegUser(loggedid, fname, lname,autoreg,email,ccnum,branchid)
{

    this.user = fname;
    this.lname = lname;
    this.isLoggedIn = loggedid;
    this.isAutoreg = autoreg;
    this.email = email;
    this.ccnum = ccnum;
    this.branchid = branchid;
}
// -----------------------------------------------
function CurrentObj(sessionid, zip,ispercookie, extID, trkID,cartTtl,cartAmt)
{
    this.sessionid = sessionid;
    this.zip = zip;
    this.ispercookie = ispercookie;
    this.extID = extID;
    this.trkID = trkID;
    this.cartTtl = cartTtl;
    this.cartAmt = cartAmt;
    
}
// -----------------------------------------------
// Store class
// -----------------------------------------------
function Store(StoreID, StoreName, LCNumber, Enabled,CardLimitReached)
{
    this.StoreID = StoreID;
    this.StoreName = StoreName;
    this.LCNumber = LCNumber;
    this.Enabled = Enabled;
    this.CardLimitReached = CardLimitReached;
}
// -----------------------------------------------
// CardStore class
// -----------------------------------------------
function CardStore(StoreID, StoreName, StoreImgUrl, StoreCardImgUrl)
{
    this.StoreID = StoreID;
    this.StoreName = StoreName;
    this.StoreImgUrl = StoreImgUrl;
    this.StoreCardImgUrl = StoreCardImgUrl;
}

// -------------------------------------

function GetCart(mod)
{
    var cart = "";
    var mod = GetQueryStringValue("mod");
    var cartCookie = null;
    var cardNum = (typeof(ci_regObj) != "undefined" ? ci_regObj.ccnum : 0)
    if(mod !=null && mod.length =='crd')
    {
        cartCookie = GetCookie("ClientCardCookie_" + cardNum);
    }
    else
    {
        var sessionCookie = GetCookie("ClientSessionInfoCookie");
        var cartCookie = ( sessionCookie != null && sessionCookie.indexOf("CLIENTCOOKIE") > -1 ? sessionCookie.substring(0,sessionCookie.indexOf("CLIENTCOOKIE")) : (sessionCookie != null ? sessionCookie : "") );
    }
    return (cartCookie!= null && cartCookie.length > 0)? cartCookie.substring(0,cartCookie.length-1):"";
}
// -------

function GetCardStoreObject(strID)
{
    var retObj = null;
    if(typeof(ci_cardStoreList) != "undefined" && ci_cardStoreList.length > 0)
    {
        for(var i=0;i<ci_cardStoreList.length;i++)
        {
            if(ci_cardStoreList[i].StoreID == strID)
            {
                retObj = ci_cardStoreList[i];
                break;
            }
        }
    }
    return retObj;
}


// --------------------------------------------------------
// 20091119: Check coupons between pIDs within the same session
function CheckForCartCoupon(printcart)
{
    var count = 0;

    try
    {
       var cart = new Array();
       if (printcart.constructor.toString().indexOf("Array") == -1)
            cart = printcart.toString().split(",");
       else
            cart = printcart;

      /* for(var ii=0;ii< cart.length;ii++)
       {
           for(var jj=0;jj<ci_pods.length;jj++)
           { 
                if (ci_pods[jj].id == cart[ii])
                {
                    count =  count+1;
                    break;
                }
           } 
       }*/
       
        count = (cart.length > 1 ? cart.length : (printcart.length > 0 ? 1: 0 ));
    }
    catch(err){}
   
    return count;
}
