function getExclusionText(elementId){
	for(var i=0;i<aExclusionsTexts.length;i++){
		if (aExclusionsTexts[i].id == elementId) {
			return aExclusionsTexts[i].exclusion;
		}
	}
	return null;
}

//Global variables
var gAgeCond = 0;
var gCurrentEtape = 1;
var aEtapes = new Array(0,'etape1-form','etape2-form','etape3-form','etape4-form');
var aEtapesContainers = new Array(0,'etape1','etape2','etape3','etape4');
var aEtapesNextBtns = new Array(0,'next-etape2','next-etape3','next-etape4');
var gExclusions = new Array();
var gCodePostal = 0;
var cylindree = 0;
//for quadro 
var isQuadro = false;

function appendAffiliateId(){
    var model = $('select[@name="modele"] option:selected') ? $('select[@name="modele"] option:selected').text() : false;
    var birthday = $('input[@name="birthdate"]') ? $('input[@name="birthdate"]').val().replace(/-|\//gi, '') : false;
    var lname = $('input[@name="lastname"]') ? $('input[@name="lastname"]').val() : false;
    if(model && birthday && lname){
        createAffiliateTag(model, birthday, lname);
    }
}
/*
ADD QUADRO
isQuadro
initQuadro()
initBycicle()
$()

*/
function initQuadro(){
	isQuadro = true;
	$(".for_bycicle").hide();
	$(".for_quadro").show();
	$("#homolog").show();
	$('#usage').removeOption(/./);
	$('#usage').addOption({"":getExclusionText('faites_votre_choix'),1:getExclusionText('usage_prive_trajet'),2:getExclusionText('usage_coursiers'),3:getExclusionText('usage_competition')}, false);
	$("#usage").removeAttr("disabled");
	
	$('.for_quadro input[@name="modele"]').attr("disabled",false);
	$('.for_quadro input[@name="cylindree"]').attr("disabled",false);
	$('.for_quadro input[@name="marque"]').attr("disabled",false);
	
	$('.for_bycicle input[@name="modele"]').attr("disabled",true);
	$('.for_bycicle input[@name="cylindree"]').attr("disabled",true);
	$('.for_bycicle input[@name="marque"]').attr("disabled",true);
	
	
	initTytleCalc();
	initTableCalc();
}
function initBycicle(){
	isQuadro = false;
	$(".for_bycicle").show();
	$(".for_quadro").hide();
	$("#homolog").hide();
	if($('input[@name="type_veh"]:checked').val() == 1){
		$("#immat").hide();
	}
	$("#usage").attr("disabled",true);
	$("#gcp_question").hide();

	$('.for_quadro input[@name="modele"]').attr("disabled",true);
	$('.for_quadro input[@name="cylindree"]').attr("disabled",true);
	$('.for_quadro input[@name="marque"]').attr("disabled",true);
	
//	$('.for_bycicle input[@name="modele"]').attr("disabled",true);
//	$('.for_bycicle input[@name="cylindree"]').attr("disabled",true);
//	$('.for_bycicle input[@name="marque"]').attr("disabled",true);

	initTytleCalc();
	initTableCalc();
}
function initTableCalc()
{
	$('#ratetab tr').each(function(i){
			if(isQuadro){
				if(i == 3){
					$(this).removeClass('odd');
				}
				if(i == 4){
					$(this).addClass('odd');
				}
			}else{
				if(i == 3){
					$(this).addClass('odd');
				}
				if(i == 4){
					$(this).removeClass('odd');
				}
			}
	});
}
function initTytleCalc()
{
	if(isQuadro){
		var pre = 'quadro_';
	}else{
		var pre = '';
	}
	$('#ratetab .plan').each(function(i){
		$(this).removeAttr('title');
		$(this).removeAttr('tooltip');
		$(this).attr('title',getExclusionText(pre + 'f' + (i+1) + '_text'));
	});
}
function resetQuadro(){
	$('body').mousemove(function(){
		if(isQuadro && $('input[@name="type_veh"]:checked').val() != 2){
			$('#type_veh2').attr('checked',true);
	}
	$("#usage").removeAttr("disabled");
});}
function franchiseQuadro(){
	if(!isQuadro){
		return;
	}
	$.getJSON(home_folder+"estimation/index/loadoptions/fr/list/quadro_franchise/",null, function(j){
		$("#quadro_franchise").html(j.data);
	});
}
function optQuadro(){
	if(!isQuadro){
		return;
	}
	$.getJSON(home_folder+"estimation/index/loadoptions/fr/list/quadro_opt/",null, function(j){ 
		for(i=1;i<=5;i++){
			if(j[i][0]){
				$("#quadro_opt_" + i).attr('disabled',false);
			}else{
				$("#quadro_opt_" + i).attr('disabled',true);
			}
			if(j[i][1]){
				$("#quadro_opt_" + i).attr('checked',true);
			}else{
				$("#quadro_opt_" + i).attr('checked',false);
			}
		}
	});
}
$(function(){
    switch ($('input[@name="type_veh"]:checked').val()){
		case '2':
			initQuadro();
			break;
		case '1':
		case '0':
			marque();
		default:
			initBycicle();
	}


	$('input[@name="type_veh"]').click(function(e){
		if($('input[@name="type_veh"]:checked').val() == 2){
			initQuadro();
		}else{ 
			initBycicle();
			marque();
		}
    });

	/*$('#etape1-form :input, #etape2-form :input, #etape3-form :input').change(function (){
  	checkEtapeFilled();
  });*/
    $('table#ratetab label').click(function() {
        $('#'+$(this).attr('for')).attr('checked', true);
    });

	/*==========================*/
	/* Validate radiobuttons
	/*==========================*/
	$("input.exclusion").click(function(e){			
			var exclusion = getExclusionText(this.id);
			if(exclusion && $(this).val() == 0){
				alert(exclusion);
				addExclusion(this.id);
			}else{
				removeExclusion(this.id);
			}
			checkExclusions();
	});

	$("input.exclusion_oui").click(function(e){			
			var exclusion = getExclusionText(this.id);
			if(exclusion && $(this).val() == 1){
				alert(exclusion);
				addExclusion(this.id);
			}else{
				removeExclusion(this.id);
			}
			checkExclusions();
	});

    
    function marque() {
        $('#cylindree').val(0);
        $('#modele').val(0);
	    $('#cylindree').attr('disabled',true);
        $('#modele').attr('disabled',true);
        $.getJSON(home_folder+"estimation/index/loadoptions/fr/list/marque/",{type_veh: $('input[@name="type_veh"]:checked').val()}, function(j){
        	var $dest = $('#marque');
            if (j.length > 0) {

                  var options = '<option value="">'+getExclusionText('choisissez_marque')+'</option>';
                  for (var i = 0; i < j.length; i++) {

                     options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';

                  }

               }
								
               if(options){
	               $dest.removeAttr('disabled');
	               $dest.html(options);
	               $dest.find('option:first');
	               $dest.attr('selected', 'selected');
               }

            });
    }
	
	$('#marque').change(function(e){
	    $("#usage").attr("disabled","true");
		$("#modele > option[@value='']").attr("selected","true");
		$("#modele").attr("disabled","true");
	});
	
	$('#modele').change(function(e){
	    prive = {"":getExclusionText('faites_votre_choix'),0:getExclusionText('usage_prive_trajet'),2:getExclusionText('usage_coursiers')};
        enduro = {"":getExclusionText('faites_votre_choix'),0:getExclusionText('usage_prive'),2:getExclusionText('usage_coursiers')};
        classicNo = {"":getExclusionText('faites_votre_choix'),0:getExclusionText('usage_prive_trajet'),1:getExclusionText('usage_affaires'),2:getExclusionText('usage_coursiers')};
        classicYes = {"":getExclusionText('faites_votre_choix'),1:getExclusionText('usage_affaires'),2:getExclusionText('usage_coursiers')};
    $.getJSON(home_folder+"estimation/index/loadoptions/fr/list/ant/",{modele: $(this).val()}, function(data) {
          $('#code_ant').val(data['code_ant']);
          $('#bike_type').val(data['bike_type']);
          if (data['bike_type'] == 2) {
              $('#homolog').removeClass('hidden');
			  $('#homolog').show();
              $('#immat').addClass('hidden');
             $('#usage').removeOption(/./);
             $('#usage').addOption(enduro, false);
          }
          if (data['bike_type'] == 1) {
              $('#homolog').addClass('hidden');
              $('#immat').removeClass('hidden');
             $('#usage').removeOption(/./);
             $('#usage').addOption(prive, false);
          }
          if (data['bike_type'] == 3) {
              $('#homolog').addClass('hidden');
              $('#immat').addClass('hidden');
             $('#usage').removeOption(/./);
             $('#usage').addOption(classicNo, false);
          }
          
          $('#usage').attr('disabled',false);
            $('input[@name="cgs"]').attr('disabled',false);
    });
	});
	
	$("#homolog0").click(function(){
       if(!isQuadro){
			alert(getExclusionText('homolog'));
	   }
	});
	
	$('#immat0').click(function(){
       alert(getExclusionText('immat'));
	});

	$("#tcg0").click(function(){
	   alert(getExclusionText('tcg'));
	});
		
	$("#cgf0").click(function(){
	   alert(getExclusionText('cgf'));
    });
		
	$('#cylindree').change(function(){
		if(gCurrentEtape > 1){
			var typePermiss = $('#type_permis').val();
			var cylindree = 0;
	        $("#cylindree option:selected").each(function(){
    		  cylindree = $(this).text();  	
            });
//			validateAgeCondCylindree(cylindree);
//			validateTypePermiss(cylindree,typePermiss);
			checkExclusions();
		}
	});
	
	$("input[@name='cgs']").each(function(){
	$(this).click(function(){
		if($("input[@name='cgs']:checked").val() == 1){
		    if ($('#bike_type').val() == 1 || $('#bike_type').val() == 2) {
		        alert(getExclusionText('question_error'));
		        addExclusion('gcp');
		        $('#gcp_question').hide();
                $('#usage').removeOption(/./);
		    } else {
			    $('#gcp_question').show();
			    $('#usage').removeOption(/./);
                $('#usage').addOption(classicYes, false);
		    }
		}else{
			$('#gcp_question').hide();
			$("input[@name='gcp']").each(function(){
				$(this).attr('checked',false);
			});
			$('#usage').removeOption(/./);
            $('#usage').addOption(classicNo, false);
			removeExclusion('gcp');
		}
		$('#usage').val(1);
		checkExclusions();
	});
	});
	
	$('#code_postal').change(function(){
	  if(!$(this).val().match("_") && gCodePostal != $(this).val()){
			validateCodePostal();
	  }
	});

	$("#gcp0").click(function(){
	   if($("input[@name='gcp']:checked").val() == 0){
	       alert(getExclusionText('gcp_exclusion'));
		   addExclusion('gcp');
	   } else {
	       removeExclusion('gcp');
	   }
	});

	
	
	//Validate usage selectbox
	// Correct "Usage" depending on motorcycle type / #3776
	//Estimate step 1: usage for Enduro motorcycles wrong in IE / #3954
	$("#usage").change(function(e){
		var exclusion = getExclusionText(this.id);
		//for quadro
		if(isQuadro){
			if($(this).val() != 1){
				alert(exclusion);
			    addExclusion(this.id);	
			}else{
				removeExclusion(this.id); 
			}
			checkExclusions();
			return;
		}
		//for bycicle
		if ($(this).val() == 2) {
		    alert(exclusion);
			addExclusion(this.id);
		} else if ($('#bike_type').val() < 3 && $(this).val() == 1) {
            alert(exclusion);
			addExclusion(this.id);
        } else if ($('#bike_type').val() == 3) {
            if ($('input[@name="cgs"]:checked').val() == 1 && $(this).val() == 0) {
                alert(exclusion);
			    addExclusion(this.id);
            } else {
                removeExclusion(this.id);
            }
		} else {
		   removeExclusion(this.id); 
		}
		checkExclusions();
	});
	
	//Validate titre selectbox
	$("#titre").change(function(e){
		if($(this).val() > 0){
		  $("#femme").val(1);
		}
	});
	
	//Validate lastname
	$("#lastname").blur(function(){
	  var exclusion = getExclusionText(this.id);
	  if ($("#lastname").val().length > 40) {
      var reg = /^([A-Za-z_\-\'\`])$/;
      if(reg.test($("#lastname").val()) == false) {
        var exclusion = getExclusionText('deny_symbols');
	    }
	    alert(exclusion);
			addExclusion(this.id);
		}else{
			removeExclusion(this.id);
		}
		checkExclusions();
	});
	
	//Validate firstname
	$("#firstname").blur(function(){
	  var exclusion = getExclusionText(this.id);
	  if ($("#firstname").val().length > 40) {
	  var reg = /^([A-Za-z_\-\'\`])$/;
      if(reg.test($("#firstname").val()) == false) {
        var exclusion = getExclusionText('deny_symbols');
	    }
	    alert(exclusion);
	  	addExclusion(this.id);
		}else{
			removeExclusion(this.id);
		}
		checkExclusions();
	});
	
	//Validate email
	$("#email").blur(function(){
	    var exclusion = getExclusionText(this.id);
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(reg.test($("#email").val()) == false || $('#email').val() == '') {
            alert(exclusion);
           	addExclusion(this.id);
		}else{
    		removeExclusion(this.id);
		}
		checkExclusions();
	});
	
	//Validate type_permis
	$("#type_permis").change(function(e){
		birthdate = $('#birthdate').val();
		if (birthdate == false) {
		  alert(getExclusionText('birthdate'));
		  $('#birthdate').focus();
		  $('#type_permis').val(0);
			addExclusion(this.id);
		}else{
			removeExclusion(this.id);
		}
		
		$("#cylindree option:selected").each(function () {
        cylindree = $(this).text();
		});
		
		var typePermiss = $('#type_permis').val();
		
//		if (typePermiss == 'b' && $('#age_permis').val() < 2) {
//		    alert(getExclusionText('exclusion_type'));
//	        addExclusion('typePermiss');
//		}
//		if (typePermiss == 'a'){
//		    var result = gAgeCond - $('#age_permis').val();
//		    if (result < 21 && $('#bridee').val() == 0 ) {
//		        alert(getExclusionText('exclusion_type'));
//	            addExclusion('typePermiss');
//		    }
//		}

        validateBridee(typePermiss, $('#age_permis').val());
		validateTypePermiss(cylindree,typePermiss);
		checkExclusions();
	});
	
	$('input[@name="bridee"]').click(function(e){
	   if ($(this).val() == 0) {
           alert(getExclusionText('bridee'));
           addExclusion("bridee");
	   } else {
	       removeExclusion("bridee");
	   }
	   checkExclusions();
	});
	
	//multicheck
	$('#multicheck').click(function(e) {
		if ($('#multicheck').val() == 0) {
		  var age = gAgeCond;
		  var code = $('#code_ant').val();
		  if (age >= 18 && age <= 29 && code == 2) {
		    alert(getExclusionText('multicheck18'));
		    addExclusion(this.id);
		  }else if (age >= 23 && code == 3) {
		    alert(getExclusionText('multicheck23'));
		    addExclusion(this.id);
		  }else{
		  	removeExclusion(this.id);
		  }
		  checkExclusions();
		}
	});
	
	//pour_une_auto
	$("input[@name='auto']").click(function(){
//show allwais
//		if ($(this).val() == 1) {
//		  $('#majoration_auto').removeClass('hidden');
//	 	}else{
//	 	  $('#majoration_auto').addClass('hidden');
//	 	}
	});
	
	$('#sin_resp_auto').change(function(e) {
		volMoto();
	});
	$('#sin_nonresp_auto').change(function(e) {
		volMoto();
	});
	
	$('#sin_resp_moto').change(function(e) {
		volMoto();
	});
	$('#sin_nonresp_moto').change(function(e) {
		volMoto();
	});
	//vol_moto
	$('#vol_moto').change(function(e) {
		volMoto();
	});
	
	function volMoto(e) {
	    removeExclusion(this.id);
		if (gAgeCond < 23) {
		    if ((Number($('#sin_nonresp_auto').val()) + Number($('#sin_nonresp_moto').val()) + Number($('#vol_moto').val())) > 1){
                alert(getExclusionText('vol_moto'));
                addExclusion(this.id); 
		    } else if ((Number($('#sin_resp_auto').val()) + Number($('#sin_resp_moto').val())) > 0) {
                alert(getExclusionText('vol_moto'));
                addExclusion(this.id);
            } else {
                removeExclusion(this.id);
            }
		} else if (gAgeCond >= 23) {
            if ((Number($('#sin_resp_auto').val()) + Number($('#sin_resp_moto').val()) + Number($('#sin_nonresp_auto').val()) + Number($('#sin_nonresp_moto').val()) + Number($('#vol_moto').val())) > 3 ||
                (Number($('#sin_resp_auto').val()) + Number($('#sin_resp_moto').val())) > 1 ||
                (Number($('#sin_resp_moto').val()) + Number($('#sin_nonresp_moto').val()) + Number($('#vol_moto').val())) > 2) {
                    alert(getExclusionText('vol_moto'));
                    addExclusion(this.id);
            } else {
                removeExclusion(this.id);
            }
		}
        checkExclusions();
	}
	
	/*==========================================*/
	/* JQuery calendar section & masked inputs
	/*==========================================*/
	
	$.datepicker.setDefaults({ showOn: 'button', buttonImage: home_folder+'img/calendar.gif', buttonImageOnly: true, dateFormat: 'dd/mm/yy' });
	$('#date_mc').datepicker({ maxDate: 0, minDate: '-40y', onSelect: function(){$(this).focus();}});
    $('#date_mc').mask("99/99/9999");
  
    $('#date_obtention').mask("99/99/9999", {completed:validateObtention});
    $('#birthdate').mask("99/99/9999", {completed:validateBirthDate});
  
    $('#code_postal').mask("99999",{completed:validateCodePostal});
    $('#birthdate').datepicker({maxDate: '-14y', onSelect:validateBirthDate});
    $('#date_obtention').datepicker({onSelect:validateObtention,maxDate: +0});
    
  /*==========================*/
	/* Next etape button
	/*==========================*/
	$('#next-etape2').click(function(e) {
		
		validateEtape(1,$(this));
        $('#type_permis').attr('disabled',true);
    	//alert(5);
        $('#usage').attr('disabled',true);
        $('#date_obtention').datepicker('disable');
		
		//$('#etape1-form').submit();
        //$('#etape2').removeClass('hidden');
	});
	
	$('#next-etape3').click(function(e) {
//		validateEtape(1,$(this));
        validateEtape(2,$(this)); 
		$.getJSON(home_folder+"estimation/index/loadoptions/fr/list/gener-login/",function(j){	
			$('#fLogin').val(j.login);
		});
		//$('#etape3').removeClass('hidden');
	});
	
	$('#dune_suspension1').click(function(){
	   alert(getExclusionText('cours_des_36_exclusion'));
	});
	$('#dune_annulation1').click(function(){
	   alert(getExclusionText('cours_des_36_exclusion'));
	});
	$('#dune_resiliation1').click(function(){
	    alert(getExclusionText('cours_des_36_exclusion'));
	});
	$('#dune_nonpayment1').click(function(){
		if($("#crm").val() > 95) {
			alert(getExclusionText('cours_des_36_exclusion'));
		}
	});
	$('#dune_condamnation1').click(function(){
	   alert(getExclusionText('cours_des_36_exclusion'));
	});
	$('#dune_condamnation_two1').click(function(){
	   alert(getExclusionText('cours_des_36_exclusion'));
	});
	
	
	$('#next-etape4').click(function(e) {
		validateEtape(3,$(this));
		cylindree = $('#cylindree option:selected').text();
		
		$('#opt_1').attr('checked', !isQuadro);
		$('#assistance_text').show();
		
		if ($('#vol_moto').val() == 2) {
		    $('#franchise_vol').addClass('hidden');
		    $('#franchise_dommage').addClass('hidden');
		    $('#protections').addClass('hidden');
		} else {
	
            if (cylindree < 50) {
                $('#franchise_dommage').addClass('hidden');
                if ($('#vol_moto').val() == 0) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_50_0'));
//                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
//                    getExclusionText('franchise_dommage_50'));
                } else if ($('#vol_moto').val() == 1) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_50_1'));
//                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
//                    getExclusionText('franchise_dommage_50'));
                }
            } else if (cylindree <= 125) {
                if ($('#vol_moto').val() == 0) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_125_0'));
                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
                    getExclusionText('franchise_dommage_125'));
                } else if ($('#vol_moto').val() == 1) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_125_1'));
                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
                    getExclusionText('franchise_dommage_125'));
                }
            } else if (cylindree > 125) {
                if ($('#vol_moto').val() == 0) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_150_0'));
                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
                    getExclusionText('franchise_dommage_150'));
                } else if ($('#vol_moto').val() == 1) {
                    $('#franchise_vol').html('<strong>'+getExclusionText('franchise_vol')+'</strong> '+
                    getExclusionText('franchise_vol_150_1'));
                    $('#franchise_dommage').html('<strong>'+getExclusionText('franchise_dommage')+'</strong> '+
                    getExclusionText('franchise_dommage_150'));
                }
            }
        }
	});
	
	$('#opt_3').click(function(){
		$('#opt_4').removeAttr('checked');
	});
  
	$('#opt_4').click(function(){
		$('#opt_3').removeAttr('checked');
	});
  
    $('#opt_5').click(function(){
 		$('#opt_6').removeAttr('checked');
 	});

	$('#opt_6').click(function(){
 		$('#opt_5').removeAttr('checked');
 	});
	
 	if ($('#opt_3').attr('checked') == false &&
 	    $('#opt_4').attr('checked') == false &&
 	    $('#opt_5').attr('checked') == false &&
 	    $('#opt_6').attr('checked') == false) {
 	    ;
 	}
 	
	$('input[@name="quadro_opt[]"]').click(function(e){
		optChecking();
	});
	
	$('input[@name="opt[]"]').click(function(e){
	    if ($(this).val() == 1) {
	       if ($(this).attr('checked') == true) {
    	        $('#assistance_text').removeClass('hidden');
	       } else {
	            $('#assistance_text').addClass('hidden');
	       }
	    }
	    
	    if ($(this).val() == 2) {
	       if ($(this).attr('checked') == true) {
    	        $('#individuelle_text').removeClass('hidden');
	       } else {
	            $('#individuelle_text').addClass('hidden');
	       }
	    }
	    
	    if ($(this).val() == 3) {
	       if ($(this).attr('checked') == true) {
    	        $('#accessoires_text').removeClass('hidden');
    	        $('#accessoires_plus_text').addClass('hidden');
    	        $('#franchise_garantie').show();
	       } else {
	            $('#accessoires_text').addClass('hidden');
	            if ($('#opt_4').attr('checked') != true && $('#opt_5').attr('checked') != true && $('#opt_6').attr('checked') != true) {
	               $('#franchise_garantie').hide();
 	            }
	       }
	    }
	    
	    if ($(this).val() == 4) {
	       if ($(this).attr('checked') == true) {
    	        $('#accessoires_plus_text').removeClass('hidden');
    	        $('#accessoires_text').addClass('hidden');
    	        $('#franchise_garantie').show();
	       } else {
	            $('#accessoires_plus_text').addClass('hidden');
	            if ($('#opt_3').attr('checked') != true && $('#opt_5').attr('checked') != true && $('#opt_6').attr('checked') != true) {
	               $('#franchise_garantie').hide();
 	            }
	       }
	    }
	    
	    if ($(this).val() == 5) {
	       if ($(this).attr('checked') == true) {
    	        $('#equipment_text').removeClass('hidden');
    	        $('#equipment_plus_text').addClass('hidden');
    	        $('#franchise_garantie').show();
	       } else {
	            $('#equipment_text').addClass('hidden');
	            if ($('#opt_3').attr('checked') != true && $('#opt_4').attr('checked') != true && $('#opt_6').attr('checked') != true) {
	               $('#franchise_garantie').hide();
 	            }
	       }
	    }
	    
	    if ($(this).val() == 6) {
	       if ($(this).attr('checked') == true) {
    	        $('#equipment_plus_text').removeClass('hidden');
    	        $('#equipment_text').addClass('hidden');
    	        $('#franchise_garantie').show();
	       } else {
	            $('#equipment_plus_text').addClass('hidden');
	            if ($('#opt_3').attr('checked') != true && $('#opt_4').attr('checked') != true && $('#opt_5').attr('checked') != true) {
	               $('#franchise_garantie').hide();
 	            }
	       }
	    }
	    
	    cylindree = $('#cylindree option:selected').text();
	    
	    if ($(this).val() > 2) {
	        if (cylindree <= 125) {
	           $('#franchise_accessoires').html('<strong>'+getExclusionText('franchise_accessoires')+'</strong><br/>'+
	           getExclusionText('franchise_text_ae_125'));
	        } else {
	           $('#franchise_accessoires').html('<strong>'+getExclusionText('franchise_accessoires')+'</strong><br/>'+
	           getExclusionText('franchise_text_ae_150'));
	        }
	    }
	    
	    optChecking();
	});
	
	$('input[@name="plan"]').click(function(e) {
	  number = $(this).val();
	  $('td').removeClass('plan_color');
	  $('#td_'+number).addClass('plan_color');
	});
	
	/**********************
	/* Etape 4 buttons
	/**********************/
	$('#button_save').click(function(e){
	    resetEtape(1);
		resetEtape(2);
		resetEtape(3);
		resetEtape(4);
		$('#etape1-form input').attr('disabled', false);
		$('#etape1-form select').attr('disabled', false);
		$('#etape2-form input').attr('disabled', false);
		$('#etape2-form select').attr('disabled', false);
		$('#etape3-form input').attr('disabled', false);
		$('#etape3-form select').attr('disabled', false);
		$('input[@name="opt[]"]').attr('checked', false);
		$('#type_permis').attr('disabled', true);
		$('#date_mc').datepicker('enable');
		$('#birthdate').datepicker('enable');
		$('table#ratetab label').removeClass();
		window.location.reload();
	});

	$('#button_done').click(function(e){
//		validateEtape(1,$(this));
//      validateEtape(2,$(this));
//		validateEtape(3,$(this));
	
		if ($('#plan').val() == '') {
		    alert(getExclusionText('empty_plan'));
		    return;
		}
		
		//$('#accept').attr('disabled',true);
		var options = {
			url: home_folder+'estimation/index/accept/fr' + partner_url,
			dataType: 'json',
			type: 'post',
			success: function(j){
				$('#accept').attr('disabled',false);

			    if(j == 0){
					alert(getExclusionText('estimation_save'));
					location.href = home_folder+'member/index/index';
				}
				if(j.length == 1){
		  			if(j[0].code == 0){
						alert(getExclusionText('estimation_save'));
		  			} else if (j[0].code == 2) {
		  			    if(partner_url == '') {
		  			    	alert(getExclusionText('estimation_save'));
		  			    }
						location.href = home_folder+'sale/index/index/fr/estimate_id/'+j[0].id + partner_url;
		  			} else {
		  				alert(j[0].error);
		  			}
	  		    } else if(j.length > 1) {
		  			for(var i=0;i<j.length;i++){
		  				alert(j[i].error);
		  			}
	  		    }
			}
		};
		$("#"+aEtapes[4]).ajaxSubmit(options);
	});
	
	$('#button_pdf').click(function(e){ 
	    $('#button_pdf').attr('disabled',true);
		if ($('input[@name="plan"]:checked').attr('disabled') === true) {
		    alert(getExclusionText('empty_plan'));
		    $('#button_pdf').attr('disabled',false);
		} else {
		    
	        // @begin :: set img to footer if user comes from affiliate systems
	        //appendAffiliateId();
	        // @end :: set img to footer if user comes from affiliate systems
		
	        
	      var options = {
		    dataType: 'json',
			url: home_folder+'estimation/index/loadoptions/fr/list/pdf' + partner_url,
			success: function(j){
				if(j.code==0){
  			       $('#button_pdf').attr('disabled',false);
				   window.open(j.path);
			    }else{
				   alert(j.error);
				   $('#button_pdf').attr('disabled',false);
			    }
			}
		  };
		  $("#"+aEtapes[4]).ajaxSubmit(options);
		}
	});
	
	$('#button_mail').click(function(e){
	    $('#button_mail').attr('disabled',true);
	    if ($('input[@name="plan"]:checked').attr('disabled') === true) {
	        alert(getExclusionText('empty_plan'));
	        $('#button_mail').attr('disabled',false);
	    } else {
	        // @begin :: set img to footer if user comes from affiliate systems
	        //appendAffiliateId();
	        // @end :: set img to footer if user comes from affiliate systems
	        
		    var options = {
		    dataType: 'text',
			url: home_folder+'estimation/index/loadoptions/fr/list/send/',
			success: function(j){
               var arr = j.split('<br />');
			   j = eval('('+arr[0]+')');
               alert(j.error);
    		   $('#button_mail').attr('disabled',false);
			}
		  };
		  $("#"+aEtapes[4]).ajaxSubmit(options);
	    }
	});
	
	/*==========================*/
	/* Restart buttons
	/*==========================*/
	$('#restart-etape1').click(function(e){
		resetEtape(1);
		resetEtape(2);
		resetEtape(3);
		resetEtape(4);
		$('#etape2-form input').attr('disabled', false);
		$('#etape2-form select').attr('disabled', false);
		$('#etape3-form input').attr('disabled', false);
		$('#etape3-form select').attr('disabled', false);
		$('input[@name="opt[]"]').attr('checked', false);
		$('#type_permis').attr('disabled', true);
		$('#date_mc').datepicker('enable');
		$('#birthdate').datepicker('enable');
		$('table#ratetab label').removeClass();
		resetQuadro();
	});
	$('#restart-etape2').click(function(e){
		resetEtape(2);
		resetEtape(3);
		resetEtape(4);
		$('#etape2-form input').attr('disabled', false);
		$('#etape2-form select').attr('disabled', false);
		$('#etape3-form input').attr('disabled', false);
		$('#etape3-form select').attr('disabled', false);
		$('input[@name="opt[]"]').attr('checked', false);
		$('#type_permis').attr('disabled', true);
		$('#birthdate').datepicker('enable');
		$('table#ratetab label').removeClass();
		$('#date_obtention').datepicker('disable');

		$('#bridee_li').addClass('hidden');
  	    removeExclusion('bridee');
	});
	
	$('#restart-etape3').click(function(e){
		resetEtape(3);
		resetEtape(4);
		$('#etape3-form input').attr('disabled', false);
		$('#etape3-form select').attr('disabled', false);
		$('input[@name="opt[]"]').attr('checked', false);
		$('table#ratetab label').removeClass();
	});

	/*======================*/
	/* login user
	/*======================*/
	$('#create_new_user').click(function(e){
		if ($('#create_new_user').attr('checked') == true) {
			$('#new_user').removeClass('hidden');
			$('#old_user').addClass('hidden');
		} else {
			$('#new_user').addClass('hidden');
			$('#old_user').removeClass('hidden');
		}
	});

});

