var horaires_list = [];
var horaires_list_retour = [];
var subtotal = 0.000000000000001;
var pickups_list = [];
var dropto_list = [];
var edition_began = false;
var cart_content_before_edit = "";

$(function () {
    $("#depart").on("change", function () { $("#places_chosen_input").val(''); });
});

var orderSelect = function ($select) {
    var my_options = $select.find("option");

    var selectedOptionValue = $select.find("option:selected").val();
    my_options.sort(function (a, b) {
        if (a.text > b.text) return 1;
        else if (a.text < b.text) return -1;
        else return 0
    })
    $select.empty().append(my_options);

    $select.val('');
    if (selectedOptionValue) {
        $select.val(selectedOptionValue);
    }

}



var productIsReadOnly = function () {
    bootbox.alert(keytoursI18n.orderReadOnly);
}

var spinnerOpts = {
    lines: 11, // The number of lines to draw
    length: 24, // The length of each line
    width: 8, // The line thickness
    radius: 33, // The radius of the inner circle
    corners: 0.8, // Corner roundness (0..1)
    rotate: 5, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: '#fff', // #rgb or #rrggbb or array of colors
    speed: 0.8, // Rounds per second
    trail: 71, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: '80', // Top position relative to parent in px
    left: '230' // Left position relative to parent in px
};

var _parseInt = function (iValue) {
    var _return = parseInt(iValue);
    return isNaN(_return) ? 0 : _return;
}

var _parseFloat = function (iValue) {
    var _return = parseFloat(iValue);
    return isNaN(_return) ? 0 : _return;
}

// var close_places_chooser = function () {
//     $("#choose-places-div").fadeOut(function () {
//         $(this).remove();
//     });
//     verif_form_validity(true);

// }

// var choose_places = function () {
//     $("#choose-places-div").remove();
//     $.ajax({
//         url: 'index.php?section=choose_places&vehicule=' + $("#heure_depart option:selected").data("vehicule"),
//         success: function (data) {
//             $("body").prepend('<div id="choose-places-div">' + data + '</div>');
//             $("#choose-places-div").addClass('choose-places-div');

//             var selected = $("#places_chosen_input").data("vehiculePlaces");
//             if (selected.ids) {
//                 for (var i = selected.ids.length - 1; i >= 0; i--) {
//                     $("#place-" + selected.ids[i]).addClass('chosen');
//                 }
//             }


//             $("#choose-places-div .case").on('click', function (e) {
//                 e.stopPropagation();
//                 if ($(this).hasClass("booked") || !$(this).hasClass("case-place")) {
//                     return;
//                 }

//                 $(this).toggleClass('chosen');

//                 if ($("#choose-places-div .chosen").length > totalNbPax()) {
//                     $(this).removeClass('chosen');
//                 }

//                 var chosen = {
//                     ids: [],
//                     names: []
//                 };
//                 $("#choose-places-div .chosen").each(function () {
//                     chosen['names'].push($(this).text());
//                     chosen['ids'].push($(this).data('placeId'));
//                 });

//                 $("#places_chosen_input").data("vehiculePlaces", chosen);
//                 $("#places_chosen_input").val(chosen['names'].join(', '));

//                 verif_form_validity(true);
//             });


//             $("#choose-places-div").on("click", function () {
//                 close_places_chooser();
//             });
//         }
//     });
// };




var keytourAlbum = {
    imgList: [],
    initAlbum: function () {
        this.imgList = [];
    },
    add: function (apercu, img, title) {
        var row = {
            title: title,
            href: "https://dev.tripbooker.ch/upload/products-illustrations/" + img,
            thumbnail: "https://dev.tripbooker.ch/upload/products-illustrations/" + apercu
        };
        this.imgList.push(row);
    },
    showAlbum: function () {
        if (this.imgList.length) {
            var gallery = blueimp.Gallery(this.imgList);
            //montest = blueimp.Gallery(this.imgList);
        }
    },
    getImages: function (id) {
        xajax_get_product_images(id);
    }
};

var sidebarCarousel = null;
$(function () {
    sidebarCarousel = $('#sidebar-carousel').carousel().carousel("pause");
});



var spinner = new Spinner(spinnerOpts);
var spinnerSidebar = new Spinner(spinnerOpts);
var spinnerNextSchedules = new Spinner(spinnerOpts);

var editProductWaitingShow = function () {
    var $waitingBg = $('<div class="waiting-bg" id="edit-product-waiting"></div>').hide();
    var $waitingSpin = $('<div class="waiting-spin" id="edit-product-spin"></div>').hide();

    $waitingBg.css("height", $("form.developed").outerHeight());
    //$waitingSpin.css("height", $("form.developed").outerHeight());
    $("form.developed").parent().prepend($waitingSpin);
    $("form.developed").parent().prepend($waitingBg);

    spinner.spin($waitingSpin.get(0));
    $(spinner.el).css({
        top: ($waitingBg.outerHeight() / 2) + "px",
        left: ($waitingBg.outerWidth() / 2) + "px"
    });
    $waitingBg.fadeIn(100);
    $waitingSpin.fadeIn(100);
};

var reloadSidebar = function () {
    var $waitingBg = $('<div class="waiting-bg" id="sidebar-edit-product-waiting"></div>').hide();
    var $waitingSpin = $('<div class="waiting-spin" id="sidebar-edit-product-spin"></div>').hide();

    $waitingBg.css("height", "200px");
    //$waitingSpin.css("height", $("form.developed").outerHeight());
    $("#produits").html('<br><br><br><br><br><br><br><br><br><br><br>');
    $("#produits").prepend($waitingSpin);
    $("#produits").prepend($waitingBg);

    spinnerSidebar.spin($waitingSpin.get(0));
    $(spinnerSidebar.el).css({
        top: ($waitingBg.outerHeight() / 2) + "px",
        left: ($waitingBg.outerWidth() / 2) + "px"
    });
    $waitingBg.fadeIn(100);
    $waitingSpin.fadeIn(100);
};

var updateNextSchedulesForProduct = function (fieldId, jsonData) {
    var data = JSON.parse(jsonData);
    var length = data.length;
    var html = "";
    for (var i = 0; i < length; i++) {
        html += "<div>" + data[i].date + " " + data[i].time + " : " +
            "<span class=\"show-chfs\">" + data[i].prix + " CHF</span>" +
            "<span class=\"show-dollars\">" + data[i].prix_usd + " $</span>" +
            "<span class=\"show-euros\">" + data[i].prix_eur + " €</span>" +
            "</div>";
    }
    $("#" + fieldId).attr('title', html)
        .tooltip('fixTitle');
    $('.tooltip-inner').html(html);

}

var keytoursUpdateFilteredRows = function (jsonData) {
    var data = JSON.parse(jsonData);
    var $container = $("#next-schedules-content");

    $("#next-schedules-content .entry").remove();
    var length = data.length;
    for (var i = 0; i < length; i++) {

        var $newItem = $("#filter-result-template").clone();
        $newItem.removeAttr('id');

        var id = "schedule-entry-" + i;

        $newItem.find('.filter-result-link')
            .attr("id", id)
            .attr("href", data[i].url)
            .tooltip({ 'trigger': 'hover', 'title': keytoursI18n.loadingSchedules, "html": true, placement: "bottom" })
            .data('nextSchedules', "")
            .data('codeProduit', data[i].codeproduit)
            .data('date', data[i].date)
            .data('heure', data[i].heure)
            .bind("mouseenter", function () {
                xajax_next_schedules_for_product(
                    $(this).data('codeProduit'),
                    $(this).data('date'),
                    $(this).data('heure'),
                    $(this).attr('id')
                );
            });


        $newItem.find('.filter-result-title').text(data[i].title);
        $newItem.find('.filter-result-ref').text(data[i].codeproduit);
        $newItem.find('.filter-result-price-eur').text(data[i].prix_eur + " €");
        $newItem.find('.filter-result-price-usd').text(data[i].prix_usd + " $");
        $newItem.find('.filter-result-price-chf').text(data[i].prix + " CHF");

        $newItem.find('.filter-result-illustration').attr("src", data[i].img);

        $newItem.find('.filter-result-time').text(data[i].heuredepart);
        $newItem.find('.filter-result-duration').text(data[i].duree);
        $newItem.find('.filter-result-daily').text(data[i].ouverture);
        $newItem.find('.filter-result-resume').text(data[i].description);
        $newItem.find('.filter-result-prochain-depart').text(data[i].prochain_depart_heure);


        if (data[i].produitParent) {
            $newItem.find('.filter-result-section').remove();
        }


        // $newItem.find('.filter-result-section').css({
        //     "backgroundColor": data[i].type_style
        // });

        if (data[i].type) {
            $newItem.find('.filter-type').text(data[i].type);
        } else {
            $newItem.find('.filter-type').remove();
        }

        if (data[i].subtype) {
            $newItem.find('.filter-subtype').text(data[i].subtype);
        } else {
            $newItem.find('.filter-subtype').remove();
        }

        if (data[i].subsubtype) {
            $newItem.find('.filter-subsubtype').text(data[i].subsubtype);
        } else {
            $newItem.find('.filter-subsubtype').remove();
        }

        $newItem.addClass('entry');
        $newItem.addClass(
            i % 2 ? "even" : "odd"
        );


        $container.append($newItem);
        $newItem.fadeIn();
    }
    $("#next-schedule-container").removeClass('loading');
    spinnerNextSchedules.stop();
}


