﻿var numModules;
var currentModule;
var t_modules;
var moduleDelay = 7; //seconds
var gblForTimeOut;

//webtrends
var wtHeromodule = "";
var wtTabSelected = "";
var wtSetup = false;

$(document).ready(function() {
    SetNotFoundMessage();
    SetBrowseByCategoryGATracking();
    wtSetup = $('#webtrendsEnabled').text().toLowerCase();

    $('#close404').click(function() {
        CloseSetNotFoundMessage();
    });

    $('#xs_pDiv2 img').hover(
        function() {
            if (xs_pTuck == 1) {
                setPromoBlockPosition($(this));
            }
            else if (GetCookieDictionary('apc', 'pv') > 1) {
                setPromoBlockPosition($(this));
            }
            clearTimeout(gblForTimeOut);
        },
        function() {
            if ($('#PromoContainerBlock').is(":visible")) {
                gblForTimeOut = setTimeout("fadeOutPromoBlock()", 5000);
            }
        }
    );
    $('#PromoContainerBlock').hover(
        function() {
            clearTimeout(gblForTimeOut);
        },
        function() {
            $(this).fadeOut();
        }
    );
    if (GetCookieDictionary('apc', 'pv') > 1) {
        // relative to the header bottom.      
        var headerOffset = $('#headerBottomRow').offset();
        var width = $('#pageContainer').width();
        var leftPos = headerOffset.left + width;
        leftPos = leftPos - 330; // substract width of div                         
        $('#xs_pDiv2').show();
        $('#xs_pDiv2').css('left', leftPos);
        $('#xs_pDiv2').css('top', headerOffset.top + 35);
    }
    //Hero Module

    $('.featureCircle').bind('click', function() {
        clearTimeout(t_modules);
        selectModule($(this));
        var theID = $('.featureCircle').index($(this));
        theID = theID + 1;
        trackGAEvent('SelectHeroNav' + theID, 'Home');
    });

    $('.featureBlock').bind('click', function() {
        var theModule = $(this).attr('id');
        trackGAEvent('Select' + theModule, 'Home');

        //webtrends
        if (wtSetup) {
            var theID = $('.featureBlock').index($(this));
            theID = theID + 1;

            wtHeromodule = wtHeromodule.replace("/-st/", "");
            wtHeromodule = wtHeromodule.replace("/-sl/", "");
            wtHeromodule = wtHeromodule.replace("/-se/services/", "");
            wtHeromodule = wtHeromodule.replace("/-se/", "");

            if (wtHeromodule.indexOf("_.htm") != -1) {
                wtHeromodule = wtHeromodule.replace("_.htm", "");
            }
            if (wtHeromodule.indexOf(".htm") != -1) {
                wtHeromodule = wtHeromodule.replace(".htm", "");
            }
            //alert(wtHeromodule);
            var wt_ti = "Link:Hero|" + theID + "|" + wtHeromodule;
            var wt_dcsuri = "/hp-hero/" + theID + "/" + wtHeromodule;

            dcsMultiTrack("WT.ti", wt_ti, "DCS.dcsuri", wt_dcsuri, "WT.nv", "Rotating Hero", "WT.dl", "99", "WT.z_hph", "1");
        }
        //webtrends

    });

    //cycle through each module for x seconds & stop cycle on click of thumbnail
    numModules = ($('.featureBlock').length);
    currentModule = -1;
    cycleModules();


    //End Hero Module

    // Best Sellers Carousel defaultCategoryID
    var selectedCategory = $('#defaultCategoryID').text();

    //webtrends
    if (wtSetup) {
        var wtSelTab = $('#bestSellerTab' + selectedCategory).find('.bestSellerTabName').text();
        wtSelTab = wtSelTab.replace(/ *\([^)]*\) */g, "");
        wtSelTab = wtSelTab.replace(" ", "_");
        $('#wtSelectedTab').val(wtSelTab);
    }
    //alert($('#bestSellerTab' + selectedCategory).find('.bestSellerTabName').text());
    //webtrends

    //$('.ui-tabs-nav li').addClass('ui-tabs-nav_li'); Moved to the code
    $('#bestSellerTab' + selectedCategory).addClass('ui-tabs-selected');
    $('.bestSellerViewMore span').text($('#bestSellerTab' + selectedCategory).find('.bestSellerTabName').text());
    $('.bestSellerViewMore a').attr('href', $('#bestSellerTab' + selectedCategory).find('.bestSellerTabLink').text());
    $("#bestSellerTabContent" + $('#bestSellerTab' + selectedCategory).find('.bestSellerTabId').text()).show();

    $('#bestSellersCarousel' + selectedCategory).jcarousel({ scroll: 4, visible: 4, wrap: "last", itemVisibleInCallback: { onAfterAnimation: jcarousel_VisibleInCallback }, initCallback: carousel_callback });

    $('.tabContainer ul li').bind("click", function() {
        $('.tabContainer ul li').attr('class', 'ui-tabs-nav_li');
        $(this).attr('class', 'ui-tabs-nav_li ui-tabs-selected');

        $('.bestSellerViewMore span').text($(this).find('.bestSellerTabName').text());
        $('.bestSellerViewMore a').attr('href', $(this).find('.bestSellerTabLink').text());
        $('.bestSellerCarouselContent').hide();

        $("#bestSellerTabContent" + $(this).find('.bestSellerTabId').text()).show();
        if (!$("#bestSellersCarousel" + $(this).find('.bestSellerTabId').text()).hasClass("jcarousel-list")) {
            $("#bestSellersCarousel" + $(this).find('.bestSellerTabId').text()).jcarousel({ scroll: 4, visible: 4, wrap: "last", itemVisibleInCallback: { onAfterAnimation: jcarousel_VisibleInCallback }, initCallback: carousel_callback });
        }
        var theEventName = 'SelectBestSellers_Tab_' + $(this).find('.bestSellerTabName').text();

        //webtrends
        if (wtSetup) {

            wtTabSelected = $(this).find('.bestSellerTabName').text();

            wtTabSelected = wtTabSelected.replace(/ *\([^)]*\) */g, "");
            wtTabSelected = wtTabSelected.replace(" ", "_");
            var wt_ti = "Link:Best Sellers|" + wtTabSelected;
            var wt_dcsuri ="/hp-bestsellers/" + wtTabSelected;
            $('#wtSelectedTab').val(wtTabSelected);

            dcsMultiTrack("WT.ti", wt_ti, "DCS.dcsuri", _atag.dcsEncode(wt_dcsuri), "WT.nv", "Best Sellers", "WT.dl", "99", "WT.z_hpbs", "1");
        }
        //webtrends

        trackGAEvent(theEventName, 'Home');
    });

    $('a.bestSellerViewMore').bind('click', function() {
        trackGAEvent('SelectBestSellers_Link_ViewMore', 'Home');
    });

    $('.ui-tabs-nav li').hover(
      		function() { $(this).addClass('ui-tabs-nav_li_hover'); },
      		function() { $(this).removeClass('ui-tabs-nav_li_hover'); }
    );

    $('.jcarousel-prev').live('click', function() {
        trackGAEvent('SelectLeftArrowPull', 'Home');

        //webtrends
        if (wtSetup) {
            dcsMultiTrack("WT.ti", "Link:Best Sellers|Previous", "DCS.dcsuri", "/hp-bestsellers/previous", "WT.nv", "Best Sellers", "WT.dl", "99", "WT.z_hpbs", "1");
        }
    });

    $('.jcarousel-next').live('click', function() {
        trackGAEvent('SelectRightArrowPull', 'Home');

        //webtrends
        if (wtSetup) {
            dcsMultiTrack("WT.ti", "Link:Best Sellers|Next", "DCS.dcsuri", "/hp-bestsellers/next", "WT.nv", "Best Sellers", "WT.dl", "99", "WT.z_hpbs", "1");
        }
    });

    $('.itemBox').bind('mouseenter', function() {
        $lrgImage = $(this).find('img');
        lrgImageSrc = $lrgImage.attr('src');
        bkImage = 'url(' + lrgImageSrc + ')';
        $(this).css('background-image', bkImage);
        $(this).css('background-position', 'center center');
        $(this).css('background-repeat', 'no-repeat');
        $lrgImage.fadeOut('fast');
    });
    $('.itemBox').bind('mouseleave', function() {
        $lrgImage = $(this).find('img');
        $(this).css('background-image', 'none');
        $lrgImage.fadeIn('fast');
    });

    $('#staff_pickImg').bind('click', function() {
        location.href = "/-sl/staffpicks.htm";
        trackGAEvent('StaffPicksMainImageClick', 'Home');
    });
    $('.staff_browse_gallery').bind('click', function() {
        location.href = "/-sl/staffpicks.htm";
        trackGAEvent('StaffPicksBrowseTheGalleryClick', 'Home');
    });

    // Best Sellers Carousel
    $('#valueproposition').children().bind('click', function() {
        
        var theID = $('#valueproposition').children().index($(this));        
        
        var varTitle = $(this).attr('title');        
     
        if (typeof(varTitle) == "undefined" || varTitle == '')
        {
              varTitle = 'valprop';
        }        
             
        theID = theID + 1;
        trackGAEvent('SelectValueProp' + theID, 'Home'); 
        
        var wt_ti = "Link:Values|" + theID + "|" + varTitle;
        var wt_dcsuri = "/hp-values/" + theID + "/"+ varTitle;
        //webtrends
        if (wtSetup) {
            dcsMultiTrack("WT.ti", wt_ti, "DCS.dcsuri", wt_dcsuri, "WT.nv", "Values", "WT.dl", "99", "WT.z_hpv", "1");
        }
    });

    $('#holidayNoLonger').slideDown('fast');
    $('#valueMagHomepageOffer img').css('cursor', 'pointer');
    $('#valueMagHomepageOffer').show();
    //For AB Testing, track the load of this page
    trackGAEvent('Test_Group_Homepage_Viewed', 'newHomepageABTest');

});

