var W3CDOM = (document.createElement && document.getElementsByTagName);

document.getElementsByClassName = function(className, container){
   var data = tags = [];
   var obj = document.getElementById("wrapper");
   var node = aux = null;
	var strClassName = className.replace(/\-/g, "\\-");
    var pattern = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	if(container) node = (typeof(container) == "object") ? container : document.getElementById(container);
	else node = (obj) ? obj : document;
	aux = node.getElementsByTagName("*");
	tags = (document.all) ? node.all : aux;
   for(var i=0;i<tags.length;i++) { if(pattern.test(tags[i].className)) data.push(tags[i]);}
   return data;
}



var e = {
	addEvent : function(obj, evType, fn, useCapture){
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		}else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		}else {
			return false;
		}
	}
}

var curves={		
	roundModule:function(obj){
		var cTl = cTr = cBl = cBr = null;
		cTl = curves.createElementsCurves("cTl");			
		cTr = curves.createElementsCurves("cTr");
		cBl = curves.createElementsCurves("cBl");
		cBr = curves.createElementsCurves("cBr");
		obj.appendChild(cTl);
		obj.appendChild(cTr);
		obj.appendChild(cBl);
		obj.appendChild(cBr);
	},
	partialRoundModule:function(obj){
		var cTl = cTr = cBl = cBr = null;
		cTl = curves.createElementsCurves("cTl");			
		cTr = curves.createElementsCurves("cTr");		
		obj.appendChild(cTl);
		obj.appendChild(cTr);
	},
	roundModules:function(obj){
		for(var i = 0; i < obj.length; i++) curves.roundModule(obj[i]);
	},
	partialRoundModules:function(obj){
		for(var i = 0; i < obj.length; i++) curves.partialRoundModule(obj[i]);
	},
	createElementsCurves:function(style){
		var element = document.createElement("div");
		element.className = style + " sp";
		element.appendChild(document.createTextNode(" "));
		return element;
	}
}

var boletin = {
	creados:0,
	load:function(){
		var sel= null;
		if(sel=document.getElementById("numAlumnos")){
			sel.onchange=function(){	
//				if(sel.value>0)builder.alumno(sel.value);
				builder.alumno(sel.value);
			}		
		}
	}
}

var builder = {		
	datos:["nombre","apellidos","telefono","mail","cargo","depart"],
	literales:["Nombre* ","Apellidos* ","Teléfono *","Email* ","Cargo","Departamento"],
	total:0,
	alumno:function(cuantos){
		var txt= null;
		var e_ref = e_field = e_legend = e_strong = e_ul = e_li = null;
				if (builder.total>cuantos){
					destroyer.alumno(builder.total-cuantos);
					builder.total=cuantos;
				}
				else {
					for (j=builder.total;j<cuantos;j++){
						e_ref = document.getElementById("ref")
						e_field = document.createElement("fieldset");
						if(j%2!=0)
							e_field.className="frt";
						else
							e_field.className="flt";
						
						e_legend = document.createElement("legend");
						e_strong = document.createElement("strong");		
						txt=document.createTextNode("Datos persona "+(parseInt(j)+1));
						e_strong.appendChild(txt)
						
						e_ul = document.createElement("ul");			
				
							for(i=0;i<builder.datos.length;i++){
								e_li = document.createElement("li");
									
								e_label = document.createElement("label");
									e_label.htmlFor=builder.datos[i]+j;
									txt=document.createTextNode(builder.literales[i]);
									e_label.appendChild(txt)
								e_input = document.createElement("input");				
									e_input.type="text";
									e_input.className="txt";
									e_input.id=builder.datos[i]+j;
									e_input.name=builder.datos[i]+j;
					
								//creando...
								e_li.appendChild(e_label);
								e_li.appendChild(e_input);
								e_ul.appendChild(e_li);
							}
						
						
								
						//creando...
						e_legend.appendChild(e_strong);
						e_field.appendChild(e_legend);
						e_field.appendChild(e_ul);
						e_ref.appendChild(e_field);
					}
				
					builder.total=cuantos;
				}

		
		//console.log("builder.total: ", builder.total)
	}
}

var destroyer = {
	alumno:function(cuantos){
		//console.log("tengo que eliminar: ", cuantos)	
		e_ref = document.getElementById("ref");
		for (i=0;i<cuantos;i++)
			e_ref.removeChild(e_ref.lastChild)
		//eliminar los errores (si los hay)
		
	}
	
}

