﻿// JScript File
/*****************************************************************************
This file contains the functions needed to initialize the headers in the site
when it is loaded through Chameleon. It was developed in 2009FB2.

Main function in this file: InitHeader()

*****************************************************************************/

//Main function in the file
function InitHeader()
{
   HighlightCurrentTab();
    
    if(typeof(_runningFromMicrosite) == "undefined")
    {
        ActivatePreviouslyViewProductsLink('PreviouslyViewProducts');
        InitUserLogin('SignIn','NotUser', 'FrVisit');
        SetShoppingBagCount('ShoppingBagCount');
        ShowCardLinks('YourCreditCard','PreApprovedOffer','SavingsId');
        ShowShoppersClubLogo('logo_img','logo_link');
    }
    else
    {
        ActivatePreviouslyViewProductsLink('PreviouslyViewProducts', 'vendor');
        InitUserLogin('SignIn','NotUser', 'FrVisit', 'vendor');
        SetShoppingBagCount_Vendor('ShoppingBagCount', 'vendor');
        ShowCardLinks('YourCreditCard','PreApprovedOffer','SavingsId', 'vendor');
        ShowShoppersClubLogo('logo_img','logo_link', 'vendor');
    }
    
    ActivateWishList('MyWishList');
    
    // Initialize and show promotion slider
    offers_load();
    autoScroll('newsslider','newssection',5,true);
}

function ShowShoppersClubLogo(ClubLogo, LogoLink, vendorName)
{
   if(GetLoginStatus(vendorName))
    {
         var MembershipStatus =
         {
            NoMember:0,
            Member:1,
            Joined:2,
            Expired:3,
            NotEligible:4,
            MemberJoined:5,
            ExpiredJoined:6,
            Guestmember:7
         };
        var cookieValue;
        var cookieName = GetUserCookieName(vendorName);
        var subCookiePrefix = GetSubCookiePrefix(vendorName);
    
        cookieValue = GetDecodedSubCookieValue(cookieName, subCookiePrefix + '.ShoppersClubMember');
        
        if((cookieValue != null) && cookieValue == MembershipStatus.Member.toString())
        {
           var logo_Img = document.getElementById(ClubLogo);
           if(logo_Img != null)
           {
              logo_Img.src ='//secureimages.redcatsusa.com/images/site_images/mastersite/osp_header_logo_shoppers_club.gif';
           }
        }
    }
}

function ShowCardLinks(YourCreditCardId,PreApprovedOfferId,SavingsId,vendorName)
{
    var hasPreApprovedOffer = false;
    var hasPreApprovedOfferDeclined = false;
    var hasAdsCards = false;
    
    var cookieValue;
    var htmlElement;
    
    var cookieName = GetUserCookieName(vendorName);
    var subCookiePrefix = GetSubCookiePrefix(vendorName);
    
    cookieValue = GetDecodedSubCookieValue(cookieName, subCookiePrefix + '.HasPreApprovedOffer');
    
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasPreApprovedOffer = true;        
    }

    cookieValue = GetDecodedSubCookieValue(cookieName,subCookiePrefix + '.PreApprovedOfferDeclined');
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasPreApprovedOfferDeclined = true;        
    }
    
        cookieValue = GetDecodedSubCookieValue(cookieName,subCookiePrefix + '.HasAdsCard');
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasAdsCards = true;        
    }
    
    cookieValue = GetDecodedSubCookieValue(cookieName,subCookiePrefix + '.CreditInfoString');
    if((cookieValue != null) && (cookieValue.indexOf('A') == 0))
    {
        hasAdsCards = true;        
    }
    
    if((hasPreApprovedOffer == true) && (hasPreApprovedOfferDeclined == false))
    {
        htmlElement = document.getElementById('SavingsId');
        if(htmlElement != null)
        {
            htmlElement.style.display='none';
        }
        
        htmlElement = document.getElementById('PreApprovedOffer');
        if(htmlElement != null)
        {
            htmlElement.style.display='block';
        }
    }
    else if(hasAdsCards == true)
    {
        htmlElement = document.getElementById('SavingsId');
        if(htmlElement != null)
        {
            htmlElement.style.display='none';
        }
        
        htmlElement = document.getElementById('YourCreditCard');
        if(htmlElement != null)
        {
            htmlElement.style.display='block';
        }
    }
    
    return true;
}

function RedirectToPreApprovedOffer()
{
    window.location = BaseURL + 'Account/Acct_PreQualifiedOffer_plcc.aspx';
}

