var tmp = 0;
var fonctions= new Array();
var formations = new Array();
var modification = false;

$(document).ready(function()
{
	$("div#body").html(
		$("div#body").html().replace(new RegExp("\{MORE\}", "g"),
															   '<div class="liresuite"><a href="#" class="liresuite" rel="facebox[.body]">Lire la suite...</a></div>')
	);
	
	$("div.liresuite").each(function()
	{
		var parent = $(this).parent().parent().eq(0);
		var a      = $(this).children("a").eq(0);
		var titre  = parent.children("div.h3").eq(0);
		//alert(titre.text());
		titre.html('<a href="'+ url +'#'+ parent.attr('id') +'Content" class="liresuite" rel="facebox[.body]">'+ titre.text() +'</a>');
		a.attr("href", url +"#"+ parent.attr("id") +"Content");
	});
	$("#pass").keydown(function()
	{
		evalPwd($(this));
	});
	displayNivPass();
	// changer la valeur du champ login et password.
	$(".login").focus(function(){$(this).val("");});
	$(".password").focus(function(){$(this).val("");});
	//$(".form").validationEngine();
	$(".form").submit(function(e)
	{
		//e.preventDefault();
		if ($("#tel").val() == "" && $("#email").val() == "")
		{
			$("#tel").toggleClass("validate[required,custom[telephone]]");
		}
		else
		{
			$("#tel").removeClass("validate[required,custom[telephone]]");
			//$.validationEngine.closePrompt('.telformError',true);
		}
		if ($("#tel").val() != "")
		{
			$("#tel").toggleClass("validate[required,custom[telephone]]");
			$("#email").removeClass("validate[required,custom[email]]");
			$.validationEngine.closePrompt('.emailformError',true);
		}
		if ($("#email").val() != "")
		{
			$("#email").toggleClass("validate[required,custom[email]]");
			$("#tel").removeClass("validate[required,custom[telephone]]");
			$.validationEngine.closePrompt('.telformError',true);
		}
		$(this).validationEngine();
		return $(this).validationEngine({returnIsValid:true});
	});
	$("#new_pass").validationEngine();
	
	$("#formListe").keydown(function(e)
	{
		if (e.keyCode == 13 && $("#liste").val())
		{
			e.preventDefault();
			$.ajax({
			 type: "GET",
			 url: "index.php?page=gestion_liste&liste="+ $("#liste").val(),
			 dataType: "json",
			 success: function(response){
				addListe(response);
			 }
			});
		}
	});
	$("#ajouterListe").click(function(e)
	{
		e.preventDefault();
		
		if ($("#liste").val())
		{
			$.ajax({
			 type: "GET",
			 url: "index.php?page=gestion_liste&liste="+ $("#liste").val(),
			 dataType: "json",
			 success: function(response){
				addListe(response);
			 },
			 error: function(t,u,e){alert(e);}
			});
		}
	});
	$("#liste").focus(function(){$(this).val('')});
	if (!$.browser.opera)
	{
		$(".ui-icon").tooltip("#demotip");
	  $(".infoUpload").tooltip("#demotip");
	  $("acronym").tooltip("#demotip");
	}
	var elem     = $.browser.webkit ? $("body") : $("html");
	
	if ($("#menuRight").attr("id"))
	{
		var posMenuRight  = $("#menuRight").offset().top;
		
		setInterval(function()
		{
			var maxiMenu = $("#contenu").outerHeight() - $("#menuRight").outerHeight() + $("#contenu").offset().top + 5;
			var topMenu  = $("#menuRight").offset().top;
			var scollTop = elem.scrollTop();
			
			if (scollTop > maxiMenu && maxiMenu > 0)
			{
				$("#menuRight").animate({"top" : maxiMenu},300);
			}
			else if (scollTop > posMenuRight) 
			{
				$("#menuRight").animate({"top" : scollTop - 9},300);
			}
			else if (topMenu > posMenuRight)
			{
				$("#menuRight").animate({"top" : posMenuRight},300);
			}
		}, 500);
	}
	if ($("#lienContacts").length)
	{
		var posRaccourcis = $("#lienContacts").offset().top;
		
		setInterval(function()
		{
			var maxiRaco = $("#contenu").outerHeight() - $("#lienContacts").outerHeight();
			var topRaco  = $("#lienContacts").offset().top - 300;
			var scollTop = elem.scrollTop();
			
			if (scollTop > maxiRaco && maxiRaco > 0)
			{
				$("#lienContacts").animate({"top" : maxiRaco},300);
			}
			else if (scollTop > 0 || topRaco > 0) 
			{
			 	$("#lienContacts").animate({"top" : scollTop < posRaccourcis ? 0 : scollTop - 300}, 300);
			}
			else if (topRaco >= posRaccourcis)
			{
				$("#lienContacts").animate({"top" : 0}, 300);
			}
		}, 500);	
	}
	if ($.browser.webkit)
	{
		$("head").append('<style type="text/css">#liste{font-size: 1.4em;}</style>');	
	}
	$("#menuRight a").click(function(e)
	{
		if (this.hash != "")
		{
			e.preventDefault();
			$.scrollTo(this.hash, 500);
		}
	});
	$("div.accordion a").click(function(e)
	{
			$("#accordion div").hide();
			$(this.hash).show();
	});
	$("#accordion div").hide();
	$("#sisenior").show();
	// cliquer pour afficher le CV
	$("#displayCv").click(function(e)
	{
		displayCv(e);
	});
	// Si IE 8
	if($.browser.msie && $.browser.version >= '8.0')
	{
     $("div#contenu div.blockContact div.centre div").css("bottom","33px");
  }
	// envoi du formulaire recrutement
	$("#recrutement").submit(function(e)
	{
		if ($(this).validationEngine({returnIsValid:true}))
		{
			modification = false;
		}
	});
	
	//
	callCalendar('dateNaissance');
	// Devis
	if ($("#wizard").attr("id"))
	{
		activerDevis("#wizard");
		// ajout event pour la modification du formulaire devis
		$("#devis").children().click(function()
		{
			modification = true;
		});
		// envoi du formulaire recrutement
		$("#devis").submit(function(e)
		{
			e.preventDefault();
			// efface les message d'erreur
			$.validationEngine.closePrompt('.formError',true);
			// test si les conditions générales sont accesptées
			if (!$("#charte").attr("checked"))
			{
				$.validationEngine.buildPrompt("#charte",msg[23],"error");
				return false;
			}
			// test si pas d'erreur
			if ($(this).validationEngine({returnIsValid:true}))
			{
				modification = false;
			}
			var url = $(this).attr("action");
			var data = $(this).serialize();
			$.ajax({
			 url: url,
			 type: "POST",
			 data: data,
			 dataType: "json",
			 success: function(response){
				  if (response.code === 1)
					{
						alert(msg[48]);
					}
					else if (response.code === 2)
					{
						alert(msg[49]);
					}
					else if (response.error === "dateError")
					{
						alert(msg[50]);
					}
					else if (response.error === "dateFin")
					{
						alert(msg[51]);
					}
					else if (response.error === "dateDebut")
					{
						alert(msg[50]);
					}
					else if (response.error === "charte")
					{
						$.validationEngine.buildPrompt("#charte",msg[23],"error");
					}
					else if (response.error === 1)
					{
						alert(msg[52]);
					}
					else
					{
						api.next();
					}
				}
		  });
		});
	}
	// charger la liste des tâches
	if (!datas.length)
	{
		$.ajax({
		 type: "GET",
		 url: "index.php?page=gestion_liste&liste_tache=true&lg="+ lang,
		 async: false,
		 success: function(response){
			datas = response.split("|");
		 }
		});	
	}
	// tester la version du navigateur
	var browsers = {
		msie: 8,
		opera: 10,
		mozilla: 3.6,
		webkit: 4
	}
	var browser = "";
	
	if ($.browser.webkit)
	{
		browser = "webkit";
	}
	else if ($.browser.opera)
	{
		browser = "opera";
	}
	else if ($.browser.mozilla)
	{
		browser = "mozilla";
	}
	else if ($.browser.msie)
	{
		browser = "msie";
	}
	if (!GetCookie("alertNavigateur") && browsers[browser] > $.browser.version)
	{
		$("#drawer").css("display","block");
		$("#close").click(function()
		{
			$("#drawer").css("display","none");
			if ($("#alertNavigateur").attr("checked"))
			{
				SetCookie("alertNavigateur",1,{cookies : {

					// Cookie path
					path : '',
		
					// Cookie domain
					domain : '',
		
					// Cookie expiration time in days
					expires : 15,
		
					// Store a secure cookie?
					secure : false,
		
					// Cookie name for close Widgets
					closeName : 'ew-close',
		
					// Cookie name for disable all Widgets
					disableName : 'ew-disable',
		
					// Cookie name for positined Widgets
					positionName : 'ew-position',
		
					// Cookie name for collapsed Widgets
					collapseName : 'ew-collapse'
				}});
			}
		});
	}
	$("select#source").change(function()
	{
		if ($(this).val() == "personne")
		{
			$("#divRelation").css("display","");
			$("#viaRelation").addClass("validate[required]");
		}
		else
		{
			$("#divRelation").css("display","none");
			$("#viaRelation").removeClass("validate[required]");
			$(".viaRelationformError").remove();
		}
	});
});

