// JavaScript Document

function inicializa ()
{
	inicializa_general ();	
		
	//Enviar el formulario de la sección Solicítenos Información
	var enviar = document.getElementById("enviar");
	
	enviar.onclick = function ()
	{
		if (lenguaje=="esp")
			validar_formulario_productos();
		else
			validate_form_productos();
	}
	//Fin de enviar el formulario de la sección Solicítenos Información 	
	
	// Cambio del idioma de los elementos de texto
	var mapa_idioma = document.getElementById("mapa_idioma");
	mapa_idioma.onclick = function()
	{	
		if(lenguaje == "esp")
		{
			cambiar_lenguaje("../","eng");			
			lenguaje = "eng";			
		}
		else
		{			
			cambiar_lenguaje("../","esp");
			lenguaje = "esp";
		}		
		
		// Cargamos los textos en su idioma
		
		if(get_param("cdimodelo")!="")		
			cargar_contenedores("","cargar_variedades.php","php","cdimodelo=" + get_param("cdimodelo") + "&lenguaje=" + lenguaje);	
		else
			cargar_contenedores("","cargar_variedades.php","php","lenguaje=" + lenguaje);	
			
		// Colocamos la banderita según el lenguaje actual
		if (lenguaje=="esp")
			document.getElementById("logo_esp").src = "../imagenes/logo_eng.gif";
		else
			document.getElementById("logo_esp").src = "../imagenes/logo_esp.gif";	
			
		// Cargamos los campos del formulario según idioma
		cargar_campos_form(lenguaje);
			
	}
	// Fin de cambio del idioma de los elementos de texto	

	//Colocamos el pie de página
	document.getElementById("centro_fila_5").innerHTML = fecha();
	
	// Cargamos los distintos tipos de productos (nivel 2) en el div "centro_fila_3_productos_izq"
	if(get_param("cdimodelo")!="")		
		cargar_contenedores("","cargar_variedades.php","php","cdimodelo=" + get_param("cdimodelo") + "&lenguaje=" + lenguaje);	
	else
		cargar_contenedores("","cargar_variedades.php","php","lenguaje=" + lenguaje);			
	
	if (lenguaje=="esp")
		document.getElementById("logo_esp").src = "../imagenes/logo_eng.gif";
	else		
		document.getElementById("logo_esp").src = "../imagenes/logo_esp.gif";		
		
	// Cargamos los campos del formulario según idioma
	cargar_campos_form(lenguaje);
	
}

function cargar_campos_form (lenguaje_actual)
{
	// ******************************************************************************************
	// Parámetros de entrada:
	// lenguaje: lenguaje actual (esp , eng)
	// ------------------------------------------------------------------------------------------
	// Parámetros de salida:
	// No tiene
	// ------------------------------------------------------------------------------------------
	// Descripción:
	// Carga los campos del formulario según el lenguaje actual	
	// ******************************************************************************************	
	
	var campos_esp = new Array ("Nombre","Empresa","Teléfono","E-mail","Ciudad","País","Cantidad","Formato","Mensaje");
	var campos_eng = new Array ("Name","Company","Phone","E-mail","City","Country","Amount","Format","Message");
		
	for (i=0;i<9;i++)		
		if (lenguaje_actual=="esp")
			document.getElementById("campo_" + (i+1)).innerHTML = campos_esp[i];
		else
			document.getElementById("campo_" + (i+1)).innerHTML = campos_eng[i];		
			
	if (lenguaje_actual=="esp")
		document.getElementById("texto_form").innerHTML = "Si desea informaci&oacute;n adicional o est&aacute; interesado en adquirir este producto, env&iacute;enos este formulario con sus datos. Gracias.";
	else
		document.getElementById("texto_form").innerHTML = "If you wish some additional information or you are interested on buying this product, you can send us this form filled. Thank you.";
}

