// JavaScript Document


$.getScript = function(url, callback, cache){
    $.ajax({
            type: "GET",
            url: url,
            success: callback,
            dataType: "script",
            cache: cache
    });
};


// hide containers on click outside

$(document).bind('click', function(evt) {
    if (!$(evt.target).parents().hasClass("OptionSelectBox"))
        $("ul.OptionBox").hide();

    if (!$(evt.target).parents().hasClass("qvOptionSelectBox"))
        $("ul.qvOptionBox").hide();

    if (!$(evt.target).parents().hasClass("Nav"))
        $("div.MoreToggleWrap").hide();

    if (!$(evt.target).parents().hasClass("OptionBox"))
        $("ul.OptionBox > li div.OutOfStockContainer").hide();

    if (!$(evt.target).parents().hasClass("qvOptionBox"))
        $("ul.qvOptionBox > li div.OutOfStockContainer").hide();

    if (!$(evt.target).parents().hasClass("ItemWrap"))
        $("li.ItemWrap div.OutOfStockContainer").hide();

    if (!$(evt.target).parents().hasClass("UtilityLinks"))
        $("div.EmailAFriendContainer").hide();

    if (!$(evt.target).parents().hasClass("ShipOptionSelectBox"))
        $("ul.ShipOptionBox").hide();
});



$(document).ready(function() {
    productWarningMessage();
    searchBoxWaterMark();
    shipOptionBoxSelect();
    checkoutShippingSelect();
    prodDetailOptionBox();
    prodDetailShowSelection();
    prodDetailShowLargeImage();
    prodDetailPreorderHover();
    prodDetailOutOfStockEmail();
    prodDetailEmailAFriend();
    leftNavToggle();
    typeAheadRegistration();
    smoothScroll();
    partyKitShowAndHideExtras();
    facebookSharePTR();
    paypalRegistration();
    recommendedProductSlider();
    productDetailTabs();
  //  hideFacebookUponMagicZoom();


});     //document ready function end

function productWarningMessage() {
    // Product Warning Message JS
    $("a.CPSCCloseBox").click(function(event) {
        $(".CPSCWarningDetails").hide();
        event.preventDefault();
    });
    $("a.CPSCWarningLink").click(function(event) {
        $(".CPSCWarningDetails").hide();
        $(this).parent("div.CPSCWarningMsgContainer").children("div.CPSCWarningDetails").show("fast");
        event.preventDefault();
    });
}

function searchBoxWaterMark() {
    //Search Bar Watermark
    $("input.SearchBox").watermark("Adults, Teens, Kids...");
}

var quickViewLink;
var quickViewShown;
function showQuickView(link, productId) {

    $("input.hProductId").val(productId);
    $("span.QuickViewToggle > div.contentwrapQuickView").css('marginTop', $(window).scrollTop() + 60 + 'px'); //works in IE
    $("span.QuickViewToggle").show();


    quickViewLink = link;
    quickViewShown = true;

    return false;
}

function shipOptionBoxSelect() {
    //Checkout shipping dropdown
    $("div.ShipOptionSelectBox ul.ShipOptionBox").hide(); //Hide all content

    $('div.ShipOptionSelectBox > a').click(function() {
        $("div.ShipOptionSelectBox ul.ShipOptionBox").animate({ "height": "toggle" }, { duration: 100 });
        return false;

    });
}

function checkoutShippingSelect()
{
    //Checkout show shipping selection
    $('ul.ShipOptionBox > li > input,ul.ShipOptionBox > li > span.ShipOption').click(function(event) {
        if (!$(this).is('.Disabled')) {
            var OptionInput;
            OptionInput = $(this).closest('li').children('span.ShipOption').html();
            $(this).closest('div.ShipOptionSelectBox').children('a.ShipSelected').html(OptionInput);
            $(this).closest('ul.ShipOptionBox').animate({ "height": "toggle" }, { duration: 100 });
            $(this).closest('li').children('input').attr('checked', 'checked');
            $(this).closest('li').addClass('ShipSelectedLine');
        }

    });
}


