﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
function setStoreCookie(storeProfileId, storefrontId) {
    // Switch the stores, clears the minicart and main cart and reloads the same page where user is on.
    return ShopThisHTStoreSelectorSwitcher(false, storeProfileId, storefrontId);
}
function setStoreCookieRedirect(storeProfileId, storefrontId) {
    // Switch the stores, clears the minicart and main cart and redirects the user to Home page.(This happens only when user clicks "Shop This HobbyTown" in Store Profile Page.
    return ShopThisHTStoreSelectorSwitcher(true, storeProfileId, storefrontId);

}
function ShopThisHTStoreSelectorSwitcher(redirectToHome, storeProfileId, storefrontId) {

    // When trying to shop a different store and a store is already selected and cart has atleast one item.
    //alert('Total Items in Cart: ' + $(".hdnCartItemCount").val());
    if ($(".hdnStoreId").val() != storeProfileId && $(".hdnStoreId").val() > 0) {
        if ($(".hdnCartItemCount").val() > 0) {
            if (confirm("WARNING: This will clear your cart contents.")) {
                return HandleStoreSelectSwitch(redirectToHome, storeProfileId, storefrontId);
                return false;
            } else {
                return false;
            }
        } else {
        return HandleStoreSelectSwitch(redirectToHome, storeProfileId, storefrontId);
        }
    } else if ($(".hdnStoreId").val() != storeProfileId && $(".hdnStoreId").val() == 0) {
        // No warning as there is no store selected already. So clear cart and do rest.
    return HandleStoreSelectSwitch(redirectToHome, storeProfileId, storefrontId);
    }
    else {
        return false;
    }

}

function HandleStoreSelectSwitch(redirectToHome, storeProfileId, storefrontId) {
    remoteStoreCookieRedirect();
    // Call Empty Cart to clear Main Cart First and then empty mini cart and then atlast set new store cookie and redirect to Home page.
    GetSearchResults('', '', "emptycart");
    emptyMiniCart();
    var date = new Date();
    date.setFullYear(date.getFullYear() + 1);
    $.cookie("Store", storeProfileId + "," + storefrontId, { path: '/', expires: date });
    if (redirectToHome) {
        window.location.replace("/");
    }
    else {
        window.location.reload();
    }
    return false;
}
function remoteStoreCookieRedirect() {
    var date = new Date(1000, 1, 1);
    $.cookie("Store", "null", { path: '/', expires: date });

}

function setRecentlyAddedCookie(recentlyAddedItem) {
    $.cookie("RAI", recentlyAddedItem, { path: '/', expires: null });
}
function updateRecentlyAddedCookie() {
    if ($.cookie("RAI")) {
        var Item = $.cookie("RAI");
        if (Item.indexOf('CartUpdated') == -1) {
            Item = $.cookie("RAI") + ",CartUpdated";
            $.cookie("RAI", Item, { path: '/', expires: null });
        }
    }
}
function emptyMiniCart() {
    var date = new Date(1000, 1, 1);
    // Clear RAI Cookie
    $.cookie("RAI", "null", { path: '/', expires: date });
    // Set quantity hidden field to 0
    $('input[id=quantity]').val(1);
    // Set RAI Hidden field to empty.
    $('#hdnRAI').val('');
    $(".hdnCartItemCount").val(0);
    //window.location.reload();
}
function remoteStoreCookie() {
 //If atleast one iyem in cart, then show warning
    if ($(".hdnCartItemCount").val() > 0) {
        if (confirm("WARNING: This will clear your cart contents.")) {
            return HandleDeselectStores();
        } else {
            return false;
        }
    }
    else {
        return HandleDeselectStores();
    }
}
function HandleDeselectStores() {
    //This is called on deselect store:- Call Empty Cart to clear Main Cart First and then empty mini cart and then atlast set new store cookie and redirect to Home page.
    GetSearchResults('', '', "emptycart");
    emptyMiniCart();
    var date = new Date(1000, 1, 1);
    $.cookie("Store", "null", { path: '/', expires: date });
    window.location.reload();
    return false;
}