function cargar_contenedores (id_contenedor,url,carpeta,parametros)
{
	// ******************************************************************************************
	// Parámetros de entrada:
	// id_contenedor: id del elemento HTML que actuará como contenedor
	// url: nombre del script de servidor que obtendrá los datos
	// carpeta: nombre de la carpeta dónde se almacenan los scripts de servidor
	// parametros: lista de parámetros (dato=valor&dato=valor ...) que pasaremos al script
	// ------------------------------------------------------------------------------------------
	// Parámetros de salida:
	// No tiene
	// ------------------------------------------------------------------------------------------
	// Descripción:
	// Usamos AJAX para obtener el código HTML ya formateado mediante inyección de código vía ASP	
	// o PHP y cargarlo dentro de un contenedor HTML especificado por su id
	// ******************************************************************************************	
	
	var ahora = new Date();
	var cargador = creaAjax();
	var query_string;
	
	ahora = ahora.getHours().toString() + ahora.getMinutes().toString() + ahora.getSeconds().toString();
	
	if (parametros == "")
		query_string = "nuevo=" + ahora;	
	else
		query_string = parametros + "&nuevo=" + ahora;			
			
	url = carpeta + "/" + url;
	
	cargador.open("POST",url,true);
	cargador.onreadystatechange=function()
	{	
		document.getElementById("iconos_foto").style.visibility = "hidden";
		document.getElementById("foto_referencia").innerHTML = "<img src='watermark_formato.jpg' alt='' />";	
		if (id_contenedor=="")		
			document.getElementById("centro_fila_3_productos_izq").innerHTML = "<p style='text-align:center;margin-top:30px'><img src='../imagenes/cargando.gif'><br /><br /><strong>Cargando Datos ...</strong></p>";
		else
		{
			document.getElementById("foto_modelo").src = "watermark_producto.jpg";		
			document.getElementById("desc_modelo").innerHTML = "<p style='text-align:center;margin-top:90px'><img src='../imagenes/cargando.gif'><br /><br /><strong>Cargando Datos ...</strong></p>";				
		}
		
		if (cargador.readyState==4)
		{			
			var resultados = cargador.responseText.split("__");		
			
			var icn_lupa = document.getElementById("icn_lupa");
			var icn_mas = document.getElementById("icn_mas");
			
			icn_lupa.style.display = "inline";
			icn_mas.style.display = "inline";
			
			if (id_contenedor=="")
			{							
				
				document.getElementById("centro_fila_3_productos_izq").innerHTML = resultados[0];
				document.getElementById("nombre_modelo").innerHTML = resultados[1];			
				document.getElementById("desc_modelo").innerHTML = resultados[2];					
												
				if (resultados[3]=="watermark_producto.jpg")
				{
					document.getElementById("foto_modelo").src = resultados[3];	
					icn_lupa.style.display = "none";
					icn_mas.style.display = "none";
				}
				else
				{
					var fotos = resultados[3].split("#");
					if (fotos.length == 1)
					{
						document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + resultados[3];	
						//Iconos de lupa y más						
						
						icn_lupa.onclick = function ()
						{
							abre_ventana ("../panel/almacen/fotos/" + resultados[3]);
						}						
												
						icn_mas.style.display = "none";
						
						//Fin de Iconos de lupa y más
					}						
					else
					{
						document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[0];							
						
						var foto_actual="";							
																		
						icn_lupa.onclick = function ()
						{										
						
							for (i=0;i<document.getElementById("foto_modelo").src.length;i++)									
								if (document.getElementById("foto_modelo").src.substr (i+1,1) == "/")								
									foto_actual =  document.getElementById("foto_modelo").src.substr(i+2);
						
							if (foto_actual==fotos[0])
								abre_ventana ("../panel/almacen/fotos/" + fotos[0]);
							else
								abre_ventana ("../panel/almacen/fotos/" + fotos[1]);
						}							
						
						icn_mas.onclick = function ()
						{	
						
							for (i=0;i<document.getElementById("foto_modelo").src.length;i++)									
								if (document.getElementById("foto_modelo").src.substr (i+1,1) == "/")								
									foto_actual =  document.getElementById("foto_modelo").src.substr(i+2);
						
							if (foto_actual==fotos[0])
								document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[1];
							else
								document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[0];
						}
					}
				}															
								
				document.getElementById("formatos").innerHTML = resultados[4];
			}
			else
			{
				document.getElementById("nombre_modelo").innerHTML = resultados[0];			
				document.getElementById("desc_modelo").innerHTML = resultados[1];		
											
				if (resultados[2]=="watermark_producto.jpg")
				{	
					document.getElementById("foto_modelo").src = resultados[2];	
					icn_lupa.style.display = "none";
					icn_mas.style.display = "none";					
				}
				else
				{
					var fotos = resultados[2].split("#");
					if (fotos.length == 1)
					{
						document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + resultados[2];	
						//Iconos de lupa y más
						
						icn_lupa.onclick = function ()
						{
							abre_ventana ("../panel/almacen/fotos/" + resultados[2]);
						}						

						icn_mas.style.display = "none";
						
						//Fin de Iconos de lupa y más
					}						
					else
					{
						document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[0];							
						
						var foto_actual="";							
																		
						icn_lupa.onclick = function ()
						{										
						
							for (i=0;i<document.getElementById("foto_modelo").src.length;i++)									
								if (document.getElementById("foto_modelo").src.substr (i+1,1) == "/")								
									foto_actual =  document.getElementById("foto_modelo").src.substr(i+2);
						
							if (foto_actual==fotos[0])
								abre_ventana ("../panel/almacen/fotos/" + fotos[0]);
							else
								abre_ventana ("../panel/almacen/fotos/" + fotos[1]);
						}							
						
						icn_mas.onclick = function ()
						{	
						
							for (i=0;i<document.getElementById("foto_modelo").src.length;i++)									
								if (document.getElementById("foto_modelo").src.substr (i+1,1) == "/")								
									foto_actual =  document.getElementById("foto_modelo").src.substr(i+2);
						
							if (foto_actual==fotos[0])
								document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[1];
							else
								document.getElementById("foto_modelo").src = "../panel/almacen/fotos/thumb3/" + fotos[0];
						}
					}
				}
				
				document.getElementById("formatos").innerHTML = resultados[3];
			}
			
			document.getElementById("iconos_foto").style.visibility = "visible";
		}		
	}
	cargador.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	cargador.send(query_string);
}