var formsValidations = {
	setMsgError_varios:function(txt, form,cadena){
		
		var parentForm = form.parentNode;		
		var msgError = document.getElementsByClassName("msgError", parentForm);
		var divElement = (msgError.length != 0) ? msgError[0] : document.createElement("div");		
		
		
			
		var ulElement = document.createElement("ul");
		var liElement = null;		
		var errors = txt.split("|");				
		divElement.className = "msgError"
		if(divElement.getElementsByTagName("ul").length != 0) divElement.removeChild(divElement.getElementsByTagName("ul")[0])
		for(var i = 0; i < errors.length - 1; i++){
			liElement = document.createElement("li");
			if(errors[i].indexOf("(#)")!=-1) liElement.className="txtError"			
			liElement.appendChild(document.createTextNode(errors[i]));
			ulElement.appendChild(liElement);
		}
		/*
		if(divElement.getElementsByTagName("span").length!=0) divElement.removeChild(divElement.getElementsByTagName("span")[0])
	
		var e_span = document.createElement("span");		
			e_span.className="tituloError";
			e_span.appendChild(document.createTextNode(cadena));
		divElement.appendChild(e_span);		*/

		
		divElement.appendChild(ulElement);		
		divElement.tabIndex = -1;
		if(msgError.length == 0) parentForm.insertBefore(divElement,form);
		divElement.focus();
	},
	setMsgError:function(txt, form){
		var parentForm = form.parentNode;		
		var msgError = document.getElementsByClassName("msgError", parentForm);
		var divElement = (msgError.length != 0) ? msgError[0] : document.createElement("div");		
		
		
			
		var ulElement = document.createElement("ul");
		var liElement = null;		
		var errors = txt.split("|");				
		divElement.className = "msgError"
		if(divElement.getElementsByTagName("ul").length != 0) divElement.removeChild(divElement.getElementsByTagName("ul")[0])
		for(var i = 0; i < errors.length - 1; i++){
			liElement = document.createElement("li");
			liElement.appendChild(document.createTextNode(errors[i]));
			ulElement.appendChild(liElement);
		}



		
		divElement.appendChild(ulElement);		
		divElement.tabIndex = -1;
		if(msgError.length == 0) parentForm.insertBefore(divElement,form);
		divElement.focus();
	},
	
	validaFormContact:function(){
		
		var f = document.getElementById("formContact");		
		var errorTxt = "";		
		
		
		if(f.ejemplares.value == "") errorTxt += "(!) El campo 'Nº de ejemplares' es obligatorio|";			
		else{
			if(!regularExpressions.esNumero(f.ejemplares.value))  errorTxt += "(!) El formato del campo 'Nº de ejemplares' no es correcto|";			
		}
		if(f.nombre.value == "") errorTxt += "(!) El campo 'Nombre' es obligatorio|";			
		if(f.apellidos.value == "") errorTxt += "(!) El campo 'Apellidos' es obligatorio|";			
		if(f.empresa.value == "") errorTxt += "(!) El campo 'Empresa' es obligatorio|";			
		if(f.direccion.value == "") errorTxt += "(!) El campo 'Dirección' es obligatorio|";
		if(f.localidad.value == "") errorTxt += "(!) El campo 'Localidad' es obligatorio|";		
		if(f.provincia.value == "") errorTxt += "(!) El campo 'Provincia' es obligatorio|";				
		if(f.cp.value == "") errorTxt += "(!) El campo 'Código Postal' es obligatorio|";	
		
		
							
		else{
			if(!regularExpressions.esCodigoPostal(f.cp.value))  errorTxt += "(!) El formato del campo 'Código Postal' no es correcto|";			
		}
		if(f.telefono .value == "") errorTxt += "(!) El campo 'Teléfono' es obligatorio|";		
		if(f.mail.value == "") errorTxt += "(!) El campo 'Email' es obligatorio|";
		else{
			if(!regularExpressions.isValidEmail(f.mail.value))  errorTxt += "(!) El formato del campo 'Email' no es correcto|";
		}	
		if(f.cif.value == "") errorTxt += "(!) El campo 'CIF' es obligatorio|";
		
		if(errorTxt != ""){			
/*			formsValidations.setMsgError(errorTxt, document.getElementById("formContact"),"Revise los siguientes errores:");*/
			formsValidations.setMsgError(errorTxt, document.getElementById("formContact"));
			return false;
		}
		
	},

	validaFormContact2:function(){
		
			var f = document.getElementById("formContact2");		
			var errorTxt = "";		
			var traza = f.traza.value;
			var traza2 = f.traza2.value;
			var traza3 = f.traza3.value;
			var traza4 = f.traza4.value;
			
		
			if(f.nombre.value == "") errorTxt += "(!) El campo 'Nombre' es obligatorio|";			
			if(f.apellidos.value == "") errorTxt += "(!) El campo 'Apellidos' es obligatorio|";			
			if(f.empresa.value == "") errorTxt += "(!) El campo 'Empresa' es obligatorio|";			
			if(f.direccion.value == "") errorTxt += "(!) El campo 'Dirección' es obligatorio|";
			if(f.localidad.value == "") errorTxt += "(!) El campo 'Localidad' es obligatorio|";		
			if(f.provincia.value == "") errorTxt += "(!) El campo 'Provincia' es obligatorio|";				
			if(f.cp.value == "") errorTxt += "(!) El campo 'Código Postal' es obligatorio|";	
		
		
							
			else{
				if(!regularExpressions.esCodigoPostal(f.cp.value))  errorTxt += "(!) El formato del campo 'Código Postal' no es correcto|";			
			}
			if(f.telefono .value == "") errorTxt += "(!) El campo 'Teléfono' es obligatorio|";		
			if(f.mail.value == "") errorTxt += "(!) El campo 'Email' es obligatorio|";
			else{
				if(!regularExpressions.isValidEmail(f.mail.value))  errorTxt += "(!) El formato del campo 'Email' no es correcto|";
			}	
			if(f.cif.value == "") errorTxt += "(!) El campo 'CIF' es obligatorio|";
		
			if(errorTxt != ""){			
				formsValidations.setMsgError(errorTxt, document.getElementById("formContact2"));
				return false;
			}
			else
			{	
			
				if ((traza !="") && (traza2 !=""))
				{
					
					if (traza2=="responsabilidad")
					{	
						pageTracker._trackPageview('/formulario/responsabilidad');
					}
					
					if (traza2=="herramientas")
					{	
						pageTracker._trackPageview('/formulario/herramientas');
					}
					
					if (traza2=="lascincoS")
					{	
						pageTracker._trackPageview('/formularios/ordenylimpieza/inscribete'); 
					}
					
				}
				return true;
			}
		
		},	
	validaBoletinForm:function(){
		
		var f = document.forms.formBoletin;		
		var errorTxt = "";
		var check = "";
		var traza = f.traza.value;
		var traza2 = f.traza2.value;
		var traza3 = f.traza3.value;
		var traza4 = f.traza4.value;
		
		/*particular*/			
		if(f.nombreP.value == "") check += "(!) El campo 'Nombre' es obligatorio|";			
		if(f.apellidosP.value == "") check += "(!) El campo 'Apellidos' es obligatorio|";			
		if(f.telefonoP.value == "") check += "(!) El campo 'Teléfono' es obligatorio|";			
	/*	if(f.mailP.value == "") check += "(!) El campo 'Email' es obligatorio|";
		else{
			if(!regularExpressions.isValidEmail(f.mailP.value))  check += "(!) El formato del campo 'Email' no es correcto|";
		}	*/					
		if(f.cargoP.value == "") check += "(!) El campo 'Cargo' es obligatorio|";
		if(f.departP.value == "") check += "(!) El campo 'Departamento' es obligatorio|";
		if(check!="") errorTxt += "(#)Errores en 'Datos del alumno 1 inscrito:'|" + check;
		check = "";
		
		/*empresa*/		
		if(f.empresa.value == "") check += "(!) El campo 'Empresa' es obligatorio|";			
		if(f.cif.value == "") check += "(!) El campo 'CIF' es obligatorio|";			
		if(f.direccion.value == "") check += "(!) El campo 'Dirección' es obligatorio|";			
		if(f.localidad.value == "") check += "(!) El campo 'Localidad' es obligatorio|";		
		if(f.provincia.value == "") check += "(!) El campo 'Provincia' es obligatorio|";		
		if(f.telefono .value == "") check += "(!) El campo 'Teléfono' es obligatorio|";		
		if(f.fax.value == "") check += "(!) El campo 'FAX' es obligatorio|";	
		
		if(!f.avisolegal.checked) errorTxt += "(!) Debe aceptar las condiciones de privacidad|";
		
		if(check!="") errorTxt += "(#)Errores en 'Datos de la empresa:'|" + check;			
		
		check = "";		
		/*persona que inscribe*/
		//alert(f.nombreI.value);
		if(f.nombreI.value == "") check += "(!) El campo 'Nombre' es obligatorio|";			
		if(f.apellidosI.value == "") check += "(!) El campo 'Apellidos' es obligatorio|";			
/*		if(f.mail_inscribe.value == "") check += "(!) El campo 'Email' es obligatorio|";
		else{
			if(!regularExpressions.isValidEmail(f.mail_inscribe.value))  check += "(!) El formato del campo 'Email' no es correcto|";
		}	*/					
		if(f.cargoI.value == "") check += "(!) El campo 'Cargo' es obligatorio|";
		//if(f.numAlumnos.value == 0) check += "(!) Debe seleccionar al menos un alumno para inscribir|";
		if(check!="") errorTxt += "(#)Errores en 'Datos de la persona que inscribe:'|" + check;
		check = "";
		
		
		/*datos personales*/
		var ref= document.getElementById("ref");
		var total= ref.getElementsByTagName("ul")
		var tip = null;
		for(i=0;i<total.length;i++){
			check = "";			
				if(document.getElementById("nombre"+i).value == "") check += "(!) El campo 'Nombre' es obligatorio|";				
				if(document.getElementById("apellidos"+i).value == "") check += "(!) El campo 'Apellidos' es obligatorio|";				
				if(document.getElementById("telefono"+i).value == "") check += "(!) El campo 'Teléfono' es obligatorio|";				
			/*	if(document.getElementById("mail"+i).value == "") check += "(!) El campo 'Email' es obligatorio|";		
				else{
					if(!regularExpressions.isValidEmail(document.getElementById("mail"+i).value))  check += "(!) El formato del campo 'Email' no es correcto|";
				}	*/
			if(check!="") errorTxt += "(#)Errores en 'Datos de la persona" +(i+1)+ ":'|" + check;				
			}
		
	
		if(errorTxt != "")
		{			
			formsValidations.setMsgError_varios(errorTxt, document.getElementById("formBoletin"));
			return false;
		}
		else
		{	
			if ((traza !="") && (traza2 !=""))
				{
					
					if (traza2=="responsabilidad")
					{	
						pageTracker._trackPageview('/formulario/responsabilidad');
					}
					else
					{
						pageTracker._trackPageview('/formulario/herramientas');
					}	
				}
				return true; 
		}	
		
		
		
	},
	validaFormInfo:function(){
		var f = document.forms.formInfo;
		var errorTxt = "";
		
		if (f.empresa.value == "") errorTxt += "(!) El campo 'Empresa' es obligatorio|";
		if(f.cif.value == "") errorTxt += "(!) El campo 'CIF / NIF ' es obligatorio|";
		else
			if(!regularExpressions.esCif(document.getElementById("cif").value) && !regularExpressions.esNif(document.getElementById("cif").value))errorTxt += "(!) El formato del campo 'CIF / NIF' no es correcto|";
			
		if(f.actividad.value == "") errorTxt += "(!) El campo 'Actividad' es obligatorio|";
		if(f.plantilla.value == "") errorTxt += "(!) El campo 'Plantilla' es obligatorio|";
		if(f.dire.value == "") errorTxt += "(!) El campo 'Dirección' es obligatorio|";
		if(f.poblacion.value == "") errorTxt += "(!) El campo 'Población' es obligatorio|";
		if(f.cp.value == "") errorTxt += "(!) El campo 'Código Postal' es obligatorio|";
		else
			if(!regularExpressions.esNumero(document.getElementById("cp").value))errorTxt += "(!) El formato del campo 'Código postal' tiene que ser numérico|";
			else
				if(f.cp.value.length != 5) errorTxt += "(!) El campo 'Código Postal' tiene que tener cinco dígitos|";
		
		if(f.tel.value == "") errorTxt += "(!) El campo 'Teléfono' es obligatorio|";
		else
			if(!regularExpressions.esNumero(document.getElementById("tel").value))errorTxt += "(!) El formato del campo 'Teléfono' tiene que ser numérico|";
			else
				if(f.tel.value.charAt(0) != 9 && f.tel.value.charAt(0) != 6 ) errorTxt += "(!) El campo 'Teléfono' tiene que empezar por 6 ó 9|";
				else
					if(f.tel.value.length != 9) errorTxt += "(!) El campo 'Teléfono' tiene que tener 9 dígitos|";
		
		if(f.mail.value != "" && !regularExpressions.isValidEmail(document.getElementById("mail").value))errorTxt += "(!) El formato del campo 'Email' no es correcto|";
		
		if(!f.info.checked) errorTxt += "(!) Debe aceptar las condiciones|";
		
		
		
		
		if(errorTxt != ""){			
			formsValidations.setMsgError_varios(errorTxt, document.getElementById("formInfo"));
			return false;
			
		}
	}	
}