function resetEtape(etapeId){
	$('#'+aEtapes[etapeId]).resetForm();
	switch(etapeId){
		case 1:{
		    $('#etape1-form input').attr('disabled', false);
		    $('#etape1-form select').attr('disabled', false);
			$('#cylindree').attr('disabled',true);
			$('#modele').attr('disabled',true);
			$('#commune').attr('disabled',true);
			$('#usage').attr('disabled', true);
			$('#marque').attr('disabled', true);
			$('#gcp_question').addClass('hidden');
			$('#homolog').addClass('hidden');
			$('#immat').addClass('hidden');
			$('input[@name="type_veh"]:checked').attr('disabled', false);
			$('input[@name="type_veh"]:checked').click();
			resetEtape(2);
			resetEtape(3);
			$('#'+aEtapesContainers[2]).hide();
			break;			
		}
		case 2:{
			$('input[@name="bridee"]').attr('disabled',true);
			if(gCurrentEtape == 3){
				gCurrentEtape = 2;
			}
			resetEtape(3);
			$('#'+aEtapesContainers[3]).hide();
		}
		case 3:{
			$('#'+aEtapesContainers[4]).hide();
		}
	}
}

function validateEtape(etapeId,button){
	button.attr('disabled',true);
		var options = {
			dataType: 'json',
			type: 'post',
			success: function(j){
				button.attr('disabled',false);
				if(j.length == 1){
	  			  if(j[0].code == 0){
	  				$('#'+aEtapesContainers[etapeId+1]).removeClass('hidden').show();
	  				gCurrentEtape = etapeId+1;
	  				//scrolling
	  				try {
	  					$(document).scrollTo($('#'+aEtapesContainers[gCurrentEtape]).offset().top , 500);
	  				}catch (e) {
	  					try{
	  					$(parent.frames[0]).scrollTo($('#'+aEtapesContainers[gCurrentEtape]).offset().top , 500);
	  					}catch(e){}
	  				}

	  				$('#'+aEtapesContainers[etapeId]+'-form input').attr('disabled', true);
	       	        $('#'+aEtapesContainers[etapeId]+'-form select').attr('disabled', true);
	       	        if (etapeId == 1) {
	       	            $('#date_mc').datepicker('disable');
	       	        } else if (etapeId == 2) {
	       	            $('#birthdate').datepicker('disable');
		                $('#date_obtention').datepicker('disable');
	       	        } else if (etapeId == 3) {
						optChecking();
						appendAffiliateId();
	       	        }
	  			  }else if (j[0].code == 1){
	  				if (etapeId==1) {
	  			        $('#usage').attr('disabled',false);
	  				}
	  				alert(j[0].error);
	  			  }else if (j[0].code == 2){
	  			    validateEtape(etapeId,button);
	  			  }
	  		   }else if(j.length > 1){
	  				if (etapeId==1) {
	  			        $('#usage').attr('disabled',false);
	  				}
	  			  for(var i=0;i<j.length;i++){
	  				alert(j[i].error);
	  			  }
	  		   }
			}
		};
		$("#"+aEtapes[etapeId]).ajaxSubmit(options);
}

