﻿$(function() {
    InitializeCart();
});

InitializeCart = function() {
    SetupDeleteButtons();
    SetupAddButtons();
    SetupQuantityBoxes();
}

/**--------- PAGE LOAD/SETUP FUNCTIONS -----------**/

//create a variable that is appended to an id when searching for an asp.net control
var aspID = "#ctl00_phMainContent_";

/***** SetupDeleteButtons *****/
/** This function adds a click event to all elements with a class of 'deleteFromCart'
It finds the value of the rel attribute and removes the table row matching this value
then it calls a function that deletes the order from the orders table via ajax **/
SetupDeleteButtons = function() {
    $(".deleteFromCart").live('click', function(e) {
        //prevent default behaviour. ie: dont go to url
        e.preventDefault();
        
        //NOT WORKING - using workaround
        //alert($("#ct100_hfPromptConfirm").val());
        var lang = $.query.get('lang');
        if (lang == "")
            lang = "en";
            
        var promptString = "";
        
        if (lang == "fr")
            promptString = "Êtes-vous sûr(e)?";
        else
            promptString = "Are you sure?";
        
        //prompt
        //if(confirm($("#ct100_hfPromptConfirm").val()))
        if(confirm(promptString))
        {
            //get rel value
            var OrderID = $(this).attr('rel');
            var OrderOwnerID = $("#ctl00_hfOrderOwnerID").val();

            //delete order from orders table via ajax
            DeleteOrderFromDB(OrderID, OrderOwnerID);
        }
    });
}

/***** SetupAddButtons *****/
/** This function adds a click event to all elements with a class of 'addToCart'.
Also finds the values of various field values in the page and creates the 'OrderArray'
paramater to be passed to the AddOrderToDB() function, which in turn calls the AddRowToCart()
function if the ajax call is successful **/
SetupAddButtons = function() {
    $(".btnAddToCart").click(function(e) {
        //prevent the default behavior. ie: causing a postback
        e.preventDefault();
        if (ValidateViewProduct()) {
            //Create an array from field values
            var OrderArray = new Array(15)
            // 0 = OrderOwnerID, 1 = OrderProductID, 2 = OrderSize, 3 = OrderFabric, 4 = OrderColor, 5 = OrderQuantity, 6 = OrderUnitPrice,
            // added: 7 = orderColorCode, 8 = string orderFabricCode, 9 = string orderSizeCode, 10 = int orderLineNum, 11 = orderLPCode, 12 = itemdescription, 13 = lang
            // 14 = image source
            var lang = $.query.get('lang');
            if (lang == "")
                lang = "en";
            OrderArray[0] = $("#ctl00_hfOrderOwnerID").val();
            OrderArray[1] = $(aspID + "hfOrderItemID").val();
            OrderArray[2] = $(aspID + "ddlItemSize :selected").text();
            OrderArray[3] = $(aspID + "ddlItemFabric :selected").text();
            OrderArray[4] = $(aspID + "ddlItemColor :selected").text();
            OrderArray[5] = $(aspID + "tbOrderQuantity").val();
            OrderArray[6] = $(aspID + "hfOrderUnitPrice").val();
            OrderArray[7] = $(aspID + "ddlItemColor").val();
            OrderArray[8] = $(aspID + "ddlItemFabric").val();
            OrderArray[9] = $(aspID + "ddlItemSize").val();
            OrderArray[10] = $(aspID + "hfLineItemNum").val();
            OrderArray[11] = $(aspID + "ddlLPC").val();
            OrderArray[12] = $(aspID + "hfItemDesc").val();
            OrderArray[13] = lang;
            OrderArray[14] = $(aspID + "hfItemImgUrl").val();
            
            showCart();
                        
            //Add order to database table
            AddOrderToDB(OrderArray);
        }
        
    });
}

