var activePurchasingPanel;
var currentSelectedSerialNo;


function showWMVMediaPlayer() {
    $('#mediaplayer').show();
    $('.mediafile').attr('href', src);
    $.fn.colorbox({ width: "430px", height: "380px", inline: true, title: sTitle, href: "#hdnMediaPlayer" });
    $('#hdnMediaPlayer').show();
    $('.media').media({ width: 385, height: 300, autoplay: true });
}

function showMP3MediaPlayer(src, sTitle) {
    $('#mediaplayer').show();
    $('.mediafile').attr('href', src);
    $.fn.colorbox({ width: "430px", height: "100px", inline: true, title: sTitle, href: "#hdnMediaPlayer" });
    $('#hdnMediaPlayer').show();
    var swfSrc = '/includes/GuitarCenter/flash/mediaplayer.swf?file=' + src;
    $('.media').media({ width: 385, height: 20, autoplay: true, src: swfSrc });
}


function initOtherMedia() {


    $(".mp3entity").click(function () {
        var src;
        var title;
        var internalsrc;
        src = $(this).attr('href');
        title = $(this).html();
        showMP3MediaPlayer(src, title);
        return false;
    });

    $(".videoentity").click(function () {
        var src;
        var title;
        src = $(this).attr('href');
        title = $(this).html();

        showWMVMediaPlayer(src, title);
        return false;
    });

    $("a[href*=.pdf]").attr({
        target: "_blank"
    });

    $("a[href*=.PDF]").attr({
        target: "_blank"
    });

}

function GetNearestStoreServiceParams(sExtSysId, serialNum, sOptionStatus) {
    var params;
    var city = $("#ipCity").val();
    var state = $("#ipState").val();
    var zip = $("#homeStoreZip").val();
    sExtSysId = ClearnExternalSystemId(sExtSysId);
    var params;
    if (serialNum == null || serialNum == "") {
        if (zip != "") {
            params = { "nStartIndex": 0, "nPageSize": 1, "sCity": "", "sState": "", "sZip": zip, "sDistance": "0", "sStoreFilter": "1", "sHomeStore": "", "sExtSysId": sExtSysId, "sSerialNum": '', "sOptionStatus": sOptionStatus };
        }
        else {
            params = { "nStartIndex": 0, "nPageSize": 1, "sCity": city, "sState": state, "sZip": zip, "sDistance": "0", "sStoreFilter": "1", "sHomeStore": "", "sExtSysId": sExtSysId, "sSerialNum": '', "sOptionStatus": sOptionStatus };
        }
    }
    else {
        if (zip != "") {
            params = { "nStartIndex": 0, "nPageSize": 1, "sCity": "", "sState": "", "sZip": zip, "sDistance": "0", "sStoreFilter": "1", "sHomeStore": "", "sExtSysId": sExtSysId, "sSerialNum": serialNum, "sOptionStatus": sOptionStatus };
        }
        else {
            params = { "nStartIndex": 0, "nPageSize": 1, "sCity": city, "sState": state, "sZip": zip, "sDistance": "0", "sStoreFilter": "1", "sHomeStore": "", "sExtSysId": sExtSysId, "sSerialNum": serialNum, "sOptionStatus": sOptionStatus };
        }
    }
    return params;
}

function loadNearstStoreFromServerGeoCodeValues(sExtSysId, serialNum, OptionStatus, isInventory) {
    //first we check the if the item is a potentially an item that will have an inventory
    if (activePurchasingPanel == "#purchasing-store") {
        return;
    };

    if (sExtSysId == undefined || isInventory == undefined) {

        $(activePurchasingPanel + ' .ClosestStore').hide();
        $(activePurchasingPanel + ' .ShipToStoreContaner').show();
        return;
    }
    sExtSysId = ClearnExternalSystemId(sExtSysId);
    //If clean external system id != 9 that means the product is not an inventoried product so no need to check the service for inventory.
    if (isInventory != "true" || sExtSysId.length != 9) {
        $(activePurchasingPanel + ' .ClosestStore').hide();
        $(activePurchasingPanel + ' .ShipToStoreContaner').show();
        return;
    }
    var cachedData;
    var cacheKey;
    cacheKey = sExtSysId + "_" + serialNum;
    cachedData = $.jCache.getItem(cacheKey);
    if (cachedData) {
        showCurrentStore(cachedData);
        return;
    }
    $(activePurchasingPanel + ' .ClosestStore').hide();
    if (!sExtSysId || sExtSysId == "0") {
        //It will look weird if Available stores is not visible so we load the ship to store image to fill estate area.
        $(activePurchasingPanel + ' .ClosestStore').hide();
        $(activePurchasingPanel + ' .ShipToStoreContaner').show();
        return;
    }

    params = GetNearestStoreServiceParams(sExtSysId, serialNum, OptionStatus);
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        url: "/ajax/itemend/Inventory.asmx/GetStores",
        data: JSON2.stringify(params, '', ''),
        success: function (response) {
            //cache it.
            if (response != null) {
                $.jCache.setItem(cacheKey, response.d);
                showCurrentStore(response.d)
            }
            else {
                $(activePurchasingPanel + ' .ShipToStoreContaner').show();
            }
        },
        error: function (xhr, status, error) {
            $(activePurchasingPanel + ' .ShipToStoreContaner').show();
            return;
        }
    });
}


function SetFindInStoreToSelectedItem() {
    //We don't need to do anything if the active panel is not the find in store tab
    //prevent unnecessary hits to the service.
    if (activePurchasingPanel != "#purchasing-store") {
        return;
    }
    var currentSelectedItemNo;
    var currentSelectedExtSysId;
    currentSelectedExtSysId = $('#selectedextsysid').val();
    currentSelectedItemNo = $("#selecteditemno").val();
    var currentSelectedserialno;
    currentSelectedserialno = $("#selectedserialno").val();
    if (currentSelectedItemNo == "" || currentSelectedItemNo == 0) {
        currentSelectedItemNo = $("#hdnExtSysId").val();
        currentSelectedserialno = "";
    }

    $('#purchasing-store  .serialItemNo').hide();
    $('#purchasing-store .serialItemno').val('');
    var listItem;
    listItem = $(activePurchasingPanel + ' .options-box-locator .list-wrapper .option' + currentSelectedItemNo);
    if ($(listItem).html() != undefined) {
        listItem.click();
    }
    else {
        //likely because its a new item that has a platinum equivalent so we need to find the platinum option eequivalant via the sExtSysId then click that one.
        //Fun stuff.  Good data structures.
        $(activePurchasingPanel + ' .itemno option').each(function () {
            if ($(this).attr('sextsysid') == currentSelectedExtSysId) {
                currentSelectedItemNo = $(this).val();
                listItem = $(activePurchasingPanel + ' .options-box-locator .list-wrapper .option' + currentSelectedItemNo);
                listItem.click();
            };
        });

    }
    if (currentSelectedItemNo != "") {
        $('#purchasing-store  .serial' + currentSelectedItemNo).show();
    }
    //This means it was a direct link fthe find more button.
    if ($('#findinstoreventsource').val() == "findmore") {
        $('#purchasing-store .hrefHideStore').each(function (index) {
            $(this).click();
        });
        $(activePurchasingPanel + ' .options-box-serialnumber .list-wrapper .option').click();

    }
    else {
        jQuery.each($('#purchasing-store  .serialItemno option'), function () {
            if (currentSelectedserialno == this.value) {
                $('#purchasing-store .serialItemno').val(currentSelectedserialno);
                $(activePurchasingPanel + ' .options-box-serialnumber .list-wrapper .option' + currentSelectedserialno).click();
                $('#purchasing-store .serialItemno').show();
            }
        });

    }
    //If we have a selected store and the map and direction link was clicked ( that controls the findinstoreventsource value) then show the map
    if ($('#selectedstoreno').val() != "" && $('#findinstoreventsource').val() == "map") {
        showStoreExpanded($('#selectedstoreno').val());
    }

    $('#purchasing-module').unbind('tabsshow', SetFindInStoreToSelectedItem);
}

function ShowFindMoreStores() {
    //ensure we unbind any existing so the events don't build up.
    $('#purchasing-module').unbind('tabsshow', SetFindInStoreToSelectedItem);
    $('#purchasing-module').bind("tabsshow", SetFindInStoreToSelectedItem);
    $('#purchasing-module').tabs('select', 'purchasing-store');
}

function SetHiddenSelectedInfo() {
    var seloption;
    var selsernum;
    var childselecteditem;
    seloption = $(activePurchasingPanel + " .selOptionInfo option:selected").val();
    selsernum = $(activePurchasingPanel + " .serialItemno option:selected").attr("serialno");
    childselecteditem = $(activePurchasingPanel + " .serialItemno option:selected").attr("itemno");
    var hdnExtSysId;
    var hdnOptionStatus;
    if (seloption != undefined && seloption != 0) {
        hdnExtSysId = $(activePurchasingPanel + " .selOptionInfo option:selected").attr("sExtSysId");
        hdnOptionStatus = $(activePurchasingPanel + " .selOptionInfo option:selected").attr("OptionStatus");
    }
    else {
        hdnExtSysId = $('#hdnExtSysId').val();
        seloption = $('.hdnDefaultItemno').val();
        hdnOptionStatus = $('#hdnDefaultOptionStatus').val();
        $('#selectedextsysid').val($('#hdnExtSysId').val());
    }
    //if we couldn't find it because option is not null but for some reason the sExtSysId in the OptionInfo is not set
    //use the default.
    if (hdnExtSysId == null) {
        $('#selectedextsysid').val($('#hdnExtSysId').val());
        $('#selectedoptionstatus').val($('#hdnDefaultOptionStatus').val());
    }

    $('#selecteditemno').val(seloption);
    $('#selectedextsysid').val(hdnExtSysId);
    $('#selectedoptionstatus').val(hdnOptionStatus);
    if (selsernum) {
        $('#selectedserialno').val(selsernum);
        $('#selectedchilditemno').val(childselecteditem);

    }
    else {
        $('#selectedserialno').val('');
        $('#selectedchilditemno').val('');
    }



}


