/* FUNCIONS BÀSIQUES JavaScript
   desembre de 2005, */

// Script per redimensionar el navegador

function Browser() {
  var ua, s, i;
  this.isIE    = false;  
  this.isNS    = false;  
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

function doNothing(){
return true;
}

function getParam(purl, parametro, defvalue)
{
	var inicio = -1, siguiente = -1, fin = -1;
	var url = purl;
	
	inicio = url.indexOf(parametro);

	if (inicio != -1)
	{
		//Si hem trobat el parametre hem de buscar el seu valor
		inicio = url.indexOf("=", inicio);
		siguiente = url.indexOf("&", inicio);
		fin = (siguiente != -1 ? siguiente : url.length);
		return url.substring(inicio + 1, fin);
	}
	else
		return (defvalue == null ? '' : defvalue);
}

function get_cookie(name_to_get) {
	var cookie_pair;
	var cookie_name;
	var cookie_value;
	var cookie_array = document.cookie.split('; ');
	var cont;
	for (cont = 0; cont < cookie_array.length; cont++) {
		cookie_pair = cookie_array[cont].split('=');
		cookie_name = cookie_pair[0];
		cookie_value = cookie_pair[1];
		if (cookie_name == name_to_get) {return unescape(cookie_value)}
	}
	return null;
}

function set_cookie(name_to_set, value_to_set, expire_time) {
	//expire_time: dies que trigarà en expirar. P. ex. 365
	if (!navigator.cookieEnabled)  return;
	if (CookiePath == '') {
		var inicio = window.location.pathname.lastIndexOf('/');
		CookiePath = window.location.pathname.substr(0, inicio);
	}
	var cad = name_to_set + "=" + escape(value_to_set);
	if (expire_time) {
		var expire_date = new Date();
		var ms_from_now = expire_time * 24 * 60 * 60 * 1000;
		expire_date.setTime(expire_date.getTime() + ms_from_now);
		var cadexp = expire_date.toGMTString();
		cad += '; expires=' + cadexp;
	}
	cad += "; path=" + CookiePath;
	document.cookie = cad
}

// Scripts per ubicar en la pantalla
//----------------------------------------------------------------------------
// Obté la màxima posició per a la coordenada x
//----------------------------------------------------------------------------
function ObtenirMaxX() {
  var maxX;

  if (browser.isNS) {
    maxX = window.scrollX + window.innerWidth;
  }
  if (browser.isIE && browser.version < 6) {
    maxX = document.body.scrollLeft + document.body.clientWidth;
  }
  if (browser.isIE && browser.version >= 6) {
    maxX = document.body.scrollLeft + document.body.clientWidth;
  };
  return maxX
}

//----------------------------------------------------------------------------
// Obté la màxima posició per a la coordenada y
//----------------------------------------------------------------------------
function ObtenirMaxY() {
  var maxY;

  if (browser.isNS) {
    maxY = window.scrollY + window.innerHeight;
  }
  if (browser.isIE && browser.version < 6) {
    maxY = document.body.scrollTop  + document.body.clientHeight;
  }
  if (browser.isIE && browser.version >= 6) {
    maxY = document.body.scrollTop  + document.body.clientHeight;
  };
  return maxY
}

function getPageOffsetLeft(el) {
  var x;
  x = el.offsetLeft;
  if (el.offsetParent != null)
    x += getPageOffsetLeft(el.offsetParent);

  return x;
}

function getPageOffsetTop(el) {
  var y;
  y = el.offsetTop;
  if (el.offsetParent != null)
    y += getPageOffsetTop(el.offsetParent);

  return y;
}
//
//	Retorna elements
//
function gE(e) {
   if (document.layers) return document.layers[e];
   if (document.all) return document.all[e];
   return document.getElementById(e);
}


function FinestraCarregada() {
	if (Precarrega === true) {
		Precarrega = false;
		AmagaPrecarrega();
	}
/*	if (browser.isNS) {*/
		var Imatges = document.getElementsByTagName("img");
		for (var i = 0; i < Imatges.length; i++) {
				if (Imatges[i].className == "AltToTitle") {Imatges[i].title = Imatges[i].alt;}
		}
/*	}	*/
	for (var j = 0 ; j < FuncionsExecutarInici.length; j++) {
		eval(FuncionsExecutarInici[j]);
	}
	if (ScriptDeclarat("pos_menu.js")) {
		if (IdDivMenu != "") {
			var menu = gE(IdDivMenu);
			if (menu != null) {
				EngegarTimerPosicionarMenu();
			}
		}
	}
}

function ScriptDeclarat(NomScript) {
	var lenNom = NomScript.length;
	var lenSrc = 0;
	var cadNomSrc = "";
	var Declarat = false;
	if (browser.isIE) {var S = document.scripts}
	else {var S = document.getElementsByTagName("script")}
	for (var i = 1 ; i < S.length; i++) {
		lenSrc = S[i].src.length;
		cadNomSrc = S[i].src.substr(lenSrc - lenNom);
		if (NomScript == cadNomSrc) {
			Declarat = true;
			break;
		}
	}
	return Declarat;
}

function EscriureCorreuDominiUB(Usuari, Classe) {
	if (!Usuari) {Usuari = "";}
	else {Usuari = Trim(String(Usuari));}
	if (Usuari != "") {
		if (!Classe) {Classe = "";}
		else {Classe = Trim(String(Classe));}
		if (Classe != "") Classe = ' class="' + Classe + '"';
		var EnllaçCorreu = '<a' + Classe + ' href="mailto:' + Usuari + '@ub.edu">' + Usuari + '@ub.edu</a>';
		document.write(EnllaçCorreu);
	}
}

Array.prototype.ValueExists = function(Value) {
	var Resultat = false;
	for (var Clau in this) {
		if (Value == this[Clau]) {
			Resultat = true;
			break;
		}
	}
	return Resultat;
}

Array.prototype.KeyExists = function(Key) {
	var Resultat = false;
	for (var Clau in this) {
		if (Key == Clau) {
			Resultat = true;
			break;
		}
	}
	return Resultat;
}

Array.prototype.NumKey = function(Key) {
	var Resultat = false;
	var n = 0;
	for (var Clau in this) {
		if (Key == Clau) {
			Resultat = n;
			break;
		}
		n++;
	}
	return Resultat;
}

Array.prototype.KeyFromValue = function(Value) {
	var Resultat = null;
	for (var Clau in this) {
		if (Value == this[Clau]) {
			Resultat = Clau;
			break;
		}
	}
	return Resultat;
}

Array.prototype.NumKeyFromValue = function(Value) {
	var Resultat = false;
	var n = 0;
	for (var Clau in this) {
		if (Value == this[Clau]) {
			Resultat = n;
			break;
		}
		n++;
	}
	return Resultat;
}

Array.prototype.KeyFromNumKey = function(Num) {
	var Resultat = false;
	var n = 0;
	for (var Clau in this) {
		if (n == Num) {
			Resultat = Clau;
			break;
		}
		n++;
	}
	return Resultat;
}

Array.prototype.KeysToString = function(Sep) {
	var str = "";
	var n = 0;
	for (var Clau in this) {
		if (n > 0) str += Sep;
		str += Clau;
		n++;
	}
	return str;
}

Array.prototype.KeysAndValuesToString = function(Sep, SepKeyValue) {
	var str = "";
	var n = 0;
	for (var Clau in this) {
		if (n > 0) str += Sep;
		str += Clau + SepKeyValue + this[Clau];
		n++;
	}
	return str;
}

Array.prototype.KeysAndNotEmptyStringValuesToString = function(Sep, SepKeyValue) {
	var str = "";
	var n = 0;
	for (var Clau in this) {
		if (this[Clau] != "") {
			if (n > 0) str += Sep;
			str += Clau + SepKeyValue + this[Clau];
			n++;
		}
	}
	return str;
}

Array.prototype.ReorderStringsArray = function(Start, End) {
	// Algoritmo de ordenación de matrices. "Método rápido" de C. A. R. Hoare.
	// Extraido del libro "Algoritmos + estructuras de datos = programas" de Niklaus Wirth.
	// Funciona de manera recursiva.
	// Retocado por Franchis
	var ValX = "";
	var ValW = "";
	if (!Start) Start = 0;
	if (!End) End = (this.length - 1);
	var Valor = (Start == End);
	if ((Valor) || (Start > End)) {
		Valor = false;
	} else {
		var i = Start;
		var j = End;
		if (j == (i + 1)) {
			if (this[i] > this[j]) {
				ValW = this[i];
				this[i] = this[j];
				this[j] = ValW;
			}
			Valor = true;
		} else {
			ValX = this[Math.floor((Start + End) / 2)];
			do {
				while (this[i] < ValX) {i += 1;}
				while (ValX < this[j]) {j -= 1;}
				if (i <= j) {
					if (i < j) {
						ValW = this[i];
						this[i] = this[j];
						this[j] = ValW;
					}
					i += 1;
					j -= 1;
				}
			} while (i <= j);
			Valor = true;
			if (Start < j) {Valor = this.ReorderStringsArray(Start, j);}
			if ((Valor) && (i < End)) {Valor = this.ReorderStringsArray(i, End);}
		}
	}
	return Valor;
}

Array.prototype.SumaDelsValors = function(Start, End) {
	if (!Start) Start = 0;
	if (!End) End = (this.length - 1);
	var Suma = 0;
	for (var Clau in this) {
		if (isFinite(this[Clau])) {
			Suma += this[Clau];
		}
	}
	return Suma;
}


/* 

		Funcions obsoletes

function ValueInArray(Value, Array) {
	var Resultat = false;
	for (var Clau in Array) {
		if (Value == Array[Clau]) {
			Resultat = true;
			break;
		}
	}
	return Resultat;
}

function KeyInArray(Key, Array) {
	var Resultat = false;
	for (var Clau in Array) {
		if (Key == Clau) {
			Resultat = true;
			break;
		}
	}
	return Resultat;
}

function numKeyInArrayFromKey(Key, Array) {
	var Resultat = false;
	var n = 0;
	for (var Clau in Array) {
		if (Key == Clau) {
			Resultat = n;
			break;
		}
		n++;
	}
	return Resultat;
}

function numKeyInArrayFromValue(Value, Array) {
	var Resultat = false;
	var n = 0;
	for (var Clau in Array) {
		if (Value == Array[Clau]) {
			Resultat = n;
			break;
		}
		n++;
	}
	return Resultat;
}

function keyInArrayFromNumKey(Num, Array) {
	var Resultat = false;
	var n = 0;
	for (var Clau in Array) {
		if (n == Num) {
			Resultat = Clau;
			break;
		}
		n++;
	}
	return Resultat;
}

function ArraySearch(Valor, Array) {
	var Resultat = null;
	for (var Clau in Array) {
		if (Valor == Array[Clau]) {
			Resultat = Clau;
			break;
		}
	}
	return Resultat;
}

function ArrayValuesToString(Arr, sep) { //== join()
	var str = "";
	var n = 0;
	for (var Clau in Arr) {
		if (n > 0) str += sep;
		str += Arr[Clau];
		n++;
	}
	return str;
}

function ArrayKeysToString(Arr, sep) {
	var str = "";
	var n = 0;
	for (var Clau in Arr) {
		if (n > 0) str += sep;
		str += Clau;
		n++;
	}
	return str;
}

function ArrayKeysAndValuesToString(Arr, sep, sepKeyValue) {
	var str = "";
	var n = 0;
	for (var Clau in Arr) {
		if (n > 0) str += sep;
		str += Clau + sepKeyValue + Arr[Clau];
		n++;
	}
	return str;
}

function ArrayKeysAndNotEmptyStringValuesToString(Arr, sep, sepKeyValue) {
	var str = "";
	var n = 0;
	for (var Clau in Arr) {
		if (Arr[Clau] != "") {
			if (n > 0) str += sep;
			str += Clau + sepKeyValue + Arr[Clau];
			n++;
		}
	}
	return str;
}
*/

function StringToArray (str, sep) {
	var len = sep.length;
	var ind = str.indexOf(sep);
	var Arr = new Array();
	while (ind>-1) {
		Arr[Arr.length] = str.substring(0, ind);
		str = str.substr(ind + len);
		ind = str.indexOf(sep)
	}
	if (str != "") Arr[Arr.length] = str;
	return Arr;
}

//----------------------------------------------------------------------------
// Objecte per manegar dates
//----------------------------------------------------------------------------

DadesData = function (dia, mes, any, hora, minut, segon) {
	this.Dia = parseInt(dia, 10);
	this.Mes = parseInt(mes, 10);
	this.Any = parseInt(any, 10);
	if (typeof(hora) != 'undefined') {
		this.Hora = parseInt(hora, 10);
		if (typeof(minut) != 'undefined') {
			this.Minut = parseInt(minut, 10);
			if (typeof(segon) != 'undefined') {
				this.Segon = parseInt(segon, 10);
			} else {
				this.Segon = 0;
			}
		} else {
			this.Minut = 0;
			this.Segon = 0;
		}
	} else {
		this.Hora = 0;
		this.Minut = 0;
		this.Segon = 0;
	}
	this.Data = new Date(this.Any, this.Mes - 1, this.Dia, this.Hora, this.Minut, this.Segon);
	this.Dies = 0;
}

DadesData.prototype = {
	DiaIMes:function(Idioma) {
		if (typeof(Idioma) == 'undefined') {
				Idioma = "ca";
		} else {
			Idioma = Trim(Idioma.toLowerCase());
			if ((Idioma != "es") && (Idioma != "en")) Idioma = "ca";
		}
		var Cad = this.Dia + " ";
		var NomMes = this.NomDelMes(this.Mes, Idioma);
		if (Idioma == "ca") {
			NomMes = NomMes.toLowerCase();
			if ((this.Mes == 4) || (this.Mes == 8) || (this.Mes == 10)) {
				NomMes = "d’" + NomMes;
			} else {
				NomMes = "de " + NomMes;
			}
		} else {
			if (Idioma == "es") NomMes = "de " + NomMes.toLowerCase();
		}
		Cad += NomMes;
		return Cad;
	},
	NomDelMes:function(Mes, Idioma) {
		if (typeof(Idioma) == 'undefined') {
				Idioma = "ca";
		} else {
			Idioma = Trim(Idioma.toLowerCase());
			if ((Idioma != "es") && (Idioma != "en")) Idioma = "ca";
		}
		if (Mes < 1) {
			Mes = 1;
		} else {
			if (Mes > 12) Mes = 12;
		}
		var NomsDeMes = new Array();
		NomsDeMes["ca"] = new Array();
		NomsDeMes["es"] = new Array();
		NomsDeMes["en"] = new Array();
		NomsDeMes["ca"]	= ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"];
		NomsDeMes["es"]	= ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
		NomsDeMes["en"]	= ["January", "February", "March", "April", "May", "June", "April", "August", "September", "October", "November", "December"];
		return NomsDeMes[Idioma][Mes - 1];
	}
}

//----------------------------------------------------------------------------
// Funció per afegir controladors d'events
//----------------------------------------------------------------------------

function addHandler(object, event, handler) {
	// addHandler(<NomObjecte>, <Event>, <Funció>);
	// addHandlet(Boto, "mousedown", ProcessarRatoli)
	// var Boto = document.getElementById(<Id>)
	// funtion ProcessarRatoli() {}
	if (typeof object.addEventListener != 'undefined') 
		object.addEventListener(event, handler, false);
	else
		if (typeof object.attachEvent != 'undefined')
			object.attachEvent('on' + event, handler);
		else 
			throw 'Navegador incompatible';
}

//----------------------------------------------------------------------------
// Funcions d'encriptació
//----------------------------------------------------------------------------
var std_offset = -5;

function encryptCharcode(n,start,end,offset)	{
	n = n - offset;
	if (offset > 0 && n < start)	{
		n = end - (start - n - 1);
	} else if (offset < 0 && n > end)	{
		n = start + (n - end - 1);
	}
	return String.fromCharCode(n);
}

function decryptCharcode(n,start,end,offset)	{
	n = n + offset;
	if (offset > 0 && n > end)	{
		n = start + (n - end - 1);
	} else if (offset < 0 && n < start)	{
		n = end - (start - n - 1);
	}
	return String.fromCharCode(n);
}

function encryptString(dec,offset)	{
	var enc = "";
	var len = dec.length;
	for(var i=0; i < len; i++)	{
		var n = dec.charCodeAt(i);
		if (n >= 0x2B && n <= 0x3A)	{
			enc += encryptCharcode(n,0x2B,0x3A,offset);	// 0-9 . , - + / :
		} else if (n >= 0x40 && n <= 0x5A)	{
			enc += encryptCharcode(n,0x40,0x5A,offset);	// A-Z @
		} else if (n >= 0x61 && n <= 0x7A)	{
			enc += encryptCharcode(n,0x61,0x7A,offset);	// a-z
		} else {
			enc += dec.charAt(i);
		}
	}
	return enc;
}

function decryptString(enc,offset)	{
	var dec = "";
	var len = enc.length;
	for(var i=0; i < len; i++)	{
		var n = enc.charCodeAt(i);
		if (n >= 0x2B && n <= 0x3A)	{
			dec += decryptCharcode(n,0x2B,0x3A,offset);	// 0-9 . , - + / :
		} else if (n >= 0x40 && n <= 0x5A)	{
			dec += decryptCharcode(n,0x40,0x5A,offset);	// A-Z @
		} else if (n >= 0x61 && n <= 0x7A)	{
			dec += decryptCharcode(n,0x61,0x7A,offset);	// a-z
		} else {
			dec += enc.charAt(i);
		}
	}
	return dec;
}

function returnEncryptedString(s)	{
	return encryptString(s,std_offset);
}

function returnDecryptedString(s)	{
	return decryptString(s,std_offset);
}

function linkTo_UnCryptMailto(s)	{
	location.href = returnDecryptedString(s);
}

//----------------------------------------------------------------------------
// Funcions 
//----------------------------------------------------------------------------

function Trim (Cadena) {
	while (Cadena.substr(0, 1) == ' ') {Cadena = Cadena.substr(1);}
	while (Cadena.substr(Cadena.length - 1) == ' ') {Cadena = Cadena.substring(Cadena.length - 1, 0);}
	return Cadena;
}

function AfegirFuncioExecutarInici (nomFuncio) {
	FuncionsExecutarInici[FuncionsExecutarInici.length] = nomFuncio;
}

function SubstituirDarreraFuncioExecutarInici (nomFuncio) {
	if (FuncionsExecutarInici.length == 0) {
		FuncionsExecutarInici[FuncionsExecutarInici.length] = nomFuncio;
	} else {
		FuncionsExecutarInici[FuncionsExecutarInici.length - 1] = nomFuncio;
	}
}

var IdDivMenu = "";
var Precarrega = false;
var FuncionsExecutarInici = new Array();
var browser = new Browser();
window.onload=FinestraCarregada;


/*
function RetornarMatriuCadenesOrdenada(Matriu, Inici, Fi) {
	// Algoritmo de ordenación de matrices. "Método rápido" de C. A. R. Hoare.
	// Extraido del libro "Algoritmos + estructuras de datos = programas" de Niklaus Wirth.
	// Funciona de manera recursiva.
	// Retocado por Franchis
	var ValX = "";
	var ValW = "";
	var Valor = (Inici == Fi);
	if ((Valor) || (Inici > Fi)) {
		Valor = false;
	} else {
		var i = Inici;
		var j = Fi;
		if (j == (i + 1)) {
			if (Matriu[i] > Matriu[j]) {
				ValW = Matriu[i];
				Matriu[i] = Matriu[j];
				Matriu[j] = ValW;
			}
			Valor = true;
		} else {
			ValX = Matriu[Math.floor((Inici + Fi) / 2)];
			do {
				while (Matriu[i] < ValX) {i += 1;}
				while (ValX < Matriu[j]) {j -= 1;}
				if (i <= j) {
					if (i < j) {
						ValW = Matriu[i];
						Matriu[i] = Matriu[j];
						Matriu[j] = ValW;
					}
					i += 1;
					j -= 1;
				}
			} while (i <= j);
			Valor = true;
			if (Inici < j) {Valor = OrdenarMatriuCadenes(Matriu, Inici, j);}
			if ((Valor) && (i < Fi)) {Valor = OrdenarMatriuCadenes(Matriu, i, Fi);}
		}
	}
	return Valor;
}
*/