function heroLink(theLink){
    wtHeromodule = theLink;
	location.href = theLink;
}

function setPromoBlockPosition(item){
        var promoOffset = $(item).offset();
        var bigPromoTopPos = promoOffset.top;
        var bigPromoLeftPos = promoOffset.left;    
        $('#PromoContainerBlock').css('position', 'absolute');
        $('#PromoContainerBlock').fadeIn();
        $('#PromoContainerBlock').css('top', bigPromoTopPos +22);
     	$('#PromoContainerBlock').css('left', bigPromoLeftPos-27);    
}
function fadeOutPromoBlock(){
    $('#PromoContainerBlock').fadeOut();
}

function jcarousel_VisibleInCallback(carousel, item, idx, state) {
   
    imgCarousel = $(item).find('img');
    
    if ($(imgCarousel).attr('src') == undefined || $(imgCarousel).attr('src')=='') {
        var imgSrc = $(imgCarousel).attr('id');        
        $(imgCarousel).load(function() {
        $(this).removeAttr("width");
        $(this).removeAttr("height");
        adjustDimensions($(this));
        });
        $(imgCarousel).attr('src', imgSrc);
    }
    adjustDimensions(imgCarousel);
}
function carousel_callback(carousel, state) {
   // $('#bestSellerCarouselWrapper').css('height','auto');
    $('.jcarousel-next').hover(
          	function() { $(this).addClass('jcarousel-next-horizontal-hover'); },
      		function() { $(this).removeClass('jcarousel-next-horizontal-hover'); }
    );
    $('.jcarousel-prev').hover(
          	function() { $(this).addClass('jcarousel-prev-horizontal-hover'); },
      		function() { $(this).removeClass('jcarousel-prev-horizontal-hover'); }
    );
    if ($.browser.safari) {
        //safari fix for dynamically created jCarousel on tab click to work
        carousel.setup();
        carousel.options.scroll = 0;//safari disables the buttons, to enable it we scroll.
        carousel.next();
        carousel.options.scroll = 4;

    }
}
function adjustDimensions(imgCarousel) {
    var imgWidth = $(imgCarousel).width();
    var imgHeight = $(imgCarousel).height();
    
    if (imgWidth > 200 || imgHeight > 200) {
        var ratioWidth = 200 / imgWidth;
        var ratioHeight = 200 / imgHeight;
        var ratio = 1;
        if (ratioHeight < ratioWidth) {
            ratio = ratioHeight;
        }
        else {
            ratio = ratioWidth;
        }
        imgHeight = imgHeight * ratio;
        imgWidth = imgWidth * ratio;
        $(imgCarousel).height(Math.floor(imgHeight));
        $(imgCarousel).width(Math.floor(imgWidth));
    }
}
function selectModule($theModule){

	//unselect all thumbnails 
	$('.featureCircle').each(function(){
		$(this).removeClass('featureCircleOn');
	});
	
	//select current thumbnail
	$theModule.addClass('featureCircleOn');
	
	//determine which module to slide to
	thisIndex = $('.featureCircle').index($theModule); //get the 0-based index of this thumbnail
	newMarginLeft = -1 * ($('#featureContainer').width() * thisIndex);
	newMarginLeft = newMarginLeft + 'px';
	
	//slide the selected module into position
	$('#featureSlide').animate({marginLeft:newMarginLeft},'normal');
	
}