function showMoreToggleWrap() {
    //Top Nav Show More Toggle
    $("div.MoreToggleWrap").animate({ "height": "toggle" }, { duration: 500 });
    return false;
}


function prodDetailOptionBox()
{
    //Prod Detail Show Option Box
    $("div.OptionSelectBox ul.OptionBox").hide(); //Hide all content

    $('div.OptionSelectBox > a').click(function() {
        $("div.OptionSelectBox ul.OptionBox").animate({ "height": "toggle" }, { duration: 100 });
        return false;
    });
}

function prodDetailShowSelection(){
//Prod Detail show selection
	$('ul.OptionBox > li > input,ul.OptionBox > li > span.Option').click(function() {
		if (!$(this).is('.Disabled')) {
			var OptionInput;
			OptionInput = $(this).closest('li').children('span.Option').html();
			$(this).closest('div.OptionSelectBox').children('a.Selected').html(OptionInput);
			$(this).closest('ul.OptionBox').animate({ "height": "toggle" }, { duration: 100 });
			$(this).closest('li').addClass('SelectedLine');
			$(this).closest('li').children('input').attr('checked', 'checked');
		}
		return true;
	});
}




function prodDetailShowLargeImage() {
//Prod Detail Accessories Show Lg image
    $("a.CloseBox").click(function() {
        $("div.HoverContainer").hide();
        return false;
    });

    $("a.HoverTrig").mouseenter(function(event) {
        $("div.HoverContainer").hide();
        $(this).parent("div.SmallImageWrap").children("div.HoverContainer").animate({ "opacity": "toggle" }, { duration: 300 });
        event.preventDefault();
    });

    $(".SmallImageWrap").mouseleave(function(event) {
        $("div.HoverContainer").hide();
        event.preventDefault();
    });
}


function prodDetailPreorderHover() {
//Prod Detail Pre-Order hover box
    $("span.PreOrderContainer").hide();
    $("a.HoverTrig").mouseenter(function(event) {
        $("span.PreOrderContainer").hide();
        $(this).parent(".Availability").children("span.PreOrderContainer").animate({ "opacity": "toggle" }, { duration: 300 });
        event.preventDefault();
    });

    $(".Availability").mouseleave(function(event) {
        $("span.PreOrderContainer").hide();
        event.preventDefault();
    });
}

function prodDetailOutOfStockEmail(){
//Prod Detail Out of stock email
    $("a.CloseBox").click(function(event) {
        $("div.OutOfStockContainer").hide();
        return false;
    });

    $("a.HoverTrig").click(function(event) {
        $("div.OutOfStockContainer").hide();
        $(this).parent(".Availability").siblings("div.OutOfStockContainer").animate({ "opacity": "toggle" }, { duration: 300 });
        return false;
    });

}

function prodDetailEmailAFriend(){
//Prod Detail Email a Friend
    $("a.CloseBox").click(function() {
        $("div.EmailAFriendContainer").hide();
        return false;
    });

    $("a.HoverTrig").click(function() {
        $("div.EmailAFriendContainer").hide();
        $(this).parent("ul.UtilityLinks li").children("div.EmailAFriendContainer").animate({ "opacity": "toggle" }, { duration: 300 });
        $(".WaterMarkSeperateEmail").watermark("Separate multiple email addresses with a comma.");

        return false;
    });
}

function leftNavToggle(){
//Left Nav Toggle
    //Hide (Collapse) the toggle containers on load
    $("ul.NavToggleContainer").show();
    //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
    $("h2.NavHeader").click(function() {
        $(this).toggleClass("Active").next().slideToggle("slow");
        return false; //Prevent the browser jump to the link anchor
    });
}

//Product Detail Large image popup
function LGImgpopitup(url) {
    newwindow = window.open(url, 'name', 'height=802,width=802');
    if (window.focus) { newwindow.focus() }
    return false;
}

//Size chart popup window
function SizeChartpopitup(url) {
    newwindow = window.open(url, 'name', 'height=680,width=680,scrollbars=yes');
    if (window.focus) { newwindow.focus() }
    return false;
}


