
/**
 * Redireciona o usuário para uma URL
 * @param String url Url de destino
 */
function goLink(url) {
	document.location = url;
}

/**
 * Redirecina o usuário para uma página de resultados específica
 * Usar com paginação de resultados
 * @param String url url da página atual
 */
function irParaPagina(url) {
	page = document.getElementById('irpara').value;
	if (url.indexOf('?') != -1) {
		document.location = url+'&page='+page;
	} else {
		document.location = url+'?page='+page;
	}
}

/**
 * Limpa os campos de um filtro
 * @param Object obj Botao contido no form de filtro
 */
function limpaFiltro(obj) {
	var form = obj.form;
	for(var i=0;i<form.elements.length; i++) {
		//alert(form.elements[i].type);
		if (form.elements[i].type == 'text') {
			form.elements[i].value = '';
		} else if (form.elements[i].type.indexOf('select') != -1) {
			form.elements[i].options[0].selected=true;
		}
	}
}

/**
 * Valida um endereço de e-mail
 * @param String email
 * @return bool
 */
function validaEmail(email) {
	var er3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var er = er3;
	eval("er = er" + 3);
	if (er.test(email)) {
		return true;
	} else if (email != null && email != "") {
		return false;
	}
}

/**
 * Formata o valor de um input text de acordo com uma máscara
 * Deve ser utilizado no evento onkeydown
 * @example <input type="text" id="input-cep" onkeydonw="formatar(this, '##.###-###')>" />
 * @param Object src Objeto Input que será formatado
 * @param String mask Máscara que será aplicada
 */
