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;
}

String.prototype.trim = function() { return this.replace(/^[\s]+|[\s]+$/g,'') }
String.prototype.numOfCharacters = function(character){
	var rep = 0;
	for(var i=0; i<=this.length-1;i++) if(this.charAt(i) == character) rep++;
	return rep;
}

var behaviours = {
	setEventHeaderSearch:function(){
		document.getElementById("header").getElementsByTagName("input")[0].onfocus = function(){ this.value = "";}
	}
			
	
			
}

var fixes={
	setLinkPrint:function(){	
		var obj = document.getElementById("pageOptions");
		var firstChild = obj.getElementsByTagName("li")[0];
		var liElement = document.createElement("li");
		var aElement = document.createElement("a");
		aElement.href = "javascript:window.print()";
		aElement.appendChild(document.createTextNode(literal["imprimir"]))
		liElement.appendChild(aElement);
		liElement.className = "print";
		obj.insertBefore(liElement,firstChild);		
	},
	setMsgError:function(){
		var obj = document.getElementById("error").getElementsByTagName("div")[0];
		var divElement = document.createElement("div");
		divElement.className = "fix sp";
		divElement.appendChild(document.createTextNode(""));
		obj.appendChild(divElement);
	},
	setBackRecommend:function(){
		var obj = document.getElementById("recommendPage");
		var forms = obj.getElementsByTagName("form");
		var parent = obj.parentNode;
		var spanElement = document.createElement("span");
		var spanElement2 = document.createElement("span");
		var aElement = document.createElement("a");
		spanElement.className = "btn";
		aElement.appendChild(document.createTextNode(literal["volver"]));
		aElement.href = (forms.length != 0) ? "javascript:history.back()" : "javascript:history.go(-2)";
		spanElement2.appendChild(aElement);
		spanElement.appendChild(spanElement2);		
		parent.appendChild(spanElement);
	},
	setTxtInfo:function(){
		var obj = document.getElementById("text");
		var description = document.getElementsByClassName("description",obj)[0];
		var uls = description.getElementsByTagName("ul");
		for(var i = 1; i < uls.length; i++) uls[i].className = "reset";		
	}		
}
var curves={
	createMainCurves:function(){
		var obj = document.getElementById("wrapperContent");
		var obj2 = document.getElementById("wrapperFooter");
		var cTopLeft = cTopRight = cBottomLeft = cBottomRight = null;		
		cTopLeft = curves.createElementsCurves("cLeftTop");
		cTopRight = curves.createElementsCurves("cRightTop");
		cBottomLeft = curves.createElementsCurves("cLeftBottom");
		cBottomRight = curves.createElementsCurves("cRightBottom");
		obj.appendChild(cTopLeft);
		obj.appendChild(cTopRight);
		obj2.appendChild(cBottomLeft);
		obj2.appendChild(cBottomRight);
		obj2.appendChild(cTopLeft.cloneNode(true));
		obj2.appendChild(cTopRight.cloneNode(true));		
	},
	createGeneralCurves:function(obj){
		var cTLeft = cTRight = cBLeft = cBRight = null;
		cTLeft = curves.createElementsCurves("cTLeft");
		cTRight = curves.createElementsCurves("cTRight");
		cBLeft = curves.createElementsCurves("cBLeft");
		cBRight = curves.createElementsCurves("cBRight");
		obj.appendChild(cTLeft);
		obj.appendChild(cTRight);
		obj.appendChild(cBLeft);
		obj.appendChild(cBRight);
	},	
	createAddressesDirectory:function(){
		var obj = document.getElementById("directory");			
		var uls = obj.getElementsByTagName("ul");
		var title = hType1 = hType2 = cLeft = cRight = null;			
		title = document.getElementsByClassName("title", obj);
		if(uls.length != 0){
			hType1 = uls[0].getElementsByTagName("h4");
			for(var i = 0; i < hType1.length; i++){			
				cLeft = curves.createElementsCurves("cLeft");
				cRight = curves.createElementsCurves("cRight");
				hType1[i].appendChild(cLeft);
				hType1[i].appendChild(cRight);
				cLeft = cRight = null;
			}

		}
		for(var i = 0; i < title.length; i++){			
			cLeft = curves.createElementsCurves("cLeft");
			cRight = curves.createElementsCurves("cRight");				
			title[i].appendChild(cLeft);
			title[i].appendChild(cRight);
			cLeft = cRight = null;
		}

	},
	createGalleryCurves:function(){
		var obj = document.getElementById("createGalleryCurves");		
		var blocks = document.getElementsByClassName("title", obj)
		var cLeft = cRight = null;		
		for(var i = 0; i < blocks.length; i++){
			cLeft = curves.createElementsCurves("cLeft");
			cRight = curves.createElementsCurves("cRight");
			blocks[i].appendChild(cLeft);
			blocks[i].appendChild(cRight);
			cLeft = cRight = null;
		}		
	},
	createReferences:function(){
		var obj = document.getElementById("searchFormContent");				
		if(obj.className == "type2"){
			cLeft = curves.createElementsCurves("cLeft");
			cRight = curves.createElementsCurves("cRight");
			obj.appendChild(cLeft);
			obj.appendChild(cRight);		
		}				
	},
	createElementsCurves:function(style){
		var element = document.createElement("div");
		element.className = style + " sp";
		element.appendChild(document.createTextNode(" "));
		return element;
	}
}