function showCurrentStore(data) {
    var stores = data.Stores;
    if (stores && stores.length == 0) {
        //It will look weird if Available stores is not visible so we load the ship to store image to fill estate area.
        $(activePurchasingPanel + ' .ShipToStoreContaner').show();
        $(activePurchasingPanel + ' .ClosestStore').hide();
        SetCurrentlyViewingOptionText();
        return;
    }

    var currentStore = stores[0];
    //hide or show make home store if the store is == to the closest store 
    if (currentStore.StoreNo == $("#hdnHomeStoreNo").val()) {
        $(activePurchasingPanel + ' .ClosestStore_HomeStore').hide();
    }
    else {
        $(activePurchasingPanel + ' .ClosestStore_HomeStore').show();
    }
    $(activePurchasingPanel + ' .ShipToStoreContaner').hide();
    $(activePurchasingPanel + ' .stickers-b').hide();
    $(activePurchasingPanel + ' .ClosestStore').show();
    $(activePurchasingPanel + ' .ClosestStore_name').html("Guitar Center " + currentStore.StoreName);
    $(activePurchasingPanel + ' .ClosestStore_City').html(currentStore.StoreCity);
    $(activePurchasingPanel + ' .ClosestStore_State').html(currentStore.StoreState);
    $(activePurchasingPanel + ' .ClosestStore_Zip').html(currentStore.StoreZipcode);
    $(activePurchasingPanel + ' .ClosestStore_address').html(currentStore.StoreAddress);
    $(activePurchasingPanel + ' .ClosestStore_phone').html(currentStore.StorePhone);
    $(activePurchasingPanel + ' .ClosestStore_Email').attr('storeno', currentStore.StoreNo);
    $(activePurchasingPanel + ' .ClosestStore_Email').attr('storename', currentStore.StoreName);

    $(activePurchasingPanel + ' .ClosestStore_HomeStore').attr('storeno', currentStore.StoreNo);
    $(activePurchasingPanel + ' .ClosestStore_HomeStore').attr('storename', currentStore.StoreName);
    $(activePurchasingPanel + ' .ClosestStore_HomeStore').attr('storezip', currentStore.StoreZipcode);
    $(activePurchasingPanel + ' .ClosestStore_Map').attr('storeno', currentStore.StoreNo);

    //unwire and rewire so the events to pile up.
    $(activePurchasingPanel + ' .ClosestStore_Map').unbind('click');
    $(activePurchasingPanel + ' .ClosestStore_Map').click(function (e) {
        $('#selectedstoreno').val(currentStore.StoreNo);
        $('#findinstoreventsource').val("map");
        ShowFindMoreStores();
    });

    $(activePurchasingPanel + ' .ClosestStore_HomeStore').unbind('click');
    $(activePurchasingPanel + ' .ClosestStore_HomeStore').click(function (e) {
        makeHomeStore(currentStore.StoreNo, currentStore.StoreName, currentStore.StoreZipcode);
    });

    if (currentStore.TotalRows > 1) {
        $(activePurchasingPanel + ' .ClosestStore_FindMoreStores').unbind('click');
        $(activePurchasingPanel + ' .ClosestStore_FindMoreStores').click(function (e) {
            $('#selectedstoreno').val("");
            $('#findinstoreventsource').val("findmore");
            SetHiddenSelectedInfo();
            ShowFindMoreStores();
        });
        $(activePurchasingPanel + ' .ClosestStore_FindMoreStores').parent().show();
        $(activePurchasingPanel + ' .AvailableInStoreTitle').html("<h2>Available In-Store</h2>");
    }
    else {
        $(activePurchasingPanel + ' .AvailableInStoreTitle').html("<h2>Contact Store To Purchase</h2>");
        $(activePurchasingPanel + ' .ClosestStore_FindMoreStores').parent().hide();

    }


    $(activePurchasingPanel + ' .ClosestStore_Email').unbind('click');
    $(activePurchasingPanel + ' .ClosestStore_Email').click(function (e) {
        var storeno;
        var storename;
        var contacttype;
        var seloption;
        var selsernum;
        seloption = $(activePurchasingPanel + " .selOptionInfo option:selected").val();
        selsernum = $(activePurchasingPanel + " .serialItemno option:selected").attr("itemno");
        storeno = $(activePurchasingPanel + ' .ClosestStore_Email').attr("storeno");
        storename = $(activePurchasingPanel + ' .ClosestStore_Email').attr("storename");
        showEmailManagerForm($(activePurchasingPanel + ' .ClosestStore_Email').attr("storeno"), $(this).attr("storename"), $(this).attr("contacttype"));
    });
    //gotta do this because a store location would have changed
    SetCurrentlyViewingOptionText();

}

function SetCurrentlyViewingOptionText() {
    var currentlyViewingOption;
    var selectedOption;
    var optionName;

    var selectedOption = $(activePurchasingPanel + " .selOptionInfo option:selected");
    //var selectedSerialNumber = $(activePurchasingPanel + " .serialItemno option:selected").val();
    var selectedSerialNumber = $('#selectedserialno').val();
    optionName = selectedOption.attr("name");
    if ($(activePurchasingPanel + " .spanOptionName").is(':visible')) {
        optionName = $(activePurchasingPanel + " .spanOptionName").html();
    }
    if (selectedSerialNumber != undefined && selectedSerialNumber != "") {
        optionName = optionName + " Serial # " + selectedSerialNumber;
    }
    currentlyViewingOption = GetCurrentlyViewingOptionName(optionName);
    if (currentlyViewingOption != "") {
        $(activePurchasingPanel + ' .currentOption').html(currentlyViewingOption);
        $(activePurchasingPanel + ' .currentlyViewing').show();
    }
    else {
        $(activePurchasingPanel + ' .currentlyViewing').hide();
    }
}

function SetTabsDropDownDisplay() {
    //If we only have 1 option then just select that option, hide the combo associate with that option and set a label that has that option name
    //also show the serial number associated with that option if they exist.
    var numOptions;
    numOptions = $(activePurchasingPanel + ' .itemno option').size();
    $(activePurchasingPanel + ' .spanOptionName').hide();

    if (numOptions != undefined && numOptions == 2) {
        var firstitemno = $(activePurchasingPanel + " .itemno option:nth-child(2)");
        var itemno = firstitemno.val();
        var optionText = $(firstitemno).text();
        if (optionText != undefined) {
            optionText = optionText.toUpperCase();
        }
        if (optionText != undefined && optionText != "STANDARD") {
            $(activePurchasingPanel + ' .spanOptionName').show();
            SetCurrentlyViewingOptionText();
        }
        var option;
        if (activePurchasingPanel != "#purchasing-store") {
            option = $(activePurchasingPanel + ' .options-box .list-wrapper .option' + itemno);
        }
        else {
            $(activePurchasingPanel + ' .spanOptionName').show();
            option = $(activePurchasingPanel + ' .options-box-locator .list-wrapper .option' + itemno);
        }
        option.click();
        $(activePurchasingPanel + ' .serial' + itemno).show();
        $(activePurchasingPanel + ' .spanOptionName').html($(option).html());
        $(option).parent().parent().parent().hide();
        $(activePurchasingPanel + ' .itemno').val(itemno);
    }
}
function ClearnExternalSystemId(extsysid) {
    var cleanid;
    if (extsysid != undefined) {
        cleanid = extsysid.replace("_C", "");
        cleanid = cleanid.replace("_V", "");
        cleanid = cleanid.replace("_U", "");
        cleanid = cleanid.replace("_P", "");
    }
    return cleanid;
}

(function ($) {
    $.fn.lazyload = function (options) {
        var settings = { threshold: 0, failurelimit: 0, event: "scroll", effect: "show", container: window }; if (options) { $.extend(settings, options); }
        var elements = this; if ("scroll" == settings.event) { $(settings.container).bind("scroll", function (event) { var counter = 0; elements.each(function () { if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) { } else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) { $(this).trigger("appear"); } else { if (counter++ > settings.failurelimit) { return false; } } }); var temp = $.grep(elements, function (element) { return !element.loaded; }); elements = $(temp); }); }
        this.each(function () {
            var self = this; if (undefined == $(self).attr("original")) { $(self).attr("original", $(self).attr("src")); }
            if ("scroll" != settings.event || undefined == $(self).attr("src") || settings.placeholder == $(self).attr("src") || ($.abovethetop(self, settings) || $.leftofbegin(self, settings) || $.belowthefold(self, settings) || $.rightoffold(self, settings))) {
                if (settings.placeholder) { $(self).attr("src", settings.placeholder); } else { $(self).removeAttr("src"); }
                self.loaded = false;
            } else { self.loaded = true; }
            $(self).one("appear", function () {
                if (!this.loaded) {
                    $("<img />").bind("load", function () {
                        $(self).hide().attr("src", $(self).attr("original"))
[settings.effect](settings.effectspeed); self.loaded = true;
                    }).attr("src", $(self).attr("original"));
                };
            }); if ("scroll" != settings.event) { $(self).bind(settings.event, function (event) { if (!self.loaded) { $(self).trigger("appear"); } }); }
        }); $(settings.container).trigger(settings.event); return this;
    }; $.belowthefold = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).height() + $(window).scrollTop(); } else { var fold = $(settings.container).offset().top + $(settings.container).height(); }
        return fold <= $(element).offset().top - settings.threshold;
    }; $.rightoffold = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).width() + $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left + $(settings.container).width(); }
        return fold <= $(element).offset().left - settings.threshold;
    }; $.abovethetop = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollTop(); } else { var fold = $(settings.container).offset().top; }
        return fold >= $(element).offset().top + settings.threshold + $(element).height();
    }; $.leftofbegin = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left; }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    }; $.extend($.expr[':'], { "below-the-fold": "$.belowthefold(a, {threshold : 0, container: window})", "above-the-fold": "!$.belowthefold(a, {threshold : 0, container: window})", "right-of-fold": "$.rightoffold(a, {threshold : 0, container: window})", "left-of-fold": "!$.rightoffold(a, {threshold : 0, container: window})" });
})(jQuery);


