//global vars
if(navigator.userAgent.toLowerCase().indexOf("safari")==-1){
var i,j;
var iCookie = document.cookie.match(/var_i[^;]*(;|$)/);
if (iCookie != null) i = parseInt(iCookie[0].split("=")[1]);
else i = 0;
} else i = 0;

/*
$(document).ready(function(){

//cargamos tamaņo de fuente
var fontCookie = document.cookie.match(/fwi_fontSize[^;]*(;|$)/);
if (fontCookie != null)
{
	$("#primary-content").css("font", unescape(fontCookie[0].split("=")[1]));
	$("#secondary-content").css("font", unescape(fontCookie[0].split("=")[1]));
}

//rollovers #actions	
actions();
	imprimir();
	
	//validaciķ formulari contacte i submits dināmics
	if ($('.contacte')){
		contacte();
		submits();
	}
	

//canvi de layout per la resolucio
checkBrowserWidth();

//rollover .image_container
if ($('.image_container')) gallery();

//inicia la galeria
if (document.getElementById('photogallery')) galeria();

//incrementar y decrementar fuente
font();
if (document.getElementById('info')) informacio();
if (document.getElementById('enviar')) enviar();

//toggle calendario salones y seccion mapas
if (document.getElementById('maps') || document.getElementById('calendario_salones')) toggle();

//toggle buscado avanzado
if (document.getElementById('buscador')) buscador_avanzado();

//toggle mas_info
if (document.getElementById('link-form-mes-info')) mes_info();
	if (document.getElementById('link-form-mes-info')) mes_info();
	
});
*/

//$(document).resize(function(){
	/*if(typeof sIFR == "function"){
		sIFR.rollback();
	};*/
	
	//checkBrowserWidth();
	
	/*if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:"h2", sFlashSrc:"/resources/fonts/FranklinGothicBook.swf", sColor:"#000000", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#000000", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0",sWmode: "transparent"}));
		sIFR.replaceElement(named({sSelector:"h3", sFlashSrc:"/resources/fonts/FranklinGothicDemi.swf", sColor:"#000000", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#000000", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0",sWmode: "transparent"}));
		sIFR.replaceElement(named({sSelector:"h4", sFlashSrc:"/resources/fonts/FranklinGothicDemi.swf", sColor:"#000000", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#000000", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0",sWmode: "transparent"}));
		sIFR.replaceElement(named({sSelector:"#nav-institution li", sFlashSrc:"/resources/fonts/FranklinGothicBookCond.swf", sColor:"#8A8A8A", sLinkColor:"#8A8A8A", sBgColor:"#FFFFFF", sHoverColor:"#000000", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0"}));
		sIFR.replaceElement(named({sSelector:"#subnav li", sFlashSrc:"/resources/fonts/FranklinGothicBookCond.swf", sColor:"#8A8A8A", sLinkColor:"#8A8A8A", sBgColor:"#FFFFFF", sHoverColor:"#000000", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0"}));
	};*/
//});

checkBrowserWidth();

function actions(){
	$("#impresion").hover(function(){
		this.firstChild.style.visibility = 'visible';
		this.style.background = 'url(/resources/images/impresion.png) no-repeat center -22px';
	},function(){
		this.firstChild.style.visibility = 'hidden';
		this.style.background = 'url(/resources/images/impresion.png) no-repeat';
	});
	
	$("#info").hover(function(){
		this.firstChild.style.visibility = 'visible';
	},function(){
		this.firstChild.style.visibility = 'hidden';
	});
	
	$("#add_descargas").hover(function(){
		this.firstChild.style.visibility = 'visible';
		$(this).css('background','url(/resources/images/descargas.png) no-repeat center -22px');
	},function(){
		this.firstChild.style.visibility = 'hidden';
		$(this).css('background','url(/resources/images/descargas.png) no-repeat');
	});
	
	$("#increase_font").hover(function(){
		this.firstChild.style.visibility = 'visible';
		this.style.background = 'url(/resources/images/a+.png) no-repeat center -22px';
	},function(){
		this.firstChild.style.visibility = 'hidden';
		this.style.background = 'url(/resources/images/a+.png) no-repeat';
	});
	
	$("#decrease_font").hover(function(){
		this.firstChild.style.visibility = 'visible';
		this.style.background = 'url(/resources/images/a-.png) no-repeat center -22px';
	},function(){
		this.firstChild.style.visibility = 'hidden';
		this.style.background = 'url(/resources/images/a-.png) no-repeat';
	});
	
	$("#enviar").hover(function(){
		this.firstChild.style.visibility = 'visible';
		this.style.background = 'url(/resources/images/enviar.png) no-repeat center -21px';
	},function(){
		this.firstChild.style.visibility = 'hidden';
		this.style.background = 'url(/resources/images/enviar.png) no-repeat';
	});
		
	$("#info").hover(function(){
		this.firstChild.style.visibility = 'visible';
		this.style.background = 'url(/resources/images/informacion.png) no-repeat center -22px';
	},function(){
		this.firstChild.style.visibility = 'hidden';
		this.style.background = 'url(/resources/images/informacion.png) no-repeat';
	});
}