var editProductWaitingHide = function () {
    $("#edit-product-waiting, #edit-product-spin").fadeOut(100, function () {
        $(this).remove();
    });
};


function clear_cart() {
    if (confirm(keytoursI18n.emptyCart)) {
        window.location.href = origin_url + "/?section=empty_cart";
    }
}

function launch_payment(linkObject) {
    if (!$(linkObject).hasClass("disabled")) {
        window.location.href = payment_url;
    }
}

$(function () {
    cart_content_before_edit = $("#cart_inner").html();
});

var calendar_on_select = function (dateText) {
    edition_began = true;
    editProductWaitingShow();
    xajax_get_product_horraires(
        $("#opened_product_id").val(),
        dateText,
        1,
        0
    );
};

var calendar_on_select_retour = function (dateText) {
    edition_began = true;
    editProductWaitingShow();
    verif_form_validity();
    xajax_get_product_horraires(
        $("#retour_product_id").val(),
        dateText,
        1,
        1,
        $("#opened_product_id").val(),
        $("#jour_depart").val(),
        $("#heure_depart").val()
    );
};


function open_product(html) {

    if (!close_product(false)) return;
    //$("#cart_inner").prepend(html);
    $(html).hide().prependTo("#cart_inner").fadeIn("slow");
    init_product_popup();
}

function cancel_edit() {
    if (!close_product(true)) return;
    xajax_refresh_cart();
}

function change_heure_depart() {
    if ($("#arrivee > option").length > 1) $("#arrivee").parents('.control-group').slideDown(200);
}

function hide_vol_form(noAnimation) {
    if (noAnimation) {
        //$("#vol-depart").hide();
        $("#vol-retour").hide();
    }
    else {
        //$("#vol-depart").slideUp();
        $("#vol-retour").slideUp();
    }

}


function show_vol_form(noAnimation) {
    if (noAnimation) {
        //$("#vol-depart").show();
        $("#vol-retour").show();
    }
    else {
        //$("#vol-depart").slideDown();
        $("#vol-retour").slideDown();
    }

}

function change_lieux(noAnimation) {
    if ($("#arrivee").val() > 0 && $("#zone_pickup").val() > 0) {
        $("#retour-available").show();
    }

    /*
    if($("#zone_pickup option:selected").data("aeroport") == "1" || $("#arrivee option:selected").data("aeroport") == "1") {
        show_vol_form(noAnimation);
    }
    else {
        hide_vol_form(noAnimation);
    }*/
}

function show_villes() {
    $("#ville-depart").show();
}

function init_product_popup() {
    /*$( "#jour_depart" ).datepicker({
        dateFormat: "dd/mm/yy" ,
        onSelect:function(dateText, inst) {
            edition_began = true;
            xajax_get_product_horraires(
                $("#opened_product_id").val(),
                dateText
            );
        }
    });*/

    $("#heure_depart, #heure_retour").trigger("focus");

    if ($("#baseTarif").length) {
        $("form.developed").addClass("has-base-price");
    } else {
        $("form.developed").removeClass("has-base-price");
    }

    $("#jour_depart").iabsisCalendar({
        url: calendar_url,
        productKey: $("#opened_product_id").val(),
        onSelect: calendar_on_select,
        end: $("#jour_retour")
    });

    $("#jour_retour").iabsisCalendar({
        url: calendar_url,
        productKey: $("#opened_product_id").val(),
        onSelect: calendar_on_select_retour,
        start: $("#jour_depart"),
        forcePrice: $("#price1").data("price")
    });

    $("input.nb-places").keyup(function () {
        edition_began = true;
        calculate_subtotal();
        verif_form_validity();
    });


    $("#cart_inner input, #cart_inner select").change(function () {
        edition_began = true;
        verif_form_validity();
        calculate_subtotal();
    });

    $("#keep_retour").change(function () {
        if ($(this).is(':checked')) {
            $("#manual-adjustments").hide();
            $("#retour_fields").show(200);
            if (parseInt($("#jour_retour").data("tempsAvionVersProduit")) > 0 || parseInt($("#jour_retour").data("tempsProduitVersAvion")) > 0) {
                show_vol_form();
            }
            else {
                hide_vol_form();
            }
        }
        else {
            $("#manual-adjustments").show();
            $("#heure_retour").html('');
            $("#jour_retour").val('');
            $("#retour_fields").hide(200);
        }
    });

    $("[id^='tarif-gr-']").each(function () {
        if ($(this).html() === "0 CHF") {
            $(this).parent().hide();
        }
    });

    if ($("#arrivee > option").length <= 1) $("#arrivee").parents('.control-group').hide();
    edition_began = false;
    change_lieux(true);

    if (parseInt($("#jour_retour").data("tempsAvionVersProduit")) > 0 || parseInt($("#jour_retour").data("tempsProduitVersAvion")) > 0) {
        show_vol_form(true);
    }
    else {
        hide_vol_form(true);
    }
    update_arrival_times();
    verif_form_validity();

    orderSelect($('#depart'));


    setTimeout(function () {
        auto_update_tarifs();
    }, 200);


}

function edit_product(cart_item_id, content, product_key) {
    if (!close_product(false)) return;
    show_product_description(product_key);
    var block = $(content).hide();
    //alert($("#cart-id-" + cart_item_id).get());
    $("#cart-id-" + cart_item_id).attr("id", "cart-id-" + cart_item_id + "-old");
    //alert($("#cart-id-" + cart_item_id + "-old").get());
    $("#cart-id-" + cart_item_id + "-old").hide().after(block);
    $("#cart-id-" + cart_item_id + "-old").remove();
    block.show(200);
    init_product_popup();

    xajax_get_product_horraires(
        $("#opened_product_id").val(),
        $("#jour_depart").val(),
        0
    );

}

function close_product(force) {

    var _return = true;
    if (force == true) {
        sidebarCarousel.carousel(0).carousel("pause");
        if (edition_began == true) {
            if (!confirm(keytoursI18n.closeProduct)) {
                _return = false;
            }
        }
    }
    else {
        if (parseInt($("#sess_cart_id").val()) > 0 && edition_began == true) {
            alert(keytoursI18n.pleseConfirm);
            _return = false;
        }
        else {
            $("#cart_inner").html(cart_content_before_edit);
        }

    }

    if (_return) {
        edition_began = false;
        if (force) {
            $("#cart_inner form").hide(200, function () {
                $(this).remove();
            });
        }
        else {
            $("#cart_inner form").remove();
        }

        return true;
    }
    setPayableOrNot();
    return _return;
}

function reset_horaire_for_place() {
    horaires_list = [];
    pickups_list = [];
    dropto_list = [];
}

function reset_horaire_retour_for_place() {
    horaires_list_retour = [];
}

function add_horaire_for_place(horaire, place, place_id, is_retour, ville, jsonTarifs, placesRestantes, hasVehicule, nomVille, event) {
    jsonTarifs = JSON.stringify(jsonTarifs);
    if (is_retour) {
        if (!place_exists(place_id, horaires_list_retour)) {
            horaires_list_retour.push(new Array(place_id, place, [], ville));
        }
        for (i = 0; i < horaires_list_retour.length; i++) {
            if (horaires_list_retour[i][0] == place_id) {
                horaires_list_retour[i][2].push({ horaire: horaire, tarifs: jsonTarifs, placesRestantes: placesRestantes, ville: nomVille, event: event });
            }
        }
    }
    else {
        if (!place_exists(place_id, horaires_list)) {
            horaires_list.push(new Array(place_id, place, [], ville));
        }
        for (i = 0; i < horaires_list.length; i++) {
            if (horaires_list[i][0] == place_id) {
                horaires_list[i][2].push({ horaire: horaire, tarifs: jsonTarifs, placesRestantes: placesRestantes, hasVehicule: hasVehicule, ville: nomVille, event: event });
            }
        }
    }
}

function add_pickup(place, horaire, pickup_id, pickup_label, aeroport) {
    pickups_list.push(new Array(place, horaire, pickup_id, pickup_label, aeroport));
}

function add_dropto(place, horaire, pickup_id, pickup_label, aeroport) {
    dropto_list.push(new Array(place, horaire, pickup_id, pickup_label, aeroport));
}

function place_exists(val, array) {
    for (i = 0; i < array.length; i++) {
        if (array[i][0] == val) return true;
    }

    return false;
}

function inArray(array, p_val) {
    var l = array.length;
    for (var i = 0; i < l; i++) {
        if (array[i] == p_val) {
            return true;
        }
    }
    return false;
}

