var onSubDiv = false;
var isoverview = false;
var myOptions = {
    min: 0,         // Set lower limit.
    max: 100,       // Set upper limit.
    step: 1         // Set increment size
}
jQuery.noConflict();
jQuery(document).ready(function () {
    //Options Price Update
    jQuery('.grp').live('change', function () {
        var grpCount = jQuery('.grp').length;
        var basePrice = jQuery('#hidden_price').val();
        var hdnID = "hdnQty_" + jQuery(this).val().split(';')[1];
        var hdnPrice = jQuery('#' + hdnID).attr('rel');
        var shdnID = '';
        var shdnPrice = '';
        var totHdnPrice = '';
        //var currPrice = parseFloat(jQuery('#product_price').html().split('$')[1]);
        var newPrice = '';
        if (parseInt(grpCount) > 1) {
            jQuery('.grp').each(function () {
                if (jQuery(this).val() != "0") {
                    shdnID = "hdnQty_" + jQuery(this).val().split(';')[1];
                    shdnPrice = jQuery('#' + shdnID).attr('rel');
                    if (totHdnPrice == '') {
                        totHdnPrice = shdnPrice;
                    } else {
                        totHdnPrice = totHdnPrice + ';' + shdnPrice;
                    }
                }
            });
            var priceAdd = 0;
            totHdnPrice = totHdnPrice.split(';');
            for (var i = 0; i < totHdnPrice.length; i++) {
                priceAdd = parseInt(priceAdd) + parseInt(totHdnPrice[i]);
            }
            newPrice = parseInt(priceAdd) + parseInt(basePrice);
            jQuery('#product_price').html('$' + newPrice.toFixed(2));
        } else {
            newPrice = parseInt(basePrice) + parseInt(hdnPrice);
            jQuery('#product_price').html('$' + newPrice.toFixed(2));
        }
    });
    //#main height to keep footer at bottom
    var browserHeight = document.documentElement.offsetHeight - 300;
    jQuery('#main').css('min-height', browserHeight + 'px');
    //Homepage Rotator
    jQuery('#slideshow').cycle({
        timeout: 6000,
        speed: 1000,
        prev: '#slideshowprev',
        next: '#slideshownext'
    });
    //Active Class on Main Nav
    var majDeptName = jQuery('#majDeptName').val();
    jQuery('.mn_active').removeClass('mn_active');
    jQuery('.mn_toplink').each(function () {
        if (jQuery(this).text().toLowerCase() == majDeptName) {
            jQuery(this).addClass('mn_active');
        }
    });
    //Active Class for Secondary Nav
    var secondaryActive = jQuery('#secondary_nav').val();
    jQuery('#fc_header_utility li a').removeClass('second_active');
    jQuery('#fc_header_utility li a').each(function () {
        if (jQuery(this).attr('id') == secondaryActive) {
            jQuery(this).addClass('second_active');
        }
    });
    //Subsub A Breadcrumbs
    if (jQuery('#breadcrumbs').length > 0) {
        var oldLastCrumb = jQuery('#breadcrumbs ul li:last').html().indexOf('&nbsp;');
        var lastCrumb = jQuery('#breadcrumbs ul li:last').html().slice(0, parseInt(oldLastCrumb));
        jQuery('#breadcrumbs ul li:last').html(lastCrumb);
    }
    //Product Page Image Thumbnails
    jQuery('.cloud-zoom-gallery:first').parent('li').addClass('pt_selected');
    jQuery('.cloud-zoom-gallery').click(function () {
        jQuery('.cloud-zoom-gallery').parent('li').removeClass('pt_selected');
        jQuery(this).parent('li').addClass('pt_selected');
        var thumbSrc = jQuery(this).children('img').attr('src').split('path=')[1];
        var oldHref = jQuery('#subsub_b_view_lg').attr('href').split('path=')[0];
        jQuery('#subsub_b_view_lg').attr('href', oldHref + 'path=' + thumbSrc);
    });
    jQuery('#slider').tinycarousel({ display: 4, rewind: true });
    //Wishlist Check For Options
    jQuery('.prod_add_wishlist').click(function () {
        var initial_href = jQuery(this).attr('href');
        var href_len = initial_href.length;
        var href_find_opt = initial_href.slice(-8);
        if (href_find_opt == "options=") {
            if (jQuery('#wishlist_options').val() == "wishlist_options") {
                var optGrpCount = jQuery('.grp').length;
                var optCount = 0;
                var optWish = "";
                jQuery('.grp').each(function () {
                    if (jQuery(this).val() != "0") {
                        optCount = optCount + 1;
                        if (optWish == "") {
                            optWish = jQuery(this).val();
                        } else {
                            optWish = optWish + ', ' + jQuery(this).val();
                        }
                    }
                });
                if (parseInt(optGrpCount) == parseInt(optCount)) {
                    var wishlink = jQuery('#prod_wish').attr('href');
                    var wishlink_find = wishlink.indexOf('options=') + 8;
                    var new_href = wishlink.slice(0, wishlink_find);
                    jQuery('#prod_wish').attr('href', new_href + optWish);
                    return true;
                } else {
                    alert('Please select your option(s)');
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }
    });
    //Product Page Tabs
    jQuery('#prod_tabs').tabs();
    //Member Login Header - Added h2 to shoplogic to contain image per client request
    //Do below once shoplogic push issue is fixed
    jQuery('#SubContent.memberLogin h1:first').html('<img src="/images/design/member_login_header.jpg" alt="Member Login" />');
    jQuery('h2.memberLoginSecondHeader').html('Member Area Login');


    /******************************/
    /*START SV COMMON JS FUNCTIONS*/
    /******************************/
    //jquery lightwindow
    jQuery('.lightwindow').live('click', function () {
        //Get dimensions from rel tag
        var jWinDimensions = jQuery(this).attr('rel');

        var jWinWidth = 400;
        var jWinHeight = 300;
        var jWinTitle = " ";
        if (jWinDimensions != "") {
            var jWinWidthStart = jWinDimensions.indexOf("width") + 6;
            var jWinHeightStart = jWinDimensions.indexOf("height") + 7;
            var jWinHeightEnd;

            if (jWinWidthStart < jWinHeightStart) {
                jWinWidthEnd = jWinDimensions.indexOf(",", jWinWidthStart);
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinWidthEnd));
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinDimensions.length));

            }
            else {
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinDimensions.length));
                jWinHeightEnd = jWinDimensions.indexOf(",", jWinHeightStart);
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinHeightEnd));
            }
        }
        jQuery.fn.colorbox({ href: jQuery(this).attr('href'), iframe: true, width: jWinWidth, height: jWinHeight, rel: "nofollow" });
        return false;
    });
    // opens non-modal window - no iframe
    jQuery('.nolightwindow').live('click', function () {
        //Get dimensions from rel tag
        var jWinDimensions = jQuery(this).attr('rel');
        var jWinWidth = 400;
        var jWinHeight = 300;
        var jWinTitle = " ";
        if (jWinDimensions != "") {
            var jWinWidthStart = jWinDimensions.indexOf("width") + 6;
            var jWinHeightStart = jWinDimensions.indexOf("height") + 7;
            var jWinHeightEnd;

            if (jWinWidthStart < jWinHeightStart) {
                jWinWidthEnd = jWinDimensions.indexOf(",", jWinWidthStart);
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinWidthEnd));
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinDimensions.length));

            }
            else {
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinDimensions.length));
                jWinHeightEnd = jWinDimensions.indexOf(",", jWinHeightStart);
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinHeightEnd));
            }
        }
        jQuery.fn.colorbox({ href: jQuery(this).attr('href'), iframe: false, width: jWinWidth, height: jWinHeight, rel: "nofollow" });
        return false;
    });

    // Quick view
    jQuery('.subsub_prod_img').live('mouseenter', function () {
        jQuery(this).children('.quickview').show();
        jQuery(this).children('.quickview').find().show();

    });
    jQuery('.subsub_prod_img').live('mouseleave', function () {
        jQuery(this).children('.quickview').hide();
    });
    jQuery('.productImage').live('mouseover', function () {
        jQuery(this).children('.viewLarger').show();
        jQuery(this).children('.viewLarger').find().show();

    });
    jQuery('.productImage').live('mouseleave', function () {
        jQuery(this).children('.viewLarger').hide();
    });
    // Watermark
    jQuery('.watermark').each(function () {
        if (jQuery(this).val() == "") {
            jQuery(this).val(jQuery(this).attr('title')).addClass('watermarked');
        }
        jQuery(this).focus(function () {
            if (jQuery(this).val() == jQuery(this).attr('title')) {
                jQuery(this).val("").removeClass('watermarked');
            }
        });
        jQuery(this).blur(function () {
            if (jQuery(this).val() == "") {
                jQuery(this).val(jQuery(this).attr('title')).addClass('watermarked');
            }
        });

    });
    // expanded hot state
    var expandedLi = jQuery('.accordionNav').attr('id');
    jQuery('#S_' + expandedLi).addClass('hot').children('ul').show();
    // spin button

    //Ajax Hash
    if (window.location.hash.length > 0) {
        hashDance();
    }
    jQuery(window).hashchange(function () {
        hashDance();
    })
    jQuery('.psize').live('change', function () {
        if (jQuery('#hiddenBrandID').length < 1) {
            ajaxHash("psize=" + jQuery(this).attr('value'));
        }
        else {
            ajaxHash("psize=" + jQuery(this).attr('value') + '&brandlist=' + jQuery('#hiddenBrandID').attr('value'));
        }
    });

});                                                                      //end document.ready
//Remove All Filters
function clearFilters() {
    clearThis = "";
    ajaxHash('catList=' + clearThis)
}
//Ajax Hash
function verifyAttributeChecks() {
    hashString = window.location.hash;
    CatListPosition = hashString.indexOf("catList")
    catList = hashString.slice(CatListPosition)
    NextParamPosition = catList.indexOf("&")
    if (NextParamPosition > 0) {
        catList = catList.slice(0, NextParamPosition)
    }
    CatListCSV = catList.slice(8)
    //alert(CatListCSV);
    if (CatListCSV != "") {
        jQuery('.filtering_select option:selected').each(function () {
            thisAttributeValue = jQuery(this).attr('value')
            if (CatListCSV.indexOf(thisAttributeValue) < 0) {
                //jQuery(this).attr('checked', false)
                jQuery(this).removeAttr('selected')
            }
        });
        CatListArray = CatListCSV.split(',')
        //alert(CatListArray);
        jQuery('.filtering_select option:selected').each(function () {
            thisAttributeValue = jQuery(this).attr('value')
            //alert(thisAttributeValue);
            for (var i = 0; i < CatListArray.length; i++) {
                if (thisAttributeValue == CatListArray[i]) {
                    //jQuery(this).attr('checked', true)
                    jQuery(this).attr('selected', 'selected');
                }
            }
        });
    } else {
        jQuery('.filtering_select option:selected').each(function () {
            //jQuery(this).attr('checked', false)
            jQuery(this).removeAttr('selected');
        });
    }
}
function ajaxHash(filters) {
    jQuery.bbq.pushState(filters);
}