/***** SetupQuantityTextboxes *****/
/** This function adds an onchange event to all elements with a class of 'order-quantity'
It finds the value of the textbox and updates the orders table via ajax.
The ajax method returns the new subtotal which then replaces the .subTotal field in the row
 **/
SetupQuantityBoxes = function() {
    var OrderOwnerID = $("#ctl00_hfOrderOwnerID").val();
    $(".order-update").live('click', function(e) {
        e.preventDefault();
        //get rel value
        var OrderID = $(this).attr('rel');
        var NewAmount = $("#cartRow" + OrderID).find(".order-quantity").val();
        var OldAmount = $("#cartRow" + OrderID).find(".currQuantity").val();
                
        //delete order from orders table via ajax
        OrderQuantityChange(OrderOwnerID,OrderID, NewAmount, OldAmount);
    });
}

/**---------- EVENTS (Click, Change) ----------------------**/

/***** CalculateGrandTotal *****/
/** This function takes 2 paramaters: the rowID and the orderOwnerID
If the rowID is set to -1 then we load all orders owned by this member
and calculate the total [this is called when an item is added to the cart].
If the rowID is anything else we get the subtotal of the rowID being deleted
and subtact it from the current cart total.
Finally we replace the cart total with the new one.
**/
CalculateGrandTotal = function(rowID, orderOwnerID) {

    var lang = $.query.get('lang');
        if (lang == "")
            lang = "en";

    if (rowID == "-1") {
        var s = "orderOwnerID :'" + orderOwnerID + "'";

        var p = "../../../webservice/OrderService.asmx/GetOrderTotal";

        //perform the ajax call
        $.ajax({
            url: p,
            data: '{' + s + '}',
            success: function(msg) {
                //order was saved
                $(".cart-total").text(msg.toFixed(2));
                if (msg.toFixed(2) == 0.00)
                    if( lang == "fr" )
                        $(".cartNoItemsPanel").html("Vous n'avez pas d'articles dans votre panier.");
                    else
                        $(".cartNoItemsPanel").html("There are currently no items in your cart.");

            },
            failure: function() {
                //if the orer was not saved

                //console.log('Error: Order not deleted');
            }
        });
    }
    else {
        var amtSubtract = $(rowID).find(".subTotal").text();
        var amtTotalBefore = $(".cart-total").text();
        var amtNewTotal = (parseFloat(amtTotalBefore) - parseFloat(amtSubtract));
        if (amtNewTotal == 0)
            if( lang == "fr" )
                $(".cartNoItemsPanel").html("Vous n'avez pas d'articles dans votre panier.");
            else
                $(".cartNoItemsPanel").html("There are currently no items in your cart.");
        //console.log("before: " + amtTotalBefore);
        //console.log("minus: " + amtSubtract);
        //console.log("new" + amtNewTotal);
        $(".cart-total").text(amtNewTotal.toFixed(2));
    }

    //highlight the newly added row
    $(".cart-row > td").effect("highlight", {}, 1000, function() { });
    $(".cart-total").effect("highlight", {}, 1000, function() { });
}

/* Client side form validation */
ValidateViewProduct = function() {
    var formIsValid = true;
    
    if ($(aspID + "ddlItemSize").val() == "-1") {
        $(aspID + "ddlItemSize").addClass("form-error");
        formIsValid = false;
    }
    else
        $(aspID + "ddlItemSize").removeClass("form-error");
        
    if ($(aspID + "ddlItemColor").val() == "-1") {
        $(aspID + "ddlItemColor").addClass("form-error");
        formIsValid = false;
    }
    else
        $(aspID + "ddlItemColor").removeClass("form-error");
       
    if ($(aspID + "ddlLPC").val() == "-1") {
        $(aspID + "ddlLPC").addClass("form-error");
        formIsValid = false;
    }
    else
        $(aspID + "ddlLPC").removeClass("form-error");
    
    if ($(aspID + "tbOrderQuantity").val() == "" || $(aspID + "tbOrderQuantity").val() <= 0 || isUnsignedInteger($(aspID + "tbOrderQuantity").val())) {
        $(aspID + "tbOrderQuantity").addClass("form-error");
        formIsValid = false;
    }
    else
        $(aspID + "tbOrderQuantity").removeClass("form-error");
    
    return formIsValid;
}