$(document).ready(function () {

    $(".btnAddToCartId").removeAttr('disabled');
    $(".btnAddToWishId").removeAttr('disabled');
    $('.btnAddToCartId').each(function (index) {
        $(this).removeClass('redGCBtnInactive');
    });
    $('.btnAddToWishId').each(function (index) {

        $(this).removeClass('grayGCBtnInactive');
    });

    $(".mediagallery img").lazyload({
        placeholder: "/Includes/GuitarCenter/Images/largespacer.gif",
        effect: "fadeIn",
        threshold: 5
    });
    $("#accessories-module img").lazyload({
        placeholder: "/Includes/GuitarCenter/Images/largespacer.gif",
        effect: "fadeIn",
        threshold: 5
    });
    $(".accessories-list img").lazyload({
        placeholder: "/Includes/GuitarCenter/Images/largespacer.gif",
        effect: "fadeIn",
        threshold: 5
    });
    $("#user-gen-module img").lazyload({
        placeholder: "/Includes/GuitarCenter/Images/largespacer.gif",
        effect: "fadeIn",
        threshold: 5
    });


    if ($('.itemno option').length > 1) {
        $('.options-box select').sexyCombo(
            {
                changeCallback: function () {
                    var txtvalue;
                    txtvalue = this.getTextValue();
                    if (txtvalue.indexOf("Serial #") == -1) {
                        hiddenvalue = this.getHiddenValue();
                        if (this.getHiddenValue() != "" && activePurchasingPanel != '#purchasing-store') {
                            $(activePurchasingPanel + ' .spnSerialized  .list-wrapper .option').click();
                        }
                    }
                }
            });

        $('.options-box-locator select').sexyCombo(
        {
            textChangeCallback: function () {
                if (activePurchasingPanel != "#purchasing-store") {
                    return;
                }
                var txtvalue;
                txtvalue = this.getTextValue();
                if (txtvalue.indexOf("Serial #") != -1 || txtvalue.indexOf("Please select a serial number") != -1) {
                    //$(activePurchasingPanel + ' .serialItemno').val(this.getHiddenValue());
                    $('#selectedserialno').val(this.getHiddenValue());

                    btnInvSearchClick(true);
                }

            },
            changeCallback: function () {
                if (activePurchasingPanel != "#purchasing-store") {
                    return;
                }
                var txtvalue;
                txtvalue = this.getTextValue();
                if (txtvalue.indexOf("Serial #") == -1) {
                    //In here because a parent option sexy combo value changed.
                    hiddenvalue = this.getHiddenValue();
                    if (this.getHiddenValue() != "") {
                        $('#purchasing-store .itemno').val(this.getHiddenValue());
                        $('#selecteditemno').val(this.getHiddenValue());
                        btnInvSearchClick(true);
                    }
                }
            }
        });
    }


    if ($('#accessories-module select').length > 0) {
        $('#accessories-module select').each(function (index, domEle) {
            if ($(domEle).find('option').length > 1) {
                $(domEle).sexyCombo();
            }
        });
    }

    $('#accessories').bxSlider({ nextid: 'accessorynext', previd: 'accessoryprev', alignment: 'horizontal', controls: true, speed: 800, pager: true, pager_short: false, pager_short_separator: ' / ', main_width: 316, main_positioning: -336, margin: 20, next_text: 'Next Item &raquo;', next_image: '', prev_text: '&laquo; Prev Item', prev_image: '', auto: false, pause: 3500, auto_direction: 'next', auto_hover: true, auto_controls: false, ticker: false, ticker_controls: false, ticker_direction: 'next', ticker_hover: true, stop_text: 'stop', start_text: 'start', wrapper_class: 'bxslider_wrap' });
    $('#photoUploadForm').ajaxForm({
        dataType: 'json',
        beforeSubmit: function (a, f, o) {
            var bIsValid = true;
            $('.photoForm .required').each(function (index, domEle) {
                if ($(domEle).val() == "") {
                    $(domEle).addClass("errorReq");
                    $("<span class=pError>* required</span>").insertAfter(domEle);
                    bIsValid = false;
                }
            });
            return bIsValid;
        },
        success: function (data) {
            res = data.d;
            if (res.IsError) {
                $('.photoError').html(res.ErrorMsg).show();
            }
            else {
                $('.photoForm').hide();
                $('.photoConfirm').show();
            }
        },
        error: function (data) {
            $('.photoError').show("There has been an error with your request.  This has been reported to the technical team.");
        }
    });

    $('#videoUploadForm').ajaxForm({
        beforeSubmit: function (a, f, o) {
            var bIsValid = true;

            $('.videoForm .required').each(function (index, domEle) {
                if ($(domEle).val() == "") {
                    $(domEle).addClass("errorReq");
                    $("<span class=pError>* required</span>").insertAfter(domEle);
                    bIsValid = false;
                }

            });
            return bIsValid;

        },
        dataType: 'json',
        success: function (data) {
            res = data.d;
            if (res.IsError) {
                $('.videoError').html(res.ErrorMsg).show();
            }
            else {
                $('.videoForm').hide();
                $('.videoConfirm').show();
            }
        },
        error: function (data) {
            $('.videoError').show("There has been an error with your request.  This has been reported to the technical team.");
        }
    });

    $('#purchasing-module').tabs({
        show: function (event, ui) {
            activePurchasingPanel = "#" + ui.panel.id;
            var isValid = true;
            if (activePurchasingPanel == "#purchasing-store") {
                validateInvForm(true);
                SetFindInStoreToSelectedItem();
            }
            else {
                //reset last findinstoreevent
                $('#findinstoreventsource').val("");
                //Reset the serial number back to empty
                SetHiddenSelectedInfo();
            }
            SetTabsDropDownDisplay()
            if (activePurchasingPanel != "#purchasing-store") {
                var extSysId;
                var selsernum;
                var seloptionstatus;
                extSysId = $("#selectedextsysid").val();
                selsernum = $("#selectedserialno").val();
                seloptionstatus = $("#selectedoptionstatus").val();
                var externalSystemId;
                externalSystemId = ClearnExternalSystemId(extSysId);
                if (externalSystemId.length == 9) {
                    loadNearstStoreFromServerGeoCodeValues(externalSystemId, selsernum, seloptionstatus, "true");
                }
                else {

                    loadNearstStoreFromServerGeoCodeValues(externalSystemId, selsernum, seloptionstatus, "false");
                }
                if ($('#selectedserialno').val() == "") {
                    $(activePurchasingPanel + ' .spnSerialized  .list-wrapper .option').click();
                }
                if ($(activePurchasingPanel + ' #photo-gallery .thumb').length == 0
                    && $(activePurchasingPanel + ' #customer-photo-gallery .thumb').length == 0
                    && $(activePurchasingPanel + ' #video-gallery-carousel .thumb').length == 0) {
                    $(activePurchasingPanel + ' .hrefMediaUpload').click();
                    $(activePurchasingPanel + ' .hrefMediaUpload').parents('li').addClass('ui-tabs-selected');
                    $(activePurchasingPanel + ' .hrefMediaUpload').parents('li').addClass('ui-tabs-active');

                }
            }
            return isValid;
        }
    });

    var itemno = readCookie("selitemno");
    var selTab = "";
    var foundOption = false;
    if (itemno != null) {
        jQuery.each($('.purchasing-panel .selOptionInfo'), function () {
            jQuery.each($('#' + this.id + ' option'), function () {
                if (this.value == itemno && !foundOption) {
                    foundOption = true;
                }
            });
            if (foundOption) {
                selTab = '#' + $('#' + this.id).parent().parent().attr('id');
                return false;
            }
        });
    }

    if (window.location.href.indexOf('#used') > -1) {
        selTab = '#purchasing-used';
    }

    var index = -1;
    var tabIndex = -1;
    jQuery.each($('#purchasing-module ul:first li a'), function () {
        index++;
        var curHref = this.href.substring(this.href.indexOf('#'));
        if (curHref == selTab) {
            tabIndex = index;
        }
    });



    if (tabIndex > -1) {
        activePurchasingPanel = selTab;
        $('#purchasing-module').tabs('select', selTab);
    }



    //serialnumber options
    $('.serialItemno').change(function () {
        if (activePurchasingPanel != "#purchasing-store") {
            var serialnumber = $(this).val();
            if (serialnumber) {
                var sMedImage;
                var sZoomImage;
                var id = $(this).attr('id');
                sMedImage = $('#' + id + ' :selected').attr('MediumImg');
                sZoomImage = $('#' + id + ' :selected').attr('ZoomImg');
                var selectedchilditemno;
                selectedchilditemno = $('#' + id + ' :selected').attr('itemno');
                $("#selectedchilditemno").val(selectedchilditemno);
                swapSerialOptionImages(sMedImage, sZoomImage, serialnumber);
            }
            var sExtSysId = $("#selectedextsysid").val();
            var seloptionstatus = $("#selectedoptionstatus").val();
            $("#selectedserialno").val(serialnumber);
            loadNearstStoreFromServerGeoCodeValues(sExtSysId, serialnumber, seloptionstatus, "true");
        }
    });

    // regular options
    $('.itemno').change(function () {
        showOptionInfo();
        var itemno = $(this).val();
        var selectedOption;
        $(activePurchasingPanel + ' .selOptionInfo option').each(function (index) {
            if ($(this).val() == itemno) {
                selectedOption = $(this);
            }
        });
        $(activePurchasingPanel + ' .selOptionInfo').val(itemno);

        var sExtSysId;
        var serialNo;
        var isSerializedOption;
        var isInventory;
        var InventoryText;
        var sOptionStatus
        isInventory = $(selectedOption).attr("IsInventoryProduct");
        sExtSysId = $(selectedOption).attr("sExtSysId");
        sOptionStatus = $(selectedOption).attr("OptionStatus");
        InventoryText = $(selectedOption).attr("InventoryText");

        if (InventoryText != undefined && InventoryText != "") {
            if (InventoryText.indexOf("Available") != -1) {
                $(activePurchasingPanel + ' .in-stock').html(InventoryText);
                $(activePurchasingPanel + ' .instock').show();
                $(activePurchasingPanel + ' .outofstock').hide();
                $(activePurchasingPanel + ' .in-stock').show();
            }
            else {
                $(activePurchasingPanel + ' .out-of-stock').html(InventoryText);
                $(activePurchasingPanel + ' .instock').hide();
                $(activePurchasingPanel + ' .outofstock').show();
                $(activePurchasingPanel + ' .out-of-stock').show();
            }
        }

        $("#selectedextsysid").val(sExtSysId);
        $("#selectedoptionstatus").val(sOptionStatus);
        //probably because the hit please select an option.  default to the default externalsystemid
        if (sExtSysId == undefined) {
            $("#selectedextsysid").val($('hdnExtSysId').val());
            sExtSysId = $('#hdnExtSysId').val();
            isInventory = "true";
        }

        isSerializedOption = $(selectedOption).attr("IsSerialized");
        ///only need to reload when the itemno has changed.  otherwise its the same one
        var isClosestStoreVisible;
        isClosestStoreVisible = $(activePurchasingPanel + ' .ClosestStore').is(':visible');
        var serialsNumberVisible;
        isSerialNumbersVisible = $(activePurchasingPanel + ' .serialItemno').is(':visible');
        if (isSerializedOption) {
            var selectedSerialNumber
            if (isSerialNumbersVisible) {
                selectedSerialNumber = $(".serialItemno option:selected").attr("serialNo");
            }
            else {
                //backwards compatible for MF where serial number is right in the main option. 
                selectedSerialNumber = $(selectedOption).attr("serialNo");
            }
            loadNearstStoreFromServerGeoCodeValues(sExtSysId, selectedSerialNumber, sOptionStatus, isInventory);
        }
        else if ($("#selecteditemno").val() != itemno || !isClosestStoreVisible) {
            loadNearstStoreFromServerGeoCodeValues(sExtSysId, $(selectedOption).attr("serialNo"), sOptionStatus, isInventory);
        }
        $("#selecteditemno").val(itemno);
        $("#selectedextsysid").val(sExtSysId);
        SetCurrentlyViewingOptionText();
    });


    initMediaArea();
    initOtherMedia();
    var buyinstore = $(activePurchasingPanel + ' .phonespecial').html()
    var wasprice = $(activePurchasingPanel + ' .spanWasPrice').html();
    var spanNowPrice = $(activePurchasingPanel + ' .spanNowPrice').html();

    if (wasprice != undefined && wasprice != "" && wasprice == spanNowPrice) {
        $(activePurchasingPanel + ' .wasPriceContainerMain').hide();
    }

    if (buyinstore != undefined && buyinstore != "") {
        $(activePurchasingPanel + ' .wasPriceContainerMain').hide();
    }
    $("#information-module").tabs();
    $("#user-gen-module").tabs();
    $('#history').bxSlider({
        alignment: 'horizontal', controls: true, speed: 800, pager: true, pager_short: false, pager_short_separator: ' / ', main_width: 624, main_positioning: -624, margin: 0, next_text: '', next_image: 'includes/guitarcenter/Images/clear.gif', prev_text: '', prev_image: 'includes/guitarcenter/Images/clear.gif', auto: false, pause: 3500, auto_direction: 'next', auto_hover: true, auto_controls: false, ticker: false, ticker_controls: false, ticker_direction: 'next', ticker_hover: true, stop_text: 'stop', start_text: 'start', wrapper_class: 'bxslider_wrap'
    });
    // Tooltip
    $("#print-this").tooltip({ offset: [11, 44], effect: 'slide', position: 'bottom left', delay: 100 });
    //chrome does not support adding bookmarks via javacript so we show a tooltip on how to do it.
    if (window.chrome) {
        $("#chromebookmark").tooltip({ offset: [11, 44], effect: 'slide', position: 'bottom left', delay: 100 });
    }
    var ua = navigator.userAgent.toLowerCase();
    var isChrome = /\bchrome\b/.test(ua);
    var isSafari = !isChrome && /safari/.test(ua);
    if (isSafari) {
        //we use same chrome bookmark tooltip for safari
        $("#chromebookmark").tooltip({ offset: [11, 44], effect: 'slide', position: 'bottom left', delay: 100 });
    }

    // Button
    $(".button").button();
    $(".button").click(function () { return false; });

    // read and write review toggle

    $("#read").click(function (e) {
        $('.reviewToggle').hide();
        $('#read-reviews').show();
        $('.readwrite').removeAttr("style");
        $(this).attr("style", "color:#333;text-decoration:none");

    });

    $("#write").click(function (e) {
        $('.reviewToggle').hide();
        $('#write-reviews').show();
        $('.readwrite').removeAttr("style");
        $(this).attr("style", "color:#333;text-decoration:none");
    });



    // accessory add to cart
    $('.accessoryAddToCart').click(function (e) {
        addAccessory($(this).attr("containerIndex"));
    });

    // reviews
    if (parseInt($('.hdnReviewsCount').val()) > 0) {
        //getReviews(1, $('.reviewSortOptions').val());
    }
    else {
        $('.reviews-header').hide();
        $('#reviews-none').show();
    }
    initReviews();

    $('.hrefKitAddCart').click(function (e) {
        kitAddToCart();
    });


    // list price containers show/hide
    if ($('.listpricecontainerMain').is(':visible')) {
        $('.listpricecontainer').each(function (index, domEle) {
            $(domEle).show();
        });
    }

    // was price containers show/hide
    if ($('.waspricecontainerMain').is(':visible')) {
        $('.waspricecontainer').each(function (index, domEle) {
            $(domEle).show();
        });
    }


    // save containers show/hide
    if ($('.savepricecontainerMain').is(':visible')) {
        $('.savepricecontainer').each(function (index, domEle) {
            $(domEle).show();
        });
    }

    // manage height on accessores/at a glance
    var accessoryHeight = $('#accessories-module').height();
    var infoModuleHeight = $('#information-module').height();
    var specsHeight = $('#specifications').height();
    var warrantyHeight = $('#warranty').height();
    var nFinalHeight = 0;

    if (accessoryHeight > nFinalHeight)
        nFinalHeight = accessoryHeight;

    if (infoModuleHeight > nFinalHeight)
        nFinalHeight = infoModuleHeight;

    if (specsHeight > nFinalHeight)
        nFinalHeight = specsHeight;

    if (warrantyHeight > nFinalHeight)
        nFinalHeight = warrantyHeight;
    $('.photo-viewer').show();
    $('.video-viewer').hide();

    //we don't have at least a second list so no scrolling so hide the contoller
    if ($(".acc1").length == 0) {
        $('.bx_pager').hide();
        $('#accessoryprev').hide();
        $('#accessorynext').hide();
    }

    if ($(".acc1").length == 0) {
        $('.bx_pager').hide();
        $('#accessoryprev').hide();
        $('#accessorynext').hide();
    }


    var slideCount = $(".bullet").length;

    if (slideCount == 1) {
        $('.bx_pager').hide();
        $('#accessoryprev').hide();
        $('#accessorynext').hide();
    }
    $('.stickers-b').hide();
    var hdnExtSysId = $('#hdnExtSysId').val();
    var hdnIsInventoryProduct = $('#hdnIsInventoryProduct').val();
    hideBrokenImages();

    $('.video').append('<img src="/includes/guitarcenter/Images/play.png" class="vidplay" height="16" width="16" alt="" />');
    //$(".ui-tabs-nav-v2").tabs("div.parentPane div.panes", { history: true, selected: 2});

    $(".ui-tabs-nav-v2").tabs();
    equalHeight($("#other-media-content .equalHeight"));
    $(".equalHeight:not(:has(h3))").css('display', 'none');
    ShowSharingUploadForm();
    SetCurrentlyViewingOptionText();
    //AdjustExternalMediaReferences();
    //InitAjaxForms();
});