var gallery = {
	media:null,
	history:null,
	init:function(){
		var obj = $("#thumb");
		var aElements = $(obj).find("a");
		gallery.media = $("#detailItem").find(".innerDetail");
		for(var i = 0; i < aElements.length; i++) {
			aElements[i].onclick = function(i){
				return function(e){
					if(gallery.history) $(gallery.history).toggleClass("current");
					$(this).toggleClass("current");					
					gallery.showMedia(this, i);
					gallery.history = this;
					return false;
				};
			}(i);
		}
	},
	showMedia:function(obj,idx){
		var item = galleryItems[idx].src;		
		$(gallery.media).empty();		
		if(item.indexOf(".swf") == -1){
			$(gallery.media).append(gallery.createImg(galleryItems[idx]));
			//$("#detailItem").find(".btn").eq(0).hide();
		}else{
			gallery.createSwf(galleryItems[idx]);	
			/*$("#detailItem").find(".btn").eq(0).show();
			$("#detailItem").find(".btn").eq(0).find("a").eq(0).attr("href",galleryItems[idx].srcTxt);*/
		}
		$("#text").empty();
		$("#text").html("<p>" + galleryItems[idx].txt + "</p>");
		
	},
	createImg:function(data){
		var img = document.createElement("img");
		img.src = data.src;
		img.width = 415;
		img.height = 229;
		img.alt = data.alt;
		return img;
	},
	createSwf:function(data){
		var s1 = new SWFObject("/swf/mediaplayer.swf","single","415","229","7");
		s1.addParam("allowfullscreen","true");
		s1.addVariable("file",data.src);
		s1.addVariable("image",data.image);
		s1.addVariable("width","415");
		s1.addVariable("height","229");
		s1.addVariable("wmode", "transparent");
		s1.addVariable("bgcolor", "#ffffff");
		s1.write("player1");
						
	}
}