/***** OrderQuantityChange *****/
/** This function is called when the value of a quantity textbox is changed in the cart.
We get the order id and update the database via ajax and then update the cart totals accordingly.
**/
OrderQuantityChange = function(orderOwnerID, orderID, orderAmount, oldAmount) {

    //break out if invalid value
    if( orderAmount <= 0){
        $("#cartRow" + orderID).find(".order-quantity").val(oldAmount);
        return;
    }
    
    var s = "cartItemID :'" + orderID + "' , " +
        "newAmount :'" + orderAmount + "'";

    var p = "../../../webservice/OrderService.asmx/UpdateOrderAmount";

    //perform the ajax call
    $.ajax({
        url: p,
        data: '{' + s + '}',
        success: function(msg) {
            //convert data to JSON
            var values = eval(msg);
            //order was saved
            $("#cartRow" + orderID).find(".miniSubTotal").html(values.resultString);
            $("#cartRow" + orderID).find(".currQuantity").val(orderAmount);
            CalculateGrandTotal("-1", orderOwnerID);
        },
        failure: function() {
            //if the orer was not saved
            $("#cartRow" + orderID).find(".order-quantity").val(oldAmount);
        },
        error: function() {
            //return to previous value
            $("#cartRow" + orderID).find(".order-quantity").val(oldAmount);
        }
    });
    
    //highlight the modified row
    $("#cartRow" + orderID).effect("highlight", {}, 500, function() { });
}