function InitUserLogin(SignInId, NotSignedInId, FrVisitId, vendorName)
{
    var cookieName = GetUserCookieName(vendorName);
    var subCookiePrefix = GetSubCookiePrefix(vendorName);

    if(GetLoginStatus(vendorName))
    {
            var FirstName = toTitleCase(GetDecodedSubCookieValue(cookieName, subCookiePrefix + '.FirstName'));
            document.getElementById(SignInId).innerHTML = ' <span style="color:#919191;">&nbsp;back, ' + FirstName + '!&nbsp;&nbsp;</span>';    
            document.getElementById(NotSignedInId).innerHTML = 'Not ' + FirstName + '?'; 
            document.getElementById(SignInId).style.cursor = 'text';
            if(typeof(FrVisitId) != "undefined" && FrVisitId != null)
            {
                document.getElementById(FrVisitId).style.display = 'none';
            }
            
    }
}

function HighlightCurrentTab()
{
    if(GetTopLevelDepartment() > 0 )
    {
        var eleId = 'dept_' + GetTopLevelDepartment();
        if(typeof(eleId) != "undefined" && eleId != null)
        {
            var liId = document.getElementById(eleId);
            if(typeof(liId) != "undefined" && liId != null)
            {
             var aId = liId.getElementsByTagName('a');
                if(typeof(aId) != "undefined" && aId != null)
                {
                    aId[0].style.backgroundPosition = "0 0";
                }
            }
        }
        //document.getElementById(eleId).childNodes[1].style.backgroundImage = "url('//secureimages.redcatsusa.com/images/site_images/womanwithin/dept_" + GetSubCookieValue('Department','TopLevelDepartment') + "_on.jpg')"
    }
}

function SetShoppingBagCount(ShoppingBagId)
{
    if(document.getElementById(ShoppingBagId)!=null)
    {
        if(GetSubCookieValue('Basket','Indy.Basket.BasketCount') !=null )
        {
            document.getElementById(ShoppingBagId).innerHTML = '(' + GetSubCookieValue('Basket','Indy.Basket.BasketCount') + ')';
        }
        else
        {
            document.getElementById(ShoppingBagId).innerHTML = '(0)';
        }
    }
}

function SetShoppingBagCount_Vendor(ShoppingBagId, vendorName)
{
    if(typeof(vendorName) != "undefined")
    {
        if(document.getElementById(ShoppingBagId)!=null)
        {
            var basketCount = GetCookie(vendorName + '.Basket.BasketCount');
            if(basketCount !=null )
            {
                document.getElementById(ShoppingBagId).innerHTML = '(' + basketCount + ')';
            }
            else
            {
                document.getElementById(ShoppingBagId).innerHTML = '(0)';
            }
        }
    }
}


function LogoutUser()
{
    setSubCookieAndCookie('User','Indy.FirstName','');
    setSubCookieAndCookie('User','Indy.MasterId','');
}

//This function returns a bool to indicate the login status.
function GetLoginStatus(vendorName)
{
    var cookieName = GetUserCookieName(vendorName);
    var subCookiePrefix = GetSubCookiePrefix(vendorName);

    if(
        (GetSubCookieValue(cookieName,subCookiePrefix + '.MasterId') != null) && 
        (GetSubCookieValue(cookieName,subCookiePrefix + '.FirstName') != null) &&
        (GetSubCookieValue(cookieName,subCookiePrefix + '.MasterId') != '') && 
        (GetSubCookieValue(cookieName,subCookiePrefix + '.FirstName') != '')
      )
    {
        return true;        
    }
    else
    {
        return false;
    }
}

//This function handles search functionality.

  function SearchProducts(SearchInputId)
    {
        if(document.getElementById(SearchInputId).value!='Enter key word or number')
        {
            var searchVal = encodeURIComponent( document.getElementById(SearchInputId).value );
            location.href = BaseURL + "Search/SearchResults.aspx?SearchHeader="+searchVal;
        }
    } 


function SearchOnEnter(myfield,e,SearchInputId)
    {
        var keycode;
          if (window.event) keycode = window.event.keyCode;
             else if (e) keycode = e.which;
               else return true;

          if (keycode == 13)  {
             var searchVal = encodeURIComponent( document.getElementById(SearchInputId).value );
                  if (parseInt(searchVal) > 0) {
                       location.href   = "/Catalog/CatalogQuickOrder.aspx?Quick="+searchVal;
       } else {
              location.href = BaseURL + "Search/SearchResults.aspx?SearchHeader="+searchVal;
     }
                return false;
        }
                 else
                   return true;
}

/*************************** END ***************************/