////Magic zoom facebook
//function hideFacebookUponMagicZoom() {
//    $("div.ProductImage a#zoom1").mouseenter(function() {
//		// $("div.addthis_toolbox").hide();
//		$("div.addthis_toolbox").css('zIndex', -1);
//    });
//    $("div.ProductImage a#zoom1").mouseleave(function() {
//		// $("div.addthis_toolbox").show();
//		 $("div.addthis_toolbox").css('zIndex', 5);
//    });
//}


//
// Start Section: Typeahead Search
// Author: Girish Borkar
//
var searchResultIndex = -1;
var searchResultMaxIndex = 0;
var originalPrefix = "";
var searchBox;
var typeAheadContainer;
var responseData;
var txtChangeIsProgramatic = false;
var isTypeAheadSelectionHandler = false;


function SetSearchTextValue(txt) {
    searchBox.val(txt);
    txtChangeIsProgramatic = true;
}

function GetSearchTextValue() {
    return jQuery.trim(searchBox.val());
}

function SelectSuggestion(index, isKeystroke) {

    $('.TypeAheadContainer li').each(function(i, l) {
        var li = $(l);
        if (li.hasClass("Selected")) {
            li.removeClass("Selected");
        }
        if (i == index) {
            li.addClass("Selected");
            if (!li.hasClass("InCategory")) {
                var a = li.children(':first').text();
                if (isKeystroke)
                    SetSearchTextValue(a);

                hdnSearchUrl.val('/browse/_/N-/Ntt-' + a + '/results1.aspx');
            }
            else {
                var a = $('.TypeAheadContainer').children(':first').children(':first').text();

                if (isKeystroke)
                    SetSearchTextValue(a);

                var url2 = '/browse' + responseData[0].Departments[i - 1].SearchUrl + '/results1.aspx';
                hdnSearchUrl.val(url2);
            }
        }
    });

    searchResultIndex = index;
}


function typeAheadRegistration(){

    searchBox = $('.SearchBox');
    typeAheadContainer = $('.TypeAheadContainer');

    searchBox.bind('textchange', function(event, previousText) {

        if (txtChangeIsProgramatic) {
            txtChangeIsProgramatic = false;
            return;
        }

        var newText = GetSearchTextValue();

        if (typeof (previousText) == "undefined")
            previousText = "";

        if (newText != previousText) {
            searchResultIndex = -1;
            if (newText.length > typeAheadMinLength && newText != "") {
                originalPrefix = newText;
                FetchAndDisplayTypeAheadData(newText, previousText);
            } else {
                clearTypeAheadContainer();
            }
        }
    });


    $('body').click(function() {
        clearTypeAheadContainer();
    });




    typeAheadContainer.mouseout(function() {
        SetSearchTextValue(originalPrefix);
        if (!isTypeAheadSelectionHandler) hdnSearchUrl.val('');
        SelectSuggestion(-1);

    });

    searchBox.keydown(function(event) {

        if (event.keyCode == 8 && searchBox.val() == "") {
            clearTypeAheadContainer();
        } else if (event.keyCode == 13 && hdnSearchUrl.val() != "") {
            isTypeAheadSelectionHandler = true;

        } else if (event.keyCode == 38 || event.keyCode == 40) {

            if (searchResultIndex < searchResultMaxIndex - 1
					&& searchResultIndex >= -1
					&& event.keyCode == 40) {
                searchResultIndex++;
            }
            else if (searchResultIndex < searchResultMaxIndex
					&& searchResultIndex >= 0
					&& event.keyCode == 38) {
                searchResultIndex--;
            }

            if (searchResultIndex == -1) {
                SetSearchTextValue(originalPrefix);
                hdnSearchUrl.val('');
            }

            SelectSuggestion(searchResultIndex, true);

        }
    });
}

function FetchAndDisplayTypeAheadData(newText, previousText) {

    var fetchNewData = false;

    if (responseData == null || responseData.length == 0 || newText.length < previousText.length) {

        fetchNewData = true;
    }
    else {
        for (i = 0; i < responseData.length; i++) {
            if (responseData[i].Keyword.indexOf(newText) !== 0) {
                fetchNewData = true;
                break;
            }
        }
    }
    if (fetchNewData) {
        var fetchUrl = '/WebServices/TypeAhead.ashx?prefix=' + newText;
        AjaxCallHandler.Schedule(fetchUrl, typeAheadDelay);
    }
    else
        ShowTypeAheadHtml(responseData);
}