/***** AddRowToCart *****/
/** This function appaneds a new row to the shopping cart table
and then calls a function to add a new order to the database 
This function takes an array with 7 keys: 0=OrderOwnerID, 1=OrderProductID, 2=OrderSize, 3=OrderFabric, 4=OrderColor, 
5=OrderQuantity, 6=OrderUnitPrice **/
AddRowToCart = function(OrderArray, OrderID) {
    /*console.log("Order Owner ID:" + OrderArray[0]);
    console.log("Order ProductID:" + OrderArray[1]);
    console.log("Order Size:" + OrderArray[2]);
    console.log("Order Fabric:" + OrderArray[3]);
    console.log("Order Color:" + OrderArray[4]);
    console.log("Order Quantity:" + OrderArray[5]);
    console.log("Order Unit Price:" + OrderArray[6]);*/

    var subTotal = (parseInt(OrderArray[5]) * parseFloat(OrderArray[6]));
    var fullURL = parent.document.URL;
    var language = fullURL.substring(fullURL.indexOf('?lang=')+6, fullURL.indexOf('?lang=')+8);
    var tempStringAr = new Array(7);
    
    $(".cartNoItemsPanel").html("");
    
    // set language labels
    if ( language == "fr" )
    {
        tempStringAr[0] = "Item : ";
        tempStringAr[1] = "Couleur : ";
        tempStringAr[2] = "Grandeur : ";
        tempStringAr[3] = "Tissu : ";
        tempStringAr[4] = "mettre à jour";
        tempStringAr[5] = "Logo : ";
    }
    else
    {
        tempStringAr[0] = "Item: ";
        tempStringAr[1] = "Color : ";
        tempStringAr[2] = "Size : ";
        tempStringAr[3] = "Fabric : ";
        tempStringAr[4] = "update";
        tempStringAr[5] = "Logo: ";
    }

    //create table row to be added
    var rowString = "<tr class='cart-row' id='cartRow" + OrderID + "'>" +
                        "<td style='width:50px;'><img style='height:50px; width:42px border-width:0px;' src='" + OrderArray[14].replace("~/","../") + "' /></td>" +
                        "<td>" +
                            "<table class='cart-sub-table'>" +
                                "<tr>" +
                                    "<td class='product-name'>" +
                                        tempStringAr[0] + OrderArray[1] +
                                    "</td>" +
                                "</tr>" +
                                "<tr>" +
                                        "<td>" +
                                            OrderArray[12] +
                                        "</td>" +
                                "</tr>" +
                            "</table>" +
                        "</td>" +
                        "<td>" +
                            "<table class='cart-sub-table'>" +
                                "<tbody>" +
                                    "<tr>" +
                                        "<td>" +
                                            "<strong>" + tempStringAr[1] + "</strong>" + OrderArray[4] +
                                        "</td>" +
                                    "</tr>" +
                                    "<tr>" +
                                        "<td>" +
                                            "<strong>" + tempStringAr[5] + "</strong>" + OrderArray[11] +
                                        "</td>" +
                                    "</tr>" +
                                    "<tr>" +
                                        "<td>" +
                                            "<strong>" + tempStringAr[2] + "</strong>" + OrderArray[2] +
                                        "</td>" +
                                    "</tr>" +
                                    "<tr>" +
                                        "<td>" +
                                            "<strong>" + tempStringAr[3] + "</strong>" + OrderArray[3] +
                                        "</td>" +
                                    "</tr>" +
                                "</tbody>" +
                            "</table>" +
                        "</td>" +
                        "<td>" +
                            "<strong>$" + OrderArray[6] + "</strong> CAD" +
                        "</td>" +
                        "<td>" +
                            "<input name='currQuantity' id='currQuantity' class='currQuantity' value=" + OrderArray[5] + " type='hidden'>" +
                            "<input type='text' rel='" + OrderID + "' class='order-quantity' style='width:25px;' value=" + OrderArray[5] + " /><br />" +
                            "<a href='#' rel='" + OrderID + "' class='order-update'>" + tempStringAr[4] + "</a>" +
                        "</td>" +
                        "<td>" +
                            "<strong>$<span class='miniSubTotal'>" + subTotal.toFixed(2) + "</span></strong>" +
                        "</td>" +
                        "<td>" +
                            "<a href='#' rel='" + OrderID + "' class='deleteFromCart' ><img src='../images/delete_16.png' /></a>" +
                        "</td>" +
                    "</tr>" +
                    "<tr class='separator-row' id='cartRowB" + OrderID + "'>" +
                        "<td>" +
                            "&nbsp;" +
                        "</td>" +
                    "</tr>";

    //add the row to the table
    $('#cart-table  > tbody:last').append(rowString);

    //highlight the newly added row
    $("#cartRow" + OrderID).effect("highlight", {}, 500, function() { });

    CalculateGrandTotal("-1",OrderArray[0]);

}

