//if (document.getElementsByTagName) window.onload = Inicia;
var obert=0;
var aGaleria = new Array();
var pagActual=0;
var sTanca = ["Tanca","Cerrar","Close"];
var sImatge = new Array();
sImatge[0] = new Array("imatge","imagen","image");
sImatge[1] = new Array("de","de","of");

if (document.getElementsByTagName) window.onload = preInicia;
	function preInicia(){
	try {
	  Inicia();
	}catch(E){
	 
	}
}

function CreaFinestra() {
	var NovaFinestra = new Array(); var o = new Array();
	for (var b=0;b<Finestra.length;b++){
		for (var i=0;i<Finestra.length;i++) {NovaFinestra[Finestra[i][0]] = Finestra[i][1]}
		o[b] = document.getElementById(Finestra[b][0]);
		o[b].onclick = function (){
			return ObreFinestra(this.href,NovaFinestra[this.id])
		}
	}
}

function ObreFinestra(url,ident){
	nf=window.open(url,'name',ident);
	if (window.focus) {nf.focus()}
	return false;
}

//utilització de jquery per fer l'arrodoniment del banner de l'alcalde
function Cantonades() {
	$(".cantonades").append('<span class="se"></span><span class="sd"></span><span class="ie"></span><span class="id"></span>');
	$("#llista_galeria li").append('<span class="se"></span><span class="sd"></span><span class="ie"></span><span class="id"></span>');
	$(".cantonades_sup").append('<span class="se"></span><span class="sd"></span>');
	$(".cantonades_inf").append('<span class="ie"></span><span class="id"></span>');
}

//canviem els hr per divs
function hr2div() {
	$("#destaquem hr").after('<div class="degr_separacio"></div>');
	$(".fotografies_despatx hr").after('<div class="degr_separacio"></div>')
}

function paginam(num){
	//if(aGaleria==null || aGaleria==undefined)
	//aGaleria=aData;
	if(num==-1)	num=aData.length-1;
	else if(num==aData.length) num=0;
	pagActual = num;
	//alert(aGaleria[num][1]);
	//alert(num);
	//alert(aGaleria[num][0]+"--"+aGaleria[num][1]);
	//$("div#imatge_foto img").attr("src")=aGaleria[num][0];
	$("div#imatge_foto img").attr({ src: aData[num][0], alt: aData[num][1] });
	$("div#imatge_foto p#descripcio").html(aData[num][1]);
	$("div#imatge_foto p#paginat_fotos").html(sImatge[0][idioma]+" "+(num+1)+" "+sImatge[1][idioma]+" "+aData.length);
	
	
	return false;
}
function passaPagina(direccio){
	if(direccio=="dreta")
		pagActual++;
	else
		pagActual--;
		
	paginam(pagActual);
}

function land(){
	obert=0;
	$("div#sombra").fadeTo("slow", 1, function(){
		$("div#imatge_foto").fadeTo("slow", 0 ,function(){
			$("div#imatge_foto").remove();
		});											
		$("div#sombra").fadeTo("slow", 0 ,function(){
			$("div#sombra").remove();
		});
	});
	
}

function deprecated_load_aImg(){
	var i = 0;
	$("ul#llista_imatges li a").each(function(i){
		var itemGaleria = new Array();
		itemGaleria[0]=this.href;
		itemGaleria[1]=$("img",this).attr("alt");
		aGaleria[i]=itemGaleria;
		//alert(aGaleria[i][0]+aGaleria[i][1]+"-"+i);		
		$(this).click( function() {
			//alert(aGaleria[i][0]+aGaleria[i][1]+"-"+i);
			takeOff(aGaleria[i][0],aGaleria[i][1],i); return false;
			i++;
		});
			
	});
	
}

/*
	aDesti: array a on es desarà la informació
	idContenidor: id del tag "UL" que conté una estructura de l'estil
		<ul id="idContenidor">
			<li><a href="source_imatge_gran_1"><img src="source_thumbnail_1" alt="Descripcio_imatge_1" /></a></li>
			<li><a href="source_imatge_gran_2"><img src="source_thumbnail_2" alt="Descripcio_imatge_2"/></a></li>
			...
			<li><a href="source_imatge_gran_N"><img src="source_thumbnail_N" alt="Descripcio_imatge_N"/></a></li>
		</ul>
*/
function html2array(aDesti,idContenidor){
	var i = 0;
	
	$("#"+idContenidor+" a").each(function(i){
				
		var itemGaleria = new Array();
		itemGaleria[0]=this.href;
		itemGaleria[1]=$("img",this).attr("alt");
		
		itemGaleria[2]=$("img",this).attr("src");
		aDesti[i]=itemGaleria;	
	});	
}	

