var timeout = 0;

$(document).ready(function() {

    $("#basketItemsWrap").hide();

    $("#basketItemsWrap").mouseover(function() {
        clearTimeout(timeout);
    });

    $("#basketItemsWrap").mouseout(function() {
        timeout = setTimeout(
        function() {
            $("#basketItemsWrap").slideUp("slow");
            RefreshSlidingCart();
        }, document.getElementById("addToCartTimeOut").value);
    });

    GetCartItemCount();
});

function GetFirstItem(catalogentryid) {
    $.ajax({
        type: "GET",
        url: document.getElementById("basicposturlwithlang").value,
        data: { "get": "GetLastCartItem", randomize: new Date().getTime(), catalogentrycode: catalogentryid },
        success: function(response) {
            $("#basketWrap li").html(LastItemUI(response));
            GetCartItemCount();
        },
        dataType: "json"
    });
}

function AddToWishList(addtowishlistbutton, qty) {
    var productIDValSplitter = (addtowishlistbutton.id).split("_");
    var productIDVal = productIDValSplitter[1];
    $.ajax({
        type: "POST",
        url: document.getElementById("postwishlistdatasource").value,
        data: { catalogentryid: productIDVal, quantity: qty, post: "AddToWishList", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
            if (theResponse)
                window.location = $("#wishlistredirecturl").val();
            else
                alert("Unable to add the item to the Wish list");
        },
        async: false
    });
    //window.location = window.location;
}

function AddToWishListByCode(code, qtyId, qty) {
    $.ajax({
        type: "POST",
        url: document.getElementById("postwishlistdatasource").value,
        data: { code: code, quantity: qty, post: "AddToWishListByCode", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
            if (theResponse) {
                var qtyDiv = $("#" + qtyId);
                
                if (qtyDiv)
                    qtyDiv.text(parseInt(qtyDiv.text()) + qty);
            }
            else
                alert("Unable to add the item to the Wish list.");
        }
    });
    //window.location = window.location;
}

function RemoveFromWishListByLineItemId(lineItemId, qtyId, qty) {
    $.ajax({
        type: "POST",
        url: document.getElementById("postwishlistdatasource").value,
        data: { lineItemId: lineItemId, quantity: qty, post: "RemoveFromWishListByLineItemId", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
        if (theResponse) {
            //window.location = window.location;
                var qtyDiv = $("#" + qtyId);

                if (qtyDiv) {
                    var newQty = parseInt(qtyDiv.text()) - qty;
                    qtyDiv.text(newQty);
                    
                    if (newQty == 0)
                        HideRowOrGrid(qtyDiv);
                }
            }
            else
                alert("Unable to remove the item from the Wish list.");
        }
    });
    //window.location = window.location;
}

function AddToCartDeleteRow(lineItemId, code) {

    var qtyDiv = $("#Quantity_" + lineItemId);

    AddToCartByCode(code, qtyDiv);
}

function AddToCartHelper(catalogEntryId, qty, className, qtyDiv) {
    clearTimeout(timeout);
    var errormessage = "This item could not be added to the cart.";
    $("#basketWrap li").html('<div class="mm_SlidingCart"><img src="' + $('#waitSpinnerImageUrl').val() + '"></div>');
    $.scrollTo("#goToPageTop_ScrollTo", 500);

    if ($("#basketItemsWrap").is(":visible")) {
        $.ajax({
            type: "POST",
            url: document.getElementById("postitemdatasource").value,
            data: { codeOrCatalogEntryId: catalogEntryId, quantity: qty, post: className, randomize: getUniqueTime() },
            dataType: "json",
            success: function(theResponse) {
                if (theResponse == 'undefined' || theResponse == "-1111")
                    $("#basketWrap li").html('<div class="mm_SlidingCart">' + errormessage + '</div>');
                else
                    $("#basketWrap li").html(LastItemUI(theResponse));
                GetCartItemCount();

                HideRowOrGrid(qtyDiv);
            }
        });
    }
    else {
        $("#basketItemsWrap").slideDown("slow", function() {
            $.ajax({
                type: "POST",
                url: document.getElementById("postitemdatasource").value,
                data: { codeOrCatalogEntryId: catalogEntryId, quantity: qty, post: className, randomize: getUniqueTime() },
                dataType: "json",
                success: function(theResponse) {
                    clearTimeout(timeout);
                    timeout = setTimeout(
                    function() {
                        $("#basketItemsWrap").slideUp("slow");
                        RefreshSlidingCart();
                    }, document.getElementById("addToCartTimeOut").value);
                    if (theResponse == 'undefined' || theResponse == "-1111")
                        $("#basketWrap li").html('<div class="mm_SlidingCart">' + errormessage + '</div>');
                    else
                        $("#basketWrap li").html(LastItemUI(theResponse));
                    GetCartItemCount();

                    HideRowOrGrid(qtyDiv);
                }
            });
        });
    }

    return false;
}

