/**
* Funções de Javascript
*
* @version 1.0.3
* @since update	- 2010-01-20
* @copyright ©2007 - Texto Editores
*/

//Funções de acções dos metodos

function jsInclude(filename) {
	var body = document.getElementsByTagName('head').item(0);
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	body.appendChild(script)
}

function insertActionConfirm(meth, id, class_name, cat_id) {
	conf = confirm("Tem a certeza que pretende continuar com esta operação?");
	if (conf==true) {
		 insertAction(meth, id, class_name, cat_id);
	}
}

function insertAction(meth, id, class_name, cat_id) {
	document.listagem.start.value = '';
	document.listagem.class_name.value = class_name;
	document.listagem.cat_id.value = cat_id;
	document.listagem.id.value = id;
	document.listagem.meth.value = meth;
	document.listagem.submit();
}

function setPaginador(page) {
	document.listagem.start.value = page;
	document.listagem.submit();
}

function setOrder(order, dir) {
	document.listagem.order.value = order;
	document.listagem.order_dir_new.value = dir;
	document.listagem.submit();
}

function setAction(class_name, meth, cat_id, id) {
	cat_id = cat_id == undefined ? '' : cat_id;
	id = id == undefined ? '' : id;

	//document.listagem.start.value = '';
	var x = document.getElementById("setAction");
	x.meth.value = meth;
	x.class_name.value = class_name;
	x.cat_id.value = cat_id;
	x.id.value = id;
	x.submit();
}

function removeFilter() {
	var filtro = document.getElementById('listagem').filtro;

	//para o caso de ser com varios filtros
	if(filtro.length >0) {
		for (i=0;i<filtro.length;i++) {
			if(filtro[i]) { filtro[i].value = ""; }
		}
	//para o caso de ser so um filto
	} else {
		filtro.value = "";
	}
	document.listagem.start.value = '';
	document.listagem.submit();
}

function setFilter() {
	var filtro = document.getElementById('listagem').filtro;
	var set = false;

	//para o caso de ser com varios filtros
	if(filtro.length >0) {
		for (i=0;i<filtro.length;i++) {
			if((filtro[i] && filtro[i].value!='')) { set = true; }
		}
	} else {
		//para o caso de ser so um filto
		if(filtro.value!='') { set = true; }
	}

	if(set == true) {
		document.listagem.start.value = '';
		document.listagem.submit();
	}
	else{ alert("Tem de preencher pelo menos um filtro!"); }
}

function checkMultiple(formname, documento, mycheck, eixo, id) {
	var i, cur_id, tmp, val;

	documento = document.forms[formname].elements[documento];
	for (i = 0; i < documento.length; i++) {
		val = documento[i].value;
		val = val.split(":");
		cur_id = eixo == "x" ? val[0] : val[1];

		if(cur_id == id) { documento[i].checked = mycheck.checked; }
	}
}


