// ==================================================================================
// ACCESSIBLE VALIDATION FORM SCRIPT: 
// Sergi Meseguer http://zigotica.com/
// under CC license http://creativecommons.org/licenses/by-sa/2.0/
// tutorial and change log:  http://zigotica.com/validform/
// Requires EXTRAS namespace (addEvent, addClass, removeClass, getElementsByClass)
// ==================================================================================

  
VALID = {
	
	tieFormEvents : function() {
		// customize your own messages:
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		VALID.compulsory = "Debe rellenar los siguientes campos obligatorios (*) o con formato incorrecto:\n";
		VALID.goodurl = "la URL debe empezar por http://";
		VALID.goodemail = "el correo electrónico debe tener el formato nombre@dominio.ext";
		VALID.gooddni = "el DNI / NIE no tiene formato correcto";
		VALID.gooddate = "la fecha debe tener formato dd-mm-aaaa o dd/mm/aaaa";
		VALID.goodnum = "el valor debe ser numérico";
		VALID.range = "se requiere un rango (";
		VALID.defecto = "el campo no tiene formato correcto";
		VALID.labeled = "el campo no debe tener el mismo valor que el título";
		VALID.goodgroup = "el grupo requiere por lo menos un campo correcto";
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

		var forms = document.getElementsByTagName('form');
		for (var a = 0; (form = forms[a]); a++) {
			form.onsubmit = VALID.checkForm;
			if(!form.id) alert("id must be added to all forms");
		}
		
		// chequeo de campos para efectos
		
	var inputs = document.getElementsByTagName('input');
    var type;
    var id;
    for (var i=0; i<inputs.length; i++) {
      type = inputs[i].getAttribute('type');
      
      if (type == 'text') {
          addListener(inputs[i], 'focus', focointhis, false);         
          addListener(inputs[i], 'blur', no_focointhis, false);
      }      
      /*
      if (type == 'password') {
          addListener(inputs[i], 'focus', focointhis, false);
          addListener(inputs[i], 'mouseover', focointhis, false);
          addListener(inputs[i], 'mouseout', no_focointhis, false);
          addListener(inputs[i], 'blur', no_focointhis, false);
      }
	  if (type == 'checkbox') {
          addListener(inputs[i], 'focus', focointhis, false);
          addListener(inputs[i], 'mouseover', focointhis, false);
          addListener(inputs[i], 'mouseout', no_focointhis, false);
          addListener(inputs[i], 'blur', no_focointhis, false);
      }
      */
    }
		
		
	}, 

	checkForm : function(e) {
	   
		// hacking IE events:
		var e = (e) ? e : window.event ;
		var target = (e.target) ? e.target : e.srcElement ; 
		
		VALID.badformat = [];
		VALID.tmpbadradioboxes = [];
		
		var areas = target.getElementsByTagName('textarea');
		for (var i = 0; (area = areas[i]); i++) {
			VALID.checkfield(area, target); 
		}
		var inputs = target.getElementsByTagName('input');
		for (var i = 0; (input = inputs[i]); i++) {
		 
			if(input.type != "submit" && input.type != "reset" && input.type != "image") 
			VALID.checkfield(input, target);
			 
		}
		var sels = target.getElementsByTagName('select');
		for (var i = 0; (sel = sels[i]); i++) {
			VALID.checkfield(sel, target); 
		}
		var fields = target.getElementsByTagName('fieldset');
		for (var i = 0; (field = fields[i]); i++) {
			if(field.className.indexOf("required") > -1) VALID.checkFieldset(field); 
		}

		
		var remaining = [];

		var requireds = EXTRAS.getElementsByClass('problem',target,0); 
		for (var i = 0; i < requireds.length; i++) {
			valor = requireds[i].title;
			remaining.push("\n"+valor)
		}
		
		
		if(remaining.length > 0) {
			alert(VALID.compulsory + VALID.badformat);
			return false; // stop submission!
		}
		else return true; // do submit
		
		
	},

	checkfield : function(target, parentform) {
		node = (parentform) ? parentform : document;
		
		var label;
		var labels = node.getElementsByTagName('label');
		
		for (var i = 0; i < labels.length; i++) if (labels[i].htmlFor == target.name) label =  labels[i]; 
		

		//step 1: checking presence
		// if radio or checkboxes are required within a label, any of its input fields must be checked
		var ok = 0;
		if(target.type=="radio" || target.type=="checkbox") {
			VALID.checkInputsGroup(label, node); 
			return;
		}
		else if(target.type!="radio" && target.type!="checkbox"){
			// select, textarea, input text or input password use this:
			if (target.value.length != 0) ok = 1; 
		}
		
		if (ok == 1)  {
		//step 2: checking data format (normal text is default)
			if(target.value != label.title) VALID.checkFormat(label, target);
			else if(target.value == label.title) VALID.markBadFormat(label, VALID.labeled);
			else VALID.markGood(label);
		}
		else if (ok == 0) VALID.markBadFormat(label);
	},

	checkInputsGroup : function(group, form) {
		var OK = 0;
		var tmp = VALID.tmpbadradioboxes; 
		var grtmp = 0; 	
		
		var radiochecks = form.getElementsByTagName('input');
		for (var r=0; r < radiochecks.length; r++) {
			if(radiochecks[r].name == group.htmlFor && radiochecks[r].checked) {
					OK = 1; 
					break;
			}
		}
		if (OK == 1) {
			VALID.markGood(group); 
			for(var i = tmp.length - 1; i == 0; i --) if(tmp[i] == group.htmlFor) tmp[i] = null; 
		} 
		else if(OK == 0) {
			VALID.tmpbadradioboxes.push(group.htmlFor);
			for(var i = 0; i < tmp.length; i ++) if(tmp[i] == group.htmlFor) grtmp += 1; 
			if(grtmp == 1) VALID.markBadFormat(group); 
		}
	},
	
	checkFieldset : function(group) {
		var OK = 0;
		var labels = group.getElementsByTagName('label'); 
		for (var i = 0; (label = labels[i]); i++) if(label.className.indexOf("completed") > -1) OK = 1; 
		if(OK == 0) VALID.markBadFormat(group); 			
		else VALID.markGood(group);
	},
	
	checkFormat : function (label, elm){
		var format = elm.alt;
		var value = elm.value;
		var check, errmsg;
			var tmp = format.split("|"); 
			var format = (tmp.length > 0) ? tmp[0] : format;
			var minlen = (tmp[1])?tmp[1]:null; 
			var maxlen = (tmp[2])?tmp[2]:null;
			var min = (tmp[3])?tmp[3]:null; 
			var max = (tmp[4])?tmp[4]:null;

		switch(format) {
			case "url":
				check = /http:\/\//i; 
				errmsg = VALID.goodurl;
				break;
			case "email":
				// http://regexlib.com/UserPatterns.aspx?authorId=1758
			    	check = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/i;
				errmsg = VALID.goodemail;
				break;
			case "dni":
				// http://regexlib.com/REDetails.aspx?regexp_id=997
				value = elm.value = value.toUpperCase();
				check = /^(X(-|\.)?0?\d{7}(-|\.)?[A-Z]|[A-Z](-|\.)?\d{7}(-|\.)?[0-9A-Z]|\d{8}(-|\.)?[A-Z])$/;
				errmsg = VALID.gooddni;
				break;
			case "date":
				check = /(0[1-9]|[12][0-9]|3[01])([-/])(0[1-9]|1[012])\2(19|20)\d\d/;
				errmsg = VALID.gooddate;
				break;
			case "num":
				check = (minlen != null && maxlen != null)? eval('/^[0-9]{'+minlen+','+maxlen+'}$/') : (minlen != null)? eval('/[0-9]{'+minlen+',}/') : /[0-9]/ ;
				errmsg = VALID.goodnum;
				if(min != null) errmsg += " " + VALID.range + min + ">= n <= " + max + ")";
				break;
			case "text":
				check = (minlen != null && maxlen != null)? eval('/^[0-9a-z_]{'+minlen+','+maxlen+'}$/i') : (minlen != null)? eval('/[0-9a-z_]{'+minlen+',}/i') : /[0-9a-z_]/i ;
				errmsg = (min != null) ? VALID.range + min + ">= x <= " + max + ")" : VALID.defecto;
				
				
				break;
			default:
				check = /[0-9a-z_]/ ;
				errmsg = VALID.defecto;
				break;
		}
		
		var range = (format == "text" && min != null && value >= min && max != null && value <= max) ? true : (format == "text" && min != null && max == null && value >= min) ? true : (format == "num" && min != null && parseInt(value) >= parseInt(min) && max != null && parseInt(value) <= parseInt(max)) ? true : (format == "num" && min != null && max == null && parseInt(value) >= parseInt(min)) ? true : (min == null && max == null) ? true : false;
		
		if (check.test(value) && range) VALID.markGood(label);
		else VALID.markBadFormat(label, errmsg);
	},
	
	markGood : function(elm) {
		EXTRAS.removeClass(elm, 'problem');
		EXTRAS.addClass(elm, 'completed');
	},
	
	markBadFormat : function(elm, errmsg) {
		var compulsory = "";
		EXTRAS.removeClass(elm, 'completed');
		if(elm.className.indexOf("required") > -1) compulsory = "(*) "; 
		
		if(elm.tagName == "FIELDSET") {
			VALID.badformat.push("\n" + compulsory + elm.title + ": " + VALID.goodgroup);
			EXTRAS.addClass(elm, 'problem');
		}
		else if(elm.tagName == "LABEL" && errmsg != undefined) {
			VALID.badformat.push("\n" + compulsory + elm.title + ": " + errmsg);
			EXTRAS.addClass(elm, 'problem');
		}
		else if(elm.tagName == "LABEL" && elm.className.indexOf("required") > -1 && errmsg == undefined) {
			VALID.badformat.push("\n" + compulsory + elm.title);
			EXTRAS.addClass(elm, 'problem');
		}
		else if(elm.tagName == "LABEL" && elm.className.indexOf("required") == -1 && errmsg == undefined) {
			EXTRAS.removeClass(elm, 'problem'); // non compulsory fields that become empty
		}
	}
	
}
//***************************