function HideRowOrGrid (qtyDiv) {
    var count = GetWishListItemCount();

    // If the grid will be empty after deleting the row.
    if (count == 0)
        HideGrid()
    else
        HideRow(qtyDiv);
}

function HideRow(qtyDiv) {

    if (qtyDiv) {
        var row = qtyDiv.closest('tr');

        //row.slideUp('slow');
        row.hide('slow');
    }
}

function HideGrid() {
    // Hide the grid.
    $(".mm_WishlistTable").css("display", "none");
    $(".mm_WishListEmptyHidden").show();
}

function AddToCartByCode(code, qtyDiv) {
    return AddToCartHelper(code, qtyDiv.text(), "AddToCartByCode", qtyDiv);
}

function AddToCart(addtocartbutton, qty) {

    var productIDValSplitter = (addtocartbutton.id).split("_");
    var productIDVal = productIDValSplitter[1];

    return AddToCartHelper(productIDVal, qty, "AddToCart");
}

function LastItemUI(result) {
    var tickurl = $("#cartSliderTickImageUrl").val();
    var tagurl = $("#cartSliderTagImageUrl").val();
    var promomessage = result.PromoDescription == "" ? '' :
        '   <div class="mm_SlideCartPromo">' +
        '       <div class="mm_SlideCartPromoImg"><img src="' + tagurl + '" width="40" height="40"/></div>' +
        '       <div class="mm_SlideCartPromoText">' + result.PromoDescription + '</div>' +
        '   </div>';

    if (result == "")
        return '<div class="highlight">Your cart is empty.</div>';

    var imageurl = result.ThumbNail;
    var outputhtml;
    var itemcount = result.TotalCartItems == 1 ? "View the only item " : "View all " + result.TotalCartItems + " items ";
    outputhtml =
        '<div class="mm_SlidingCart">' +
        '   <div class="mm_SlidingCartMsg">' +
        '       <div class="mm_SlideCartTick"><img src="' + tickurl + '" /></div>' +
        '       <h4>You\'ve added the following to your cart</h4>' +
        '   </div>' +
        '   <div class="mm_SlideCartProduct">' +
        '       <div class="mm_SlideCartProductImg"><a href="' + result.EntryUrl + '"><img src="' + imageurl + '" width="60" height="60"/></a></div>' +
        '       <div class="mm_SlideCartProductText">' +
        '           <h3 class="highlight">' + result.DisplayName + '</h3>' +
        '           <div class="mm_SlideCartPrice">Price: ' + result.DiscountPrice + '</div>' +
        '           <div class="mm_SlideCartPrice">Qty: ' + result.Quantity + '</div>' +
        '       </div>' +
        '   </div>' + promomessage +
        '   <div class="mm_SlideCartTotals">' +
        '       <div class="mm_SlideCartSubtotal">Subtotal: <span class="highlight">' + result.SubTotal + '</span></div>' +
        '       <div class="mm_SlideCartTotalMsg"><a href="' + $("#cartpageurl").val() + '" class="higlight">' + itemcount + '</a> in your cart</div>';
    '   </div>';
    '</div>' +
        '<div class="clearboth"></div>';

    return outputhtml;
}

// Javascript generic
function getUniqueTime() {
    var time = new Date().getTime();
    while (time == new Date().getTime());
    return new Date().getTime();
}

function GetCartItemCount() {
    $.ajax({
        type: "GET",
        url: document.getElementById("basicposturlwithlang").value,
        data: { "get": "GetCartItemCount", randomize: new Date().getTime() },
        success: function(response) {
            var itemcount = parseInt(response.value) != 1 ? "<br /> ITEMS" : "<br /> ITEM";

            $("#cartitemcountlink").html(response.value + itemcount);
        },
        dataType: "json"
    });
}

function GetWishListItemCount() {
    var count;
    $.ajax({
        type: "GET",
        url: document.getElementById("basicposturlwithlang").value,
        data: { "get": "GetWishListItemCount", randomize: new Date().getTime() },
        success: function(response) {
            count = response.value
        },
        dataType: "json",
        async: false
    });

    return count;
}

function AddToCartByLineItemId(lineitemid) {
    $.ajax({
        type: "POST",
        url: document.getElementById("basicposturlwithlang").value,
        data: { lineitemid: lineitemid, post: "AddByLineItem", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
        },
        async: false
    });
    window.location = window.location;
}