var fakeSelect = function ($selectField, ignoreTrigger) {
    $selectField.parent().find("span.replace-select").remove();
    if (ignoreTrigger === undefined) ignoreTrigger = false;

    $selectField.find("option:last").attr("selected", "selected");

    $selectField.hide();
    $selectField.parent().append('<span class="replace-select">' + $selectField.find("option:selected").text() + '</span>');
    if (!ignoreTrigger) $selectField.trigger("change");
};

var destroyFakeSelect = function ($selectField) {
    $selectField.parent().find("span.replace-select").remove();
    $selectField.show();
};

function show_places(is_retour) {
    var triggerChange = false;
    if (is_retour) {
        show_all_horaires_retour();
        $("#heure_retour").removeAttr("disabled");
    }
    else {
        $("#depart, #heure_depart, #retour-available, #arrivee").parents('.control-group').slideUp(100);
        $("#depart").val('-1');
        $("#heure_depart").html('');
        $("#div-zone-pickup").hide();

        if ($("#is_transfer").val() != 1) {
            $("#depart").parent().find("span.replace-select").remove();

            if (horaires_list.length == 1) {
                $("#depart").hide();
                $("#depart").html('');
                $("#depart").append("<option  selected=\"selected\" value=\"" + horaires_list[0][0] + "\">" + horaires_list[0][1] + "</option>");
                $("#depart").parent().append('<span class="replace-select">' + horaires_list[0][1] + '</span>');
                triggerChange = true;
            }
            else {
                $("#depart").show();
                $("#depart").html('');
                $("#depart").append("<option selected=\"selected\" value=\"\">-- " + keytoursI18n.selection + " --</option>");
                for (i = 0; i < horaires_list.length; i++) {
                    $("#depart").append("<option value=\"" + horaires_list[i][0] + "\">" + horaires_list[i][1] + "</option>");
                }
            }

        }

        orderSelect($('#depart'));

        $("#depart").parents('.control-group').slideDown(200);


        $("#depart").removeAttr("disabled");
        $("#heure_depart").removeAttr("disabled");

        if ($("#is_transfer").val() == 1) {
            show_all_horaires(true);
        }
        else {
            show_horaires(true);
        }

        $("#ville_depart").val(horaires_list[0][3]);

        if (triggerChange) {
            $("#depart").trigger("change");
        }
    }

}

function time_to_int(time) {
    if (!/[0-9]+\:[0-9]+/.test(time)) { return 0; }
    var aTime = time.split(":");
    return parseInt(aTime[0] * 60) + parseInt(aTime[1]);
}

function minutes_to_time(minutes) {
    var hours = parseInt(minutes / 60);
    var mins = minutes % 60;

    if (hours < 10) { hours = "0" + hours };
    if (mins < 10) { mins = "0" + mins };

    return hours + ":" + mins;
}


function update_arrival_times() {
    // Also update arrival times
    var startTime = time_to_int($("#heure_depart").val());
    var departDuration = parseInt($("#jour_depart").data("dureeProduit"));

    var textTime = "";
    if (startTime != 0 && departDuration != 0) {
        textTime = minutes_to_time(startTime + departDuration);
    }

    $("#heure-arrivee-depart").text(textTime);

    var startTime = time_to_int($("#heure_retour").val());
    var departDuration = parseInt($("#jour_retour").data("dureeProduit"));
    var textTime = "";
    if (startTime != 0 && departDuration != 0) {
        textTime = minutes_to_time(startTime + departDuration);
    }

    $("#heure-arrivee-retour").text(textTime);
}

function auto_update_tarifs() {
    var tarifs = $("#heure_depart option:selected").data("tarifs");

    if (!tarifs) {
        return
    };

    update_products_prices("price1", tarifs.tarif1, tarifs.tarifGroupe1);
    update_products_prices("price2", tarifs.tarif2, tarifs.tarifGroupe2);
    update_products_prices("price3", tarifs.tarif3, tarifs.tarifGroupe3);
    update_products_prices("price4", tarifs.tarif4, tarifs.tarifGroupe4);

    // Mise à jour des places restantes :
    $("#remaining-places").html($("#heure_depart option:selected").data("places"));
    $("#remaining-places-retour").html($("#heure_retour option:selected").data("places"));

    calculate_subtotal();
    update_arrival_times();
}

function auto_update_places() {
    var hasVehicule = $("#heure_depart option:selected").data("vehicule");

    if (hasVehicule != ($("#heure_depart").data("previousVehicule"))) {
        $("#heure_depart").data("previousVehicule", hasVehicule);
        $("#places_chosen_input").val('');
        $("#places_chosen_input").data('vehiculePlaces', { id: [], names: [] });
    }

    if (hasVehicule) {
        $("#places-selection").show();
    } else {
        $("#places-selection").hide();
    }
}

function add_amount_to_option(amount) {
    if ($("#baseTarif").length) {
        return ""
    } else {
        return amount;
    }
}

function show_horaires(ignoreFieldShow) {
    var place = $("#depart").val();
    var found = false;
    var count = 0;

    destroyFakeSelect($("#heure_depart"));

    $("#div-zone-pickup").hide();
    $("#heure_depart").html('');

    if (ignoreFieldShow === undefined || !ignoreFieldShow) $("#heure_depart").parents('.control-group').slideDown(200);

    for (i = 0; i < horaires_list.length; i++) {
        if (horaires_list[i][0] == place) {
            $("#heure_depart").append("<option value=\"\">-- " + keytoursI18n.selection + " --</option>");
            for (j = 0; j < horaires_list[i][2].length; j++) {
                found = true;
                count++;
                $("#heure_depart").append("<option data-ville=\"" + horaires_list[i][2][j].ville + "\" data-vehicule=\"" + horaires_list[i][2][j].hasVehicule + "\"" + (horaires_list[i][2][j].placesRestantes <= 0 || horaires_list[i][2][j].event ? "disabled" : "") + " data-places=\"" + horaires_list[i][2][j].placesRestantes + "\" data-event=\"" + horaires_list[i][2][j].event + "\" data-tarifs='" + horaires_list[i][2][j].tarifs + "' value=\"" + horaires_list[i][2][j].horaire + "\">" + horaires_list[i][2][j].horaire + "</option>");
			}
            if (found == true) break;
        }
    }

    $("#heure_depart option").each(function () {
        var tarifs = $(this).data("tarifs");
		var event = $(this).data("event");


        if (getCurrentCurrency() == "dollars") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToUsdRate).toFixed(2) + " $"));
        }
        else if (getCurrentCurrency() == "euros") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToEurRate).toFixed(2) + " €"));
        }
        else {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1).toFixed(2) + " CHF"));
        }
        if ($(this).data("places") <= 0 && !$(this).data("event")) $(this).html($(this).html() + " (" + keytoursI18n.plusDispo + ")");
        
		if (event) $(this).html($(this).html() + " (" + event + ")");
		
    });

    $("#heure_depart, #heure_retour").unbind("change").bind("change", function () {
        auto_update_tarifs();
        auto_update_places();
    });


    if (count === 1) {
        fakeSelect($("#heure_depart"));
    }

}

function show_pickups() {
    var horaire = $("#heure_depart").val();
    var count = 0;
    var place = $("#depart").val();

    destroyFakeSelect($("#zone_pickup"));

    $("#zone_pickup").html("");

    $("#zone_pickup").append("<option value=\"\">-- " + keytoursI18n.selection + " --</option>");
    for (i = 0; i < pickups_list.length; i++) {
        if (pickups_list[i][0] == place && horaire == pickups_list[i][1]) {
            count++;
            $("#zone_pickup").append("<option data-aeroport=\"" + pickups_list[i][4] + "\" value=\"" + pickups_list[i][2] + "\">" + pickups_list[i][3] + "</option>");
        }
    }

    if (count > 0) {
        $("#div-zone-pickup").show();
        if (count === 1) {
            fakeSelect($("#zone_pickup"));
        }
    }
    else {
        $("#div-zone-pickup").hide();
    }
}


function show_dropto() {
    var horaire = $("#heure_depart").val();
    var count = 0;
    var place = $("#depart").val();
    $("#arrivee").html("");

    destroyFakeSelect($("#arrivee"));

    $("#arrivee").append("<option value=\"\">-- " + keytoursI18n.selection + " --</option>");
    for (i = 0; i < dropto_list.length; i++) {
        if (dropto_list[i][0] == place && horaire == dropto_list[i][1]) {
            count++;
            $("#arrivee").append("<option data-aeroport=\"" + dropto_list[i][4] + "\" value=\"" + dropto_list[i][2] + "\">" + dropto_list[i][3] + "</option>");
        }
    }

    if (count > 0) {
        $("#div-zone-dropto").show();
        if (count === 1) {
            fakeSelect($("#arrivee"));
        }
    }
    else {
        $("#div-zone-dropto").hide();
    }
}