/**
/* Function disables current etape next button if form is not filled fully
**/
function checkEtapeFilled(){
	var form = aEtapes[gCurrentEtape];
	var isFilled = true;
	$('#'+form+' :input').each(function(){
			 $$ = $(this);
			 if($$.attr('type') != 'button' && $$.attr('type') != 'hidden'){
			 	if(!$$.val()){
			 		isFilled = false;
			 	}
			 }
	});
	
	if(isFilled){
		 $('#'+aEtapesNextBtns[gCurrentEtape]).attr('disabled',false);
	}else{
		 $('#'+aEtapesNextBtns[gCurrentEtape]).attr('disabled',true);
	}
	return isFilled;
}

function optChecking() {
	    var options = {
			dataType: 'json',
			beforeSubmit: function(){ 
				if(isQuadro){
					$('input[@name="quadro_opt[]"]').attr('disabled',true);
				} 
				$('input[@name="opt[]"]').attr('disabled',true);},
			success: function(j){
				if(j.code == 0){
					$('input[@name="plan"]').removeAttr('disabled');
					for(var i=0;i<j.summ.length;i++){
						for(var k=0;k<j.summ[i].length;k++){
						  if (j.summ[i][k] != 0) {
						    $('#f'+(i+1)+'-summ'+(k+1)).html(j.summ[i][k] + '&nbsp;');
						  } else {
						    $('#plan_'+(i+1)+(k+1)).attr('disabled', true);
							$('#f'+(i+1)+'-summ'+(k+1)).html('---');
						  }
						}
					}
					optQuadro();
					franchiseQuadro();
				}else{
					alert(j.error);
					$('#etape4"').hide();
		            resetEtape(3);
		            resetEtape(2);
		            resetEtape(1);
		            $('#etape2-form input').attr('disabled', false);
		            $('#etape2-form select').attr('disabled', false);
		            $('#etape3-form input').attr('disabled', false);
		            $('#etape3-form select').attr('disabled', false);
		            $('input[@name="opt[]"]').attr('checked', false);
		            $('#type_permis').attr('disabled', true);
		            $('#date_mc').datepicker('enable');
		            $('#birthdate').datepicker('enable');
//		            $('table#ratetab label').removeClass();
//					window.location.reload();
				}
				$('input[@name="plan"]').each(function(){
					$(this).removeAttr('checked');
					var number = $(this).val();
					$('#td_'+number).removeClass('plan_color');
				});
				
				$('table#ratetab label').removeClass();
				
				if ($('#bike_type').val() == 3 && $('#vol_moto').val() < 2) {
				    $('input[@name="opt[]"]').attr('disabled',false);
				} else {
				   $('#opt_1').attr('disabled',false); 
				   $('#opt_2').attr('disabled',false); 
				}
			}
		};
		
		$("#"+aEtapes[4]).ajaxSubmit(options);
        $("#"+aEtapes[4]).ajaxError(function(event, request, settings){
            alert(getExclusionText('ajax_error'));
        });
	}