function editerCv(id, type)
{
	var txt = $("#"+ type +'Data').html().replace(new RegExp("&lt;","g"),"<");
	txt     = txt.replace(new RegExp("&gt;","g"),">");
	
	jQuery.facebox('<div id="'+ type +'">'+ txt +'</div>');
	if (id)
	{
		$("#"+ type +'Date').val($('#date'+ id).val()); 
		$("#"+ type +'Occupation').val($('#occupation'+ id).val()); 
		$("#"+ type +'Lieu').val($('#lieu'+ id).val()); 
		$("#"+ type +'Detail').val($('#detail'+ id).val()); 
	}
	
	$("#"+ type +"Form").submit(function(e)
	{
		e.preventDefault();
		if (!$("#"+ type +"Form").validationEngine({returnIsValid:true}))
		{
			return false;	
		}
		//fonctions.push(new Array($("#dateFonction").val(),$("#poste").val(),$("#entreprise").val(),$("#descriptionPoste").val()));
		var html = '<div id="'+ type + tmp +'">'
							+'<div class="quandCv"><strong>'+ $("#"+ type +'Date').val() +'</strong></div>'
							+'<div class="ouCv">'
							+'<div><strong>'+ $("#"+ type +'Lieu').val() +' : '+ $("#"+ type +'Occupation').val() +'</strong></div>'
							+'<div>'+ $("#"+ type +'Detail').val() +'</div>'
							+'</div>'
							+'<div class="editCv">'
							+'<span onclick="editerCv(\''+ type + tmp +'\', \''+ type +'\')" title="'+ msg[15] +'"><img src="images/edit.png" alt="Edit" /></span>'
							+'<span onclick="delCv(\''+ type + tmp +'\')" title="'+ msg[16] +'"><img src="images/delete.png" alt="Delete" /></span>'
							+'</div>'
							+'<input type="hidden" name="'+ type +'Date[]" id="date'+ type + tmp +'" value="'+ escapeHTMLEncode($("#"+ type +'Date').val()) +'" />'
							+'<input type="hidden" name="'+ type +'Occupation[]" id="occupation'+ type + tmp +'" value="'+ escapeHTMLEncode($("#"+ type +'Occupation').val()) +'" />'
							+'<input type="hidden" name="'+ type +'Lieu[]" id="lieu'+ type + tmp +'" value="'+ escapeHTMLEncode($("#"+ type +'Lieu').val()) +'" />'
							+'<textarea style="display:none" name="'+ type +'Detail[]" id="detail'+ type + tmp +'">'+ escapeHTMLEncode($("#"+ type +'Detail').val()) +'</textarea>'
							+'<br class="rc" /></div>';
		if (id)
		{
			$("#"+ id).replaceWith(html);
			if (!$.browser.opera)
			{
			  $("#"+ id +' span').tooltip("#demotip");
			}
		}
		else
		{
			$("#"+ type +"Liste").append(html);
			if (!$.browser.opera)
			{
			  $("#"+ type + tmp +' span').tooltip("#demotip");
			}
			tmp++;
		}
		$("#"+ type +"Liste > div").removeClass("ligne1 ligne2");
		$("#"+ type +"Liste > div").each(function(index)
		{
			$(this).addClass('ligne'+ ((index % 2) + 1));
		});
		$.facebox.close();
	});
	$("#"+ type +"Form").validationEngine();
	// ajout event pour la modification d'un formulaire
	$(".form").children().keydown(function()
	{
		modification = true;
	});
}

function delCv(id)
{
	if (confirm(msg[17]))
	{
		$("#"+ id).remove();	
	}
}

function displayCv(e)
{
	e.preventDefault();
	
	if ($('#cvEnLigne').css('display') == 'none')
	{
		$.get("index.php?page=formulaire_cv",function (response)
		{
			$('#cvEnLigne').append(response);
		});
		$('#cvEnLigne').show();
	}
	else
	{
		$.validationEngine.closePrompt('.formError',true);
		$('#cvEnLigne').hide();
		$('#cvEnLigne').empty();
	}
}