//This function shows the previously view products 
//link if the user has visited any product.
function ActivatePreviouslyViewProductsLink(PVPId, vendorName)
{
    var prevProducts;
    if(typeof(vendorName) == "undefined")
    {
        prevProducts = GetCookie('LastViewedProducts');
    }
    else
    {
        prevProducts = GetCookie(vendorName + '.LastViewedProducts');
    }
    
    var RegEX = /(([0-9]+)#([0-9]+)\*([0-9]+)){1,}/;
    
    if(RegEX.test(prevProducts))
    {
        if(document.getElementById(PVPId)!=null)
        {
            document.getElementById(PVPId).style.display='';
        }
    }
    else
    {
        if(document.getElementById(PVPId)!=null)
        {
            document.getElementById(PVPId).style.display='none';
        }
    }
}

//This function shows wishlist link if the user has added any
//items to the wishlist.
function ActivateWishList(WishListId)
{
    if(IsUserHavingWishList())
    {
        if(document.getElementById(WishListId)!=null)
        {
            document.getElementById(WishListId).style.display = '';
        }
    }
    else
    {
        if(document.getElementById(WishListId)!=null)
        {
            document.getElementById(WishListId).style.display = 'none';
        }
    }
}

 

function toTitleCase(strToConvert)
{

   var mx_replace = new Array('to','it','on','the','a','and','or','nor','of','in');

   var mx_ignore = new RegExp('[-\\s]');

   var mx_newS = strToConvert;

   var mx_prevC = '';

   var mx_thisC = null;

   var mx_match = null;

   var mx_iR = '';



   mx_newS = mx_newS.replace(/\s+|\r|\n/g,' ').toLowerCase();

   mx_newS = mx_newS.replace(/^\s*/,'');

   mx_newS = mx_newS.replace(/\s*$/,'');



   for(var i=1;i<mx_newS.length+1;i++) {

   mx_iR = new RegExp('^'+ (i!=1?'(.{'+ eval(i-1) +'})':'') +'(.)'+ (i!=mx_newS.length?'(.{'+ eval(mx_newS.length - i) +'})':'') +'$');

   mx_match = mx_newS.match(mx_iR);

   mx_thisC = ( (mx_match.length==3 && i==1) ? mx_match[1] : mx_match[2] );



   if(mx_prevC.match(mx_ignore) != null || mx_prevC=='') {

   mx_newS = ( (mx_newS.length == 1) ? mx_newS.toUpperCase() :

   (mx_match.length == 3 && i==1) ? mx_newS.replace(mx_iR, mx_match[1].toUpperCase()+mx_match[2]) :

   (mx_match.length == 3 && i==mx_newS.length) ? mx_newS.replace(mx_iR, mx_match[1]+mx_match[2].toUpperCase()) :

   mx_newS.replace(mx_iR, mx_match[1]+mx_match[2].toUpperCase()+mx_match[3]) );

   }

   mx_prevC = (mx_thisC ? mx_thisC.toLowerCase() : '');

   }

   for (var n=0;n<mx_replace.length;n++) {

   mx_iR = new RegExp(' '+ mx_replace[n] +' ','gi');

   mx_newS = mx_newS.replace(mx_iR,' '+ mx_replace[n] +' ')

   }

       return(mx_newS);
}


/********************************The following functions are provided for the brand to support making changes to the header ***************/
//This function returns the First Name of the logged in user.
function GetFirstName()
{
    if(GetLoginStatus())
    {
        var FirstName = toTitleCase(GetDecodedSubCookieValue('User','Indy.FirstName'));
        return FirstName;
    }
    else
    {
        return '';
    }
}

//This function returns a bool to indicate the login status.
function IsUserLoggedIn()
{
    if(
        (GetSubCookieValue('User','Indy.MasterId') != null) && 
        (GetSubCookieValue('User','Indy.FirstName') != null) &&
        (GetSubCookieValue('User','Indy.MasterId') != '') && 
        (GetSubCookieValue('User','Indy.FirstName') != '')
      )
    {
        return true;        
    }
    else
    {
        return false;
    }
}

//This function indicates if the user has by brand credit cards.
function IsUserHavingWishList()
{
    if(GetDecodedSubCookieValue('User','Indy.WishListCount') != null)
    {
        if(GetDecodedSubCookieValue('User','Indy.WishListCount') == 'true')
        {
            return true;
        }
    }
    return false;
}

function GetTopLevelDepartment()
{
    if((document.getElementById('hdnTopDeptId') != null) &&
       (document.getElementById('hdnTopDeptId').value != '-2147483648'))
    {
        return document.getElementById('hdnTopDeptId').value;
    }
    else
    {
        return -1;
    }
}

function GetShoppingBagCount()
{
    if(GetSubCookieValue('Basket','Indy.Basket.BasketCount') !=null )
    {
        return GetSubCookieValue('Basket','Indy.Basket.BasketCount');
    }
}

function GetUserCookieName(vendorName)
{
    if(typeof(vendorName) == "undefined")
    {
        return "User";
    }
    else
    {
        return vendorName + ".User";
    }
}

function GetSubCookiePrefix(vendorName)
{
    if(typeof(vendorName) == "undefined")
    {
        return "Indy";
    }
    else
    {
        return vendorName;
    }
}


/*** Fade div***/

var TimeToFade = 2000.0;

function fade(eid)
{
  var element = document.getElementById(eid);
  if(element == null)
    return;
    
   
  if(element.FadeState == null)
  {
    if(element.style.opacity == null || element.style.opacity == '' 
       || element.style.opacity == '1')
      element.FadeState = 2;
    else
      element.FadeState = -2;
  }
    
  if(element.FadeState == 1 || element.FadeState == -1)
  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade;
    setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
  }  
}

