// generic

function overCell(quinID, col, bgcol) {
  	obj = document.getElementById(quinID);
  	//obj.style.fontWeight = "bold";
	obj.style.color = col;
	obj.style.backgroundColor=bgcol;		
}

function toggleMenu(currMenu) {
	if (document.getElementById) {
		thisMenu = document.getElementById(currMenu).style		
		if (thisMenu.display == "") {
			thisMenu.display = "none"
		}
		else {
			thisMenu.display = ""
		}
		return false
	}
	else {
		return true
	}
}

function toggleBloc(currMenu) {
	if (document.getElementById) {
		thisMenu = document.getElementById(currMenu).style		
		if (thisMenu.display == "block") {
			thisMenu.display = "none"
		}
		else {
			thisMenu.display = "block"
		}
		return false
	}
	else {
		return true
	}
}

function canviarTots (_array) {
	n=_array.length;
	for (i=0;i<n;i++) {		
		toggleMenu(_array[i]);
	}
}

function amagarTots (_array) {
	n=_array.length;
	for (i=0;i<n;i++) {				
		if (document.getElementById) {
			thisMenu = document.getElementById(_array[i]).style;
			thisMenu.display = "none"
		}
	}
}


function finestracentre (url, nom, ample, alta) {
	ampl = screen.availWidth/2;
	alt = screen.availHeight/2;
	_left=ampl-ample/2;
	_top=alt-alta/2;			
	finestra = window.open(url, nom, "toolbar=no,location=no,scrollbars=yes,resizable=no,width="+ample+",height="+alta+",top=" + _top + ",left=" + _left);			
	finestra.focus(); 
}

function obrirfinestra_centre (url, nom, ample, alta, caract) {
	
	ampl = screen.availWidth/2;

	alt = screen.availHeight/2;

	_left=ampl-ample/2;

	_top=alt-alta/2;			

	finestra = window.open(url, nom, caract+",width="+ample+",height="+alta+",top=" + _top + ",left=" + _left);			

	finestra.focus(); 

}


function openform (url) {
	ample = screen.availWidth-20;
	//alta = screen.availHeight-20;
	alta = 620;				
	finestra = window.open(url, "wf", "toolbar=no,location=no,scrollbars=yes,resizable=yes,width="+ample+",height="+alta+",top=0, left=0");			
	finestra.focus(); 
}

String.prototype.trim = function() {
		return this.replace( /(^\s*)|(\s*$)/g, '' ) ;
}

/* NO provades!
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}*/

function filtra_str_url (form,camp1,camp2,idioma) {
	if (form[camp2].value=='') {
		str=form[camp1].value.toLowerCase();
		str.trim();
		// treu accents i altes com ^ % & ? ¿ / $ = ¡ ! , ; : . º ª i altres
		caracters_ = Array("\\u00E1","\\u00E9","\\u00ED","\\u00F3","\\u00FA","\\u00E0","\\u00E8","\\u00EC","\\u00F2","\\u00F9","\\u00F1","\\u00E7","\\u002E","\\u0020","\\u0027","\\u005C","\\u00BF","\\u003F","\\u0023","\\u0024","\\u0025","\\u0026","\\u0028","\\u0029","\\u002F","\\u002C","\\u003A","\\u003B","\\u0060","\\u0021","\\u002E","\\u00A1","\\u00AA","\\u00BA","\\u00FC","\\u00FB","\\u00EA","\\u00E2","\\u00B7","\\u00B4","\\u005C","\\u003E","\\u003C","\\u003F","\\u0040","\\u005E","\\u00B0","\\u2018","\\u2019","\\u201A","\\u201C","\\u201D","\\u201E","\\u20AC","\\u2022","\\u0022","\\u002A","\\u003D","\\u005B","\\u005D","\\u007B","\\u007C","\\u007D","\\u007E");
		caracters = Array("a","e","i","o","u","a","e","i","o","u","n","c","","-","","","","","","","","","","","","","","","","","","","","","u","u","e","a","","","","","","","","","","","","","","","","","","","","","","","","","","");
		 for (i=0; i<caracters_.length; i++) {
			 rx = eval("/"+caracters_[i]+"/g");
			 str = str.replace(rx,caracters[i]);
		 }
		 str = str.replace("---","-");
		 str = str.replace("--","-");
		form[camp2].value=str;
	}
}

// noticies 

function esborrar_noticia (id,txt) {
	if (confirm('Borrar notícia: ' + txt + '?')) {
		this.location = "transac/transac_noticies.php?action=Esborrar&id="+id;
	} 
}

function esborrar_linia (id,txt,transac,sufix) {
	if (confirm('Borrar : ' + txt + '?')) {
		this.location = "transac/"+ transac +"?action=Esborrar&id="+id+"&sufix="+sufix;
	} 
}

