﻿/* Victor LaLoggia @ C2, June 12, 2009
*   Sitecore's page editor is implemented with Prototype.js.
*   It is well known that Prototype and jQuery do not play well together.
*   As per Sitecore (http://sitecoresupport.blogspot.com/2009/01/jquery-conflicts-with-pageeditor.html), 
*   vic added this modification (http://docs.jquery.com/Using_jQuery_with_Other_Libraries).
*
*   Every reference to the jQuery '$' nomenclature has been replaced with '$j'
*/
var $j = jQuery.noConflict();

if (typeof GMCR == 'undefined') var GMCR = {};

$j(document).ready(function() {
    // Initialize the sli search complete functionality
    sli_init();

    // My Account mgmt forms
    var myAccount = $j("div.myAccount");
    if ( myAccount[0] ) {
        // IE z-index bug fix
        $j('#datepicker').bgiframe();

        var fc = $j("div.formContainer");  
        if (fc[0]) { //handle my account forms
            $j("input.labelify").labelify({ labelledClass: "light-grey" }); // Inline labels
            $j("label.offscreen + input").addClass("labelless");            // hide offscreen labelsk

            var subheader = $j("li.header");
            if (subheader[0]) { //handle dynamic subheaders
                var legend = $j("legend.dynamic");
                if (legend[0]) { 
                    legend.append(" &mdash; " + subheader.text());
                    subheader.remove();
                }
            }
        }
        var fcColorbox = $j("div.formContainer.lightbox");  
        if (fcColorbox[0]) { // My Account - Lightboxes
            $j("#cbEditClubName").colorbox({width:"740px", inline:true, href:"#divEditClubName"});
            $j("#cbAnchorRecipient").colorbox({width:"500px", inline:true, href:"#divClubRecipientInfo"});
            $j("#cbAnchorBilling").colorbox({width:"740px", inline:true, href:"#divEditClubBillingInfo"});
            $j("#cbAnchorDelivery").colorbox({width:"580px", inline:true, href:"#divClubDeliverySchedule"});
            $j('a.cbCloseWindowButton').click($j.fn.colorbox.close); 
        }
    }
    
    // cvc note 
    var cvsNote = $j("div#cvc-note");
    if (cvsNote[0]) {
         cvsNote.hide();
        $j("a#show-cvc-note").click(function(e) {
            cvsNote.slideToggle();
            e.preventDefault();
        });
        cvsNote.find("a").click(function(e) {
            cvsNote.slideUp();
            e.preventDefault();
        });
    }

    GMCR.ReviewTabNumber = 2;
    GMCR.FeaturesAndSpecsTabNumber = 4;
    GMCR.DisplayFriendlyAjaxError = true;

    //Global ajax error handler
    $j().ajaxError(function(event, xhr, options, ex) {
        GMCR.AjaxError(xhr, options, ex);
    });

    //*******************************
    //TopNav Functions
  
    // IE z-index bug fix
    $j('#megaMenuContainer1').bgiframe();
    $j('#megaMenuContainer2').bgiframe();
    $j('#megaMenuContainer3').bgiframe();
  
    $j('li>a[topnav], li>div[topnav]').hoverIntent({
        sensitivity: 4,
        interval: 100,
        over: ShowMenus,
        timeout: 0,
        out: HideMenus
    });

    //*******************************
    //Show brandName-only css classes
    $j('.' + GMCR.brand + '-only' ).show();

    if (GMCR.brand != "bce") {
        $j('.b2c-only').show();
    }
    
    function ShowMenus() {
        $j('div[id^="megaMenuContainer"]').hide();
        GMCR.currentMenu = $j(this).parents("li[id^='topMenuParent']")[0].id;
    
        var menuID = 'megaMenuContainer';
        if($j(this).attr('id').split('-')[1] == undefined)
        {
            //assuming that the number of departments will be in the single digits
            menuID += GMCR.currentMenu.charAt(GMCR.currentMenu.length - 1);
        }
        else{
            menuID += $j(this).attr('id').split('-')[1]
        }
        $j('#' + menuID).slideDown('fast');  // Increased the drop speed to help prevent sticking menus from quick mouse outs
    }

    function HideMenus() {
        if (GMCR.currentMenu == undefined) {
            GMCR.currentMenu = $j(this).parents("li[id^='topMenuParent']")[0].id;
        }
        if ($j(this).parents("#" + GMCR.currentMenu).length == 0) {
            $j('div[id^="megaMenuContainer"]').hide();
            GMCR.currentMenu = $j(this).parents("li[id^='topMenuParent']")[0].id;
        }
    }

    $j('li[id^="topMenuParent"]').mouseleave(
        function() {
            $j('div[id^="megaMenuContainer"]').hide();
        }
        );

    $j('li[id^="megaMenuContainer"]').mouseleave(
        function() {
            $j('div[id^="megaMenuContainer"]').hide();
        }
        );

    //******************************Begin SB TopNav Functions
    $j(".navContainer").hoverIntent({
        sensitivity: 4,
        interval: 100,
        over: ShowB2BMenus,
        timeout: 0,
        out: HideB2BMenus
    });

    function ShowB2BMenus() {
        GMCR.currentMenu = $j(this)[0].className.split('navNumber-')[1];
        $j('#megaMenuContainer' + GMCR.currentMenu).slideDown('fast');  // Increased the drop speed to help prevent sticking menus from quick mouse outs
    }

    function HideB2BMenus() {
        $j(".megaMenuContainer").hide();
    }

    $j(".megaMenuContainer").mouseleave(
        function() {
            $j(".megaMenuContainer").hide();
        }
        );
    //***************************End SB Top Nav Functions

    //*******************************
    //Product Detail Tab Functions
    $j("a[id^='tab_']").click(function() {
        var tabNumber = $j(this).attr('id').replace('tab_', '');
        GMCR.SetTabActive(tabNumber);
        return false;
    });

    //Hides the tabs and displays just the reviews tab
    $j('#basedOnReviews, #viewRatingsTabs').click(function() {
        GMCR.SetTabActive(GMCR.ReviewTabNumber);
    });

    //Hides the tabs and displays just the features and specs tab
    $j('#tabFeaturesSpecLink').click(function() {
        GMCR.SetTabActive(GMCR.FeaturesAndSpecsTabNumber);
    });

    GMCR.SetTabActive = function(tabNumber) {
        var tabID = 'content_' + tabNumber;
        $j('div[tabid]').hide();
        $j("div[tabid='" + tabID + "']").show();
        $j(".productDetailTabContainer").attr('id', 'tab' + tabNumber);
        return false;
    };

    // Match div heights to there tallest sibling
    var tier2promos = $j("#tier2container > div")
    if ( tier2promos[0] ) {
        tier2promos.matchDimensions();
        tier2promos.find("a > img").css("height", "auto");
        if (GMCR.brand === "gmcr") {$j("#tier2container").wrap("<div id='tier2Wrapper'></div>");}
        if (GMCR.brand === "bce") { tier2promos.find("img:first").addClass("tier2-shadow");}
    }

    //Quick print of the page
    $j('#lnkPrintPage').click(function() {
        window.print();
        return false;
    });

    //Promo auto tabs
    GMCR.AutoTab = function(original, destination) {
        var dest = document.getElementById(destination);
        if (original.getAttribute && original.value.length == original.getAttribute("maxlength"))
            dest.focus()
    };

    //Constructs the add to cart URL
    GMCR.BuildAddToCartURL = function(productID, quantity, grindCode, grindName, brandID) {
        var url = "/ajaxHandlers/shophandler.aspx?commandName=";
        url += "AddToBasket";
        url += "&productID=" + productID;
        url += "&quantity=" + quantity;
        url += "&grindCode=" + grindCode;
        url += "&grindName=" + grindName;
        url += "&brandID=" + brandID;
        return url;
    };

    //Constructs the add to cart URL
    GMCR.BuildAddToClubURL = function(productID, quantity, grindCode, grindName, brandID, operation) {
        var url = "/ajaxHandlers/shophandler.aspx?commandName=";
        url += operation;
        url += "&productID=" + productID;
        url += "&quantity=" + quantity;
        url += "&grindCode=" + grindCode;
        url += "&grindName=" + grindName;
        url += "&brandID=" + brandID;
        return url;
    };

    //Pulls the value from any hidden field
    GMCR.SelectorFromHidden = function(hiddenID) {
        return '#' + $j('#' + hiddenID).val();
    };

    //Store the ID's of the server side hidden fields
    GMCR.QuantityDropDownSelector = GMCR.SelectorFromHidden('ddlQuantityID');
    GMCR.GrindCodeDropDownSelector = GMCR.SelectorFromHidden('ddlGrindsID');
    GMCR.AddToCartButtonSelector = GMCR.SelectorFromHidden('addToCartButton');
    GMCR.AddToClubButtonSelector = GMCR.SelectorFromHidden("addToClubButton");
    GMCR.StockMessageSelector = GMCR.SelectorFromHidden('StockMessageID');
    GMCR.DisabledAddToCartSelector = GMCR.SelectorFromHidden('disabledAddToCart');
    GMCR.QuantityDivSelector = GMCR.SelectorFromHidden('divQuantity');

    //*******************************
    //Just added to cart function
    $j(GMCR.AddToCartButtonSelector).click(function() {
        var quantitySelected = $j(GMCR.QuantityDropDownSelector + ' :selected').text() || 1;
        var grindSelected = $j(GMCR.GrindCodeDropDownSelector).length > 0 ? $j(GMCR.GrindCodeDropDownSelector).val().split("|")[1] : GMCR.ProductDetails.GrindCode;
        var grindNameSelected = $j(GMCR.GrindCodeDropDownSelector + ' :selected').text() || GMCR.ProductDetails.GrindName;
        var productID = $j(GMCR.GrindCodeDropDownSelector).length > 0 ? $j(GMCR.GrindCodeDropDownSelector).val().split("|")[0] : GMCR.ProductDetails.ProductID;
        var renderURL = GMCR.BuildAddToCartURL(productID, quantitySelected, grindSelected, grindNameSelected, GMCR.ProductDetails.BrandID);
        $j.ajax({
            type: "POST",
            data: "{}",
            url: renderURL,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function(data) {
                if (data.Result == 'OK') {
                    $j('#grindType').text(grindNameSelected);
                    $j('#justAddedQuantity').text(quantitySelected);
                    GMCR.ShowJustAddedToCartPopup();
                    $j('#miniCartResults').text(data.CartString);
                } else {
                    alert('Unable to add item to the cart, please try again later.');
                }
            }
        });
        return false;
    });

    //add to club button click
   
    //this will show the lightbox
    //tb_show('', 'TB_inline?height=155&width=300&inlineId=ClubsListDiv&modal=true');
    $j(GMCR.AddToClubButtonSelector).click(function() {
        var grindSelected = $j(GMCR.GrindCodeDropDownSelector).length > 0 ? $j(GMCR.GrindCodeDropDownSelector).val().split("|")[1] : GMCR.ProductDetails.GrindCode;
        var grindNameSelected = $j(GMCR.GrindCodeDropDownSelector + ' :selected').text() || GMCR.ProductDetails.GrindName;
        var productID = $j(GMCR.GrindCodeDropDownSelector).length > 0 ? $j(GMCR.GrindCodeDropDownSelector).val().split("|")[0] : GMCR.ProductDetails.ProductID;
        var addToClubURL = GMCR.BuildAddToClubURL(productID, quantitySelected, grindSelected, grindNameSelected, GMCR.ProductDetails.BrandID, "AddToClub");
        var addToSessionURL = GMCR.BuildAddToClubURL(productID, quantitySelected, grindSelected, grindNameSelected, GMCR.ProductDetails.BrandID, "SaveProductToSession");

        if ($j("#isSignedIn").val() == "true") {
            if ($j("#currentClubID").val() != "") {
                $j.ajax({
                    type: "POST",
                    data: "{}",
                    url: addToClubURL,
                    dataType: 'json',
                    contentType: 'application/x-www-form-urlencoded',
                    success: function(data) {
                        if (data.Result == 'OK') {
                            //$j('#grindType').text(grindNameSelected);
                            //$j('#justAddedQuantity').text(quantitySelected);
                            //GMCR.ShowJustAddedToCartPopup();
                            //$j('#miniCartResults').text(data.CartString);
                            document.location = $j("#clubUrl").val();
                        } else {
                            alert('Unable to add item to the club, please try again later.');
                        }
                    }
                });
            }
            else {
                tb_show('', 'TB_inline?height=155&width=300&inlineId=ClubsListDiv&modal=true');
            }        
        }
        else {
            //save selected product options to session
            //set isClubAdding to session or request or something
            $j.ajax({
                type: "POST",
                data: "{}",
                url: addToSessionURL,
                dataType: "json",
                contentType: "application/x-www-form-urlencoded",
                success: function(data) {
                    if (data.Result == "OK") {
                        document.location = $j("#clubUrl").val();
                    }
                    else {
                        alert('unable to add to session - please log in to add this product to your club.');
                    }
                }
            });
        }
        

        return false;
    });

    $j('#imgCloseWindow').click(function() {
        $j('#justAddedMiniCart').hide();
    });

    //Alert me when available submission
    $j('#btnSubmitAlert').click(function() {
        var renderURL = "/ajaxHandlers/shophandler.aspx?commandName=SetAlert";
        $j.ajax({
            type: "POST",
            data: $j('#alertBrandId, #txtEmail, #txtProdID, #txtCreatedByID, #txtSellGroupId').serialize(),
            url: renderURL,
            dataType: 'html',
            contentType: 'application/x-www-form-urlencoded',
            success: function(data) {
                if (GMCR.EmailIsValid(data)) { //came back with NO error
                    //Clear the errors if they exists and unhighlight fields
                    $j('#errorResults1').html('');
                    GMCR.EmailUnHighlightFields();
                    $j('#divConfirmMessage').show();
                    $j('#divSubmitEmail').hide();
                } else {
                    //came back with error
                    //Clear the completed data
                    $j('#divSubmitEmail').show();
                    $j('#divConfirmMessage').hide();
                    $j('#errorResults1').html(data);
                    GMCR.EmailHighlightErrorFields();
                }
            }
        });
    });


    //Grind Codes
    $j(GMCR.GrindCodeDropDownSelector).change(function() {
        var myProduct = GMCR.GetProductBySKU($j(this).val());

        //Display InStock Status message
        $j(GMCR.StockMessageSelector).text(myProduct.InStock);

        GMCR.ToggleAddToCart(myProduct.InStock);

        GMCR.ToggleAlertMe(myProduct.AlertMe);

        $j('#txtProdID').val(myProduct.ProductSKU);

        //clear the old options
        $j(GMCR.QuantityDropDownSelector + '>option').remove();

        //rebuild the options
        for (var i = 1; i < myProduct.Quantity + 1; i++) {
            $j('<option />').val(i).text(i).appendTo(GMCR.QuantityDropDownSelector);
        }
        //Set the first value as selected value.
        $j(GMCR.QuantityDropDownSelector).val("1");
    });

    //Finds the Product out of the JSON list
    GMCR.GetProductBySKU = function(sku) {
        for (var i = 0; i < GMCR.Products.length; i++) {
            if (GMCR.Products[i].ProductSKU == sku) {
                return GMCR.Products[i];
            }
        }
    };

    //Enables or disables Add To Cart button
    GMCR.ToggleAddToCart = function(stockMessage) {
        if (stockMessage == 'Discontinued' || stockMessage == 'Out of stock') {
            $j(GMCR.AddToCartButtonSelector).hide();
            $j(GMCR.DisabledAddToCartSelector).show();
            $j(GMCR.QuantityDivSelector).hide();
        }
        else {
            $j(GMCR.DisabledAddToCartSelector).hide();
            $j(GMCR.AddToCartButtonSelector).show();
            $j(GMCR.QuantityDivSelector).show();
        }
    };

    GMCR.ToggleAlertMe = function(alertMe) {
        if (alertMe == "True") {
            $j('#phmiddle_0_phproductdetail_0_GrindCodes1_AlertMeDiv').show();
        }
        else {
            $j('#phmiddle_0_phproductdetail_0_GrindCodes1_AlertMeDiv').hide();
        }
    };

    //global error handler for ajax functions
    GMCR.AjaxError = function(xhr, info, ex) {
        if (GMCR.DisplayFriendlyAjaxError) {
            $j('body').append('<div id="divAjaxError" name="divAjaxError" class="AjaxError">\
        <a href="#" onclick="tb_remove();window.location.reload(true);" title="Close"><b>Close</b></a>\
        <div class="AjaxErrorMessage">There was an unexpected error in the application.  System will attempt to reset the page.</div>\
        </div>');

            tb_show('Error Issuing Request', 'TB_inline?height=300&width=300&inlineId=divAjaxError&modal=true');
        } else {
            //For dev and test
            alert('Error! ' + info + '\n\n' + xhr.responseText);
        }
    };

    //Show the hidden div programtically when the page loads
    if (GMCR.ShowBasketErrorsOnLoad) {
        tb_show('', 'TB_inline?height=300&width=300&inlineId=basketErrors&modal=true');
    }

    //Closing the thickbox div window
    $j('#lnkClose').click(function() {
        tb_remove();
    });

    // Rollover event handler for brand tabs
    $j('.roTab').hover(
        function() {
            $j(this).attr(
                'src',
                $j(this).attr('src').replace('_off', '_over')
                );
        },
        function() {
            $j(this).attr(
                'src',
                $j(this).attr('src').replace('_over', '_off')
                );
        }
        );

    //EmailAFriend Functionality
    //Constrain the message to 250 characters
    $j('#eafMessage').keypress(function(e) {
        var length = this.value.length;
        if (length > 250) {
            e.preventDefault();
        }
    });

    //Highlights the fields that are in error
    GMCR.EmailHighlightErrorFields = function() {
        $j.each($j('#IsError').val().split(','), function() {
            $j('#' + this).addClass('formErrorStyle');
        });
    };

    GMCR.EmailUnHighlightFields = function() {
        $j(":input").removeClass('formErrorStyle');
    };

    //Checks for a validation error in the AJAX call
    GMCR.EmailIsValid = function(data) {
        return data.indexOf('IsError') === -1;
    };

    // Determine if text only checkbox is checked
    $j('#eafChkText').click(function() {
        GMCR.IsTextOnlyChecked = $j('#eafChkText').attr('checked');
    });

    GMCR.ClearFields = function() {
        $j('#eafTo').val('');
        $j('#eafFriendsEmail').val('');
        $j('#eafSenderEmail').val('');
        $j('#eafSenderName').val('');
        $j('#eafMessage').val('');
    };


    //hitting the continue button from shipping
    $j('#eafSend').click(function() {
        var renderURL = "/ajaxHandlers/shophandler.aspx?commandName=emailAFriend";
        if (GMCR.IsTextOnlyChecked) {
            renderURL += "&ChText=" + "true";
        }
        else {
            renderURL += "&ChText=" + "false"
        }
        $j.ajax({
            type: "POST",
            data: $j('#hiddenBrandID, #hiddenSellGroup, #hiddenSellGroupName, #eafTo, #eafFriendsEmail, #eafSenderEmail, #eafSenderName, #eafMessage').serialize(),
            url: renderURL,
            dataType: 'html',
            contentType: 'application/x-www-form-urlencoded',
            success: function(data) {
                if (GMCR.EmailIsValid(data)) { //came back with NO error
                    //Clear the errors if they exists and unhighlight fields
                    $j('#errorResults').html('');
                    GMCR.EmailUnHighlightFields();
                    $j('#emailForm').hide();
                    GMCR.ClearFields();
                    $j('#divConfirmation').show();
                } else {
                    //came back with error
                    //Clear the completed data
                    $j('#emailForm').show();
                    $j('#divConfirmation').hide();
                    $j('#errorResults').html(data);
                    GMCR.EmailHighlightErrorFields();
                }
            }
        });

    });

    //hide/show email a friend
    $j('#emaiAFriendAnchor').click(function() {
        $j('#emailForm').show();
        $j('#divConfirmation').hide();
    });

    // Refer A Friend Section

    //Checks for a validation error in the AJAX call
    GMCR.RAFIsValid = function(data) {
        return data.indexOf('IsError') === -1;
    };

    //Highlights the fields that are in error
    GMCR.RAFHighlightErrorFields = function() {
        $j.each($j('#IsError').val().split(','), function() {
            $j('#' + this).addClass('formErrorStyle');
        });
    };

    GMCR.RAFUnHighlightFields = function() {
        $j(":input").removeClass('formErrorStyle');
    };

    GMCR.RAFFound = function(data) {

        return data.valueOf('rafFound');
    };

    GMCR.RAFClearFields = function() {
        $j('#rafFirstName').val('');
        $j('#rafLastName').val('');
        $j('#rafEmail').val('');
        $j('#rafPhoneNumber').val('');
        $j('#rafPhoneExtension').val('');
        $j('#rafAddress1').val('');
        $j('#rafAddress2').val('');
        $j('#rafCity').val('');
        $j('#rafZipCode').val('');
        $j('#rafMessage').val('');
        $j('#selectRafState').val('');
    };


    // Show sign In component
    $j('#rafLanding').show();
    // Hide confirmation component
    $j('#rafConfirm').hide();

    $j('#referMyFriend').click(function() {
        var renderURL = "/ajaxHandlers/ReferAFriendHandler.aspx?commandName=referAFriend";
        $j.ajax({
            type: "POST",
            data: $j('#rafFirstName, #rafLastName, #rafEmail, #selectRafCountry, #rafPhoneNumber, #rafPhoneExtension, #rafAddress1, #rafAddress2, #rafCity, #selectRafState, #rafZipCode, #rafMessage').serialize(),
            url: renderURL,
            dataType: 'html',
            contentType: 'application/x-www-form-urlencoded',
            success: function(data) {
                if (GMCR.RAFIsValid(data)) { //came back with NO error
                    //Clear the errors if they exists and unhighlight fields
                    $j('#rafErrorMessages').html(data);
                    GMCR.RAFUnHighlightFields();
                    var status = $j('#rafFound').val();
                    GMCR.DisplayConfirmation(status, data);

                } else {
                    //came back with error
                    //Clear the completed data
                    $j('#rafForm').show();
                    $j('#rafErrorMessages').html(data);
                    GMCR.RAFHighlightErrorFields();
                }
            }
        });
    });

    GMCR.DisplayConfirmation = function(rafStatus, data) {
        // Hide sign In component
        $j('#rafLanding').hide();

        // Show confirmation component
        $j('#refereeSelect').hide();
        $j('#refereeExists').hide();
        $j('#refereeNew').hide();
        $j('#referAnother').hide();
        $j('#rafConfirm').show();

        // Set diplay for inner components
        if (rafStatus == 'new') {
            // show new referee confirmation
            $j('#refereeNew').show();
            $j('#referAnother').show();
            $j('#refereeSelect').hide();
            $j('#refereeExists').hide();
        }

        if (rafStatus == 'select') {
            // show select
            $j('#refereeSelect').show();
            $j('#rptSelect').html(data);
            $j('#refereeNew').hide();
            $j('#refereeExists').hide();
        }

        if (rafStatus == 'referred') {
            // show referee exists
            $j('#refereeExists').show();
            $j('#referAnother').show();
            $j('#refereeNew').hide();
            $j('#refereeSelect').hide();
        }
    };

    // If user clicks on "cancel"
    $j('#rafCancel').click(function() {
        // Show sign In component
        $j('#rafLanding').show();
        // Hide confirmation component
        $j('#rafConfirm').hide();
        // Clear html data
        $j('#rafErrorMessages').html('');
    });

    // When user clucks "Refer Another Friend"
    $j('#referAnother').click(function() {
        // Hide confirmation component
        $j('#rafConfirm').hide();
        // Show landing page component
        $j('#rafLanding').show();
        // Clear html data
        $j('#rafErrorMessages').html('');
        // Clear all the fields
        GMCR.RAFClearFields();
    });

    // Select referee from the list
    GMCR.SelectedContactID = '';
    // If user selects one of the available contacts
    //handle the clicking/changing of any radio button on checkout
    var evt = $j.browser.msie ? "click" : "change";
    $j('input[name="rdbContact"]').bind(evt, function() {
        GMCR.SelectedContactID = $j('input[name="rdbContact"]:checked').val();
    });

    // Create referral for selected contact
    $j('#rafContinue').click(function() {
        var contactId = $j('input[name="rdbContact"]:checked').val();
        var renderURL = "/ajaxHandlers/ReferAFriendHandler.aspx?commandName=Selection&contactId=" + contactId;
        $j.ajax({
            type: "POST",
            data: "{}",
            url: renderURL,
            dataType: 'html',
            contentType: 'application/x-www-form-urlencoded',
            success: function(data) {
                if (GMCR.RAFIsValid(data)) { //came back with NO error
                    //Clear the errors if they exists and unhighlight fields
                    $j('#rafErrorMessages').html(data);
                    GMCR.RAFUnHighlightFields();
                    $j('#rafPhoneExtension').val($j('#rafFound').val());
                    var status = $j('#rafFound').val();
                    GMCR.DisplayConfirmation(status, data);

                } else {
                    //came back with error
                    //Clear the completed data
                    $j('#rafForm').show();
                    $j('#rafErrorMessages').html(data);
                    GMCR.RAFHighlightErrorFields();
                }
            }
        });
    });

    // SLI Search functionality
    function createSearchUrl(shopParam) {
        var searchUrl = "";
        if ((window.location.href.indexOf("www.uat") != -1) || (window.location.href.indexOf("www.test") != -1)) {
            searchUrl = "http://greenmountaincoffee.resultsdemo.com/";
        }
        else {
            var strParts = window.location.href.match(/:\/\/(.[^/]+)/)[1].split('.');
            // Assume the brand domain immediatly precedes the top-level domain
            var searchUrl = "http://search";
            for(var i=1; i<strParts.length; i++) {
                searchUrl += "." + strParts[i];
            }
            if(searchUrl.charAt(searchUrl.length -1) != "/")
            {
                searchUrl += "/";
            }
        }
        var searchPageAddress = searchUrl + "search?w=" + $j('input[name="kwsearch"]').val();

        // Add ga parameters
        if (typeof (pageTracker) != 'undefined') {
            searchPageAddress = pageTracker._getLinkerUrl(searchPageAddress);
        }
        window.location = searchPageAddress;
    }
    GMCR.createSearchUrl = createSearchUrl;

    //
    //  Script for Sitecore Rollover Content Objects
    //
    $j(".rolloverParent").hover(
        function() {
            $j(this).children(".imageOff").attr("style", "display:none;");
            $j(this).children(".imageOn").attr("style", "display:block;");
        },
        function() {
            $j(this).children(".imageOff").attr("style", "display:block;");
            $j(this).children(".imageOn").attr("style", "display:none;");
        }
        );

    /*coffee calculator
---------------------------*/
    $j(".coffeeCalculatorCancel").click(function() {
        tb_remove();
        $j(".errorMessageContainer").html("");
        //reset error classes if they exist
        $j("#numEmployees").removeClass("formErrorStyle");
        $j("#numVisitors").removeClass("formErrorStyle");
        $j(".errorMessageContainer").css("display", "none");
    });
    
    $j("#coffeeCalculatorCalculate").click(function() {
        var cupdays = 0;
        var boxdays = 0;
        var employees = 0;
        var visitors = 0;
        var cupweeks = 0;
        var boxweeks = 0;
        var cupmonths = 0;
        var boxmonths = 0;
        
        var weeklength = 5;
        var monthlength = 20;
        var cupsperday = 0.5;
        var cupsperbox = 24;
        
        var re = /[^0-9]/gi;
        
        //reset error classes if they exist
        $j("#numEmployees").removeClass("formErrorStyle");
        $j("#numVisitors").removeClass("formErrorStyle");
        $j(".errorMessageContainer").css("display", "none");

        //test for values in employee field
        var employeesEntered = $j("#numEmployees").val();
        var visitorsEntered = $j("#numVisitors").val();
        if ((isNaN(parseFloat(employeesEntered)) == false) && (employeesEntered.match(re) == null)) {
            employees = parseFloat(employeesEntered);
            //test for any text in visitors field
            if (visitorsEntered != "") {
                //test for number in visitors field
                if ((isNaN(parseFloat(visitorsEntered)) == false) && (visitorsEntered.match(re) == null)) {
                    visitors = parseFloat(visitorsEntered);
                    cupdays = (employees + visitors) * cupsperday;
                }
                else {
                    $j(".errorMessageContainer").css("display", "block");
                    $j("#numVisitors").addClass("formErrorStyle");
                    $j(".errorMessageContainer").html("You have to enter a number for visitors to calculate, or you can just leave it blank.");

                    cupdays = employees * cupsperday;
                }
            }
            else {
                cupdays = employees * cupsperday;
            }
            
            boxdays = Math.ceil(cupdays / cupsperbox);

            //calculate cups & boxes per week, & month
            cupweeks = Math.ceil(cupdays * weeklength);
            boxweeks = Math.ceil(cupweeks / cupsperbox);
            cupmonths = Math.ceil(cupdays * monthlength);
            boxmonths = Math.ceil(cupmonths / cupsperbox);

            //set control values
            $j("#cupsPerDay").html(cupdays);
            if (boxdays == 1) {
                $j("#boxesPerDay").html("or 1 24-cup box");
            }
            else {
                $j("#boxesPerDay").html("or " + boxdays + " 24-cup boxes");
            }
            
            $j("#cupsPerWeek").html(cupweeks);
            if (boxweeks == 1) {
                $j("#boxesPerWeek").html("or 1 24-cup box");
            }
            else {
                $j("#boxesPerWeek").html("or " + boxweeks + " 24-cup boxes");
            }
            
            $j("#cupsPerMonth").html(cupmonths);
            if (boxmonths == 1) {
                $j("#boxesPerMonth").html("or 1 24-cup box");
            }
            else {
                $j("#boxesPerMonth").html("or " + boxmonths + " 24-cup boxes");
            }
        }
        else {
            $j(".errorMessageContainer").css("display", "block");
            $j("#numEmployees").addClass("formErrorStyle");
            $j(".errorMessageContainer").html("You have to at least enter a number of employees to calculate.");
        }
    });
/*end coffee calculator
    -----------------------------*/
    
});