/*=============================*/
/* Validation functions
/*=============================*/
function validateTypePermiss(cylindree, typePermiss){
      removeExclusion('typePermiss');

      var date = birthdate.split('/');
      if (typePermiss == 'Aucun' && Number(date[2]) >= 1988) {
          alert(getExclusionText('aucun_exclusion'))
          addExclusion('typePermiss');
      }
		
      var agePermiss = Number(gAgeCond) - Number($('#age_permis').val());
	  if (agePermiss >= 14 && agePermiss < 16) {
	      if (typePermiss != 'bsr' || cylindree > 50) {
	          alert(getExclusionText('exclusion_type'));
              addExclusion('typePermiss');
	      }
	  }
	  if (agePermiss >= 16 && agePermiss < 18) {
	      if (typePermiss != 'al' && typePermiss != 'bsr') {
	          alert(getExclusionText('exclusion_type'));
              addExclusion('typePermiss');
	      }
	      if ((typePermiss == 'bsr' && cylindree > 50) || cylindree > 125) {
	          alert(getExclusionText('exclusion_type'));
              addExclusion('typePermiss');
	      }
	  }
	  if (agePermiss >= 18) {
	      if (cylindree > 125 && typePermiss != 'a' && typePermiss != 'b') {
	          alert(getExclusionText('exclusion_type_permis'));
              addExclusion('typePermiss');
	      }
	      if (typePermiss == 'bsr' && cylindree > 50) {
	          alert(getExclusionText('exclusion_type_permis'));
              addExclusion('typePermiss');
	      }
	      if (typePermiss == 'b') {
	          if (cylindree <= 125 && cylindree > 50) {
	              if (gAgeCond < 20 || $('#age_permis').val() < 2) {
                      alert(getExclusionText('exclusion_type_b'));
                      addExclusion('typePermiss');
	              }
	          } else if (cylindree > 125 && $('#modele option:selected').val()!=3682) {
	              alert(getExclusionText('exclusion_type_b'));
                  addExclusion('typePermiss');
	          }
          }
	  }
	  checkExclusions();
}