//rollover elementos galeria y menu desplegable
function gallery(){
	$('.image_container').hover(function(){
		/* BEGIN esto solo funciona en explorer */
		if(navigator.userAgent.toLowerCase().indexOf("msie") + 1) window.status = $("img",this).parent().get(0).href; //equivalente a this.getElementsByTagName("a")[0].href
		/* END esto solo funciona en explorer */
		$(this).addClass('image_container_hover');
	},function(){
		$(this).removeClass('image_container_hover');
	}).click(function(){
		location.href = $("img",this).parent().get(0).href; 
	});
	
	//desplegar/plegar capa option-layer en .image-container
	$(".option-layer").hover(function(){
		$("ul",this).removeClass("hidden");
	},function(){
		$("ul",this).addClass("hidden");
	});
}

//incremento y decremento fuente
function font(){
	//incremento de fuente
	$("#increase_font").click(function(){
		i++;
		if (i>3) i=3;
		switch(i){
			case 0: j=100; break;
			case 1: j=110; break;
			case 2: j=120; break;
			case 3: j=130; break;
		}
		
		$("#primary-content").css("font",j + "% 'Trebuchet MS'");
		$("#secondary-content").css("font",j + "% 'Trebuchet MS'");
		
		document.cookie = "fwi_fontSize=" + j + "% 'Trebuchet MS'";
		document.cookie = "var_i=" + i;
	});
	
	//decremento de fuente
	$("#decrease_font").click(function(){
		i--;
		if (i<0) i=0;
		switch(i){
			case 0: j=100; break;
			case 1: j=110; break;
			case 2: j=120; break;
			case 3: j=130; break;
		}

		$("#primary-content").css("font",j + "% 'Trebuchet MS'");
		$("#secondary-content").css("font",j + "% 'Trebuchet MS'");
		
		document.cookie = "fwi_fontSize=" + j + "% 'Trebuchet MS'";
		document.cookie = "var_i=" + i;
	});
}

// va a la pagina de enviar a un amigo
function enviar()
{
	$('#enviar').click(function(){
		window.location = $(this).find("a").get(0).href;
	});
}

function informacio()
{
	$('#info').click(function(){
		window.location = $(this).find("a").get(0).href;
	});
}

//toggle de calendario salones y mapas
function toggle(){
	$("#maps a.button-open, #calendario_salones a.button-open").click(function(){
		var ul = $(".content-toggle",this.parentNode);
		if (ul.is(":hidden")){
			$(".content-toggle:visible").each(function(){
				$(this).slideUp('slow');	
				//$(this).removeClass("button-close");
				//$(this).addClass("button-open");
				
			});
			ul.slideDown("slow");
			$(this).removeClass("button-open");
			$(this).addClass("button-close");
		}
		else{
			ul.slideUp("slow");
			$(this).removeClass("button-close");
			$(this).addClass("button-open");
		}
		return false;
	});
}

//toggle de buscador avanzado
function buscador_avanzado(){
	$("#buscador.advanced a.button-open").click(function(){
		var ul = $("fieldset#campos-busqueda-avanzada",this.parentNode.parentNode.parentNode);
		$("input.last-cercar",this.parentNode).css("visibility","hidden");
		if (ul.is(":hidden")){
			ul.slideDown("slow", button_down);
			$(this).removeClass("button-open");
			$(this).addClass("button-close");
			$("input.first-cercar",this.parentNode).css("visibility","hidden");
		}
		else{
			ul.slideUp("slow", button_up);
			$(this).removeClass("button-close");
			$(this).addClass("button-open");
			$("input.last-cercar",this.parentNode).css("visibility","hidden");
		}
		return false;
	});
}

function button_down(){
	$("input.last-cercar",this.parentNode).css("visibility","visible");
}

