var ci_CMEntityString = ""; // global entity string
var ci_CurrPage= 1;
var ci_FeaturedMessages = null;
var processReqChange = "";
var ci_mobphone = null;
var ci_UserUpdateStatus = null;
// --------------------------------------------------------
function clientEntity(url)
{
    this.URL = url;
}

function clientEvent(trID,action,template)
{
  this.trID = trID;
  this.Action = action;
  this.Template = template;
  
}

// --------------------------------------------------------
var ci_RegisterUser = null;

function RegisterUser()
{
 this.Status;
 this.Msg;
 this.UserID;
}

// --------------------------------------------------------
var ci_LoggedInUser = null;

function LoggedInUser()
{
 this.Status;
 this.Msg;
 this.UserID;
 this.FName;
 this.LName;
 this.IsLoggedIn;
}
// --------------------------------------------------------
var ci_MyLoyaltyCards = null;
var ci_AllCharities = null;
var ci_MyCharities = null;
var ci_InvalidCardNum = null;

function GetCouponsFromCardsResult()
{
	this.Status;
	this.Message;
	this.ImageURLPrefix;
	this.CouponList;
}

function Coupon()
{
	this.CardList;
	this.Exp;
	this.ID;
	this.IURL;
	this.OfrDesc;
	this.Summ;
	this.Type;
	this.Val;
	this.BrandName;
	this.RdmType;
	this.PPrice;	
	this.CatID;
	this.CatDesc;
	this.StartDate
}

function Card()
{
	this.CardNum;
	this.StoreID;
	this.Coupons;
}

function GetCouponsFromCardsResult()
{
	this.Status;
	this.Message;
	this.ImageURLPrefix;
	this.CouponList;
}

function LCRestrictionArray()
{
   this.CouponActionList;   
}

function CouponAction()
{
    this.id;
    this.printed;
    this.onCard;
    this.lcCount;
    this.redeemed;
}

function RestrxArr()
{
    this.id;
    this.printed;
    this.onCard;
    this.lcCount;
    this.redeemed;
}

/*CHARITY*/
function GetCharityDetailsResponse()
{
    this.GetCharityDetailsResult;
}

function GetCharityDetailsResult()
{
    this.CharityDetails;
}

function CharityDetails()
{
    this.Status;
    this.Message;
    this.CharityList;
}

function Charity()
{
    this.Default;
    this.Desc;
    this.EndDate;
    this.ID;
    this.Name;
    this.NID;
    this.Order;
    this.PID;
    this.StartDate;
}

/*CHARITY FOR USER*/
function GetCharityDetailsForUserResponse()
{
    this.GetCharityDetailsResult;
}

function GetCharityDetailsForUserResult()
{
    this.CharityDetails;
}

function UserCharity()
{
    this.NID;
    this.UserID;
    this.CharityID;
    this.Name;
    this.Desc;
    this.Order;
    this.StartDate;
    this.Status;
    this.Percentage;
}

function UserCharityRequest()
{
    this.CharityID;
    this.Percentage;
}
/*END CHARITY*/

function UserLoyaltyCards()
{
    this.LCNumber;
    this.StoreID;    
}




function LoadClientEvents()
{
    if(ci_clientEntities != null)
    {
        var imagePxlHTML = "";
        
        for(var i=0;i < ci_clientEntities.length; i++)
        {
           if( ci_clientEntities[i].URL.length > 0 )
           {  
              imagePxlHTML += '<img src="' + ci_clientEntities[i].URL 
                                    + (ci_clientEntities[i].URL.indexOf("?") > -1 ? "&" : "?")
                                    + "seed=" + (new Date()).getTime()
                                    + '" width="1" height="1" />';
           }
        }
        document.getElementById("ClientImgDiv").innerHTML = imagePxlHTML;    
        HandleAction("ClientPageLoad");
    }
}

// -----------------------------------------------
function HandleAction(caller,Data)
{
    
    if(typeof(ci_clientEvents) != "undefined" && ci_clientEvents  != null)
    {
        var location = window.location.toString();	      
        ci_CMEntityString = "";
   
        for(var i=0;i < ci_clientEvents.length; i++)
            {           
                if(caller == ci_clientEvents[i].Action )
                 {                                                               
                    BuildCMEString(ci_clientEvents[i].trID, ci_clientEvents[i].Template, Data);                                        
                 }                 
            } 
    
        XferCME();
    }
}

//--------------------------------------------------------
function GetPagesViewed()
{
  var PagesViewed = "";
          for (var i=0;i < ci_pagesViewed.length; i++)
           {             
             PagesViewed = PagesViewed +  ci_pagesViewed[i];                                    
           }   
   return PagesViewed                   
}
//---------------------------------------------------------
function BuildCMEString(TrID, Template, Data)
{
 
    ci_CMEntityString = ci_CMEntityString +  "<ClientEntity>"
                     + "<ClientID>" + TrID + "</ClientID>"
                     + ReplaceAttributes(Template,Data)
                     + "</ClientEntity>";                                            
    
           
}

//----------------------------------------------------------
function ReplaceAttributes(Template, Data)
{

  var AccessID = document.getElementById(ci_controlPrefix+"AccessID").value; 
  var DeviceID = document.getElementById(ci_controlPrefix+"DeviceID").value;
  var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
  
  var AttribStr = "";  
  var tmpStr = Template;
  
    tmpStr = tmpStr.replace("[accessID]", AccessID);  
    if(Template.indexOf("[pagesviewed]") > -1)
        tmpStr = tmpStr.replace("[pagesviewed]", GetPagesViewed());  
    
    tmpStr = tmpStr.replace("[pid]", GetQueryStringValue('pid'));
    tmpStr = tmpStr.replace("[sessionid]", (typeof(ci_sObj) != "undefined" ? ci_sObj.trkID : "" ));
    
    if(tmpStr.indexOf("[deviceID]") > -1)
     tmpStr = tmpStr.replace("[deviceID]", DeviceID);  
     
   if(tmpStr.indexOf("[userid]") > -1)
     tmpStr = tmpStr.replace("[userid]", userID);    
    
     if(typeof(Data) != "undefined" && Data.length > 0) 
     {
        tmpStr = ReplaceDataAttributes(tmpStr, Data);
     }
     
     AttribStr = "<AttribValues>"
                 + Convert.encode(tmpStr)
                 + "</AttribValues>"
                 + GetChildAttribs(Template);
                  
   return AttribStr;
  
}
//---------------------------------------------------------
function ReplaceDataAttributes(Template, Data)
{
    var tmpStr = Template;
    var arrAttr = Data.split("|");
    for(var i=0;i<arrAttr.length;i++)
    {
        if(arrAttr[i].indexOf("=") > -1)
            tmpStr = tmpStr.replace(arrAttr[i].substr(0,arrAttr[i].indexOf("=")), ((arrAttr[i].indexOf("=")+1) < arrAttr[i].length? arrAttr[i].substr(arrAttr[i].indexOf("=")+1) : ""));
    }
    return tmpStr;
}


//---------------------------------------------------------

function GetChildAttribs(Template)
{
   var ChildAttribStr = "";
   if(Template.indexOf("[printslotdata]") > -1)
   {
     ChildAttribStr =  "<ChildAttribValues>"
                      + Convert.encode(GetSlotData())
                      + "</ChildAttribValues>";
   }
   return ChildAttribStr;
}

