﻿/// <reference path="/js/jquery-1.3.2.js" />

$(document).ready(function () {
    SBX.Initialize();

})


SBX = {
    TrackEvent: function (category, action, optional_label, optional_value) {
        if (DO_PERFORM_GOOGLE_TRACKING) {
            //pageTracker._trackEvent(category, action, optional_label, optional_value); - Traditional syntax
            _gaq.push(['_trackEvent', category, action, optional_label]);
        }
    },

    TrackPageView: function (page) {
        if (DO_PERFORM_GOOGLE_TRACKING) {
            //pageTracker._trackPageview(page); - Traditional syntax
            _gaq.push(['_trackPageview', page]);
        }
    },

    Initialize: function () {
        $("html").addClass("hasJS");
        initAddThis();
        $("iframe").css("width", "95px");

        $("form").each(function () { $(this).validate({ errorClass: "input-validation-error" }); });
        //Set up JQuery Validation rules that are global to the application.
        try {
            $(".fmt_accountnumber").rules("add", {
                minlength: 7,
                maxlength: 7,
                messages: {
                    minlength: jQuery.format("Account # must be {0} characters"),
                    maxlength: jQuery.format("Account # must be {0} characters")
                }
            });
        } catch (e) { }

        // Globalized external link handler
        $("a[rel='ext']").click(function () {
            window.open($(this).attr("href"), "_blank");

            return false;
        });

        $("a.new").click(function () {
            window.open($(this).attr("href"), "_blank");
            return false;
        });

        //Globalized PDF link handler
        $("a[href $= '.pdf']:not([rel='ext'])").click(function () {
            SBX.TrackPageView($(this).attr("href"));
        });

        //Globalized ContactUs Submit Button Tracking
        $("input.contactus_submit").click(function () {
            SBX.TrackEvent("Contact Us", CONTACT_FORM_ID, "Submit");
        });




        // Video popin links
        $("a.video").click(function () {

            SBX.TrackPageView($(this).attr("href"));

            $.fancybox(
                {
                    'href': $(this).attr("href"),
                    'autoDimensions': true,
                    'onComplete': function () {
                        $("div#fancybox-inner a[href$='.flv']").each(function () {
                            $(this).flowplayer({
                                src: "/Resources/swf/flowplayer-3.1.5.swf",
                                wmode: "opaque"
                            }, {
                                clip: {
                                    url: $(this).attr("href"),
                                    autoPlay: true,
                                    autoBuffering: true
                                },

                                plugins: {
                                    controls: {
                                        autoHide: "always"
                                    }
                                }
                            });
                        });
                    }

                }
            );

            return false;
        });

        // Print Page (Static Recipe Buttons)
        $("a.printRecipe").click(function () {
            window.print();
            return false;
        })

        //Turn off automcomplete in js... this is a hack because autocomplete is not xhtml compliant
        $("#global_search_box .textbox").attr("autocomplete", "off");
        $("#quickAddOrderItem_SKUNumber").attr("autocomplete", "off");

        //Hide the cart status message if it is visible.
        if ($("#topNav dd.cart_status div.message").length > 0) {
            $("#topNav dd.cart_status div.message").fadeIn(600, function () {
                setTimeout(function () {
                    $("#topNav dd.cart_status div.message").fadeOut(500, function () { $("#topNav dd.cart_status").removeClass("cart_status_notification") });
                }, 6000);
            });

        }



        //Load Flowplayer for any anchors pointing to .flv files
        $("a[href$='.flv']").each(function () {
            $(this).flowplayer({
                src: "/Resources/swf/flowplayer-3.1.5.swf",
                wmode: "opaque"
            }, {
                clip: {
                    url: $(this).attr("href"),
                    autoPlay: true,
                    autoBuffering: true
                },

                plugins: {
                    controls: {
                        autoHide: "always"
                    }
                }
            });
        });


        var submitC = 0;
        $(".f1Submit").click(function () {
            if (submitC < 1) {
                if ($("form.marketing_download_brand_guidelines").valid()) {
                    submitC++;
                    $(".firstForm, form h1, form p").hide();
                    $(".secondForm, .button, #actions").show();
                    $("#Agree").addClass("required");
                    $(".f1Submit").attr("value", "Download");
                    return false;
                }
            }

        });

        




        SBX.LoadEffectsManagers();
        SBX.Coffee.Initialize();
    },



    LoadEffectsManagers: function () {
        $(".ui-fade-rollover").each(function () {
            if ($(this).attr("ui-fade-rollover-effect_loaded") == "true") return;
            $(this).attr("ui-fade-rollover-effect_loaded", "true");

            var wrapper = "<div style='display: block; height: auto; width: auto; background-repeat: no-repeat; background-image: url(" + $(this).attr("src").replace("_off", "_over") + ")'></div>";
            if ($(this).parent().get(0).tagName == "A") {
                $(this).parent().wrap(wrapper);
            }
            else {
                $(this).wrap(wrapper);
            }

            $(this).bind("mouseenter", function (e) {
                $(this).stop().animate({ opacity: 0 }, 300);
            });
            $(this).bind("mouseleave", function (e) {
                $(this).stop().animate({ opacity: 1 }, 300);
            });
        });
    }
}