var AjaxCallHandler = {
    Schedule: function(fetchUrl, delay) {
        this.Cancel();
        this.timeOutId = window.setTimeout(function() {
            $.ajax({
                url: fetchUrl,
                context: document.body,
                dataType: "json",
                success: function(data) {
                    responseData = data;
                    ShowTypeAheadHtml(data);
                    searchResultMaxIndex = data.length;
                    if (data.length > 0) {
                        searchResultMaxIndex += data[0].Departments.length;
                    }
                }
            });
        }, delay);
    },
    Cancel: function() {
        if (typeof this.timeOutId == "number") {
            window.clearTimeout(this.timeOutId);
            delete this.timeOutId;
        }
    }
};

function clearTypeAheadContainer() {

    typeAheadContainer.html('');
    typeAheadContainer.hide();

    if (!isTypeAheadSelectionHandler)
        hdnSearchUrl.val('');

}

function ShowTypeAheadHtml(data) {

    if (data.length <= 0) {
        typeAheadContainer.html('');
        typeAheadContainer.hide();
        return;
    }

    var items = [];
    for (var i = 0; i < data.length; i++) {

        var url = '/browse/_/N-/Ntt-' + data[i].Keyword + '/results1.aspx';
        var keyword = data[i].Keyword;
        items.push('<li><a href="' + url + '" onclick="HandleSearchSelection(\'' + keyword + '\');" >' + GetSearchKeywordDisplay(GetSearchTextValue(), data[i].Keyword) + '</a></li>');
        if (i == 0) {
            for (var j = 0; j < data[i].Departments.length; j++) {
                var dept = data[i].Departments[j];
                var url2 = '/browse' + dept.SearchUrl + '/results1.aspx';
                items.push('<li class="InCategory"><a href="' + url2 + '" onclick="HandleSearchSelection(\'' + keyword + '\');">in ' + dept.Name + ' (' + dept.Count + ')' + '</a></li>');
            }
        }
    }

    //	typeAheadContainer.html(''); 
    var html = "<ul class='ResultsList'>" + items.join('') + "</ul>";
    typeAheadContainer.html(html);

    typeAheadContainer.show();



    $('.TypeAheadContainer li').each(function(i, l) {
        $(l).mouseover(function() {
            SelectSuggestion(i, false);
        });
    });


}

function GetSearchKeywordDisplay(searchTerm, keyword) {
    var reg = new RegExp(searchTerm, 'g');
    var replace = '<strong>' + searchTerm + '</strong>';
    return keyword.replace(reg, replace);
}

function HandleSearchSelection(txt) {

    //searchBox.val(txt);

    SetSearchTextValue(txt);
    typeAheadContainer.hide();
    btnSearchSubmit.click();

}
//
// End Section: Typeahead Search
//

//Begin Section: Port of old js code
function copyAToB(controlAId, controlBId) {
	$('#' + controlBId).val($('#' + controlAId).val());
}

// Postbacks
function disablePostBack() {
	var hiddenValue = get_object("hdnSubmitted").value;

	if (hiddenValue == "false") {
		get_object("hdnSubmitted").value = "true";
		hiddenValue = get_object("hdnSubmitted").value;
		return true;
	}

	return false;
}

function enablePostback() {
	get_object("hdnSubmitted").value = "false";
}


function createCookie(name, value, hours) {
	var expires = hours / 24;
	setCookie(name, value, expires, "/", '', '');
}

function setCookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}

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);
}


function RemoveCoupon(couponcode) {
	setCookie('BuyCostumesRemoveCoupon', couponcode, 30, '/', '', '');
	window.location.href = unescape(window.location.pathname);
}
//End Section: Port of old js code


