(function($) {

    window.stores = {};

    $(document).ready(function() {

        renderSavedLocationButtons();

        Sterling.WhereToBuy.onSavedLocationChange(function(store) {
            renderSavedLocationButtons();
        });

        // View Store Location Map
        $(".whereToBuy-result a.whereToBuy-mapLink, .whereToBuy-result-first a.whereToBuy-mapLink").bind("click.viewMap", function() {
            var storeElem = $(this).parents("div:first");
            Sterling.WhereToBuy.viewMap(getStoreFromElement(storeElem));
            return false;
        });

        // Save store location as default
        $(".whereToBuy-result img, .whereToBuy-result-first img").bind("click.setSaved", function() {
            var storeElem = $(this).parents("div:first");
            Sterling.WhereToBuy.setSavedLocation(getStoreFromElement(storeElem));
            return false;
        });

        // Find if any store is a saved location
        function renderSavedLocationButtons() {
            var savedLocation = Sterling.WhereToBuy.getSavedLocation();

            $(".whereToBuy-result, .whereToBuy-result-first").each(function(){
                //var storeId = $(this).find("wtb\\:id").text();
                var storeId = $(this).find("div.storeId").text();
                if (savedLocation != null && savedLocation.id == storeId) {
                    $(this).find("img").css("display", "none");
                } else {
                    $(this).find("img").css("display", "");
                }
            });
        }

        function getStoreFromElement(elem) {
            var id = $(elem).find("div.storeId").text();
            return window.stores[id];
        }
    });

})(jQuery);