//---------------------------------------------------------
function GetSlotData()
{
    var prtSlotData = "";
    
     if(ci_PodsPerPage != null)
           {
              var startIndex = (ci_PodsPerPage * ci_CurrPage)- ci_PodsPerPage ;
              var endIndex = startIndex + ci_PodsPerPage;
              
              if (ci_sortedPods.length <= endIndex)
              {
                endIndex = ci_sortedPods.length;
              } 
               
              for( var i=startIndex; i< endIndex; i++ )
                  {                          
                    var pageSlotIndex = i%ci_PodsPerPage;
                    var slotIndex = i;
                    prtSlotData += ci_sortedPods[i].id + "|" + ci_CurrPage + "|" + pageSlotIndex + "|" + slotIndex + ",";                            
                  }
           }   
      return prtSlotData         
}

//-------------------------------------------------
function TrackPagesViewed(pageNum)
{
   ci_CurrPage = pageNum; 
   ci_pagesViewed[pageNum-1] = "1";   
   HandleAction("ClientPageView");
}
//-------------------------------------------------
function XferCME()
{
  if (ci_CMEntityString != "")
  {
   var soapBody  = '<StoreEvents xmlns="http:/www.coupons.com/CouponWeb/">';
       soapBody += '<ClientEntities>';
       soapBody += ci_CMEntityString ;
       soapBody += '</ClientEntities></StoreEvents>' ; 
       
       sendSoapPostRequest('MS2Bridge.asmx',    
       ci_CLIPHost,'http:/www.coupons.com/CouponWeb/StoreEvents', soapBody, processReqChange);  
   }    
        
}

//---------------------------------------------------

function SendForgotPassword(email, PID)
{     
       var soapBody = '<SendForgotPassword xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '</SendForgotPassword>';

       sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/SendForgotPassword', soapBody, processSendForgotPassword);
}

//----------------------------------------------------


function processSendForgotPassword()
{
    if(_soapRequest.readyState==4)
    {
        //
    }
}

//---------------------------------------------------
function LogUserIn(email, passwd, PID, NID, remember)
{     
//       alert("Email : " + email + ", password : " + passwd + ", PID : " + PID + ", NID : " + NID + ", remember : " + remember);
       var soapBody = '<LogUserIn xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<email>'+ email +'</email>'
            + '<passwd>'+ passwd +'</passwd>'
            + '<PID>'+ PID +'</PID>'
            + '<NID>'+ NID +'</NID>'        
            + '<remember>'+ remember +'</remember>'        
            + '</LogUserIn>';

       sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/LogUserIn', soapBody, processLogUserIn);
}

//----------------------------------------------------


