$(document).ready(function()
{
    $(".jqCartLink").click(function()
    {
        showAjaxLoader($(this));
        $.ajax({
            url:baseUrl + "store/cart",
            dataType:'json',
            success:function(response)
            {
                if(response.TotalQuantity > 0)
                {
                    $("body").append(response.Html);
                    var bodyHeight = $(document).height();
                    var bodyWidth = $(document).width();
                    $("#shoppingCart").height(bodyHeight + "px");
                    $("#shoppingCart").width(bodyWidth + "px");
                }
                else
                {
                    alert("Your cart is empty.\nPlease add products");
                }
            },
            complete:function(){hideAjaxLoader()}
        })
        return false;
});
/* Get shipping quote */
$(".jqGetquote").live("click", getShippingQuote);
$(".jqCartCheckout").live("click", validateShippingLocation);
$('.jqItemQuantity').live('keypress', function(e){
    var pressedKey = String.fromCharCode(e.which);
    if (e.which == 0 || e.which == 8) {

    } else if (pressedKey < 0 || parseInt(pressedKey) != pressedKey) {
        return false;
    }
});

});

/**
 * Comment
 */
function updateItemSubTotal(objQuantity)
{
    /**
    * Sub total and grand total will update
    * When change quantity
    **/
    var myQuantity = $(objQuantity).val();
    if (myQuantity >= 0 && parseInt(myQuantity) == myQuantity) {
        var myPrice = $(objQuantity).parents(".jqCartItemContainer").find(".jqItemPrice").text();
        roundedPrice = (myQuantity * myPrice * 100) / 100;
        $(objQuantity).parents(".jqCartItemContainer").find(".jqItemTotal").html(roundedPrice);
        updateTotalPrice();
    }
}

/**
 * To remove an item from Cart
 */
function removeItem(objRemoveButton)
{
    $(objRemoveButton).parents(".jqCartItemContainer").remove();
    updateTotalPrice();
    updateCart(0);
    return false;
}

/**
 * Comment
 */
function updateTotalPrice()
{
     var subTotal = 0


       $(".jqItemTotal").each(function()
        {
            subTotal += eval($(this).text());
        });

        $(".jqCartSubTotal").html(subTotal);
        $(".jqCartGrandTotal").html(subTotal);

}

/**
 * Comment
 */
function updateCart(redirect)
{
   
    var data = "";
    var url = "";
    var postData = "";
    if($(".jqCartItemContainer").length > 0)
        {
            data = "{";

        var comma = "";
        var count = 0;
        var isValid = true;
    $(".jqCartItemContainer").each(function()
    {
           var productID = $(this).find(".jqProductID").val();
           var productTypeID = $(this).find(".jqProductTypeID").val();
           var productQuantity = $(this).find(".jqItemQuantity").val();

           if (productQuantity >= 0 && parseInt(productQuantity) == productQuantity) {

           } else {
               isValid = false;
           }

           var product = '{"ProductId" :' + productID + ',    "ProductTypeId":' + productTypeID + ', "ProductQuantity":' + productQuantity + '}';

           data += comma + '"' + (count++) + '":' + product ;
           comma = ",";

    });
    data += "}";
        }

    if (!isValid) {
        alert('Invalid quantity. Please enter a valid quantity');
        return false;
    }

    if(data != "")
    {
        url = baseUrl + "store/updatecart";
        postData = {"items" : data};
        showCartAjaxLoader($("#shoppingCart.cartPopup"), "jqCartUpdateAjaxLoader");
        $.post(url, postData, function(response)
        {
            if(response.error)
            {
                if(response.error == 'cart')
                {
                    alert(response.info);
                }
                else
                {
                    handleAjaxError(response.error);
                }
            }
            else if(response.success)
            {
                $(".jQCartTotalQuantityNumber").html(response.totalQuantity);
                if(redirect == 1)
                {
                     var shippingCountryId         = document.getElementById('cboCountry').value;
                     window.location = baseUrl + "store/store-shipping-address" + "/country/" + shippingCountryId;
                }
                else if(redirect == 2)
                {
                    var shippingCountryId         = document.getElementById('cboCountry').value;
                    ajaxGetShippingQuote(shippingCountryId);
                }
               // alert(response.info);
            }
            hideCartAjaxLoader("jqCartUpdateAjaxLoader");

        }, "json");
    }
    else
        {
             url = baseUrl + "store/deletecart";
             
             $.ajax({url : url, success: function(){
                     $(".jQCartTotalQuantityNumber").html(0);
        closeCart();
             }
    });
    

        }
    return false;
}