// Funções de validação de formulários
function valida_campos(formName, array) {
	var i, name, val, documento, erro, tmp, valNome, tmp_aux, tmp_documento;

	erro = '';
	for (i=0; i < array.length; i+=3) {
		tmp		= '';
		nome	= array[i];
		val		= array[i+1];
		valNome	= array[i+2];

		documento = document.getElementById(nome);

		//verifica se trás mais alguma info	na validacao
		tmp		= val.split("||");
		val		= tmp[0];
		tmp_aux	= tmp[1];

		switch(val) {
			// verifica se está preenchido
			case 'isR':
			case 'isRequired':
				erro += isRequired(documento, valNome);
				break;

			// verifica se está preenchido no caso das wysiwyg
			case 'isRspaw':
			case 'isRwysiwyg':
				eval("var documento_spaw = "+nome+"_obj;");
				//var documento_spaw = nome+'_obj';
				erro += isRequired_wysiwyg(documento, valNome, documento_spaw);
				break;

			// verifica se é um numero
			case 'isNum':
				erro += isNum(documento, valNome);
				break;

			// verifica se é um email
			case 'isMail':
				erro += isMail(documento, valNome);
				break;

			// verifica se é um URL
			case 'isUrl':
				erro += isUrl(documento, valNome);
				break;

			// faz a relação de preenchido com outro campo do form
			case 'isRelational':
				tmp_documento = document.getElementById(tmp_aux);
				erro += isRelational(documento, valNome, tmp_documento);
				break;
/*
			//ou um ou outro checkbox
			case 'isRORChechbox':
				tmp_documento = document.getElementById(tmp_aux);
				erro += isRORChechbox(documento, valNome, tmp_documento,tmp_aux);
				break;
*/
			// Verifica que o campo seleccionado não é o primeiro valor
			case 'isCombo':
				erro += isCombo(documento, valNome);
				break;

			case 'isPrice':
				erro += isPrice(documento, valNome);
				break;

			case 'isFloat':
				erro += isFloat(documento, valNome);
				break;

			// o campo tem de ter pelo menos X caracteres
			case 'isBigger':
				erro += isBigger(documento, valNome, tmp_aux);
				break;
				
			// o campo tem de ter no maximo X caracteres
			case 'isShorter':
				erro += isShorter(documento, valNome, tmp_aux);
				break;
				
			// o campo tem de ter X caracteres
			case 'isLength':
				erro += isLength(documento, valNome, tmp_aux);
				break;

			// o campo tem de ter X caracteres
			case 'isCheckDigit':
				erro += isCheckDigit(documento, valNome);
				break;

			case 'isName':
				erro += isName(documento, valNome);
				break;

		}
	}

	if(erro != '') {
		alert(erro);
		return false;
	}
	return true;
}

function isRequired(documento, valNome) {
	if(documento.value == '') {
		return 'O campo ' + valNome + ' é de preenchimento obrigatório!\n';
	}
	return '';
}

function isRequired_wysiwyg(documento, valNome, documento_spaw) {
	var myerr = 'O campo ' + valNome + ' é de preenchimento obrigatório!\n';
	if(documento_spaw.current_context) {
		if(documento_spaw.current_context.textContent == '') {
			return myerr;
		}
	} else {
		if(documento.value == '') {
			return myerr;
		}
	}
	return '';
}

function isNum(documento, valNome) {
	if(isNaN(documento.value)) {
		return 'O campo ' + valNome + ' tem de ser um número!\n';
	}
	return '';
}

function isMail(documento, valNome) {
	var emailRegxp = /^([\w]+)(\.[\w]+)*@([\w]+)(\.[\w]+)*(\.[\w]{2,3}){1,2}$/;
	if (emailRegxp.test(documento.value) != true && documento.value != '') {
		return 'O campo ' + valNome + ' tem de ser um E-mail válido!\n';
	}
	return '';
}

function isUrl(documento, valNome) {
	//  /^((http(s?)|ftp))\:\/\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$/
	//var emailRegxp = (?i)(((https?|ftp|gopher)://([^:]+\:[^@]*@)?)?([\d\w\-]+\.)?[\w\d\-\.]+\.[\w\d]+((/[\w\d\-@%]+)*(/([\w\d\.\_\-@]+\.[\w\d]+)?(\?[\w\d\?%,\.\/\##!@:=\+~_\-&]*(?<![\.]))?)?)?)\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
	var myregexp = new RegExp("(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?");
	if (myregexp.test(documento.value) != true && documento.value != '')
		return 'O campo ' + valNome + ' tem de ser um URL válido!\n';
	return '';
}

function isRelational(documento, valNome, tmp_documento) {
	if(tmp_documento.value != '' && documento.value == '') {
		return 'O campo ' + valNome + ' é de preenchimento obrigatório!\n';
	}
	return '';
}
/*
function isRORChechbox(documento, valNome, tmp_documento, tmp_aux) {
	if(tmp_documento.checked==false && documento.checked==false) {
		return 'O campo ' + valNome + ' é de preenchimento obrigatório!\n';
	}
	return '';
}
*/
function isCombo(documento, valNome) {
	if(documento.selectedIndex == 0) {
		return 'O campo ' + valNome + ' é de preenchimento obrigatório!\n';
	}
	return '';
}