function AdjustExternalMediaReferences() {
    $('#other-media-content a').each(function (index) {
        var reflink;
        reflink = $(this).attr('href');
        reflink = reflink.replace("musiciansfriend", "guitarcenter");
        $(this).attr('target', "_blank");
        $(this).attr('href', reflink);
    });
}

function swapSerialOptionImages(sMedImg, sZoomImg, serialItemNo) {
    if (serialItemNo != undefined) { // style image (pertains to specific ssrial option)
        if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {
            $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
            $(activePurchasingPanel + ' .hrefZoomImg').attr("href", sZoomImg);
            initCloudZoom();
        }
    }
}



function swapOptionImages(sMedImg, sZoomImg, itemno, filesrc, serialnumber) {
    //alert(itemno);
    if (itemno != undefined) { // style image (pertains to specific option)
        if (serialnumber != undefined && serialnumber != '') {
            //Get parent
            //serialItemno
            var optionserial;
            var parentitemno;
            jQuery.each($(activePurchasingPanel + ' .serialItemno option'), function () {
                optionserial = $(this).attr('serialno');
                //Get Parent Option.
                if (optionserial == serialnumber) {
                    parentitemno = $(this).attr('parentitemno');
                }
            });
            $(activePurchasingPanel + ' .options-box .list-wrapper .option' + parentitemno).click();
            $(activePurchasingPanel + ' .options-box .list-wrapper .option' + serialnumber).click();
            $(activePurchasingPanel + ' .currentlyViewing').show();
        }
        else {
            if ($(activePurchasingPanel + ' .options-box .list-wrapper .option' + itemno).html() != null && $(activePurchasingPanel + ' .options-box .list-wrapper .option' + itemno).html() != "") {

                $(activePurchasingPanel + ' .options-box .list-wrapper .option' + itemno).click();
                $(activePurchasingPanel + ' .currentlyViewing').show();
            }
        }

        if (!$(activePurchasingPanel + ' .options-box .list-wrapper').is('visible')) {
            $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
            $(activePurchasingPanel + ' .hrefZoomImg').attr("href", sZoomImg);
            if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {
                initCloudZoom();
            }
            else {
                if (filesrc != null && filesrc != '') {
                    $(activePurchasingPanel + ' .optionimage').attr("src", filesrc);
                    $(activePurchasingPanel + ' .hrefZoomImg').attr("href", filesrc);
                    initCloudZoom();
                }
            }
        }

        if (itemno == 0) {
            $(activePurchasingPanel + ' .options-box .list-wrapper .option ').click();
            $(activePurchasingPanel + ' .currentOption').html("Default Option");
            $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
            $(activePurchasingPanel + ' .hrefZoomImg').attr("href", sZoomImg);
            if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {
                initCloudZoom();
            }
            $(activePurchasingPanel + ' .currentlyViewing').hide();
        }
    }
    else { // detail image (default option)
        //default the option box to the first item.
        $(activePurchasingPanel + ' .options-box .list-wrapper .option ').click();
        $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
        $(activePurchasingPanel + ' .hrefZoomImg').attr("href", sZoomImg);
        if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {

            initCloudZoom();
        }
    }
}

function ShowSharingUploadForm() {
    //if uploadtype parameter is on query string then set that tab as visible.  This happens when a user logins from the upload video photo form.
    var sUrl = window.location.search;
    if (sUrl != undefined && sUrl != "") {
        var uploadType = gup('uploadtype', sUrl);
        if (uploadType != undefined && sUrl != "") {
            var found = false;
            if (uploadType == "video") {
                showVideoForm();
                found = true;
            }
            else if (uploadType == "photo") {
                showPhotoForm();
                found = true;

            }
            if (found == true) {
                $('.hrefMediaUpload').parents('li').addClass('ui-tabs-selected');
                $('.hrefMediaUpload').parents('li').addClass('ui-tabs-active')
            }
        }
    }
}

function hideBrokenImages() {
    $('.slider-item').each(function (index) {
        if (($(this).find("img").attr("src") == "http://images.guitarcenter.com/") || ($(this).find("img").attr("src") == "http://images.test.miretail.com/")) {
            $(this).hide();
        }
    });
}

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);
}

//make our link call create cookie first the continue with url
function DetailPage(ctrl, itemno) {
    if (itemno != null) {
        createCookie("selitemno", itemno, 0);
    }
    return true;
}

/* media stuff */


