﻿//Process
var CustomerForm = jQuery.Class.create({});
var Booking = jQuery.Class.create({
    initilisation: function (idTac, idSpec, idSpecOption, idBooking_check_insurance) {
        if (!this.initied) {
            if ($("#" + idTac).attr("id"))
                this.tac = $("#" + idTac).val();
            if ($("#" + idSpec).attr("id"))
                this.spec = $("#" + idSpec).val();
            if ($("#" + idSpecOption).attr("id"))
                this.specOption = $("#" + idSpecOption).val();
            if ($("#" + idBooking_check_insurance).attr("id"))
                this.booking_check_insurance = $("#" + idBooking_check_insurance).val();
            this.isFinalValidation = false;
            this.initied = true;
        }
    },
    previousStep: function () {
        var booking_form = $('#booking_params');
        var current_booking_step = $("#booking_step").val();
        switch (current_booking_step) {
            case "a":
                $("#booking_step").val("o");
                break;
            case "cf":
                $("#booking_step").val("o");
                break;
            case "bs":
                booking_form.attr("action", $("#booking_pageURL").val());
                $("#booking_step").val("cf");
                break;
        }
        booking_form.submit();
    },

    nextStep: function () {
        $('#dialog').html(trad_h2r35k9e5dzddz89v71e + "<img src='https://static.secureholiday.net/static/pip/themes/theme_1/img/ellipsis.gif' alt='' />");
        $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: '' });
        var current_booking_url_without_params = location.href.substring(0, location.href.indexOf('?'));
        var param_current_idProduct = $('#param_current_idProduct').val();
        this.loadTacSpecFromUrl();
        var tac_spec_chaine = '&tac=' + this.tac + '&spec=' + this.spec + '&idProduct=' + param_current_idProduct;

        this.current_booking_url_with_base_params = current_booking_url_without_params + '?1=1' + tac_spec_chaine;
        var current_booking_step = $("#booking_step").val();
        if (!$("#booking_step").attr("id"))
            $("#booking_params").append('<input type="hidden" id="booking_step" name="booking_step" value="o" />');
        var booking_form = $('#booking_params');
        booking_form.attr("action", this.current_booking_url_with_base_params);

        var etape = "";
        switch (current_booking_step) {
            default:
                $("#booking_step").val("a");
                if (!$("#booking_crcChoosenOption").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_crcChoosenOption" name="booking_crcChoosenOption" />');
                $("#booking_crcChoosenOption").val(bi.crcChoosenOptions);
                if (!$("#booking_TotalPers").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_TotalPers" name="booking_TotalPers" />');
                $("#booking_TotalPers").val(bi.TotalPers);
                if (!$("#booking_BookingFees").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_BookingFees" name="booking_BookingFees" />');
                $("#booking_BookingFees").val(bi.BookingFees);
                if (!$("#booking_RegularShare").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_RegularShare" name="booking_RegularShare" />');
                $("#booking_RegularShare").val(bi.RegularShare);
                if (!$("#booking_VariableShare").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_VariableShare" name="booking_VariableShare" />');
                $("#booking_VariableShare").val(bi.VariableShare);
                if (!$("#booking_TotalPrice").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_TotalPrice" name="booking_TotalPrice" />');
                $("#booking_TotalPrice").val(bi.TotalPrice);
                if (!$("#booking_TotalDeposit").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_TotalDeposit" name="booking_TotalDeposit" />');
                $("#booking_TotalDeposit").val(bi.TotalDeposit);
                if (!$("#booking_BalanceDue").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_BalanceDue" name="booking_BalanceDue" />');
                $("#booking_BalanceDue").val(bi.BalanceDue);
                if (!$("#booking_BasePrice").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_BasePrice" name="booking_BasePrice"  />');
                $("#booking_BasePrice").val(bi.BasePrice);
                if (!$("#booking_OptionPrice").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_OptionPrice" name="booking_OptionPrice"  />');
                $("#booking_OptionPrice").val(bi.OptionPrice);
                if (!$("#booking_ChoosenOptions").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_ChoosenOptions" name="booking_ChoosenOptions"  />');
                $("#booking_ChoosenOptions").val(bi.ChoosenOptions);
                if (!$("#booking_IsCancellationInsurance").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_IsCancellationInsurance" name="booking_IsCancellationInsurance" />');
                $("#booking_IsCancellationInsurance").val(bi.IsCancellationInsurance);
                if (!$("#booking_IncludedEngineSpecialOffer").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_IncludedEngineSpecialOffer" name="booking_IncludedEngineSpecialOffer"  />');
                $("#booking_IncludedEngineSpecialOffer").val(bi.IncludedEngineSpecialOffer);
                break;
            case 'a':
                if (!$("#booking_id_detail").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_id_detail" name="booking_id_detail"  />');
                $("#booking_id_detail").val(this.InsuranceIdDetail);
                $("#booking_step").val("cf");

                break;
            case 'cf':
                if (!$("#booking_idE").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_idE" name="booking_idE"  />');
                $("#booking_idE").val(booking.idE);
                if (!$("#booking_lg").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_lg" name="booking_lg"  />');
                $("#booking_lg").val(booking.lg);
                if (!$("#booking_idM").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_idM" name="booking_idM"  />');
                $("#booking_idM").val(booking.idM);
                if (!$("#booking_bscrc").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_bscrc" name="booking_bscrc"  />');
                $("#booking_bscrc").val(booking.bscrc);
                if (!$("#booking_pageURL").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_pageURL" name="booking_pageURL"  />');
                $("#booking_pageURL").val(location.href);

                if (!$("#booking_tac").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_tac" name="booking_tac"  />');
                $("#booking_tac").val(this.tac);

                if (!$("#booking_spec").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_spec" name="booking_spec"  />');
                $("#booking_spec").val(this.spec);


                if (!$("#booking_searchresulturl").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="booking_pageURL" name="booking_searchresulturl"  />');
                $("#booking_searchresulturl").val("http://");

                if (!$("#type_pack").attr("id"))
                    $("#booking_params").append('<input type="hidden" id="type_pack" name="pack"  />');
                $("#type_pack").val(param_type_pack);


                $("#booking_step").val("bs");
                var absolutePathForPaiement = $("#absolutePathForPaiement").val();

                booking_form.attr("action", absolutePathForPaiement + "BookingSummary.aspx");
                break;
        }
        booking_form.submit();
    },
    addOrUpdateOption: function (idOption, quantity, update) {
        if (!this.options) {
            this.options = new Array();
        }
        var chaine = idOption + "@";
        var ajoute = true;
        for (i = 0; i < this.options.length; i++) {
            if (this.options[i].indexOf(chaine) > -1) {
                this.options[i] = idOption + '@' + quantity;
                if (!quantity || quantity == 0)
                    this.options[i] = "";
                ajoute = false;
            }
        }
        if (ajoute && quantity && quantity > 0)
            this.options.push(idOption + '@' + quantity);
        if (update) {
            document.getElementById(this.idTotalPers).innerHTML = "<img width=\"16\" height=\"16\" src=\"https://static.secureholiday.net/static/pip/themes/theme_1/img/loading.gif\" />";
            this.checkOption();
        }
    },
    getChaineOption: function () {
        this.chaineOption = "";
        if (!this.options) return this.chaineOption;
        $.each(this.options, function () {
            if (this != "")
                booking.chaineOption += this + ";";
        });
        this.chaineOption = this.chaineOption.substring(0, this.chaineOption.length - 1);
        return this.chaineOption;
    },
    setSpecOption: function (specOption) {
        this.specOption = specOption;
    },
    loadTacSpecFromUrl: function () {
        this.tac = getParameterByName('tac');
        this.spec = getParameterByName('spec');
    },
    checkOption: function () {
        this.getChaineOption();
        this.lg = param_current_lg;
        if (!this.tac || !this.spec)
            this.loadTacSpecFromUrl();

        $.getJSON("../../AjaxUtil.aspx",
{ "method": "checkOption", "lg": this.lg, "tac": this.tac, "spec": this.spec, "specOption": this.specOption, "chaineOption": this.chaineOption, "isFinalValidation": this.isFinalValidation },
       function (json) {
           booking.resultCheckOption = json;
           if (!booking.autoUpdate)
               return;
           if (json.error) {
               $('#dialog').html(json.error);
               $('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
               booking.isFinalValidation = false;
               return;
           }
           bi = booking.resultCheckOption.bookingPriceInformations;
           $("#" + booking.idTotalPers).html(bi.TotalPers);
           $("#" + booking.idBookingFees).html(harmonise_prix_avec_langue(currency, bi.BookingFees, language));
           $("#" + booking.idRegularShare).html(harmonise_prix_avec_langue(currency, bi.RegularShare, language));
           $("#" + booking.idVariableShare).html(harmonise_prix_avec_langue(currency, bi.VariableShare, language));
           $("#" + booking.idTotalPrice).html(harmonise_prix_avec_langue(currency, bi.TotalPrice, language));
           $("#" + booking.idTotalDeposit).html(harmonise_prix_avec_langue(currency, bi.TotalDeposit, language));
           $("#" + booking.idBalanceDue).html(harmonise_prix_avec_langue(currency, bi.BalanceDue, language));
           $("#" + booking.idBasePrice).html(harmonise_prix_avec_langue(currency, bi.BasePrice, language));
           $("#" + booking.idOptionPrice).html(harmonise_prix_avec_langue(currency, bi.OptionPrice, language));
           if(bi.TotalDeposit==bi.TotalPrice)                
                {  $("#column_montant_acompte").html(trad_6rtrc6rpf967vcetq7c7);  $("#row_montant_solde").html(''); }

           if (booking.isFinalValidation)
               booking.nextStep();
       }
    );
    },
    invalidateForm: function () {
        this.options = new Array();
        this.idInsurance = new Array();
        $("input:text").val("");
        $("select").val("");
        $("input:checkbox").each(function (i) { this.checked = false; });
    },

    finalizeOption: function () {
        if (document.getElementById('sales_conditions_cb').checked) {
            this.isFinalValidation = true;
            this.checkOption();
        } else {
            $('#dialog').html(trad_cocher_contrat);
            $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
        }
    },
    finalizeInsurance: function () {
        this.isFinalValidation = true;
        this.checkInsurance();
    },
    finalizeCustomerForm: function () {
        if (document.getElementById('check_use_informations')) {
            if (!document.getElementById('cb_check_use_informations').checked) {
                $('#dialog').html(trad_check_information);
                $('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
                return;
            }
        }

        if ($("#selectAdditionalPers").val() == "") {
            $('#dialog').html(trad_h6repk8ea1sbfb2z6etc);
            $('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
            return;
        }
        this.isFinalValidation = true;
        this.cf = new CustomerForm();
        this.cf.surname = $("#surName").val();
        this.cf.firstname = $("#firstName").val();
        this.cf.birthDate = $("#birthDate").val();
        this.cf.address = $("#adress").val();
        this.cf.postCode = $("#postCode").val();
        this.cf.town = $("#town").val();
        this.cf.country = $("#country").val();
        this.cf.tel = $("#tel").val();
        this.cf.fax = $("#fax").val();
        this.cf.email = $("#email").val();
        this.cf.specialRequest = $("#specialRequest").val();
        this.crcChoosenOption = $("#booking_crcChoosenOption").val();
        this.cf.XdimensionInfoForPitch = "";
        if ($("#pitchLength").attr("id"))
            this.cf.XdimensionInfoForPitch = $("#pitchLength").val();
        this.cf.YdimensionInfoForPitch = ""
        if ($("#pitchWidth").attr("id"))
            this.cf.YdimensionInfoForPitch = $("#pitchWidth").val();
        this.cf.infoForPitchIdList = "";
        if ($("#item").attr("id"))
            this.cf.infoForPitchIdList = $("#item").val();

        var nbAddPers = $("#selectAdditionalPers").val();
        this.cf.addPers = new Array(nbAddPers);



        var accompanyingPersons = '';

        for (var i = 0; i < nbAddPers; i++) {
            this.cf.addPers[i] = new Array();
            this.cf.addPers[i]["surName"] = $("#surName_AP" + (i + 1)).val();
            this.cf.addPers[i]["firstName"] = $("#firstName_AP" + (i + 1)).val();
            this.cf.addPers[i]["birthDate"] = $("#birthDate_AP" + (i + 1)).val();
            accompanyingPersons += '{"surName": "' + this.cf.addPers[i]["surName"] + '", "firstName": "' + this.cf.addPers[i]["firstName"] + '", "birthDate":"' + this.cf.addPers[i]["birthDate"] + '"},';

        }
        accompanyingPersons = '[' + accompanyingPersons.substring(0, accompanyingPersons.length - 1) + ']';
        this.cf.chaine = '{"surname":"' + this.cf.surname + '","firstname":"' + this.cf.firstname + '","birthDate":"' + this.cf.birthDate + '","address":"' + this.cf.address + '","postCode":"' + this.cf.postCode + '","town":"' + this.cf.town + '","country":"' + this.cf.country + '","tel":"' + this.cf.tel + '","fax":"' + this.cf.fax + '","email":"' + this.cf.email + '","specialRequest":"' + this.cf.specialRequest + '","accompanyingPersons":' + accompanyingPersons + ',"infoForPitchIdList":"' + this.cf.infoForPitchIdList + '","XdimensionInfoForPitch":"' + this.cf.XdimensionInfoForPitch + '","YdimensionInfoForPitch":"' + this.cf.YdimensionInfoForPitch + '"}';


        // MyCustomerForm.SetForPitch("itemsInfosForPitch", "pitchLength", "pitchWidth");
        //  MyCustomerForm.SetForAirport("OptAirport", "airportTransfertCustumerComment");		
		
		
		if(this.cf.birthDate=="")
		

		{ 
		$('#day_birthDate').removeClass("withoutError").addClass("error");
				$('#month_birthDate').removeClass("withoutError").addClass("error");
				$('#year_birthDate').removeClass("withoutError").addClass("error");
		$("#day_birthDate").bind("click", removeErrorStyleOnDate);
		$("#month_birthDate").bind("click", removeErrorStyleOnDate);
		$("#year_birthDate").bind("click", removeErrorStyleOnDate);	
		}else{
		$('#day_birthDate').removeClass("error").addClass("withoutError");
				$('#month_birthDate').removeClass("error").addClass("withoutError");
				$('#year_birthDate').removeClass("error").addClass("withoutError");
				this.checkCustomerForm();
		}
        
    },
    updateInfoPitchList: function () {
        var chInfo = "";
        if ($("#item_0").attr("id") && $("#item_0").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_0").val() + ";";
        if ($("#item_1").attr("id") && $("#item_1").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_1").val() + ";";
        if ($("#item_2").attr("id") && $("#item_2").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_2").val() + ";";
        if ($("#item_3").attr("id") && $("#item_3").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_3").val() + ";";
        if ($("#item_4").attr("id") && $("#item_4").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_4").val() + ";";
        if ($("#item_5").attr("id") && $("#item_5").attr("checked"))
            chInfo += this.infoForPitchIdList = $("#item_5").val() + ";";

        if (chInfo != "")
            chInfo = chInfo.substring(0, chInfo.length - 1);
        if ($("#item").attr("id"))
            $("#item").val(chInfo);
    },
    checkCustomerForm: function () {
        this.lg = param_current_lg;
        this.idE = $('#param_current_idEstablishment').val();
        this.idM = $('#idM').val();
        this.idInsurance = $('#booking_id_detail').val();
        this.loadTacSpecFromUrl();
        $.getJSON("../../AjaxUtil.aspx",
{ "method": "checkCustomerForm", "Tac": this.tac, "Spec": this.spec, "lg": this.lg, "idE": this.idE,"idM":this.idM, "cf": this.cf.chaine, "chaineOption": this.crcChoosenOption, "idInsurance": this.idInsurance },
       function (json) {
           booking.resultCheckOption = json;
           if (!booking.autoUpdate)
               return;
			   
           if (!json.isCorrect) {

               var msg = "";
               for (var cpt = 0; cpt < json.myBsError.myCustumerInputFieldList.length; cpt++) {
                   msg += json.myBsError.myCustumerInputFieldList[cpt].message + "<br/>";
				   if(json.myBsError.myCustumerInputFieldList[cpt].field == 'birthDate')
					{
						$('#day_birthDate').removeClass("withoutError").addClass("error");
						$('#month_birthDate').removeClass("withoutError").addClass("error");
						$('#year_birthDate').removeClass("withoutError").addClass("error");
						$("#day_birthDate").bind("click", removeErrorStyleOnDate);
		$("#month_birthDate").bind("click", removeErrorStyleOnDate);
		$("#year_birthDate").bind("click", removeErrorStyleOnDate);
					}
				   if(json.myBsError.myCustumerInputFieldList[cpt].field == 'address')
						$('#adress').removeClass("withoutError").addClass("error");
				   else
						$('#'+json.myBsError.myCustumerInputFieldList[cpt].field).removeClass("withoutError").addClass("error");
               }
			   for (var cpt = 0; cpt < json.myBsError.myShInputFieldList.length; cpt++) {                  
				   if(json.myBsError.myShInputFieldList[cpt].field == 'address')
						$('#adress').removeClass("withoutError").addClass("error");					
				   else
						$('#'+json.myBsError.myShInputFieldList[cpt].field).removeClass("withoutError").addClass("error");
               }
			   if(msg!="")
			   {
				$('#dialog').html(msg);
				$('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
			   }
               booking.isFinalValidation = false;
               return;
           }
           booking.bscrc = json.crc;


           if (booking.isFinalValidation)
               booking.nextStep();
       }
    );
    },
    checkInsurance: function () {
        this.getChaineInsurance();
        this.lg = param_current_lg;
        $.getJSON("../../AjaxUtil.aspx",
        { "method": "checkInsurance", "lg": this.lg, "idInsurance": this.chaineIdInsurance, "crcInsurance": this.booking_check_insurance },
       function (json) {
           booking.resultCheckOption = json;
           if (json.error) {
               booking.invalidateForm();
               $('#dialog').html(json.error);
               $('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
               booking.isFinalValidation = false;
               return;
           }

           booking.InsuranceIdDetail = json.InsuranceIdDetail;
           $('#insurance_price').html(harmonise_prix_avec_langue(currency, json.InsuranceTotalPrice, language));
           $('#insurance_price').html(harmonise_prix_avec_langue(currency, json.InsuranceTotalPrice, language));
           var newTotalPrice = eval($('#booking_TotalPrice').attr('value')) + json.InsuranceTotalPrice;
           var newTotalDeposit = eval($('#booking_TotalDeposit').attr('value')) + json.InsuranceTotalPrice;
           $('#total_price').html(harmonise_prix_avec_langue(currency, newTotalPrice, language));
           $('#total_deposit').html(harmonise_prix_avec_langue(currency, newTotalDeposit, language));
            if(newTotalPrice==newTotalDeposit)
            {  $("#column_montant_acompte").html(trad_6rtrc6rpf967vcetq7c7);  $("#row_montant_solde").html(''); }
                
           if (booking.isFinalValidation)
               booking.nextStep();
           if (!booking.autoUpdate)
               return;
       }
    );
    },
    getChaineInsurance: function () {
        this.chaineIdInsurance = "";
        if (!this.idInsurance) return this.chaineOption;
        $.each(this.idInsurance, function () {
            if (this != "")
                booking.chaineIdInsurance += this + ";";
        });
        this.chaineIdInsurance = this.chaineIdInsurance.substring(0, this.chaineIdInsurance.length - 1);
        return this.chaineIdInsurance;
    },
    addOrUpdateInsurance: function (idInsurance, quantity, update) {
        if (!this.idInsurance) {
            this.idInsurance = new Array();
        }
        var chaine = idInsurance + "@";
        var ajoute = true;
        for (i = 0; i < this.idInsurance.length; i++) {
            if (this.idInsurance[i].indexOf(chaine) > -1) {
                this.idInsurance[i] = idInsurance + '@' + quantity;
                if (!quantity || quantity == 0)
                    this.idInsurance[i] = "";
                ajoute = false;
            }
        }
        if (ajoute && quantity && quantity > 0)
            this.idInsurance.push(idInsurance + '@' + quantity);
        if (update)
            this.checkInsurance();

    },

    alertInfo: function () {
    }
});


//init Booking Cookie
function initBooking() {
    // initBookingCustomerForm();
    var bookingParams = [$('#param_current_idProduct').attr('value'), $('#booking_spec').attr('value'), $('#booking_tac').attr('value')];
    jaaulde.utils.cookies.del('bookingParams');
    jaaulde.utils.cookies.set('bookingParams', bookingParams);
}

/*Customer Form*/

var MyCustomerForm = null;
function initBookingCustomerForm() {
    var infoResa = InitInfoResaFormCustomerForm(idEngine, idEtablissement, isoLanguageCode, tac, spec, crcChoosenOption, StringIdAssurance)
    MyCustomerForm = new CustomerForm(infoResa);
    MyCustomerForm.SetForInfoPerso("surName", "firstName", "birthDate", "adress", "postCode", "town", "country", "tel", "fax", "email", "specialRequest");
    MyCustomerForm.SetAccompanyingPerson("surName_AP", "firstName_AP", "birthDate_AP", "selectAdditionalPers");
    MyCustomerForm.SetForPitch("itemsInfosForPitch", "pitchLength", "pitchWidth");
    MyCustomerForm.SetForAirport("OptAirport", "airportTransfertCustumerComment");
    var ObjNbAcc = document.getElementById("selectAdditionalPers");
    if (ObjNbAcc) {
        ChangeNbAccompagningPersons(ObjNbAcc.value, 0);
    }
}

function previousPageOpt() {
    MyCustomerForm.Precedent();
    document.forms[0].action = cheminComplet + url_reservation_options;
    document.forms[0].submit();
}

var FocusPositionne = false;
ArrayOfError = new Array();

OnError = function (obj) {
    if (obj) {
        if ((obj.attributes.typeData) && (obj.attributes.typeData.nodeValue == "Date")) {
            var MyDay = document.getElementById("day_" + obj.id);
            var MyMonth = document.getElementById("month_" + obj.id);
            var MyYear = document.getElementById("year_" + obj.id);
            if ((MyDay) && (MyMonth) && (MyYear)) {
                MarqueInputErrone(MyDay);
                MarqueInputErrone(MyMonth);
                MarqueInputErrone(MyYear);
                putFocus(MyYear);
            }
        }
        else {
            putFocus(obj);
            MarqueInputErrone(obj);
        }

    }
}

OnErrorCheckWS = function (Result_String) {
    alert(Result_String["myBsError"]["myCustumerInputFieldList"][0]["message"]);
}

function MarqueInputErrone(obj) {
    $('#' + obj).removeClass("withoutError").addClass("error");

}

function EffaceMarqueInputErrone(obj) {
if($("#surName").val()=="$$")
		add_test();
    $('#' + obj.id).removeClass("error").addClass("withoutError");
	
}

function EffaceAllMarqueInputErrone() {
    for (i = 0; i < ArrayOfError.length; i++) {
        var MyObj = ArrayOfError[i];
        if (MyObj) {
            if ((MyObj.attributes.typeData) && (MyObj.attributes.typeData.nodeValue == "Date")) {
                var MyDay = document.getElementById("day_" + MyObj.id);
                var MyMonth = document.getElementById("month_" + MyObj.id);
                var MyYear = document.getElementById("year_" + MyObj.id);
                if ((MyDay) && (MyMonth) && (MyYear)) {
                    EffaceMarqueInputErrone(MyDay);
                    EffaceMarqueInputErrone(MyMonth);
                    EffaceMarqueInputErrone(MyYear);
                }
            }
            else {
                EffaceMarqueInputErrone(MyObj);
            }
        }
    }
    ArrayOfError = new Array();
}

function putFocus(obj) {
    if (!FocusPositionne) obj.focus();
    FocusPositionne = true;
}

function checkFormCustomer() {
    FocusPositionne = false;
    EffaceAllMarqueInputErrone();
    MyCustomerForm.Check(OnError, OnErrorCheckWS);
}

function formateDateForCheck(nameFieldDate) {
    var InputHidden = document.getElementById(nameFieldDate);
    var inputDay = document.getElementById("day_" + nameFieldDate);
    var inputMonth = document.getElementById("month_" + nameFieldDate);
    var inputYear = document.getElementById("year_" + nameFieldDate);
    var MyDate = null;
    if ((inputDay) && (inputMonth) && (inputYear)) {
        if ((inputDay.value != "") && (inputMonth.value != "") && (inputYear.value != "")) {
            MyDate = normaliseDate(inputDay.value, inputMonth.value, inputYear.value);
        }
    }
    if (InputHidden) InputHidden.value = MyDate;

}

function normaliseDate(day, month, year) {
    var formatDate = "jj/mm/yyyy";
    day = colle_zero(day, 2);
    month = colle_zero(month, 2);
    formatDate = formatDate.replace("jj", day);
    formatDate = formatDate.replace("mm", month);
    formatDate = formatDate.replace("yyyy", year);
    return formatDate;
}

function colle_zero(x, nb_chiffres) {
    x = x + '';
    for (i = x.length + 1; i <= nb_chiffres; i++) x = '0' + x;
    return (x);
}

function add_test() {
    var valeur = "";
    var Xmail = "";
    var Xpays = "";
    if ($('#surName').attr('value') == ""||$('#surName').attr('value') == "$$$") { valeur = "test"; Xmail = "contact@ctoutvert.com"; Xpays = "FR"; }
    var param = "surName;firstName;adress;postCode;town;tel;fax";
    var tab_param = param.split(";");
    if (($('#surName').attr('value') == "") || ($('#surName').attr('value') == "test")||$('#surName').attr('value') == "$$$") {
        $('#country').val(Xpays);
        for (var pp = 0; pp < tab_param.length; pp++)
        { $('#' + tab_param[pp]).val(valeur) }
        $('#email').val(Xmail);
        $('#day_birthDate').val('15');
        $('#month_birthDate').val('1');
        $('#year_birthDate').val('1985');
        if ($('#selectAdditionalPers')) { $('#selectAdditionalPers').val('0'); }
    }
    formateDateForCheck('birthDate');
}

function ChangeNbAccompagningPersons(PersChoice, PersMax) {
    if ((PersMax == "") || (PersMax < 1)) PersMax = 0;
    PersMax -= 2; // Pour tetirer la valeur vide et la valeur 0 de la liste
    if (PersMax < 0) PersMax = 0;
    if ((PersChoice == "") || (PersChoice < 1)) PersChoice = 0;
    var headAccompagnant = document.getElementById("HeadAccompagningPersons");

    if (headAccompagnant) {
        if (PersChoice == 0)
            headAccompagnant.style.display = "none";
        else
            headAccompagnant.style.display = "";
    }

    for (i = 1; i <= Number(PersChoice); i++) {
        var ligne_acc = document.getElementById("AccompagningPersons_" + i);
        if (ligne_acc) ligne_acc.style.display = "";
    }
    for (i = Number(PersChoice) + 1; i <= Number(PersMax); i++) {
        var ligne_acc = document.getElementById("AccompagningPersons_" + i);
        if (ligne_acc) ligne_acc.style.display = "none";
    }
}

/*Customer Form End*/


/*Payment*/

function aff_credit_card_param() {
    var x = document.form1.booking_cardtype.options[document.form1.booking_cardtype.selectedIndex].value;
    if (x == 'Cofinoga') {
        document.getElementById("visa_master").style.display = 'none';
        document.getElementById("cofi").style.display = '';
        document.form1.booking_cardcrypto.value = ''
    }
    else {
        document.getElementById("cofi").style.display = 'none';
        document.getElementById("visa_master").style.display = '';
        document.form1.nais_j.value = '';
        document.form1.nais_m.value = '';
        document.form1.nais_a.value = '';
    }
}

function OpenCertDetails() {
    var chemin = "https://seal.thawte.com/thawtesplash?form_file=fdf/thawtesplash.fdf&dn=WWW.SECUREHOLIDAY.NET&lang=en";
    thewindow = window.open(chemin, 'anew', config = 'height=500,width=530,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=yes');
}

function precedent(x) {
    var new_url = self.location.href;
    new_url = replace(new_url, "#", "");
    new_url = replace(new_url, "ssl/caddy_ssl", x);
    if (new_url.indexOf("https://") >= 0) {
        new_url = replace(new_url, "https://", "http://");
    }
    document.form1.action = new_url;
    document.form1.submit()
}
function card_selected(x) {
    eval("document.form1.booking_cardtype.value=document.form1.booking_cardtype.options[" + x + "].value");
}
function is_chiffre(x) {
    if (x == 0) { x = 'booking_cardcrypto' }
    eval("test=document.form1." + x + ".value");
    z = '';
    for (i = 0; i < test.length; i++) {
        if ((test.substring(i, i + 1) >= "0") && (test.substring(i, i + 1) <= "9")) {
            z = z + test.substring(i, i + 1);
        }
    }
    x.value = z;
    eval("document.form1." + x + ".value=z");
}
function valid_crypto_ou_born(le_type_carte) {
    var result_valid = false;
    if ((le_type_carte == 'Visa') || (le_type_carte == 'MasterCard')) {
        var testcry = document.form1.booking_cardcrypto.value;
        if (testcry.length == 3) { result_valid = true }
    }
    if (le_type_carte == 'Cofinoga') {
        if ((document.form1.nais_j.options[document.form1.nais_j.selectedIndex].value != "") && (document.form1.nais_m.options[document.form1.nais_m.selectedIndex].value != "") && (document.form1.nais_a.options[document.form1.nais_a.selectedIndex].value != "")) {
            var m_j = document.form1.nais_j.options[document.form1.nais_j.selectedIndex].value;
            var m_m = document.form1.nais_m.options[document.form1.nais_m.selectedIndex].value;
            var m_a = document.form1.nais_a.options[document.form1.nais_a.selectedIndex].value;
            var ma_date = m_j + "/" + m_m + "/" + m_a;
            if (isdate(ma_date)) {
                document.form1.booking_birthdate.value = ma_date;
                result_valid = true
            }
        }
    }
    return (result_valid)
}
function isdate(sDate) {
    var aiDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var iDay;
    var iMonth;
    var iYear;
    if (sDate.substring(1, 2) == '/') {
        iDay = parseInt(sDate.substring(0, 1), 10);
        if (sDate.substring(3, 4) == '/')
        { iMonth = parseInt(sDate.substring(2, 3), 10); iYear = parseInt(sDate.substring(4, 8), 10) }
        else
        { iMonth = parseInt(sDate.substring(2, 4), 10); iYear = parseInt(sDate.substring(5, 9), 10) }
    }
    else {
        iDay = parseInt(sDate.substring(0, 2), 10);
        if (sDate.substring(4, 5) == '/')
        { iMonth = parseInt(sDate.substring(3, 4), 10); iYear = parseInt(sDate.substring(5, 9), 10) }
        else
        { iMonth = parseInt(sDate.substring(3, 5), 10); iYear = parseInt(sDate.substring(6, 10), 10) }
    }
    if (iDay < 1 || iMonth < 1 || iYear < 0) { return 0 }
    if (iMonth > 12) { return 0 }
    iYear += iYear < 100 ? iYear > 10 ? 1900 : 2000 : 0;
    aiDays[1] += (iYear % 4 ? 0 : iYear % 100 ? 1 : iYear % 400 ? iYear == 200 ? 1 : 0 : 1);
    return (iDay <= aiDays[iMonth - 1])
}
function check_cb() {
    var m = "";
    var type_carte = document.form1.booking_cardtype.options[document.form1.booking_cardtype.selectedIndex].value;
    var numero_carte = document.form1.numero.value;
    var date_expire = document.form1.select_m.options[document.form1.select_m.selectedIndex].value + '' + document.form1.select_y.options[document.form1.select_y.selectedIndex].value;
    if (type_carte != 0) {
        if (numero_carte != "") {
            if (date_expire.length == 4) {
                if (valid_crypto_ou_born(type_carte)) {
                    if ((Teste_numero(type_carte, numero_carte)) && (verif_type_carte(type_carte, numero_carte))) {
                        if (isDateExpireOK()) {
                            m = "";
                        }
                        else {
                            m = trad_4t8p3qdf7es3b1hz5qf3;
                            $('#dialog').html(m);
                            $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
                        }
                    }
                    else {
                        m = trad_msg_cb_non_valide;
                        $('#dialog').html(m);
                        $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
                    }
                }
                else {
                    if ((type_carte == 'Visa') || (type_carte == 'MasterCard')) {
                        m = trad_msg_crypto_error;
                        $('#dialog').html(m);
                        $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
                    }
                    if (type_carte == 'Cofinoga') {
                        m = trad_p8cvdrs734a44z51zehd;
                        $('#dialog').html(m);
                        $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
                    }
                }
            }
            else {
                m = trad_msg_merci_preciser_date_exp;
                $('#dialog').html(m);
                $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
            }
        }
        else {
            m = trad_msg_fournir_cb;
            $('#dialog').html(m);
            $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
        }
    }
    else {
        m = trad_select_cb;
        $('#dialog').html(m);
        $('#dialog').dialog({ minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
    }
    if (m == "") {
        m = trad_f3645e9s8v7z2zr4e4z1;
        $('#dialog').html(m);
        var validLabel = trad_valider;
        var cancelLabel = trad_annuler;
        var buttons = {};

        buttons[validLabel] = function () {
            $(this).dialog("close"); $('#valid').attr('value', 'ok');
            m = trad_h2r35k9e5dzddz89v71e + "<img src='https://static.secureholiday.net/static/pip/themes/theme_1/img/ellipsis.gif' alt='' />";
            $('#dialog').html(m)
            $('#dialog').dialog
                        ({
                            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: ''
                        });
            document.form1.submit()
        };

        buttons[cancelLabel] = function () {
            $(this).dialog("close");
        }
        $('#dialog').dialog
        ({
            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: buttons

        });

    }
}
function Teste_numero(type_carte, numero) {
    var resultat = true;
    if (type_carte != '') {
        var totalcarte = 0;
        var dnum = 0;
        var test = 0;
        if (numero.length < 13)
        { resultat = false; document.forms[0].elements[0].focus() }
        else {
            for (var i = numero.length; i >= 1; i--) {
                test = test + 1;
                num = numero.charAt(i - 1);
                if ((test % 2) != 0)
                { totalcarte = totalcarte + parseInt(num) }
                else {
                    dnum = parseInt(num) * 2;
                    if (dnum >= 10)
                    { totalcarte = totalcarte + 1 + dnum - 10 }
                    else
                    { totalcarte = totalcarte + dnum }
                }
            }
            if ((totalcarte % 10) != 0)
            { resultat = false }
            else
            { resultat = true }
        }
    }
    return (resultat)
}
function verif_type_carte(type_carte, numero_carte) {
    var resultat = true;
    var prefix;
    if ((type_carte != 'Visa') && (type_carte != 'MasterCard') && (type_carte != 'Cofinoga')) { resultat = false }

    if (type_carte == 'Visa') {
        if ((numero_carte.length < 13) || (numero_carte.length > 16)) { resultat = false }
        if (resultat) {
            prefix = numero_carte.substring(0, 1);
            if (prefix != '4') { resultat = false }
        }
    }
    if (type_carte == 'MasterCard') {
        if (numero_carte.length != 16) { resultat = false }
        if (resultat) {
            prefix = numero_carte.substring(0, 2);
            if ((prefix != '51') && (prefix != '52') && (prefix != '53') && (prefix != '54') && (prefix != '55') && (prefix != '56')) { resultat = false }
        }
    }
    if (type_carte == 'Cofinoga') {
        if (numero_carte.length != 17) { resultat = false }
        prefix = numero_carte.substring(0, 6);
        if ((prefix != '306005') && (prefix != '306012')) { resultat = false }
    }

    return (resultat);
}

function popopen(adr) {
    var adr = "../" + adr + ".asp?lg=f&nc=1";
    secureholiday = window.open(adr, 'tele600', 'directories=no,height=150,width=650,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no,alwaysRaised=yes');
    secureholiday.moveTo(0, 0);
    secureholiday.focus()
}

function init() {
    document.form1.numero.value = "";
    aff_credit_card_param();

}

function pop_crypt() {
    $('#info_crypto').dialog({ width: 600, maxHeight: 600, resizable: false, title: trad_cryptogramme, show: 'fade', hide: 'fade', modal: true, draggable: false })
}

function isDateExpireOK() {
    var dTxt = date_en_texte("20/" + document.form1.select_m.value + "/20" + document.form1.select_y.value);
    document.form1.booking_expirationdate.value = document.form1.select_m.value + "/20" + document.form1.select_y.value;
    var borne = date_en_texte(dayDate);
    if ((Date.parse(dTxt)) > (Date.parse(borne)))
    { return (true) }
    else
    { return (false) }
}
function date_en_texte(madate) {
    tabmadate = madate.split("/");
    return (new Date(parseInt(tabmadate[2], 10), (parseInt(tabmadate[1], 10) - 1), parseInt(tabmadate[0], 10)));
}



function confirmer() {
    var msg_error = "";
    var nomB = document.form1.booking_bankname.value;
    var fincompte = document.form1.booking_last3numberaccount.value;
    if ((fincompte.length != 3) || (nomB == "")) { msg_error = "Tous les champs doivent être remplis!" }
    if (msg_error == "") {
        if (!auMoinsUneLettre(nomB)) {
            var m = trad_fg2e8devzv4s77gyfht6;
            $('#dialog').html(m);
            $('#dialog').dialog({ minHeight: 0, resizable: false, title: 'Erreur', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
            return;
        }
        m = trad_f3645e9s8v7z2zr4e4z1;
        $('#dialog').html(m);
        var validLabel = trad_valider;
        var cancelLabel = trad_annuler;
        var buttons = {};

        buttons[validLabel] = function () {
            $(this).dialog("close"); $('#valid').attr('value', 'ok');
            m = trad_h2r35k9e5dzddz89v71e + "<img src='https://static.secureholiday.net/static/pip/themes/theme_1/img/ellipsis.gif' alt='' />";
            $('#dialog').html(m)
            $('#dialog').dialog
                        ({
                            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: ''
                        });
            document.form1.submit()
        };

        buttons[cancelLabel] = function () {
            $(this).dialog("close");
        }
        $('#dialog').dialog
        ({
            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: buttons

        });

    }
    else {
        $('#dialog').html(msg_error);
        $('#dialog').dialog({ minHeight: 0, resizable: false, title: trad_7hcf9qf7c4cheaf18eqt, show: 'fade', hide: 'fade', modal: false, draggable: false, buttons: { "Ok": function () { $(this).dialog("close"); } } });
        //alert(msg_error);
    }
}

function cleanfields() {

    document.form1.booking_bankname.value = "";
    document.form1.booking_last3numberaccount.value = "";
}

function auMoinsUneLettre(chaineTest) {
    var retour = false;
    for (i = 0; i < chaineTest.length; i++) {
        var unChar = chaineTest.substring(i, i + 1);
        if (unChar != ' ' && (unChar < "0" || unChar > "9")) {
            retour = true;
        }
    }
    return (retour);
}



function removeErrorStyleOnDate(){
  		$("#day_birthDate").unbind("click", removeErrorStyleOnDate);
		$("#month_birthDate").unbind("click", removeErrorStyleOnDate);
		$("#year_birthDate").unbind("click", removeErrorStyleOnDate);
		$('#day_birthDate').removeClass("error").addClass("withoutError");
				$('#month_birthDate').removeClass("error").addClass("withoutError");
				$('#year_birthDate').removeClass("error").addClass("withoutError");
}
function confirmerMenuAutres() {
    if (document.form1.mode.value != "") {
        m = trad_f3645e9s8v7z2zr4e4z1;
        $('#dialog').html(m);
        var validLabel = trad_valider;
        var cancelLabel = trad_annuler;
        var buttons = {};

        buttons[validLabel] = function () {
            $(this).dialog("close"); $('#valid').attr('value', 'ok');
            m = trad_h2r35k9e5dzddz89v71e + "<img src='https://static.secureholiday.net/static/pip/themes/theme_1/img/ellipsis.gif' alt='' />";
            $('#dialog').html(m)
            $('#dialog').dialog
                        ({
                            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: ''
                        });
            document.form1.submit()
        };

        buttons[cancelLabel] = function () {
            $(this).dialog("close");
        }
        $('#dialog').dialog
        ({
            minHeight: 0, resizable: false, title: '', show: 'fade', hide: 'fade', modal: true, draggable: false, buttons: buttons

        });
    }
}

