// JavaScript Document

function $(id){ return document.getElementById(id)}

function readMoreHeadText(option){
//This function open the hidden head text in index
// 1 - Visible  0 - Hidden

	if (option == 1){
		if ($("div_headText2").style.overflow == "visible"){
			$("div_headText2").style.overflow = "hidden";
		}else{
			$("div_headText2").style.overflow = "visible";
		}
	}else{
		$("div_headText2").style.overflow = "hidden";
		window.scrollTo(0,0);
	}
	
}

function popUp(URL,w,h) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=0,width='+w+',height='+h);");
Xpos=(screen.width/2)-700; 
Ypos=(screen.height/2)-715; 
}

//to control the subject change combo box

function changeSubject(url){
	window.open(url,'_parent')
}

//to control the selection mark for main menu
//The user will have a mark on the neath of his/her main menu selection selection

function selectionMark(option){
	
	alert (option);	
	
}

//Code to work with documents layers

function hiddenDivDocuments(nameDiv){
	
		$("div_policiesDoc").style.visibility = "hidden";
		$("div_policiesDoc").style.position = "absolute";
		$("div_newslettDoc").style.visibility = "hidden";
		$("div_newslettDoc").style.position = "absolute";
		$("div_parentsDoc").style.visibility = "hidden";
		$("div_parentsDoc").style.position = "absolute";
		$("div_pupilsDoc").style.visibility = "hidden";
		$("div_pupilsDoc").style.position = "absolute";
		$("div_othersDoc").style.visibility = "hidden";
		$("div_othersDoc").style.position = "absolute";
		$(nameDiv).style.visibility = "visible";
		$(nameDiv).style.position = "static";		
}

//Code to work with census data proteccion layers and pages each layer

//First layers

function hiddenDivNumPagesLayer(nameDiv,controlNLayer,numPage){ 
		//Work with pages buttons
		var visibleLayer = $("controlLayer").value;
		var visiblePage = $("controlPage").value;
		
		$("div_layer"+visibleLayer+"PagesCmds").style.visibility = "hidden";
		$("div_Layer"+visibleLayer+"Page"+visiblePage).style.visibility = "hidden";
		$("div_Layer"+visibleLayer+"Page"+visiblePage).style.position = "absolute";
		
		//save the user selection layer
		$("controlLayer").value = controlNLayer;
		$("controlPage").value = numPage;
		
		//change to visible the user selection
		$(nameDiv).style.visibility = "visible";
		$("div_Layer"+controlNLayer+"Page"+numPage).style.visibility = "visible";
		//$("div_layer"+controlNLayer+"Page"+numPage).style.visibility = = "visible";
		$("div_Layer"+controlNLayer+"Page"+numPage).style.position = "static";
		
	
	

}
function breadcrumbs(){
  sURL = new String;
  bits = new Object;
  var x = 0;
  var stop = 0;
  var output = "<a href=\"/\">Home</a>  >  ";
  sURL = location.href;
  sURL = sURL.slice(8,sURL.length);
  chunkStart = sURL.indexOf("/");
  sURL = sURL.slice(chunkStart+1,sURL.length)
  while(!stop){
    chunkStart = sURL.indexOf("/");
    if (chunkStart != -1){
      bits[x] = sURL.slice(0,chunkStart)
      sURL = sURL.slice(chunkStart+1,sURL.length);
    }else{
      stop = 1;
    }
    x++;
  }
  for(var i in bits){
    output += "<a href=\"";
    for(y=1;y<x-i;y++){
      output += "../";
    }
    output += bits[i] + "/\">" + bits[i] + "</a>  >  ";
  }
  document.write(output + document.title);
}

/* Function to control the change news in index */
function change_photo(n,photo,WHS){ //WHS will have the class name to get the rigth photo size, landspace, portrait or square
switch(n){
	case 1 :
		$("img_news").src = "images/news/thumbnails/"+photo;
		$("img_news").className = WHS;
		//("li_news1").style.backgroundImage = "url(../../images/newsIndexBackground2.jpg)";
		$("li_news1").className = "li_news_text_1_onmouseover";
		$("li_news2").className = "li_news_text_2";
		$("li_news3").className = "li_news_text_3";
		break;
	case 2 : 
		document.getElementById("img_news").src = "images/news/thumbnails/"+photo;
		$("img_news").className = WHS;
		$("li_news2").className = "li_news_text_2_onmouseover";
		$("li_news1").className = "li_news_text_1";
		$("li_news3").className = "li_news_text_3";
		break;
	case 3 : 
		document.getElementById("img_news").src = "images/news/thumbnails/"+photo;
		$("img_news").className = WHS;
		$("li_news3").className= "li_news_text_3_onmouseover";
		$("li_news2").className = "li_news_text_2";
		$("li_news1").className = "li_news_text_1";
		break;
	}
}
//We use the next code to do the AJAX object
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; 
}
/////////////We will use this code to validate the newsletter sign_up///////////////////////////////