function DeleteByLineItemId(lineitemid) {
    $.ajax({
        type: "POST",
        url: document.getElementById("basicposturlwithlang").value,
        data: { lineitemid: lineitemid, post: "RemoveByLineItem", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
        },
        async: false
    });
    window.location = window.location;
}

function BindShippingCost(zipcodetextbox, shippingcostlabel, errorlabel) {
    $("#waitspinner").html('<div><img src="' + $('#waitSpinnerImageUrl').val() + '"></div>');
    $("#EstimateDiv").hide();
    var countrycode;
    var statecode;
    var zipcodetext = document.getElementById(zipcodetextbox).value;

    if (!isValidZipCode(zipcodetext) && !isValidPostalCode(zipcodetext)) {
        $('#' + errorlabel).removeClass("hidden"); 
        if (!isValidZipCode(zipcodetext)) {
            document.getElementById(errorlabel).innerHTML = "Invalid Zip code";
        }
        else {
            document.getElementById(errorlabel).innerHTML = "Invalid Postal code"; ;
        }
        $("#waitspinner").html("");
        return false;
    }
    else {
        $('#' + errorlabel).addClass("hidden");
        $('#' + errorlabel).html("");
    }

    if (isValidZipCode(zipcodetext)) {
        countrycode = 'US';
        $.ajax({
            type: "GET",
            url: 'JSON.ashx',
            data: { randomize: getUniqueTime(), 'USZip': zipcodetext, "get": "StateCode"
            },
            dataType: "html",
            success: function(response) {
                statecode = response == "" ? undefined : response;
            },
            failure: function(response) {
                alert(response);
            },
            async: false
        });

        if (statecode != undefined) {
            $.ajax({
                type: "GET",
                url: document.getElementById("basicposturlwithlang").value,
                data: { CountryCode: countrycode, StateCode: statecode, ZipCode: zipcodetext, "get": "ShippingCost",
                    randomize: getUniqueTime()
                },
                dataType: "html",
                success: function(theResponse) {
                    var objResponse = eval('(' + theResponse + ')');
                    document.getElementById(shippingcostlabel).innerHTML = objResponse.rate;
                    if (objResponse.discount == "") {
                        $("[id*=divCartDiscount]").hide();
                    }
                    else {
                        $("[id*=divCartDiscount]").show();
                    }
                    $("[id*=TotalDiscount]").html(objResponse.discount);
                },
                async: false
            });
        }
        else {
            document.getElementById(shippingcostlabel).innerHTML = "NA";
        }
    }
    else if (isValidPostalCode(zipcodetext)) {
        countrycode = 'CA';
        statecode = '';
        $.ajax({
            type: "GET",
            url: document.getElementById("basicposturlwithlang").value,
            data: { CountryCode: countrycode, StateCode: statecode, ZipCode: zipcodetext.replace(' ', ''), "get": "ShippingCost",
                randomize: getUniqueTime()
            },
            dataType: "html",
            success: function(theResponse) {
                var objResponse = eval('(' + theResponse + ')');
                document.getElementById(shippingcostlabel).innerHTML = objResponse.rate;
                if (objResponse.discount == "") {
                    $("[id*=divCartDiscount]").hide();
                }
                else {
                    $("[id*=divCartDiscount]").show();
                }
                $("[id*=TotalDiscount]").html(objResponse.discount);
            },
            async: false
        });
    }
    $("#EstimateDiv").show();
    $("#waitspinner").html("");
    return false;
}

function ValidateCouponCode(couponcode) {
    $.ajax({
        type: "POST",
        url: document.getElementById("basicposturlwithlang").value,
        data: { couponcode: $('#' + couponcode).val(), post: "ValidateCouponCode", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
        },
        async: false
    });
    window.location = window.location;
}

function MoveToWishList(catalogEntryId, qty, lineitemids) {
    $.ajax({
        type: "POST",
        url: document.getElementById("postwishlistdatasource").value,
        data: { catalogentryid: catalogEntryId, quantity: qty, lineitemids: lineitemids, post: "MoveToWishList", randomize: getUniqueTime() },
        dataType: "json",
        success: function(theResponse) {
            if (theResponse)
                window.location = window.location;
            else
                alert("Unable to add the item to the Wish list");
        }
    });
}

function RefreshSlidingCart() {
    var isShoppingCart = window.location.pathname.toLowerCase().indexOf("shoppingcart.aspx") != -1;
    if (isShoppingCart)
        window.location = window.location;
}
