﻿
// 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()
{
    ActivatePreviouslyViewProductsLink('PreviouslyViewProducts');
    InitUserLogin('SignIn','NotUser','FrVisit');
    SetShoppingBagCount('ShoppingBagCount');
    HighlightCurrentTab();
    ShowCardLinks('YourCreditCard','PreApprovedOffer','SavingsId');
    ActivateWishList('MyWishList');
}

function ChangeCardLinkToPreApproved(BrandCardId)
{
    htmlElement = document.getElementById('BrandCardId');
    if(htmlElement != null)
    {
        htmlElement.href = "/Account/Acct_PreQualifiedOffer_common.aspx";
    }
}

function ChangeCardLinkToBrandCard(BrandCardId)
{
    htmlElement = document.getElementById('BrandCardId');
    if(htmlElement != null)
    {
        htmlElement.href = "/Account/Acct_CreditCards.aspx";
    }
}

function ShowCardLinks(YourCreditCardId,PreApprovedOfferId,SavingsId)
{
    var hasPreApprovedOffer = false;
    var hasPreApprovedOfferDeclined = false;
    var hasAdsCards = false;
    
    var cookieValue;
    var htmlElement;
    
    cookieValue = GetDecodedSubCookieValue('User','Indy.HasPreApprovedOffer');
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasPreApprovedOffer = true;        
    }

    cookieValue = GetDecodedSubCookieValue('User','Indy.PreApprovedOfferDeclined');
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasPreApprovedOfferDeclined = true;        
    }
    
    cookieValue = GetDecodedSubCookieValue('User','Indy.HasAdsCard');
    if((cookieValue != null) && (cookieValue.toLowerCase() == 'true'))
    {
        hasAdsCards = true;        
    }
    
    cookieValue = GetDecodedSubCookieValue('User','Indy.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';
        }
        
        ChangeCardLinkToPreApproved('BrandCardId')
    }
    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';
        }
        
        ChangeCardLinkToBrandCard('BrandCardId')
    }
    
    return true;
}

function RedirectToPreApprovedOffer()
{
    window.location = BaseURL + 'Account/Acct_PreQualifiedOffer_plcc.aspx';
}

function InitUserLogin(SignInId,NotSignedInId,FrVisitId)
{
    if(GetLoginStatus())
    {
            var FirstName = toTitleCase(GetDecodedSubCookieValue('User','Indy.FirstName'));
            document.getElementById(SignInId).innerHTML = ' back, ' + FirstName + '!';    
            document.getElementById(NotSignedInId).innerHTML = 'Not ' + FirstName + '?';
            document.getElementById(SignInId).style.color = '#919191';
            document.getElementById(SignInId).style.textDecoration = 'none';  
            document.getElementById(FrVisitId).style.display = 'none';
            document.getElementById(SignInId).style.paddingLeft = '3px';
             
    }
}

 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 LogoutUser()
{
    setSubCookieAndCookie('User','Indy.FirstName','');
    setSubCookieAndCookie('User','Indy.MasterId','');
}

//This function returns a bool to indicate the login status.
function GetLoginStatus()
{
    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 shows the previously view products 
//link if the user has visited any product.
function ActivatePreviouslyViewProductsLink(PVPId)
{
    var prevProducts = GetCookie('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';
        }
    }
}

//This function handles search functionality.
function SearchProducts(SearchInputId)
{
if(document.getElementById(SearchInputId).value!='ex: blue blouse') {
  var searchVal = encodeURIComponent( document.getElementById(SearchInputId).value );
  location.href = "/Search/SearchResults.aspx?SearchHeader=" + searchVal;
  }
  }

//This function handles quickorder functionality.

function SearchCatalogQuickOrder(SearchCatalogInputId)
{

   if(document.getElementById(SearchCatalogInputId).value!='ex: 1234-12345-123') {
  
           var searchVal = encodeURIComponent( document.getElementById(SearchCatalogInputId).value );
  
               location.href = "/Catalog/CatalogQuickOrder.aspx?Quick=" + 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 );
           location.href   = "/Search/SearchResults.aspx?SearchHeader="+searchVal;
           return false;
        }
                 else
                   return true;
}

function SearchCatalogOnEnter(myfield,e,SearchCatalogInputId)
{
    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(SearchCatalogInputId).value );
           location.href   = "/Catalog/CatalogQuickOrder.aspx?Quick="+searchVal;
           return false;
        }
             else
               return true;
}    

/*************************** END ***************************/ 
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');
    }
}




/*** 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);
}
