var ci_CMEntityString = ""; // global entity string
var ci_CurrPage= 1;
// --------------------------------------------------------
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;
}

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 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(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);
}

//----------------------------------------------------

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");
       if(userID == "0")
            return;	  
        var soapBody = '<GetCouponsFromCards xmlns="http:/www.coupons.com/CouponWeb/">'            
            + '<UserID>'+ userID +'</UserID>'
            + '<NID>'+ GetQueryStringValue('nid') +'</NID>' 
            + '<PID>'+ GetQueryStringValue('pid') +'</PID>'  
            + '</GetCouponsFromCards>';
            
            //alert(soapBody);

        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);  
        }
                

        
    }
}
//----------------------------------------------------

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);
}
