/* 
    Cart contents
    
    product:Array - array [id, product name, amount]
 */
var cart = new Array();

/**
    Add to cart
    
    Parameters
    product:String - Product name
    pkg:String - package size
    amount:Number - Amount of the product ordered
    specs:String - Product ID and amount [id,amount]
    
    Returns
    Nothing
 */
var addToCart = function (product, pkg, article, specs) {
    var specsArray = specs.split(",");
    var id = specsArray[0];
    var amount = specsArray[1];
    var prodCartID = isInCart(id);
    if (prodCartID) {
        // remove already existing item from cart
        var devnull = cart.splice(prodCartID,1);
    }
    // clean possible previous errors
    $("input[name='product-"+id+"'] ~ p").remove();
    var targetField = $("input[name='product-"+id+"']").eq(0);
    // validate field's format
    if (isNaN($(targetField).val()) || ($(targetField).val() != 0 && $(targetField).val().charAt(0) == 0)) {
        $(targetField).after("<p class='error'>"+products_and_ordering_translations.err_invalid_format+"</p>");
        return false;
    }
    // confirm max amount
    var maxAmount = Number($(targetField).eq(0).next().val());
    if (maxAmount < amount) {
        $(targetField).after("<p class='error'>"+products_and_ordering_translations.err_max_amount+" "+maxAmount+"</p>");
        return false;
    }
    if (amount > 0) {
        // add new item to the cart
        cart.push([id, product, pkg, amount, article]);
    }
};

/**
    Seek for the product in the cart
    
    Parameters
    id:Number - product ID
    
    Returns
    Number|Boolean - cart position of the product and false if not found
 */
var isInCart = function (id) {
    for (var i in cart) {
        if (cart[i][0] == id) {
            return i;
        }
    }
    return false;
};


$(document).ready(function() {

    // Order form processing
    $("#orderBtn").click(function() {

        // clean all previous errors
        $("fieldset > p.error").remove();

        // required set fields
        var requiredFields = new Array("name", "address", "phone", "company", "email");
        var optionalFields = new Array("notes");
        var dataObj = new Object();

        // see if any of the products were actually selected
        if (cart.length < 1) {
            //$("#infoHeader").after("<p class='error'>"+products_and_ordering_translations.err_no_product+"</p>");
            $("<p class='error'>"+products_and_ordering_translations.err_no_product+"</p>").prependTo("#POAFieldset");
            return false;
        } else {
            var cartStr = new String(); 

            // convert cart data to a string // article no + ": "+product+" - "+pkg+" x "+amount+"\n"
            for (var i in cart) {
                cartStr += cart[i][4] + ": "+cart[i][1]+" - "+cart[i][2]+" x "+cart[i][3]+"\n"
            }

            dataObj['cart'] = cartStr;
        }

        // validate input
        for (var i in requiredFields) {
            var fieldID = "#" + requiredFields[i] + "Fld";
            if ($(fieldID).val() != "") {
                dataObj[requiredFields[i]] = $(fieldID).val();
            } else {
                $(fieldID).after("<p class='error'>"+products_and_ordering_translations.err_missing_field+"</p>");
            }
        }

        if ($("#phoneFld").val() != "" && !validatePhoneNo($("#phoneFld").val())) {
            // phone format error
            $("#phoneFld").after("<p class='error'>"+products_and_ordering_translations.err_invalid_format+"</p>");
        } else if ($("#emailFld").val() != "" && !validateEmail($("#emailFld").val())) {
            // email format error
            $("#emailFld").after("<p class='error'>"+products_and_ordering_translations.err_invalid_email+"</p>");
        }

        if ($("p.error").text() != "") {
            return false;
        }

        // run through the optional fields and set if applicable
        for (var i in optionalFields) {
            var fieldID = "#" + optionalFields[i] + "Fld";
            if ($(fieldID).val() != "") {
                dataObj[optionalFields[i]] = $(fieldID).val();
            }
        }

        // set language
        dataObj['lang'] = lang;

        // set user ID if applicable
        if (typeof uid != 'undefined') dataObj['uid'] = uid;

        // hide everything and display a loader
        $("input").attr("disabled","disabled");
        $("#POAFieldset").hide();
        $("#POAFieldset").after("<div id='loader'></div>");


        $.post(siteIndex+"plugins/products_and_ordering/order.php", dataObj,
                function(data, textStatus) {
                    $("#loader").remove();
                    $("input").removeAttr("disabled");
                    if (textStatus == 'success') {
                        if (data.Success) {
                            pageTracker._trackPageview("/order-success");
                            $("#contentArea").empty().append(data.Success);
                        } else {
                            $("<p class='error'>"+data.Error+"</p>").prependTo("#POAFieldset");
                            $("#POAFieldset").show();
                        }
                    } else {
                        $("<p class='error'>"+data.Error+"</p>").prependTo("#POAFieldset");
                        $("#POAFieldset").show();
                    }
                }
            ,'json');
    });
    
    // hook up enter key on form
    $("#POAFieldset input").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#orderBtn").trigger('click');
        }
    });
});