function processLogUserIn()
{
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
//        alert(resText);
        //strip off the soap headers
        var strOutput = KeepOnlyElement(resText, 'LogUserInResponse');
//        alert("string output " + strOutput);
        
        ci_LoggedInUser = new LoggedInUser();
        ci_LoggedInUser.Status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser.Msg = ParseElement(strOutput, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser.UserID = ParseElement(strOutput, 'UserID', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser.FName = ParseElement(strOutput, 'FName', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser.LName =ParseElement(strOutput, 'LName', 'xmlns="http:/www.coupons.com/OfferServices/"');
        
//        alert("message" + ci_LoggedInUser.Msg + ", Status : " + ci_LoggedInUser.Status );
        if(ci_LoggedInUser.Status == 'OK')
        {
            ci_LoggedInUser.IsLoggedIn = 1;
             GetUserLCRestrictions();
            
//            alert("status : " + ci_LoggedInUser.Status + ", Msg : " + ci_LoggedInUser.Msg + ", IsLoggedIn : " + ci_LoggedInUser.IsLoggedIn + ", UserID : " + ci_LoggedInUser.UserID + ", FName : " + ci_LoggedInUser.FName + ", LName : " + ci_LoggedInUser.LName);
        }
        else
        {
            // do something else?
            // log user out?
            ci_LoggedInUser.IsLoggedIn = 0;
            
//            alert("status : " + ci_LoggedInUser.Status + ", Msg : " + ci_LoggedInUser.Msg + ", IsLoggedIn : " + ci_LoggedInUser.IsLoggedIn + ", UserID : " + ci_LoggedInUser.UserID + ", FName : " + ci_LoggedInUser.FName + ", LName : " + ci_LoggedInUser.LName);
       }
    }
}
//------------------------------------------------------------------------------
function LogUserOut()
{
   
        
      var soapBody = '<LogUserOut xmlns="http:/www.coupons.com/CouponWeb/">'            
              + '<nPid>'+ GetQueryStringValue('pid') +'</nPid>'
              + '</LogUserOut>';

       sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/LogUserOut', soapBody, processLogUserOut);    
}

function processLogUserOut()
{
    if(_soapRequest.readyState==4)
    {
       if((typeof(ci_LoggedInUser) == "undefined")||(ci_LoggedInUser == null))
            ci_LoggedInUser = new LoggedInUser();
   
       ci_LoggedInUser.UserID = 0;
       ci_LoggedInUser.FName = "";
       ci_LoggedInUser.LName = "";
   
      if(ci_regObj != "undefined"){
          ci_regObj.isLoggedIn = "0";
          ci_regObj.user = "";
          ci_regObj.lname = "";
          ci_regObj.email = "";
    }
    
    
    if(ci_restrxArr != "undefined"){
        ci_restrxArr.id = null;
        ci_restrxArr.printed = null ;
        ci_restrxArr.onCard =null;
        ci_restrxArr.lcCount = null;
        ci_restrxArr.redeemed = null;
    }
    else
        ci_restrxArr = (null,null,null,null,null); 

    }
}

 function ParseElement(maintext, elementname, xmlnamespace)
 {
    var start = 0;
    var stop = 0;
    
    if (maintext.indexOf('<' + elementname + '>') > -1 )
    {
        start = maintext.indexOf('<' + elementname + '>') + elementname.length + 2;  // < and > are 2 characters
    }
    else
    {
        start = maintext.indexOf('<' + elementname + ' ' + xmlnamespace + '>') + elementname.length + xmlnamespace.length + 3; // < and > and ' ' are 3 characters
    }
    
    if (maintext.indexOf('</' + elementname + '>') > -1 )
    {
        stop = maintext.indexOf('</' + elementname + '>');
    }
    else
    {
        return ''; // couldn't find the closing tag, it must be an empty node
    }
    
 	return maintext.substring(start, stop);
 }

//---------------------------------------------------

function RegisterCouponWebUser(NID, PID, email, passwd, remember, storeID, cardNumber)
{     
//       alert("NID : " + NID + ", PID : " + PID + ", email : " + email + ", password : " + passwd + ", remember : " + remember + ", store ID : " + storeID + ", card number : " + cardNumber);
       var soapBody = '<RegisterUser xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '<passwd>'+ passwd +'</passwd>'
            + '<remember>'+ remember +'</remember>'        
            + '<storeID>'+ storeID +'</storeID>'
            + '<cardNumber>'+ cardNumber +'</cardNumber>'
            + '<Optin1>0</Optin1><Optin2>0</Optin2><Optin3>0</Optin3><Optin4>0</Optin4>'
            + '</RegisterUser>';

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/RegisterUser', soapBody, processRegisterUser);
}

function makeZeroOrOne(x)
{
  try {
    if (x + 0 < 0.5) return 0;
    if (x + 0 >= 0.5) return 1;
    }
    catch (e)
    {
        return 0; 
    }
}

function RegisterCouponWebUserWithOptIn(NID, PID, email, passwd, remember, storeID, cardNumber, Optin1, Optin2, Optin3, Optin4)
{     
//       alert("NID : " + NID + ", PID : " + PID + ", email : " + email + ", password : " + passwd + ", remember : " + remember + ", store ID : " + storeID + ", card number : " + cardNumber);
       makeZeroOrOne(Optin1);
       makeZeroOrOne(Optin2);
       makeZeroOrOne(Optin3);
       makeZeroOrOne(Optin4);
       
       var soapBody = '<RegisterUser xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '<passwd>'+ passwd +'</passwd>'
            + '<remember>'+ remember +'</remember>'        
            + '<storeID>'+ storeID +'</storeID>'
            + '<cardNumber>'+ cardNumber +'</cardNumber>'
            + '<Optin1>' + Optin1 + '</Optin1>'
            + '<Optin2>' + Optin2 + '</Optin2>'
            + '<Optin3>' + Optin3 + '</Optin3>'
            + '<Optin4>' + Optin4 + '</Optin4>'
            + '</RegisterUser>';

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/RegisterUser', soapBody, processRegisterUser);
}

// ***************************************************
//
// 3/22/2010 KWu: register new user with zipcode input
//
// ***************************************************
function RegisterCouponWebUserWithZipcodeOptIn(NID, PID, email, passwd, remember, storeID, cardNumber, Optin1, Optin2, Optin3, Optin4, Zipcode)
{     
    try
    {
        //register a user
        makeZeroOrOne(Optin1);
        makeZeroOrOne(Optin2);
        makeZeroOrOne(Optin3);
        makeZeroOrOne(Optin4);
       
        var rcwz = new AjaxObject('MS2RegistrationBridge.asmx', 'RegisterUserWithZipcodeResult');
        
        //overwrite callback function after response received
        rcwz.callback = function () { ReturnRegisterCouponWebUserWithZipcodeOptIn(rcwz.getresponse());}
        var soapBody = '<RegisterUserWithZipcode xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '<passwd>'+ passwd +'</passwd>'
            + '<remember>'+ remember +'</remember>'        
            + '<storeID>'+ storeID +'</storeID>'
            + '<cardNumber>'+ cardNumber +'</cardNumber>'
            + '<Optin1>' + Optin1 + '</Optin1>'
            + '<Optin2>' + Optin2 + '</Optin2>'
            + '<Optin3>' + Optin3 + '</Optin3>'
            + '<Optin4>' + Optin4 + '</Optin4>'
            + '<Zipcode>' + Zipcode + '</Zipcode>'
            + '</RegisterUserWithZipcode>';
        
        rcwz.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/RegisterUserWithZipcode', soapBody);
    }
    catch (ex) {}
    
    
}

// 3.22.2010: assign value to the ci_register object ----------------------------------------------------
function ReturnRegisterCouponWebUserWithZipcodeOptIn(strOutput)
{
    try
    {
        ci_InvalidCardNum = "";  

        ci_RegisterUser = new RegisterUser();
        ci_RegisterUser.Status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.Msg = ParseElement(strOutput, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser = new LoggedInUser();
         
        if(ci_RegisterUser.Status == 'OK')
        {
            // log user in
            ci_LoggedInUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
           // ci_LoggedInUser.FName = ParseElement(strOutput, 'FName', 'xmlns="http:/www.coupons.com/OfferServices/"');
           // ci_LoggedInUser.LName =ParseElement(strOutput, 'LName', 'xmlns="http:/www.coupons.com/OfferServices/"');
           ci_LoggedInUser.IsLoggedIn = 1;
           
           if (ci_RegisterUser.Msg.length > 0)
             ci_InvalidCardNum = ci_RegisterUser.Msg;
           else
             ci_InvalidCardNum = "1";  
             
           GetUserLCRestrictions();
        }
        else
        {
           ci_InvalidCardNum = "";
        }
    }
    catch (ex) {}
}

// ***************************************************
//
// 6/18/2010 Sarita Inguava: Update User
//
// ***************************************************
function UpdateCouponWebUser(NID, PID, email, passwd, remember, Optin1, Optin2, Optin3, Optin4, Zipcode)
{     
  //alert("NID : " + NID + ", PID : " + PID + ", email : " + email + ", password : " + passwd + ", remember : " + remember + ", Optin1 : " + Optin1 + ", Optin2 : " + Optin2 + ", Optin3 : " + Optin3 + ", Optin4 : " + Optin4 + ", Zipcode : " + Zipcode);
    try
    {
        //register a user
        makeZeroOrOne(Optin1);
        makeZeroOrOne(Optin2);
        makeZeroOrOne(Optin3);
        makeZeroOrOne(Optin4);
       
        var rcwz = new AjaxObject('MS2RegistrationBridge.asmx', 'UpdateRegisteredUserResult');
                
        //overwrite callback function after response received
        rcwz.callback = function () { ReturnUpdateRegisteredUser(rcwz.getresponse());}
        var soapBody = '<UpdateRegisteredUser xmlns="http:/www.coupons.com/CouponWeb/">'                          
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '<passwd>'+ passwd +'</passwd>'
            + '<remember>'+ remember +'</remember>'
            + '<Optin1>' + Optin1 + '</Optin1>'
            + '<Optin2>' + Optin2 + '</Optin2>'
            + '<Optin3>' + Optin3 + '</Optin3>'
            + '<Optin4>' + Optin4 + '</Optin4>'
            + '<Zipcode>' + Zipcode + '</Zipcode>'
            + '</UpdateRegisteredUser>';       
        rcwz.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/UpdateRegisteredUser', soapBody);
    }
    catch (ex) {}
    
}

function ReturnUpdateRegisteredUser(strOutput)
{
    try
    {
        ci_RegisterUser = new RegisterUser();
        ci_RegisterUser.Status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.Msg = ParseElement(strOutput, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');     
         
        if(ci_RegisterUser.Status == 'OK')
        {
          ci_UserUpdateStatus = "1";
        }
        else
        {
          ci_UserUpdateStatus = "0";
        }
        //alert(ci_UserUpdateStatus);
    }
    catch (ex) {}
}

//----------------------------------------------------

function processRegisterUser()
{
    ci_InvalidCardNum = "";  
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;

        //strip off the soap headers
        var strOutput = KeepOnlyElement(resText, 'RegisterUserResponse');

        ci_RegisterUser = new RegisterUser();
        ci_RegisterUser.Status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.Msg = ParseElement(strOutput, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser = new LoggedInUser();
         
        if(ci_RegisterUser.Status == 'OK')
        {
            // log user in
            ci_LoggedInUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
           // ci_LoggedInUser.FName = ParseElement(strOutput, 'FName', 'xmlns="http:/www.coupons.com/OfferServices/"');
           // ci_LoggedInUser.LName =ParseElement(strOutput, 'LName', 'xmlns="http:/www.coupons.com/OfferServices/"');
           ci_LoggedInUser.IsLoggedIn = 1;
           
           if (ci_RegisterUser.Msg.length > 0)
             ci_InvalidCardNum = ci_RegisterUser.Msg;
           else
             ci_InvalidCardNum = "1";  
             
           GetUserLCRestrictions();
        }
        else
        {
           ci_InvalidCardNum = "";
        }

    }
}
//---------------------------------------------------

function RemoveLoyaltyCard(storeID, cardNum)
{     

       var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       if(userID == "0")
            return;	  
        var soapBody = '<AddLoyaltyCard xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<StoreID>'+ storeID +'</StoreID>'
            + '<UserID>'+ userID +'</UserID>'
            + '<CardNumber>'+ cardNum +'</CardNumber>'
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>'     
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'    
            + '<IsDelete>1</IsDelete>'        
            + '</AddLoyaltyCard>';
            
            //alert(soapBody);

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/AddLoyaltyCard', soapBody, processAddCardRes);
        
}

//---------------------------------------------------

function AddLoyaltyCard(storeID, cardNum)
{     

       var userID = "0";
       if (typeof(ci_regObj) != "undefined" && ci_regObj.isLoggedIn > 0) 
            userID =  ci_regObj.isLoggedIn;
       else if (typeof(ci_LoggedInUser)!= "undefined" && ci_LoggedInUser != null) 
            userID =  ci_LoggedInUser.UserID;   

       if(userID == "0")
            return;	  
        var soapBody = '<AddLoyaltyCard xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<StoreID>'+ storeID +'</StoreID>'
            + '<UserID>'+ userID +'</UserID>'
            + '<CardNumber>'+ cardNum +'</CardNumber>'
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>'     
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'        
            + '<IsDelete>0</IsDelete>'        
            + '</AddLoyaltyCard>';
            

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/AddLoyaltyCard', soapBody, processAddCardRes);
        
}

//----------------------------------------------------

function processAddCardRes()
{
    ci_InvalidCardNum = "";  
    
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
        if(resText != null && resText.indexOf('<Status') > -1)
        {
            var status = ParseElement(resText, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"'); 
            //resText.substring(resText.indexOf('<Status>')+ 8, resText.indexOf('</Status>'));
            
            if(status == 'OK')
            {
            
                   if (resText.indexOf('<Message />') > 0 || resText.indexOf('<Message/>') > 0 || resText.indexOf('<Message xmlns="http:/www.coupons.com/OfferServices/" />') > 0 || resText.indexOf('<Message xmlns="http:/www.coupons.com/OfferServices/"/>') > 0 )
                        ci_InvalidCardNum = "1";                     
                   else
                        ci_InvalidCardNum = ParseElement(resText, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"'); 
            }
            else
            {
                ci_InvalidCardNum = ""; 
            }
        }
    }
}

//---------------------------------------------------
function GetCouponsFromCards()
{    
 
       var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       //var branchID = "111"; 
       var branchID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.branchid : "0");
       //alert(ci_regObj.branchid);
	   if(userID == "0" )
       {
            return;	  
       }

        var soapBody = '<GetCouponsFromCards xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<UserID>'+ userID +'</UserID>'
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'
            + '<BranchID>'+ branchID +'</BranchID>'  
            + '<CardNumber>'+ '' +'</CardNumber>'  
            + '</GetCouponsFromCards>';
            

        sendSoapPostRequest( 'MS2Bridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetCouponsFromCards', soapBody, processCards);
        
}
//----------------------------------------------------

function processCards()
{
    
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
        if(resText != null && resText.indexOf('<Status>') > -1)
        {
        
            var status = resText.substring(resText.indexOf('<Status>')+ 8, resText.indexOf('</Status>'));
            if(status == 'OK')
            {
            
                //strip off the soap headers
                var strOutput = KeepOnlyElement(resText, 'GetCouponsFromCardsResponse');
                //deserialize into objects
                var NewObject = JDeserialize(strOutput);
                //turn the arrays inside out
                ci_MyLoyaltyCards = turnCouponsIntoCards(NewObject);
                
                //debug
                /*
                	var soutput = "";
                	var mycard = "";
	                for (mycard in ci_MyLoyaltyCards)
	                {
	                    if (mycard == 'contains') continue;
	                    if (mycard == 'swap') continue;
		                soutput += mycard;
		                soutput += " ";
		                soutput += ci_MyLoyaltyCards[mycard].StoreID;
		                soutput += "\n";
		                for (i=0; i<ci_MyLoyaltyCards[mycard].Coupons.length; i++)
		                {
			                soutput += "\t";
			                soutput += ci_MyLoyaltyCards[mycard].Coupons[i].ID;
			                soutput += "\n";
		                }
	                }
	                alert(soutput);                	
	               */
            }
            else
            {
                //do nothing
            }
        }
    }
}

//---------------------------------------------------

function GetUserLCRestrictions()
{     

       var soapBody = '<GetLCRestrictions xmlns="http:/www.coupons.com/CouponWeb/">'            
                        + '<nPid>'+ GetQueryStringValue('pid') +'</nPid>'                 
                        + '</GetLCRestrictions>';

       sendSoapPostRequest( 'MS2Bridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetLCRestrictions', soapBody, processGetRestrictions);
}

//----------------------------------------------------


function processGetRestrictions()
{

    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;        
        var strOutput = KeepOnlyElement(resText, 'LCRestrictionArray');
     
        if(strOutput.length > 0)
        {
            var NewObject = JDeserialize(strOutput);
            
            ci_restrxArr = new Array();
            
            // form the new restrictions array
            for(var i = 0;i<NewObject.length;i++)
            {
                var rstx = new RestrxArr()
                rstx.id = NewObject[i].CID;
                rstx.printed = (NewObject[i].Printed == "true" ? "1" : "0") ;
                rstx.onCard =(NewObject[i].OnCard == "true" ? "1" : "0");
                rstx.lcCount = NewObject[i].LCCount;
                rstx.redeemed = (NewObject[i].IsRedeemed ? "1" : "0");
                ci_restrxArr.push(rstx);          
            
            }
        }
        else
        {
            ci_restrxArr = new Array();
            var rstx = new RestrxArr()
            rstx.id = null;
            rstx.printed = null;
            rstx.onCard =null;
            rstx.lcCount = null;
            rstx.redeemed = null;
                
            ci_restrxArr.push(rstx);  
        }
                

        
        if (typeof(RefreshRegistrationContent) != 'undefined')
        {
            //refresh after login with SSO on client side
            RefreshRegistrationContent();
        }
    }
}
//----------------------------------------------------

function GetStoresForUsers(userIDPassedIn)
{     
   
        
        var soapBody = '<GetLoyaltyCards xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<UserID>'+ userIDPassedIn +'</UserID>'
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'  
            + '</GetLoyaltyCards>';
            
            //alert(soapBody);

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetLoyaltyCards', soapBody, processUserLCCards);
        
}

//---------------------------------------------------

function processUserLCCards()
{

      if(_soapRequest.readyState==4)
      {
        var resText = _soapRequest.responseText;       
         
        var strOutput = KeepOnlyElement(resText, 'CardList');
      
        if(strOutput.length > 0)
        {
          var NewObject = JDeserialize(strOutput);
            
           ci_userCardStoreList = new Array();
           
           for(var i=0;i<NewObject.length;i++)
           {
                var usrCardStore = new Store(NewObject[i].StoreID, "", NewObject[i].LCNumber, 1,0);
                ci_userCardStoreList.push(usrCardStore);
           }
           
        }
      }
}


//---------------------------------------------------
 function KeepOnlyElement(maintext, elementname)
 {
    if ((maintext.indexOf('<'+ elementname + '/>') > -1)||(maintext.indexOf('<'+ elementname + ' />') > -1)||(maintext.indexOf('<'+ elementname + ' xmlns=\"http:/www.coupons.com/OfferServices/\" />') > -1))
        return ''
    else
        return maintext.substring(maintext.indexOf('<' + elementname ), maintext.indexOf('</' + elementname ) + 3 + elementname.length);
 }

function GetCouponsFromCardsResponse()
{
	this.GetCouponsFromCardsResult;
}

//----------------------------------------------------

function IsComplex(s)
{
	var retval = false;
	if (s == "GetCouponsFromCardsResponse") return true;
	if (s == "GetCouponsFromCardsResult") return true;
	if (s == "Coupon") return true;
	if (s == "Card") return true;
	if (s == "CouponAction") return true;
	if (s == "LCRestrictionArray") return true;
	if (s == "UserLoyaltyCards") return true;	
	if (s == "GetCharityDetailsResponse") return true;
	if (s == "GetCharityDetailsResult") return true;
	if (s == "CharityDetails") return true;
	if (s == "Charity") return true;
	if (s == "CharityList") return true;
    if (s == "GetCharityDetailsForUserResponse") return true;
	if (s == "GetCharityDetailsForUserResult") return true;
	if (s == "UserCharity") return true;
	if (s == "UserCharityList") return true;
	if (contains(s, "list")) return true;
	return retval;
}

//----------------------------------------------------
//hold the coupons and cards here
//for cards that hold coupons

function turnCouponsIntoCards(Thisoutput)
{
    var couponsarray = Thisoutput.GetCouponsFromCardsResult.CouponList;
    var acoupon;
    var oldcardarray;
    var newcardarray = new Array();
    for(var i=0; i<couponsarray.length; i++)
    {
        acoupon = couponsarray[i];
        oldcardarray = acoupon.CardList;
        var acard;
        for (var j=0; j<oldcardarray.length; j++)
        {
            acard = oldcardarray[j];
            acard.Coupons = new Array();
            acard.Coupons.push(acoupon);
            if (newcardarray[acard.CardNum] == null)
                newcardarray[acard.CardNum] = acard;
            else
            {
                if (newcardarray[acard.CardNum].Coupons == null)
                    newcardarray[acard.CardNum].Coupons = new Array();
                newcardarray[acard.CardNum].Coupons.push(acoupon);
            }
        }
    }
    return newcardarray;
}

//-----------------------------------------------------
//-CHARITY FUNCTIONS for AARP
//-----------------------------------------------------

//-----------------------------------------------------
function GetAllCharitiesForPID()
{     
//       var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
  //     if(userID == "0")
    //        return;	  
        var soapBody = '<GetCharityDetails xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'  
            + '</GetCharityDetails>';
            
            //alert(soapBody);

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetCharityDetails', soapBody, processCharityDetails);
        
}

function GetAllCharitiesForUser()
{     
       var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       
       //userID = "41229621";
       
       if(userID == "0")
            return;	  
        var soapBody = '<GetCharityDetailsForUser xmlns="http:/www.coupons.com/CouponWeb/">'                        
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'  
            + '<UserID>'+ userID +'</UserID>'
            + '</GetCharityDetailsForUser>';
            
        //alert(soapBody);

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetCharityDetailsForUser', soapBody, processCharityDetailsForUser);
        
}

//----------------------------------------------------

function UpdateAllCharitiesForUser(UserCharityRequestArray)
{     
       var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       
       //uncomment this for testing from seantest.html
       //userID = "41229621";
       
       if(userID == "0")
            return;	  
            
        var serializedCharityRequest = JSerializeArrayOfObjects(UserCharityRequestArray, 'UserCharityRequestArray', 'UserCharityRequest','http:/www.coupons.com/OfferServices/');
        
        var soapBody = '<UpdateCharityDetailsForUser xmlns="http:/www.coupons.com/CouponWeb/">'                        
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'  
            + '<UserID>'+ userID +'</UserID>'
            + serializedCharityRequest            
            + '</UpdateCharityDetailsForUser>';
            
            soapBody = soapBody.replace('<CharityID type="string">', '<CharityID xmlns="http:/www.coupons.com/OfferServices/" type="string">');  
            soapBody = soapBody.replace('<Percentage type="number">', '<Percentage xmlns="http:/www.coupons.com/OfferServices/" type="number">');  
            
            //alert(soapBody);

        sendSoapPostRequest( 'MS2RegistrationBridge.asmx',    
        ci_CLIPHost,'http:/www.coupons.com/CouponWeb/UpdateCharityDetailsForUser', soapBody, processCharityUpdateDetailsForUser);
        
}

//----------------------------------------------------

function processCharityDetails()
{
    
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
        if(resText != null && resText.indexOf('<Status') > -1)
        {
        
         //   var status = resText.substring(resText.indexOf('<Status')+ 7, resText.indexOf('</Status>'));
            var status = ParseElement(resText, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
            if(status.indexOf('OK') > -1)
            {
            
                //strip off the soap headers
                var strOutput = KeepOnlyElement(resText, 'GetCharityDetailsResponse');
                //deserialize into objects
                var NewObject = JDeserialize(strOutput);
                //turn the arrays inside out
                ci_AllCharities = NewObject;
                
                //debug
                /*
                	var soutput = "";
                	var myCharityList = ci_AllCharities.GetCharityDetailsResult.CharityDetails.CharityList;
                	var mycharity = "";
	                for (mycharity in myCharityList)
	                {
	                    if (mycharity == 'contains') continue;
	                    if (mycharity == 'swap') continue;
		                soutput += mycharity;
		                soutput += " ";
		                soutput += myCharityList[mycharity].ID
		                soutput += " ";
		                soutput += myCharityList[mycharity].Name
		                soutput += "\n";

	                }
	                alert(soutput);                	
	              */ 
            }
            else
            {
                ci_AllCharities="";
                //do nothing
            }
        }
    }
    }
    
function processCharityUpdateDetailsForUser()
{
    
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
        if(resText != null && resText.indexOf('<Status') > -1)
        {
            var status = ParseElement(resText, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
          //  var status = resText.substring(resText.indexOf('<Status')+ 7, resText.indexOf('</Status>'));
            if(status.indexOf('OK') > -1)
            {            
                //strip off the soap headers
                var strOutput = KeepOnlyElement(resText, 'UpdateCharityDetailsForUserResponse');
                //deserialize into objects
                var NewObject = JDeserialize(strOutput);
                ci_MyCharities = NewObject;
                //debug
                
                	//var soutput = NewObject.Message;

		            //alert(soutput); 
		        
            }
            else
            {
            ci_MyCharities = "";
                //alert('FAIL');
                //document.write(resText);
                //document.close();
                //do nothing
            }
        }
    }
}

function processCharityDetailsForUser()
{
    
    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;
        if(resText != null && resText.indexOf('<Status') > -1)
        {
        
            var status = resText.substring(resText.indexOf('<Status')+ 7, resText.indexOf('</Status>'));
            if(status.indexOf('OK') > -1)
            {            
                //strip off the soap headers
                var strOutput = KeepOnlyElement(resText, 'GetCharityDetailsForUserResponse');
                //deserialize into objects
                var NewObject = JDeserialize(strOutput);
                //turn the arrays inside out
                ci_MyCharities = NewObject;
                
                //debug
                    /*  
                	var soutput = "";
                	var myCharityList = ci_MyCharities.GetCharityDetailsForUserResult.UserCharityList;
                	var mycharity = "";
	                for (mycharity in myCharityList)
	                {
	                    if (mycharity == 'contains') continue;
	                    if (mycharity == 'swap') continue;
		                soutput += mycharity;
		                soutput += " ";
		                soutput += myCharityList[mycharity].CharityID
		                soutput += " ";
		                soutput += myCharityList[mycharity].Name
		                soutput += "\n"; 
		            }
		            */
		            //alert(soutput); 
		          
            }
            else
            {
                //do nothing
            }
        }
    }
 }

//----------------- user optin flag update ----
function UpdateUserOptIn(NID, PID, UserID, Optin1, Optin2, Optin3, Optin4)
{     
       //alert("NID : " + NID + ", PID : " + PID + ", UerID : " + UserID + ", Opt1 : " + Optin1 + ", Optin2 : " + Optin2 + ", Optin3 : " + Optin3 + ", Optin4 : " + Optin4);

       makeZeroOrOne(Optin1);
       makeZeroOrOne(Optin2);
       makeZeroOrOne(Optin3);
       makeZeroOrOne(Optin4);
       
       var userLookUp =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       
       if(userLookUp == "0" || userLookUp != UserID)
            return;	  
       
       var soapBody = '<UpdateUserOptIn xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<UserID>'+ UserID +'</UserID>'
            + '<Optin1>' + Optin1 + '</Optin1>'
            + '<Optin2>' + Optin2 + '</Optin2>'
            + '<Optin3>' + Optin3 + '</Optin3>'
            + '<Optin4>' + Optin4 + '</Optin4>'
            + '</UpdateUserOptIn>';

      sendSoapPostRequest( 'MS2RegistrationBridge.asmx', ci_CLIPHost,'http:/www.coupons.com/CouponWeb/UpdateUserOptIn', soapBody, processRegisterUser);
}


// category class
function category(cat,summ, catid)
{
    this.category = cat;
    this.catid = catid;
    this.subCategories = new Array();
    this.podsIx = new Array();
    this.summ = summ;
    this.addPodIx = function(x) { this.podsIx.push(x); }
}

// brand class
function brand(brd,summ)
{
    this.brand = brd;
    this.podsIx = new Array();
    this.summ = summ;
    this.addPodIx = function(x) { this.podsIx.push(x); }
}




//----------------- return all messages with the given pid and nid ----
function GetPidNidAllMessages(pageId, nid, pid, typeid, pageIndex, type, login)
{
    try
    {
    var ajaxcall = new AjaxObject('MS2Bridge.asmx', 'GetSiteMessagesResult');
    
            //overwrite callback function after response received
            ajaxcall.callback = function () { 
            //convert to message list object for UI processing
            ci_FeaturedMessages = eval ( '(' + ajaxcall.getresponse() + ')'); 
            //search again to handle first load
              //search again to handle first load
            if (typeof(ci_OfferThemeObj) != "undefined" && ci_OfferThemeObj != null)
                ci_OfferThemeObj.GetMessage(pageId, typeid, pageIndex, type, login);
            else if (typeof(ci_MyOfferThemeObj) != "undefined" && ci_MyOfferThemeObj != null)
                ci_MyOfferThemeObj.GetMessage(pageId, typeid, pageIndex, type, login);
            else
                GetMessage(pageId, typeid, pageIndex, type, login); 
    }
    
    var soapBody = "<GetSiteMessages xmlns=\"http:/www.coupons.com/CouponWeb/\"><NID>"+ nid +"</NID><PID>"+ pid + "</PID><PageID>" + pageId + "</PageID><TypeID>0</TypeID><TypeName></TypeName><PageNo>0</PageNo></GetSiteMessages>";
    ajaxcall.postdata('MS2Bridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetSiteMessages', soapBody);
    }
    catch (ex) {}
}


//----------------- return a matched message ----
function GetPidNidSingleMessage(pageId, typeid, pageIndex, type, login)
{
      try
      {
          //get site message object if not loaded
          if (ci_FeaturedMessages == null)
          {
              if (GetQueryStringValue('pid').length == 0)
                return msg;
              if (GetQueryStringValue('nid').length == 0)
                return msg;
              
              var nid = GetQueryStringValue('nid');
              var pid = GetQueryStringValue('pid');
          
              GetPidNidAllMessages(pageId, nid, pid, typeid, pageIndex, type, login);
          }
            
          if (ci_FeaturedMessages == null)
                return null;
          
          //getting message with login status
          switch(login)
          {
                //get message for login status depending on status from ci_regObj.isLoggedIn 
                case 1:
                    return SearchLoginMessageList(pageId, typeid, pageIndex, type);
                    break;
                //get all messages disregarding login status
                default:
                    return SearchMessageList(pageId, typeid, pageIndex, type);
                    break;
           }
           
     }
     catch (ex){}   
          
     return null;
}

//----------------- loop to find a message ----
function SearchMessageList(pageId, typeid, pageIndex, type)
{
    var msg = new Array();

    try
    {
          //search message
          //loop messsages to find a message
          for (var i=0; i < ci_FeaturedMessages.MessageList.length; i++)
          {
            var arr = ci_FeaturedMessages.MessageList[i];
            
            switch (typeid)
            {
               case 0: //page
                    for (var j = arr.PgList.length-1; j > -1; j--)
                    {
                        //msg the page rquesting for the message
                        if (arr.PgList[j].PgID.toLowerCase() == pageId.toLowerCase())
                        {
                           //default page message
                           for (var k = arr.PgList[j].PgOptLst.length-1; k > -1; k--)
                           { 
                                //exact page match
                                if (arr.PgList[j].PgOptLst[k].PgOpt == 1 && arr.PgList[j].PgOptLst[k].RngLwr == pageIndex && arr.PgList[j].PgOptLst[k].RngUpr == pageIndex)
                                {
                                    msg.push(arr);
                                }
                                //range page match
                                else if (arr.PgList[j].PgOptLst[k].PgOpt == 2 &&  arr.PgList[j].PgOptLst[k].RngLwr <= pageIndex && arr.PgList[j].PgOptLst[k].RngUpr >= pageIndex)
                                {
                                    msg.push(arr);
                                }
                                //default page match
                                else if (arr.PgList[j].PgOptLst[k].PgOpt == 0)
                                {
                                    msg.push(arr);
                                }
                            }
                        }    
                    }
                    break;
                    
                case 1: //category
                    for (var j = arr.Categories.length-1; j > - 1; j--)
                    {
                        //default category message
                        if (arr.Categories[j] != null && arr.Categories[j].toLowerCase() == "")
                        {
                            msg.push(arr);
                        }
                        else if (arr.Categories[j] != null && arr.Categories[j].toLowerCase() == type.toLowerCase())
                        {
                            msg.push(arr);
                        }
                    }
                    break;
                    
                case 2: //brand
                    for (var j = arr.Brands.length-1; j > - 1; j--)
                    {
                        //default brand message
                        if (arr.Brands[j] != null && arr.Brands[j].toLowerCase() == "")
                        {
                            msg.push(arr);
                        }
                        else if (arr.Brands[j] != null && arr.Brands[j].toLowerCase() == type.toLowerCase())
                        {
                            msg.push(arr);
                        }
                    }
                    break;
            }
         }
    }
    catch(ex) {}
    
    return msg;
}


//----------------- loop to find a message ----
function SearchLoginMessageList(pageId, typeid, pageIndex, type)
{
    var msg = new Array();
    
    try
    {
          //default 2 = Not Logged In
          var currntLoginStatus = 2;
          if (typeof(ci_regObj) != "undefined" && ci_regObj.isLoggedIn > 0)
                //1= Logged In
                currntLoginStatus = 1;  
          
          //search message
          //loop messsages to find a message
          for (var i=0; i < ci_FeaturedMessages.MessageList.length; i++)
          {
            var arr = ci_FeaturedMessages.MessageList[i];
            
            switch (typeid)
            {
               case 0: //page
                    for (var j = arr.PgList.length-1; j > -1; j--)
                    {
                        //check login status
                        if (arr.PgList[j].LgnState == currentLoginStatus)
                        {
                            //msg the page rquesting for the message
                            if (arr.PgList[j].PgID.toLowerCase() == pageId.toLowerCase())
                            {
                               //default page message
                               for (var k = arr.PgList[j].PgOptLst.length-1; k > -1; k--)
                               { 
                                    //exact page match
                                    if (arr.PgList[j].PgOptLst[k].PgOpt == 1 && arr.PgList[j].PgOptLst[k].RngLwr == pageIndex && arr.PgList[j].PgOptLst[k].RngUpr == pageIndex)
                                    {
                                        msg.push(arr);
                                    }
                                    //range page match
                                    else if (arr.PgList[j].PgOptLst[k].PgOpt == 2 &&  arr.PgList[j].PgOptLst[k].RngLwr <= pageIndex && arr.PgList[j].PgOptLst[k].RngUpr >= pageIndex)
                                    {
                                        msg.push(arr);
                                    }
                                    //default page match
                                    else if (arr.PgList[j].PgOptLst[k].PgOpt == 0)
                                    {
                                        msg.push(arr);
                                    }
                                }
                            } 
                        }   
                    }
                    break;
                    
                case 1: //category
                    for (var j = arr.Categories.length-1; j > - 1; j--)
                    {
                        //default category message
                        if (arr.Categories[j] != null && arr.Categories[j].toLowerCase() == "")
                        {
                            msg.push(arr);
                        }
                        else if (arr.Categories[j] != null && arr.Categories[j].toLowerCase() == type.toLowerCase())
                        {
                            msg.push(arr);
                        }
                    }
                    break;
                    
                case 2: //brand
                    for (var j = arr.Brands.length-1; j > - 1; j--)
                    {
                        //default brand message
                        if (arr.Brands[j] != null && arr.Brands[j].toLowerCase() == "")
                        {
                           msg.push(arr);
                        }
                        else if (arr.Brands[j] != null && arr.Brands[j].toLowerCase() == type.toLowerCase())
                        {
                           msg.push(arr);
                        }
                    }
                    break;
            }
         }
    }
    catch(ex) {}
    
    return msg;
}

//--------------------------------------------------------------------------------------------------
//SendMySavingsList web service call
//

function SendMySavingsListEmail(nid, pid, cardNumber, ref)
{
       //var userLookUp =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
       
       //if(userLookUp == "0" || userLookUp != UserID)
         //   return;	  
         
        var stAddr1;
        var stAddr2;
        var city;
        var state;
        var zip;
        
        var storeAddress = '';
        
        if( typeof(ci_storeBranch) != 'undefined' && ci_storeBranch != null )
        {
            for( var i=0; i<ci_storeBranch.length; i++ )
            {
                stAddr1 = ci_storeBranch[i].stAddr1;
                stAddr2 = ci_storeBranch[i].stAddr2;
                city = ci_storeBranch[i].city;
                state = ci_storeBranch[i].state;
                zip = ci_storeBranch[i].zip;
            }
        
        
            storeAddress = stAddr1+', ';
            if( stAddr2 != '' )
                storeAddress += stAddr2+', ';
            storeAddress += city+', '+state+' '+zip;
        }
 
        if (startsWith(storeAddress,'undefined')) storeAddress = '';
         
       var branchid = (typeof(ci_regObj) != "undefined" ?  ci_regObj.branchid : "0");
       var soapBody = '<SendMySavingsList xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ nid +'</NID>'        
            + '<PID>'+ pid +'</PID>'
            + '<LoyaltyCardNumber>'+ cardNumber +'</LoyaltyCardNumber>'
            //+ '<EID>' + eid + '</EID>'
            + '<ReferrerUrl>' + ref + '</ReferrerUrl>'
            + '<BranchID>' + branchid + '</BranchID>'
            + '<BranchAddress>' + storeAddress + '</BranchAddress>'
            + '</SendMySavingsList>';

      sendSoapPostRequest( 'tellafriendservice.asmx', ci_CLIPHost, 'http:/www.coupons.com/CouponWeb/SendMySavingsList', soapBody, processSavingsList);    
}

function startsWith(mystr, str)
{return (mystr.match("^"+str)==str)}

var SavingsListStatus = "";

function processSavingsList()
{

    if(_soapRequest.readyState==4)
    {
        var resText = _soapRequest.responseText;

        //strip off the soap headers
        var strOutput = KeepOnlyElement(resText, 'SendMySavingsListResponse');

        var status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/CouponWeb/"');
               
        SavingsListStatus = status;
    }
}

//
//-------------------------------------------------------
// 2/20/2010 KWu: Validation call for ShopRite with CardNumber and Zipcode
//
function ValidateCardNumberZipcodeEmail(cardnumber, zipcode, email, pid)
{
    try
    {
        var vcaz = new AjaxObject('MS2RegistrationBridge.asmx', '');
        
        //overwrite callback function after response received
        vcaz.callback = function () { ReturnValidateCardNumberAndZipcode(vcaz.getresponse());}
        var soapBody = "<ValidateCardNumberZipcodeEmail xmlns=\"http:/www.coupons.com/CouponWeb/\"><cardnumber>"+ cardnumber +"</cardnumber><zipcode>"+ zipcode + "</zipcode><email>" + email + "</email><pid>" + pid + "</pid></ValidateCardNumberZipcodeEmail>";
        vcaz.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/ValidateCardNumberZipcodeEmail', soapBody);
    }
    catch (ex) {}
}

/// bCode
function updatephone(MobilePhoneNumber)
{
   var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
   var nid = GetQueryStringValue('nid');
   var ajaxcall = new AjaxObject('MS2RegistrationBridge.asmx', 'UpdateMobilePhoneNumberResult');
   var s ='<UpdateMobilePhoneNumber xmlns="http:/www.coupons.com/CouponWeb/">'
           + '<MobilePhoneNumber>'+MobilePhoneNumber+'</MobilePhoneNumber>'
           + '<UserId>'+userID+'</UserId>'
           + '<NID>'+nid+'</NID>'
           + '</UpdateMobilePhoneNumber>' 
  ajaxcall.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/UpdateMobilePhoneNumber', s);      
}

function GetSMSbcodeInfo(MobilePhoneNumber, CouponID)
{
      var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
      var nid = GetQueryStringValue('nid');
      var pid = GetQueryStringValue('pid');
      var DeviceID = 0;
      var ajaxcall = new AjaxObject('MS2Bridge.asmx', 'sendSMSTobCodeResult');
      var soapBodybCode ='<sendSMSTobCode xmlns="http:/www.coupons.com/CouponWeb/">'
                        + '<userid>'+userID+'</userid>'
                        + '<deviceid>'+DeviceID+'</deviceid>'
                        + '<mobilephonenumber>'+MobilePhoneNumber+'</mobilephonenumber>'
                        + '<pid>'+pid+'</pid>'
                        + '<nid>'+nid+'</nid>'
                        + '<CouponID>'+CouponID+'</CouponID>'
                        +'</sendSMSTobCode>'        
        ajaxcall.postdata('MS2Bridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/sendSMSTobCode', soapBodybCode);       
}

function GetMobilePhoneNumber()
{
    var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");
    var nid = GetQueryStringValue('nid');
    var pid = GetQueryStringValue('pid');  
    var  res;
      var ajaxcall = new AjaxObject('MS2RegistrationBridge.asmx', 'GetMobilePhoneNumberResult');
       ajaxcall.callback = function () { 
                    var result = ajaxcall.getresponse(); 
                    ci_mobphone = result;
                    }
        var sbody ='<GetMobilePhoneNumber xmlns="http:/www.coupons.com/CouponWeb/">'
                 + '<UserId>'+userID+'</UserId>'
                 + '<nNid>'+nid+'</nNid>'
                 + '<nPid>'+pid+'</nPid>'
                 + '</GetMobilePhoneNumber>'
                 //alert(sbody);
        ajaxcall.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/GetMobilePhoneNumber', sbody);         
          
}

function getresult(result)
{
    return result;
}
// ---- functions to add club prices numbers.

// Gayathri 4/15/2010

function AddClubPriceToCard(cardnumber, itemID)

{

    try

    {

        var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");

        var nid = GetQueryStringValue('nid');

        var pid = GetQueryStringValue('pid'); 

        var acp = new AjaxObject('MS2Bridge.asmx', 'AddClubPriceToCard');        

        

        //AddClubPriceToCard(int PID, int NID, string CardNumber, int UserID, int ItemID)

        //overwrite callback function after response received

        acp.callback = function () { ci_OfferThemeObj.CheckAddClubPriceResponse(acp.getresponse());}

        var soapbody ='<AddClubPriceToCard xmlns="http:/www.coupons.com/CouponWeb/">'

                 + '<UserID>'+userID+'</UserID>'

                 + '<NID>'+nid+'</NID>'

                 + '<PID>'+pid+'</PID>'

                 + '<CardNumber>'+cardnumber+'</CardNumber>'

                 + '<ItemID>'+itemID+'</ItemID>'

                 + '</AddClubPriceToCard>'

        // alert(soapbody)

        

        acp.postdata('MS2Bridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/AddClubPriceToCard', soapbody);

    }

    catch (ex) {}

}

 

// ---- functions to remove club prices numbers.

// Gayathri 4/15/2010

function RemoveClubPriceToCard(cardnumber, itemID)

{

    try

    {

        var userID =  (typeof(ci_regObj) != "undefined" ?  ci_regObj.isLoggedIn : "0");

        var nid = GetQueryStringValue('nid');

        var pid = GetQueryStringValue('pid'); 
        var acp = new AjaxObject('MS2Bridge.asmx', 'RemoveClubPriceFromCard');        

        //AddClubPriceToCard(int PID, int NID, string CardNumber, int UserID, int ItemID)

        //overwrite callback function after response received

        acp.callback = function () { ci_OfferThemeObj.CheckRemoveClubPriceResponse(acp.getresponse());}
        var soapbody ='<RemoveClubPriceFromCard xmlns="http:/www.coupons.com/CouponWeb/">'
                 + '<UserID>'+userID+'</UserID>'

                 + '<NID>'+nid+'</NID>'

                 + '<PID>'+pid+'</PID>'

                 + '<CardNumber>'+cardnumber+'</CardNumber>'

                 + '<ItemID>'+itemID+'</ItemID>'
                 + '</RemoveClubPriceFromCard>'

        // alert(soapbody)


        acp.postdata('MS2Bridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/RemoveClubPriceFromCard', soapbody);

    }

    catch (ex) {}
}
// ---- functions to support single signon for MWG.
// 5/10/2010
function LoginMWGUserData()
{
    try
    {
  	    var timestamp = new Date();         // Get a new date (this will make the url unique)  
	    var mwgscript = "<script type='text/javascript' src='https://secure3.mywebgrocer.com/D/CustomerDataService.aspx?UC=DC97B&VendorKey=dc99475b-4973-4cbe-8977-d34b94fa208d&timestamp=" + (timestamp*1) + "'></script>"
	    document.write(mwgscript);
    }
    catch (ex) {}
}
function RedirectMWGUser()
{
    try
    {
        var timestamp = new Date();         // Get a new date (this will make the url unique)         
        var url = "https://secure2.mywebgrocer.com/uma/RegisterSignIn.aspx?mgl=9c1db9a0-8103-4a9f-8c73-a52b53e85a78&uc=dc97b&timestamp=" + (timestamp*1);  

        //redirect
        window.location = url;
    }
    catch (ex){}
}
// Define what to do when the customer data is received	
function OnCustomerDataReceived() 
{
    try
    {
        var idOK = CustomerData.customerIdentified;
        if ( idOK ) 
        {
        
            var customerEmail = CustomerData.customerEmail;
            var TYC = CustomerData.frequentShopperNumber;

            //register user
            //validate email address before a save    
            if (ValidateEmail(customerEmail))
                RegisterSSOWebUserWithZipcodeOptIn(customerEmail, TYC, storeID, 0, 0, 0, 0, '99999');
            else
                alert("Invalid email format: " + customerEmail);
        } 
    }
    catch(ex){}
}
// ***************************************************
//
// 3/22/2010 KWu: register new user with zipcode input
//
// ***************************************************
function RegisterSSOWebUserWithZipcodeOptIn(email, cardNumber, store, Optin1, Optin2, Optin3, Optin4, Zipcode)
{     
    try
    {
        var remember = 0;
        
        if (GetQueryStringValue('pid').length == 0 || GetQueryStringValue('nid').length == 0) 
            return;
            
        var NID = GetQueryStringValue('nid');
        var PID = GetQueryStringValue('pid'); 

        //register a user
        makeZeroOrOne(Optin1);
        makeZeroOrOne(Optin2);
        makeZeroOrOne(Optin3);
        makeZeroOrOne(Optin4);
       
        var rsu = new AjaxObject('MS2RegistrationBridge.asmx', 'RegisterSSOUserResult');
        
        //overwrite callback function after response received
        rsu.callback = function () { ReturnRegisterSSOWebUserWithZipcodeOptIn(rsu.getresponse(), email, cardNumber, store);}
        var soapBody = '<RegisterSSOUser xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<NID>'+ NID +'</NID>'        
            + '<PID>'+ PID +'</PID>'
            + '<email>'+ email +'</email>'
            + '<remember>'+ remember +'</remember>'        
            + '<storeID>'+ store +'</storeID>'
            + '<cardNumber>'+ cardNumber +'</cardNumber>'
            + '<Optin1>' + Optin1 + '</Optin1>'
            + '<Optin2>' + Optin2 + '</Optin2>'
            + '<Optin3>' + Optin3 + '</Optin3>'
            + '<Optin4>' + Optin4 + '</Optin4>'
            + '<Zipcode>' + Zipcode + '</Zipcode>'
            + '</RegisterSSOUser>';
        
        rsu.postdata('MS2RegistrationBridge.asmx',ci_CLIPHost,'http:/www.coupons.com/CouponWeb/RegisterSSOUser', soapBody);
    }
    catch (ex) {}
    
    
}
// 3.22.2010: assign value to the ci_register object ----------------------------------------------------
function ReturnRegisterSSOWebUserWithZipcodeOptIn(strOutput, email, card, store)
{
    try
    {
        ci_InvalidCardNum = "";  

        ci_RegisterUser = new RegisterUser();
        ci_RegisterUser.Status = ParseElement(strOutput, 'Status', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.Msg = ParseElement(strOutput, 'Message', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_RegisterUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
        ci_LoggedInUser = new LoggedInUser();
         
        if(ci_RegisterUser.Status == 'OK')
        {
            // log user in
            ci_LoggedInUser.UserID = ParseElement(strOutput, 'ReturnValue', 'xmlns="http:/www.coupons.com/OfferServices/"');
           ci_LoggedInUser.IsLoggedIn = 1;
           
           if (ci_RegisterUser.Msg.length > 0)
             ci_InvalidCardNum = ci_RegisterUser.Msg;
           else
             ci_InvalidCardNum = "1";  
             
           if (typeof(ci_regObj) != "undefined")
           {
                ci_regObj.isLoggedIn = ci_RegisterUser.UserID;
                ci_regObj.email = email;
		        ci_regObj.ccnum = card;
		        //manually adding store to user card
 		        var usrCardStore = new Store(store, "", card, 1,0);
                ci_userCardStoreList.push(usrCardStore);
		        ci_OfferThemeObj.cardNum = card;
           }
                
           GetUserLCRestrictions();
        }
        else
        {
           ci_InvalidCardNum = "";
        }
    }
    catch (ex) {}
}
//----------------------------------------------------


function ValidateEmail(email)
{  
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    
    return emailPattern.test(email);  
} 