function ajaxSort() {
    if (jQuery('#hiddenBrandID').length < 1) {
        ajaxHash("sort=" + jQuery('#sort').attr('value'));
    } else {
        ajaxHash("sort=" + jQuery('#sort').attr('value') + '&brandlist=' + jQuery('#hiddenBrandID').attr('value'));
    }
}
function ajaxAttributeFilters() {
    attributeList = ""
    brandList = ""
    jQuery('.filtering_select option:selected').each(function () {
        if (jQuery(this).val() != "0") {
            if (attributeList == "") {
                attributeList = jQuery(this).attr('value')
            } else {
                attributeList = attributeList + ',' + jQuery(this).attr('value')
            }
        }
    });
    jQuery('.brandFilter:selected').each(function () {
        if (brandList == "") {
            brandList = jQuery(this).attr('value')
        } else {
            brandList = brandList + ',' + jQuery(this).attr('value')
        }
    });
    ajaxHash('catList=' + attributeList + '&brandList=' + brandList)
}

function hashDance() {
    hashString = window.location.hash.substr(1);
    if (hashString.indexOf("subcat") < 1 && jQuery('#subcatid').length) {
        hashString = hashString + "&subcat=" + jQuery('#subcatid').attr('value')
    }
    if (window.location.hash.length < 1 && jQuery('#subcatid').length) {
        hashString = "subcat=" + jQuery('#subcatid').attr('value')
    }
    ajaxPanel(hashString);
    //verifyAttributeChecks();
}

