$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "combo/fichier.xml",
		dataType: "xml",
		success: function(xml) {	
			$("#projet").append("<option value=''></option>");
			$(xml).find('projet').each(function(){
				var nom = $(this).attr('nom');
				$("#projet").append("<option value='1'>" + nom + "</option>");	
			});
			
			$("#projet").blur(function() {
				verifInput($(this), 'select');							 
			});
			
			$("#projet").change(function() {
				var valeur = $(this).children("option:selected").text();
				$(xml).find('projet').each(function(){					
					if ($(this).attr('nom') == valeur)
					{
						enlever(false);
						 
						var i = 0;
						if (!$(this).find('format').attr('nom'))
						{	
							$(this).find('item').each(function(){							
								i++;
								if ($(this).find('choix:first').text() != 'autre')
								{									
									var valLabel = $(this).attr('label');
									$('<label>' + valLabel + ' :</label>').appendTo("#combo");
									$('<select id="choix' + i + '"></select>').appendTo("#combo");
									$("#choix" + i + "").append("<option value=''></option>");
									$("#choix" + i + "").blur(function() {
										verifInput($(this), 'select');							 
									});
								}
								else
								{
									var valLabel = $(this).attr('label');
									$('<label>' + valLabel + ' :</label>').appendTo("#combo");
									$('<textarea id="textSpec' + i + '" class="textarea"></textarea>').appendTo("#combo");
									$("#textSpec" + i + "").blur(function() {
										verifInput($(this), 'textarea');							 
									});
								}
								$(this).find('choix').each(function(){										
										var valeur = $(this).text();
										$("#choix" + i + "").append("<option value='1'>" + valeur + "</option>");
										
										if ($("#choix" + i + "").prev("label").text() != 'Forfait :')
										{
											//alert($("#choix" + i + "").prev("label").text())
											if (valeur == 'autre')
											{	
												$("#choix" + i + "").change(function(){
													var valeurChoix = $(this).children("option:selected").text();	
													if (valeurChoix == 'autre')
													{
														i++;
														$('<textarea id="text' + i + '" class="textarea"></textarea>').insertAfter($("#" + $(this).attr("id")));
														$('<label>Pr\351ciser :</label>').insertAfter($("#" + $(this).attr("id")));	
														$("#text" + i + "").blur(function() {
															verifInput($(this), 'textarea');							 
														});
													}
													else
													{													
														enleverTextarea($(this).next("label").next("textarea").attr("id"));
													}
												});
											}	
										}
								});
							});
							$(ajoutBas()).appendTo("#combo");
							$("#phone").mask("(999) 999-9999");
							$("#code").mask("a9a 9a9");
						}
						else
						{
							var valLabel = $(this).attr('label');
							$('<label id="labFormat">Format :</label>').appendTo("#combo");
							$('<select id="format"></select>').appendTo("#combo");
							$("#format").append("<option value=''></option>");
							$(this).find('format').each(function(){
								var nom = $(this).attr('nom');
								$("#format").append("<option value='1'>" + nom + "</option>");																	
							});	
							
							$("#format").blur(function() {
								verifInput($(this), 'select');							 
							});
							$("#format").change(function() {							
								var valeurFormat = $(this).children("option:selected").text();
								$(xml).find('format').each(function(){								 
									if ($(this).attr('nom') == valeurFormat)
									{										
										enlever(true);
										
										var i = 0;
										$(this).find('item').each(function(){						
											i++;
											if ($(this).find('choix:first').text() != 'autre')
											{									
												var valLabel = $(this).attr('label');
												$('<label>' + valLabel + ' :</label>').appendTo("#combo");
												$('<select id="choix' + i + '"></select>').appendTo("#combo");
												$("#choix" + i + "").append("<option value=''></option>");
											}
											$(this).find('choix').each(function(){
												var valeur = $(this).text();
												$("#choix" + i + "").append("<option value='1'>" + valeur + "</option>");
												valeurLamination = $(this).attr('valeur');										
												if (valeurLamination == '1')
												{
													$("#choix" + i + "").change(function(){
																						 
														$(this).next("label").next("select")[0].options.length=0;
														var valeurChoix = $(this).attr("selectedIndex");
														var listeSelect = $(this).next("label").next("select");
														enleverTextarea(listeSelect.next("label").next("textarea").attr("id"));
														if (valeurChoix == '1')
														{														
															listeSelect.append("<option value=''></option>");
															listeSelect.append("<option value='1'>500</option>");
															listeSelect.append("<option value='1'>1000</option>");	
															listeSelect.append("<option value='1'>2000</option>");	
															listeSelect.append("<option value='1'>3000</option>");	
															listeSelect.append("<option value='1'>4000</option>");	
															listeSelect.append("<option value='1'>5000</option>");	
															listeSelect.append("<option value='1'>6000</option>");	
															listeSelect.append("<option value='1'>autre</option>");	
														}
														else
														{
															listeSelect.append("<option value=''></option>");
															listeSelect.append("<option value='1'>500</option>");
															listeSelect.append("<option value='1'>1000</option>");	
															listeSelect.append("<option value='1'>2000</option>");	
															listeSelect.append("<option value='1'>4000</option>");	
															listeSelect.append("<option value='1'>6000</option>");	
															listeSelect.append("<option value='1'>autre</option>");
														}
													});
												}
												
												if (valeur == 'autre')
												{	
													$("#choix" + i + "").change(function(){
														var valeurChoix = $(this).children("option:selected").text();											
														if (valeurChoix == 'autre')
														{
															i++;
															$('<textarea id="text' + i + '" class="textarea"></textarea>').insertAfter($("#" + $(this).attr("id")));
															$('<label>Pr\351ciser :</label>').insertAfter($("#" + $(this).attr("id")));	
															$("#text" + i + "").blur(function() {
																verifInput($(this), 'textarea');							 
															});
														}
														else
														{
															enleverTextarea($(this).next("label").next("textarea").attr("id"));
														}
													});
												}												
											});
										});
										if (valeurFormat == 'Autres')
										{
											$('<textarea id="textFormat' + i + '" class="textarea"></textarea>').insertAfter("#format");
											$('<label>Pr\351ciser :</label>').insertAfter("#format");
											$("#textFormat" + i + "").blur(function() {
												verifInput($(this), 'textarea');							 
											});
										}
										
										$(ajoutBas()).appendTo("#combo");
										$("#phone").mask("(999) 999-9999");
										$("#code").mask("a9a 9a9");
									}
								});
							});
						}						
					}
				});
			});
		}
	});
});