function cycleModules(){
	currentModule = currentModule+1;
	if (currentModule >= numModules)
		currentModule = 0;
	var x = '.featureCircle:eq('+currentModule+')';
	$selectedCircle = $(x);
	selectModule( $selectedCircle );
	t_modules = setTimeout("cycleModules()",moduleDelay*1000);
}


function CloseSetNotFoundMessage()
{
    $('#NotfoundMessage').fadeOut();
    clearTimeout(t);
}

function SetNotFoundMessage()
{
  qscreenWidth = document.body.clientWidth;
  var screenCenter = qscreenWidth / 2;
  screenCenter = screenCenter - 225;
  $('#NotfoundMessage').css('left',screenCenter);
    var headerOffset=$('#headerBottomRow').offset();  
     $('#NotfoundMessage').css('top',headerOffset.top+35) ;
  $('#NotfoundMessage').show();
  t = setTimeout('CloseSetNotFoundMessage()', 10000);
}

function SetBrowseByCategoryGATracking() {
    $('.categoryList > li > a').live('click', function() {
        gaEvent = $(this).parents('.browseFloatContainer').find('.browseTitleContainer').find('.event').text();
        trackGAEvent(gaEvent,'Home');
    });
    $('.browseTitle > a').live('click', function() {
        gaEvent = $(this).parents('.browseTitleContainer').find('.event').text();
        trackGAEvent(gaEvent, 'Home');
    });
}


function trackGAEvent(eventName, pageName) {
    try {
        console.log('Google tracking : Event =' + eventName);
    }
    catch (e) {
    }
    if (typeof (_gaq) != "undefined") {
        var tmpEventName = "\'" + eventName + "\'";
        var tmpPageName = "\'" + pageName + "\'";
        _gaq.push(['t1._trackEvent', tmpPageName, tmpEventName, tmpEventName]);
    }
}
function carouselImageClick(url) {
    window.location.href = url;
    trackGAEvent('SelectProductImageinPull', 'Home');
}

function wtCallForBestSellerItemClick(rowNum, rowTitle) {
    if (wtSetup) {
        var temp = $('#wtSelectedTab').val();
        rowTitle = rowTitle.replace(/ /g, "_");

        var wt_ti = "Link:Best Sellers|" + temp + "|" + rowNum + "|" + rowTitle;
        var dcsuri = "/hp-bestsellers/" + temp + "/" + rowNum + "/" + rowTitle;
        dcsMultiTrack("WT.ti", wt_ti, "DCS.dcsuri", _atag.dcsEncode(dcsuri), "WT.nv", "Best Sellers", "WT.dl", "99", "WT.z_hpbs", "1");
    }
}