function cambiar_foto_referencia()
{
	var ahora = new Date();
	var cargador = creaAjax();
	var query_string;
	
	ahora = ahora.getHours().toString() + ahora.getMinutes().toString() + ahora.getSeconds().toString();	
	
	query_string = "lenguaje=" + lenguaje + "&cdireferencia=" + document.formProductos.formato.value + "&nuevo=" + ahora;	
	
	cargador.open("POST","php/cambiar_foto_referencia.php",true);
	cargador.onreadystatechange=function()
	{	
	
		//document.getElementById("foto_referencia").innerHTML = "<img src='../imagenes/cargando.gif'>";				
	
		if (cargador.readyState==4)
		{
			document.getElementById("foto_referencia").innerHTML = cargador.responseText;			
		}
	}
	cargador.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	cargador.send(query_string);	
}

function borra_form()
{
	document.formProductos.reset();
	document.getElementById("foto_referencia").innerHTML = "<img src='watermark_formato.jpg' alt='' />";
}


function lee_raton(mievento, modelo, referencia, descripcion,lenguaje)
{	
	if (lenguaje=="esp")
		document.getElementById("boca_txt").innerHTML = "<p><strong><span style='color: #CC0000'>Variedad: " + modelo + "</span><br /><span style='color:#000000'>Formato: " + referencia + "</span></strong></p><p>" + descripcion + "</p><p><span style='color:#000000'>Haga clic sobre la foto para ampliarla</span></p>";
	else
		document.getElementById("boca_txt").innerHTML = "<p><strong><span style='color: #CC0000'>Type: " + modelo + "</span><br /><span style='color:#000000'>Format: " + referencia + "</span></strong></p><p>" + descripcion + "</p><p><span style='color:#000000'>Click on Image to zoom</span></p>";
	
	if (navigator.appName == "Microsoft Internet Explorer" || navigator.appName == "Opera")	
		document.getElementById("bocadillo").style.top = (document.body.parentNode.scrollTop + mievento.clientY-225)+"px";
	else
		document.getElementById("bocadillo").style.top = (window.scrollY + mievento.clientY-215)+"px";
		
	document.getElementById("bocadillo").style.left = (mievento.clientX - 103)+"px";
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		document.getElementById("bocadillo").style.filter="alpha(opacity='85')";
		document.getElementById("bocadillo").style.visibility="visible";
	}
	else
	{				
		document.getElementById("bocadillo").style.opacity = "0.85";
		document.getElementById("bocadillo").style.visibility="visible";
	}
}

function borra_bocadillo()
{
	document.getElementById("bocadillo").style.visibility="hidden";
	document.getElementById("bocadillo").style.top = "0px";
	document.getElementById("bocadillo").style.left = "0px";	
}

function enviar_email(parametros)
{	
	
	var ahora = new Date();
	var cargador = creaAjax();
	var query_string;
	
	ahora = ahora.getHours().toString() + ahora.getMinutes().toString() + ahora.getSeconds().toString();	
	
	query_string = parametros + "&nuevo=" + ahora;	
	
	cargador.open("POST","../enviar_email.php",true);
	cargador.onreadystatechange=function()
	{		
		
		document.getElementById("texto_form").innerHTML = "<p style='text-align:center;margin-top:30px'><img src='../imagenes/cargando.gif' align='absmiddle'><strong>&nbsp;Enviando Email ...</strong></p>";				
	
		if (cargador.readyState==4)
		{			
			if (lenguaje=="esp")
				document.getElementById("texto_form").innerHTML = "Si desea informaci&oacute;n adicional o est&aacute; interesado en adquirir este producto, env&iacute;enos este formulario con sus datos. Gracias.";
			else
				document.getElementById("texto_form").innerHTML = "If you wish some additional information or you are interested on buying this product, you can send us this form filled. Thank you.";
			
			if (cargador.responseText == "1")
				alert ("Su solicitud de información ha sido enviada con éxito. Le atenderemos con la mayor brevedad posible. Gracias por su interés.");
			else
				alert ("Su solicitud de información no ha sido enviada. Le rogamos vuelva a intentarlo más adelante. Disculpe las molestias.");
		}
	}
	cargador.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	cargador.send(query_string);
	
}