function esborrar_linia_galeria (id,id_pare,categoria,txt,transac,sufix) {
	if (confirm('Borrar : ' + txt + '?')) {
		this.location = "transac/"+ transac +"?action=Esborrar&id="+id+"&id_pare="+id_pare+"&categoria="+categoria+"&sufix="+sufix;
	} 
}

function enviar_news (id,txt,str,str2) {
	if (confirm('Enviar : ' + txt + '?' + '\r\n' + str + '\r\n' + str2)) {
		this.location = "cms.php?sec=enviarnewsletter&id="+id;
	} 
}

function popup_upload(seccio,tipus,camp) {
	finestracentre ('upload_file.php?seccio='+seccio+'&tipus='+tipus+'&camp='+camp, 'uploadimg', 500, 250)
}

function popup_upload2(seccio,tipus_file,camp) {
	finestracentre ('upload_file2.php?seccio='+seccio+'&tipus_file='+tipus_file+'&camp='+camp+'&action=insert', 'uploadimg', 500, 320)
}

function update_upload2(seccio,tipus_file,camp,id,domid) {
	finestracentre ('upload_file2.php?seccio='+seccio+'&tipus_file='+tipus_file+'&camp='+camp+'&id='+id+'&domid='+domid+'&action=update', 'uploadimg', 500, 320)
}

function popup_fechas (tipo) {
	finestracentre ('popup_fechas.php?tipo='+tipo,'popupfechas',500,400)
}

function update_fechas (tipo,id,domid) {
	finestracentre ('popup_fechas.php?tipo='+tipo+'&id='+id+'&domid='+domid+'&action=update','popupfechas',500,350)
}

function submitIt(camp,str) {		
	// str es obligatori
	val = camp.value;
	val = val.trim() 
	if (val=="") {
		alert(str + " es un campo obligatorio");
		return false;
	}
	return true;
}

function validEmail(email) {

			invalidChars = " /:,;"


			if (email == "") {

				return false

			}

			for (i=0; i<invalidChars.length; i++) {

				badChar = invalidChars.charAt(i)

				if (email.indexOf(badChar,0) > -1) {

					return false

				}

			}

			atPos = email.indexOf("@",1)

			if (atPos == -1) {

				return false

			}

			if (email.indexOf("@",atPos+1) > -1) {

				return false

			}

			periodPos = email.indexOf(".",atPos)

			if (periodPos == -1) {

				return false

			}

			if (periodPos+3 > email.length)	{

				return false

			}

			return true

}

function validEmail2(form) {
	if (!validEmail(form.email.value)) {
		alert('Formato de email incorrecto');
		return false;
	}
}

function submitItMultiple__(form,array_camps,array_strs,frase) {
	if (frase == undefined ) {
		frase='is empty';
	}
	// aqui form es un string
	for (var i=0;i<array_camps.length;i++) {
		camp = eval("form."+array_camps[i]);	
		val = camp.value;
		val = val.trim();
		if (camp.id=='email' && !validEmail(val)) {
				//alert('Formato de email incorrecto');
				alert(array_strs[i] + " " + frase);
				return false;
		} else if (val=="") {
			alert(array_strs[i] + " " + frase);
			return false;
		}
	}
	return true;
}

// idem anterior, però entend els radio button
function submitItMultiple(form,array_camps,array_strs,frase) {
	if (frase == undefined ) {
		frase='is empty';
	}
	// aqui form es un string
	for (var i=0;i<array_camps.length;i++) {
		camp=eval("form."+array_camps[i]);
		val = "";
		if (camp.type!='select-one' && camp.length>0) { // radio buttons!		
			for (var j=0;j<camp.length;j++) {
				if (camp[j].checked) {
					val='checked';
				}
			}
		} else {
			val = camp.value;
			val = val.trim();
		}
		if (camp.id=='email' && !validEmail(val)) {
				//alert('Formato de email incorrecto');
				alert(array_strs[i] + " " + frase);
				return false;
		} else if (val=="") {
			alert(array_strs[i] + " " + frase);
			return false;
		}
	}
	return true;
}

function mapa_contact(id,mapaimg) {
	if (document.getElementById) {
		thisID = document.getElementById(id).style				
		thisID.backgroundImage = "url(../img/"+mapaimg+")";				
		return false
	} else {
		return true
	}
}

function idioma (quin) {	
	// activar per a que funcionen els idiomes
	
	var validez = 1000;//dies
	var caduca = new Date(); 
	caduca.setTime(caduca.getTime() + (validez*24*60*60*1000));	
	setCookie("newlang", quin, caduca, "/", null, null)
	document.location.reload();
	
}

// Esta es la función que usa Heinle para recuperar una cookie
// name - nombre de la cookie deseada
// devuelve un string conteniendo el valor de la cookie especificada o null si la cookie no existe