function ajaxPanel(urlVariables) {
    var url = '../ajax_subcat.asp?' + urlVariables
    var target = '#ajaxPanel'
    var subCatId = jQuery('#subcatid').attr('value');
    panelHeight = jQuery(target).height()
    jQuery('#spinload').css('height', panelHeight).fadeIn('700');
    jQuery.get(url, function (data) {
        if (document.all) {
            document.getElementById("ajaxPanel").innerHTML = data;
            jQuery('#spinload').fadeOut('700');
        }
        else {
            jQuery(target).html(data, function () {
                jQuery('#spinload').fadeOut('700');
            });
        }
        //Select correct attributes
        var selAttrs = jQuery('#attrids').val().split(",");
        for (var i = 0; i < selAttrs.length; ++i) {
            jQuery('.filtering_select option[value="' + selAttrs[i] + '"]').attr('selected', true);
        }
        //alert(selAttrs.length);
        if (jQuery('#attrids').val() != '' && jQuery('#attrids').val() != null) {
            jQuery('#clear_filters').css('display', 'block');
        } else {
            jQuery('#clear_filters').css('display', 'none');
        }
        //Active Class on Main Nav
        var majDeptName = jQuery('#majDeptName').val();
        jQuery('.mn_active').removeClass('mn_active');
        jQuery('.mn_toplink').each(function () {
            if (jQuery(this).text().toLowerCase() == majDeptName) {
                jQuery(this).addClass('mn_active');
            }
        });
        //Subsub Breadcrumbs
        if (jQuery('#breadcrumbs').length > 0) {
            var oldLastCrumb = jQuery('#breadcrumbs ul li:last').html().indexOf('&nbsp;');
            var lastCrumb = jQuery('#breadcrumbs ul li:last').html().slice(0, parseInt(oldLastCrumb));
            jQuery('#breadcrumbs ul li:last').html(lastCrumb);
        }
    });
}
//top nav drop-downs with hover intent
jQuery(function () {
    jQuery('.topnav').hoverIntent({
        over: displayMenu,
        timeout: 800,
        out: hideMenu
    });
});
function displayMenu() {
    jQuery('.flyout').hide();
    jQuery('.topnav').removeClass('active');
    jQuery(this).addClass('active');
    jQuery(this).children('.flyout ul').show();
    jQuery(this).children('.flyout').fadeIn();
}
function hideMenu() {
    jQuery(this).children('.flyout').fadeOut();
    jQuery(this).children('.flyout ul').hide();
    jQuery(this).removeClass('active');
}

