/*
--------------------------------------------------

Weaver Popcorn
application.js

David Munger [david.munger@acquitygroup.com]
3/19/2008

Copyright © 2009 Acquity Group LLC

--------------------------------------------------
*/

/* Load all required functions on DOM load */
$(document).ready(function(){

    // Safari stylesheet
    if (BrowserDetect.browser == "Safari") {
        $("head").append('<link media="all" href="styles/safari.css" type="text/css" rel="stylesheet">');
    }

    // FF Win stylesheet
    if (BrowserDetect.browser == "Firefox" && BrowserDetect.OS == "Windows") {
        $("head").append('<link media="all" href="styles/ff-win.css" type="text/css" rel="stylesheet">');
    }

    // Fix PNGs
    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") {
        DD_belatedPNG.fix('.png');
    }

    // Primary navigation dropdowns
    $('.sf-menu').supersubs({
        minWidth: 15,
        maxWidth: 20,
        extraWidth: 1
    }).superfish({
        delay: 415,
        autoArrows: false,
        animation: {height: 'show'},
        speed: 415,
        dropShadows: false
    }).find('ul').bgIframe({
        opacity: false
    });

    // Home Page: Center to middle element of carousel when page is loaded
    var size = $("div.carousel div.productInfoContainer").size();
    if (size > 0) {
        var midIndex = ((size + (size % 2)) / 2) - 1;
        //if we only have two, select second element
        if (size > 1 && midIndex == 0) {
            midIndex++;
        }
        $("div.carousel div.productInfoContainer").eq(midIndex).addClass("selected");
        $("div.carousel div.filmstripWrapper ul li").eq(midIndex).addClass("selected");

        // Slide to the correct position
        var thisStrip = $("div.filmstripWrapper div.filmstripFrame ul");
        // move over midIndex-1 slots to the right. index 1 is centered by default
        var cellWidth = thisStrip.find("li").eq(0).width() * (midIndex - 1);
        var moveValue = "-=" + cellWidth + "px";
        thisStrip.animate({
            left: moveValue
        }, 0);
    }

    // Apply carousel nav to appropriate elements
    $("a.previous, a.next, .filmstripFrame ul li a").carouselNav();

    // Scout support windowshade
    $("#supportChooser a").click(function() {
        $("#windowshade").slideDown(830);
        return false;
    });

    $("#windowshade a.close").click(function() {
        $("#windowshade").slideUp();
        return false;
    })

    // Email Template chooser
    $("fieldset.chooseTemplate select").change(function() {

        var templateFieldset = $(this).parents("fieldset.chooseTemplate").eq(0);

        // first turn off the previously-selected one
        templateFieldset.find(".templateCopy").removeClass("selected");

        // now turn on the one just selected by the user
        templateFieldset.find("#" + $(this).val()).addClass("selected");

    });

    // Select All checkbox
    $("fieldset.selectAll input:checkbox").click(function() {

        var groupFieldset = $(this).parents("fieldset.selectAll").eq(0).parents("fieldset");
        var targetValue;

        if ($(this).is(":checked")) {
            targetValue = true;
        } else {
            targetValue = false;
        }

        groupFieldset.find(".checkboxGroup input:checkbox").each(function() {
            this.checked = targetValue;
        });

    });

    // Tabbed Box
    $(".tabbedBox ul.tabNavigation li a").click(function () {

        var thisBox = $(this).parents(".tabbedBox").eq(0);

        // remove pre-existing selected states
        thisBox.find("ul.tabNavigation li").each(function(i){
            $(this).removeClass("selected");
        });
        thisBox.find("div.tabContent").each(function(i){
            $(this).removeClass("selected");
        });

        // activate selected tab and content
        $(this).parent().addClass("selected");
        var selectedIdNode = $(this).parent().attr("id").split("-")[1];
        $("#content-" + selectedIdNode).addClass("selected");

        // if there is only on nutritional info div, show it
        $("#content-" + selectedIdNode + " div.nutritionTableWrapper:only-child").addClass("selected");

        return false;
    });

    // Nutritional Info Nav
    $(".tabbedBox ul.nutritionNav li a").click(function() {

        var thisNutritionBlock = $(this).parents(".tabContent.nutritionInfo").eq(0);

        // remove pre-existing selection
        thisNutritionBlock.find("li").each(function(i) {
            $(this).removeClass("selected");
        });

        thisNutritionBlock.find("div.nutritionTableWrapper").each(function(i) {
            $(this).removeClass("selected");
        });

        // activate selected link and content
        $(this).parent().addClass("selected");
        var selectedIdNode = $(this).parent().attr("id").split("-")[1];
        $("#nutritionTable-" + selectedIdNode).addClass("selected");

        return false;
    });

    // Product Image Switching
    $(".imageArea .thumbnails a").click(function() {

        var thisImageArea = $(this).parents(".imageArea").eq(0);

        // remove pre-existing selection
        thisImageArea.find("a.selected").each(function(i){
            $(this).removeClass("selected");
        });
        thisImageArea.find("img.selected").each(function(i){
            $(this).removeClass("selected");
        });

        // activate newly selected image
        $(this).addClass("selected");
        var selectedIdNode = $(this).attr("id").split("-")[1];
        $("#image-" + selectedIdNode).addClass("selected");

        return false;
    });

    // show parent/guardian section for under-13 signups
    // not entirely accurate -- calculation ignores leap years
    $("#newAccount-createAccount").click(function(){
        if ($("div#under13").css("display") == "block") {
            return true;
        }
        return handleParentVerificationDiv();
    });

    //you might need to show the div on page load (if the forms already been submitted)
    handleParentVerificationDiv();

    // show #updateUnit on scouts profile page
    $("a#myProfile-updateUnit").click(function(){
        if ($("#updateUnit").css("display") == "block") return false;

        slideFadeIn($("#updateUnit"));
        return false;
    });

    // apply table striping
    $("table.stripe tbody tr:even").addClass("even");

    // Edit address toggle
    $("a.editAddressButton").click(function(){

        var thisRow = $(this).parent().parent();

        // toggle off if this is already in edit mode
        if (thisRow.hasClass("editMode")) {

            thisRow.removeClass("editMode");

            // next row is the edit form row
            thisRow.next().addClass("inactive");

        } else {

            // toggle off edit mode for any previously activated
            $("table.addressTable tr.editMode").removeClass("editMode");
            $("table.addressTable tr.editAddress").addClass("inactive");

            // Put row in edit 'mode'
            thisRow.addClass("editMode");

            // Reveal edit row beneath
            thisRow.next().removeClass("inactive");
        }

        return false;
    });

    // confirmation for clear form
    $("input.reset").click(function(){
        if (confirm("Are you sure you want to clear all the values in this form?")) {
            return;
        } else {
            return false;
        }
    });

    // go back to the shopping cart
    $("input.back").click(function(){
        window.location.href ="../checkout/shopping_cart.jsp";
    });

    // confirmation for delete address
    $(".confirmDelete").click(function(){
        if (confirm("Are you sure you want to delete this address?")) {
            return;
        } else {
            return false;
        }
    });

    // Tooltips
    // act on each, otherwise cluetip() will only be called on the first element in the array
    $("a.tooltip").each(function(){
        $(this).cluetip({
            attribute: "rel",
            cluetipClass: "weaver",
            cluezIndex: "5000",
            dropShadowSteps: "3",
            fx: { open: "fadeIn" },
            local: true,
            waitImage: false
        });

        if ($(this).children("img")) {
            // remove alt attribute on hover so it doens"t show in IE
            var imgalt = $(this).children("img").attr("alt")
            $(this).hover(function(){
                $(this).children("img").attr("alt", "")
            }, function(){
                $(this).children("img").attr("alt", imgalt)
            })
        }
    })

    $("a.product-tooltip").each(function(){
        $(this).cluetip({
            attribute: "rel",
            cluetipClass: "weaver",
            cluezIndex: "5000",
            dropShadowSteps: "3",
            fx: { open: "fadeIn" },
            local: true,
            waitImage: false,
            positionBy: "auto",
            leftOffset: 0
        });

        if ($(this).children("img")) {
            // remove alt attribute on hover so it doens"t show in IE
            var imgalt = $(this).children("img").attr("alt")
            $(this).hover(function(){
                $(this).children("img").attr("alt", "")
            }, function(){
                $(this).children("img").attr("alt", imgalt)
            })
        }
    })

    $("a.tooltip").click(function() {
        return true;
    });


    // "Name This Address" default for new addresses on single address forms.
    // Uses the 'rel' attribute to determine an element ID to target
    $(".defaultSaveName").blur(function() {

        if ($(this).val() != "") {

            var target = $("#" + $(this).attr("rel"));

            if (target.val() == "") {
                target.val($(this).val());
            }
        }
    });


    // toggle the "Save as default..." checkbox label on Manage Addresses page
    // First, set it up the way it should be by default...
    $(".addressLabelToggle").each(function() {

        var radioValue = $("input[name='" + $(this).attr("name") + "']:checked").val();
        var addressLineNumber = $(this).attr("id").split("-")[1];

        if (radioValue == "shipping") {
            $("#defaultLabel-billing-" + addressLineNumber).addClass("hidden");
            $("#defaultLabel-shipping-" + addressLineNumber).removeClass("hidden");
        } else { // otherwise assume it's billing
            $("#defaultLabel-shipping-" + addressLineNumber).addClass("hidden");
            $("#defaultLabel-billing-" + addressLineNumber).removeClass("hidden");
        }

    });

    $(".addressLabelToggle").click(function() {

        var addressLineNumber = $(this).attr("id").split("-")[1];

        if ($(this).val() == "shipping") {
            $("#defaultLabel-billing-" + addressLineNumber).addClass("hidden");
            $("#defaultLabel-shipping-" + addressLineNumber).removeClass("hidden");
        } else { // otherwise assume it's billing
            $("#defaultLabel-shipping-" + addressLineNumber).addClass("hidden");
            $("#defaultLabel-billing-" + addressLineNumber).removeClass("hidden");
        }

    });


    $(".leaderTypeToggle").click(function() {
        handleLeaderTypeToggle();
    });

    // display correct fields on page load...
    handleLeaderTypeToggle();


    // Create Account - 'Same as Shipping' checkbox which duplicates
    // the shipping address field values into the billing address fields.
    //
    // Note: IE doesn't seem to trigger the 'change' until the element loses
    // focus so we also bind to some others events.
    $(".sameAsShipping").bind("change click keypress", function() {
        sameAsShippingChange(this);
    });

    // copy over values on page refresh
    if ($(".sameAsShipping").is(":checked")) {
        sameAsShippingChange($(".sameAsShipping"));
    }

    // Council name input auto-complete (type-ahead)
    $("#createNewAccount-councilName, #staffSalesReport-councilName").autocomplete("../services/council_name_suggest.jsp",
        {
            maxItemsToShow: 20,
            selectFirst: true
        }
    );


    // BEGIN Scout Chooser Modal functions

    // var suppressScoutChosenModal = false; // remove for production; instead, put inline
                             // into each page to reflect session state
    var targetUrl = ""; // global variable to be used for preserving the
                        // original target of a diverted click (for scout chooser modal)

    // Callback function to position the modal relative to the scroll state of the viewport
    var positionModal = function(hash) {

        targetUrl = hash.t.href;
        var topOffset = 120;
        var leftOffset = -50;

        if (typeof window.pageYOffset != 'undefined') {
            var topScrollLocation = window.pageYOffset;
        } else {
            var topScrollLocation = document.documentElement.scrollTop;
        }

        var popupTop = (topScrollLocation + topOffset);
        var popupLeft = ((document.documentElement.clientWidth / 2) - ($("#scoutChooserModal").width()) + leftOffset);
        $("#scoutChooserModal").css("top", popupTop);
        $("#scoutChooserModal").css("left", popupLeft);

        $("#scoutChooserModal").load("services/scout_chooser_modal.jsp", function() {
            $("#scoutChooserModal #continue").attr("href", targetUrl);
            $("form.divertedUrl input.targetUrl").val(targetUrl);

            // var myHTML = $("#messaging").html();
            // alert('myHTML: ' + myHTML);

            //

            if (typeof(hasModalError) != "undefined") {
                if ( hasModalError == true ) {
                    $("#messaging").html(varModalErrorMessage);
                }
            }
        });

        hash.w.show();

    };

    // initialize the scout chooser modal to intercept clicks if no scout/council has been chosen
    if (typeof(suppressScoutChosenModal) != "undefined") {
        if (suppressScoutChosenModal != true) {
            $("#scoutChooserModal").jqm(
                {
                    modal: true,
                    onShow: positionModal, // callback function to position the modal
                    trigger: "a:not(.modalException)"
                }
            );
        }
    }
    // END Scout Chooser Modal functions

    //initialize the scout prevent modal to intercept clicks if the scout tries to checkout
    if(isScout=true){
            $("#scoutPreventModal").jqm();
            $("#scoutPreventModal").jqmShow();
    }
    // END Scout Prevent Modal

});

