/**
 *  Binding of events in the order level
 */
function bindOrderEvents()
{
    $('#shipping_country').bind(change, shippingCountrySelected);
    $('#shipper').bind(change, shipperSelected);
    $('#shipping_zone').bind(change, shippingZoneSelected);
    $('#payment_method').bind(change, paymentMethodSelected);
    $('#logo_discounted').bind('click keyup', discountSelected);
    $('#verso_discounted').bind('click keyup', discountSelected);
}


/*
 *
 * SELECTED METHODS:
 * When an element is selected.
 *
 *
 */


function shippingCountrySelected()
{
    for (var i = 0; i < $('div.job_concerns').length; i++)
    {
        var $jobDiv = $('#job_concerns_' + i);
        var productRef = $('#product_reference_' + $jobDiv.attr('index')).val();
        updateDeadline(productRef);
        testShippers(function()
        {
            updateShippingMethod();
        });
    }
}

function discountSelected()
{
    versoDiscounted = $('#verso_discounted').is(':checked');
    logoDiscounted = $('#logo_discounted').is(':checked');
    for (var i = 0; i < $('div.job_concerns').length; i++)
    {
        updateJobPrice($('#job_line_' + i));
    }
}

function shipperSelected()
{
    var $selectShipper = $('#shipper');
    var selectedShipper = $selectShipper.val();
    var $selectPaymentMethod = $('#payment_method');
    var $selectPaymentMethodClone = $selectPaymentMethod.clone();
    var selectedValue = $('option[value=]', $selectPaymentMethodClone).attr('selected_value');
    var selectedCountry = $('#shipping_country').val();

    // reset the select box
    $('option[value=]', $selectPaymentMethodClone).removeAttr('selected');
    selectedValue = selectedValue == '' ? '' : selectedValue;
    $('option[value!=]', $selectPaymentMethodClone).remove();

    if (selectedShipper != '')
    {
        // update the select box
        var paymentMethods = shipperMap[selectedShipper].paymentMethods;

        for (i in paymentMethods)
        {
            var paymentMethod = paymentMethods[i];
            var $optionToAdd = $('<option></option>').val(paymentMethod.type).text(paymentMethod.label);
            if (selectedValue == paymentMethod.type && paymentMethods.length > 1)
            {
                $optionToAdd.attr('selected', 'selected');
            }
            $selectPaymentMethodClone.append($optionToAdd);
        }
        if ($('option[value!=]', $selectPaymentMethodClone).length == 1)
        {
            $('option[value!=]', $selectPaymentMethodClone).attr('selected', 'selected');
        }
    }

    // shipping zone if needed
    if (selectedCountry == "BE" && (selectedShipper == "FLYPRINT" || selectedShipper == "UPS"))
    {
        $('tr.shipping_zone_line').show();
    }
    else
    {
        $('tr.shipping_zone_line').hide();
        $('#shipping_zone').val("");
    }

    $selectPaymentMethodClone.bind(change, paymentMethodSelected);
    $selectPaymentMethod.replaceWith($selectPaymentMethodClone);
    updateShippingMethod();
}

function shippingZoneSelected()
{
    updateShippingMethod();
}

function paymentMethodSelected()
{
    var $selectPaymentMethod = $('#payment_method');
    $('option[value=]', $selectPaymentMethod).attr('selected_value', $selectPaymentMethod.val());
    updateShippingMethod();
}


/*
 *
 * UPDATE METHODS:
 * Update an element
 *
 */


function updateShippers()
{
    var $selectShipper = $('#shipper');
    $selectShipper.unbind(change, shipperSelected);
    var $shipperClone = $selectShipper.clone();

    // reset select box
    $('option[value!=]', $shipperClone).remove();
    var selectedValue = $('option[value=]', $shipperClone).attr('selected_value');
    $('option[value=]', $shipperClone).removeAttr('selected').removeAttr('selected_value');
    selectedValue = (selectedValue == '' || selectedValue == undefined) ? '' : selectedValue;

    // update select box
    for (i in shipperMap)
    {
        var shipperInfos = shipperMap[i];
        var $optionToAdd = $('<option></option>').val(i).text(shipperInfos.label);
        if (i == "CHRONO" && (selectedValue == ''|| selectedValue == undefined)) selectedValue = "CHRONO";
        $shipperClone.append($optionToAdd);
    }
    if ($('option[value!=]', $shipperClone).length == 1)
    {
        $('option[value!=]', $shipperClone).attr('selected', 'selected');
    }
    else
    {
        $('option[value=' + selectedValue + ']', $shipperClone).attr('selected', 'selected');
    }
    $shipperClone.bind(change, shipperSelected);
    $selectShipper.replaceWith($shipperClone);
}