function smoothScroll() {
// jQuery SmoothScroll | Version 11-03-14
    $('a[href*=#Scroll]').click(function() {
        // duration in ms
        var duration = 500;

        // easing values: swing | linear
        var easing = 'swing';

        // get / set parameters
        var newHash = this.hash;
        var target = $(this.hash + ', a[name=' + this.hash.slice(1) + ']').offset().top;
        var oldLocation = window.location.href.replace(window.location.hash, '');
        var newLocation = this;

        // make sure it's the same location      
        if (oldLocation + newHash == newLocation) {
            // set selector
            if ($.browser.safari) var animationSelector = 'body:not(:animated)';
            else var animationSelector = 'html:not(:animated)';

            // animate to target and set the hash to the window.location after the animation
            $(animationSelector).animate({ scrollTop: target }, duration, easing, function() {

                // add new hash to the browser location
                window.location.href = newLocation;
            });

            // cancel default click action
            return false;
        }
    });

}

function scrollToLocation(location, duration) {

    var destination = $("#" + location).offset().top;

    $('html,body').animate({
        scrollTop: destination
    }, duration);
}

function partyKitShowAndHideExtras() {
//Party Kit Show and Hide Party Extras
    $('div.ConfigurePartyOrder ul.PartyExtrasToggleWrapper').hide();

    $('div.ConfigurePartyOrder a.ToggleTrigger > span.togglehide').hide();

    $('div.ConfigurePartyOrder a.ToggleTrigger').click(function(event) {

        if ($('div.ConfigurePartyOrder ul.PartyExtrasToggleWrapper').is(':hidden')) {

            $('div.ConfigurePartyOrder ul.PartyExtrasToggleWrapper').slideDown();

            $('div.ConfigurePartyOrder a.ToggleTrigger > span.togglehide').show();

            $('div.ConfigurePartyOrder a.ToggleTrigger > span.toggleshow').hide();

        } else {

            $('div.ConfigurePartyOrder ul.PartyExtrasToggleWrapper').slideUp();

            $('div.ConfigurePartyOrder a.ToggleTrigger > span.togglehide').hide();

            $('div.ConfigurePartyOrder a.ToggleTrigger > span.toggleshow').show();

        }
        event.preventDefault();

    });
}

//Party Kit Detail Tabs
$(function() {
    var tabContainers = $('div.PartyTabContents');
    tabContainers.hide().filter(':first').show();

    $('div.PartyTabs ul.PartyTabNavigation a').click(function() {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.PartyTabs ul.PartyTabNavigation a').removeClass('PartyTabSelected');
        $(this).addClass('PartyTabSelected');
        return false;
    }).filter(':first').click();
});



function facebookSharePTR() {
//Facebook share post transaction
    $("div.AddThisContentContainer .goleft").click(function(e) {
        var $active = $("div.AddThisContentContainer .active");
        var $next = $active.prev().length ? $active.prev() : $("div.AddThisContentContainer .focusitem:last");

        $active.removeClass('active');
        $active.addClass('notactive');
        $next.addClass('active');
        $next.removeClass('notactive');
    });

    $("div.AddThisContentContainer .goright").click(function(e) {
        var $active = $("div.AddThisContentContainer .active");
        var $next = $active.next().length ? $active.next() : $("div.AddThisContentContainer .focusitem:first");

        $active.removeClass('active');
        $active.addClass('notactive');
        $next.addClass('active');
        $next.removeClass('notactive');
    });

}

function showPaymentMethod() {
    //Checkout payment method toggle
    $("div.PaymentMethodContents").slideDown();
    $('div.PaymentMethodButton > ul.CreditCards').addClass('Selected');
    $('div.PaymentMethodButton > ul.PayPal').removeClass('Selected');
}

function paypalRegistration() {
    $("div.PaymentMethodButton > ul > li > input.Hide").live("click", function(event) {
        $("div.PaymentMethodContents").slideUp();
        $('div.PaymentMethodButton > ul.PayPal').addClass('Selected');
        $('div.PaymentMethodButton > ul.CreditCards').removeClass('Selected');

    });

    //Checkout paypal popup prevent default
    $("div.PaymentMethodButton > ul.PayPal > li > a").live("click", function(event) {
        event.preventDefault();
    });
}