/***** AddOrderToDB *****/
/** This function is called when a user clicks the add to cart button. 
It inserts the order into the database via ajax/webservice
This function takes an array with 7 keys: 0=OrderOwnerID, 1=OrderProductID, 2=OrderSize, 3=OrderFabric, 4=OrderColor, 
5=OrderQuantity, 6=OrderUnitPrice **/
AddOrderToDB = function(OrderArray) {
    var s = "orderOwnerID :'" + OrderArray[0] + "' , " +
        "orderProductID :'" + OrderArray[1] + "' , " +
        "orderSize :'" + OrderArray[2] + "' , " +
        "orderFabric :'" + OrderArray[3] + "' , " +
        "orderColor :'" + OrderArray[4] + "' , " +
        "orderQuantity :'" + OrderArray[5] + "' , " +
        "orderUnitPrice :'" + OrderArray[6] + "' , " +
        "orderSchoolID :'" + $(aspID + 'hfSchoolID').val() + "' , " +
        "orderColorCode :'" + OrderArray[7] + "' , " +
        "orderFabricCode :'" + OrderArray[8] + "' , " +
        "orderSizeCode :'" + OrderArray[9] + "' , " +
        "orderLineNum :'" + OrderArray[10] + "' , " +
        "orderLPCode :'" + OrderArray[11] + "' , " +
        "orderDesc :'" + OrderArray[12] + "' , " +
        "lang :'" + OrderArray[13] + "' , " +
        "itemUrl :'" + OrderArray[14] + "'";
    
    var p = "../../../webservice/OrderService.asmx/SaveOrder";
    //perform the ajax call
    $.ajax({
        url: p,
        data: '{' + s + '}',
        success: function(msg) {
            //order was saved
            if (msg) {
                // this if won't fire without proper JSON formatting
                if( msg.toString().indexOf("AddToExisting|") >= 0  )
                {
                    // msg format should be: "AddToExisting|orderID|newAmount|oldAmount"
                    var values = msg.split('|');
                    //an order has matched this one
                    $("#cartRow" + values[1]).find(".order-quantity").val(parseInt(values[2]));
                    OrderQuantityChange(OrderArray[0], values[1], parseInt(values[2]), parseInt(values[3]));
                    //OrderQuantityChange( OrderArray[0],  = function(orderOwnerID, orderID, orderAmount, oldAmount)
                }
                else
                {
                    //add a row to the cart table
                    AddRowToCart(OrderArray, msg);
                }
            }
        },
        failure: function() {
        },
        error: function(msg, status, exthrown) {
            //workaround for string being evaled as bad JSON format. Will need to change this for proper JSON formatting in OrderService.cs
            if( exthrown.toString().indexOf("AddToExisting|") >= 0 )
            {
                //an order has matched this one
                var values = exthrown.toString().replace("Invalid JSON: ", "").split('|');
                // exthrown post replace format should be: "AddToExisting|orderID|newAmount|oldAmount"
                $("#cartRow" + values[1]).find(".order-quantity").val(parseInt(values[2]));
                OrderQuantityChange(OrderArray[0], values[1], values[2], values[3]);
            }
        }
    });
}

/***** DeleteRowFromCart *****/
/** This function is called when a user clicks the delete icon in the cart.
It takes 1 paramater: OrderID and finds the table row matching the order id and fades out
and removes it from display **/
DeleteRowFromCart = function(OrderID, OrderOwnerID) {
    $("#cartRow" + OrderID).fadeTo(200, 0, function() {
        $(this).hide(0, function() { $(this).remove(0, function() { }); });
    });
    $("#cartRowB" + OrderID).fadeTo(200, 0, function() {
        $(this).hide(0, function() { $(this).remove(0, function() { }); });
    });
    CalculateGrandTotal(-1, OrderOwnerID);
}

/***** DeleteOrderFromDB *****/
/** This function is called when a user clicks the delete icon in the cart. 
It takes 1 paramater: orderID which is used in an ajax method to remove
the matching record from the orders table. Finally, it calls a method that calculates
the new order total via ajax and sets the value in the cart **/
DeleteOrderFromDB = function(orderID, orderOwnerID) {
    var s = "cartItemID :'" + orderID + "'";

    var p = "../../../webservice/OrderService.asmx/DeleteOrder";

    //perform the ajax call
    $.ajax({
        url: p,
        data: '{' + s + '}',
        success: function(msg) {
            // convert string to JSON
            var values = eval(msg);
            //order was saved
            if (values.resultString == "true") {
                //delete the row from the cart table
                DeleteRowFromCart(orderID, orderOwnerID);
            }
        },
        failure: function() {
        },
        error: function(msg, status, exthrown) {
        }
    });
}

/**--------- HELPER METHODS ---------------**/

// Func: isUnsignedInteger
//  Param(s): controlVal - value to be checked
//  Returns : true if integer, false otherwise
isUnsignedInteger = function( controlVal ) {
    return (controlVal.toString().search(/^[0-9]+$/) != 0);
}