function initMediaArea() {

    $('.purchasing ').each(function () {
        var panel;
        panel = "#" + $(this).attr('id');
        if ($(panel + ' #photo-gallery .thumb').length == 0) {
            panel = "#" + $(this).attr('id');
            $(panel + ' .our-photo-slider-code').hide();
            $(panel + ' .our-photo-slider-code-commingsoon').show();
            //if there are videos keep if visible.  Otherwise hide this tab.  If videos we keep it visible to we can get back to the 
            //the default image.
            if ($(panel + ' #video-gallery-carousel .thumb').length == 0) {
                $(panel + ' .ourphotostab').hide();
            }
        }
        else {
            $(panel + ' .our-photo-slider-code').show();
            $(panel + ' .our-photo-slider-code').gcCarousel({ display: 5 });
            $(panel + ' .our-photo-slider-code-commingsoon').hide();
            var firstimage;
            //Set first image in zoom area if its valid
            firstimage = $(panel + ' #photo-gallery .slider-item a:first');
            if (firstimage != null) {
                var sMedImg = firstimage.attr('smedimg');
                var sZoomImg = firstimage.attr('szoomimg');
                if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {
                    //Commented out for now until we figure how to get the default image into the carousel
                    //$(panel + ' .optionimage').attr("src", sMedImg);
                    //$(panel + ' .hrefZoomImg').attr("href", sZoomImg);
                    //initCloudZoom();
                }
            }
        }
        if ($(panel + ' #customer-photo-gallery .thumb').length == 0) {
            $(panel + ' .customerphotostab').hide();
            $(panel + ' .customer-photo-slider-code').hide();
        }
        else {
            $(panel + ' .customer-photo-slider-code').show();
            $(panel + ' .customer-photo-slider-code').gcCarousel({ display: 5 });
        }

        if ($(panel + ' #video-gallery-carousel .thumb').length == 0) {
            $(panel + ' .our-video-slider-code').hide();
        }
        else {
            $(panel + ' .our-video-slider-code').show();
            $(panel + ' .our-video-slider-code').gcCarousel({ display: 5 });
        }
        if (panel == "#purchasing-used" || panel == "#purchasing-retailused" || panel == "#purchasing-vintage") {
            $(panel + ' .hrefMediaUpload').hide();
        }


        /// cloud zoom
        if ($(panel + ' .hrefZoomImg').attr("href") != "" && $(panel + ' .hrefZoomImg').attr("href") != undefined && IsValidImagePath($(panel + ' .hrefZoomImg').attr("href"))) {
            $(panel + ' .mousetrap').remove();
            $(panel + ' .cloud-zoom').CloudZoom();
        }
        //$(panel + ' .placeholderimage').hide();

    });

    $('.hrefMediaVideos').click(function (e) {
        $('.video:first').click();
        $('.video-viewer').show();
        $('.photo-viewer').hide();
    });

    $('.hrefMediaCustomerPhotos').click(function (e) {
        $('.video-viewer').hide();
        $('.photo-viewer').show();
        $('.customerPhotos').show();
        $('.ourPhotos').hide();

        if ($(activePurchasingPanel + ' .customer-photo-gallery .thumb').length == 0) {
            $(activePurchasingPanel + ' #customer-photo-slider-code').hide();
        }
        if ($(activePurchasingPanel + ' .customer-photo-gallery .slider-item a').length > 0) {
            $(activePurchasingPanel + ' .customer-photo-gallery .slider-item a:first').click();
        }
    });

    $('.hrefMediaPhotos').click(function (e) {
        $('.video-viewer').hide();
        $('.photo-viewer').show();
        if ($(activePurchasingPanel + ' #photo-gallery .thumb').length == 0) {
            $(activePurchasingPanel + ' #our-photo-slider-code').hide();
        }

        if ($(activePurchasingPanel + ' #photo-gallery .slider-item a').length > 0) {
            $(activePurchasingPanel + ' #photo-gallery .slider-item a:first').click();
        }
        else {
            //$(activePurchasingPanel + ' #currentlyViewing').hide();
        }
    });

}


function showVideoForm() {
    $(activePurchasingPanel + ' .upload .option-header a').removeAttr("style");
    $(activePurchasingPanel + ' .divUploadVideo').show();
    $(activePurchasingPanel + ' .divUploadPhoto').hide();
    $('.videoForm').show();
    $('.videoConfirm').hide();
    $("input#txtExternalVideoUrl").val("");
    $("input#txtExternalVideoTitle").val("");
    $("#submitvideolink").attr('style', 'color:#333;text-decoration:none');
}
function showPhotoForm() {
    $(activePurchasingPanel + ' .upload .option-header a').removeAttr("style");
    $(activePurchasingPanel + ' .divUploadVideo').hide();
    $(activePurchasingPanel + ' .divUploadPhoto').show();
    $(activePurchasingPanel + ' .photoConfirm').hide();
    $('.photoForm').show();
    $('.photoConfirm').hide();
    $("input#txtPhotoFile").val("");
    $("input#txtPhotoTitle").val("");
    $("#submitphotolink").attr('style', 'color:#333;text-decoration:none');
}


/* option stuff */

function GetCurrentlyViewingOptionName(optionname) {
    var formatted;
    formatted = optionname;
    //only tack on city and state to option name when there is a store showing and its not a new product.
    if ($(activePurchasingPanel + ' .ClosestStore').is(':visible') && activePurchasingPanel != "purchasing-new") {
        var city;
        var state;
        city = $(activePurchasingPanel + ' .ClosestStore_City').html();
        state = $(activePurchasingPanel + ' .ClosestStore_State').html();
        formatted = formatted + ' ' + city + ', ' + state;
    }
    return formatted;
}

function IsValidImagePath(path) {
    var isvalid = true
    if (path == null)
        return false;
    if (path.length == 0)
        return false;
    if (path.toUpperCase().indexOf(".JPG") > 0)
        return true;
    if (path.toUpperCase().indexOf(".GIF") > 0)
        return true;
    if (path.toUpperCase().indexOf(".PNG") > 0)
        return true;
    return false;
}

function showOptionInfo(itemno, bIgnoreImage, serialNo) {
    var bIgnoreImageChange = false;
    var bShowAvailability = false;
    if (bIgnoreImage != undefined) {
        bIgnoreImageChange = bIgnoreImage;
    }
    var nSelectedOptionItemno = "";
    var bIsSerial = false;
    if (serialNo != undefined && serialNo != "") {
        //nSelectedOptionItemno = serialNo;
        bIsSerial = true;
        currentSelectedSerialNo = serialNo;

    }
    else {
        if (itemno == undefined)
            nSelectedOptionItemno = $(activePurchasingPanel + ' .itemno option:selected').val();
        else
            nSelectedOptionItemno = itemno;
        // "please select" option
        if (nSelectedOptionItemno == "") {
            nSelectedOptionItemno = 0;
        }
    }
    // hide inventory statuses
    $(activePurchasingPanel + ' .invStatus').hide();
    // loops through list of options, finds selectedOption
    var selectedOption = null;
    $(activePurchasingPanel + ' .selOptionInfo option').each(function (index) {
        if (bIsSerial) {
            if ($(this).attr("serialNo") == nSelectedOptionItemno) {
                selectedOption = $(this);
            }
        }
        else if ($(this).val() == nSelectedOptionItemno) {
            selectedOption = $(this);
        }
    });

    // assign info accordingly
    if (selectedOption != null) {

        if (selectedOption[0].value == 0 && $(activePurchasingPanel + ' .photos-gallery-carousel').is(':visible')) {
            //$('#currentlyViewing').hide();
        }
        var price = selectedOption.attr("price");
        $(activePurchasingPanel + ' .selecteditemno').val(nSelectedOptionItemno);
        $("#selecteditemno").val(nSelectedOptionItemno);
        $("#selectedserialno").val("");
        $(activePurchasingPanel + ' .itemno').val(nSelectedOptionItemno).attr("selected", "selected");
        $(activePurchasingPanel + ' .spanPrice').html(selectedOption.attr("price"));
        if (selectedOption.attr("YouSaveDollar") == undefined) {
            $(activePurchasingPanel + ' .savepricecontainerMain').hide();
        }
        else {
            $(activePurchasingPanel + ' .savepricecontainerMain').show();
        }
        $(activePurchasingPanel + ' .spanListPrice').html(selectedOption.attr("listprice"));
        $(activePurchasingPanel + ' .spanSave').html(selectedOption.attr("YouSaveDollar"));
        $(activePurchasingPanel + ' .spanSavePct').html(selectedOption.attr("YouSavePct"));
        $(activePurchasingPanel + ' .spanShipping').html(selectedOption.attr("shipping"));
        $(activePurchasingPanel + ' .spanNowPrice').html(selectedOption.attr("nowprice"));

        var bIsNewBStock
        bIsNewBStock = selectedOption.attr("IsNewBStock");
        if (bIsNewBStock == "true") {
            $(activePurchasingPanel + ' .NewBStock').show();
        }
        else {
            $(activePurchasingPanel + ' .NewBStock').hide();
        }

        var showAddToCart = selectedOption.attr('displayAddtoCart');
        if (showAddToCart == 'true') {
            $(activePurchasingPanel + ' .AddCartWishListContainer').show();
        }
        else {
            $(activePurchasingPanel + ' .AddCartWishListContainer').hide();
        }
        $(activePurchasingPanel + ' #btnAddToCart').attr('value', selectedOption.attr('addToCartButtonText'));

        if (nSelectedOptionItemno == 0) { // default option
            $(activePurchasingPanel + ' .shippingcontainer').hide();
            $(activePurchasingPanel + ' .inventory-status').hide();
            $(activePurchasingPanel + ' .shippingcontainer').hide();
            $(activePurchasingPanel + ' .secStickers').hide();
            $(activePurchasingPanel + ' .secStickerDefault').show();
            $(activePurchasingPanel + ' .optionimage').attr("src", selectedOption.attr("MediumImg"));
            $(activePurchasingPanel + ' .hrefZoomImg').attr("href", selectedOption.attr("ZoomImg"));
            initCloudZoom();
            var wasprice = selectedOption.attr("wasprice");
            if (wasprice != "" && wasprice != price) {
                $(activePurchasingPanel + ' .spanWasPrice').html(selectedOption.attr("wasprice"));
            }
            else {
                $(activePurchasingPanel + ' .wasPriceContainerMain').hide();
            }
            // serialized
            if ($(activePurchasingPanel + ' .spnSerialized').length > 0) {
                $(activePurchasingPanel + ' .spnSerialized').hide();
                $(activePurchasingPanel + ' .serial' + nSelectedOptionItemno).show();
            }
        }
        else {

            $(activePurchasingPanel + ' .itemno').val(nSelectedOptionItemno);
            $("#selecteditemno").val(nSelectedOptionItemno);
            $("#selectedserialno").val("");
            $(activePurchasingPanel + ' .spanPrice').html(selectedOption.attr("price"));
            $(activePurchasingPanel + ' .spanListPrice').html(selectedOption.attr("listprice"));
            $(activePurchasingPanel + ' .spanSave').html(selectedOption.attr("YouSaveDollar"));
            $(activePurchasingPanel + ' .spanSavePct').html(selectedOption.attr("YouSavePct"));
            if (!bIgnoreImageChange) {
                $(activePurchasingPanel + ' .optionimage').attr("src", selectedOption.attr("MediumImg"));
                $(activePurchasingPanel + ' .hrefZoomImg').attr("href", selectedOption.attr("ZoomImg"));
            }
            SetCurrentlyViewingOptionText();
            $(activePurchasingPanel + ' .spanShipping').html(selectedOption.attr("shipping"));
            var wasprice = selectedOption.attr("wasprice");
            if (wasprice != "" && wasprice != price) {
                $(activePurchasingPanel + ' .spanWasPrice').html(selectedOption.attr("wasprice"));
                $(activePurchasingPanel + ' .wasPriceContainerMain').show();
            }
            else {
                $(activePurchasingPanel + ' .wasPriceContainerMain').hide();
            }
            // shipping
            $(activePurchasingPanel + ' .shippingcontainer').show();

            if (selectedOption.attr("ZoomImg") != "" && IsValidImagePath(selectedOption.attr("ZoomImg"))) {
                $(activePurchasingPanel + ' .mousetrap').remove();
                $(activePurchasingPanel + ' .cloud-zoom').CloudZoom();
            }
            // inventory
            var sOOSText = selectedOption.attr("sOOSText");
            var bIsInStock = selectedOption.attr("IsInStock");

            if (bIsInStock == "true") {
                $(activePurchasingPanel + ' .instock').show();
                $(activePurchasingPanel + ' .in-stock').show();
            }
            else {

                var InventoryText = $(selectedOption).attr("InventoryText");
                if (InventoryText != undefined && InventoryText != "") {

                }
                else {
                    $(activePurchasingPanel + ' .outofstockStatus').html(sOOSText);
                }
                $(activePurchasingPanel + ' .outofstock').show();
            }
            $(activePurchasingPanel + ' .inventory-status').show();
            // secondary stickers
            $(activePurchasingPanel + ' .secStickers').hide();
            $(activePurchasingPanel + ' .secStickers' + nSelectedOptionItemno).show();
            // serialized
            if ($(activePurchasingPanel + ' .spnSerialized').length > 0) {
                $(activePurchasingPanel + ' .spnSerialized').hide();

                $(activePurchasingPanel + ' .serial' + nSelectedOptionItemno).show();
            }
        }
    }

    $(".list-wrapper").css('height', '150px');
    $(".list-wrapper").css('overflow-y', 'auto');

}