/*
	Genera un string per passar l'objecte array per url
	l'string te la següent forma.
	nombre_elements#$%#imatge_gran#$%#descripcio#$%#thumbnail#$%#imatge_gran2#$%#descripcio2#$%#thumbnail2 ...

*/
function array2string(aOrigen){
	var longitud = aOrigen.length;	
	var strReturn = "";
	var strSepara = "separaciodedades";
	for(var i=0; i < longitud; i++)
		strReturn += aOrigen[i][0]+strSepara+aOrigen[i][1]+strSepara+aOrigen[i][2]+strSepara;
	return strReturn;
}


/*
	Programa els onclick de tots els <a> que conté idContenidor per fer el takeoff segons les dades de l'array aDades
*/
function programa_takeoff(aDades,idContenidor){
	var i = 0;
	$("#"+idContenidor+" a").each(function(i){	
		$(this).click( function() {
			takeOff(aDades[i][0],aDades[i][1],i); return false;
			i++;
		});
			
	});

}

function takeOff(src_img,desc_img,num){
	if(!obert){
		obert=1;
		pagActual=num;
		$("#marc_web").append("<div id='sombra'></div>")
		$("#marc_web").append("<div id='imatge_foto'><div><img src='"+src_img+"' alt='"+desc_img+"'\></div><p id='descripcio'>"+desc_img+"</p><p id='paginat_fotos'>"+sImatge[0][idioma]+" "+(parseInt(pagActual)+1)+" "+sImatge[1][idioma]+" "+aData .length+"</p><a href='#imatge_foto' onclick='passaPagina(\"esquerra\");' id='anterior'></a><a href='#imatge_foto' onclick='passaPagina(\"dreta\");' id='seguent'></a><a id='tanca' href='#imatge_foto' onclick='land();'>"+sTanca[idioma]+"</a></div>");
		$("div#imatge_foto").fadeIn("slow");
		$("div#sombra").fadeIn("slow");
		$("div#sombra").fadeTo("slow", 0.3);	
	}
}

/*
Posa un flash en lloc de idContenidor, cal tenir abans de la crida el import seguent
<!--[if IE]>
		<script type="text/VBScript" src="http://www.bcn.cat/js/detec_flash2/crea_activex.vbs"></script>
	<![endif]-->
<script type="text/javascript" src="http://www.bcn.cat/js/detec_flash2/detec_final.js"></script>

i fer la crida com a aquest exemple:

array2flash(aData,"llista_imatges","nomFlash","../movies/galeria.swf","","#4D88C4");


*/
function array2flashNew(idContenidor){
		var bAmb_Flash = DetectFlashVer(8,0,0);
		if (bAmb_Flash){
			$("#capsa_fotos div").css({overflow:"hidden"});	
			$("#"+idContenidor+" ul").css({display:"none"});
			$("#"+idContenidor+" object").css({display:"block"});
		}
	
}

function posaFlash(aData){
	longitud=aData.length;
	txtInfo = array2string(aData);
	var leflash = "../movies/galeria.swf?longitud="+longitud+"&amp;dades="+txtInfo;				
	document.write('<object style="display:none;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="fotos" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" height="100%" width="100%"><param name="movie" value="'+leflash+'"><param name="menu" value="false"><param name="quality" value="high"><param name="bgcolor" value="\'#4D88C4\'"><param name="allowScriptAccess" value="sameDomain"><param name="wmode" value="transparent"><embed src="'+leflash+'" menu="false" quality="high" bgcolor="\'#4D88C4\'" name="fotos" play="true" loop="false" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" align="middle" height="100%" width="100%"><\/object>');
}

/*
Posa un flash en lloc de idContenidor, cal tenir abans de la crida el import seguent
<!--[if IE]>
		<script type="text/VBScript" src="http://www.bcn.cat/js/detec_flash2/crea_activex.vbs"></script>
	<![endif]-->
<script type="text/javascript" src="http://www.bcn.cat/js/detec_flash2/detec_final.js"></script>

i fer la crida com a aquest exemple:

array2flash(aData,"llista_imatges","nomFlash","../movies/galeria.swf","","#4D88C4");


*/
function array2flash(aDades,idContenidor,nomFlash,urlFlash,alternativa,bColor,transp){
	strReturn = "";
	longitud=aDades.length;
	txtInfo = array2string(aDades);
	if (transp==undefined || transp=="") transp="true";
	if (bColor==undefined || bColor=="") bColor="#FFFFFF";
	if(alternativa==undefined) alternativa="";
	//DADES FLASH I ALTERNATIVA
	//DetectFlashVer(Major version,Minor version,Revision)
	var bAmb_Flash = DetectFlashVer(28,0,0); 
	var sNom_flash = nomFlash; 
	var anMesures_flash = new Array('100%','100%'); 
	if (bAmb_Flash){ 
		//url del flash (swf) 
		url_flash = urlFlash+"?longitud="+longitud+"&dades="+txtInfo; 
		//crea_flash(url_flash,anMesures,sColor_fons,sNom_movie,bTransparent) 
		var sObj_flash = crea_flash(url_flash,anMesures_flash,"'"+bColor+"'",sNom_flash,transp); 
		strReturn = sObj_flash; 
	}else{ 
		//alternativa 
		var sAlternativa = '"+alternativa+"'; 
		strReturn=sAlternativa; 
	} 
	strReturn = strReturn;			
	//amb jquery canviem el codi si el navegador suporta flash
	if (bAmb_Flash){
		$("#"+idContenidor).html(strReturn);
	}
}