/* validaciones de formularios */
var formsValidations = {
	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();
	},
	validaFormRecommend:function(){
		var f = document.forms.formRecommend;		
		var errorTxt = aux = "";
		var okMailsAmigo = true;
		if(f.nombre.value == "") errorTxt += literal["recommend"][0];
		if(f.mail.value == "") errorTxt += literal["recommend"][1];
		else{
			if(!regularExpressions.isValidEmail(f.mail.value)) errorTxt += literal["recommend"][4];		
		}
		if(f.destino.value == "") errorTxt += literal["recommend"][2];		
		if (f.destino.value.numOfCharacters("@") == 0 && f.destino.value != "") errorTxt += literal["recommend"][5];
		else {			
			aux = f.destino.value.replace(/,/g, " ");
			mailsAmigo = aux.split(" ");
			for (i = 0; i < mailsAmigo.length && okMailsAmigo; i++) {				
				if (mailsAmigo[i].trim() == "") {
					okMailsAmigo = true;
					continue;
				}
				okMailsAmigo = regularExpressions.isValidEmail(mailsAmigo[i]);
			}
			if (!okMailsAmigo) errorTxt += literal["recommend"][5];
			else {
				if (aux.numOfCharacters("@") > 1 && f.destino.value.numOfCharacters(",") != f.destino.value.numOfCharacters("@") - 1) errorTxt += literal["recommend"][6];
			}
		}
		if(f.comentarios.value == "") errorTxt += literal["recommend"][3];		
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, document.getElementById("formRecommend"));
			return false;
		}
	},
	validaContactForm:function(){
		var f = document.forms.formContact;		
		var errorTxt = "";
		if(f.nombre.value == "") errorTxt += literal["contactPromo"][0];
		if(f.apellidos.value == "") errorTxt += literal["contactPromo"][1];
		if(f.mail.value == "") errorTxt += literal["contactPromo"][2];
		else{
			if(!regularExpressions.isValidEmail(f.mail.value))  errorTxt += literal["contactPromo"][3];
		}		
		if(document.getElementById("medio")){
			if(f.medio.value == "") errorTxt += literal["contactPromo"][4];
		}
		if(f.motivo.value == "") errorTxt += literal["contactPromo"][5];		
		else{
			if(f.motivo.value.length > 250)  errorTxt += literal["contactPromo"][6];
		}
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, document.getElementById("formContact"));
			return false;
		}
	},
	validaSearchContentForm:function(){
		var f = document.forms.searchFormContent;		
		var errorTxt = "";
		if(f.actividad.selectedIndex == 0) errorTxt += literal["formProjects"][0];
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, document.getElementById("searchFormContent"));
			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)},
	esCif:function(c){
		if (!/^[A-Za-z0-9]{9}$/.test(c) || !/^[ABCDEFGHKLMNPQS]/.test(c)) 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;
	}
}