function isPrice(documento, valNome) {
	var emailRegxp = /^[-]?([1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|\.[0-9]{1,2})$/;
	if (emailRegxp.test(documento.value) != true && documento.value != '') {
		return 'O campo ' + valNome + ' tem de ser um Preço válido!\n';
	}
	return '';
}

function isFloat(documento, valNome) {
	// +22 | 22 | -22 | -22.02 | 22.1
	//var emailRegxp = /^[-+]?[0-9]+((\.([0-9]) {1,2}))?$/;
	var myregexp = new RegExp("^[-+]?[0-9]+((\.([0-9]) {1,2}))?$");
	if (myregexp.test(documento.value) != true && documento.value != '') {
		return 'O campo ' + valNome + ' tem de ser um valor válido! (Ex. 10.02)\n';
	}
	return '';
}

function isBigger(documento, valNome, bigger){
	if(isNaN(bigger)){ return '';}
	else if(documento.value != '' && documento.value.length < bigger){
		return 'O campo ' + valNome + ' tem de ter pelo menos '+bigger+' caracteres!\n';
	}
	return '';
}

function isShorter(documento, valNome, shorter){
	if(isNaN(shorter)){ return '';}
	else if(documento.value != '' && documento.value.length > shorter){
		return 'O campo ' + valNome + ' tem de ter no máximo '+shorter+' caracteres!\n';
	}
	return '';
}

function isLength(documento, valNome, equal){
	if(isNaN(equal)){ return '';}
	else if(documento.value != '' && documento.value.length != equal){
		return 'O campo ' + valNome + ' tem de ter '+equal+' caracteres!\n';
	}
	return '';
}

function isCheckDigit(documento, valNome) {
	var msg_erro = 'O campo ' + valNome + ' não é um número válido!\n';
	if(isNaN(documento.value)){
		return msg_erro;
	}else{
		var nr_bi = documento.value;
		
		while (nr_bi.length < 9) { nr_bi = "0" + nr_bi; }
		var calc = (9 * nr_bi.charAt(0)) + (8 * nr_bi.charAt(1)) + (7 * nr_bi.charAt(2)) + (6 * nr_bi.charAt(3)) + (5 * nr_bi.charAt(4)) + (4 * nr_bi.charAt(5)) + (3 * nr_bi.charAt(6)) + (2 * nr_bi.charAt(7)) + (1 * nr_bi.charAt(8));
		calc = calc % 11;
		
		if(nr_bi.charAt(8) == 0 && calc != 0){
			calc = (9 * nr_bi.charAt(0)) + (8 * nr_bi.charAt(1)) + (7 * nr_bi.charAt(2)) + (6 * nr_bi.charAt(3)) + (5 * nr_bi.charAt(4)) + (4 * nr_bi.charAt(5)) + (3 * nr_bi.charAt(6)) + (2 * nr_bi.charAt(7)) + (1 * 10);
			calc = calc % 11;
		}

		if (calc != 0) { return msg_erro; }
	}
	return '';
}

function isName(documento, valNome) {
	var msg_erro = 'O campo ' + valNome + ' tem de ter pelo menos dois nomes!\n';
	var nome = documento.value.split(" ");
	var palavras_minimas = 2;
	var caracteres_minimos = 2;
	
	//nao atingiu as palavras minimas
	if(nome.length < palavras_minimas){ return msg_erro; }
	
	var nome_num = 0;
	for(i=0; i<nome.length; i++){
		nome_tamanho = nome[i].length;
		if(nome_tamanho >= caracteres_minimos){ nome_num++; }
	}
	
	//não atingiu os caracteres minimos para o numero minimo de palavras
	if(nome_num < palavras_minimas){ return msg_erro; }
	
	return '';
}

function getKey(e) {
	if (window.event) return window.event.keyCode;
	else if (e) return e.which;
	else return null;
}

function validChars(e, valid) {
	var key = getKey(e);
	if (key == null) return true;
	// get character
	var keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	valid = valid.toLowerCase();

	// check valid keys
	if (valid.indexOf(keychar) != -1) return true;

	// control keys
	if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27) return true;

	// else return false
	return false;
}



/********************************
 * FUNÇÕES Específicas
 ********************************/


/**
 * Activa e desactiva condições de Lisboa e do Porto
 */