/**
 * closeCart
 */
function closeCart()
{
    $("#shoppingCart").fadeOut("slow", function(){$(this).remove();});
}
/**
 * Comment
 */
function keepShipping()
{
    var currentUrl = (window.location).toString();
    if(currentUrl.indexOf(baseUrl + "store") >= 0)
    {
        closeCart()
    }
    else
    {
        window.location = baseUrl + "store";
    }
    
    return false;
}

/**
 * show products in category
 */
function showCategoryProducts(anchorObject, categoryID)
{
  
    
    if($("#jqStoreContainer").length > 0)
        {
    $(".jqStoreSubnav").removeClass('active');

    $(anchorObject).addClass('active');
    $(anchorObject).blur();

    var url = baseUrl + "store/get-category-products";
    var data = {"categoryID" : categoryID};
    showAjaxLoader(false);
    $.post(url, data, function(response)
    {
        if(response.error)
        {
            if(response.error == 'cart')
            {
                alert(response.info);
            }
            else
            {
                handleAjaxError(response.error);
            }
        }
        else if(response.success)
        {
           $("#jqStoreContainer").html(response.html);
           $("#jqStoreContainer").pngFix();
           if(categoryID == 0)
               {
                    $(".jqStoreSubnavShowAll").hide();
               }
               else
                   {
                       $(".jqStoreSubnavShowAll").show();
                   }

        }
        hideAjaxLoader();
    }, "json");
        }
        else
        {
         window.location = baseUrl + "store/index/id/" + categoryID;
        }
    return false;
}

/**
* getStates
*/
function getStates()
{
    var countryID = $("#cboCountry").val();
    if(countryID > 0)
    {
        var url = baseUrl + "store/get-states";
        var data = {"countryID" : countryID};
        showAjaxLoader($(".cartPopBtmLt"));
        $.post(url, data, function(response)
        {
            if(response.error)
            {
                if(response.error == 'cart')
                {
                    alert(response.info);
                }
                else
                {
                    handleAjaxError(response.error);
                }
            }
            else if(response.success)
            {
               $("#cboState").html(response.html);
            }
            hideAjaxLoader();
        }, "json");
        }
}

/**
 * Get shipping quote
 */
function getShippingQuote()
{
    //Select the current clicked link.
    //alert('rrrr');
    currentLinkShipping		= $(this);
    //var dvPopUpContainer        = $(".jqCartPopUpMain");
    var shippingCountryId         = document.getElementById('cboCountry').value;
    var country			  = $("#cboCountry");
    if(shippingCountryId == 0)
    {
        alert('Please select a country.');
        country.focus();
        return false;
    }
    else
    {
        updateCart(2);
       
    }
    return false;
}

function ajaxGetShippingQuote(shippingCountryId)
{
     var ajaxSubmitOption 	= {
                                url 	 : baseUrl + "store/get-shipping-quote",
                                data     : {countryid : shippingCountryId},
                                type	 : "post",
                                dataType : "json",
                                success  : function(data)
                                                   {
                                                                if(data.error)
                                                                {
                                                                        if(data.error == 'errorShowShippingTotal')
                                                                        {
                                                                                showAjaxError(data.info);
                                                                        }
                                                                        else
                                                                        {
                                                                                handleAjaxError(data.error);
                                                                        }
                                                                }
                                                                else if(data.success)
                                                                {
                                                                        $(".jqTotalShippingCharge").html("<strong>Total Shipping Charge: $" + data.grandTotal + "</strong>").fadeIn("slow");
                                                                }
                                                   },
                                beforeSend : function()
                                                         {
                                                                showAjaxLoader(currentLinkShipping);
                                                         },
                                complete : function()
                                                   {
                                                         hideAjaxLoader();
                                                   }
                          };
	$.ajax(ajaxSubmitOption);
}

//Validation of shippibg location - Check out button
function validateShippingLocation()
{
    var shippingCountryId         = document.getElementById('cboCountry').value;
    var country			  = $("#cboCountry");
   // alert(country);
    if(shippingCountryId == 0)
    {
        alert('Please select a country for shipping.');
        country.focus();
        return false;
    }
    else
    {
        updateCart(1);
        //window.location = baseUrl + "store/store-shipping-address" + "/country/" + shippingCountryId;
        //return true;
    }
    return false;
}