function initCloudZoom() {
    if ($(activePurchasingPanel + ' .hrefZoomImg').attr("href") != "" && IsValidImagePath($(activePurchasingPanel + ' .hrefZoomImg').attr("href"))) {
        $(activePurchasingPanel + ' .mousetrap').remove();
        $(activePurchasingPanel + ' .cloud-zoom').CloudZoom();
    }
}

function swapCustomerImage(sId) {
    var selector = activePurchasingPanel + " .photo" + sId;
    var sMedImg = $(selector + " .photoDetails").attr("imgmedium");
    var sZoomImg = $(selector + " .photoDetails").attr("imgzoom");
    var sTitle = "Customer Photo " + $(selector + " .photoDetails").attr("title");
    $(activePurchasingPanel + ' .mousetrap').remove();
    if (sMedImg != undefined && sZoomImg != undefined) {
        $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
        //We disbable zoom for customer pictures
        if (sTitle != "") {
            $(activePurchasingPanel + ' .currentOption').html(sTitle);
            $(activePurchasingPanel + ' .currentlyViewing').show();
        }
        else {
            $(activePurchasingPanel + ' .currentlyViewing').hide();
        }
        if ($(activePurchasingPanel + ' .hrefZoomImg').attr("href") != "") {
            if (IsValidImagePath(sMedImg) && IsValidImagePath(sZoomImg)) {
                $(activePurchasingPanel + ' .optionimage').attr("src", sMedImg);
            }
        }
    }
}

function swapCustomerVideo(sId) {

    var selector = activePurchasingPanel + " .vid" + sId;
    var sUrl = $(selector + " .vidDetails").attr("path");
    var sTitle = $(selector + " .vidDetails").attr("title");

    if (sUrl != undefined && sUrl != "") {
        sVidId = gup('v', sUrl);

        sFinalUrl = "http://www.youtube.com/v/" + sVidId;
        sFinalUrl += "&amp;hl=en_US&amp;fs=1";
        var sVideoHtml = "";
        if (sVidId == "") {
            sVideoHtml = "<p style='color:#AA0000'>Failed to find and load the video.</p>";
        }
        sVideoHtml += "<object height=300 width=620>";
        sVideoHtml += "<param class=movieUrl value=" + sFinalUrl + " name=movie></param>";
        sVideoHtml += "<param value=false name=allowFullScreen></param>";
        sVideoHtml += "<param value=always name=allowscriptaccess></param>";
        sVideoHtml += "<embed src=" + sFinalUrl + " type=application/x-shockwave-flash allowscriptaccess=always allowfullscreen=true width=480 height=300></embed></object>";
        $(activePurchasingPanel + ' .videoContents').html(sVideoHtml).show();
        $('.mediaViewer').show();
        $('.photo-viewer').hide();
        $('.video-viewer').show();
        if (sTitle != "") {
            $(activePurchasingPanel + ' .currentlyViewing').show();
            if (sTitle.length > 50) {
                sTitle = sTitle.substring(0, 50) + "...";
                $(activePurchasingPanel + ' .currentOption').html(sTitle);
            }
            else {
                $(activePurchasingPanel + ' .currentOption').html(sTitle);
            }

        }
        if (sVidId == "") {
            $(activePurchasingPanel + ' .currentOption').html("Failed to load video");
        }
    }
}

function gup(name, url) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}

/* reviews */

function sortReviews() {
    if ($('.reviewSortOptions').val() != "0") {
        getReviews(1, $('.reviewSortOptions').val());
    }
}

function getReviewsNext() {
    var nStartIndex = parseInt($('#viewReviewsEnd').html()) + 1;
    getReviews(nStartIndex, $('.reviewSortOptions').val());
}

function getReviewsPrev() {
    var nStartIndex = parseInt($('#viewReviewsStart').html()) - 3;
    getReviews(nStartIndex, $('.reviewSortOptions').val());
}

function getReviews(nStartIndex, nSortOption) {
    $('.reviewResultsLoading').show();

    // clear existing review set
    $("#reviews-slider .slide").remove();
    $('.reviewsContainer').html("<ul id=reviews-slider><li></li></ul>");

    nPageSize = 3;
    if (nStartIndex == undefined) {
        nStartIndex = 0;
    }
    if (nSortOption == undefined || nSortOption == "" || nSortOption == 0) {
        nSortOption = 1;
        $(".reviewSortOptions").val('1').attr("selected", "selected");
    }

    var params = {
        startIndex: nStartIndex,
        pageSize: nPageSize,
        productId: parseInt($('.hdnProductId').val()),
        nSortOptionId: parseInt(nSortOption),
        nItemNumber: parseInt($('.hdnDefaultItemno').val())
    };


    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/ajax/itemend/ItemEndService.svc/getReviews",
        data: params,
        success: function (response) {
            loadReviews(response, nSortOption);
        },
        error: function (xhr, status, error) {
        }
    });

}

function loadReviews(res, nSortOption) {
    try {
        $('.reviewsContainer').html("<ul id=reviews-slider><li></li></ul>");
        var reviews = res.d.Reviews;

        var nSlideOffset = 3;
        var nChange = 2;
        var reviewSlide = "";
        var startSlide = "<li class=slide><ul class=reviews>";
        var endSlide = "</ul></li>";
        var finalMarkupInsert = "";

        if (nSortOption == 5) {
            reviews.reverse();
        }
        for (var i = 0; i < reviews.length; i++) {
            var reviewTemplate = $('.reviewTemplate').html(); ;
            reviewTemplate = reviewTemplate.replace("|comments|", reviews[i].Comments);
            reviewTemplate = reviewTemplate.replace("|id|", reviews[i].Id);
            reviewTemplate = reviewTemplate.replace("|id2|", reviews[i].Id);
            reviewTemplate = reviewTemplate.replace("|id3|", reviews[i].Id);
            reviewTemplate = reviewTemplate.replace("|name|", reviews[i].Name);
            reviewTemplate = reviewTemplate.replace("|ratingimage|", "<img src='includes/guitarcenter/Images/" + reviews[i].Rating + "-stars.png' class='customer-rating-stars' />");
            reviewTemplate = reviewTemplate.replace("|summary|", reviews[i].Summary);
            reviewTemplate = reviewTemplate.replace("|createddate|", reviews[i].CreatedDate);
            reviewTemplate = reviewTemplate.replace("|totalratecount|", reviews[i].TotalRateCount);
            reviewTemplate = reviewTemplate.replace("|totalratepositive|", reviews[i].TotalRatePositive);
            if (nSortOption == 5) {  // best v. worst
                if (i == 0) {  // best
                    reviewTemplate = reviewTemplate.replace("|bestworst|", "<img src=\"includes/guitarcenter/images/icons/comment-good.png\" class=\"review-comment\" /><label class=\"label-right\">Most Helpful Positive Review</label><div class=\"clear\"></div>");
                    reviewTemplate = "<div class=\"reviews best-left\">" + reviewTemplate + "</div><div class=\"vs-divider\"></div>";
                }
                if (i == 1) {
                    reviewTemplate = reviewTemplate.replace("|bestworst|", "<img src=\"includes/guitarcenter/images/icons/comment-bad.png\" class=\"review-comment\" /><label class=\"label-right\">Most Helpful Negative Review</label><div class=\"clear\"></div>");
                    reviewTemplate = "<div class=\"reviews worst-right\">" + reviewTemplate + "</div>";
                }
            }
            else {
                reviewTemplate = reviewTemplate.replace("|bestworst|", "");
            }

            reviewSlide += reviewTemplate;

            if (i == nChange || i == (reviews.length - 1)) {
                // wrap it
                reviewSlide = startSlide + reviewSlide + endSlide;
                finalMarkupInsert += reviewSlide;

                // reset
                reviewSlide = "";
                nChange += nSlideOffset;
            }


        }
        $('#reviews-slider').html(finalMarkupInsert);
        $('.reviewResultsLoading').hide();

        var nStartRecordNo = res.d.StartRecordNo == 0 ? "1" : res.d.StartRecordNo;
        $('#viewReviewsStart').html(nStartRecordNo);
        $('#viewReviewsEnd').html(res.d.EndRecordNo);
        $('.reviewTotal').html(res.d.TotalNumberOfRows);

        if (res.d.StartRecordNo == 1) {
            $('#hrefReviewsPrev').hide();
        }
        else {
            $('#hrefReviewsPrev').show();
        }

        if (res.d.EndRecordNo == res.d.TotalNumberOfRows) {
            $('#hrefReviewsNext').hide();
        }
        else {
            $('#hrefReviewsNext').show();
        }

        initReviews();

    }
    catch (err) { }

}

function initReviews() {
    // truncate comments
    $('#reviewsContainer .comments').each(function (index, domEle) {
        $(this).jTruncate({
            length: 500,
            minTrail: 10,
            moreText: 'Read Full Review',
            lessText: 'show less',
            moreAni: "fast",
            ellipsisText: "..."
        });
    });

    $('.rateReviewYes').click(function (e) {
        rateReview(1, $(this).attr("id"));
    });

    $('.rateReviewNo').click(function (e) {
        rateReview(0, $(this).attr("id"));
    });

    if (parseInt($('.hdnReviewsCount').val()) <= 3) {
        $('#hrefReviewsNext').hide();
        $('#hrefReviewsPrev').hide();
        $('#viewReviewsEnd').html($('.hdnReviewsCount').val());
        $('.reviewTotal').html($('.hdnReviewsCount').val());
    }
}

function submitReview() {

    var bIsValid = true;

    $('#write-reviews .required').each(function (index, domEle) {
        if ($(domEle).val() == "") {
            $(domEle).addClass("errorReq");
            $("<span class=pError>* required</span>").insertAfter(domEle);
            bIsValid = false;
        }
    });

    if (bIsValid) {
        var review = {
            Rating: $("#prRating option:selected").val(),
            Name: $("#prName").val(),
            Title: $("#prTitle").val(),
            Comments: $("#prComments").val(),
            Email: $("#prEmail").val(),
            MusicalStyle: $("#prStyle").val(),
            MusicalExperience: $("#prExperience").val(),
            CityState: $("#prCityState").val(),
            ProductId: $(".hdnProductId").val(),
            psid: $("#hdnPs").val()
        }

        // commit
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/ajax/Itemend/ItemendService.svc/submitReview",
            data: review,
            success: function (response) {
                if (response.d) {
                    $('#divWriteReviewForm').hide();
                    $('#divWriteReviewResponse').show();
                }
                else {

                }
            },
            error: function (response) {
                $('#divWriteReviewForm').hide();
                $('#divWriteReviewError').show();
            }
        });
    }
}