$.fn.carouselNav = function() {

    $(this).click(function() {

        var thisCarousel = $(this).parents(".carousel").eq(0);
        var selectedInfoContainer = thisCarousel.find(".productInfoContainer.selected");
        var newInfoContainerSelection = selectedInfoContainer.next(); // defaults to move forward
        var thisStrip = thisCarousel.find(".filmstripWrapper .filmstripFrame ul");
        var selectedItem = thisStrip.find(".selected");
        var newItemSelection = selectedItem.next(); // defaults to move forward
        var cellWidth = thisStrip.find("li").eq(0).width();
        var moveValue = "-=" + cellWidth + "px"; // defaults to move forward

        // Is this a filmstrip cell?
        if ($(this).is(".filmstripFrame ul li a")) {

            var thisCell = $(this).parents("li").eq(0);

            if (! thisCell.hasClass("selected")) {
                if (thisCell.next().hasClass("selected")) {
                    moveValue = "+=" + cellWidth + "px";
                    newItemSelection = selectedItem.prev();
                    newInfoContainerSelection = selectedInfoContainer.prev();
                } // otherwise keep the default, which is to move forward
            } else {
                // drop out if this is already selected
                return false;
            }

        }

        // Is this the PREVIOUS link?
        else if ($(this).is("a.previous")) {

            // can't go any further if the selected item is first
            if (selectedItem.is(".filmstripFrame ul li:first-child")) {
                return false;
            } else {
                moveValue = "+=" + cellWidth + "px";
                newItemSelection = selectedItem.prev();
                newInfoContainerSelection = selectedInfoContainer.prev();
            }
        }

        // Is this the NEXT link?
        else if ($(this).is("a.next")) {

            // can't go any further if the selected item is last
            if (selectedItem.is(".filmstripFrame ul li:last-child")) {
                return false;
            }
            // move is still defaulted to forward, so nothing else to do here
        }

        // here comes the actual effect!
        thisStrip.animate({
            left: moveValue
        }, 500);

        selectedItem.removeClass("selected");
        newItemSelection.addClass("selected");
        selectedInfoContainer.removeClass("selected");
        newInfoContainerSelection.addClass("selected");
        return false;
    });
};

