// ------------------------------
// Groove Functionality
// ------------------------------

// kickoff

function selectbrand(){
    alert(this.href);
}

$(document).ready(function() {

    // Input Field from AndyStratton.com
    $("input.populate, textarea.populate").each(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    });
    $("input.populate, textarea.populate").focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        }
    });
    $("input.populate, textarea.populate").blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    });

    // Fancybox
    $(".fancy").fancybox();
    $(".fancyYouTube").fancybox({
        'frameWidth': 560,
        'frameHeight': 340
    });
    $(".fancyOffer").fancybox({
        'frameWidth': 760,
        'frameHeight': 625
    });
    $(".fancySignUp").fancybox({
        'frameWidth': 560,
        'frameHeight': 340
    });
    // Cigar Search
    $("a#fancybrand").fancybox({
        'frameWidth': 770,
        'frameHeight': 530
    });

    // Initiate SideNav
    if (($("body").hasClass("home")) || ($("body").hasClass("topic")) || ($("body").hasClass("blog"))) {
    //    $("#sideNav .content li.category a.expand:lt(3)").addClass("open");
    //    $("#sideNav .content li ul:lt(3)").css("display", "block");

        // Hides Tags Section on Blog
        $("#sideNav .content em.tags span").removeClass("open");
        $("#sideNav .content em.tags").next("ul").css("display", "none");
    }

    // Expand Current Category
    $("#sideNav .content li.category a.expand").parent().next("ul").css("display", "block");
    $("#sideNav .content li:last").addClass("last");

    // Animate SideNav
    $("#sideNav .content li.category a.expand").click(function() {
        if ($(this).hasClass("open")) {
            $(this).removeClass("open");
            $(this).parent().children("ul").animate({ height: "toggle", opacity: "toggle" }, "slow");
        }
        else {
            $(this).addClass("open");
            $(this).parent().children("ul").animate({ height: "toggle", opacity: "toggle" }, "slow");
        }
    });


    // Slideshow
    $("#slideshow").tabs({ fx: { opacity: 'toggle'} }).tabs('rotate', 6000);

    $("#slideshow input.styled").click(function() { $("#slideshow").tabs('rotate', 0); });

    // Top Sellers
    $("#topSellers").tabs({ fx: { opacity: 'toggle'} });

    // product multi image
    $(".productThumbnails ul li img").not(".productThumbnails ul li img.thumbnailBorder").click(function() {
        var src = new Array(4);
        src = ($(this).attr("src")).split("/", 4);

        src[2] = "medium";
        var mediumSrc = src.join("/");
        src[2] = "large";
        var largeSrc = src.join("/");

        $("td.productMedia .productImage a img").attr("src", mediumSrc);
        $("td.productMedia .productImage a").attr("href", largeSrc);
    });

    // trigger click on multi image when clicking on border images
    $(".productThumbnails ul li img.thumbnailBorder").click(function() {
        $(this).next("img").trigger("click");
    });

    // trigger click on product image when clicking on border image
    $(".productImage .productBorder").click(function() {
        $(this).next("a").trigger("click");
    });

    // Product Variant Table Alternating Row Colors
    $("#variants tbody tr:odd td").addClass("alt");

    // Buying Guide Panels
    $(".buyingGuide h3").click(function() { $(this).next("div").slideToggle(); });

    // Humidor Choose a Humidor
    $(".choose").click(function() {
        var targetOffset = $(".buyingGuide h3:eq(1)").offset().top;
        $("html, body").animate({ "scrollTop": targetOffset }, "slow");
        $(".buyingGuide div:eq(1)").slideDown();
    });

    // animate button sprites
    $("#product .productInfo .addToCartForm input.addToCart, input.customizeAndBuy").hover(
        function() { $(this).css("background-position", "0 -" + $(this).outerHeight() + "px"); },
        function() { $(this).css("background-position", "0 0"); }
    );

    if ($("div.Engraving input[type='radio']:checked").length > 0) {
        $("#toggleEngraving").attr("checked", "checked");
        $("div.Engraving").show();
    }

    if ($("div.NamePlate input[type='radio']:checked").length > 0) {
        $("#toggleNamePlate").attr("checked", "checked");
        $("div.NamePlate").show();
    }


    if ($("div.OtherOptions select[selectedIndex!=0]").length > 0) {
        $("#toggleOtherOptions").attr("checked", "checked");
        $("div.OtherOptions").show();
    }

    // init the default option (doing it in the xslt was becoming a PITA
    var totalChecked = 0;
    $("div.KitSectionHeader input[type='checkbox']").each(function() { if ($(this).is(":checked")) { totalChecked++; } });

    // customize and buy transition
    $("input.customizeAndBuy").click(function() {
        $("#customizeKit").slideDown("slow");
        $("html, body").animate({ "scrollTop": "400px" }, "slow");
    });

    var jCurrSubmit = $("#customizeKit div.AddToCartForm input.addToCart");
    var jCurrSubmitScript = jCurrSubmit.attr("onclick");
    jCurrSubmit.attr("onClick", "");

    jCurrSubmit.click(function() {
        return ValidateKit();
    });

    // NO UPGRADES - clear all options
    $("div.KitSectionHeader #toggleNoUpgrades").click(function() {
        $("div.KitSectionContent input[type='radio'], div.KitSectionHeader input[type='checkbox']:not(input[id='toggleNoUpgrades'])").removeAttr("checked");
        $("div.KitSectionContent select").each(function() {
            $(this).children("option:eq(0)").attr("selected", "selected");
        });
        $("td.namePlateText textarea, td.engravingText input[type='text']").val("");
    });

    // OTHER CHECKBOXES CHOSEN - if unchecked, clear the current content's options. if checked, chear the "no upgrades" option
    $("div.KitSectionHeader input[type='checkbox']:not(input[id='toggleNoUpgrades'])").click(function() {
        if ($(this).is(":not(:checked)"))
            $(this).parent().next("div.KitSectionContent").slideUp().find("input[type='radio']").removeAttr("checked");
        else {
            $(this).parent().next("div.KitSectionContent").slideDown();
            $("#toggleNoUpgrades").removeAttr("checked");
        }
    });

    // OPTIONS CHOSEN - if any options chosen , set the section's checkbox and clear the top
    $("div.KitSectionContent input[type='radio']").click(function() {
        if ($(this).is(":checked")) {
            $(this).parents("div.KitSectionContent").prev("div.KitSectionHeader").children("input[type='checkbox']").attr("checked", "checked");
            $("#toggleNoUpgrades").removeAttr("checked");
        }
    });

    // if nothing is selected, select the first one
    if (totalChecked == 0)
        $("#toggleNoUpgrades").attr("checked", "checked");




    $("div.KitSectionHeader #toggleNoUpgrades").click(function() {
        if (!$(this).is(":checked"))
            $("div.KitSectionContent").slideDown();
        else
            $("div.KitSectionContent").slideUp();
    });

    // SF kits page didnt bother to put the color selection inside the correct form, so we're appending it with JS
    $("td.productInfo div.AddToCartForm #Color").change(function() {
        // remove any current one...
        $("#customizeKit form input[name='Color']").remove();

        // if valid, append it inside the form
        if ($(this).val() != "-,-")
            $("#customizeKit form").append("<input type=\"hidden\" name=\"Color\" value=\"" + $(this).val() + "\" />");
    });

    $("td.productInfo div.AddToCartForm #Size").change(function() {
        // remove any current one...
        $("#customizeKit form input[name='Size']").remove();

        // if valid, append it inside the form
        if ($(this).val() != "-,-")
            $("#customizeKit form").append("<input type=\"hidden\" name=\"Size\" value=\"" + $(this).val() + "\" />");
    });

    // category list hover
    $(".search ul.categoryListing li, .category ul.categoryListing li").hover(
        function() { $(this).addClass("hover"); },
        function() { $(this).removeClass("hover"); }
    );

    // run the qtip script
    $("#engraveIt").each(function() {
        var inventory = $(this).prev("span").text();

        $(this).qtip({
            content: "Engrave this humidor!",
            style: {
                tip: 'leftMiddle',
                name: 'light'
            },
            position: {
                corner: {
                    target: 'rightMiddle',
                    tooltip: 'leftMiddle'
                }
            },
            show: 'mouseover',
            hide: 'mouseout'
        });
    });

    $("div.addressForm #password, div.addressForm #password2").blur(function() {
        var pwLength = $(this).val().length;

        if (pwLength < 5 && pwLength > 0)
            alert("Please enter a password greater than 5 characters");
    });



    // loading screen
    var jLoad = $("<div></div>");
    var jLoadImage = $("<img>");

    jLoadImage.attr("src", "/skins/Skin_1/images/loading.gif");
    jLoadImage.css({ margin: "0 auto", display: "block", marginTop: ($(window).height() / 2) - 50 });

    jLoad.attr("id", "loadWait");
    jLoad.css({ position: "fixed", "z-index": 999, width: $(window).width(), height: "100%", top: "0px", left: "0px", opacity: "0.8", backgroundColor: "#000000" });
    jLoad.hide();
    jLoad.append(jLoadImage);

    $("body").append(jLoad);

    // bind the dom elements to init the load screen
    var aryBindings = [];
    aryBindings.push("body.checkout #pnlCartAllowsShippingMethodSelection input[type='radio']");
    aryBindings.push("body.checkout #chkRushOrder");

    $(aryBindings.join(", ")).click(function() { $("#loadWait").show(); });
});
// end kickoff