function rateReview(nRating, nReviewId) {
    var params = {
        rating: nRating,
        reviewId: nReviewId,
        psid: $("#hdnPs").val()
    };

    // commit
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/ajax/Itemend/ItemendService.svc/rateReview",
        data: params,
        success: function (response) {
            if (response.d) {
                var drId = ".review" + nReviewId + " .divRateReview";
                $(drId).html("<div>Thank You for rating this review!</div>");
            }
            else {
            }
        },
        error: function (response) {
        }
    });
}

/* accessories */

function loadAccessoryOption(nAccessoryId) {
    var sAccessory = ".acc" + nAccessoryId;
    var nOptionSelectedItemno = ".selAccessory" + nAccessoryId + " option:selected";
    var price = $(nOptionSelectedItemno).attr("price");

    var sPrice = sAccessory + " .spanAccessoryPrice";
    $(sPrice).html(price);
}

function addAccessory(nAccessoryId) {
    if ($(activePurchasingPanel + ' .cartButtons .add2cart').length > 0 && $(activePurchasingPanel + ' .cartButtons .add2cart').css("display") != 'none') {
        //if it can just do the normal logic
        if (validateOptionSelection()) {
            var sQry = "itemno=" + $(activePurchasingPanel + ' .selecteditemno').val() + "&qty=1&isaccess=0";
            var accSelector = ".selAccessory" + nAccessoryId + " option:selected";
            var qtySelector = ".acc" + nAccessoryId + " .qty-input";

            var nSelectedAccessoryItemno = $(accSelector).val();
            var sParentItem = $(accSelector).attr("parentitem");
            var nQty = $(qtySelector).val();

            if (nQty == undefined || nQty == "")
                nQty = 1;

            sQry += "&itemno=" + nSelectedAccessoryItemno + "&qty=" + nQty + "&isaccess=1";
            sQry += "&parent_item=" + sParentItem;
            sQry += "&isitemendpage=1";

            location.href = "/MyAccount/Cart.aspx?" + sQry;
        }
    }
    else {
        if (validateOptionSelection()) {
            var accSelector = ".selAccessory" + nAccessoryId + " option:selected";
            var qtySelector = ".acc" + nAccessoryId + " .qty-input";
            var nSelectedAccessoryItemno = $(accSelector).val();
            var nQty = $(qtySelector).val();

            var sQry = "?qty=" + nQty + "&itemno=" + nSelectedAccessoryItemno + "&isaccess=0&isitemendpage=1";
            location.href = "/MyAccount/Cart.aspx" + sQry;
        }
    }
}


/* kit stuff */

function kitAddToCart() {
    var bIsValid = true;
    $('.select-comps').each(function (index, domEle) {
        if ($(domEle).find(".select-comp:checked").length == 0) {
            bIsValid = false;
        }
    });

    if (bIsValid) {
        var sQry = "kititemno=" + $('.selecteditemno').val() + "&kitqty=1&kitcomponents=";
        $(".select-comp:checked").each(function (index, domEle) {
            var sItemno = $(domEle).val();
            var numberofitems;
            var adjustedqty;
            var sComponentId = $(domEle).attr("componentId");
            numberofitems = $(".componentItem_" + sComponentId).length;
            var sCompQty;
            if (numberofitems != undefined && numberofitems > 1) {
                sCompQty = $(domEle).attr("componentQty") / numberofitems;
            }
            else {
                sCompQty = $(domEle).attr("componentQty");
            }


            //Hack to see if we have 2 or more of the same item no.  If we do then we divide the componet qty but the number of the same itemno that are present.
            //This is for cases like 
            sQry += sCompQty + "," + sComponentId + "," + sItemno;

            if (index != ($('.select-comp:checked').length - 1)) {
                sQry += ";";
            }
        });

        sQry += "&isitemendpage=1";
        //Check if it is an existing cart item;
        var sUrl = window.location.search;
        if (sUrl != undefined && sUrl != "") {
            var ci;
            ci = "";
            ci = gup("ci", sUrl);
            if (ci != undefined && ci != "") {
                sQry += "&ci=" + ci
            }
        }
        location.href = "/MyAccount/Cart.aspx?" + sQry;
    }
    else {
        alert('Please select an option for each Kit Component.');
    }
}

/* modal show/hide methods */

function showKitModal() {
    // colorbox
    $.fn.colorbox({ width: "925px", height: "825px", inline: true, href: "#hdnBuildKit" });
}

function showUsedDescriptions() {
    // colorbox
    $.fn.colorbox({ width: "600px", height: "600px", inline: true, href: "#hdnUsedDescriptions" });
}

function showEmailForm() {
    // colorbox
    $.fn.colorbox({ width: "600px", height: "520px", inline: true, href: "#hdnEmailForm" });
}



function postToMySpace(Title, Content, Url, Location, Image) {
    //Ttitle Content
    Content = Content.replace("localhost:3910", "gc.test.miretail.com");
    Location = Location.replace("localhost:3910", "gc.test.miretail.com");
    Content = '<p>' + Content + '</p><img src="' + Image + '" />';
    var targetUrl = 'http://www.myspace.com/index.cfm?fuseaction=postto&t=' + encodeURIComponent(Title)
    + '&c=' + encodeURIComponent(Content) + '&u=' + encodeURIComponent(Location) + '&l=3&i=' + Image;
    window.open(targetUrl, 'myspacewin', 'width=1000,height=800,scrollbars=yes').focus();
}


function showEmailManagerForm(storeno, storename, type) {
    var validator = $("#managerContactForm").validate();
    $('#contactformarea').show();
    validator.resetForm();
    $(".message").hide();
    $("input#selectedstorenumber").val(storeno);
    $("input#selectedstorename").val(storename);
    $("input#contacttype").val(type);
    $.fn.colorbox({ width: "600px", height: "700px", inline: true, href: "#hdnEmailManagerForm" });
}


function showWriteReviewForm() {
    $('.reviewToggle').hide();
    $('#write-reviews').show();
}

function closeReviewModal() {
    $.fn.colorbox.close();
}



/* other stuff */

function bookmarkPage(title, url) {

    if (window.sidebar) {// firefox
        window.sidebar.addPanel(title, window.location, "");
    }
    else if (window.opera && window.print) { // opera
        var elem = document.createElement('a');
        elem.setAttribute('href', url);
        elem.setAttribute('title', title);
        elem.setAttribute('rel', 'sidebar');
        elem.click();
    }
    else if (document.all) { // ie
        window.external.AddFavorite(window.location, title);
    }
}

function sendEmailFriend() {
    var bIsValid = true;
    //clear out any old values
    $('.email-wrapper .required').each(function (index, domEle) {
        if ($(domEle).val() == "") {
            $(domEle).removeClass("errorReq");
            $(".pError").remove();
        }
    });

    $('.email-wrapper .required').each(function (index, domEle) {
        if ($(domEle).val() == "") {
            $(domEle).addClass("errorReq");
            $("<span class=pError>* required</span>").insertAfter(domEle);
            bIsValid = false;
        }
    });

    var message = $('#message').val();
    if (message.match('<(.|\n)*?>')) {
        bIsValid = false;
        alert('Invalid message! The message must be plain text and can NOT contain any html characters.');
    }

    if (bIsValid) {

        var params = {
            sendername: $('#sendername').val(),
            emails: $('#emails').val(),
            message: $('#message').val(),
            itemno: $('.hdnDefaultItemno').val()
        };

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/ajax/itemend/ItemEndService.svc/sendEmailFriend",
            data: params,
            success: function (res) {
                if (res != null) {

                    if (res.d == "") {
                        $('.email-wrapper').html("<div><center><h1>Thanks for sending!</h1></center></div>");
                    }
                    else {
                        $('.divEmailError').html(res.d);
                        $('.divEmailError').show();
                    }
                }
            },
            error: function (xhr, status, error) {

            }
        });
    }

}