function sameAsShippingChange(element) {

    if ($(element).is(":checked")) {

        // Copy billing address fields to shipping fields; disable entry on shipping fields

        $("#createNewAccount-billingFirstName").val($("#createNewAccount-shippingFirstName").val());
        $("#createNewAccount-billingFirstName").attr("disabled", "disabled");

        $("#createNewAccount-billingLastName").val($("#createNewAccount-shippingLastName").val());
        $("#createNewAccount-billingLastName").attr("disabled", "disabled");

        $("#createNewAccount-billingAddress1").val($("#createNewAccount-shippingAddress1").val());
        $("#createNewAccount-billingAddress1").attr("disabled", "disabled");

        $("#createNewAccount-billingAddress2").val($("#createNewAccount-shippingAddress2").val());
        $("#createNewAccount-billingAddress2").attr("disabled", "disabled");

        $("#createNewAccount-billingCity").val($("#createNewAccount-shippingCity").val());
        $("#createNewAccount-billingCity").attr("disabled", "disabled");

        $("#createNewAccount-billingState").val($("#createNewAccount-shippingState").val());
        $("#createNewAccount-billingState").attr("disabled", "disabled");

        $("#createNewAccount-billingZip").val($("#createNewAccount-shippingZip").val());
        $("#createNewAccount-billingZip").attr("disabled", "disabled");

        $("#createNewAccount-billingPhoneAreaCode").val($("#createNewAccount-shippingPhoneAreaCode").val());
        $("#createNewAccount-billingPhoneAreaCode").attr("disabled", "disabled");

        $("#createNewAccount-billingPhoneExchange").val($("#createNewAccount-shippingPhoneExchange").val());
        $("#createNewAccount-billingPhoneExchange").attr("disabled", "disabled");

        $("#createNewAccount-billingPhoneNumber").val($("#createNewAccount-shippingPhoneNumber").val());
        $("#createNewAccount-billingPhoneNumber").attr("disabled", "disabled");

        $("#createNewAccount-billingAddressName").val($("#createNewAccount-shippingAddressName").val());
        $("#createNewAccount-billingAddressName").attr("disabled", "disabled");
        $("#createNewAccount-billingAddressName").parent().css("display", "none");

    } else {

        // enable the shipping fields

        $("#createNewAccount-billingFirstName").val("");
        $("#createNewAccount-billingFirstName").removeAttr("disabled");

        $("#createNewAccount-billingLastName").val("");
        $("#createNewAccount-billingLastName").removeAttr("disabled");

        $("#createNewAccount-billingAddress1").val("");
        $("#createNewAccount-billingAddress1").removeAttr("disabled");

        $("#createNewAccount-billingAddress2").val("");
        $("#createNewAccount-billingAddress2").removeAttr("disabled");

        $("#createNewAccount-billingCity").val("");
        $("#createNewAccount-billingCity").removeAttr("disabled");

        $("#createNewAccount-billingState").val("");
        $("#createNewAccount-billingState").removeAttr("disabled");

        $("#createNewAccount-billingZip").val("");
        $("#createNewAccount-billingZip").removeAttr("disabled");

        $("#createNewAccount-billingPhoneAreaCode").val("");
        $("#createNewAccount-billingPhoneAreaCode").removeAttr("disabled");

        $("#createNewAccount-billingPhoneExchange").val("");
        $("#createNewAccount-billingPhoneExchange").removeAttr("disabled");

        $("#createNewAccount-billingPhoneNumber").val("");
        $("#createNewAccount-billingPhoneNumber").removeAttr("disabled");

        $("#createNewAccount-billingAddressName").val("");
        $("#createNewAccount-billingAddressName").removeAttr("disabled");
        $("#createNewAccount-billingAddressName").parent().css("display", "block");
    }

}