function validateBridee(typePermiss, agePermiss){
	  if (typePermiss == 'a') {
        var cylindree = 0;
	    $("#cylindree option:selected").each(function(){
	       cylindree = $(this).text();  	
	    });
	    if (gAgeCond < 21 && cylindree > 125) {
	       $('#bridee_li').removeClass('hidden');
	    } else {
	        $('#bridee_li').addClass('hidden');
	  	    removeExclusion('bridee');
	    }
	  }else{
	  	$('#bridee_li').addClass('hidden');
	  	removeExclusion('bridee');
	  }
	  checkExclusions();
}

function validateAgeCondCylindree(cylindree){
	removeExclusion('age_cond16c');
	removeExclusion('age_cond16');
    if (gAgeCond < 14) {
        alert(getExclusionText('age_cond16'));
        addExclusion('age_cond16');
    }
    if (gAgeCond >= 14 && gAgeCond < 16 && cylindree > 50) {
        alert(getExclusionText('age_cond16'));
        addExclusion('age_cond16');
    }
    if (gAgeCond >= 16 && gAgeCond < 18 && cylindree > 125) {
        alert(getExclusionText('age_cond16c'));
        addExclusion('age_cond16c');
    } 
}

function validateObtention(){
    var date = $('#date_obtention').val();
    $.ajax({
        type: "POST",
	    url: home_folder+"estimation/index/loadoptions/fr/list/birthdate/",
	    data: "birthdate="+date,
	    success: function(data) {
	        var cylindree = 0;
	        if (Number(data) < 0) {
	            alert(getExclusionText('date_obtention_incorrect'));
	            addExclusion('typePermiss');
	        }else {
			$('#age_permis').val(data);
	        
	        $("#cylindree option:selected").each(function(){
	           cylindree = $(this).text();  	
	        });
	        
	        var age = gAgeCond;
	        var agePermiss = Number(gAgeCond) - Number(data);
	        
	        if ($('input[@name="type_veh"]:checked').val() == 0) {
	           var type = {0:getExclusionText('select_type'),'a':'A','b':'B','al':'AL','bsr':'BSR', 'Aucun':'Aucun'};
	        } else {
	           var type = {0:getExclusionText('select_type'),'a':'A','b':'B','al':'AL','bsr':'BSR'};
	        }
	        
	        if (agePermiss >= 14) {
			  if (age > 75) {
			    alert(getExclusionText('driver_age_75'));
                addExclusion('typePermiss');
			  } else if (age < 23 && $('#code_ant') == 3) {
			     alert(getExclusionText('exclusion_codeant'));
                 addExclusion('typePermiss');
			  } else {
		         $('#type_permis').removeOption(/./);
                 $('#type_permis').addOption(type, false);
                 $('#type_permis').attr('disabled',false);
		         removeExclusion('typePermiss');
			  }
			} else {
			    alert(getExclusionText('exclusion_type'));
                addExclusion('typePermiss');
			}
			
	        validateAgeCondCylindree(cylindree);
	        validateBridee($('#type_permis').val(), data);
	        }
	    }
    });
}