function viewCondicoes(local) {
	var local_lisboa	= document.getElementById('local_lisboa').checked;
	var local_porto		= document.getElementById('local_porto').checked;
	var insc			= document.getElementById("condicoes_inscricao");

	var lx = document.getElementById("condicoes_lisboa");
	var pr = document.getElementById("condicoes_porto");


	insc.style.display="block";

	if(local=='lx') { lx.style.display="block"; pr.style.display="none"; }								/* Lisboa */
	else if(local=='pr') { pr.style.display="block"; lx.style.display="none"; }						/* Porto */
	else if(local=='' && local_lisboa==true) { lx.style.display="block"; pr.style.display="none"; }	/* Lisboa */
	else if(local=='' && local_porto==true) { pr.style.display="block"; lx.style.display="none"; }		/* Porto */
	else { lx.style.display="block"; pr.style.display="none"; }											/* Lisboa */
}

function hideAllCondicoes() {
	var insc	= document.getElementById("condicoes_inscricao");
	var lx		= document.getElementById("condicoes_lisboa");
	var pr		= document.getElementById("condicoes_porto");

	insc.style.display="none";

	lx.style.display="none";
	pr.style.display="none";
}

/**
 * Checkbox para inscrição em Lisboa
 */
function showLisboaChkbx(el) {
/* tr */
	var tr_almoco_lisboa						= document.getElementById("tr_almoco_lisboa");
	var tr_workshop_lisboa						= document.getElementById("tr_workshop_lisboa");
	var tr_workshop_lisboa_info					= document.getElementById("tr_workshop_lisboa_info");
	var tr_local_porto							= document.getElementById("tr_local_porto");

/* input */
	var local_porto								= document.getElementById("local_porto");
	var almoco_lisboa							= document.getElementById("almoco_lisboa");
	var workshop_lisboa							= document.getElementById("workshop_lisboa");

	if(el.checked) {
		almoco_lisboa.checked					= false;
		workshop_lisboa.checked					= false;
		local_porto.checked						= false;

		tr_almoco_lisboa.style.display			= "block";
		tr_workshop_lisboa.style.display		= "block";
		if(tr_workshop_lisboa_info) {
			tr_workshop_lisboa_info.style.display= "block";
		}
		tr_local_porto.style.display			= "none";
	}
	else {
		almoco_lisboa.checked					= false;
		workshop_lisboa.checked					= false;
		local_porto.checked						= false;

		tr_almoco_lisboa.style.display			= "none";
		tr_workshop_lisboa.style.display		= "none";
		if(tr_workshop_lisboa_info) {
			tr_workshop_lisboa_info.style.display= "none";
		}
		tr_local_porto.style.display			= "block";
	}
}

/**
 * Checkbox para inscrição no Porto
 */
function showPortoChkbx(el) {
/* tr */
	var tr_workshop_porto						= document.getElementById("tr_workshop_porto");
	var tr_workshop_porto_info					= document.getElementById("tr_workshop_porto_info");
	var tr_local_lisboa							= document.getElementById("tr_local_lisboa");

/* input */
	var local_lisboa							= document.getElementById("local_lisboa");
	var workshop_porto							= document.getElementById("workshop_porto");

	if(el.checked) {
		workshop_porto.checked					= false;
		local_lisboa.checked					= false;

		tr_workshop_porto.style.display			= "block";
		if(tr_workshop_porto_info) {
			tr_workshop_porto_info.style.display= "block";
		}
		tr_local_lisboa.style.display			= "none";
	}
	else {
		workshop_porto.checked					= false;
		local_lisboa.checked					= false;

		tr_workshop_porto.style.display			= "none";
		if(tr_workshop_porto_info) {
			tr_workshop_porto_info.style.display= "none";
		}
		tr_local_lisboa.style.display			= "block";
	}
}

function validacaoExtra(form_name) {
	var frm = document.forms[form_name];

	if(frm && frm.local_lisboa && frm.local_porto) {
		if(frm.local_lisboa.checked==true && frm.local_porto.checked==true) {
			alert("Só pode escolher um local: Lisboa ou Porto");
			if(document.activeElement.checked) { document.activeElement.checked=false; }

			return false;
		}

		if(frm.local_lisboa.checked==false && frm.local_porto.checked==false) {
			alert("Tem de escolher um local: Lisboa ou Porto");
			return false;
		}
	}
	return true;
}