function sendEmailManagerForm() {

    var bIsValid = true;
    var validator = $("#managerContactForm").validate({
        rules: {
            contactsenderphonenumber: {
                required: true,
                phoneUS: true
            }
        }
    });
    bIsValid = $("#managerContactForm").valid();
    if (bIsValid) {
        var selItem = $('#selecteditemno').val();
        if (!selItem) {
            var selItem = $('.hdnDefaultItemno').val();
        }
        var params = {
            contactsenderfirstname: $('#contactsenderfirstname').val(),
            contactsenderlastname: $('#contactsenderlastname').val(),
            contactsenderphonenumber: $('#contactsenderphonenumber').val(),
            contactsenderemail: $('#contactsenderemail').val(),
            contactsenderconfirmemail: $('#contactsenderconfirmemail').val(),
            contactcontactby: $('input[name="contactcontactby"]:checked').val(),
            contactbesttime: $('input[name="contactbesttime"]:checked').val(),
            contactmessage: $('#contactmessage').val(),
            contacttype: $('#contacttype').val(),
            itemno: selItem,
            storeno: $('#selectedstorenumber').val()
        };

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/ajax/itemend/ItemEndService.svc/sendManagerEmail",
            data: params,
            success: function (res) {
                if (res != null) {
                    if (res.d == "") {
                        $('#contactformarea').hide();
                        $('.message').html("<div><h1>We have received your request, and an Associate from the " + $("input#selectedstorename").val() + " store will contact you shortly.</h1></div>");
                        $('.message').show();
                    }
                    else {
                        $('.errorMessage').html(res.d);
                        $('.error').show();
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    }
}


function validateOptionSelection() {
    if ($('#divInventory') != undefined && $('#divInventory').is(':visible')) {
        return false;
    }
    else if ($('.itemno').is(':visible') && $('.itemno').val() == "") {
        alert("Please select an option.");
        return false;
    }
    else {
        return true;
    }
}

function printPage() {
    bIsValidPrintAttempt = true;

    if ($('#chkPrintInventory').is(':checked') && $('.store-results .store-info').length == 0) {
        alert('Please enter a valid City/State or Zip in the "Find In Store" tab before attemtping to print Store Inventory.');
        bIsValidPrintAttempt = false;
    }

    if (bIsValidPrintAttempt) {

        $('.printImage').show();
        $('.mediaViewer').hide();
        $('.media-gallery').hide();
        $('#share-this').hide();
        $('.breadcrumb').hide();
        $('#ctl00_divFooter').hide();
        $('.option_image_print').attr("src", $('.optionimage').attr("src"));
        $('#ctl00_divMbox').hide();

        var divPrintPageContent = $('#top-wrapper').html();

        $('.cartButtons').hide();

        divPurchasingNew = $('#purchasing-new').html();
        st1 = divPurchasingNew.indexOf("<!-- cart buttons -->");
        st2 = divPurchasingNew.indexOf("<!-- / cart buttons -->");
        divPurchasingNewFinal = divPurchasingNew.substring(0, st1) + divPurchasingNew.substring(st2, divPurchasingNew.length);

        divPrintPageContent += divPurchasingNewFinal;

        $('.print-this input:checked').each(function (index, domEle) {
            if ($(domEle).attr("id") == "chkPrintAtAGlance") {
                divPrintPageContent += "<h2>At A Glance</h2>" + $('#at-a-glance').html();
            }
            if ($(domEle).attr("id") == "chkPrintSpecification") {
                divPrintPageContent += "<h2>Specifications</h2>" + $('#specifications').html();
            }
            if ($(domEle).attr("id") == "chkPrintWarranty") {
                divPrintPageContent += "<h2>Warranty</h2>" + $('#warranty').html();
            }
            if ($(domEle).attr("id") == "chkPrintUsed") {
                divPrintPageContent += "<h2>Used Gear Listing</h2>" + $('.usedGearContainer').html();
            }
            if ($(domEle).attr("id") == "chkPrintInventory") {
                divPrintPageContent += "<h2>Guitar Center Store Availability</h2>" + $('.storeResultsContainer').html();
            }
            if ($(domEle).attr("id") == "chkPrintReviews") {
                divPrintPageContent += "<h2>Reviews</h2>" + $('#customer-reviews').html();
            }
        });

        $('.divRegularPageContainer').hide();
        $('#ctl00_divHeader').hide();

        divPrintPageContent = "<div id=body>" + divPrintPageContent + "</div>";

        $('.divPrintPageContent').html(divPrintPageContent);
        $('.divPrintablePageContainer').show();

        window.print();
    }
}

function viewRegularPage() {

    $('.mediaViewer').show();
    $('.media-gallery').show();
    $('#share-this').show();
    $('.breadcrumb').show();
    $('#ctl00_divFooter').show();
    $('#ctl00_divMbox').show();

    $('.cartButtons').show();
    $('.printImage').hide();
    $('.divPrintPageContent').html("");
    $('#ctl00_divHeader').show();
    $('.divPrintablePageContainer').hide();
    $('.divRegularPageContainer').show();
}


function addToCartClick() {
    if ($(activePurchasingPanel + ' .selecteditemno').val() == 0) {
        alert("Please select an option.");
        return false;
    }
    var selectedvalue;
    selectedvalue = $(activePurchasingPanel + ' .options-box select').val();
    if (selectedvalue != undefined && (selectedvalue == "" || selectedvalue == "Please select an option") & $(activePurchasingPanel + ' .options-box').is(':visible')) {
        alert("Please select an option.");
        return false;
    }

    if ($(activePurchasingPanel + ' .selecteditemno').val() == 0) {
        alert("Please select an option.");
        return;
    }
    var itemno;
    //Determine if the child Serialized Item was selected if so pass that ItemNo rather than Parent ItemNo
    if ($('#selectedchilditemno').val() != undefined && $('#selectedchilditemno').val() != '') {
        itemno = $('#selectedchilditemno').val();
    }
    else {
        itemno = $(activePurchasingPanel + ' .selecteditemno').val();
    }
    sQry = "?qty=1&itemno=" + itemno + "&isaccess=0&isitemendpage=1";
    location.href = "/MyAccount/Cart.aspx" + sQry;
}

function addToWishlistClick() {

    if ($(activePurchasingPanel + ' .selecteditemno').val() == 0) {
        alert("Please select an option.");
        return false;
    }

    var selectedvalue;
    selectedvalue = $(activePurchasingPanel + ' .options-box select').val();
    if (selectedvalue != undefined && (selectedvalue == "" || selectedvalue == "Please select an option") & $(activePurchasingPanel + ' .options-box').is(':visible')) {
        alert("Please select an option.");
        return false;
    }

    sQry = "?qty=1&itemno=" + $(activePurchasingPanel + ' .selecteditemno').val() + "&isaccess=0&isitemendpage=1";
    location.href = "/MyAccount/wishadd.aspx" + sQry;
}

function optionChanged(sItemno, bSomething) {

}


function css_browser_selector(u) {
    var ua = u.toLowerCase(), is = function (t) {
        return ua.indexOf(t) > -1;
    }, g = 'gecko', w = 'webkit', s = 'safari', o = 'opera', h = document.documentElement, b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3') ? g + ' ff3' : is('firefox/4') ? g + ' ff4' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? 'mobile' : is('iphone') ? 'iphone' : is('ipod') ? 'ipod' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js']; c = b.join(' '); h.className += ' ' + c; return c;
};
css_browser_selector(navigator.userAgent);
function equalHeight(group) {
    var tallest = 0;
    group.each(function () {
        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
// Carousel
(function ($) {
    $.fn.gcCarousel = function (options) {
        var defaults = {
            start: 1, // where should the carousel start?
            display: 1, // how many blocks do you want to move at 1 time?
            axis: 'x', // vertical or horizontal scroller? ( x || y ).
            controls: true, // show left and right navigation buttons.
            pager: false, // is there a page number navigation present?
            interval: false, // move to another block on intervals.
            intervaltime: 3000, // interval time in milliseconds.
            animation: true, // false is instant, true is animate.
            duration: 1000, // how fast must the animation move in ms?
            callback: null // function that executes after every move
        };
        var options = $.extend(defaults, options);
        var oSlider = $(this);
        var oViewport = $('.viewport', oSlider);
        var oContent = $('.overview', oSlider);
        var oPages = oContent.children();
        var oBtnNext = $('.next', oSlider);
        var oBtnPrev = $('.prev', oSlider);
        var oPager = $('.pager', oSlider);
        var iPageSize, iSteps, iCurrent, oTimer, bForward = true, bAxis = options.axis == 'x';
        return this.each(function () {
            initialize();
        });
        function initialize() {
            iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true);
            var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) - 1);
            iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover);
            iCurrent = Math.min(iSteps, Math.max(1, options.start)) - 2;
            oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length));
            move(1);
            setEvents();
        }
        function setEvents() {
            if (options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0) {
                oBtnPrev.click(function () { move(-1); return false; });
                oBtnNext.click(function () { move(1); return false; });
            }
            if (options.pager && oPager.length > 0) {
                oPager.click(setPager);
            }
        }
        function setButtons() {
            if (options.controls) {
                oBtnPrev.toggleClass('disable', !(iCurrent > 0));
                oBtnNext.toggleClass('disable', !(iCurrent + 1 < iSteps));
            }
            if (options.pager) {
                var oNumbers = $('.pagenum', oPager);
                oNumbers.removeClass('active');
                $(oNumbers[iCurrent]).addClass('active');
            }
        }
        function setPager(oEvent) {
            var oTarget = oEvent.target;
            if ($(oTarget).hasClass('pagenum')) {
                iCurrent = parseInt(oTarget.rel) - 1;
                move(1);
            }
            return false;
        }
        function setTimer(bReset) {
            if (options.interval && !bReset) {
                clearInterval(oTimer);
                oTimer = window.setInterval(function () {
                    bForward = iCurrent + 1 == iSteps ? false : iCurrent == 0 ? true : bForward;
                    move(bForward ? 1 : -1, true);
                }, options.intervaltime);
            }
        }
        function move(iDirection, bTimerReset) {
            if (iCurrent + iDirection > -1 && iCurrent + iDirection < iSteps) {
                iCurrent += iDirection;
                var oPosition = {};
                oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display));
                oContent.animate(oPosition, {
                    queue: false,
                    duration: options.animation ? options.duration : 0,
                    complete: function () {
                        if (typeof options.callback == 'function')
                            options.callback.call(this, oPages[iCurrent], iCurrent);
                    }
                });
                setButtons();
                setTimer(bTimerReset);
            }
        }
    };
})(jQuery);

/**
* jCache - A client cache plugin for jQuery
* Should come in handy when data needs to be cached in client to improve performance.
* Author: 	Phan Van An 
*			phoenixheart@gmail.com
*			http://www.skidvn.com
* License : Read jQuery's license

Usage:
1. 	Include this plugin into your web document after jQuery:
<script type="text/javascript" src="js/jquery.jcache.js"></script>
2.	[OPTIONAL] Set the max cached item number, for example 20
$.jCache.maxSize = 20; 
3. 	Start playing around with it:
- Put an item into cache: $.jCache.setItem(theKey, the Value);
- Retrieve an item from cache: var theValue = $.jCache.getItem(theKey);
- ...
*/
(function (jQuery) {
    this.version = '(beta)(0.0.1)';

    /**
    * The maximum items this cache should hold. 
    * If the cache is going to be overload, oldest item will be deleted (FIFO).
    * Since the cached object is retained inside browser's state, 
    * a too big value on a too big web apps may affect system memory.
    * Default is 10.
    */
    this.maxSize = 20;

    /**
    * An array to keep track of the cache keys
    */
    this.keys = new Array();

    /**
    * Number of currently cached items
    */
    this.cache_length = 0;

    /**
    * An associated array to contain the cached items
    */
    this.items = new Array();

    /*
    * @desc	Puts an item into the cache
    *
    * @param	string Key of the item
    * @param 	string Value of the item
    * @return	string Value of the item
    */
    this.setItem = function (pKey, pValue) {
        if (typeof (pValue) != 'undefined') {
            if (typeof (this.items[pKey]) == 'undefined') {
                this.cache_length++;
            }

            this.keys.push(pKey);
            this.items[pKey] = pValue;

            if (this.cache_length > this.maxSize) {
                this.removeOldestItem();
            }
        }

        return pValue;
    }

    /*
    * @desc	Removes an item from the cache using its key
    * @param 	string Key of the item
    */
    this.removeItem = function (pKey) {
        var tmp;
        if (typeof (this.items[pKey]) != 'undefined') {
            this.cache_length--;
            var tmp = this.items[pKey];
            delete this.items[pKey];
        }

        return tmp;
    }

    /*
    * @desc 	Retrieves an item from the cache by its key
    *
    * @param 	string Key of the item
    * @return	string Value of the item
    */
    this.getItem = function (pKey) {
        return this.items[pKey];
    }

    /*
    * @desc	Indicates if the cache has an item specified by its key
    * @param 	string Key of the item
    * @return 	boolean TRUE or FALSE
    */
    this.hasItem = function (pKey) {
        return typeof (this.items[pKey]) != 'undefined';
    }

    /**
    * @desc	Removes the oldest cached item from the cache
    */
    this.removeOldestItem = function () {
        this.removeItem(this.keys.shift());
    }

    /**
    * @desc	Clears the cache
    * @return	Number of items cleared
    */
    this.clear = function () {
        var tmp = this.cache_length;
        this.keys = new Array();
        this.cache_length = 0;
        this.items = new Array();
        return tmp;
    }

    jQuery.jCache = this;
    return jQuery;
})(jQuery);