function show_all_horaires(ignoreFieldShow) {
    $("#heure_depart").html('');
    if (ignoreFieldShow === undefined || !ignoreFieldShow) $("#heure_depart").parents('.control-group').slideDown(200);

    $("#heure_depart").append("<option value=\"\">-- " + keytoursI18n.selection + " --</option>");
    for (i = 0; i < horaires_list.length; i++) {
        for (j = 0; j < horaires_list[i][2].length; j++) {
            $("#heure_depart").append("<option " + (horaires_list[i][2][j].placesRestantes <= 0 ? "disabled=\"disabled\"" : "") + " data-places=\"" + horaires_list[i][2][j].placesRestantes + "\" data-tarifs='" + horaires_list_retour[i][2][j].tarifs + "' value=\"" + horaires_list[i][2][j].horaire + "\">" + horaires_list[i][2][j].horaire + "</option>");
        }
    }

    $("#heure_depart option").each(function () {
        var tarifs = $(this).data("tarifs");
        if (getCurrentCurrency() == "dollars") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToUsdRate).toFixed(2) + " $"));
        }
        else if (getCurrentCurrency() == "euros") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToEurRate).toFixed(2) + " €"));
        }
        else {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1).toFixed(2) + " CHF"));
        }
    });

    $("#heure_depart, #heure_retour").unbind("change").bind("change", function () {
        auto_update_tarifs();
        auto_update_places();
    });
}

function show_all_horaires_retour() {
    $("#heure_retour").html('');
    $("#heure_retour").append("<option value=\"\">-- " + keytoursI18n.selection + " --</option>");
    for (i = 0; i < horaires_list_retour.length; i++) {
        for (j = 0; j < horaires_list_retour[i][2].length; j++) {
            if ($("#jour_depart").val() == $("#jour_retour").val()) {
                if (horaires_list_retour[i][2][j] <= $("#heure_depart").val()) continue;
            }
            $("#heure_retour").append("<option " + (horaires_list_retour[i][2][j].placesRestantes <= 0 ? "disabled=\"disabled\"" : "") + " data-places=\"" + horaires_list_retour[i][2][j].placesRestantes + "\" data-tarifs='" + JSON.stringify($("#heure_depart option:selected").data("tarifs")) + "' value=\"" + horaires_list_retour[i][2][j].horaire + "\">" + horaires_list_retour[i][2][j].horaire + "</option>");
        }
    }

    $("#heure_retour option").each(function () {
        var tarifs = $(this).data("tarifs");
        if (getCurrentCurrency() == "dollars") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToUsdRate).toFixed(2) + " $"));
        }
        else if (getCurrentCurrency() == "euros") {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1 * chfToEurRate).toFixed(2) + " €"));
        }
        else {
            if (tarifs) $(this).html($(this).html() + add_amount_to_option(" - " + (tarifs.tarif1).toFixed(2) + " CHF"));
        }
        if ($(this).data("places") <= 0) $(this).html($(this).html() + " (" + keytoursI18n.plusDispo + ")");
    });

    $("#heure_depart, #heure_retour").unbind("change").bind("change", function () {
        auto_update_tarifs();
        auto_update_places();
    });


}

function update_subtotal(somme) {
    if (!isNaN(somme)) {
        subtotal = parseFloat(subtotal) + parseFloat(somme);
        subtotal = parseFloat(subtotal).toFixed(2);
    }
}

function update_products_prices(field_name, amount, groupe, isGroup) {
    if ($("#tarif-" + field_name).length) {
        if (getCurrentCurrency() == "dollars") {
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount) * chfToUsdRate).toFixed(2) + " $");
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount) * chfToUsdRate).toFixed(2) + " $");
            $("#tarif-gr-" + field_name).html(((isGroup ? groupe : amount) * chfToUsdRate).toFixed(2) + " $");
        } else if (getCurrentCurrency() == "euros") {
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount) * chfToEurRate).toFixed(2) + " €");
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount) * chfToEurRate).toFixed(2) + " €");
            $("#tarif-gr-" + field_name).html(((isGroup ? groupe : amount) * chfToEurRate).toFixed(2) + " €");
        }
        else {
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount)).toFixed(2) + " CHF");
            $("#tarif-" + field_name).html(((isGroup ? groupe : amount)).toFixed(2) + " CHF");
            $("#tarif-gr-" + field_name).html(((isGroup ? groupe : amount)).toFixed(2) + " CHF");
        }
    }


    $("#" + field_name).data("price", amount);
    $("#" + field_name).data("priceGroupe", groupe);
}

function date_fr_to_en(date_fr) {
    var a = String(date_fr);
    return a.substr(6, 4) + "-" + a.substr(3, 2) + "-" + a.substr(0, 2);
}


function calculate_subtotal() {
    subtotal = 0.000000000000001;

    // Ajout des options
    var options = "";
    var tmp = 0;
    var nb_personnes = 0;
    for (i = 1; i <= 4; i++) {
        tmp = parseInt($("#price" + i).val());
        if (!isNaN(tmp)) nb_personnes += tmp;
    }

    var taille_groupe = $("#group_size").val();

    update_products_prices("price1", $("#price1").data("price"), $("#price1").data("priceGroupe"), taille_groupe > 0 && nb_personnes >= taille_groupe);
    update_products_prices("price2", $("#price2").data("price"), $("#price2").data("priceGroupe"), taille_groupe > 0 && nb_personnes >= taille_groupe);
    update_products_prices("price3", $("#price3").data("price"), $("#price3").data("priceGroupe"), taille_groupe > 0 && nb_personnes >= taille_groupe);
    update_products_prices("price4", $("#price4").data("price"), $("#price4").data("priceGroupe"), taille_groupe > 0 && nb_personnes >= taille_groupe);

    $(".product-options:checked").each(function () {
        switch ($(this).data("tarification")) {
            case "par_unite":
                update_subtotal($(this).data("tarif") * $("#options-qty-" + $(this).val()).val());
                break;
            case "cout_fixe":
                update_subtotal($(this).data("tarif"));
                break;
            case "par_personne":
                update_subtotal($(this).data("tarif1") * $("#price1").val());
                update_subtotal($(this).data("tarif2") * $("#price2").val());
                update_subtotal($(this).data("tarif3") * $("#price3").val());
                update_subtotal($(this).data("tarif4") * $("#price4").val());
                break;
        }

    });

    // Ajout du prix initial

    var price1 = $("#price1").data("price");
    var price2 = $("#price2").data("price");
    var price3 = $("#price3").data("price");
    var price4 = $("#price4").data("price");
    if (taille_groupe > 0 && nb_personnes >= taille_groupe) {
        price1 = $("#price1").data("priceGroupe");
        price2 = $("#price2").data("priceGroupe");
        price3 = $("#price3").data("priceGroupe");
        price4 = $("#price4").data("priceGroupe");
    }
    update_subtotal($("#price1").val() * parseFloat(price1));
    update_subtotal($("#price2").val() * parseFloat(price2));
    update_subtotal($("#price3").val() * parseFloat(price3));
    update_subtotal($("#price4").val() * parseFloat(price4));

    if ($("#keep_retour").is(':checked')) {
        //update_subtotal(subtotal);
        var tarifsRetour = $("#heure_retour option:selected").data("tarifs");
        if (tarifsRetour) {
            if (taille_groupe > 0 && nb_personnes >= taille_groupe) {
                // tarif groupe
                update_subtotal($("#price1").val() * parseFloat(tarifsRetour.tarifGroupe1));
                update_subtotal($("#price2").val() * parseFloat(tarifsRetour.tarifGroupe2));
                update_subtotal($("#price3").val() * parseFloat(tarifsRetour.tarifGroupe3));
                update_subtotal($("#price4").val() * parseFloat(tarifsRetour.tarifGroupe4));
            }
            else {
                // tarif normal
                update_subtotal($("#price1").val() * parseFloat(tarifsRetour.tarif1));
                update_subtotal($("#price2").val() * parseFloat(tarifsRetour.tarif2));
                update_subtotal($("#price3").val() * parseFloat(tarifsRetour.tarif3));
                update_subtotal($("#price4").val() * parseFloat(tarifsRetour.tarif4));
            }
        }

    } else {
        update_subtotal(_parseFloat($("#libre_montant").val()));
    }

    if ($("#baseTarif")) {
        update_subtotal($("#baseTarif").data("tarifBase"));
    }


    $("#subtotal").html(subtotal);
    $("#subtotal-eur").html(parseFloat(subtotal * chfToEurRate).toFixed(2));
    $("#subtotal-usd").html(parseFloat(subtotal * chfToUsdRate).toFixed(2));

    var totPerPersonne = 0;
    if (nb_personnes > 0) {
        totPerPersonne = subtotal / nb_personnes;
    }
    $("#moyennePersonneChf").html(totPerPersonne.toFixed(2));
    $("#moyennePersonneEur").html(parseFloat(totPerPersonne * chfToEurRate).toFixed(2));
    $("#moyennePersonneUsd").html(parseFloat(totPerPersonne * chfToUsdRate).toFixed(2));

    verif_form_validity()
}