$(document).ready(function() {
    $('a.lightbox').lightBox({
        imageLoading: '/content/images/lightbox-ico-loading.gif',
        imageBtnClose: '/content/images/lightbox-btn-close.gif',
        imageBtnPrev: '/content/images/lightbox-btn-prev.gif',
        imageBtnNext: '/content/images/lightbox-btn-next.gif',
        imageBlank: '/content/images/lightbox-blank.gif'
    });
    // HACK to remove all occurances of VeriSign Logo, but first.
    if ($('div#ht-footer-utility object').size() > 1) {
        $('div#ht-footer-utility object:not(:first)').remove();
    }

});
function customUpdateCart(ControlId) {
    CartClass.GetObject(ControlId).UpdateCart();
    //updateRecentlyAddedCookie();
    //window.location.reload();
}
$ektron(function() {
    $("#storeTxtSearch").keypress(function(e) {
        if (e.keyCode == 13) {
            getDirectionsSubmit();
            return false;
        }
    });

});

$(function() {
    if (document.getElementById("ShoppingCartHT")) {
        // $('div#cart-summary').hide();
        $('div#cart-summary').css('display', 'block');
        $('div#ShoppingCartHT a').click(function() {
            updateRecentlyAddedCookie();
        });
    }
    if (document.getElementById("ShoppingChekOutHT")) {
        $('div#ShoppingChekOutHT div.EktronCheckout_LoginBlock li').removeClass();
    }
});

$(function() {
    if (document.getElementById("ShoppingProductListHT")) {
        // alert($(".hdnStoreId").val());
        if ($(".hdnStoreId").val() > 0) {
            $('div.form-list-cart').css('display', 'block');
        } else {
            $('div.form-list-cart').remove();
        }
    }
});
$(function() {
  
    if (document.getElementById("product-description")) {
        $('.ht-pad20').attr('id', 'product-detail');
        if ($(".htnIsLoggedIn").val().toLowerCase() != 'false') {
            $('div#product_rating_label').html($('div#ProductRatings').html());
            $('div#ProductRatings').remove();
        } else {
            $('div#product_rating_label').html($('div#ProductRatings').html());
            $('div#product_rating_label').click(function() {
                alert('You must be logged in to rate a product');
                return false;
            });
            $('div#ProductRatings').remove();
        }

        $('p.current-description a.show-description').click(function(e) {
            $(this).parent().css('display', 'none');
            $('p.full-description').css('display', 'block');

        });
        $('p.full-description a.show-description').click(function(e) {
            $(this).parent().css('display', 'none');
            $('p.current-description').css('display', 'block');
        });
        $('a#pComments').click(function() {
            $('div#commentsContainer').children().css('display', 'block');
            GetComments($('input#htProductInContext').val());
        });

        if ($(".hdnStoreId").val() > 0) {
            $('div#StoreLocatorBox').remove();
            $('div#frmCart').css('display', 'block');
            $('div#product-availability').css('display', 'block');
            $('div.product-price').css('display', 'block');
        }
        else {
            $('div#StoreLocatorBox').css('display', 'block');
            $('div#frmCart').remove();
            $('div#product-availability').remove();
            $('div.product-price').remove();
        }

    }
});

function AddProductComment(productId) {
    //alert(productId);
    var comment = $('#txtComments').val();
    $('div#CommentForm').children().css('display', 'block');
    var args = CreateCommentRequest(productId, "18611864", comment);
    GetSearchResults('#commentResponses', args, "addcomment");
    $('#txtComments').val('');
    GetComments(productId);
}

function GetComments(productId) {
    var args = CreateCommentRequest(productId, "18611864", "");
    GetSearchResults('#commentResponses', args, "getcomments");
    $('div#commentResponses').children().css('display', 'block');
}
function HideDeliveryShipmentOption() {
    //alert('hiding delivery option...');
    $("tr.EktronCheckout_ShippingMethod_ServiceSelectRow:has(td:contains('Delivery'))").hide();
}