// Utility function to retrieve parameter values from the query string
GMCR.GetParamValue = function( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&amp;]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

// Function to Fixup External Links For Google Analytics
GMCR.FixupExternalLinksForGA = function() {
    try {
        $j('a,area').each(function() {
            GMCR.FixLinkForGA($j(this));
        });
    } catch (err) { };
}

// Function to Fix External Link For Google Analytics
GMCR.FixLinkForGA = function(link) {
    var hRef = link.attr('href');
    var isExternal = hRef.match(/^http(s*)\:/i)
    && ($j(this).attr('hostname') != location.hostname);

    // Only for external links
    if (isExternal == true) {
        var clickhandler = link.attr('onclick');
        if (clickhandler != undefined && !clickhandler.toString().match(/\_link\(/)) {
            // there's a handler already, it's not the linker - log it and leave it
            // logged by requesting an image - this will show up as a 404 in server logs
            // where we can go spelunking for them later
            var trackImg = $j('<img>').attr('src', '/images/gaerror.jpg?page=' + encodeURIComponent(location.href) + '&link_href=' + encodeURIComponent(hRef));
        } else {
            // there's not a click event already, assign it
            link.click(function(event) {
                pageTracker._link(hRef);
                event.preventDefault();
            });
        }
    }
}

GMCR.ShowJustAddedToCartPopup = function() {
    // position popup relative to mini cart in topbar and show it
    var shoppingcart = $j('#shoppingcart');
    var justAddedMiniCart = $j('#justAddedMiniCart');
    var bumpFactor = 9;
    var leftForMiniCart = shoppingcart.position().left + shoppingcart.width() - justAddedMiniCart.width() + bumpFactor;
    var yOffset = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
    var topForMiniCart = shoppingcart.offset().top + shoppingcart.height() + bumpFactor;
    if (topForMiniCart < yOffset)
        topForMiniCart = yOffset + bumpFactor;

    // Move into header so that absolute positioning within div works correctly
    var header = $j('#header');
    justAddedMiniCart.appendTo(header);

    justAddedMiniCart.css("top", topForMiniCart + "px");
    justAddedMiniCart.css("left", leftForMiniCart + "px");
    justAddedMiniCart.show();

    // add click handler to close image
    $j('#imgCloseWindow').click(function() {
        $j('#justAddedMiniCart').hide();
    });

    // fix external links in related products
    $j('.justAddedPopupContainer a').each(function() {
        GMCR.FixLinkForGA($j(this));
    });
}

GMCR.brand = getBrand();

function getBrand() {
    var hostName = location.hostname.toLowerCase();
    var brandName = "gmcr";

    if (hostName.indexOf("tullys.com") >= 0) {
        brandName = "tullys";
    }
    else if (hostName.indexOf("newmans.com") >= 0) {
        brandName = "newmans";
    }
    else if (hostName.indexOf("caribou.com") >= 0) {
        brandName = "caribou";
    }
    else if (hostName.indexOf("business") >= 0) {
        brandName = "bce";
    }
    else if (hostName.indexOf("timothys.com") >= 0) {
        brandName = "timothys";
    }
    return brandName;
}