function setPayableOrNot() {
    var cart = $("#cart_inner");
    var unvalidablesItems = cart.find(".expired, .not-enough-places");
    var cartItem = cart.find(".selection");
    if (cartItem.length === 0) {
        $("#payment-button").addClass("disabled");
        return;
    }

    if (unvalidablesItems.length > 0 && !$("#payment-button").data("admin")) {
        $("#payment-button").addClass("disabled");
        return;
    }


    $("#payment-button").removeClass("disabled");

}

var totalNbPax = function () {
    var nb = 0;
    if ($("#price1").get() != "" && parseInt($("#price1").val()) > 0) {
        nb += parseInt($("#price1").val());
    }

    if ($("#price2").get() != "" && parseInt($("#price2").val()) > 0) {
        nb += parseInt($("#price2").val());
    }

    if ($("#price3").get() != "" && parseInt($("#price3").val()) > 0) {
        nb += parseInt($("#price3").val());
    }

    if ($("#price4").get() != "" && parseInt($("#price4").val()) > 0) {
        nb += parseInt($("#price4").val());
    }

    if ($("#libre_nombre").get() != "" && parseInt($("#libre_nombre").val()) > 0) {
        nb += parseInt($("#libre_nombre").val());
    }

    return nb;
}

function verif_form_validity(show_error) {
    if (show_error === undefined) {
        show_error = false;
    };
    enable_validation_button();
    if (show_error) {
        $("#price1, #price2, #price3, #price4, #jour_depart, #heure_depart, #depart, #arrivee, #zone_pickup, #jour_retour, #heure_retour").closest(".control-group").removeClass("error");
        $("#error-choose-places").hide();
    };

    var at_least_one_place = false;

    if ($("#price1").get() != "" && parseInt($("#price1").val()) > 0) {
        at_least_one_place = true;
    }

    if ($("#price2").get() != "" && parseInt($("#price2").val()) > 0) {
        at_least_one_place = true;
    }

    if ($("#price3").get() != "" && parseInt($("#price3").val()) > 0) {
        at_least_one_place = true;
    }

    if ($("#price4").get() != "" && parseInt($("#price4").val()) > 0) {
        at_least_one_place = true;
    }

    if ($("#libre_nombre").get() != "" && parseInt($("#libre_nombre").val()) > 0) {
        at_least_one_place = true;
    }

    if (!at_least_one_place) {
        if (show_error) $("#price1, #price2, #price3, #price4").closest(".control-group").addClass("error");
        disable_validation_button(1);
    } else {
        $("#price1, #price2, #price3, #price4").closest(".control-group").removeClass("error");
    }


    if ($("#jour_depart") && $("#jour_depart").val() == "") {
        disable_validation_button(3);
        if (show_error) $("#jour_depart").closest(".control-group").addClass("error");
    } else {
        $("#jour_depart").closest(".control-group").removeClass("error");
    }

    if ($("#heure_depart") && ($("#heure_depart").val() == "" || $("#heure_depart").val() == null || $("#heure_depart option:selected").is(":disabled"))) {
        disable_validation_button(4);
        if (show_error) $("#heure_depart").closest(".control-group").addClass("error");
    } else {
        $("#heure_depart").closest(".control-group").removeClass("error");
    }

    if ($("#depart") && ($("#depart").val() == "" || $("#depart").val() < 1)) {
        if (show_error) $("#depart").closest(".control-group").addClass("error");
        disable_validation_button(5);
    } else {
        $("#depart").closest(".control-group").removeClass("error");
    }

    if ($("#arrivee") && !$("#arrivee").is(":hidden") && ($("#arrivee").val() == "" || $("#arrivee").val() < 1)) {
        if (show_error) $("#arrivee").closest(".control-group").addClass("error");
        disable_validation_button(6);
    } else {
        $("#arrivee").closest(".control-group").removeClass("error");
    }

    if ($("#zone_pickup") && $("#div-zone-pickup").css("display") != "none" && $("#div-zone-pickup").css("display") != undefined && ($("#zone_pickup").val() == "" || $("#zone_pickup").val() == null)) {
        if (show_error) $("#zone_pickup").closest(".control-group").addClass("error");
        disable_validation_button(7);
    } else {
        $("#zone_pickup").closest(".control-group").removeClass("error");
    }

    if ($("#places-selection").is(":visible")) {
        var places = $("#places_chosen_input").data("vehiculePlaces");

        if (places.names === undefined && places.names.length == 0) {
            if (show_error) {
                $("#error-choose-places").show();
            }
        }
        if (places.names.length != totalNbPax()) {
            if (show_error) {
                $("#error-choose-places").show();
            }
            disable_validation_button(10);
        }
    }

    if ($("#keep_retour").is(':checked')) {
        var retourErreur = false;
        if ($("#jour_retour").val() == "" || ($("#heure_retour").val() == "" || $("#heure_retour").val() == null || $("#heure_retour option:selected").is(":disabled"))) {
            if (show_error) $("#jour_retour").closest(".control-group").addClass("error");
            if (show_error) $("#heure_retour").closest(".control-group").addClass("error");
            disable_validation_button(8);
            retourErreur = true;
        }

        if (date_fr_to_en($("#jour_depart").val()) + " " + $("#heure_depart").val() >= date_fr_to_en($("#jour_retour").val()) + " " + $("#heure_retour").val()) {
            if (show_error) $("#jour_retour").closest(".control-group").addClass("error");
            if (show_error) $("#heure_retour").closest(".control-group").addClass("error");
            disable_validation_button(9);
            retourErreur = true;
        }
        if (!retourErreur) {
            $("#jour_retour, #heure_retour").closest(".control-group").removeClass("error");
        }
    }




}

function enable_validation_button() {
    $("#validation-button").removeClass("disabled");


    $("#validation-button").unbind().bind("click", function () {
        save_in_progress();
    });
}

function disable_validation_button(why) {
    $("#validation-button").addClass("disabled");
    $("#validation-button").unbind().bind("click", function () {
        verif_form_validity(true);
        //alert(keytoursI18n.completeForm);
    });
}

function save_in_progress() {
    var nbPlaces = 0;
    var buffer = 0;
    buffer = parseInt($("#price1").val());
    nbPlaces += isNaN(buffer) ? 0 : buffer;
    buffer = parseInt($("#price2").val());
    nbPlaces += isNaN(buffer) ? 0 : buffer;
    buffer = parseInt($("#price3").val());
    nbPlaces += isNaN(buffer) ? 0 : buffer;
    buffer = parseInt($("#price4").val());
    nbPlaces += isNaN(buffer) ? 0 : buffer;
    buffer = parseInt($("#libre_nombre").val());
    nbPlaces += isNaN(buffer) ? 0 : buffer;


    var placesAlle = parseInt($("#remaining-places").html());
    if (isNaN(placesAlle)) placesAlle = 0;
    var placesRetour = parseInt($("#remaining-places-retour").html());
    if (isNaN(placesRetour)) placesRetour = 0;

    var placesRestantes = placesAlle;

    if ($("#keep_retour").is(':checked')) {
        placesRestantes = Math.min(placesAlle, placesRetour);
    }

    var message_placesRestantes = "\n Il reste " + placesRestantes + " places pour cette horaire";
	if (nbPlaces > placesRestantes) {
        alert(keytoursI18n.noPlacesAnymore + message_placesRestantes);
        return;
    }

    $("#validation-button").addClass("disabled");
    $("#validation-button").unbind().bind("click", function () {
        alert("Sauvegarde en cours");
    });

    var options = [];
    var options_list = $(".product-options").get();

    if (options_list != "") {
        for (i = 0; i < options_list.length; i++) {
            if (options_list[i].checked == true) {
                options.push({
                    optionId: options_list[i].value,
                    number: $("#options-qty-" + options_list[i].value).val()
                });
                //options += "," + options_list[i].value;
            }
        }
    }


    xajax_save_product(
        $("#sess_cart_id").val(), // Id du produit
        $("#opened_product_id").val(), // Id du produit
        $("#jour_depart").val(), // Date de départ
        $("#ville_depart").val(), // Lieu de départ
        $("#depart").val(), // Lieu de départ
        $("#arrivee").val(), // Lieu d'arrivée (pour les transferts)
        $("#heure_depart").val(), // Heure de départ
        ($("#zone_pickup").val() == null ? "" : $("#zone_pickup").val()), // Dans le cas d'un pickup
        $("#price1").val(), // Nombre de places au tarif 1
        $("#price2").val(), // Nombre de places au tarif 2
        $("#price3").val(), // Nombre de places au tarif 3
        $("#price4").val(), // Nombre de places au tarif 4
        JSON.stringify(options), // Liste des options sélectionnées
        ($("#keep_retour").is(':checked') ? $("#keep_retour").val() : 0),
        $("#jour_retour").val(),
        $("#heure_retour").val(),
        $("#remarques").val(),

        $("#numero_vol_depart").val() !== undefined ? $("#numero_vol_depart").val() : '',
        $("#heure_vol_depart").val(),
        $("#numero_vol_retour").val() !== undefined ? $("#numero_vol_retour").val() : '',
        $("#heure_vol_retour").val(),
        $("#libre_nombre").val(),
        $("#libre_montant").val(),
        $("#libre_comment").val(),
        $("#ref_client").val(),
        $("#tel_client").val(),
        $("#email_client").val(),
        $("#places_chosen_input").val()

    );
    sidebarCarousel.carousel(0).carousel("pause");
}