function validar_form_sing_up(){ 
/*
Con la siguiente variable controlaremos la validacion del formulario. Su valor sera el que se envia como 
respuesta a la funcion validar_form. POr lo tanto si al final de toda la validacion
esta varible es false, quiere decir que no hay errores y se puede enviar la informacion. POr el contrario si la variable 
devulve true quiere decir que se ha encontrado un error y no se puede enviar el formulario.
La inicializamos en false, es decir, que el formulario no tiene errores.

Asi mismo, lo primero que haremos sera comprobar media AJAX que el email no existe ya en nuestra base de datos
Si existe enviara un mensaje y el proceso se detendra.
*/

// Al entrar inicializamos el div con los mensajes de error  e imagenes error

$("error_msj").style.visibility = "hidden";
$("error_msj").innerHTML= "";
var error_text = "";

$("img_error_email").style.visibility = "hidden";
$("img_error_email_bis").style.visibility = "hidden";
$("img_error_name").style.visibility = "hidden";
$("img_error_terms").style.visibility = "hidden";

var control = false; 


return_name = validar_name($("signUp_name").value);
return_terms= validar_terms($("signUp_terms").name); //Nota que aqui recogemos el nombre del campo
return_email = validar_email($("signUp_email").value,$("signUp_email_bis").value);	
	
var error_text = "";							
		if (return_name== true) {
			error_text = error_text + "<div>There is an error with your name.Please no blank spaces.</div>";
			$("img_error_name").style.visibility = "visible";
			control = true; //Ponermos en control que hay un error 
		}
		if (return_email == true) {
			error_text = error_text + "<div>There is an error with your email.</div>";
			$("img_error_email").style.visibility = "visible";
			$("img_error_email_bis").style.visibility = "visible";
			control = true; //Ponermos en control que hay un error 
		}else{
			//Because the email is correct format we will past to the next test.
				//Next code will chech by AJAX if the email is already singn uo so if it is in our database alredy
					var email_comprobar = $("signUp_email").value;
					$("div_Ajax_control").innerHTML.value="";
					var ajax=nuevoAjax();
					ajax.open("POST", "../../website/mailing/unique_email.php?email="+email_comprobar, true);
					ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					ajax.send("ingreso="+email_comprobar);        
					ajax.onreadystatechange=function(){
						if (ajax.readyState==4){
							// Borro el contenido del input
							$("div_Ajax_control").innerHTML.value="";
							$("div_Ajax_control").innerHTML = ajax.responseText; //div_resultado
							/* Ajax will return to singUp_Ajax_control :
								1 - If the email is not in our database
								0- If the email it is in our database already - That means error
							*/	
						 }
					}
			if ($("singUp_Ajax_control").value == 0){
				    error_text = error_text + "<div>Your email has already been registered.</div>";
				    $("img_error_email").style.visibility = "visible";
				    $("img_error_email_bis").style.visibility = "visible";
				    control = true; //Ponermos en control que hay un error 
			}
		}
		if (return_terms == true) {
			error_text = error_text + "<div>You have to read the privacy policy terms.</div>";
			$("img_error_terms").style.visibility = "visible";
			control = true; //Ponermos en control que hay un error 
		}
		
$("error_msj").innerHTML= error_text;
$("error_msj").style.visibility = "visible";
return control;
}

/////////////We will use this code to validate the contact form///////////////////////////////