function slideFadeIn(elem) {
    if (!elem) return;
    if (!jQuery.support.opacity) {
        jQuery(elem).css("display","block");
    }
    else {
        jQuery(elem).css("opacity", "0").slideDown(300, function(){jQuery(this).animate({opacity: 1}, 300)});
    }
}

function slideFadeOut(elem) {
    if (!elem) return;
    if (!jQuery.support.opacity) {
        jQuery(elem).css("display","none");
    }
    else {
        jQuery(elem).animate({opacity:0},300,function(){jQuery(this).slideUp(300)});
    }
}

function handleParentVerificationDiv() {
    var now = new Date();
    var year = now.getYear();
    year < 1000 ? year = year + 1900 : year = year;
    var cutoffDate = Date.UTC(year-13,now.getMonth(),now.getDate());
    if (cutoffDate < Date.UTC($("select.year").val(),$("select.month").val() - 1,$("select.day").val())) {
        slideFadeIn($("div#under13"));
        return false;
    } else if ($("select.year").val() == 0 || $("select.month").val() == 0 || $("select.day").val() == 0) {
        $("div#under13").css("display", "none");
        return true;
    }
}

function handleLeaderTypeToggle() {
    $(".leaderTypeToggle").each(function() {

        var radioValue = $("input[name='" + $(this).attr("name") + "']:checked").val();

        $("#councilNameFieldset").show();
        if (radioValue == "5") {
            $("#unitLeaderFieldset").hide();
        } else if (radioValue == "3") {
            $("#unitLeaderFieldset").show();
        }

        $(".createLeaderAccountButton").show();

    });
}