function updateShippingDate()
{
    var serializedOrder = serializeOrder();

    $('#delivery_date').hide();
    $('#delivery_date_empty').show();

    serializedOrder["shippingDate"] = "";
    if (serializedOrder.hasShippingInfos && serializedOrder.hasJobs)
    {
        $.getJSON(baseUrl + "/pub/ajax/shipping", serializedOrder, function(response)
        {
            $('#delivery_date span.date').html(response.date);
            if (response.date == "undefined")
            {
                $('#delivery_date').hide();
                $('#delivery_date_empty').show();
            }
            else
            {
                $('#delivery_date_empty').hide();
                $('#delivery_date').show();
            }
        });
    }
    else
    {
        $('#delivery_date span.date').html("");
        $('#delivery_date').hide();
        $('#delivery_date_empty').show();
    }
}

function updateShippingMethod()
{
    var serializedOrder = serializeOrder();
    currentShippingMethod = undefined;
    if (serializedOrder.hasShippingInfos && serializedOrder.hasJobs)
    {
        serializedOrder["shippingMethod"] = "";
        $.getJSON(baseUrl + "/pub/ajax/shipping", serializedOrder, function(response)
        {
            currentShippingMethod = response.shippingMethod;
            updateShippingDate();
            updateShippingPrice();
        });
    }
    else
    {
        updateShippingDate();
        updateShippingPrice();
    }
}


/**
 * Serialize the current order to a json object
 */

function serializeOrder()
{
    var serializedOrder = {};
    var countryIso = $('#shipping_country').val();
    var shipper = $('#shipper').val();
    var shippingZone = $('#shipping_zone').val();
    var paymentMethod = $('#payment_method').val();


    var hasShippingInfos = false;
    if (countryIso == "BE" && (shipper == "FLYPRINT" || shipper == "UPS"))
    {
        hasShippingInfos = shippingZone != "" && paymentMethod != "";
    }
    else
    {
        hasShippingInfos = countryIso != "-1" && shipper != "" && paymentMethod != "";
    }

    // ShippingMethod
    if (currentShippingMethod != undefined && currentShippingMethod.id != undefined)
    {
        serializedOrder["order.shippingMethod.id"] = currentShippingMethod.id;
    }
    // ShippingInfos
    if (hasShippingInfos && shipperMap != {})
    {
        serializedOrder["order.payment.method.type"] = paymentMethod;
        serializedOrder["order.shippingMethod.shipper"] = shipper;
        serializedOrder["order.shippingZone"] = shippingZone;
    }
    serializedOrder["order.deliveryAddress.address.country.iso"] = countryIso;
    serializedOrder["hasShippingInfos"] = hasShippingInfos;

    var index = 0;
    var jobNumber = $('div.job_concerns').length;

    for (var i = 0; i < jobNumber; i++)
    {
        var $jobDiv = $('#job_concerns_' + i);
        var productReference = $('#product_reference_' + i).val();
        var formatReference = $('#format_reference_' + i).val();
        var quantity = $('#quantity_hidden_' + i).val();


        if (productReference != "null" && formatReference != "null")
        {
            serializedOrder["order.customerJobs[" + index + "].product.reference"] = productReference;
            serializedOrder["order.customerJobs[" + index + "].format.format.reference"] = formatReference;
            serializedOrder["order.customerJobs[" + index + "].quantity"] = quantity;

            var jindex = 0;
            for (var j = 0; j < $('span.option_reference:not(.default)', $jobDiv).length; j++)
            {
                var inputOption = $($('span.option_reference:not(.default) input', $jobDiv)[j]);

                if (inputOption.is(':checked'))
                {
                    serializedOrder['order.customerJobs[' + index + '].productOptions[' + jindex + ']'] = inputOption.val();
                    jindex++;
                }
            }

            index++;
        }
    }
    if (index > 0)   serializedOrder['hasJobs'] = true;

    return serializedOrder;
}

/**
 * test if the shipperMap has to be actualized. At the end, launch the callbackFunction
 * @param callbackFunction
 */
function testShippers(callbackFunction)
{
    var oldShippers = new Array();
    for (shipper in shipperMap)
    {
        oldShippers.push(shipper);
    }
    shipperMap = {};
    var serializedOrder = serializeOrder();
    serializedOrder["shipperList"] = "";
    $.getJSON(baseUrl + "/pub/ajax/shipping", serializedOrder, function(response)
    {
        shipperMap = response.shipperMap;
        var isSame = true;
        for (shipper in shipperMap)
        {
            if ($.inArray(shipper, oldShippers) == -1)
            {
                isSame = false;
                break;
            }
        }
        if (!isSame)
        {
            updateShippers();
            shipperSelected();
        }
        callbackFunction.call();
    });
}