function button_up(){
	$("input.first-cercar",this.parentNode).css("visibility","visible");
}

//toggle mas info
function mas_info(){
	$('#link-form-mes-info').click(function(){
		var formulario = $('#form-mes-info',this.parentNode.parentNode);
		if (formulario.is(':hidden')){
			formulario.slideDown('slow');
		}
		else formulario.slideUp('slow');
	});
}

function galeria(){
	initPhotoGallery();
	$('#photogallery #thumbs a').click(function(){
		var at = this.title;
        var img = $('img', this).get(0).src.split('?');
        showPreview(img[0], this);
		document.getElementById('infoTXT').innerHTML=at;
		return false;
	});
}

	var slideSpeed = 4;	
	
	var largeImage = false;
	var imageToShow = false;
	var slideWidth = false;
	var thumbTotalWidth = false;
	var viewableWidth = false;
    var imageIndex = 0;
    var previousSlideWidth = 0;
    var nextSlideWidth = 120;
    var lastSlideWidth = 120;
	
	var currentActiveImage = false;
	var thumbDiv = false;
	var thumbSlideInProgress = false;
	
	var prev;
	var next;

	function initPhotoGallery()
	{
		prev = $('#photogallery #prev').css('visibility','hidden').css('cursor','pointer').click(moveThumbnails).get(0);
		next = $('#photogallery #next').css('cursor','pointer').click(moveThumbnails).get(0);
		largeImage = $('#photogallery #largeImage'); 
		var innerDiv = document.getElementById('thumbs_inner'); 
		thumbDiv = document.getElementById('thumbs_inner');
		thumbDiv.style.left = '0px';
		
		// muestra la descripcion de la primera foto al iniciar la galeria
		var int_description = $('#thumbs a',this).get(0).title;
		document.getElementById('infoTXT').innerHTML=int_description;

		var subDivs = thumbDiv.getElementsByTagName('img');
		thumbTotalWidth = 0;

		for (var i = 0; i < subDivs.length; i++) {
            thumbTotalWidth = thumbTotalWidth + innerDiv.getElementsByTagName('img')[i].offsetWidth + 10;
            if (i == subDivs.length - 1) {
                lastSlideWidth = innerDiv.getElementsByTagName('img')[i].offsetWidth + 10;
            }
		}
		thumbTotalWidth = thumbTotalWidth + 10; //mmm, hay un calculo en el bucle de antes que no tengo del todo controlado, por eso aņado estos 10px de margen, sino no se puede acceder al ultimo thumbnail

		viewableWidth = document.getElementById('thumbs').offsetWidth;
		currentActiveImage = thumbDiv.getElementsByTagName('a')[0];
		currentActiveImage.className='activeImage';
	}
	
	
	function moveThumbnails()
	{
        if (imageIndex > 0) {
            previousSlideWidth = document.getElementById('thumbs_inner').getElementsByTagName('img')[imageIndex - 1].offsetWidth + 10;
        }
        if (imageIndex <= document.getElementById('thumbs_inner').getElementsByTagName('img').length) {
            nextSlideWidth = document.getElementById('thumbs_inner').getElementsByTagName('img')[imageIndex].offsetWidth + 10;
        }
		if (thumbSlideInProgress) {
            return;
        }
		thumbSlideInProgress = true;
		if (this.id == 'prev') {
			next.style.visibility = 'visible';
			if (thumbDiv.style.left.replace('px', '') / 1 >= 0) {
				prev.style.visibility='hidden';
				thumbSlideInProgress = false;
				return;
			}
			slideThumbs(4, 0);
			imageIndex--;
		} else {
			prev.style.visibility = 'visible';
			var left = thumbDiv.style.left.replace('px', '') / 1;
			if (thumbTotalWidth < viewableWidth - left) {
				next.style.visibility = 'hidden';
				thumbSlideInProgress = false;
				return;
			}
			slideThumbs(-4, 0);
            imageIndex++;
		}
	}
	
	function slideThumbs(speed,currentPos)
	{
        if (speed > 0) {
            currentSlideWidth = previousSlideWidth;
        } else {
            currentSlideWidth = nextSlideWidth;
        }
		var leftPos = thumbDiv.style.left.replace('px', '') / 1;
		currentPos = currentPos + Math.abs(speed);
		leftPos = leftPos + speed;
		thumbDiv.style.left = leftPos + 'px';
		if (currentPos < currentSlideWidth) {
            setTimeout('slideThumbs(' + speed + ',' + currentPos + ')',slideSpeed);
        } else {
			if (thumbDiv.style.left.replace('px', '') / 1 >= 0) {
				document.getElementById('prev').style.visibility='hidden';
			}
			var left = thumbDiv.style.left.replace('px', '') / 1;
			if (thumbTotalWidth < viewableWidth - left) {
				document.getElementById('next').style.visibility='hidden';
			}
			thumbSlideInProgress = false;
		}
	}
	
	function showPreview(imagePath,inputObj)
	{		
		if(currentActiveImage){
			if(currentActiveImage==inputObj)return;
			currentActiveImage.className='';
		}
		currentActiveImage = inputObj;
		currentActiveImage.className='activeImage';
		
		/*if (navigator.userAgent.toLowerCase().indexOf('msie')>=0) largeImage.fadeOut().set('src',imagePath).fadeIn();
		else largeImage.fadeOut('slow').set('src',imagePath).fadeIn('slow');*/
		largeImage.fadeOut().set('src',imagePath).fadeIn();
	}