/* expresiones regulares para validar formularios */

var regularExpressions = {	
	isValidEmail:function (str){
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		return (filter.test(str));
	},
	esCadena:function(c) { return /^[0-9A-Za-z-\/Ññ?É?ÓÚáéíóúÜüÄäËë?ïÖö´,'/\\t\n\r\s]+$/.test(c); },
	esAlfabetico:function(c){return /^([a-zA-Z])+$/.test(c);},
	esNumero:function(c){return /^[0-9]+$/.test(c);},
	esTelefono:function(c){return /^[0-9\s\+\-)(]+$/.test(c)},
	esCodigoPostal:function(c){return /^([0-4]{1}[1-9]{1}|10|20|30|40|50|51|52)([0-9]{3})+$/.test(c);},
	esCif:function(c){
		if (!/^[A-Za-z0-9]{9}$/.test(c.toUpperCase()) || (!/^[ABCDEFGHKLMNPQS]/.test(c.toUpperCase()))) return false;
		var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
		var digCrtl=c.charAt(c.length-1);
		var temp = 0;
		for(i=2;i<=6;i+=2 ) {
		      temp = temp + v1[ parseInt(c.substr(i-1,1)) ];
		      temp = temp + parseInt(c.substr(i,1));
		};
		temp = temp + v1[ parseInt(c.substr(7,1)) ];
		temp = (10 - ( temp % 10));
		if( temp == 10 ){if(!(digCrtl=="J" || digCrtl=="0")) return false;
		}else{if(digCrtl!=temp) return false; }
		return true;
	},
	esNif: function(c){
		if (!/^[0-9]{8}([A-Za-z]{1})$/.test(c)) 
			return false
		var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
		return (c.substr(8, 9).toUpperCase() == letras.charAt(c.substr(0, 8) % 23));
	}
}

function tabsMode(){
	var href = document.getElementsByTagName('a');
	for (var i=0; i<href.length; i++){
		href[i].onclick = function(e){
			switch(this.parentNode.className){
				case 'type2':
					var tabs = document.getElementById("tabsMode");
					document.getElementsByClassName('type1Sel',tabs)[0].className="type1";
					this.parentNode.className = 'type2Sel';
					document.getElementById("tab1fiels").style.display="none";
					document.getElementById("tab2fiels").style.display="block";
				break;
				case 'type1':
					var tabs = document.getElementById("tabsMode");
					document.getElementsByClassName('type2Sel',tabs)[0].className="type2";
					this.parentNode.className = 'type1Sel';
					document.getElementById("tab2fiels").style.display="none";
					document.getElementById("tab1fiels").style.display="block";
				break;
			}
		}
	}		
}

var behaviours = {
	desplegables:function(){
		var collapses = $(".collapse");
		var obj = $("#inner");
		var titulos = obj.find(".title");
		var that;
		titulos.each(function(){
			that = $(this);
			that.wrapInner("<a href=''></a>")
			that.find("a").bind("click",function(event){
				var aux = $(this).parent().next();
				aux.toggle();		
				event.preventDefault();
				event.stopPropagation();
			
			})
		})
		collapses.hide();
		collapses.append("<span class='close'><a href=''>Cerrar</a></span>");
		
		obj.find(".close a").bind("click",function(event){
		
			var aux = $(this).parents(".collapse");
			aux.hide();
			event.preventDefault();
			event.stopPropagation();
		
		})
	}
}

var load={
	existeId:function(cid){	
		if(document.getElementById(cid)) return true;		
		return false;
	},
	setEvents:function(){	
		curves.roundModule(document.getElementById("wrapper"));
		if (document.getElementsByClassName("roundModule", document.getElementById("bodyContent")).length != 0) curves.roundModules(document.getElementsByClassName("roundModule", document.getElementById("bodyContent")));
		if (document.getElementsByClassName("partialRoundModule", document.getElementById("bodyContent")).length != 0) curves.partialRoundModules(document.getElementsByClassName("partialRoundModule", document.getElementById("bodyContent")));
		if(load.existeId("formBoletin")) {		
			boletin.load();
			document.getElementById("formBoletin").onsubmit = formsValidations.validaBoletinForm;	
		}
		if(load.existeId("formContact"))document.getElementById("formContact").onsubmit = formsValidations.validaFormContact;
		if(load.existeId("formContact2"))document.getElementById("formContact2").onsubmit = formsValidations.validaFormContact2;
		if(load.existeId("formInfo"))document.getElementById("formInfo").onsubmit = formsValidations.validaFormInfo;
		if(load.existeId("tabsMode"))tabsMode();
		
	}
}

if(W3CDOM) e.addEvent(window, "load", load.setEvents, false);

jQuery(document).ready(function() {	
	if($(".collapse").length != 0) behaviours.desplegables();

})