function animateFade(lastTick, eid)
{  
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;
  
  var element = document.getElementById(eid);
 
  if(element.FadeTimeLeft <= elapsedTicks)
  {
    element.style.opacity = element.FadeState == 1 ? '1' : '0';
    element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  element.style.opacity = newOpVal;
  element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
  
  setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}


/** delete cookie **/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/** QV layer **/

function OpenQuickView()
    {document.getElementById('quickinfooverlay').style.display = 'block';
	document.getElementById('dhtmlwindowholder').style.display = 'block';}

function OpenPopup(sURL, sName, sFeatures, bReplace)
{
    var url = "about:blank";
    if(typeof(sURL) != 'undefined' && sURL != null)
    {
        url = BaseURL + sURL;
    }
    
    return window.open(url, sName, sFeatures, bReplace);
}

// Function to load the promotions for promotion slider
function offers_load()
{
    // Move the offers div inside promoLayer
    var promoLayerDiv = document.getElementById("promoLayer");
    if(promoLayerDiv && promoLayerHtml)
    {
        promoLayerDiv.innerHTML = promoLayerHtml;
    }
    else
    {
        // no point to continue forward if either
        // promo layer or the HTML is not there
        return;
    }

    // Display appropriate content based on login status
    var offersTable = document.getElementById("tblOffers");
    var trUser = document.getElementById("trLoggedIn");
    var trGuest = document.getElementById("trNotLoggedIn");
    var newsSliderDiv = document.getElementById("newsslider");
    var newSliderSectionDiv = document.getElementById("newssection-1");
    if(!GetLoginStatus())
    {
        // Show appropriate <tr>
        trGuest.style.display = "";
        offersTable.deleteRow(0); // Delete the user row
    }
    else
    {
        // Show appropriate <tr>
        trUser.style.display = "block";
        offersTable.deleteRow(1); // Delete the guest row
        
        // Decode coupons
        var subCookiePrefix = GetSubCookiePrefix();
        var decodedCoupons = GetDecodedSubCookieValue("User", subCookiePrefix + ".CouponInfo");
        var coupons = decodedCoupons.split("¨");
        
        // Iterate through the coupons
        var sectionIndex = 2;
        for(var couponIndex = 0; couponIndex < coupons.length; couponIndex++)
        {
            // Get coupon type and title
            var couponFields = coupons[couponIndex].split("§");
            var couponType = couponFields[0];
            var couponTitle = couponFields[1];
            
            // Check if it is a promo-coupon, only then display it in slider
            if(couponType != "0")
            {
                continue;
            }
            
            // Prepare <a> tag for the coupon
            var couponHyperLink = '<a style="font-weight: normal; width: 100px;" href="/Account/Acct_MyPromotions.aspx"> ' +
                couponTitle + ' </a>';
            
            // Wrap it in a div tag
            var subElementSlider = document.createElement("div");
            subElementSlider.id = "newssection-" + sectionIndex;
            subElementSlider.className = "newssection";
            subElementSlider.innerHTML = couponHyperLink;
            
            // Append it to the parent newsSliderDiv
            newsSliderDiv.insertBefore(subElementSlider, newSliderSectionDiv.nextSibling);
            
            // Increment section index
            sectionIndex = sectionIndex + 1;
        }
        
        // update the Id of the last section so it appears in slider
        var sectionX = document.getElementById("newssection-X");
        sectionX.id = "newssection-" + sectionIndex;
    }
}