function ajoutBas()
{
	var texte;
	texte = '<label>Nom : </label><input type="text" id="nom" class="input" onblur="checkInput(this)">'
			+ '<label>Adresse : </label><input type="text" id="adresse" class="input" onblur="checkInput(this)">'
			+ '<label>Ville : </label><input type="text" id="ville" class="input" onblur="checkInput(this)">'
			+ '<label>Code postal : </label><input type="text" id="code" class="input" onblur="checkInput(this)" onChange="this.value=this.value.toUpperCase();">'
			+ '<label>T\351l\351phone : </label><input type="text" id="phone" class="input" onblur="checkInput(this)">'
			+ '<label>Courriel : </label><input type="text" id="email" class="input" onblur="checkInput(this)">'
			+ '<label>Commentaires : </label><textarea id="comment" onblur="checkInput(this)" class="textarea"></textarea>';
	return texte;
}

function enlever(format)
{
	if (format)
	{
		$("#combo").find("select").each(function(){
			if (($(this).attr("id") != 'projet') && ($(this).attr("id") != 'format'))
				$(this).remove();	
		});	
		
		$("#combo").find("label").each(function(){
			if (($(this).attr("id") != 'labProjet') && ($(this).attr("id") != 'labFormat'))
				$(this).remove();	
		});	
	}
	else
	{
		$("#combo").find("select").each(function(){
			if ($(this).attr("id") != 'projet')
				$(this).remove();	
		});	
		
		$("#combo").find("label").each(function(){
			if ($(this).attr("id") != 'labProjet')
				$(this).remove();	
		});		
	}
	$("#combo").find("textarea").each(function(){
		$(this).remove();
	});	
	$("#combo").find("input").each(function(){
		if ($(this).attr("class") != 'test')
				$(this).remove();
	});	
}

function enleverTextarea(niveau)
{
	$("#" + niveau + "").prev("label").remove();
	$("#" + niveau + "").remove();
}

function getXhr()
{
	var xhr = null; 
	if(window.XMLHttpRequest) // Firefox et autres
		 xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject)
	{ // Internet Explorer 
		try 
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	else 
	{ // XMLHttpRequest non supporté par le navigateur 
		alert('error', "Votre navigateur ne supporte pas les objets XMLHTTPRequest...", 'Erreur');
		xhr = false; 
	} 
	return xhr
} 