function validateBirthDate(){
		 var date = $('#birthdate').val();
		 $.ajax({
	        type: "POST",
	        url: home_folder+"estimation/index/loadoptions/fr/list/birthdate/",
	        data: "birthdate="+date,
	        success: function(data) {
	            if (data == -1) {
					alert(getExclusionText('birthdate_incorrect'));
	            } else
			    if(isQuadro && data < 16){
					alert(getExclusionText('quadro_exclusion_birthdate'));
					addExclusion('age_cond16');
				}else if (data >= 14) {
			     if (data > 75) {
			         alert(getExclusionText('driver_age_75'));
                     addExclusion('typePermiss');
			     } else if (data < 23 && $('#code_ant') == 3) {
    			     alert(getExclusionText('exclusion_codeant'));
                     addExclusion('typePermiss');
			     } else {
//    		         $('#type_permis').attr('disabled',false);
		             removeExclusion('typePermiss');
		             
		             var cylindree = 0;
	                 gAgeCond = data;
	                 $("#cylindree option:selected").each(function(){
    	                 cylindree = $(this).text();  	
	                 });
            
    		         var age = gAgeCond;
		             var code = $('#code_ant').val();
		             validateAgeCode(age,code);
			         $('#date_obtention').datepicker('enable');
			     }
			   } else {
			     alert(getExclusionText('exclusion_type'));
                 addExclusion('typePermiss');
			   }
        }
       
	});	
}

