﻿// 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');
        SetShoppingBagCount('ShoppingBagCount');

        ShowCardLinks('YourCreditCard','PreApprovedOffer','SavingsId');
    }
    else
    {
        ActivatePreviouslyViewProductsLink('PreviouslyViewProducts', 'vendor');
        InitUserLogin('SignIn','NotUser', 'vendor');
        SetShoppingBagCount_Vendor('ShoppingBagCount', 'vendor');
        ShowCardLinks('YourCreditCard','PreApprovedOffer','SavingsId', 'vendor');
    }
     ActivateWishList('MyWishList');
 }

function ShowCardLinks(YourCreditCardId,PreApprovedOfferId,SavingsId,vendorName)
{
    var hasPreApprovedOffer = false;
    var hasPreApprovedOfferDeclined = false;
    var hasAdsCards = false;
    var cardId;
    
    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;        
    }
    
    cookieValue = GetDecodedSubCookieValue(cookieName,subCookiePrefix +'.CreditBrand');
  
    if(cookieValue != null) 
    {
        cardId = cookieValue.toLowerCase();      
    }

    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';
            
               if(cardId == "j")
               {
                htmlElement = document.getElementById('imgPreApproved');
                    if(htmlElement != null)
                     {
                       htmlElement.src = '//secureimages.redcatsusa.com/images/site_images/jessicalondon/jl_header_pre-approved_icon.gif';
                     }
               }
        }
    }
    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, 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:#990000;">Welcome Back ' + FirstName + '!</span>';    
            document.getElementById(NotSignedInId).innerHTML = 'Not <span> '+FirstName+'?</span>'; 
            document.getElementById(SignInId).style.cursor = 'text';  
    }
}

 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 0px"
                 } 
             } 
         } 
        //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 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';
        }
    }
}

//This function handles search functionality.
function SearchProducts(SearchInputId)
{
if(document.getElementById(SearchInputId).value!='ex: blue blouse' && document.getElementById(SearchInputId).value!='Product Search') {
  var searchVal = encodeURIComponent( document.getElementById(SearchInputId).value );
  location.href = BaseURL + "Search/SearchResults.aspx?SearchHeader=" + searchVal;
  }
  }

//This function handles quickorder functionality.

function SearchCatalogQuickOrder(SearchCatalogInputId)
{

   if((document.getElementById(SearchCatalogInputId).value!='ex: 1234-12345-123') && (document.getElementById(SearchCatalogInputId).value!='Order from Catalog')) {
  
           var searchVal = encodeURIComponent( document.getElementById(SearchCatalogInputId).value );
  
               location.href = BaseURL + "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   = BaseURL + "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   = BaseURL + "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');
    }
}


function doSearch() {
  var searchVal = encodeURIComponent( document.getElementById('search_input').value );
  window.location = BaseURL + "Search/SearchResults.aspx?SearchHeader="+searchVal;
}

 function doSearchtoo() {
  var searchVal = encodeURIComponent( document.getElementById('searchcatalog_input').value );
  window.location = BaseURL + "Catalog/CatalogQuickOrder.aspx?Quick="+searchVal;
}

  function doSearchAsWell(myfield,e)
{
   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('search_input').value );
           window.location = BaseURL + "Search/SearchResults.aspx?SearchHeader="+searchVal;
           return false;
        }
                 else
                   return true;
    }
  
  function doSearchNum(myfield,e)
{
   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('searchcatalog_input').value );
           window.location = BaseURL +"Catalog/CatalogQuickOrder.aspx?Quick="+searchVal;
           return false;
        }
                 else
                   return true;
    }    
   
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;
    }
}

/** 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);
}