function delete_product(id) {
    if (confirm(keytoursI18n.deleteItem)) {
        xajax_delete_product(id);
    }
}
function deleted_product(id, total) {
    $("#cart-id-" + id).hide(100, function () {
        $(this).remove();
        $("#total-amount").html(parseFloat(total).toFixed(2));
        cart_content_before_edit = $("#cart_inner").html();
        setPayableOrNot();
    });;

}

function update_cart_content(content, total) {
    $("#cart_inner").html(content);
    $("#total-amount").html(parseFloat(total).toFixed(2));
    $("#total-euro-amount").html(parseFloat(total * chfToEurRate).toFixed(2));
    $("#total-dollar-amount").html(parseFloat(total * chfToUsdRate).toFixed(2));
    cart_content_before_edit = $("#cart_inner").html();
    edition_began = false;
    setPayableOrNot();
}

function show_product_description(product_id) {
    /*
    $("#ProductDescriptionContent").html("<p>" + keytoursI18n.loading + "</p>");
    xajax_get_product_description(product_id);
    $('#ProductDescription').modal('show');*/
    $("#product-description-content").html("<p>" + keytoursI18n.loading + "</p>");
    xajax_get_product_description(product_id);
    sidebarCarousel.carousel(1).carousel("pause");

}


function show_compare($link) {
    $("#ProductsDescriptionContent").html("<p>" + keytoursI18n.loading + "</p>");

    var ids = "";
    $link.closest(".collapse").find("a[data-product-id]").each(function () {
        ids += $(this).data("productId") + ",";
    });
    xajax_get_products_compare(ids);
    $('#ProductsDescription').modal('show');
}

function product_compare_returned(content) {
    $("#ProductsDescriptionContent").html(content);

}


function show_legacy() {
    $("#legacyContent").html("<p>" + keytoursI18n.loading + "</p>");
    xajax_get_legacy();
    $('#legacy').modal('show');
}

function legacy_returned(content) {
    $("#legacyContent").html(content);
}

function product_description_returned(content) {
    $("#product-description-content").html(content);
    if (document.getElementById('gallery')) {
        document.getElementById('gallery').onclick = function (event) {
            event = event || window.event;
            var target = event.target || event.srcElement,
                link = target.src ? target.parentNode : target,
                options = { index: link, event: event },
                links = this.getElementsByTagName('a');
            blueimp.Gallery(links, options);
        };
    }
}


function calGo(id, date, forcePrice) {

    var calandar = new IabsisCalendarPopup();
    calandar.refresh(
        $("#" + id).get(),
        calendar_url,
        (id == "jour_depart" ? $("#opened_product_id").val() : $("#opened_product_id").val()),
        (id == "jour_depart" ? calendar_on_select : calendar_on_select_retour),
        date,
        id,
        (id == "jour_depart" ? null : $("#jour_depart")),
        (id == "jour_retour" ? null : $("#jour_retour")),
        forcePrice
    );
}

function save_cart() {
    $("#confirm_dialog").remove();
    $("body").append('<div id="confirm_dialog"></div>');

    $("#confirm_dialog")
        .attr("title", keytoursI18n.cartName)
        .html('<p class="validateTips">' + keytoursI18n.chooseName + '</p>' +
            '<form onsubmit="return false;">' +
            '<fieldset>' +
            '<input type="text" name="name" id="cart_name" class="text ui-widget-content ui-corner-all" style="width:200px;" value="' + keytoursI18n.newCart + '" />' +
            (cart_open_from_name ? '<div class="alert">Ce panier a été chargé depuis le panier "' + cart_open_from_name + '"</div>' : '') +
            '</fieldset>' +
            '</form>');
    var name = $("#cart_name");

    var buttons = {};
    if (cart_open_from) {
        buttons['Ecraser'] = function () {
            $(this).dialog("close");
            bootbox.confirm("Voulez-vous vraiment écraser le panier actuel ?", function (confirmation) {
                if (confirmation) {
                    xajax_save_cart(name.val(), 1);
                }
            });

        }
    }

    buttons['Save new'] = function () {
        xajax_save_cart(name.val(), 0);
        $(this).dialog("close");
    };

    buttons['Annuler'] = function () {
        $(this).dialog("close");
    };

    $("#confirm_dialog").dialog({
        resizable: false,
        width: 350,
        height: 350,
        modal: true,
        buttons: buttons
    });
}

function save_cart_success() {
    alert(keytoursI18n.cartSaved);
}

function open_cart(id) {
    if (confirm(keytoursI18n.loadCart)) {
        window.location.href = "?section=submit&form=open_cart&id=" + id;
    }
}


// -------------------

function IabsisCalendarPopup() {
    this.content = "";
    this.object = null;
    this.productKey = 0;
    this.onSelect = null;
    this.url = "";
    this.fieldId = "";
    this.start = null;
    this.end = null;
    this.forcePrice = null;

    this.initCalendar = function (object, url, productKey, onSelect, fieldId, start, end, forcePrice) {
        this.object = object;
        this.productKey = productKey;
        this.onSelect = onSelect;
        this.url = url;
        this.date = $(this.object).val();
        this.fieldId = fieldId;
        this.start = start;
        this.end = end;
        this.forcePrice = forcePrice;

        var content = $('<div id="iabsisCalendarContent"></div>').hide();
        $("body").prepend(content);
        this.getContent();

    };

    this.getContent = function () {
        var url = this.url + "?product_key=" + this.productKey;
        if (/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/.test(this.date)) {
            url += "&date=" + this.date;

        }
        url += "&field_id=" + this.fieldId;

        if ($(this.object).attr("id") === "jour_retour") {
            url += "&retour=1";
            url += "&departure_date=" + $("#jour_depart").val();
            url += "&departure_time=" + $("#heure_depart").val();
        }
        else {
            url += "&retour=0";
        }

        if (this.start !== null) {
            url += "&start=" + this.start.val();
        }
        if (this.end !== null) {
            url += "&end=" + this.end.val();
        }

        if (this.forcePrice) {
            url += "&forcePrices=" + this.forcePrice;
        }

        $.ajax({
            url: url,
            context: this,
            success: function (data) {
                this.showCalendarContent(data);
            }
        });
    };

    this.refresh = function (object, url, productKey, onSelect, date, fieldId, start, end, forcePrice) {

        this.object = object;
        this.productKey = productKey;
        this.onSelect = onSelect;
        this.url = url;
        this.date = date;
        this.fieldId = fieldId;
        this.start = start;
        this.end = end;
        this.forcePrice = forcePrice;

        this.getContent();
    };

    this.showCalendarContent = function (content) {
        $('#iabsisCalendarContent').html(content).show(200);
        var me = this;
        $(".jours > .dispo").click(function () {
            $(me.object).val($(this).data("date"));
            me.hideCalendar();
            if (me.onSelect !== null) {
                me.onSelect($(this).data("date"));
            }
        });
        $(".jours > .dispo").each(function () {
            if ($(this).data("date") === $(me.object).val()) {
                $(this).addClass("selected");
            }
            else {
                $(this).removeClass("selected");
            }
        });

    };

    var clickInitialized = false;
    this.showCalendar = function (object, url, productKey, onSelect, fieldId, start, end, forcePrice) {
        if (!clickInitialized) {
            $('html').click(function () {
                me.hideCalendar();
            });

            clickInitialized = true;
        }

        if (!$('#iabsisCalendarContent').html()) {
            this.initCalendar(object, url, productKey, onSelect, fieldId, start, end, forcePrice);
            var me = this;

            $('#iabsisCalendarContent').click(function (event) {
                event.stopPropagation();
            });
        }
        else {
            this.hideCalendar();
        }

        $("#iabsisCalendarContent").css({
            top: $(object).offset().top + $(object).outerHeight(),
            right: $(window).outerWidth() - $(object).offset().left - $(object).outerWidth(),
            left: "auto"
        });

    };

    this.hideCalendar = function () {
         if ($('#iabsisCalendarContent').html()) {
            $("#iabsisCalendarContent").hide(200, function () {
                $(this).remove();
            });
        }
    };
}


function is_email(string) {
    var email_reg_expr = /^[a-zA-Z0-9\-\.\_]+@{1}[a-zA-Z0-9\-\.\_]+\.{1}[a-zA-Z0-9]{2,4}$/;
    return email_reg_expr.test(string);
    return false;
}