function addListe(response)
{
	 if (response.exist === "false")
	 {
		 var html = '<div class="liste ui-corner-all" id="liste'+ response.id +'">'
							 +'<h3><span class="left hid" style="margin-left:0;width:25px;">'
							 +'<input type="button" class="ui-icon ui-icon-pencil" title="'+ msg[6] +'" onclick="editNomListe('+ response.id +')" />'
							 +'<input type="hidden" value="'+ response.id +'" id="liste'+ response.id +'" name="liste'+ response.id +'" /></span>'
							 +'<span>'+ $("#liste").val() +'</span></h3>'
							 +'<ul></ul>'
							 +'<div class="boton">'
							 +'<input type="button" class="ui-icon ui-icon-plus" title="'+ msg[7] +'" onclick="addTache('+ response.id +')" />'
							 +'<input type="button" class="ui-icon ui-icon-gear" title="'+ msg[8] +'" onclick="editListe('+ response.id +')" />'
							 //+'<input type="button" class="ui-icon ui-icon-check" title="'+ msg[9] +'" onclick="validListe('+ response.id +')" />'
							 +'<input type="button" class="ui-icon ui-icon-print" title="'+ msg[14] +'" onclick="imprimListe('+ response.id +')" />'
							 +'<input type="button" class="ui-icon ui-icon-trash" title="'+ msg[10] +'" onclick="deleteListe(this, '+ response.id +')" />'
							 +'</div>'
							 +'</div>';
		 if ($("#listes").children().length)
		 {
		  	$(html).insertBefore($("#listes").children().eq(0));
		 }
		 else
		 {
			 $("#listes").append(html);
		 }
		 if (!$.browser.opera)
		 {
			 $("#liste"+ response.id +" .ui-icon").tooltip("#demotip");
		 }
		 $("#liste").val("");
	}
	else
	{
		alert(msg[11]);
	}
}

function addTache(id)
{
	 var show = $('#liste'+id+' ul li:first > span.show').length ? ' show' : '';
	 
	 $('#liste'+ id).children('ul').append('<li class="li'+tmp+'">'
																				 +'<span class="left'+show+'">&nbsp;</span>'
																				 +'<span class="right"><span><input type="text" class="text" id="tache'+ tmp +'" value="'+msg[4]+'" /></span>'
																				 +'<span><input type="text" class="date" class="date" id="date'+ tmp +'" value="'+msg[5]+'" /></span>'
																				 +'<span><input type="button" onclick="validAddTache('+ id +', '+ tmp +')" '
																				 +'class="ui-icon ui-icon-check" title="'+msg[3]+'" />'
																				 +'<input type="button" onclick="$(this).parent().parent().parent().hide(\'blind\');" '
																				 +'class="ui-icon ui-icon-close" title="'+msg[12]+'" /></span>'
																				 +'</span><br class="rc" /></li>');
	 $("#tache"+tmp).parent().parent().parent().show('blind');
	 $(".li"+tmp+" > span.right *").addClass("show");
	 
	 $("#tache"+tmp).focus(function()
	 {
			if ($(this).val() == msg[4])
			{
				$(this).val("");
			}
	 });
	 $("#date"+tmp).focus(function()
	 {
			if ($(this).val() == msg[5])
			{
				$(this).val("");
			}
	 });
	 callCalendar('date'+ tmp, new Date());
	 $('#tache'+ tmp).autocomplete(datas,{matchContains:true});
	 if (!$.browser.opera)
	 {
		 $(".li"+ tmp +" .ui-icon").tooltip("#demotip");
	 }
	 tmp++;
}

function validAddTache(liste, id)
{
	var tmp = $('#date'+ id).val().replace("/", "");
	var date = isNaN(parseInt(tmp)) ? '' : $('#date'+ id).val();
	
	if ($("#tache"+id).val())
	{
		$.ajax({
		 type: "GET",
		 url: "index.php?page=gestion_liste&liste="+ liste +"&tache="+ $("#tache"+id).val() +"&date="+ date,
		 dataType: "json",
		 success: function(response){
			 if (response.exist == "false")
			 {
				 var show = $('#liste'+liste+' ul li:first span.show').length ? ' show' : '';
				 
				 $("li.li"+id).show('blind');
				 $("li.li"+id).replaceWith('<li>'
																		+'<span class="left'+show+'">'
																		+'<input type="button" class="ui-icon ui-icon-pencil" onclick="editTache('+ response.id +')" />'
																		+'<input type="button" class="ui-icon ui-icon-trash" onclick="deleteTache(this, '+ response.id +')" />'
																		+'<input type="hidden" value="'+ response.id +'" id="tache'+ response.id +'" name="tache'+ response.id +'" /></span>'
																		+'<span class="right"><div class="tache">'+ $("#tache"+id).val() +'</div><div class="date">'+ date +'</div></span>'
																		+'<br class="rc" />'
																		+'</li>');
			 }
			 else
			 {
					alert(msg[2]); 
			 }
		 }
		});	
	}
}

function deleteListe(obj, id)
{
	
	if (confirm(msg[0].replace("%s", '"'+$(obj).parent().parent().children("h3").eq(0).text()+'"')))
	{
		$(obj).parent().parent().hide("highlight");
		$.ajax({
		 type: "GET",
		 url: "index.php?page=gestion_liste&liste=true&del="+ id
		});
	}
}

function deleteTache(obj, id)
{
	if (confirm(msg[1].replace("%s", '"'+$(obj).parent().next().children().eq(0).text()+'"')))
	{
		$(obj).parent().parent().hide("blind");
		$.ajax({
		 type: "GET",
		 url: "index.php?page=gestion_liste&tache=true&del="+ id
		});
	}
}

function editListe(id)
{
	$('#liste'+id+' span.left').toggleClass("show");
}

function editNomListe(id)
{
	var h = $('#liste'+id).children("h3").eq(0).children("span");
		
	if (!$('#editNomListe'+ id).attr("id"))
	{
		h.eq(1).replaceWith('<span><input type="text" class="text" id="editNomListe'+ id +'" value="'+ h.eq(1).text() +'" />'
												 +'<input type="button" id="validNomListe'+id+'" onclick="validEditListe('+ id +')" '
												 +'class="ui-icon ui-icon-check" title="'+msg[3]+'" /></span>');
		if (!$.browser.opera)
	  {
			$("#validNomListe"+id).tooltip("#demotip");
		}
	}
	else
	{
		h.eq(1).replaceWith('<span>'+$('#editNomListe'+ id).val()+'</span>');
		$('#validNomListe'+id).remove();
	}
}

function validEditListe(id)
{
	$.ajax({
	 type: "GET",
	 url: "index.php?page=gestion_liste&liste="+ $('#editNomListe'+ id).val() +"&edit="+ id,
	 dataType: "json",
	 success: function(response){
		if (response.exist == "true")
		{
			alert(msg[11]); 
		}
		else
		{
			var h = $('#liste'+id).children("h3").eq(0).children("span");
			h.eq(1).replaceWith('<span>'+$('#editNomListe'+ id).val()+'</span>');
			$('#editNomListe'+id).remove();
		}
	 }
	});	
}