var url =window.location.href;

var idioma = getIdioma();

function getIdioma() {
   
    if ( url.search('internacional') == -1) return "es"; 
    else return "en";
}
function restaurar() {

    if (idioma=='en') return "Search";
    else return "Buscar";

}
function addListener(element, type, expression, bubbling)
{
  bubbling = bubbling || false;
  if(window.addEventListener) { // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
  } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
  } else return false;
}




function focoin(elemento) {
    if(elemento.style != null) {        
        //elemento.style.color = "#FFFFFF";
       
       if (elemento.id == 'texto_buscador_rapido')   elemento.value = "";      
        
    }
    /*
    var nodeName = elemento.nodeName;
    if (nodeName == 'SELECT') {
        var child = elemento.firstChild;
        while (child != null) {
            if (child.className == 'letraroja') child.className = 'letrarojaB';
            child = child.nextSibling;
        }
    }*/
}

function no_focoin(elemento) {
    var toElem;
    try {
        toElem = window.event.toElement;
    }
    catch (error) {
        toElem = null;
    }
    if ( navigator.userAgent.indexOf('Firefox') != -1 ) {
       
       
       if ((elemento.id == 'texto_buscador_rapido') &&  (elemento.value == "" )) 
        elemento.value = restaurar();   
      
      
        
    }
    else { 
        if ( toElem != null || window.event.type == 'blur' ) {
          
        if ((elemento.id == 'texto_buscador_rapido') &&  (elemento.value == "" )) 
        elemento.value = restaurar();  
       
       
        }
    }
}



function focointhis(e) {
    if (!e) {
        e = (typeof window != "undefined" && window && window.event);
    }
    if (e) {
        var elemento;
        if (document.all) elemento = event.srcElement;
        else elemento = e.target;
        focoin(elemento);
    }
}
function no_focointhis(e) {
    if (!e) {
        e = (typeof window != "undefined" && window && window.event);
    }
    if (e) {
        var elemento;
        if (document.all) elemento = event.srcElement;
        else elemento = e.target;
        no_focoin(elemento);
    }
}



// ************************************************************
// (C) Andrea Giammarchi webreflection.blogspot.com
function onContent(f){
var a=onContent,b=navigator.userAgent,d=document,w=window,c="onContent",e="addEventListener",o="opera",r="readyState",
s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,".",c,"()}'></scr","ipt>");
a[c]=(function(o){return function(){a[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(a[c]);
if(d[e])d[e]("DOMContentLoaded",a[c],false);
if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))(function(){/loaded|complete/.test(d[r])?a[c]():setTimeout(arguments.callee,1)})();
else if(/MSIE/i.test(b))d.write(s);
};
// ************************************************************

if(document.getElementsByTagName) {
 
	onContent(function() {VALID.tieFormEvents()});
}

