window.onload = function () {
	
	var links = $$("a[class=mailClasificado]");
	var divs = $$("div[class=divEnviarConsulta]");


	links.each(function(opcion) {

		var id = opcion.id.replace("link_", "");
		opcion.onclick = function () {
			
			var ventana = $("div_" + id);
			
			for (var i=0; i<divs.length; i++) {
				divs[i].hide();
			}
			ventana.style.display = "block";
			$("cerrar_"+id).onclick = function () { ventana.hide(); };
			
			cargarFormulario();
			
			
			
			function cargarFormulario () {
				archivo = "clasificados_enviar_consulta.php?id="+id;
				if (idUsuario)
					archivo += "&idUsuario="+idUsuario;
				$Ajax(archivo, {
					  onfinish: function (html) {
						  $("contenidoDiv_"+id).innerHTML = html;
						  paso1(html);
						  opcion.onclick = paso1;
					  }
				});
			}
			
			
			function paso1 (html) {
				for (var i=0; i<divs.length; i++) {
					divs[i].hide();
				}
				ventana.style.display = "block"
				
				var formulario = $("form_"+id);
				formulario.focusFirstElement();
				
				
				$("submit_"+id).onclick = chequear;
				
				
				function chequear () {
					var elementos = $$("#form_" + id + " .camposForm");
					var mensajeTemp = "";
					
					var tituloError = "Los siguientes campos están incompletos o tienen errores.\n_______________________________________";
					
					for (var i=0; i<elementos.length; i++) {
						var elemento = elementos[i];
						
						if (elemento.name == "email") {
							if (!(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(elemento.value))) {
								mensajeTemp += "\n"+elemento.name; 
							}
						}
						
						else if (elemento.value == "" || (/^\s+$/.test(elemento.value))) {
							mensajeTemp += "\n"+elemento.name; 
						}
					
					}
					
					if (mensajeTemp != "") {
						mensajeError = tituloError + mensajeTemp;
						mensajeError += "\n_______________________________________\nCompletalos y volvé a intentar."; 
						alert(mensajeError);
						elementos[0].focus();
					}
					else
						paso2();
				}
					
					
				
				function paso2() {
					this.disabled = "disabled";
					this.value = "Enviando...";
					var valores = formulario.serialize();
					$Ajax("clasificados_enviar_consulta.php?id="+id, {
						metodo: $metodo.POST,
						parametros: valores,
						onfinish: function (html) {
							$("contenidoDiv_"+id).innerHTML = html;
							$("link_"+id).onclick = cargarFormulario;
						}
						  
					});
					
				}
					
					
				
			}	
		}
		
	});
	/*
	function esconderVentana (ventana) {
		document.onclick = function (e) {
			e = e || event
			var target = e.target || e.srcElement
			do {
				if (ventana == target) {
					// Click occured inside the box, do nothing.
					return
				}
				target = target.parentNode
			} while (target)
			// Click was outside the box, hide it.
			ventana.style.display = "none"
		}
	}
	*/
	
}