function editTache(id, liste)
{
	var span = $('#tache'+id).parent().next().children("div");
		
	if (!$('#editNomTache'+ id).attr("id"))
	{
		$('#tache'+id).parent().next().show('clip');
		span.eq(0).replaceWith('<span><input type="text" class="text" id="editNomTache'+ id +'" value="'+ span.eq(0).text() +'" /></span>');
		span.eq(1).replaceWith('<span><input type="text" class="date" id="editDateTache'+ id +'" value="'+ span.eq(1).text() +'" />'
												   +'<input type="button" id="validEditTache'+id+'" onclick="validEditTache('+ id +', '+ liste +')" '
													 +'class="ui-icon ui-icon-check" title="'+msg[3]+'" /></span>');	
		callCalendar('editDateTache'+ id, new Date());
		$('#editNomTache'+ id).autocomplete(datas,{matchContains:true});
		if (!$.browser.opera)
		{
			$('#validEditTache'+id).tooltip("#demotip");
		}
	}
	else
	{
		var span = $('#tache'+id).parent().next().children("span");
		$('#tache'+id).parent().next().show('clip');
		span.eq(0).replaceWith('<div class="tache">'+$('#editNomTache'+ id).val()+'</div>');
		span.eq(1).replaceWith('<div class="date">'+$('#editDateTache'+ id).val()+'</div>');
		$('#validEditTache'+id).remove();
	}
}

function validEditTache(id, liste)
{
	var tmp = $('#editDateTache'+ id).val().replace("/", "");
	var date = isNaN(parseInt(tmp)) ? '' : $('#editDateTache'+ id).val();
	
	$.ajax({
	 type: "GET",
	 url: "index.php?page=gestion_liste&liste="+ liste +"&tache="+ $('#editNomTache'+ id).val() +"&edit="+ id +"&date="+ date,
	 dataType: "json",
	 success: function(response){
		if (response.exist == "true")
		{
			alert(msg[2]); 
		}
		else
		{
			var span = $('#tache'+id).parent().next().children("span");
			$('#tache'+id).parent().next().show('clip');
			span.eq(0).replaceWith('<div class="tache">'+$('#editNomTache'+ id).val()+'</div>');
			span.eq(1).replaceWith('<div class="date">'+date+'</div>');
			$('#validEditTache'+id).remove();
		}
	 }
	});	
}

function validListe(id)
{
	if (confirm(msg[13].replace("%s", '"'+$('#liste'+id+' h3').children().eq(1).text()+'"')))
	{
		$.ajax({
		 type: "GET",
		 url: "index.php?page=gestion_liste&valider="+ id,
		 success: function(response){
			$('#liste'+id).remove();
		 }
		});	
	}
}

function imprimListe(id)
{
	window.open("index.php?page=gestion_liste&print=true&liste="+ id);	
}

function getIndexByIdOf(id, array)
{
	for (var i = 0; i < array.length; i++)
	{
		if (array[i].id == id)
		{
			return i;
		}
	}
	return -1;
}

function displayNivPass() {
	if ($("#nivpass")) {
		$("#nivpass").css("display","block");
	}	
}

function evalPwd(self) {
	var cmpx = 0;
	var s    = self.val();
	
	if (s.length >= 6) {
		var bad = s.search("[a-z]") != -1 || s.search("[A-Z]") != -1 || s.search("[0-9]") != -1;
		if (bad) {
			cmpx++;
		}
		var mid = (s.search("[A-Z]") != -1 && s.search("[a-z]") != -1) || 
			(s.search("[A-Z]") != -1 && s.search("[0-9]") != -1) ||
			(s.search("[a-z]") != -1 && s.search("[0-9]") != -1) || 
			s.search("[\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]") != -1 ||
			s.length >= 6;
		if (mid) {
			cmpx++;
		}
		var good =  (s.countChar("[0-9]") >= 2 && s.countChar("[a-z]") >= 2 && s.countChar("[A-Z]") >= 2) || s.length >= 8 ;
		if (good) {
			cmpx++;
		}
		var mgood =  (mid && s.search("[\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]") != -1)  || s.length > 10 ;
		if (mgood) {
			cmpx++;
		}
		var vgood = mgood && s.search("[\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]") != -1; 
		if (good && vgood) {
			cmpx++;
		}
	}
	//alert(cmpx);
	if (cmpx <= 1) {
		$("#bad").attr("class","red");
		$("#mid").attr("class","nrm");
		$("#good").attr("class","nrm");
		$("#vgood").attr("class","nrm");
	} else if (cmpx < 3) {
		$("#bad").attr("class","yellow");
		$("#mid").attr("class","yellow");
		$("#good").attr("class","nrm");
		$("#vgood").attr("class","nrm");
	} else if (cmpx < 4) {
		$("#bad").attr("class","blue");
		$("#mid").attr("class","blue");
		$("#good").attr("class","blue");
		$("#vgood").attr("class","nrm");
	} else {
		$("#bad").attr("class","green");
		$("#mid").attr("class","green");
		$("#good").attr("class","green");
		$("#vgood").attr("class","green");
	}
}