function ValidateKit()
{
    var errors = [];

    // check nameplate fields
    if ($("#toggleNamePlate").is(":checked") && ($("div.NamePlate input[type='radio']:checked").length == 0 || $("div.NamePlate td.namePlateText textarea").val().length == 0))
        errors.push("* If you are adding a nameplace, please complete all fields");

    // check nameplate fields
    if ($("#toggleEngraving").is(":checked") && ($("div.Engraving input[type='radio']:checked").length == 0 || $("div.Engraving td.engravingText input[type='text']").val().length == 0))
        errors.push("* If you are adding an engraving, please complete all fields");

    if ($("td.productInfo div.AddToCartForm #Color").val() == "-,-")
        errors.push("* Please select a color");

    if ($("td.productInfo div.AddToCartForm #Size").val() == "-,-")
        errors.push("* Please select a size");

    if (errors.length > 0)
    {
        alert(errors.join("\n"));
        return false;
    }
    else
        return true;
}

function ExpandMiniCart()
{
    var aryItems = [];
    var passedArgs = arguments;

    $(document).ready(function()
    {
        for (i = 0; i < passedArgs.length; i++)
            aryItems.push("#item_" + passedArgs[i]);

        $(aryItems.join(", ")).animate({ "backgroundColor": "#dd6a06" }, "slow").animate({ "backgroundColor": "#FEFF99" }, "slow", function() { $(this).css("background-color", "transparent"); });
    });
}