function productDetailTabs() {
    //Product Detail Tabs
    var tabContainers = $('div.PDTabContents');
    tabContainers.hide().filter(':first').show();

    $('div.PDTabs ul.PDTabNavigation a').click(function() {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.PDTabs ul.PDTabNavigation a').removeClass('PDTabSelected');
        $(this).addClass('PDTabSelected');
        return false;
    }).filter(':first').click();
}

var VPClone = $('div#ProductVideoBox').html();
function AlternateImageSwap(e, img) {

    if ($('div#ProductVideoBox').length && !$(e).hasClass('Video')) { //looking to see if div#Product Video Box exists, and if the clicked object is not a video alt image.
        VPClone = $('div#ProductVideoBox').clone(e);
        $('div#ProductVideoBox').remove();
    }

    $('a.LargeImage').attr('href', img);
    return false;
}

function AlternateImageClick() {
    $('ul.AltImageWrap > li.Video').click(function(e) {
        if (!$('div#ProductVideoBox').length) { //check if div#ProductVideoBox exists
            $('div.ProductImage').prepend(VPClone);
        }
        return false;
    });
}

function recommendedProductSlider() {
    //Slider for recommended products.

    //dynamically set the size
    var Product = $('div.RecommendedProducts > ul.GridviewList > li');
    //var ProdWidth = Math.abs(parseInt(Product.css('width')))+Math.abs(parseInt(Product.css('marginLeft')))+Math.abs(parseInt(Product.css('marginRight')))+Math.abs(parseInt(Product.css('paddingLeft')))+Math.abs(parseInt(Product.css('paddingRight')));
    var ProdWidth = Product.outerWidth(true);
    var numberOfProds = $('div.RecommendedProducts > ul.GridviewList > li').length;
    var containerSize = ProdWidth * numberOfProds;
    //start recommended product count

    var SliderSize = $('div.RecommendedProducts').outerWidth();
    var VisProdCount = Math.abs(parseInt(SliderSize / ProdWidth));
    var ProdStart = Math.abs(parseInt(VisProdCount / VisProdCount));

    $('div.RecommendedProducts').find('span.ProdCountDisplay').html(ProdStart + '-' + VisProdCount);

    //end recommended product count

    $('div.RecommendedProducts > ul.GridviewList').css('width', containerSize + "px");
    //this goes foward
    $('div.RecommendedProducts > div.SlideControl >ul>li>a.Next').bind('click', SlideFwd);
    function SlideFwd() {

        var scrollAmount = $(this).closest('div.RecommendedProducts').find('ul.GridviewList').outerWidth() - $(this).closest('div.RecommendedProducts').outerWidth();
        var currentPos = Math.abs(parseInt($(this).closest('div.RecommendedProducts').find('ul.GridviewList').css('left')));
        var remainingScroll = scrollAmount - currentPos;
        var nextScroll = $(this).closest('div.RecommendedProducts').outerWidth();


        //if there isn't a full scroll length left, only scroll the remaining amount
        if (remainingScroll < nextScroll) {
            nextScroll = remainingScroll;
        }


        //if the current position is less than the scroll amount, we know its okay to scroll
        if (currentPos < scrollAmount) {
            //unbind from function but bind to event.preventdefault to stop normal click action
            //unbinding prevents aberrant behavior if using clicks before the slide animation is complete
            $('div.RecommendedProducts > div.SlideControl >ul>li>a').unbind().bind('click', function() { return false; });

            $(this).closest('div.RecommendedProducts').find('ul.GridviewList').animate({
                left: '-=' + nextScroll + 'px'
            }, 'slow', function() {
                $('div.RecommendedProducts > div.SlideControl >ul>li>a.Next').unbind().bind('click', SlideFwd); //unbind from e.preventDefault but rebind to SlideFwd function andfer animate is complete
                $('div.RecommendedProducts > div.SlideControl >ul>li>a.Previous').unbind().bind('click', SlideBak);

            });
            if ($(this).closest('ul').find('a.Previous').hasClass('Disabled')) {
                $(this).closest('ul').find('a.Previous').removeClass('Disabled');
            }
            //change the product count dynamically
            var ProdCountMod = Math.abs(parseInt(nextScroll / ProdWidth));
            VisProdCount = VisProdCount + ProdCountMod;
            ProdStart = ProdStart + ProdCountMod;
            $('div.RecommendedProducts').find('span.ProdCountDisplay').html(ProdStart + '-' + VisProdCount);

            if (currentPos + nextScroll >= scrollAmount) { // adds a class to disable the forward btn
                $(this).addClass('Disabled');
            }
        }

        return false;
    };
    //this goes back
    $('div.RecommendedProducts > div.SlideControl >ul>li>a.Previous').bind('click', SlideBak);
    function SlideBak() {
        var scrollAmount = $(this).closest('div.RecommendedProducts').find('ul.GridviewList').outerWidth(); -$(this).closest('div.RecommendedProducts').outerWidth();
        var currentPos = Math.abs(parseInt($(this).closest('div.RecommendedProducts').find('ul.GridviewList').css('left')));
        var nextScroll = $(this).closest('div.RecommendedProducts').outerWidth();


        //if next scroll will be less than the current position, replace next scroll so not to go to far
        if (currentPos < nextScroll) {
            nextScroll = currentPos;
        }


        if (currentPos != 0) {
            //unbind from function but bind to event.preventdefault to stop normal click action
            //unbinding prevents aberrant behavior if using clicks before the slide animation is complete
            $('div.RecommendedProducts > div.SlideControl >ul>li>a').unbind().bind('click', function() { return false; });
            $(this).closest('div.RecommendedProducts').find('ul.GridviewList').animate({
                left: '+=' + nextScroll + 'px'
            }, 'slow', function() {
                $('div.RecommendedProducts > div.SlideControl >ul>li>a.Previous').unbind().bind('click', SlideBak); //rebinds to SlideBak when animation is complete.
                $('div.RecommendedProducts > div.SlideControl >ul>li>a.Next').unbind().bind('click', SlideFwd);
            });
            var ProdCountMod = Math.abs(parseInt(nextScroll / ProdWidth));
            VisProdCount = VisProdCount - ProdCountMod;
            ProdStart = ProdStart - ProdCountMod;
            $('div.RecommendedProducts').find('span.ProdCountDisplay').html(ProdStart + '-' + VisProdCount);
            if ($(this).closest('ul').find('a.Next').hasClass('Disabled')) {
                $(this).closest('ul').find('a.Next').removeClass('Disabled');
            }
        }
        if (currentPos - nextScroll <= 0) { // adds a class to disable the forward btn
            $(this).addClass('Disabled');
        }

        return false;
    }; //end recommended product slider
    
}


