// JavaScript Document
// Funciones para validad campos de Nombre e E-mail

function getHTTPObject() {
    var xmlhttp;
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
       try {
          xmlhttp = new XMLHttpRequest();
       } catch (e) { xmlhttp = false; }
    }
    return xmlhttp;
}


window.onload = attachFormHandlers;

var gShow; //variable holding the id where feedback will be sent to.
var sUrl = "formvalidation.php?validationtype=ajax&val="; //url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
var gErrors = 0; //number of errors is set to none to begin with
var http = getHTTPObject(); //don't worry about this

function attachFormHandlers()
{
	/* var form = document.getElementById('frm') 

	if (document.getElementsByTagName)//make sure were on a newer browser
	{
		var objInput = document.getElementsByTagName('input');
		for (var iCounter=0; iCounter<objInput.length; iCounter++)
		objInput[iCounter].onblur = function(){return validateMe(this);} //attach the onchange to each input field
	}
	form.onsubmit = function(){
		return validate();
	} //attach validate() to the form*/
}

/*validateMe is the function called with onblur each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateMe(objInput) {

/*	sVal = objInput.value; //get value inside of input field
	
	sRules = objInput.className.split(' '); // get all the rules from the input box classname
	sRequired = sRules[1]; // determines if field is required or not
	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
    gShow = sRules[3]; //gShow is the td id where feedback is sent to.
	
	//alert(sRequired,"",sTypeCheck,"",gShow);
  
	//sends the rules and value to the asp page to be validated
	http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
  
	http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
	http.send(null);  */
}


function handleHttpResponse() {
	//if the process is completed, decide to do with the returned data
	/*if (http.readyState == 4) 
  	{
		
  		sResults = http.responseText.split(","); //results is now whatever the feedback from the asp page was
		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the asp page. 
    	document.getElementById(gShow).innerHTML = "";
		document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
  	}*/
}


function validate()
{
/*var tables; 

tables = document.getElementsByTagName('td')

	for (i=0; i<tables.length; i++)//loop through all the <td> elements 
	{
		// if the class name of that td element is rules check to see if there are error warnings
		if (tables[i].className == "rules")
		{
			//if there is a thank you or its blank then it passes
			if (tables[i].innerHTML == 'OK' || tables[i].innerHTML == '' )
			{
				tables[i].style.color = '#000000';//the color is changed to black or stays black
			}
			else
			{
				gErrors = gErrors + 1; //the error count increases by 1
				tables[i].style.color = '#ff0000';//error messages are changed to red
			}
		}
	}
		
	if (gErrors > 0)
	{
		//if there are any errors give a message
		alert ("Please make sure all fields are properly completed.  Errors are marked in red!");
		button = document.getElementById("button_1");
        button.disabled = true;
		gErrors = 0;// reset errors to 0
		return false;
	}
	else {
       button.disable = false;	
	   return true;
	}*/
}
//--

var b1 = false;
var b2 = false;

function nuevoAjax(){ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}

function cargaContenido()
{
	var valor = document.getElementById("select_0").options[document.getElementById("select_0").selectedIndex].value;
	if(valor == 0)
	{
		// Si el usuario eligio la opcion "Elige", no voy al servidor y pongo todo por defecto
		combo = document.getElementById("select_1");
		combo.length=0;
		var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Selecciona Pais...";
		combo.appendChild(nuevaOpcion);	combo.disabled=true;
	}
	else
	{
		ajax=nuevoAjax();
		ajax.open("GET", "maize_survey_process.php?seleccionado="+valor, true);
		ajax.onreadystatechange=function() 
		{ 
			if (ajax.readyState==1)
			{
				// Mientras carga elimino la opcion "Elige pais" y pongo una que dice "Cargando"
				combo=document.getElementById("select_1");
				combo.length=0;
				var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Cargando...";
				combo.appendChild(nuevaOpcion); combo.disabled=true;	
			}
			if (ajax.readyState==4)
			{ 
				document.getElementById("fila_2").innerHTML=ajax.responseText;
			} 
		}
		ajax.send(null);
	}
}

function EnableGuardar(){
	alert(document.getElementById("select_0").value);
	alert(document.getElementById("select_1").value);
   if ((document.getElementById("q1").value != 0) && (document.getElementById("q2").value != 0) && (document.getElementById("select_0").value != "---") && (document.getElementById("select_1").value != 0)) {
   //alert(document.getElementById("q1").value);
   //alert(document.getElementById("q2").value);
   button = document.getElementById("button_1");
   button.disabled = false;
   return true;
   } else { 
     //alert("Todos los campos del Formulario son requeridos, revisar cual hace falta por llenar.");
	 //return false;
   }
}

function  ResetForm(){
   document.location = "maize_survey.php"
}

function  ResetFormPt(){
   document.location = "maize_survey_pt.php"
}