// <-- REQUIRED FOR FORGOT PASSWORD TOGGLE
function forgotpassword_toggle() {
    if ($("#forgot-display").is(":hidden")) {
        $("#forgot-display").slideDown("slow");
    }
    else {
        $("#forgot-display").slideUp("fast");
    }
}
// END FORGOT PASSWORD TOGGLE -->



// <-- REQUIRED FOR DEBUGMODE
function toggleSingleDiv(id) {
    if ($("#" + id).is(":hidden")) {
        $("#" + id).slideDown("fast");
    }
    else {
        $("#" + id).slideUp("fast");
    }
    return false;
}
// END DEBUGMODE -->









//------------------------------------------------
// Store Front Default Functionality Below
//------------------------------------------------

//----------Switches Visibility on Items----------
function switchVisibility(obj) {
    var el = document.getElementById(obj);

    if ( el.style.display != "none" ) {
        el.style.display =
        'none';
    }

    else {
        el.style.display =
        '';
    }
}

function switchVisibilityCheckbox(obj, checkbox) {
    var el = document.getElementById(obj);

    if ( el.style.display != "none" && document.getElementById(checkbox).checked == true) {
        el.style.display =
        'none';
    }

    else if (document.getElementById(checkbox).checked == false) {
        el.style.display =
        '';
    }
}

function switchVisibilityCheckout(obj, checkbox) {
    var el = document.getElementById(obj);

    var style_attrib = window.document.createAttribute("style");
        style_attrib.nodeValue = "display: none;";
    //scDiv.attributes.setNamedItem(style_attrib);

    if (document.getElementById(checkbox).checked == true) {
        el.style.display =
        'none';
    }

    else if (document.getElementById(checkbox).checked == false) {
        el.style.display =
        '';
    }
}

//-------------Validate Function For Quantity Selection Kit Group-------------
function validatebox()
{
	var msg1='Please verify your quantities and select exactly';
    var kitgroup=document.forms['kit'].elements['kgid'];

    var kid=kitgroup.value;
    var kitgroupid=new Array();
    kitgroupid=kid.split(",");

	for(var j=0; j<kitgroupid.length-1; j++)
	{
	    var gid=document.forms['kit'].elements['groupid_' + kitgroupid[j]];
	    group_id=gid.value;
	    var mid=document.forms['kit'].elements['max_number_' + kitgroupid[j]];
	    max_number=mid.value;
	    var tid=document.forms['kit'].elements['textboxid_' + kitgroupid[j] ];
	    var textboxid1=tid.value
	    var mval=document.forms['kit'].elements['max_value_' + kitgroupid[j] ];
	    var max_value=parseInt(mval.value);
	    var ids =new Array();
	    ids=textboxid1.split(",");
	    var sum=0;
	    var i=0;

	    while(max_number > 0)
	    {
		    if(ids[i]!="")
		    {
			    var value='KitGroupID_' + group_id + '_TextOption_' + ids[i];
			    var sum1=document.forms['kit'].elements['KitGroupID_' + group_id + '_TextOption_' + ids[i]];
			    i=i+1;
	            if (sum1.value!="")
                {
          	        sum=sum + parseInt(sum1.value);
			    }
			    max_number=max_number-1;
		    }
	    }

	    if (parseInt(sum) < parseInt(max_value) )
	    {
		    window.alert(msg1 + ' ' + max_value + '.');
	    	return false;
	    }
	    else if (parseInt(sum) > parseInt(max_value) )
	    {
		    window.alert(msg1 + ' ' + max_value + '.');
	   		return false;
	    }


	    if(ids.length>=0)
	    {
	    	ids.pop();
	    }

	    sum=0;
	    group_id=0;
		max_number=0;
		max_values=0;
	}
}