var carruseles = {	
	mycarousel_initCallback:function(carousel) {	
		var clicks = 1;
	    var pages = parseInt(carousel.size()) - 1;  	
		if($("#prev")) $("#prev").css("visibility", "hidden");
	    jQuery('#next').bind('click', function() {
	        carousel.next();
			clicks++;
			carruseles.updatePaging(clicks,pages);
	        return false;
	    });
				
	    jQuery('#prev').bind('click', function() {
	        carousel.prev();
			clicks--;
			carruseles.updatePaging(clicks,pages);
	        return false;
	    });
	},
	updatePaging:function(clicks, pages){
		var prev = $("#prev");		
		var next = $("#next");
		if(clicks == 1) {
			$(prev).css("visibility", "hidden");
			$(next).css("visibility", "visible");
		}
		else if(clicks != pages) {		
			$(prev).css("visibility", "visible");
			$(next).css("visibility", "visible");
		}
		else if(clicks == pages) {		
			$(prev).css("visibility", "visible");
			$(next).css("visibility", "hidden");
		}		
	},
	references:{
		init:function(){			
			$("#carrusel").find(".jcarousel-scroll").eq(0).show();
			$("#thumb").css("padding-left","0")
		    jQuery("#thumb").jcarousel({
	    	    scroll: 1,
	        	initCallback: carruseles.mycarousel_initCallback,
		        buttonNextHTML: null,
		        buttonPrevHTML: null
	    	});
		}		
	},
	info:{
		clicks:1,
		items:0,
		pages:0,						
		mycarousel_initCallback:function(carousel) {			
		    carruseles.info.items = carousel.size()				
		    jQuery('#next').bind('click', function() {
				carousel.startAuto(0);
		        carousel.next();				
		        return false;
		    });
					
		    jQuery('#prev').bind('click', function() {
				carousel.startAuto(0);
		        carousel.prev();				
		        return false;
		    });
			carousel.clip.hover(function() {
		        carousel.stopAuto();
		    }, function() {
			        carousel.startAuto();
			 });

		},
		mycarousel_itemVisibleInCallbackAfterAnimation:function (carousel, item, idx, state) {
		  if (state == "next") carruseles.info.clicks++;
		  else carruseles.info.clicks--;
 		  if(idx == 1) carruseles.info.clicks = 1;	  
 		   carruseles.updatePaging(carruseles.info.clicks,carruseles.info.items);		   
		   $("#text").parent().find(".number").eq(0).text(carruseles.info.clicks + literal["de"] + carruseles.info.items)
		   
		},
		init: function(){
			$("#thumb").toggleClass("reset");
			$("#thumb").parent().find(".number").eq(0).toggleClass("reset");
			if($("#prev")) $("#prev").css("visibility", "hidden");
			jQuery("#thumb").jcarousel({
				scroll: 1,
				auto: 5,
				wrap:'last',
				initCallback: carruseles.info.mycarousel_initCallback,
				buttonNextHTML: null,
				buttonPrevHTML: null,
				itemVisibleInCallback: {		            
        		    onAfterAnimation:  carruseles.info.mycarousel_itemVisibleInCallbackAfterAnimation
		        }			
			});
		}
	},
	galleries:{
		clicks:1,
		items:0,
		pages:0,
		mycarousel_initCallback:function(carousel) {
			carruseles.galleries.items = carousel.size()
			carruseles.galleries.pages = parseInt(carruseles.galleries.items) - 2; 
			
			 carousel.clip.hover(function() {
		        carousel.stopAuto();
			    }, function() {
			        carousel.startAuto();
				 });				
		    jQuery('#next').bind('click', function() {
		        carousel.next();														
				//carousel.startAuto(0);
				carruseles.galleries.clicks++;
				carruseles.updatePaging(carruseles.galleries.clicks,carruseles.galleries.pages);				
		        return false;
		    });						
		    jQuery('#prev').bind('click', function() {
		        carousel.prev();
				 //carousel.startAuto(0);
				carruseles.galleries.clicks--;					
				carruseles.updatePaging(carruseles.galleries.clicks,carruseles.galleries.pages);				
		        return false;
		    });
		},		
		init:function(){
			$("#thumb").toggleClass("reset");
			$("#thumb").parent().find(".number").eq(0).toggleClass("reset");	
			$("#prev").css("visibility","hidden");
		   jQuery("#thumb").jcarousel({
	    	    scroll: 1,
				//auto: 2,
		        //wrap: 'last',
	        	initCallback: carruseles.galleries.mycarousel_initCallback,		        								
				buttonNextHTML: null,
		        buttonPrevHTML: null
	    	});
		}
	}
}