String.prototype.countChar = function(char) {
	var i     = 0;
	var count = 0;
	while (i < this.length) {
		var c = this.charAt(i);
		if (c.search(char) != -1) {
			count++;
		}
		i++;
	}
	return count;
};
// equivanlent htmlentities
function escapeHTMLEncode(str) 
{
  var div = document.createElement("div");
  var text = document.createTextNode(str.replace(new RegExp('"',"g"), "&quot;"));
	//text = text.replace(new RegExp('"',"g"), "&quot");
  div.appendChild(text);
	
  return div.innerHTML;
}
// numero de la page precedente
var numPage = 0;
var api     = null;
// active le script pour le devis
function activerDevis(id)
{
	var error = false;
	// some variables that we need 
	var devis  = $(id).scrollable({size: 1, clickable: false, keyboard: false});
	var drawer = $("#drawer"); 
	api    = devis.scrollable();
	// validation logic is done inside the onBeforeSeek callback 
	api.onSeek(function(event, i)
	{
		if (api.getIndex() == 1 && $("#soci").attr("checked") && numPage <= i)
		{
			$("#nts").attr("checked","checked");
			api.setPage(2);
		}
		else if (api.getIndex() == 1 && $("#soci").attr("checked") && numPage > i)
		{
			api.setPage(0);
		}
	});
	api.onBeforeSeek(function(event, i) { 
	 		// we are going 1 step backwards so no need for validation 
			numPage = api.getIndex();
			if (api.getIndex() < i) { 
	 				// 1. get current page 
					var page = devis.find(".page").eq(api.getIndex());
					// si page 1
					if (api.getIndex() == 0)
					{
						// effacer erreur
	          $.validationEngine.closePrompt('.formError',true);
						if (!$("#part").attr("checked") && !$("#soci").attr("checked"))
						{
							$.validationEngine.buildPrompt("#part",msg[28] +" 1 "+ msg[29],"error");
							return false;
						}
						if ($("#part").attr("checked"))
						{
							$("#ts").attr("checked","checked");
							$(".typeService").css("visibility","visible");
							typeService("ts");
						}
						else
						{
							$(".typeService").css("visibility","hidden");
							typeService("nts");
						}
					}
					else if (api.getIndex() == 1)
					{
						if ($("#ts").attr("checked"))
						{
							typeService("ts");
						}
						else
						{
							typeService("nts");
						}
					}
					// si page 3
					else if (api.getIndex() == 2)
					{
						if ($("#ts").attr("checked"))
						{
							if (!checkPrestationTS())
							{
								return false;
							}
							if ($("#tarifQ").attr("checked"))
							{
								$(".serviceQualite").css("display","none");
								$("#serviceQualite").attr("checked","checked");
							}
						}
						else
					  {
							if (!checkPrestationNTS())
							{
								return false;
							}
							// si dans les 24H
							var demain = new Date();
							demain.setTime(new Date().getTime() + 86400000);
							demain = (demain.getDate() < 10 ? "0" :"")+demain.getDate()+"/"+(demain.getMonth()+1 < 10 ? "0" :"")+(demain.getMonth()+1)+"/"+demain.getFullYear();
							
							var fin    = $("#dateFin").val().split("/");
							fin[0] = parseInt(fin[0], 10);
							fin[1] = parseInt(fin[1], 10) - 1;
							var dateAjourdhui = new Date().getDate()+"/"+(new Date().getMonth()+1 < 10 ? "0" :"")+(new Date().getMonth()+1)+"/"+new Date().getFullYear();
	            var dateFin       =  fin[2]+"/"+fin[1]+"/"+fin[0];
							
							if ($("#dateFin").val() == demain || dateFin == dateAjourdhui)
							{
								calculeTarif("formule1", msg[43]);
							}
							else
							{
								calculeTarif("formule2", msg[44]);
							}
							//$("#h").text($("#nbh").val());
							//$("#optimiserHeure").text($("#nbh").val());
							//$("#optimiserTaux").text($("#nbh").val());
							//$("#optimiserMontant").text($("#nbh").val() * $("#nbh").val());
							//$("div.recurrent").css("display","none");
							
							if (recurrentOptimiser)
							{
								$("#optimiser").attr("checked","cheked");
								$("#recurrent").attr("checked","checked");
								//$("div.recurrent").css("display","");
								$("table#tarifs td").css("display","");
								$(".formule2").css("display","none");
								$(".formule3").css("display","");
								$("#formuleChoisi").val("formule3");
								
								var txt = msg[46];
								txt     = txt.replace("%h", (nbH < 4 ? 4 : nbH));
								$("#montant span.text").text(txt);
								$("#spanNh").text((nbH < 4 ? 4 : nbH));
								$("#montant span.prix").text((nbH < 4 ? 4 : nbH) * $("#formule34").val());
							}
							nbHOptimiser = 0;
							$("#nbhChoisi").val("");
							// verifier le code promo
							if ($("#promo").val())
							{
								var error = false;
								
								$.ajax({
									url : "index.php?page=traiter_devis&code="+ $("#promo").val(),
									type: "GET",
									async: false,
									dataType: "json",
									success: function(response)
									{
										if (response.code === 1 || response.code === 2)
										{
											error = true;
										}
									}
								});
								if (error)
								{
									codePromo = false;
									// cache le tableau
									var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
									$(ligne +" span").each(function()
									{
										var id = $(this).attr('id').replace("Span", "");
										$(this).text($("#"+ id).val());
										
										if ($("#"+ id +"Radio").attr("checked"))
										{
											nbHSelected = $("#"+ id +"Radio").val() == 4 && nbH > 4 ? nbH : $("#"+ id +"Radio").val();
											var txt = msg[46];
											txt     = txt.replace("%h", nbHSelected);
											var prix = (codePromo ? $("#formule34").val() :$("#"+ id).val());
											var montant  = (prix * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
											$("#montant span.text").text(txt);
											$("#montant span.prix").text(montant);
										}
									});
								}
								else
								{
									// cache le tableau
									var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
									$(ligne +" span").text($("#formule34").val());
									var txt = msg[46];
									txt     = txt.replace("%h", nbH);
									$("#montant span.text").text(txt);
									$("#montant span.prix").text(nbH * $("#formule34").val() + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0));
									nbHOptimiser = nbH;
									$("#nbhChoisi").val(nbHOptimiser);
									$.validationEngine.closePrompt('.formError',true);
									codePromo = true;
								}
								//return !error;
							}
							else
							{
								codePromo = false;
								// cache le tableau
								var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
								$(ligne +" span").each(function()
								{
									var id = $(this).attr('id').replace("Span", "");
									$(this).text($("#"+ id).val());
									
									if ($("#"+ id +"Radio").attr("checked"))
									{
										nbHSelected = $("#"+ id +"Radio").val() == 4 && nbH > 4 ? nbH : $("#"+ id +"Radio").val();
										var txt = msg[46];
										txt     = txt.replace("%h", nbHSelected);
										var prix = (codePromo ? $("#formule34").val() :$("#"+ id).val());
										var montant  = (prix * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
										$("#montant span.text").text(txt);
										$("#montant span.prix").text(montant);
									}
								});
							}
						}
					}
					// si page 4
					else if (api.getIndex() == 3)
					{
						if ($("#ts").attr("checked"))
						{
							
						}
						else
					  {
							if (nbHOptimiser > nbH)
							{
								txt = msg[47];
								txt = txt.replace("%h1", nbH);
								txt = txt.replace("%h2", nbHOptimiser);
								if (confirm(txt))
								{
									api.prev();
									recurrentOptimiser = $("#recurrent").attr("checked");
									return false;
								}
							}
							// code promo
							if ($("#promo").val())
							{
								var error = false;
								
								$.ajax({
									url : "index.php?page=traiter_devis&code="+ $("#promo").val(),
									type: "GET",
									async: false,
									dataType: "json",
									success: function(response)
									{
										if (response.code === 1)
										{
											$.validationEngine.buildPrompt("#promo",msg[48],"error");
											error = true;
										}
										else if (response.code === 2)
										{
											$.validationEngine.buildPrompt("#promo",msg[49],"error");
											error = true;
										}
									}
								});
								return !error;
							}
							else
							{
								$.validationEngine.closePrompt('.formError',true);
							}
						}
					}
					// si page 5
					else if (api.getIndex() == 4)
					{
						if (!checkDonnees())
						{
							return false;
						}
					}
	 		}
			// si retour en arrière
			else
			{
				$.validationEngine.closePrompt('.formError',true);
			}
	  	// update status bar 
			$("#status li").removeClass("active").eq(i).addClass("active");
			if (($("#status li").eq(i).position().left + $("#status li").eq(i).innerWidth()) > $(id).innerWidth())
			{
				$("#status").animate({"left" : "-"+ ($("#status li").eq(i).position().left -  $("#status li").eq(i).innerWidth())},300);
			}
			else
			{
				$("#status").animate({"left" : 0},300);
			}
	});
}
// check les prestations TS pour le devis
function checkPrestationTS()
{
	var error = false;
	var reg   = new RegExp("^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$", "g");
	// effacer erreur
	$.validationEngine.closePrompt('.formError',true);
	// date debut prestation
	if (!reg.test($("#dateDebut").val()))
	{
		$.validationEngine.buildPrompt("#dateDebut",msg[33],"error");
		error = true;
	}
	// jour de la semaine
	var jour = 0;
	$("#typeTs input.jour").each(function()
	{
		if ($(this).attr("checked"))
		{
			jour++;
		}								
	});
	if (jour == 0)
	{
		$.validationEngine.buildPrompt("#jour0",msg[28] +" 1 "+ msg[29],"error");
		error = true;
	}
	// tache
	var tache = 0;
	$("#typeTs input.tache").each(function()
	{
		if ($(this).attr("checked"))
		{
			tache++;
		}								
	});
	if (tache == 0)
	{
		$.validationEngine.buildPrompt("#tache0",msg[28] +" 1 "+ msg[29],"error");
		error = true;
	}
	return !error;	
}
// les prestation NTS pour le devis
function checkPrestationNTS()
{
	var error = false;
	var deb   = new RegExp("^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$", "g");
	var fin   = new RegExp("^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$", "g");
	// effacer erreur
	$.validationEngine.closePrompt('.formError',true);
	// date debut prestation
	if (!deb.test($("#dateDebut").val()))
	{
		$.validationEngine.buildPrompt("#dateDebut",msg[33],"error");
		error = true;
	}
	// date fin prestation
	if (!fin.test($("#dateFin").val()))
	{
		$.validationEngine.buildPrompt("#dateFin",msg[33],"error");
		error = true;
	}
	// si la période est bonne
	deb    = $("#dateDebut").val().split("/");
	deb[0] = parseInt(deb[0], 10);
	deb[1] = parseInt(deb[1], 10) - 1;
	
	fin    = $("#dateFin").val().split("/");
	fin[0] = parseInt(fin[0], 10);
	fin[1] = parseInt(fin[1], 10) - 1;
	var dateAjourdhui = new Date().getDate()+"/"+(new Date().getMonth()+1 < 10 ? "0" :"")+(new Date().getMonth()+1)+"/"+new Date().getFullYear();
	var dateFin       =  fin[2]+"/"+fin[1]+"/"+fin[0];
	
	if ((new Date(deb[2], deb[1], deb[0]).getTime() > new Date(fin[2], fin[1], fin[0]).getTime()) || dateFin < new Date().getTime())
	{
		$.validationEngine.buildPrompt("#dateFin",msg[42],"error");
		error = true;
	}
	// tache
	var tache = 0;
	$("#typeNts input[name=tachesNTS\\[\\]]").each(function()
	{
		if ($(this).val() == "")
		{
			$.validationEngine.buildPrompt("#"+$(this).attr("id"),msg[21],"error");
		  error = true;
			tache++;
		}								
	});
	return !error;	
}
// check les données pour le devis
function checkDonnees()
{
	var error = false;
	var tel   = new RegExp("^(\\+)?[0-9/ .\(\)\-]{8,25}$", "g");
	// effacer erreur
	$.validationEngine.closePrompt('.formError',true);
	if ($("#titre").val() == '')
	{
		error = true;
		$.validationEngine.buildPrompt("#titre",msg[21],"error");
	}
	if ($("#nom").val() == '')
	{
		error = true;
		$.validationEngine.buildPrompt("#nom",msg[21],"error");
	}
	if ($("#prenom").val() == '')
	{
		error = true;
		$.validationEngine.buildPrompt("#prenom",msg[21],"error");
	}
	if ($("#adresse").val() == '')
	{
		error = true;
		$.validationEngine.buildPrompt("#adresse",msg[21],"error");
	}
	if (!tel.test($("#tel").val()))
	{
		error = true;
		$.validationEngine.buildPrompt("#tel",msg[31],"error");
	}
	return !error;
}
// charge les pages en fonction du type de service
function typeService(type)
{
	if (type == "ts")
	{
		if ($("#typeTs").html() == "")
		{
			$("#typeNts").empty();
			$("#tarifNts").empty();
			$("#conditionsGenerales").empty();
			// prestation ts
			$.ajax({url:"index.php?page=type_ts",async: false, success:function (response)
			{
					$('#typeTs').append(response);
					// calendrier
	        callCalendar("dateDebut", new Date());
					$("#typeTs").parents(".page").css("background","none");
					$("#boutonType").css("display","");
					// tarif ts
					$.get("index.php?page=tarif_ts",function (response)
					{
							$('#tarifTs').append(response);
							// contrôl sur le tarif TS
							$("#tarifQ").click(function()
							{
								if ($(this).attr("checked"))
								{
									$(".serviceQualite").css("display","none");
									$("serviceQualite").attr("checked","checked");
									$("div.qualite").css("display","");
									$(".avecQualite").css("display","");
									$(".sansQualite").css("display","none");
								}
							});
							$("label[for='tarifQ']").click(function()
							{
								if ($("#tarifQ").attr("checked"))
								{
									$(".serviceQualite").css("display","none");
									$("#serviceQualite").attr("checked","checked");
									$("div.qualite").css("display","");
									$(".avecQualite").css("display","");
									$(".sansQualite").css("display","none");
								}
							});
							$("#tarifS").click(function()
							{
								if ($(this).attr("checked"))
								{
									$(".serviceQualite").css("display","");
									$("#serviceQualite").attr("checked","checked");
								}
							});
							$("label[for='tarifS']").click(function()
							{
								if ($("#tarifS").attr("checked"))
								{
									$(".serviceQualite").css("display","");
									$("#serviceQualite").attr("checked","checked");
								}
							});
							$("#serviceQualite").click(function()
							{
								if ($(this).attr("checked"))
								{
									$("div.qualite").css("display","");
									$(".avecQualite").css("display","");
									$(".sansQualite").css("display","none");
								}
								else
								{
									$("div.qualite").css("display","none");
									$(".avecQualite").css("display","none");
									$(".sansQualite").css("display","");
								}
							 });
							$("#tarifTs").parents(".page").css("background","none");
					});
					// condition ts
					$.get("lang/"+ $("#langUser").val()+"/conditions_ts_particulier.html",function (response)
					{
							$('#conditionsGenerales').append(response);
							$("#conditionsGenerales").parents(".page").css("background","none");
					});
			}});
		}
	}
	else
	{
		if ($("#typeNts").html() == "")
		{
			$("#typeTs").empty();
			$("#tarifTs").empty();
			$("#conditionsGenerales").empty();
			// prestation ts
			$.ajax({url:"index.php?page=type_nts",async: false, success: function (response)
			{
					$('#typeNts').append(response);
					// calendrier
	        callCalendar("dateDebut", new Date());
					callCalendar("dateFin", new Date());
					//
					$('#tache0').autocomplete(datas,{matchContains:true});
					if (!$.browser.opera)
			    {
			  		$("#del0").tooltip("#demotip");
					  $("#addTravaux").tooltip("#demotip");
					}
					$("#typeNts").parents(".page").css("background","none");
					$("#boutonType").css("display","");
					// tarif ts
					$.get("index.php?page=tarif_nts",function (response)
					{
							$('#tarifNts').append(response);
							// contrôl sur le tarif NTS
							$("#tarifNts").parents(".page").css("background","none");
					});
					// condition nts
					$.get("lang/"+ $("#langUser").val() +"/conditions_nts_societe.html",function (response)
					{
							$('#conditionsGenerales').append(response);
							$("#conditionsGenerales").parents(".page").css("background","none");
					});
			}});
		}
	}
	$("#devis").keydown(function(e) { 
		if (e.keyCode == 9) { 
			e.preventDefault(); 
		} 
	});
}
// ajoute une tache pour le devis NTS
function addTravaux(id)
{
	tmp++;
	var html = '<tr>'
						 +'<td><input type="text" name="tachesNTS['+ tmp +']" size="29" id="tache'+ tmp +'" /></td>'
						 +'<td class="center">'
						 +' <select name="nbhNTS['+ tmp +']">';
	for (var i = 1; i <= 20; i++)
	{
		html += '<option value="'+ i +'">'+ i +'</option>';
	}
	html    += ' </select>'
						 +'</td>'
						 +'<td class="center"><input type="checkbox" name="outillage['+ tmp +']" value="1" />'+ msg[18] +'</td>'
						 +'<td class="center"><input type="checkbox" name="fourniture['+ tmp +']" value="1" />'+ msg[18] +'</td>'
						 +'<td class="center">'
						 +'<div class="ui-corner-all bouton" style="font-size:1em" id="del'+ tmp +'" title="'+ msg[20] +'" onclick="delTravaux(\''+ id +'\',this)"> - </div></td>'
						 +'</tr>';
	$("#"+id).append(html);
	$('#tache'+ tmp).autocomplete(datas,{matchContains:true});
	if (!$.browser.opera)
	{
		$("#del"+ tmp).tooltip("#demotip");
	}
}
// supprime une tache pour le devis NTS
function delTravaux(id, obj)
{
	if ($("#"+id +' tr').length == 3)
	{
		alert(msg[21]);
		return false;
	}
	if (confirm(msg[16]))
	{
		$(obj).parent().parent().remove();
	}
}
// nombre d'heure de prestation
var nbH = 0;
var selected = 0;
var nbHOptimiser = 0;
var recurrentOptimiser = false;
var codePromo = false;

function calculeTarif(formule, message)
{
	// cache le tableau
	$(".formule1").css("display","none");
	$(".formule2").css("display","none");
	$(".formule3").css("display","none");
	// cache optimisation
	if (formule == "formule1")
	{
		$("div.optimiser").css("display","none");	
	}
	else
	{
		$("div.optimiser").css("display","");	
	}
	// nombre d'heure de prestation
	nbH = 0;
	$("select[name^='nbhNTS\\[']").each(function()
	{
		nbH += parseInt($(this).val());
	});
	// Remplacer le données dans le message
	var text = message.replace("%h", nbH);
	text = text.replace("%d", $("#dateDebut").val());
	text = text.replace("%f", $("#dateFin").val());
	// Afficher le message
	$("#selection").text(text);
	// selection le tarif
	selected = nbH > 4 ? 4 : nbH;
	$("#"+ formule + selected +"Radio").attr("checked","checked");
	
	if (nbH >= 4)
	{
		//$("#"+ formule + selected +"Span").text($("#"+ formule +"4").val());
		//$("#formule3"+ selected +"Span").text($("#formule34").val());
		$("#spanNh").text(nbH);
		$(".optimiserCheck").css("display","none");
	}
	else
	{
		$("#spanNh").text("4");
		$(".optimiserCheck").css("display","");
	}
	$("#formuleChoisi").val(formule);
	// afficher que la colonne qui correspond au heure
	$("table#tarifs td").each(function()
	{
		if ($(this).hasClass("heure"+ selected))
		{
			$(this).css("display", "");
		}
		else if ($(this).attr("class") != "" && $(this).attr("class") != "th")
		{
			$(this).css("display", "none");
		}
	});
	$("."+ formule).css("display","");
	$("#optimiser").attr("checked","");
	$("#recurrent").attr("checked","");
	// optimiser le tarif
	$("#optimiser").click(function()
	{
		var checked = $(this).attr("checked");
		
		if (checked && selected < 4)
		{
			for (var i = selected + 1; i <= 4; i++)
			{
				$(".heure"+ i).css("display", "");
			}
		}
		//$("div.recurrent").css("display","");
		if (!checked)
		{
			//$("div.recurrent").css("display","none");
			$("#recurrent").attr("checked","");
			// cache le tableau
			$(".formule2").css("display","");
			$(".formule3").css("display","none");
			$("#formuleChoisi").val("formule2");
			//$("table#tarifs tr.formule2 td").css("display","none");
			
			for (var i = 1; i <= 4; i++)
			{
				$(".heure"+ i).css("display", i < selected ? "none" : "");
			}
			// selection trarif
			$("table#tarifs tr.formule2 input[type='radio']").each(function()
			{
				if ($(this).attr("name") != "eval" && $(this).attr("checked"))
				{
					nbHSelected = $(this).val() == 4 && nbH > 4 ? nbH : $(this).val();
					var txt = msg[46];
					txt     = txt.replace("%h", nbHSelected);
					var montant  = ($("#"+ formule + $(this).val()).val() * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
					$("#montant span.text").text(txt);
					$("#montant span.prix").text(montant);
					nbHOptimiser = nbHSelected;
					$("#nbhChoisi").val(nbHOptimiser);
				}
			});
		}
	});
	// recurrent
	$("#recurrent").click(function()
	{
		var checked = $(this).attr("checked");
		
		if (checked)
		{
			// cache le tableau
			$(".formule2").css("display","none");
			$(".formule3").css("display","");
			$("table#tarifs td").css("display","");
			$("#formuleChoisi").val("formule3");
			var txt = msg[46];
			txt     = txt.replace("%h", (nbH < 4 ? 4 : nbH));
			$("#montant span.text").text(txt);
			$("#montant span.prix").text((nbH < 4 ? 4 : nbH) * $("#formule34").val());
			nbHOptimiser = (nbH < 4 ? 4 : nbH);
			$("#nbhChoisi").val(nbHOptimiser);
		}
		else
		{
			// cache le tableau
			$(".formule2").css("display","");
			$(".formule3").css("display","none");
			$("#formuleChoisi").val("formule2");
			//$("table#tarifs tr.formule2 td").css("display","none");
			
			for (var i = 1; i <= 4; i++)
			{
				$(".heure"+ i).css("display", i < selected ? "none" : "");
			}
			// selection trarif
			$("table#tarifs tr.formule2 input[type='radio']").each(function()
			{
				if ($(this).attr("name") != "eval" && $(this).attr("checked"))
				{
					nbHSelected = $(this).val() == 4 && nbH > 4 ? nbH : $(this).val();
					var txt = msg[46];
					txt     = txt.replace("%h", nbHSelected);
					var montant  = ($("#"+ formule + $(this).val()).val() * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
					$("#montant span.text").text(txt);
					$("#montant span.prix").text(montant);
					nbHOptimiser = nbHSelected;
					$("#nbhChoisi").val(nbHOptimiser);
				}
			});
		}
	});
	$("#labelRecurrent").click(function()
	{
		var checked = $(this).attr("checked");
		
		if (checked)
		{
			// cache le tableau
			$(".formule2").css("display","none");
			$(".formule3").css("display","");
			$("table#tarifs td").css("display","");
			$("#formuleChoisi").val("formule3");
			var txt = msg[46];
			txt     = txt.replace("%h", (nbH < 4 ? 4 : nbH));
			$("#montant span.text").text(txt);
			$("#montant span.prix").text((nbH < 4 ? 4 : nbH) * $("#formule34").val());
			nbHOptimiser = (nbH < 4 ? 4 : nbH);
			$("#nbhChoisi").val(nbHOptimiser);
		}
		else
		{
			// cache le tableau
			$(".formule2").css("display","");
			$(".formule3").css("display","none");
			$("#formuleChoisi").val("formule2");
			//$("table#tarifs tr.formule2 td").css("display","none");
			
			for (var i = 1; i <= 4; i++)
			{
				$(".heure"+ i).css("display", i < selected ? "none" : "");
			}
			// selection trarif
			$("table#tarifs tr.formule2 input[type='radio']").each(function()
			{
				if ($(this).attr("name") != "eval" && $(this).attr("checked"))
				{
					nbHSelected = $(this).val() == 4 && nbH > 4 ? nbH : $(this).val();
					var txt = msg[46];
					txt     = txt.replace("%h", nbHSelected);
					var montant  = ($("#"+ formule + $(this).val()).val() * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
					$("#montant span.text").text(txt);
					$("#montant span.prix").text(montant);
					nbHOptimiser = nbHSelected;
					$("#nbhChoisi").val(nbHOptimiser);
				}
			});
		}
	});
  // total
	var txt = msg[46];
	txt     = txt.replace("%h", nbH);
	var montant  = ($("#"+ formule + selected).val() * nbH) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
	
	$("#montant span.text").text(txt);
	$("#montant span.prix").text(montant);
	// selection trarif
	$("table#tarifs input[type='radio']").click(function()
	{
		if ($(this).attr("name") != "eval")
		{
			nbHSelected = $(this).val() == 4 && nbH > 4 ? nbH : $(this).val();
			var txt = msg[46];
	    txt     = txt.replace("%h", nbHSelected);
			var prix = (codePromo ? $("#formule34").val() :$("#"+ formule + $(this).val()).val());
			var montant  = (prix * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
			$("#montant span.text").text(txt);
			$("#montant span.prix").text(montant);
			nbHOptimiser = $(this).val();
			$("#nbhChoisi").val(nbHOptimiser);
		}
	});
	
	$("#promo").blur(function()
	{
		if ($(this).val())
		{
			var error = false;
			
			$.ajax({
				url : "index.php?page=traiter_devis&code="+ $("#promo").val(),
				type: "GET",
				async: false,
				dataType: "json",
				success: function(response)
				{
					if (response.code === 1)
					{
						$.validationEngine.buildPrompt("#promo",msg[48],"error");
						error = true;
					}
					else if (response.code === 2)
					{
						$.validationEngine.buildPrompt("#promo",msg[49],"error");
						error = true;
					}
				}
			});
			if (error)
			{
				codePromo = false;
				// cache le tableau
				var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
				$(ligne +" span").each(function()
				{
					var id = $(this).attr('id').replace("Span", "");
					$(this).text($("#"+ id).val());
					
					if ($("#"+ id +"Radio").attr("checked"))
					{
						nbHSelected = $("#"+ id +"Radio").val() == 4 && nbH > 4 ? nbH : $("#"+ id +"Radio").val();
						var txt = msg[46];
						txt     = txt.replace("%h", nbHSelected);
						var prix = (codePromo ? $("#formule34").val() :$("#"+ id).val());
						var montant  = (prix * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
						$("#montant span.text").text(txt);
						$("#montant span.prix").text(montant);
					}
				});
			}
			else
			{
				// cache le tableau
				var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
				$(ligne +" span").text($("#formule34").val());
				var txt = msg[46];
				txt     = txt.replace("%h", nbH);
				$("#montant span.text").text(txt);
				$("#montant span.prix").text(nbH * $("#formule34").val() + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0));
				nbHOptimiser = nbH;
				$("#nbhChoisi").val(nbHOptimiser);
				$.validationEngine.closePrompt('.formError',true);
				codePromo = true;
			}
			return !error;
		}
		else
		{
			codePromo = false;
			// cache le tableau
			var ligne = $(".formule1").css("display") == "none" ? ".formule2" : ".formule1";
			$(ligne +" span").each(function()
			{
				var id = $(this).attr('id').replace("Span", "");
				$(this).text($("#"+ id).val());
				
				if ($("#"+ id +"Radio").attr("checked"))
				{
					nbHSelected = $("#"+ id +"Radio").val() == 4 && nbH > 4 ? nbH : $("#"+ id +"Radio").val();
					var txt = msg[46];
					txt     = txt.replace("%h", nbHSelected);
					var prix = (codePromo ? $("#formule34").val() :$("#"+ id).val());
					var montant  = (prix * nbHSelected) + ($("#formuleChoisi").val() == "formule2" ? ($("input[name='eval']").val()*1) : 0);
					$("#montant span.text").text(txt);
					$("#montant span.prix").text(montant);
				}
			});
		}
	});
}

// traiter la page prestation pour particulier
