﻿/* 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() {

    // Activate png fix 
    $j(document).pngFix();

    // Initialize the sli search complete functionality
    sli_init();

    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
    $j('li>a[topnav]').hoverIntent({
        sensitivity: 4,
        interval: 300,   //Should be a minumum of 300 to prevent multiple open menus
        over: ShowMenus,
        timeout: 500,
        out: HideMenus
    });

    function ShowMenus() {
        //if ($j(this).parents("#" + GMCR.currentMenu).length == 0) {
        $j('div[id^="megaMenuContainer"]').hide();
        GMCR.currentMenu = $j(this).parents("li[id^='topMenuParent']")[0].id;
        //}
        var menuID = 'megaMenuContainer' + $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();
    }
  );

    //*******************************
    //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('body[id]').attr('id', 'tab' + tabNumber);
        return false;
    };

    //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;
    };

    //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.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;
    });

    $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
    //
    $j('input[name="kwsearch"]').keypress(function(e) {
        if ($j('input[name="kwsearch"]').val() != '' && e.which == 13) {
            createSearchUrl();
            return false;
        }
    });

    $j('input[name="btnSearchSubmit"]').click(function() {
        if ($j('input[name="kwsearch"]').val() != '') {
            createSearchUrl();
            return false;
        }
    });

    function createSearchUrl(shopParam) {
        var searchUrl = "";
        if (window.location.href.indexOf("www.uat") != -1) {
            searchUrl = "http://greenmountaincoffee.resultsdemo.com/";
        }
        else {
            /* SLI HACK */
            searchUrl = "http://search.greenmountaincoffee.com/";
            /*
            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 += "/";
            }
            */
        }
        if (typeof (shopParam) == 'undefined') {
            if (window.location.href.indexOf('greenmountaincoffee.com') != -1) shopParam = 'GMCR';
            else if (window.location.href.indexOf('tullys.com') != -1) shopParam = 'TULLYS';
            else if (window.location.href.indexOf('cariboukcups.com') != -1) shopParam = 'CARIBOU';
            else if (window.location.href.indexOf('newmansownorganicscoffee.com') != -1) shopParam = 'NEWMAN';
            else shopParam = 'GMCR';
        }

        var searchPageAddress = searchUrl + "search?w=" + $j('input[name="kwsearch"]').val() + "&shop=" + shopParam;

        // Add ga parameters
        if (typeof (pageTracker) != 'undefined') {
            searchPageAddress = pageTracker._getLinkerUrl(searchPageAddress);
        }
        window.location = searchPageAddress;
    }
    GMCR.createSearchUrl = createSearchUrl;

    //
    //  Script for Sitecore Rollover Content Objects
    //
    $j("div[id='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;");
  }
);

});

// 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));
    });
}
 