// funccion para imprimir las paginas
/* IMPRIMIR */
//function imprimir(){
//$("#impresion").click(function(){
//	doc_ref = "imprimir.html?url_to_print="+escape(document.location.href);
//	window.open(doc_ref,"","width=800px, height=500px, toolbar=no, status=no, menubar=no, location=no, scrollbars=yes");
	//alert(doc_ref);
//});
//}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

var xmlhttp
function loadXMLDoc(url)
{
xmlhttp=null
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest() }
else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change
xmlhttp.open("GET",url,true)
xmlhttp.send(null)
}
else{ alert("Error al abrir el archivo para imprimir!") }
}

function state_Change()
{
if(xmlhttp.readyState==4){
if (xmlhttp.status==200) {
	
var ghs = xmlhttp.responseText.replace(/\r|\n|\r\n/g,'');
//var re = new RegExp('<!-- InstanceBeginEditable name="primary content" -->((?:(?!<!-- InstanceEndEditable -->)).+)<!-- InstanceEndEditable -->','g');
var re = new RegExp('<div id="primary-content">((?:(?!<div id="footer">)).+)<div id="footer">','g');

re.exec(ghs);
//alert("<div id=\"primary-content\">"+RegExp.$1);
//alert(ghs);
document.getElementById('print_container').innerHTML="<div id=\"primary-content\">"+RegExp.$1;
}
else{ alert("Error al abrir el archivo para imprimir!") }
}
}
/* FIN DE IMPRIMIR */

//validacio formulari contacte
function contacte(){
	$('.contacte').submit(function(){
		$('.error').remove();
		var error = "";
		if ($('#nombre',this).val() == '') {
			error += '<li><strong>Nom</strong></li>'; 
			$('#nombre',this).css('border','1px solid red');
		}
		else $('#nombre',this).css('border','1px solid #ccc');
		
		if ($('#mail',this).val() == '') {
			error += '<li><strong>E-mail</strong></li>'; 
			$('#mail',this).css('border','1px solid red');			
		}
		else {
			if (!/(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i.test($('#mail',this).val())){
				$('#mail',this).parent().html($('#mail',this).parent().html() + '<br /><span style="color:red">Escriu el mail correctament.</span>');			
				error += '<li><strong>E-mail</strong></li>';
				$('#mail',this).css('border','1px solid red');	
			}
			else $('#mail',this).css('border','1px solid #ccc');
		}
		
		if ($('#consulta',this).val() == '') {
			error += '<li><strong>Consulta</strong></li>'; 
			$('#consulta',this).css('border','1px solid red');
		}
		else $('#consulta',this).css('border','1px solid #ccc');
		
		if($('#privacidad',this).get(0).checked == false) {
			error += '<li><strong>Llegeix i accepta</strong> les condicions de privadesa</li>';
			$('label[@for="privacidad"]',this).css('color','red');
			$('a',this).css('color','red');
		}
		else {
			$('label[@for="privacidad"]',this).css('color','#666');
			$('a',this).css('color','#000');
		}
		
		if (error != "") {
			$(this).prepend("<div class='error'>Revisa els camps marcats en vermell</div>");
			return false;
		}
		else return true;
	});
}

function submits(){
	$('#contacte').change(function(){
		$(this).parent().parent().parent().get(0).action = $(this).val();
	});
}
function change_layout(){
	var gallery = $('#change_layout').html();
	$('#change_layout').remove();
	$('#secondary-content').append(gallery);
}
