﻿$(document).ready(function() {

    $(".help2").click(function() {

    showHelpTopic('{33DFAF06-30A2-4c00-AE13-2E4709C0595F}', $(this), 15, -10); //top help icon
        return false;
    });
    $("#help3").click(function() {

    showHelpTopic('{92E68A47-14B9-49a9-8812-6FEB83214D26}', $(this), 15, 40); //promo code
        return false;
    });

    $(".basket tbody tr").each(function()
    {
        var row = $(this);
        var quantity = $(".product_quantity", row);

        // every keydown in the input, re-calculate the price
        quantity.keyup(function()
        {
            var row = $(this).parents("tr");
            updateTotal(row);
        });

        var value = $(".product_value", row);

        // every keydown in the input, re-calculate the price
        value.keyup(function()
        {
            var row = $(this).parents("tr");
            updateTotal(row);
        });
        
        var btn = $(".remove", row);

        // set click handler in the remove button
        btn.click(function()
        {
            // add confirmation modal to remove the item or not
            if (confirm("Remove this item?"))
            {
                // user decided to remove the item
                
                var id = $("input[name='id']", row).val();

                removeItemFromShoppingBasket(id, function(response)
                {
                    // check if we successfully remove the item
                    if (response == "True")
                    {
                        // it is successfully removed, then remove the row
                        removeRowLayout(row, false);
                    }
                    else
                    {
                        alert("Error occured");
                    }
                });
            }
        });
    });
        
    var shoppingbasket = $("#shoppingbasket").validate(
    {
        highlight: function(element, errorClass)
		{
			$(element).css("border", "solid 1px red");
			$(element).addClass("error");
		},
		unhighlight: function(element, errorClass)
		{
			$(element).css("border", "");
			$(element).removeClass("error");
		}
    });
    
    var card_count = $("#shoppingbasket input[name='id']").length;
    
    if (card_count > 0)
    {
        // add validation into the element
        $(".product_quantity").each(function()
        {
            $(this).rules("add",
            {
                required: true,
                range: [cardMinQuantity, cardMaxQuantity]
            });
        });
        
        $(".product_value").each(function()
        {
            $(this).rules("add",
            {
                required: true,
                range: [cardMinValue, cardMaxValue]
            });
        });
        
        // validate all input at start
        $(".product_quantity, .product_value").each(function()
        {
            shoppingbasket.element($(this));
        });

        var updateLayoutByPromo = function()
        {
            // get promocode
            var code = $("#shoppingbasket input[name='promo']").val();
            
            // check if the code is defined
            if (code != "")
            {
                var subTotal = getSubTotal();
                var promoMessage = $("#shoppingbasket .jq-promo-message");
                
                promoMessage.text("");
                
                // get the promo code
                getPromocode(code, subTotal, function(promo)
                {
                    updateLayout(promo);
                }, function(text)
                {
                    promoMessage.text("No promo valid");
                });
            }

            updateLayout();
        };
        
        $("#shoppingbasket .update").click(function()
        {
            updateLayoutByPromo();
            
            return false;
        });
        
        updateLayoutByPromo();
    }
    else
    {
        $("#shoppingbasket .jq-promo").hide();
        $("#shoppingbasket .subtotal").hide();
        $("#shoppingbasket .update").hide();
        $("#shoppingbasket .btn-a-1-69").hide();
    }
});

// update only single total element and disable the sub total
function updateTotal(row)
{
    var quantityElement = $(".product_quantity", row);
    var quantity = parseInt(quantityElement.val(), 10);
    var valueElement = $(".product_value", row);
    var value = parseFloat(valueElement.val(), 10);
    var total = quantity * (Math.round(value * 100) / 100);

    // check if the number is valid or not
    if (isNaN(total))
    {
        // it is not valid then set it to 0
        total = 0;
    }
    
    var shoppingbasket = $("#shoppingbasket");
    shoppingbasket.validate().element(quantityElement);
    shoppingbasket.validate().element(valueElement);
    
    // check if the validation is success or not
    if (quantityElement.hasClass("error") || valueElement.hasClass("error"))
    {
        // validation fails then do not calculate it
        total = 0;
    }
    
    var totalElement = $(".total", row);
    totalElement.text("$" + total.toFixed(2));
}

// calculate all total money that user should pay before discount
function getSubTotal()
{
    var subTotal = 0;
    var shoppingbasket = $("#shoppingbasket");
    
    // get all row
    $(".basket tbody tr").each(function()
    {
        var row = $(this);

        var quantityElement = $(".product_quantity", row);
        var quantity = parseInt(quantityElement.val(), 10);
        var valueElement = $(".product_value", row);
        var value = parseFloat(valueElement.val(), 10);
        var total = quantity * (Math.round(value * 100) / 100);

        // check if the number is valid or not
        if (isNaN(total))
        {
            // it is not valid then set it to 0
            total = 0;
        }
        
        shoppingbasket.validate().element(quantityElement);
        shoppingbasket.validate().element(valueElement);
        
        // check if the validation is success or not
        if (quantityElement.hasClass("error") || valueElement.hasClass("error"))
        {
            // validation fails then do not calculate it
            total = 0;
        }
        
        subTotal += total;

        var totalElement = $(".total", row);
        totalElement.text("$" + total.toFixed(2));
    });

    // check it the number is valid or not
    if (isNaN(subTotal))
    {
        // it is not valid then set it to 0
        subTotal = 0;
    }
    
    return subTotal;
}

// everytime quantity or value in the row got changes
// re-calculate the price and the sub total
// if no promo included that is mean no promo active for this
// calculation
function updateLayout(promo)
{
    var subTotal = getSubTotal();
    
    if (promo)
    {
        // get the subtotal by subtract with promo discount total
        // notice that in this page, shipping cost discount is
        // excluded
        subTotal -= promo.discountTotal;
    }
    
    var subtotalElement = $("input[name='subtotal']");
    subtotalElement.val(formatCurrency((Math.round(subTotal * 100) / 100).toFixed(2)));
}

// handler to remove row layout in the table
// it can be using animation or not
// it needs to specify what is the row element in the table
function removeRowLayout(element, animate)
{
    element.remove();
}

// AJAX call to remove specific item in the shopping basket
// the id is different with the GUID in the card design
// instead it uses shopping basket item id when the item is inserted
function removeItemFromShoppingBasket(id, successCallback, errorCallback)
{
    jQuery.ajax({
        url: "/Handlers/ShoppingCart.ashx",
        global: false,
        type: "GET",
        data: ({ action: "removeItemFromShoppingBasket", id: id }),
        success: function(response)
        {
            // check whether we define callback function
            if (successCallback)
            {
                // it is defined then call it with response
                successCallback(response);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            // check whether we define callback function
            if (errorCallback)
            {
                // it is defined then call it with error
                errorCallback(textStatus);
            }
        }
    });
}


function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
 
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}
