// 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(id) {
		thisBloc = document.getElementById(id).style		
		if (thisBloc.display=="none" || thisBloc.display=="") {
			thisBloc.display = "block"
		}
		else {
			thisBloc.display = "none"
		}
		return false;
}

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 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, '' ) ;
}

// 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) {
	if (confirm('Borrar : ' + txt + '?')) {
		this.location = "transac/"+ transac +"?action=Esborrar&id="+id;
	} 
}

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,ample,alt) {
	finestracentre ('upload_file.php?seccio='+seccio+'&tipus='+tipus+"&camp="+camp+"&ample="+ample+"&alt="+alt, 'uploadimg', 500, 250)
}

function submitIt(camp,str) {		
	// str es obligatori
	val = camp.value;
	val = val.trim() 
	if (val=="") {
		alert(str + " es un campo obligatorio");
		return false;
	}
}

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;
		}
	}
}

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)
	//alert(getCookie('newlang'));
	document.location.reload();
}

function idioma__ (quin) {
	loc = document.location
	document.location = loc + "&idioma=" + quin;
}

function idioma (idioma) {
	if (document.location!='about:blank') {
		act_url = String(document.location);
		str = "idioma=";
		index = act_url.indexOf(str,0);
		if (index!=-1) {
			act_url = act_url.substring(0,index-1);
		}
		if (idioma=="") {
			idioma = 'es';
		}
		new_url = act_url + "&idioma="+idioma;
		document.location = new_url;
	}
}

/*
act_url = String(top.mainFrame.location);
str = "idioma=";
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 = "?"
}
if (idioma+""=="") {
	idioma = 'esp';
}
new_url = act_url + char_link + "idioma="+idioma;
top.mainFrame.location = new_url;
*/

// 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];}}
}


	/**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/

// exemple: Url.encode(this.value)

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

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;
}