/************************************/
// Window Open Functions
/************************************/
//product Detail page - popup window
function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=600,left = 390,top = 212');");
}

// openwindowlink
// Opens a link in a new window
function openWindow(url, name, options) {
    var newWindow = window.open(url, name, options);
    if (newWindow != null)
        newWindow.focus();
}

function openwindowlink(imgUrl) {
    openWindow(imgUrl, "Buycostumes", "directories=0,height=550,width=420,scrollbars=no");
}

function openwindowlink_outstock() {
    openWindow("/pages/popups/outofstock_pop.htm", "Details", "directories=0,height=175,width=300,scrollbars=no");
}

function openPage(siteid, pageid, name) {
    openWindow('/pages/Content/ContentDisplay.aspx?siteid=' + siteid + '&pageid=' + pageid, name, 'width=800,height=800,scrollbars=yes');
}

function opensizechart(prodID) {
    openWindow("/Pages/Content/SizeChart.aspx?prodID=" + prodID, "Buycostumes", "directories=0,height=600,width=650,scrollbars=yes");
}

// openvideoplayer
// Opens the buycostumes videoplayer
function openvideoplayer(videoName) {
    var URL = "http://images.buycostumes.com/video/VideoPlayer.aspx?VFN=" + videoName;
    openWindow(URL, "BuyCostumesVideo", "directories=0,height=490,width=490,scrollbars=no");
}

function makeAccessFlyoutVisible(clientId) {
	makeVisible(clientId, 'AjaxRecAcBox');
}

function makeVisible(objid, classname) {
	get_object(objid).className = classname;
}