function validar_formulario_productos()
{
	var miFormu = document.getElementById("formProductos");
	
	if (miFormu.nombre.value == "")
	{
		alert("Introduzca un nombre");
		miFormu.nombre.focus();
	}
	else 
	{
		if (miFormu.telefono.value == "")
		{
			alert("Introduzca un teléfono");
			miFormu.telefono.focus();
		}
		else
		{
			if (isNaN(miFormu.telefono.value))
			{
				alert("Introduzca un n&uacute;mero de tel&eacute;fono v&aacute;lido");
				miFormu.telefono.value = "";
				miFormu.telefono.focus();
			}
			else 
			{
				if (miFormu.email.value == "")
				{
					alert("Introduzca un e-mail");
					miFormu.email.focus();
				}
				else 
				{
					if (miFormu.email.value.indexOf("@") == -1 || miFormu.email.value.indexOf(".") == -1)
					{
						alert("Introduzca una cuenta de e-mail válida");
						miFormu.email.value == "";
						miFormu.email.focus();
					}
					else 
					{
						if(miFormu.pais.value == "")
						{
							alert("Seleccione su país");
							miFormu.pais.focus();
						}
						else 
						{
							if (miFormu.mensaje.value == "")
							{
								alert("Escriba algún mensaje");
								miFormu.mensaje.focus();
							}
							else
							{
								if (miFormu.formato.value == "0")
								{
									alert("Seleccione algún formato");
									miFormu.mensaje.focus();
								}
								else
								{	
									//miFormu.submit();	
									
									var cadena = "nombre=" + escape(miFormu.nombre.value) + "&empresa=" + escape(miFormu.empresa.value) + "&telefono=" + escape(miFormu.telefono.value) + "&email=" + escape(miFormu.email.value) + "&ciudad=" + escape(miFormu.ciudad.value) + "&pais=" + escape(miFormu.pais.value) + "&variedad=" + escape(document.getElementById("solo_titulo").innerHTML) + "&cantidad=" + escape(miFormu.cantidad.value) + "&formato=" + escape(miFormu.formato.options[miFormu.formato.selectedIndex].text) + "&mensaje=" + escape(miFormu.mensaje.value) + "&tipo=0";																	
									enviar_email(cadena);
								}
							}
						}
					}
				}
			}
		}
	}
}

function validate_form_productos()
{
	var miFormu = document.getElementById("formProductos");
	
	if (miFormu.nombre.value == "")
	{
		alert("Please, insert name");
		miFormu.nombre.focus();
	}
	else 
	{
		if (miFormu.telefono.value == "")
		{
			alert("Please, insert phone");
			miFormu.telefono.focus();
		}
		else
		{
			if (isNaN(miFormu.telefono.value))
			{
				alert("Please, insert a valid phone number");
				miFormu.telefono.value = "";
				miFormu.telefono.focus();
			}
			else 
			{
				if (miFormu.email.value == "")
				{
					alert("Please, insert an e-mail");
					miFormu.email.focus();
				}
				else 
				{
					if (miFormu.email.value.indexOf("@") == -1 || miFormu.email.value.indexOf(".") == -1)
					{
						alert("Please, insert a valid e-mail");
						miFormu.email.value == "";
						miFormu.email.focus();
					}
					else 
					{
						if(miFormu.pais.value == "")
						{
							alert("Please, select your country");
							miFormu.pais.focus();
						}
						else 
						{
							if (miFormu.mensaje.value == "")
							{
								alert("Please, write some message");
								miFormu.mensaje.focus();
							}
							else
							{
								if (miFormu.formato.value == "0")
								{
									alert("Please, select format");
									miFormu.mensaje.focus();
								}
								else
								{	
									//miFormu.submit();	
									
									var cadena = "nombre=" + escape(miFormu.nombre.value) + "&empresa=" + escape(miFormu.empresa.value) + "&telefono=" + escape(miFormu.telefono.value) + "&email=" + escape(miFormu.email.value) + "&ciudad=" + escape(miFormu.ciudad.value) + "&pais=" + escape(miFormu.pais.value) + "&variedad=" + escape(document.getElementById("solo_titulo").innerHTML) + "&cantidad=" + escape(miFormu.cantidad.value) + "&formato=" + escape(miFormu.formato.options[miFormu.formato.selectedIndex].text) + "&mensaje=" + escape(miFormu.mensaje.value) + "&tipo=0";																	
									enviar_email(cadena,0);
								}
							}
						}
					}
				}
			}
		}
	}
}

function get_param( name ){
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null )
		return"";
	else
		return results[1];
}

//establecer_lenguaje ("../");
window.onload = inicializa;