//Funciones para validar fomularios en Español.
function OnlyCharacters(inputString) {
	var text1 = inputString.value;
	var c;
	var numeros = "0123456789!@#%$^&*()_+=-[]{};:'?.,<>";
	if ((text1 == "") || (text1.length < 2)) {
	    alert("El nombre no está completo."+"\n"+"Verifique y corrija correctamente");
  	    document.getElementById("name").value="";
        document.getElementById("name").focus();
		return false;
	} 
	else if (text1.length > 2) {
	for (n=0; n < text1.length; n++){
	   c = text1.substring(n, n+1);
	   if (numeros.indexOf(c,0) != -1) {
		alert("El nombre contiene caracteres inválidos"+"\n"+"Verifique y corrija correctamente");
    	document.getElementById("name").value="";
		document.getElementById("name").focus();   
		return false;
	    break;
	  }
	}
  } else { return true; }
  return true;
}

function CheckEmail(address) {
  var email = address.value;
  if ((email == "") || (email.indexOf ('@') == -1) || (email.indexOf ('.') == -1)) {
	  alert("E-mail no es correcto.\n"+"Verifique y corrija correctamente");
		document.getElementById("email").value="";
		document.getElementById("email").focus();    
		return false; 
		//break;
  } else { return true; } 
}

function CheckLength(textarea){
	var txt = textarea.value;
	if ((txt != "") && (txt.length > 1000)) {
	   alert("El comentario debe ser máximo de 1000 caracteres.\n"+"Hasta el momento su texto tiene "+txt.length+" caracteres.\n"+"Verifique y corrija correctamente");
	   document.getElementById("comments").focus();
	   return false;
	} else { return true; }
}

//Funciones para validar fomularios en Portugues.
function OnlyCharactersPt(inputString) {
	var text1 = inputString.value;
	var c;
	var numeros = "0123456789!@#%$^&*()_+=-[]{};:'?.,<>";
	if ((text1 == "") || (text1.length < 2)) {
	    alert("O nome está incompleto."+"\n"+"Verificá-lo e corrigir");
  	    document.getElementById("name").value="";
        document.getElementById("name").focus();
		return false;
	} 
	else if (text1.length > 2) {
	for (n=0; n < text1.length; n++){
	   c = text1.substring(n, n+1);
	   if (numeros.indexOf(c,0) != -1) {
		alert("O nome tem caráteres inválidos"+"\n"+"Verificá-lo e corrigir");
    	document.getElementById("name").value="";
		document.getElementById("name").focus();   
		return false;
	    break;
	  }
	}
  } else { return true; }
  return true;
}

function CheckEmailPt(address) {
  var email = address.value;
  if ((email == "") || (email.indexOf ('@') == -1) || (email.indexOf ('.') == -1)) {
	  alert("O E-mail está incompleto."+"\n"+"Verificá-lo e corrigir");
		document.getElementById("email").value="";
		document.getElementById("email").focus();    
		return false; 
		//break;
  } else { return true; } 
}

function CheckLengthPt(textarea){
	var txt = textarea.value;
	if ((txt != "") && (txt.length > 1000)) {
	   alert("O comentário deve ser pelo menos 1000 caráteres.\n"+"Até agora seu texto tem "+txt.length+" caráteres.\n"+"Verificá-lo e corrigir");
	   document.getElementById("comments").focus();
	   return false;
	} else { return true; }
}

//
function Validar() {
  b1 = OnlyCharacters(document.getElementById("name"));
  b2 = CheckEmail(document.getElementById("email"));
  b3 = CheckLength(document.getElementById("comments"));
  if ((document.getElementById("q1").value != 0) && (document.getElementById("q2").value != 0) && (document.getElementById("select_0").value != "---") && (document.getElementById("select_1").value != 0) && b1 && b2 && b3) {
   return true;
   }
   else {
	 //alert(document.getElementById("q1").value+","+document.getElementById("q2").value+","+document.getElementById("select_0").value+","+document.getElementById("select_1").value+","+b1+","+b2+","+b3)
     alert("Todos los campos del Formulario son requeridos o los comentarios sobrepasan el límite de 1000 caracteres.\n"+"Revisar nuevamente para poder procesar la información.");
	 return false;
   }
}

function ValidarPt() {
  b1 = OnlyCharactersPt(document.getElementById("name"));
  b2 = CheckEmailPt(document.getElementById("email"));
  b3 = CheckLengthPt(document.getElementById("comments"));
  if ((document.getElementById("q1").value != 0) && (document.getElementById("q2").value != 0) && (document.getElementById("select_0").value != "---") && (document.getElementById("select_1").value != 0) && b1 && b2 && b3) {
   return true;
   }
   else {
	 //alert(document.getElementById("q1").value+","+document.getElementById("q2").value+","+document.getElementById("select_0").value+","+document.getElementById("select_1").value+","+b1+","+b2+","+b3)
     alert("Todos os campos neste formulário são requeridos ou os comentários têm mais de 1000 caráteres.\n"+"Revê-lo outra vez para emiti-lo corretamente.");
	 return false;
   }
}