function parseHoraires(jsonData) {
    var data = $.parseJSON(jsonData);
    var size = data.length;
    var cpt = 0;
    for (cpt = 0; cpt < size; cpt++) {

        var vars = data[cpt].vars;

        switch (data[cpt].type) {
            case "add_horaire_for_place":
                if (vars[3] === "0") vars[3] = false;
                add_horaire_for_place(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9]);
                break;
            case "add_pickup":
                add_pickup(vars[0], vars[1], vars[2], vars[3], vars[4]);
                break;
            case "add_dropto":
                add_dropto(vars[0], vars[1], vars[2], vars[3], vars[4]);
                break;
            case "show_places":
                if (vars[0] === "0") vars[0] = false;
                show_places(vars[0]);
                break;
            case "calculate_subtotal":
                calculate_subtotal();
            default:
                break;
        }
    }

    editProductWaitingHide();
}

function keytours_update_ville_depart() {
    $("#info_ville_depart").text($("#heure_depart option:selected").data('ville'));
}

function change_heure_depart() {
    if ($("#heure_depart option:selected").data("places") <= 0) return;
    show_villes();
    show_pickups();
    show_dropto();
    keytours_update_ville_depart();
}

function add_product_to_cart(id) {
    xajax_add_product(id);
    $("#ProductsDescription").modal("hide");

}

var seeLessOrMoreAction = function (langs) {
    var setProductDisplayMode = function () {
        if ($('.seeless a span').text() == langs.compactList) {
            $.cookie('product_view', 'detailed', { path: '/' });
        } else {
            $.cookie('product_view', 'compact', { path: '/' });
        }
    };

    if (!$.cookie('product_view')) {
        $('.seeless a span').text(langs.detailedList);
        setProductDisplayMode();
    } else {
        if ($.cookie('product_view') == "compact") {
            $('.seeless a span').text(langs.detailedList);
            $("div.product").addClass("detailed");
            $("#next-schedules-content div.entry").addClass("detailed");
        } else {
            $('.seeless a span').text(langs.compactList);
            $("div.product").removeClass("detailed");
            $("#next-schedules-content div.entry").removeClass("detailed");
        }
    }

    $(".seeless a").unbind().bind("click", function () {
        $("div.product, .row-next-schedules-container").toggleClass("detailed");
        $('.seeless a span').text($('.seeless a span').text() === langs.compactList ? langs.detailedList : langs.compactList);
        setProductDisplayMode();
    });


};

var getCurrentCurrency = function () {
    return $.cookie("CURRENCY") || "euros";
}

// Gestion du modal de mail
$(function () {
    $("#send-mail-form").submit(function (e) {
        e.preventDefault();
        if (!$("#userEmail").val()) {
            $("#userEmail").parents(".control-group").addClass("error");
            return;
        }

        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        if (!re.test($("#userEmail").val())) {
            $("#userEmail").parents(".control-group").addClass("error");
            return;
        }

        $("#userEmail").parents(".control-group").removeClass("error");
        $("#mailing-product-id").val($("#send-by-mail-link").data("productId"));
        $.ajax({
            type: "POST",
            url: $("#send-mail-form").attr("action"),
            data: $("#send-mail-form").serialize()
        });

        $("#ProductSendMail").modal("hide");

    });
});

// Init the period selector
$(function () {

    $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });

    $("body").on("focus", "#heure_depart, #heure_retour", function () {
        if ($(this).attr("id") == "heure_depart") {
            var $jourSelection = $("#jour_depart");
            var heureDepart = $("#heure_vol_depart").val();
        } else {
            var $jourSelection = $("#jour_retour");
            var heureDepart = $("#heure_vol_retour").val();
        }

        var initialFieldTime = heureDepart;

        if (!(/[0-9]{2}\:[0-9]{2}/.test(heureDepart))) {
            heureDepart = "00:00";
        };
        var aTime = heureDepart.split(":");
        var heureDepartMinDecimal = (parseInt(aTime[0]) * 60) + parseInt(aTime[1]);
        var heureDepartMaxDecimal = heureDepartMinDecimal;

        if ($jourSelection.data("tempsProduitVersAvion") > 0) {
            heureDepartMaxDecimal -= parseInt($jourSelection.data("tempsProduitVersAvion"));
            heureDepartMaxDecimal -= parseInt($jourSelection.data("dureeProduit"));
        }

        if ($jourSelection.data("tempsAvionVersProduit") > 0) {
            heureDepartMinDecimal += parseInt($jourSelection.data("tempsAvionVersProduit"));
        }

        var heureMin = parseInt(heureDepartMinDecimal / 60);
        if (heureMin < 10) {
            heureMin = "0" + heureMin;
        }

        var minuteMin = parseInt(heureDepartMinDecimal % 60);
        if (minuteMin < 10) {
            minuteMin = "0" + minuteMin;
        }

        var heureDepartMinimum = heureMin + ":" + minuteMin + ":00";

        var heureMax = parseInt(heureDepartMaxDecimal / 60);
        if (heureMax < 10) {
            heureMax = "0" + heureMax;
        }

        var minuteMax = parseInt(heureDepartMaxDecimal % 60);
        if (minuteMax < 10) {
            minuteMax = "0" + minuteMax;
        }

        var heureDepartMaximum = heureMax + ":" + minuteMax + ":00";


        if ($jourSelection.data("tempsAvionVersProduit") > 0) {
            var type = "avionVersProduit";
        }
        else {
            type = "produitVersAvion";
        }

        $(this).find("option").each(function () {
            if ($(this).val() == "") return;
            switch (type) {
                case "avionVersProduit":
                    if ($(this).val() < heureDepartMinimum && initialFieldTime != "" && initialFieldTime != undefined) {
                        if (!$(this).is(":disabled")) {
                            $(this).attr("disabled", "disabled");
                            $(this).text($(this).text() + " (impossible)");
                        }

                    } else {
                        if ($(this).data("places") > 0 && !$(this).data("event")) {
                            $(this).removeAttr("disabled");
                        }
                        $(this).text($(this).text().replace(" (impossible)", ""));
                    }
                    break;
                default:
                    if ($(this).val() > heureDepartMaximum && initialFieldTime != "" && initialFieldTime != undefined) {
                        if (!$(this).is(":disabled")) {
                            $(this).attr("disabled", "disabled");
                            $(this).text($(this).text() + " (impossible)");
                        }

                    } else {
                        if ($(this).data("places") > 0 && !$(this).data("event")) {
                            $(this).removeAttr("disabled");
                        }
                        $(this).text($(this).text().replace(" (impossible)", ""));
                    }
                    break;
            }

        })
    });

    $("body").on("change", "#heure_vol_depart, #heure_vol_retour", function () {
        if ($(this).attr("id") == "heure_vol_depart") {
            $("#heure_depart").trigger("focus");
        } else {
            $("#heure_retour").trigger("focus");
        }
    });
});


// Init the currency selector
$(function () {
    $("[data-choose-currency]").on("click", function (e) {
        e.preventDefault();
        $.cookie("CURRENCY", $(this).data("chooseCurrency"), { path: "/" });
        switch ($(this).data("chooseCurrency")) {
            case "euros":
                $("body").removeClass("currency-dollars currency-chfs").addClass("currency-euros");
                break;
            case "dollars":
                $("body").removeClass("currency-euros currency-chfs").addClass("currency-dollars");
                break;
            case "chfs":
                $("body").removeClass("currency-euros currency-dollars").addClass("currency-chfs");
                break;
        }
    });
});

// Gestion des commentaires
$(function () {
    $(document).on('click', ".post-comment", function (e) {
        e.preventDefault();
        $("#product-reference-block").show();
        $("#comment-product-key").val($(this).data('productId'));
        if ($(this).data('productId')) {
            $("#product-reference-block").hide();
        }

        if (authenticated === true) {
            $("#ProducComment").modal("show");
        }
        else {
            var $loginButton = $("#login-button").clone();
            var modal = bootbox.alert(keytoursI18n.authBeforePost);
            modal.find(".modal-footer").append($loginButton);

            $loginButton.on("click", function (e) {
                e.preventDefault();
                window.location.href = $(this).attr("href");
            });
        }
    });

    $("#send-comment-form").submit(function (e) {
        var form = $(this);
        e.preventDefault();
        if ((!$("#commentProductRef").val() && !$("#comment-product-key").val()) || !$("#commentText").val()) {
            form.parents(".modal").find(".error-message").fadeIn(100).delay(600).fadeOut(100);
            return;
        }
        form.parents(".modal").find("button").prop("disabled", true);
        $.ajax({
            type: "POST",
            url: form.attr("action"),
            data: form.serialize()
        })
            .done(function () {
                form.parents(".modal").find("button").prop("disabled", false);
                $(".modal").find("[data-dismiss]").trigger("click");
                $("#commentProductRef").val('');
                $("#commentText").val('');
                $("#comment-product-key").val('');
            })
            .fail(function () {
                bootbox.alert("Erreur pendant l'envoie du formulaire");
            })
            .always(function () {
                form.parents(".modal").find("button").prop("disabled", false);
            });
    });


});