function comprova(idioma){
			var isOk=true;
		
			
			//comprovem que els valors obligatoris vinguin informats amb un minim de lletres
			isOk = isOk && (document.getElementById("nom").value.length > 0) ;
			isOk = isOk && (document.getElementById("cognoms").value.length > 2);
			isOk = isOk && (document.getElementById("adreca").value.length > 1);
			isOk = isOk && (document.getElementById("codi_postal").value.length > 4);
			isOk = isOk && (document.getElementById("correu").value.length > 3);
			isOk = isOk && (document.getElementById("msg").value.length > 1) ;
			isOk = isOk && emailCheck(document.getElementById("correu").value);
			//comprovem la validesa del correu
			
			//alert(isOk);
			if(isOk){
				if(idioma=='CA')
					document.frm.resposta.value="67";
				else if(idioma=='ES')
					document.frm.resposta.value="68";
				else
					document.frm.resposta.value="69";
				document.frm.submit();
			}else{
				if(idioma=='CA')
					alert('Si us plau, comproveu que hi hagi tota la informació obligatòria i que l\'adreça electrònica sigui correcta.');
				else if(idioma=='ES')
					alert('Debe comprobarse que esté toda la información obligatoria y que la dirección electrónica sea correcta.');
				else
					alert('Check that you have filled in all the obligatory information and that the e-mail address is correct.')

				return false;
			}
		}


function emailCheck (emailStr) {
		
		/* The following variable tells the rest of the function whether or not
		to verify that the address ends in a two-letter country or well-known
		TLD.  1 means check it, 0 means don't. */
		
		var checkTLD=1;
		
		/* The following is the list of known TLDs that an e-mail address must end with. */
		
		//var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|cat)$/;
		var knownDomsPat=/^(AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP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|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$/;
		
		
		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		
		var emailPat=/^(.+)@(.+)$/;
		
		/* The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ] */
		
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
		
		/* The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed.*/
		
		var validChars="\[^\\s" + specialChars + "\]";
		
		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
		
		var quotedUser="(\"[^\"]*\")";
		
		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		
		/* The following string represents an atom (basically a series of non-special characters.) */
		
		var atom=validChars + '+';
		
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */
		
		var word="(" + atom + "|" + quotedUser + ")";
		
		// The following pattern describes the structure of the user
		
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		
		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
		
		/* Finally, let's start trying to figure out if the supplied address is valid. */
		
		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */
		
		var matchArray=emailStr.match(emailPat);
		
		if (matchArray==null) {
		
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		
		//alert("Email address seems incorrect (check @ and .'s)");
		return false;
		}
		var user=matchArray[1];
		var domain=matchArray[2];
		
		// Start by checking that only basic ASCII characters are in the strings (0-127).
		
		for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		//alert("Ths username contains invalid characters.");
		return false;
		   }
		}
		for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
		//alert("Ths domain name contains invalid characters.");
		return false;
		   }
		}
		
		// See if "user" is valid 
		
		if (user.match(userPat)==null) {
		
		// user is not valid
		
		//alert("The username doesn't seem to be valid.");
		return false;
		}
		
		/* if the e-mail address is at an IP address (as opposed to a symbolic
		host name) make sure the IP address is valid. */
		
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null) {
		
		// this is an IP address
		
		for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
		//alert("Destination IP address is invalid!");
		return false;
		   }
		}
		return true;
		}
		
		// Domain is symbolic name.  Check if it's valid.
		 
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
		//alert("The domain name does not seem to be valid.");
		return false;
		   }
		}
		
		/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */
		
		if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		//alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
		}
		
		// Make sure there's a host name preceding the domain.
		
		if (len<2) {
		//alert("This address is missing a hostname!");
		return false;
		}
		
		// If we've gotten this far, everything's valid!
		return true;
	}