/**
* Funções de Javascript 
*
* @version 1.0
* @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;
				
			// 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;
		}
	}
	
	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 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 '';
}