function formatar(src, mask, e) {
	var i = src.value.length;

	var saida = mask.substring(0,1);

	var texto = mask.substring(i)
	
	if (texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}

/**
 * Formata o valor de um input como data dd/mm/yyyy
 * Deve ser utilizado no evento onkeyup
 * @example <input type="text" id="input-date" onkeyup="formataData(this)>" />
 * @param Object campo Objeto Input que será formatado
 */
function formataData(campo, teclapress) {
	tecla = (typeof(teclapress) == "undefined") ? window.Event : teclapress;
	if (tecla.keyCode != 8 && tecla.keyCode != 9) {
		formatar(campo, '##/##/####');
	}
}

/**
 * Verifica se um valor é composto apenas de números
 */
function isNum(caractere) {
	var strValidos = "0123456789"
	
	if ( strValidos.indexOf( caractere ) == -1 )
		return false;
		
	return true;
}

/**
 * Limita a entrada de dados em um input apenas a números
 * Deve ser utilizado no evento onkeypress
 * @example <input type="text" id="input-idade" onkepress="onlyNumbers(this)>" />
 * @param Object campo Objeto Input numérico
 */
function onlyNumbers(campo, event) {
	var BACKSPACE= 8; 
	var key;
	var tecla;
	
	if(navigator.appName.indexOf("Netscape")!= -1)
		tecla= event.which;
	else
		tecla= event.keyCode;
	
	key = String.fromCharCode( tecla);
 
	//alert( 'key: ' + tecla + ' -> campo: ' + campo.value);
	if ( tecla == 13 )
		return false;
 
	if (tecla == BACKSPACE)
		return true;
	
	if (tecla == 0)
		return true
	
	return ( isNum(key));
}


/**
 * Verifica se a String é um e-mail
 * @return bool true | false
 */
String.prototype.isEmail = function() {
	return validaEmail(this);
}

/**
 * Retorna true se a String é composta apenas por caracteres alfanuméricos
 * @return bool true | false
 */
String.prototype.alpha = function() {
	var er = /^[\w][\w\s]*$/;
	return er.test(this);
}

/**
 * Retorna a String removendo os espaços em branco no início
 * @return String String sem espaços no inicio
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/, '');
}

String.prototype.number = function(){
	var er = /^\d+$/;
	
	return er.test(this);
}

function marcar(){
	var input = document.getElementsByTagName('input');
	
	for (var i=0; i < input.length; i++){
		if(input[i].type=='checkbox'){
			if(!input[i].checked)
				input[i].checked = true;
		}
	}

}


function desmarcar(){
	var input = document.getElementsByTagName('input');
	
	for(var i=0; i < input.length; i++){
		if(input[i].type=='checkbox'){
			if(input[i].checked)
				input[i].checked=false;	
			
		}
	}
}
	
	
function verificaCheckBox(){
	var check = document.getElementsByTagName('input');
	var achou = false;
	
	for(var i=0; i<check.length; i++){
		if(check[i].type=='checkbox' && check[i].checked){
			achou = true;
			break;
		}
	}
	return achou;		
}
	

/**
 * Retorna a String removendo espaços em branco no início e no fim
 * @return String String sem espaços no inicio e no fim
 */

String.prototype.trimTotal = function() {
	return this.replace(/\s/g, '');
}

/**
 * Verifica se a String é uma data válida para o formato dd/mm/yyyy
 * @return bool true|false
 */
String.prototype.isDate = function() {
	var er = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	return er.test(this);
}


function printComprov(){

	var f = document.getElementById('ferramenta');
	f.style.display= 'none';
	window.print();
	
}


/**
 * Compara 2 objetos e verifica se eles são iguais em todos os atributos
 * @param Object a objeto 1
 * @param Object b objeto 2
 * @return bool true|false
 */
equals = function(a, b){
    for(var j, o = arguments, i = o.length, c = a instanceof Object; --i;)
        if(a === (b = o[i]))
            continue;
        else if(!c || !(b instanceof Object))
            return false;
        else for(j in b)
            if(!equals(a[j], b[j]))
                return false;
    return true;
}


/**
 * Adiciona a qualquer objeto a capacidade de se comparar com outro
 * @param Object b Objeto que será comparado
 * @return bool true|false
 */
Object.prototype.equals = function(b) {
	return equals(this, b);
}


/**
 * Retorna o valor seleciona em um objeto select
 * @return mixed|bool retorna false se nao há valor selecionado ou o valor c.c.
 */
Object.prototype.selectedValue = function() {
	if ( this.type.match(/^select/i) ){
		return this.options[this.selectedIndex].value;
	} else {
		return false;
	}
}

/**
 * Seleciona um valor específico no select
 * @param String valor valor que deve ser marcado
 * @return bool true se o valor foi encontrado e selecionado false c.c.
 */
Object.prototype.selectValue = function(valor) {
	if ( this.type.match(/^select/i) ){
		var options	= this.options;
		for (var i = 0; i < options.length;i++) {
			if (options[i].value == valor) {
				options[i].selected = true;
				return true;
			}
		}
		return false;
	}
}

/**
 * Retorna o título do elemento selecionado no select
 * @return String
 */
Object.prototype.selectedLabel = function() {
	if ( this.type.match(/^select/i) ){
		return this.options[this.selectedIndex].innerHTML;
	} else {
		return false;
	}
}

/**
 * Cria um objeto select a partir de um array de dados
 * @param Array data Dados no formato [['value1', 'label1'], ['value2', 'label2']...]
 * @return Object retorna um objeto select com suas options
 */
ListInput = function (data) {
	this.input = document.createElement("select");
	for (var i=0; i<data.length; i++) {
		var op = document.createElement("option");
		op.innerHTML = data[i][1];
		op.setAttribute("value", data[i][0]);
		
		if (typeof(data[i][2]) == "boolean" && data[i][2] == true)
			op.selected = true;
		
		this.input.appendChild(op);
	}
	
	return this.input;
}


/**
 * Adiciona os comportamentos de um campo de data dd/mm/yyyy a um input text
 * se um id nao for informado um novo objeto é criado é criado
 * @param String inputId Id do campo que receberá os comportamentos
 * @param Fcuntion addOnChange uma função a ser executada no evento onchange do input
 */
DateInput = function (inputId, addOnChange, e) {
	var _this = this;

	this.addOnChange = addOnChange;
	
	if (typeof(inputId) == 'string' && inputId!= '') {
		this.input = dojo.byId(inputId);
	} else {
		this.input = document.createElement("input");
	}
	
	this.input.type = "text";
	this.input.size = 10;
	
	this.input.onkeypress = function (e) {
		return onlyNumbers(this, e);
	}
	this.input.onkeyup = function (e) {
		return formataData(this, e);
	}
	this.input.onchange = function(e) {
		if (!this.value.isDate() && this.value != '') {
			alert ("Data invalida.");
			this.value = '';
			this.focus();
			return false;
		}
		if (typeof(_this.addOnChange) == 'function') {
				_this.addOnChange(this);
		}
		
	}
	
	this.input.maiorQue = function(dataIni) {
		return chkdatas(dataIni, _this.input.value);
	}
	
	this.menorQue = function(dataFim) {
		return chkdatas(_this.input.value, dataFim);
	}
	
	return this.input;
	
}

/**
 * Adiciona os comportamentos de um campo numérico a um input text
 * se um id nao for informado um novo objeto é criado é criado
 * @param String inputId Id do campo que receberá os comportamentos
 */
NumberInput = function (inputId, e) {
	var _this = this;

	if (typeof(inputId) == 'string' && inputId!= '') {
		this.input = dojo.byId(inputId);
	} else {
		this.input = document.createElement("input");
	}
	
	this.input.type = "text";
	
	this.input.onkeypress = function (e) {
		return onlyNumbers(this, e);
	}
	
	return this.input;
}

/**
 * Adiciona os comportamentos de um campo String com maiúsculas e sem espaços no inicio e no fim
 *  a um input text. Se um id nao for informado um novo objeto é criado é criado
 * @param String inputId Id do campo que receberá os comportamentos
 * @param Fcuntion addOnChange uma função a ser executada no evento onchange do input
 */
StringDbInput = function (inputId, addOnChange, e) {
	var _this = this;

	this.addOnChange = addOnChange;
	
	if (typeof(inputId) == 'string' && inputId!= '') {
		this.input = dojo.byId(inputId);
	} else {
		this.input = document.createElement("input");
	}
	
	this.input.type = "text";
	

	this.input.onchange = function(e) {	
		this.value = this.value.trim();
		this.value = this.value.toUpperCase();
		
		if (typeof(_this.addOnChange) == 'function') {
				_this.addOnChange(this);
		}
		
	}
	
	return this.input;
}

/**
 * Adiciona os comportamentos de um campo com máscara de entrada a um input text
 * se um id nao for informado um novo objeto é criado é criado
 * @param String inputId Id do campo que receberá os comportamentos
 * @param String mask Formato da mascara de entrada
 */
MaskInput = function (inputId, mask, e) {
	var _this = this;
	
	this.mask = mask;
	
	if (typeof(inputId) == 'string' && inputId!= '') {
		this.input = dojo.byId(inputId);
	} else {
		this.input = document.createElement("input");
	}
	
	this.input.type = "text";
	
	this.input.onkeypress = function (e) {
		return onlyNumbers(this, e);
	}
	
	this.input.onkeyup = function (e) {
		tecla = (typeof(e) == "undefined") ? window.Event : e;
			if (tecla.keyCode != 8 && tecla.keyCode != 9) {
			formatar(this, _this.mask);
		}
	}
	
	return this.input;
	
}

/**
 * Retorna um objeto <div class="campo"><label></label><input... </div>
 * @param String label Título do campo
 * @param Object input Objeto input ou outro elemento qualquer que ficará dentro da div
 * @return Object div
 */
divCampo = function (label, input) {
	var div = document.createElement("div");
	div.className = "campo";
	
	var inputLabel = document.createElement("label");
	inputLabel.innerHTML = label;
	
	div.appendChild(inputLabel);
	div.appendChild(input);
	
	return div;
	
}

/**
 * Retorna um objeto <div class="limpa"><br /></div>
 * @return Object div
 */
divLimpa = function () {
	var div = document.createElement("div");
	div.className = "limpa";
	
	var br = document.createElement("br");
	div.appendChild(br);
	
	return div;
}

/**
 * Adiciona os comportamentos de um campo numérico(Decimal) a um input text
 * se um id nao for informado um novo objeto é criado é criado
 * @param String inputId Id do campo que receberá os comportamentos
 */
NumberDecimalInput = function (inputId, e) {
	var _this = this;
	er = /^\d*[0-9](\,\d*[0-9])?$/
	
	if (typeof(inputId) == 'string' && inputId!= '') {
		this.input = dojo.byId(inputId);
	} else {
		this.input = document.createElement("input");
	}

	this.input.type = "text";
	this.input.onkeypress = function (e) {
	if(navigator.appName.indexOf("Netscape")!= -1)
		tecla= e.which;
	else
		tecla= e.keyCode;
		if (tecla!=44){
			return onlyNumbers(this, e);
		}
	}
	var n = this.input.value;
	if(!n) return false;
	
	return (er.test(n));
}

/**
 * Verifica se a data fornecida é maior que a data de hoje
 */
function menorHoje(data) {
	auxHoje = new Date();
	var hoje = auxHoje.getDate()+"/"+parseFloat(auxHoje.getMonth()+1)+"/"+auxHoje.getFullYear();

	return chkdatas(data, hoje);
}

/**
 * Checa se adt_final é maior que dt_inicio
 */
function chkdatas(dt_inicio,dt_final) {
	var dti = dt_inicio.split("/");
	var dtf = dt_final.split("/");

	var anoi = parseFloat(dti[2]);
	var anof = parseFloat(dtf[2]);
	var mesi = parseFloat(dti[1]);
	var mesf = parseFloat(dtf[1]);
	var diai = parseFloat(dti[0]);
	var diaf = parseFloat(dtf[0]);
	
	if (anof > anoi){
		return true;
	} else if ((anof==anoi)&&(mesf > mesi)) {
		return true;
	} else if ((anof==anoi) && (mesf==mesi) && (diaf >= diai)) {
		return true
	} else {
		return false;
	}
	
}


function diferencaDatas (dtInicio, dtFim) {
	
	if (!chkdatas(dtInicio, dtFim)) {
		return false;
	}
	
	var aux1   = dtInicio.split("/");
	var d1_dia = parseFloat(aux1[0]);
	var d1_mes = parseFloat(aux1[1]);
	var	d1_ano = parseFloat(aux1[2]);
	
	var aux2   = dtFim.split("/");
	var d2_dia = parseFloat(aux2[0]);
	var d2_mes = parseFloat(aux2[1]);
	var d2_ano = parseFloat(aux2[2]);
	
	var dif = new Object();
	
	var qtDiasMes = new Array();
	qtDiasMes[1]  = 31;
	qtDiasMes[2]  = (d2_ano % 4) ? 29 : 28;
	qtDiasMes[3]  = 31;
	qtDiasMes[4]  = 30;
	qtDiasMes[5]  = 31;
	qtDiasMes[6]  = 30;
	qtDiasMes[7]  = 31;
	qtDiasMes[8]  = 31;
	qtDiasMes[9]  = 30;
	qtDiasMes[10]  = 31;
	qtDiasMes[11]  = 30;
	qtDiasMes[12]  = 31;
	
	if (d2_dia >= d1_dia) {
		dif.dias = d2_dia - d1_dia;
	} else {
		dif.dias = d2_dia + qtDiasMes[d2_mes] - d1_dia;
		d2_mes--;
	}
	
	if (d2_mes >= d1_mes) {
		dif.meses = d2_mes - d1_mes;
	} else {
		dif.meses = d2_mes + 12 - d1_mes;
		d2_ano--;
	}
	
	dif.anos = d2_ano - d1_ano;
	
	return dif;
	
}

function formataFone(obj, evt){
	if(obj.value.length == 8) {
		obj.value = obj.value + "-";
	}
	if(obj.value.length == 1) {
		obj.value = "("+obj.value;
	}
	if(obj.value.length == 3) {
		obj.value = obj.value+")";
	}
}