//Slide cart functions
function addAccToOrder(prod) {
    var options = '';
    if (jQuery('#aAccessories')) {
        //found options
        options = jQuery('#aAccessories').val();
    }
    var cartQty = jQuery('#qty_' + prod).val();
    addToCartAndShow('#cartarea', prod, cartQty, options);
}
function getcartarea(divID) {
    onSubDiv = false;
    jQuery(divID).html("<img src=\"/images/loading.gif\" />");
    jQuery(divID).removeClass('Description');
    jQuery(divID).slideDown("slow");
    jQuery.get('/ajax_addedtocartpulldown.asp', function (data) {
        //jQuery((divID)).html(data);

        //ie
        if (document.all) {
            divID = divID.replace('#', '');
            //alert(divID);
            document.getElementById(divID).innerHTML = data;
        }
        else {
            jQuery(divID).html(data);
        }
    });

}
//Quick View add to cart
function quickViewAdd() {
    var qty = jQuery('#quantity').val();
    var options = '';
    if (jQuery('.grp').length > 0) {
        var countOptions = jQuery('.grp').length;
        var chkOptVals = 0;
        jQuery('.grp').each(function () {
            if (jQuery(this).val() != "0") {
                optQty = jQuery('#hdnQty_' + jQuery(this).val().split(';')[1]).val();
                if (parseInt(optQty) > 0 && parseInt(optQty) >= parseInt(jQuery('#quantity').val())) {
                    chkOptVals = chkOptVals + 1;
                } else {
                    alert('Not enough in stock to complete order.');
                }
            }
        });
        if (parseInt(countOptions) != parseInt(chkOptVals)) {
            alert('Please select your option(s).');
        } else {
            //jQuery('#cboxOverlay').click();
            addToCartAndShow();
            parent.jQuery.fn.colorbox.close();
            window.scrollTo(0, 0);
        }
    } else {
        jQuery('#cboxOverlay').click();
        window.scrollTo(0, 0);
        addToCartAndShow();
    }
}
function addToCartAndShow() {
    var divID = '#cartarea';
    var prod = jQuery('#product_id').val();
    var qty = jQuery('#quantity').val();
    var options = '';
    var optCount = 0;
    var optExist = jQuery('.grp').length;
    if (parseInt(optExist) > 0) {
        jQuery('.grp').each(function () {
            if (jQuery(this).val() != "0") {
                optQty = jQuery('#hdnQty_' + jQuery(this).val().split(';')[1]).val();
                if (parseInt(optQty) > 0 && parseInt(optQty) >= parseInt(jQuery('#quantity').val())) {
                    optCount = optCount + 1;
                    if (options == "") {
                        options = jQuery(this).val();
                    } else {
                        options = options + ', ' + jQuery(this).val();
                    }
                } else {
                    alert('Not enough in stock to complete order.');
                    return false;
                }
            }
        });
        if (parseInt(optExist) > parseInt(optCount)) {
            alert('Please select your option(s).');
            return false;
        }
    } else {
        if (parseInt(jQuery('#quantity').val()) > parseInt(jQuery('#hdnQty').val())) {
            alert('Not enough in stock to complete order.');
            return false;
        } 
    }
    jQuery(divID).html("<img src=\"/images/loading.gif\" /> Adding to Cart...");
    jQuery(divID).removeClass('Description');
    jQuery(divID).slideDown("slow");
    var url = '/ajax_addedtocartPullDownAll.asp?prod=' + prod + '&options=' + options + '&quantity=' + qty.toString();
    var currentCount = jQuery('#cartCount').html();
    currentCount = parseInt(currentCount) + parseInt(qty);
    jQuery('#cartCount').html(currentCount);
    jQuery('#utility_cart').addClass('cart_active');
    jQuery.get(url, function (data) {
        //ie
        if (document.all) {
            document.getElementById('cartarea').innerHTML = data;
        }
        else {
            jQuery(divID).html(data);
        }
        window.setTimeout("hidecartarea('" + divID + "')", 3000);
    });

}
function hidecartarea(divID, parentdivID) {
    window.setTimeout("hideIt('" + divID + "')", 500);
}
function hideIt(divID) {
    if (!onSubDiv)
        jQuery(divID).slideUp("slow");
}
jQuery(function () {
    jQuery('#utility_cart').hoverIntent({
        over: showCart,
        timeout: 800,
        out: hideCart
    });
});
function showCart() {
    onSubDiv = false;
    jQuery('#cartarea').html('<img src="/images/loading.gif" />');
    jQuery('#cartarea').slideDown('slow');
    jQuery.get('/ajax_addedtocartpulldown.asp', function (data) {
        //ie
        if (document.all) {
            document.getElementById('cartarea').innerHTML = data;
        }
        else {
            jQuery('#cartarea').html(data);
        }
    });
}
function hideCart() {
    jQuery('#cartarea').slideUp('slow');
}
//Email Signup Validation
function validateEmailSignUp() {
    var emailName = jQuery('#txtName').val();
    var emailAddress = jQuery('#txtEmail').val();
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    var checkEmail = emailFilter.test(emailAddress);
    if (emailName != "Name" && emailName.length > 2 && checkEmail != false) {
        document.forms["frmEmailSignup"].submit();
    } else {
        if (emailName == "Name" || emailName.length < 2) {
            alert('Please enter your name.');
            return false;
        }
        if (checkEmail == false) {
            alert('Please enter a valid email address.');
            return false;
        }
        return false;
    }
}
//Home page - coupon code popup
function validateCouponEmails() {
    var emailAddress = '';
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    var emailCount = 0;
    var validEmailCount = 0;
    jQuery('#email_coupon input.watermark').each(function () {
        emailAddress = jQuery(this).val();  
        if (emailAddress != '' && emailAddress != 'email address') {
            emailCount = emailCount + 1;
            var checkEmail = emailFilter.test(emailAddress);
            if (checkEmail == false) {
                alert('Please enter a valid email address.');
                jQuery(this).css('background-color', '#faffbd');
            } else {
                validEmailCount = validEmailCount + 1;
                jQuery(this).css('background-color', '#fff');
            }
        }
    });
    if (parseInt(emailCount) == parseInt(validEmailCount)) {
        document.forms["frmEmailCoupon"].submit();
    } else {
        alert('There was an error with one or more of the email addresses you entered.');
    }
}

//Product Page - FB Share
function fbs_click() {
    u = location.href;
    t = document.title;
    window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436');
    return false;
}