var gmaps = {
	ubicaciones:{
		init:function(){			
			if (GBrowserIsCompatible()) gmaps.load(document.getElementById("ubicacion"))			
		}
	},
	buscador:{
		init:function(){
			if (GBrowserIsCompatible()) gmaps.load(document.getElementById("gmapsWrap"))
		},
		espania:function(){			
			var PuntoCero = new GLatLng(40.416632788688474, -3.7040340900421143);			
			map.setCenter(PuntoCero, 4);
		},		
		madrid:function(){			
			var PuntoCero = new GLatLng(40.38839687388361, -3.72161865234375);
			map.setCenter(PuntoCero, 9);
		},
		africa:function(){			
			var PuntoCero = new GLatLng(3.6888551431470478, 21.09375);		
			map.setCenter(PuntoCero, 2);
		},
		america:function(){			
			var PuntoCero = new GLatLng(41.50857729743935, -102.65625);
			map.setCenter(PuntoCero, 3);
		},
		americaC:function(){			
			var PuntoCero = new GLatLng(16.63619187839765, -84.814453125);
			map.setCenter(PuntoCero, 4);
		},
		americaS:function(){			
			var PuntoCero = new GLatLng(-24.206889622398023, -60.29296875);
			map.setCenter(PuntoCero, 3);
		},
		asia:function(){			
			var PuntoCero = new GLatLng(53.74871079689897, 91.40625);
			map.setCenter(PuntoCero, 2);
		},
		europa:function(){			
			var PuntoCero = new GLatLng(50.12057809796007, 16.171875);
			map.setCenter(PuntoCero, 4);
		},
		oceania:function(){			
			var PuntoCero = new GLatLng(-3.1624555302378474, 129.375);
			map.setCenter(PuntoCero, 2);
		},
		mundo:function(){
			var PuntoCero = new GLatLng(40, -3);
			map.setCenter(PuntoCero, 1);
		},
		events:function(){
			var nacional = document.getElementById("nacional").getElementsByTagName("a")[0];			
			var africa = document.getElementById("africa").getElementsByTagName("a")[0];
			var america = document.getElementById("america").getElementsByTagName("a")[0];
			var americaC = document.getElementById("americaC").getElementsByTagName("a")[0];
			var americaS = document.getElementById("americaS").getElementsByTagName("a")[0];
			var madrid = document.getElementById("madrid").getElementsByTagName("a")[0];
			var asia = document.getElementById("asia").getElementsByTagName("a")[0];
			var europa = document.getElementById("europa").getElementsByTagName("a")[0];
			var oceania = document.getElementById("oceania").getElementsByTagName("a")[0];
			nacional.onclick = function(){
				gmaps.buscador.espania();
				return false;
			}
			madrid.onclick = function(){
				gmaps.buscador.madrid();
				return false;
			}			
			africa.onclick = function(){
				gmaps.buscador.africa();
				return false;
			}
			america.onclick = function(){
				gmaps.buscador.america();
				return false;
			}
			americaC.onclick = function(){
				gmaps.buscador.americaC();
				return false;
			}
			americaS.onclick = function(){
				gmaps.buscador.americaS();
				return false;
			}
			asia.onclick = function(){
				gmaps.buscador.asia();
				return false;
			}
			europa.onclick = function(){
				gmaps.buscador.europa();
				return false;
			}
			oceania.onclick = function(){
				gmaps.buscador.oceania();
				return false;
			}			
		}
	},
	load:function(obj){
		var map = new GMap2(obj);		
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl(1));
		map.enableDoubleClickZoom();					
		var PuntoCero = new GLatLng(latitud, longitud);
		map.setCenter(PuntoCero, zoom);					
		var markerD2 = new GMarker(PuntoCero, {icon:G_DEFAULT_ICON, draggable: false});
		map.addOverlay(markerD2);
	}
}

var load={
	existeId:function(cid){	
		if(document.getElementById(cid)) return true;		
		return false;
	}
}
// activación de carruseles
jQuery(document).ready(function() {	
	curves.createMainCurves();
	behaviours.setEventHeaderSearch();
	if (load.existeId("info")) carruseles.info.init();		
	if (load.existeId("galleryProject")) carruseles.galleries.init();		
	if(load.existeId("pageOptions")) fixes.setLinkPrint();		
	if(load.existeId("error")){
		curves.createGeneralCurves(document.getElementById("error").getElementsByTagName("div")[0]);
		fixes.setMsgError();
	}
	if(load.existeId("carrusel")) carruseles.references.init();
	if(load.existeId("searchFormContent")) curves.createReferences();
	if(load.existeId("directory")) curves.createAddressesDirectory();
	if(load.existeId("galleryIntro")) curves.createGalleryCurves(); 	
	if (load.existeId("recommendPage")) fixes.setBackRecommend();		
	if(load.existeId("formRecommend")) document.getElementById("formRecommend").onsubmit = formsValidations.validaFormRecommend 
	if(load.existeId("detailGalleryProject")) gallery.init();
	if(load.existeId("formContact")) document.getElementById("formContact").onsubmit = formsValidations.validaContactForm;			
	if(load.existeId("searchFormContent") && load.existeId("actividad")){
		document.getElementById("searchFormContent").onsubmit = formsValidations.validaSearchContentForm;	
	}
	if(load.existeId("info")) fixes.setTxtInfo();
	if(load.existeId("mapDirectory")) {
		gmaps.buscador.mundo();
		gmaps.buscador.events();
	}
	if(load.existeId("gmaps")) gmaps.buscador.events();

});		