function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}


// Esta es una adaptación de la función de Dorcht para colar una cookie
// name - nombre de la cookie
// value - valor de la cookie
// [expires] - fecha de caducidad de la cookie (por defecto, el final de la sesión)
// [path] - camino para el cual la cookie es válida (por defecto, el camino del documento que hace la llamada)
// [domain] - dominio para el cual la cookie es válida (por defecto, el dominio del documento que hace la llamada)
// [secure] - valor booleano que indica si la trasnmisión de la cookie requiere una transmisión segura
// al especificar el valor null, el argumento tomará su valor por defecto

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}


// Esta es una adaptación de la función de Dorcht para borrar una cookie
// name - nombre de la cookie
// [path] - camino de la cookie (debe ser el mismo camino que el especificado al crear la cookie)
// [domain] - dominio de la cookie (debe ser el mismo dominio que el especificado al crear la cookie)
// se considera el camino y dominio por defecto si se especifica null o no se proporcionan argumentos

function delCookie (name,path,domain) {
  if (getCookie(name)) { 
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function select_url (url) {	
		this.document.location = url
}

function  esborrar_encuesta (id,txt,url) {
	if (confirm('Borrar : ' + txt + '?')) {
		this.location = "cms.php?sec=encuestas&"+ url;
	} 
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  w = window.open(theURL,winName,features);
  w.focus();
}
function Calendario (id) {
	MM_openBrWindow('/calendar/calendario.php?id_apartamento='+id,'fcalendar','toolbar=no,location=no,status=no,resizable=no,width=300,height=350');
}

function xec_data (d1,m1,y1,d2,m2,y2) {

		// d1 > data hoy
		// d2 > d1 (per tant d2>data hoy, no fa falta xequjar)
		dmy = new Date()
		//alert(dmy);
		dmy1 = new Date();
		dmy2 = new Date();
		
		dmy1.setFullYear(y1);// els mesos van de 0 a 11
		dmy1.setMonth(m1-1);// els mesos van de 0 a 11		
		dmy1.setDate(d1);		
		
		//alert(dmy1);	
		dmy2.setFullYear(y2);		
		dmy2.setMonth(m2-1);// els mesos van de 0 a 11
		dmy2.setDate(d2);		
	
		if (dmy1>=dmy2 || dmy1<=dmy || (m1==m2 && d2-d1<3)) {
			alert("Please, check your dates");
			return false; 
		} else {
			return true
		}
}

function send_busqueda_rooms (rooms) {
	document.forms.buscador.numrooms.value=rooms;	
	setCookie('inpValBuscador',getFormString(document.forms.buscador,true))
	document.forms.buscador.submit();
}

function popup_googlemaps (ref,lat,long) {
	obrirfinestra_centre ('popuplocation.php?zoom=15&lat='+lat+'&lng='+long+'&nombre='+ref, 'location', 500, 400, "scrollbars=no");
}

// otros

function ValidarFecha(vFecha, vCaption)
{	
	var Fecha= new String(vFecha);	// Crea un string
	while (Fecha.indexOf("/")>-1) {
		Fecha = Fecha.replace("/","-");
	}
	while (Fecha.indexOf(".")>-1) {
		Fecha = Fecha.replace(".","-");
	}
	if (Fecha.length == 0) return true;
	
	var strCaption = new String(vCaption);
	

	var RealFecha= new Date();	// Para sacar la fecha de hoy

	var strMsg = "Error en el campo '" + strCaption.toString() + "'\n";
	if (Fecha.length != 10 || Fecha.indexOf("-") != 2 || Fecha.lastIndexOf("-") != 5 || Fecha.indexOf("-") == Fecha.lastIndexOf("-"))
	{
		alert(strMsg + 'Fecha inválida: ' + vFecha + "\n\nDebe tener el siguiente formato DD-MM-AAAA." + "\nEjemplo: 03-01-1999");
		return false;
	}
	
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("-")));
	var Mes= new String(Fecha.substring(Fecha.indexOf("-")+1,Fecha.lastIndexOf("-")));
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("-")+1,Fecha.length));
	
    //alert('Año: ' + Ano + "\n" + 'Mes: ' + Mes + "\n" + 'Día: ' + Dia + "\n");
    
	// Valido el año
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900)
	{
		alert(strMsg + 'Año inválido: ' + Ano + "\n\nEl año debe ser un número de 4 cifras mayor que 1900." + "\nEjemplo: 1999");
		return false;
	}
	// Valido el Mes
	if (isNaN(Mes) || Mes.length<2 || parseFloat(Mes)<1 || parseFloat(Mes)>12)
	{
		alert(strMsg + 'Mes inválido: ' + Mes + "\n\nEl mes debe ser un número de 2 cifras, entre 01 y 12." + "\nEjemplo: 08");
		return false;
	}
	// Valido el Dia
	if (isNaN(Dia) || Dia.length<2 || parseFloat(Dia)<1 || parseFloat(Dia)>31)
	{
		alert(strMsg + 'Día inválido: ' + Dia + "\n\nEl día debe ser un número de 2 cifras, entre 01 y 31." + "\nEjemplo: 21");
		return false;
	}

	//alert("Mes = " + Mes + " parseFloat(Mes) = " + parseFloat(Mes) + " Dia = " + Dia + " parseFloat(Dia) = " + parseFloat(Dia));
	switch (parseFloat(Mes)) 
	{ 
		case 4:
		case 6:
		case 9:
		case 11:
			//mes de 30 dias
			if (parseFloat(Dia) > 30) 
			{
				alert(strMsg + 'Día inválido: ' + Dia + "\n\nPara el mes indicado, el día debe ser un número de 2 cifras, entre 01 y 30." + "\nEjemplo: 21");
				return false;
			}
			break; 
		case 2: 
			if (parseFloat(Ano)%4 ==0 && parseFloat(Dia) > 29) 
			{
				//mes de 29 dias
				alert(strMsg + 'Día inválido: ' + Dia + "\n\nPara el mes de febrero de un año bisiesto, el día debe ser un número de 2 cifras, entre 01 y 29." + "\nEjemplo: 21");
				return false;
			}
			if (parseFloat(Ano)%4 !=0 && parseFloat(Dia) > 28) 
			{
				//mes de 28 dias
				alert(strMsg + 'Día inválido: ' + Dia + "\n\nPara el mes de febrero, el día debe ser un número de 2 cifras, entre 01 y 28." + "\nEjemplo: 21");
				return false;
			}
			break; 
		default: 
			//mes de 31 dias
			//ya controlado
			break; 
	}
            	
	return true;	
}