function validateCodePostal(){
      var $$ = $('#code_postal');
      var $dest = $('#commune');
      var url = villesUrl;
			removeExclusion($$.attr('id'));
      $dest.attr('disabled','false');
      $dest.append('<option value=""></option>');
      $dest.ajaxStart(function(){

              $$.show();

      });
	if(isQuadro){
		url = url + '/type_veh/2';
	}
	  
      $.getJSON(url,{str: $$.val(), id_type: $('input[@name="type_veh"]').val() }, function(j){
         if (j.length > 0) {

            var options = '<option value="">'+ villesChooseStr +'</option>';              

            for (var i = 0; i < j.length; i++) {

               options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';

            }
            
            gCodePostal = $$.val();
         }else{
         		alert(getExclusionText($$.attr('id')));
         		addExclusion($$.attr('id'));
         }
         
				 if(options){
           $dest.removeAttr('disabled');
           $dest.html(options);
           $dest.find('option:first');
           $dest.attr('selected', 'selected');
				 }
				 checkExclusions();
      }); 
}

function addExclusion(elementId){
	var isElementExists = false;
	for(var i=0;i<gExclusions.length;i++){
		if(gExclusions[i] == elementId){
			isElementExists = true;
		}
	}
	
	if(!isElementExists){
		gExclusions[gExclusions.length] = elementId;
	}
}