SBX.Home = {
    Initialize: function() {
        var selectedVideo = "f2";
        //$("#videoHome div." + selectedVideo + " img").attr("src", "/images/play_cover.png");
        $('.promos .box').hover(
            function() {
                SBX.Home.OpenPromoBox(this);
            },
            function() {
                SBX.Home.ClosePromoBox(this);
            });

    },

    OpenPromoBox: function(obj) {
        $(obj).stop().addClass("hover").animate({
            "top": ($(document.body).css("font-size").replace("px", "") / 16) * -184,
            "height": ($(document.body).css("font-size").replace("px", "") / 16) * (55 + 184)
        }, 500);
    },

    ClosePromoBox: function(obj) {
        $(obj).stop().removeClass("hover").animate({
            "top": 0,
            "height": ($(document.body).css("font-size").replace("px", "") / 16) * 65
        }, 200);
    },

    LoadVideo: function(selectedVideo) {

        var p_wmode = $.browser.mozilla ? "window" : "opaque";
        var duration = 300;
        var openWidth = ($(document.body).css("font-size").replace("px", "") / 16) * 452;
        var closeWidth = ($(document.body).css("font-size").replace("px", "") / 16) * 85;
        if ($("#videoHome div." + selectedVideo).width() == openWidth) duration = 0;

        $("#videoHome .feature a").show();
        $("#videoHome .feature .video").html(" ").hide();
        $("#videoHome .feature img").attr("src", "/images/blank.gif");
        $("#videoHome div." + selectedVideo + " a").hide();

        $("#videoHome div." + selectedVideo).animate({ width: openWidth }, duration, function() {
            $("#videoHome .feature .video").html(" ").hide();
            $("#videoHome div." + selectedVideo + " .video").show();
            $("#vh_player_" + selectedVideo).flowplayer({
                src: "/Resources/swf/flowplayer-3.1.5.swf",
                wmode: p_wmode
            }, {
                clip: {
                    url: $("#videoHome div." + selectedVideo + " a").attr("href"),
                    autoPlay: true,
                    autoBuffering: true
                },

                plugins: {
                    controls: {
                        autoHide: "always"
                    }
                },

                onFinish: function() {
                    $("#videoHome .feature a").show();
                    $("#videoHome .feature .video").html(" ").hide();
                    $("#videoHome .feature img").attr("src", "/images/blank.gif");
                }
            });
        });

        $("#videoHome div." + selectedVideo).siblings(".feature").animate({ width: closeWidth }, duration);
        return false;
    }
}

SBX.ReOrder = {
    RefreshCartStatus: function() {
        var originalText = SBX.Utility.Trim($("a.cart_status").text());
        $.get(ACT_REORDER_CARTSTATUS, function(data) {
            $("a.cart_status").html(data);
            if (originalText != SBX.Utility.Trim($("a.cart_status").text())) {
                alert("Your cart was updated.");
            }
        });
    },

    CancelCart: function() {
        if (confirm('Are you sure you want to clear all items from your cart?')) {
            window.open(ACT_REORDER_CANCEL_CART + "?r=" + Math.random(), "_top");
        }
        return false;
    }
}

SBX.Search = {
    DelayedSearchTimer: null,
    
    SetSearchType: function(value) {
        if(value == "SITE") actionValue = $("#searchForm").attr("action", ACT_SEARCH_SITE);
        if(value == "PRODUCT") actionValue = $("#searchForm").attr("action", ACT_SEARCH_PRODUCT);
        if(value == "RECIPE") actionValue = $("#searchForm").attr("action", ACT_SEARCH_RECIPE);
        $("#searchForm").submit();
    },
    
    ShowSearchOptions: function() {
        $("#searchForm .searchOptions").show();
        this.CancelHideSearchOptions();
    },
    
    HideSearchOptions: function() {
        $("#searchForm .searchOptions").hide();
    },
    
    DelayedHideSearchOptions: function() {
        this.CancelHideSearchOptions();
        this.DelayedSearchTimer = setTimeout(SBX.Search.HideSearchOptions, 2000);
    },
    
    CancelHideSearchOptions: function() {
       clearTimeout(this.DelayedSearchTimer);
    }
}

SBX.Recipes = {
    ToggleFilterList: function() {
        if ($(".filterList").is(":visible")) { $(".filterList").fadeOut(300); } else { $(".filterList").fadeIn(300); }
    }
}

SBX.Coffee = {
    ToggleBrewerList: function(obj) {
        $("div.brewerlist").not($(obj).parents("tr").first().find("td div.brewerlist").toggle()).hide();
    },

    SuccessFilterCategory: function(context) {
        $("#filtered_category_label").html($(this).html()).fadeIn(300);
        SBX.Coffee.ToggleFilterList();
    },

    ToggleFilterList: function() {
        if ($(".filterList").is(":visible")) { $(".filterList").slideUp(300); } else { $(".filterList").slideDown(300); }
    },

    Initialize: function() {
        $(".filterList").hide();

        $(".filterButton a").click(function() {
            SBX.Coffee.ToggleFilterList()
            filterIndicate("filterArrow", $(".filterButton img").attr("alt")) 
        });

        $("td.brewers a.toggle").bind("click", function() {
            SBX.Coffee.ToggleBrewerList(this);
            return false;
        });
    }
}


SBX.Utility = {
    Trim: function(stringToTrim) {
        return stringToTrim.replace(/^\s+|\s+$/g, "");
    },

    LTrim: function(stringToTrim) {
        return stringToTrim.replace(/^\s+/, "");
    },

    RTrim: function(stringToTrim) {
        return stringToTrim.replace(/\s+$/, "");
    }
}

function filterIndicate(imgId, alt) {
    
    if (alt == "arrow-right") {
        $("#" + imgId).attr("alt", "arrow-down");
        $("#" + imgId).attr("src", $("#" + imgId).attr("src").replace("_right", "_down"));
    }

    else {
        $("#" + imgId).attr("alt", "arrow-right");
        $("#" + imgId).attr("src", $("#" + imgId).attr("src").replace("_down", "_right"));
    }
    //alert(alt);
}

function initAddThis() {
    addthis.init()
}

function redirect(linkPath) {
    window.location.href = linkPath;
}