function validaHora (hhmmss,str) {
	hhmmss = hhmmss.trim()
	// tipus HH:MM:SS
	if (hhmmss!="") {		
		if (!XecChars(hhmmss,"0123456789:")) {
			alert(str);
			return false;
		 }
		 h = hhmmss.split(":");
		if (h.length>3) {
			alert(str);
			return false;
		}
		if (Number(h[0])<0 || Number(h[0])>23) {
			alert(str);
			return false;
		}
		if (Number(h[1])<0 || Number(h[1])>59) {
			alert(str);
			return false;
		}
		if (Number(h[2])<0 || Number(h[2])>59) {
			alert(str);
			return false;
		}
	}
	return true;
}

function XecChars(sText,chars) {
   var ValidChars = chars;
   var IsOK=true;
   var Char;
 
   for (i = 0; i < sText.length && IsOK == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsOK = false;
         }
      }
   return IsOK;
   
}

function XecDiasSemana(dias,str) {
	dias = dias.trim();
	if (dias!="") {
		if (!XecChars(dias,"LMXJVSD")) {
			alert(str);
			return false;
		}
	}
	return true;
}

function data2MYSQL (fecha) {
	// data en format mysql
	if ((fecha == "") || (fecha == "00-00-0000")) {
		return ""
	} else {
		d = fecha.split('-');
		new_d = d[2]+"-"+d[1]+"-"+d[0]
		return new_d;
	}
}

function filtrar_pag_cat (selec,tipo) {
	act_url = String(document.location);
	str = "filtre_cat_"+tipo;
	index = act_url.indexOf(str,0);
	if (index!=-1) {
		act_url = act_url.substring(0,index-1);
	}
	index = act_url.indexOf("?",0);
	if (index!=-1) {
		char_link = "&"
	} else {
		char_link = "?"
	}
	new_url = act_url + char_link + str + '='+selec.value;
	//document.location = document.location + '&filtre_cat_'+tipo+'='+selec.value;
	document.location = new_url;
}

function do_cadaver (id,id_img) {
	div_id = '#'+id+' .img';
	div = '#'+id;
 	$(div).html('<div class="img">loading...</div>');
	$(div_id).fadeOut(100,
					  function () {
						  $(this).load("/include/get_img_cadaver.php?id_img="+id_img+"&parte="+id,
											function () {
												$(this).fadeIn(500);
											}
										)
					 				}
							)
	/*$(div_id).load("/include/get_img_cadaver.php?id_img="+id_img+"&parte="+id,
						  	function () {
								$(this).fadeOut(500).fadeIn(500);
							}
						);*/
}

function do_cadaver_random(id,sessio) {
	if (sessio) {
		param_sessio = "?sessio=true";
	} else {		
		param_sessio = '';
	}
	div_id = '#'+id;
	$(div_id).load("/include/do_cadaver_random.php"+param_sessio);
}