function removeExclusion(elementId){
	var newExclusions = new Array();
	for(var i=0;i<gExclusions.length;i++){
		if(gExclusions[i] != elementId){
			newExclusions[newExclusions.length] = gExclusions[i];
		}
	}
	
	gExclusions = newExclusions;
}
//lock next-button
function checkExclusions(){
	if(gExclusions.length > 0){
		$('#'+aEtapesNextBtns[gCurrentEtape]).attr('disabled',true);
	}else{
		$('#'+aEtapesNextBtns[gCurrentEtape]).attr('disabled',false);
	}
}

function validateAgeCode(age,code){
	$("input[@id=multicheck]").show();
		$("#etape3-table > * > tr").each(function(){
			$(this).show();
		});
		
		for(var i=1;i<=8;i++){
			$('#question'+i).hide();
		}
		
	if (code == 2) {
		if (age >= 18 && age <= 22) {
	      $('#question1').removeClass('hidden').show();
	  	}
	    if (age >= 23 && age <= 29) {
	      $('#question2').removeClass('hidden').show();
	    }
	    if (age >= 30) {
	      $('#question3').removeClass('hidden').show();
	    }
	}
   
	if (code == 3) {
	    if (age >= 23 && age <= 29) {
	      $('#question4').removeClass('hidden').show();
	    }
	    if (age >= 30){
	      $('#question5').removeClass('hidden').show();
	    }
	    if (age < 23) {
	      $('#question5').removeClass('hidden').show();
	    }
	}

	if (age >= 18 && age <= 75 && code == 1) {
      $('#question7').removeClass('hidden').show();
    }

    if ((age == 16 || age == 17)) { // #22826
      $('#question7').removeClass('hidden').show();
    }
    
    if(age < 23){
      $('#en_auto24').addClass('hidden');
      $('#en_auto36').removeClass('hidden').show();
    }
    
    if (age >= 23){
      $('#en_auto24').removeClass('hidden').show();
      $('#en_auto36').addClass('hidden');
    }
}