function envoiEmail()
{				
	if (verif())
	{
		var parametres = '';
		var i = 0;
		$("#combo").find("label").each(function(){
			i++;
			parametres = parametres + i + '=' + $(this).text() + '&';
				
			if ($(this).next("select").size() > 0 )
			{	
				i++;
				parametres = parametres + i + '=' + $(this).next("select").children("option:selected").text() + '&';
			}
			
			if ($(this).next("input").size() > 0 )
			{	
				i++;
				parametres = parametres + i + '=' + $(this).next("input").val() + '&';
			}
			
			if ($(this).next("textarea").size() > 0 )
			{	
				i++;
				parametres = parametres + i + '=' + $(this).next("textarea").val() + '&';
			}
		});
		
		
		var url = 'combo/script/script.php';
		
		$.blockUI({ message: '<img src="combo/image/busy.gif" /><font class="titre"> Envoi du formulaire en cours...</font>', 
			css: { border: '3px solid #bbb' }  }); 
						
		var xhr = getXhr()
		// On défini ce qu'on va faire quand on aura la réponse
		xhr.onreadystatechange = function(){
			// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
			if(xhr.readyState == 4 && xhr.status == 200)
			{
				if (xhr.responseText == 'commandeOK')
				{	
					setTimeout('afficheLoading("Le formulaire a \351t\351 envoy\351.", "Formulaire envoy\351.", "true")', 1000);	
				}
				else if (xhr.responseText == 'commandeErreur')
				{
					setTimeout('afficheLoading("Une erreur est survenue durant l\'envoi.", "Erreur", "false")', 500);
				}
				else if (xhr.responseText == 'noData')
				{		
					setTimeout('afficheLoading("Une erreur est survenue.", "Erreur", "false")', 500);
				}
				else
				{
					setTimeout('afficheLoading("Une erreur est survenue, veuillez essayer de nouveau.", "Erreur", "false")', 500);	
				}
			}
		}
		xhr.open("POST",url,true);
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.send(parametres);
	}
}

function checkInput(el)
{
	if (el.value.length > 0)
	{
		if (el.id == 'email')// test si c'est un champs contenant un email
		{
			if (!isEmail(el.value))
			{
				changeClassInput(el, 'inputAlert');
				//alert("le courriel saisie est invalide");
			}
			else
			{
				changeClassInput(el, 'input');
				majuscule('email');
			}
		}
		else
		{
			if (el.tagName == 'TEXTAREA')
				changeClassInput(el, 'textarea');
			else
				changeClassInput(el, 'input');
			majuscule('email');
		}
	}
	else
	{
		if (el.tagName == 'TEXTAREA')
			changeClassInput(el, 'textareaAlert');
		else
			changeClassInput(el, 'inputAlert');
	}
}

function verif()
{
	var pass = true;
	$("#combo").find("textarea").each(function(){
		if ($(this).val().length <= 0)
		{
			$(this).addClass('inputAlert');
			$(this).removeClass('input');
			pass = false;
		}
		else
		{
			$(this).addClass('input');
			$(this).removeClass('inputAlert');
		}
	});	
	
	$("#combo").find("input").each(function(){
		if ($(this).val().length <= 0)
		{
			$(this).addClass('inputAlert');
			$(this).removeClass('input');
			pass = false;
		}
		else
		{
			if ($(this).attr("id") == 'email')// test si c'est un champs contenant un email
			{
				if (!isEmail($(this).val()))
				{
					$(this).addClass('inputAlert');
					$(this).removeClass('input');
					pass = false;
				}
				else
				{
					$(this).addClass('input');
					$(this).removeClass('inputAlert');
				}
			}
			else
			{
				$(this).addClass('input');
				$(this).removeClass('inputAlert');
			}
		}
	});


	$("#combo").find("select").each(function(){
		if ($(this).children("option:selected").text().length <= 0)
		{			
			$(this).addClass('selectAlert');
			$(this).removeClass('select');
			pass = false;
		}
		else
		{
			$(this).addClass('select');
			$(this).removeClass('selectAlert');
		}
	});	
	return pass;
}

function verifInput(el, typeInput)
{
	if (typeInput == 'select')
	{
		if (el.children("option:selected").text().length <= 0)
		{			
			el.addClass('selectAlert');
			el.removeClass('select');
		}
		else
		{
			el.addClass('select');
			el.removeClass('selectAlert');
		}	
	}
	else if (typeInput == 'textarea')
	{
		if (el.val().length <= 0)
		{
			el.addClass('textareaAlert');
			el.removeClass('textarea');
		}
		else
		{
			el.addClass('textarea');
			el.removeClass('textareaAlert');
		}		
	}
	else
	{
		if (el.val().length <= 0)
		{
			el.addClass('inputAlert');
			el.removeClass('input');
		}
		else
		{
			el.addClass('input');
			el.removeClass('inputAlert');
		}		
	}
}

function changeClassInput(el, valClass)
{
	el.className = valClass;	
}

function isEmail(value) 
{  
	var verif = /^[^@]+@(([\w\-]+\.){1,4}[a-zA-Z]{2,4}|(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5]))$/
	if (verif.test(value))
	{	
		return true;
	}
	else
	{		
		return false;
	}
}

function afficheLoading(alertTexte, titre, fermer)
{			  
	$.unblockUI();
	jAlert(alertTexte, titre, 
	function(r) 
	{
		if (fermer == 'true')
		{						
			
		}		
	});		
}

function majuscule(id, valeur)
{
	//var elm = $("email").val();
	//$("email").toUpperCase();
	//$("#email").val() = $("#email").val().toUpperCase();
}