function validar_form_contact(){ 
/*
Con la siguiente variable controlaremos la validacion del formulario. Su valor sera el que se envia como 
respuesta a la funcion validar_form. POr lo tanto si al final de toda la validacion
esta varible es false, quiere decir que no hay errores y se puede enviar la informacion. POr el contrario si la variable 
devulve true quiere decir que se ha encontrado un error y no se puede enviar el formulario.
La inicializamos en false, es decir, que el formulario no tiene errores.
*/


// Al entrar inicializamos el div con los mensajes de error  e imagenes error

$("error_msj").style.visibility = "hidden";
$("error_msj").innerHTML= "";
var error_text = "";

$("img_error_email").style.visibility = "hidden";
$("img_error_email_bis").style.visibility = "hidden";
$("img_error_name").style.visibility = "hidden";
$("img_error_subject").style.visibility = "hidden";
$("img_error_terms").style.visibility = "hidden";

var control = false; 
	
return_name = validar_name($("contact_name").value);
return_email = validar_email($("contact_email").value,$("contact_email_bis").value);
return_terms= validar_terms($("contact_terms").name); //Nota que aqui recogemos el nombre del campo
return_subject = validar_subject($("contact_subject").value);

var error_text = "";							
	if (return_name== true) {
		error_text = error_text + "<div>There is an error with your name.Please no blank spaces.</div>";
		$("img_error_name").style.visibility = "visible";
		control = true; //Ponermos en control que hay un error 
	}
	if (return_email == true) {
		error_text = error_text + "<div>There is an error with your email.</div>";
		$("img_error_email").style.visibility = "visible";
		$("img_error_email_bis").style.visibility = "visible";
		control = true; //Ponermos en control que hay un error 
	}
	if (return_subject == true) {
		error_text = error_text + "<div>There is an error with the subject text.</div>";
		$("img_error_subject").style.visibility = "visible";
		control = true; //Ponermos en control que hay un error 
	}
	if (return_terms == true) {
		error_text = error_text + "<div>You have to read the privacy policy terms.</div>";
		$("img_error_terms").style.visibility = "visible";
		control = true; //Ponermos en control que hay un error 
	}
$("error_msj").innerHTML= error_text;
$("error_msj").style.visibility = "visible";
return control;

}

////////////////////////////////////////////// FUNCTION TO USE WITH FORMS VALIDATIONS //////////////////////////////////////////////////////

///////////////////////****************** VALIDAR EMAIL ******************///////////////////////
function validar_email(email_str, email_bis_str){
/*
Esta funcion conprobara si el email introducuido es valido.
 Si lo es devolvera true. Si no es valido devolvera false 
*/

//Lo priemro que comprobamos es si los dos email ( email e email bis son iguales. Si no lo son error
												  
if (email_str != email_bis_str){
	return true; // Devolvemos true ya qyese ha encontrado un error.
}else{
	var filter=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	
	// Comprobamos el email. Si hay un error i devolvemos error = true
	
		if (email_str.length > 100 ){ //Comprobamos la longitud del email aunque en el campo email hemos puesto el max permitido.
			return true; // Devolvemos true ya qyese ha encontrado un error.
		}else if (filter.test(email_str)){
			return false; // Devolvemos false ya que no hay error
		} else {
			return true; // Devolvemos true ya que se ha encontrado un error.
		}
	}
}
///////////////////////****************** VALIDAR NOMBRE y APELLIDOS ******************///////////////////////
function validar_name(name_str){
/*
Comprobamos el campo nombre y los apellidos. Los apellidos llegaran en don strings distintos para que el control sea independiente.
Que no sea menor que 3 caracteres ni mayor que 50
Que no tenga espacios en blanco
Que no sea un numero ni tenga _
Que no tenga numeros entre las letras ni caracteres extranos
*/
var filter_espacios_blanco = /^\s+$/; 
var filter_letras = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóú";
	if (name_str.length > 50  || name_str.length < 3 || filter_espacios_blanco.test(name_str)){ //Comprobamos la longitud del email aunque en el campo email hemos puesto el max permitido.
		return true; // Devolvemos true ya que se ha encontrado un error.
	}else if ((isNaN(name_str) == false) || (name_str == '_')){
		return true; // Devolvemos true ya que se ha encontrado un error.
	}else{
		for (i = 0; i < name_str.length; i++) {
    		ch = name_str.charAt(i); 
    		for (j = 0; j < filter_letras.length; j++)
     			 if (ch == filter_letras.charAt(j))
       			 	break;
    		if (j == filter_letras.length) { 
      			return true; // Devolvemos true ya que se ha encontrado un error.
      			break; 
    		}
		}
	}
}
///////////////////////****************** VALIDAR SUBJECT ******************///////////////////////
function validar_subject(subject_str){
/*
Comprobamos el campo nombre y los apellidos. Los apellidos llegaran en don strings distintos para que el control sea independiente.
Que no sea menor que 3 caracteres ni mayor que 50
Que no tenga espacios en blanco
Que no sea un numero ni tenga _
Que no tenga numeros entre las letras ni caracteres extranos
*/
	if (subject_str.length > 75  || subject_str.length < 3 ){ //Comprobamos la longitud del email aunque en el campo email hemos puesto el max permitido.
		return true; // Devolvemos true ya que se ha encontrado un error.
	}else if (isNaN(subject_str) == false){
		return true; // Devolvemos true ya que se ha encontrado un error.
	}
}
///////////////////////****************** VALIDAR terms - checkbox button******************///////////////////////
/*
Este codgio copmprobara que le usuario a seleccionario uno de los radio botones

*/
function validar_terms(name){
	if(!$(name).checked) {
  		return true; // Devolvemos true ya que se ha encontrado un error.
	}
}