$(document).ready(function() {
	if (!$("#payment-button").data("admin") && ($("#payment-button").data("admin") == '')) {
		var cart_ids = $('.selection').data("initial-product-id");
		if ($('.btn-add-product').data("product-id") == cart_ids) {
			$('a.[data-product-id]').remove();
		}
	}
});



/*
$(document).ready(function() {

    $("ul.notes-echelle").addClass("js");
    $("ul.notes-echelle li").addClass("note-off");

    $("ul.notes-echelle input")
            .focus(function() {
                    $(this).parents("ul.notes-echelle").find("li").removeClass("note-focus");
                    $(this).parent("li").addClass("note-focus");
                    $(this).parent("li").nextAll("li").addClass("note-off");
                    $(this).parent("li").prevAll("li").removeClass("note-off");
                    $(this).parent("li").removeClass("note-off");
            })
            .blur(function() {
                    $(this).parents("ul.notes-echelle").find("li").removeClass("note-focus");
                    if($(this).parents("ul.notes-echelle").find("li input:checked").length == 0) {
                            $(this).parents("ul.notes-echelle").find("li").addClass("note-off");
                    }
            })
            .click(function() {
                    $(this).parents("ul.notes-echelle").find("li").removeClass("note-checked");
                    $(this).parent("li").addClass("note-checked");
            });

    $("ul.notes-echelle li").mouseover(function() {
            $(this).nextAll("li").addClass("note-off");
            $(this).prevAll("li").removeClass("note-off");
            $(this).removeClass("note-off");
    });

    $("ul.notes-echelle").mouseout(function() {
            $(this).children("li").addClass("note-off");
            $(this).find("li input:checked").parent("li").trigger("mouseover");
    });

    $("ul.notes-echelle input:checked").parent("li").trigger("mouseover");
    $("ul.notes-echelle input:checked").trigger("click");

});
*/

$(function () {
    $('#rating-comment').rating(null, {
        maxvalue: 5, increment: .5, curvalue: 5, callback: function (value) {
            $("#id-note").val(value);
        }
    });
});






//////////// Credit card tester ////////////////////////////////////////////////////////////////////

/*================================================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on the web, although the
best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia
Updated:    11th Sep. 2010      Typos removed from Diners and Solo definitions (thanks to Noe Leon)
Updated:    10th April 2012     New matches for Maestro, Diners Enroute and Switch
Updated:    17th October 2012   Diners Club prefix 38 not encoded

*/

/*
   If a credit card number is invalid, an error reason is loaded into the global ccErrorNo variable.
   This can be be used to index into the global error  string array to report the reason to the user
   if required:

   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array()

ccErrors[0] = "Unknown card type";
ccErrors[1] = "No card number provided";
ccErrors[2] = "Credit card number is in invalid format";
ccErrors[3] = "Credit card number is invalid";
ccErrors[4] = "Credit card number has an inappropriate number of digits";
ccErrors[5] = "Warning! This credit card number is associated with a scam attempt";

function checkCreditCard(cardnumber, cardname) {
    // Array to hold the permitted card characteristics
    var cards = new Array();

    // Define the cards we support. You may add addtional card types as follows.

    //  Name:         As in the selection box of the form - must be same as user's
    //  Length:       List of possible valid lengths of the card number for the card
    //  prefixes:     List of possible prefixes for the card
    //  checkdigit:   Boolean to say whether there is a check digit

    cards[0] = {
        name: "Visa",
        length: "13,16",
        prefixes: "4",
        checkdigit: true
    };
    cards[1] = {
        name: "MasterCard",
        length: "16",
        prefixes: "51,52,53,54,55",
        checkdigit: true
    };
    cards[2] = {
        name: "DinersClub",
        length: "14,16",
        prefixes: "36,38,54,55",
        checkdigit: true
    };
    cards[3] = {
        name: "CarteBlanche",
        length: "14",
        prefixes: "300,301,302,303,304,305",
        checkdigit: true
    };
    cards[4] = {
        name: "American Express",
        length: "15",
        prefixes: "34,37",
        checkdigit: true
    };
    cards[5] = {
        name: "Discover",
        length: "16",
        prefixes: "6011,622,64,65",
        checkdigit: true
    };
    cards[6] = {
        name: "JCB",
        length: "16",
        prefixes: "35",
        checkdigit: true
    };
    cards[7] = {
        name: "enRoute",
        length: "15",
        prefixes: "2014,2149",
        checkdigit: true
    };
    cards[8] = {
        name: "Solo",
        length: "16,18,19",
        prefixes: "6334,6767",
        checkdigit: true
    };
    cards[9] = {
        name: "Switch",
        length: "16,18,19",
        prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
        checkdigit: true
    };
    cards[10] = {
        name: "Maestro",
        length: "12,13,14,15,16,18,19",
        prefixes: "5018,5020,5038,6304,6759,6761,6762,6763",
        checkdigit: true
    };
    cards[11] = {
        name: "VisaElectron",
        length: "16",
        prefixes: "4026,417500,4508,4844,4913,4917",
        checkdigit: true
    };
    cards[12] = {
        name: "LaserCard",
        length: "16,17,18,19",
        prefixes: "6304,6706,6771,6709",
        checkdigit: true
    };

    // Establish card type
    var cardType = -1;
    for (var i = 0; i < cards.length; i++) {

        // See if it is this card (ignoring the case of the string)
        if (cardname.toLowerCase() == cards[i].name.toLowerCase()) {
            cardType = i;
            break;
        }
    }

    // If card type not found, report an error
    if (cardType == -1) {
        ccErrorNo = 0;
        return false;
    }

    // Ensure that the user has provided a credit card number
    if (cardnumber.length == 0) {
        ccErrorNo = 1;
        return false;
    }

    // Now remove any spaces from the credit card number
    cardnumber = cardnumber.replace(/\s/g, "");

    // Check that the number is numeric
    var cardNo = cardnumber
    var cardexp = /^[0-9]{13,19}$/;
    if (!cardexp.exec(cardNo)) {
        ccErrorNo = 2;
        return false;
    }

    // Now check the modulus 10 check digit - if required
    if (cards[cardType].checkdigit) {
        var checksum = 0;                                  // running checksum total
        var mychar = "";                                   // next char to process
        var j = 1;                                         // takes value of 1 or 2

        // Process each digit one by one starting at the right
        var calc;
        for (i = cardNo.length - 1; i >= 0; i--) {

            // Extract the next digit and multiply by 1 or 2 on alternative digits.
            calc = Number(cardNo.charAt(i)) * j;

            // If the result is in two digits add 1 to the checksum total
            if (calc > 9) {
                checksum = checksum + 1;
                calc = calc - 10;
            }

            // Add the units element to the checksum total
            checksum = checksum + calc;

            // Switch the value of j
            if (j == 1) { j = 2 } else { j = 1 };
        }

        // All done - if checksum is divisible by 10, it is a valid modulus 10.
        // If not, report an error.
        if (checksum % 10 != 0) {
            ccErrorNo = 3;
            return false;
        }
    }

    // Check it's not a spam number
    if (cardNo == '5490997771092064') {
        ccErrorNo = 5;
        return false;
    }

    // The following are the card-specific checks we undertake.
    var LengthValid = false;
    var PrefixValid = false;
    var undefined;

    // We use these for holding the valid lengths and prefixes of a card type
    var prefix = new Array();
    var lengths = new Array();

    // Load an array with the valid prefixes for this card
    prefix = cards[cardType].prefixes.split(",");

    // Now see if any of them match what we have in the card number
    for (i = 0; i < prefix.length; i++) {
        var exp = new RegExp("^" + prefix[i]);
        if (exp.test(cardNo)) PrefixValid = true;
    }

    // If it isn't a valid prefix there's no point at looking at the length
    if (!PrefixValid) {
        ccErrorNo = 3;
        return false;
    }

    // See if the length is valid for this card
    lengths = cards[cardType].length.split(",");
    for (j = 0; j < lengths.length; j++) {
        if (cardNo.length == lengths[j]) LengthValid = true;
    }

    // See if all is OK by seeing if the length was valid. We only check the length if all else was
    // hunky dory.
    if (!LengthValid) {
        ccErrorNo = 4;
        return false;
    };

    // The credit card is in the required format.
    return true;
}


$(function () {
    var tabletMaxResolution = 979;
    var mobileMaxResolution = 767;

    var setBodyClass = function () {
        if ($(window).width() <= mobileMaxResolution) {
            $("body").removeClass('is-tablet is-desktop').addClass('is-mobile');
        } else if ($(window).width() <= tabletMaxResolution) {
            $("body").removeClass('is-mobile is-desktop').addClass('is-tablet');
        } else if ($(window).width() > tabletMaxResolution) {
            $("body").removeClass('is-mobile is-tablet').addClass('is-desktop');
        }
    }

    $(window).resize(function () {
        setBodyClass();
    });

    setBodyClass();
});

/*================================================================================================*/