// This function is a HACK to fix the Checkout control(click twice to login for returning user as CSS class missing for the below four list items inside .EktronCheckout_Rows_Container). This is registered and called from Checkout Control.
function FixCheckOutControlLoginViewCss() {

    if (!$ektron(".EktronCheckout_Rows_Container li:has(input[type=text])").hasClass("EktronCheckout_LoginEmail")) {
        $ektron(".EktronCheckout_Rows_Container li:has(input[type=text])").addClass("EktronCheckout_LoginEmail");
    }
    if (!$ektron(".EktronCheckout_Rows_Container li:has(input[type=password])").hasClass("EktronCheckout_LoginPassword")) {
        $ektron(".EktronCheckout_Rows_Container li:has(input[type=password])").addClass("EktronCheckout_LoginPassword");
    }
    if (!$ektron(".EktronCheckout_Rows_Container li:has(input[type=submit])").hasClass("EktronCheckout_LoginButton")) {
        $ektron(".EktronCheckout_Rows_Container li:has(input[type=submit])").addClass("EktronCheckout_LoginButton");
    }
    if (!$ektron(".EktronCheckout_Rows_Container li:has(span:contains('Recover Password'))").hasClass("EktronCheckout_RecoverPasswordLink")) {
        $ektron(".EktronCheckout_Rows_Container li:has(a:contains('Recover Password'))").addClass("EktronCheckout_RecoverPasswordLink");
    }
}

function AddToCart(productId, storeFrontId, price) {
    $.blockUI();
    var quantity = $('input[id=quantity]').val();
    if (quantity == 0)
        quantity = 1; //default quantity value = 1. For some products the Product Detail Page loads with 0 qty, so this fixes that issue.
    if (quantity == undefined)
        quantity = 1; //default quantity value = 1
    var recentlyAddedItem = $('input[id=hdnProduct_' + productId + ']').val() + "," + window.location.pathname.toString();
    //update items in cart
    $(".hdnCartItemCount").val(parseInt($(".hdnCartItemCount").val()) + parseInt(quantity));
    //alert('Updated cart items: ' + $(".hdnCartItemCount").val());
    var args = CreateAddToCartRequest(productId, 0, storeFrontId, quantity, recentlyAddedItem, price);
    itemAdded();
    GetSearchResults('#MiniCartHolder', args, "addtocart");
    recentlyAddedItem = $('#hdnRAI').val();
    //alert(recentlyAddedItem);
    setRecentlyAddedCookie(recentlyAddedItem);
    // alert($('div#CartSummary').html());
    $('div#cart-summary').html($('div#CartSummary').html());
    $.unblockUI();
}
function CreateSearchRequest(ZipCode, Range, OnlyOnlineShopping) {
    request = {
        "ZipCode": ZipCode,
        "Range": Range,
        "OnlyOnlineShopping": OnlyOnlineShopping
    };
    return Ektron.JSON.stringify(request);
}
function CreateAddToCartRequest(ProductId, UserId, StoreFrontId, Quantity, recentlyAddedItem, Price) {
    request = {
        "ProductId": ProductId,
        "UserId": UserId,
        "Quantity": Quantity,
        "StoreFrontId": StoreFrontId,
        "RecentlyAddedItem": recentlyAddedItem,
        "Price": Price
    };
    return Ektron.JSON.stringify(request);
}
function CreateCommentRequest(ContentId, UserId, Comment) {
    request = {
        "ContentId": ContentId,
        "UserId": UserId,
        "Comment": Comment
    };
    return Ektron.JSON.stringify(request);
}

function GetSearchResults(selector, args, action) {
    $ektron(selector).empty().html('<img alt="" id="loading" src="/images/ajax_loading.gif" />');
    $ektron.ajax({
        type: "POST",
        cache: false,
        async: false,
        url: "/Components/Handlers/Generic.ashx?action=" + action,
        data: { "request": args
        },
        success: function(msg) {

            if (action == 'getstorelocations') {
                // For getstorelocations, the response(msg) is always two part(rangefound~RANGE~resultshtml), where ~RANGE~ is the separator
                var locationStores = new Array();
                locationStores = msg.toString().split("~RANGE~");
                if (msg.toString().length > 30 && locationStores.length == 2) {
                    // If results found, then set modalRange dropdown selected value to the result returned range value in response.
                    $('#modalRange').val(locationStores[0]);
                    $ektron(selector).html(locationStores[1]);
                }
                else {
                    $ektron(selector).html(locationStores[1]);
                }
            }
            else {
                $ektron(selector).html(msg);
            }
        }
    });

}
