/* Funções de utilidades básicas */

/*
 * Owner: David Franco (abstraido da library prototype.js)
 * Date: 12/9/2006
 * Função: getElementById abreviado
 * Uso: $("divConteudo") (retorna o objeto) ou $("divConteudo", "paragrafo1") (retorna array de objs);
 * Retorno: (Object)
 * 
 * @param elements (string ou array de strings)
 */
function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}







//Função para chamar o programa de atualização de arquivos
function openFile() {
	var wsh=new ActiveXObject("WScript.Shell");
	wsh.Run("Atualiza_PVet.exe",1);
}

//Finction para esconder os objetos Selects
function EscondeCombo(sHidden){
	for (var i=0; i<document.all.tags("select").length; i++){
		document.all.tags("select").item(i).style.visibility = sHidden;
	}
}

//Function Menu
	function MostraMenu(iMenu, iMenus) {
		var iContador, iContaSub;
		for(iContador=1;iContador<=iMenus;iContador++) {
			eval("document.all.Menu" + iContador + ".style.visibility = 'hidden'");
			for(iContaSub=1;iContaSub<=64;iContaSub++) 
				if(eval('document.all.Menu' + iContador + iContaSub + '')) {
					for(iContaSubSub=1;iContaSubSub<=64;iContaSubSub++) 
						if(eval('document.all.Menu' + iContaSub + iContaSubSub + ''))
							eval('document.all.Menu' + iContaSub + iContaSubSub + '.style.visibility = \'hidden\'');
					eval('document.all.Menu' + iContador + iContaSub + '.style.visibility = \'hidden\'');
				} else {
					if (iMenu == 0) {
						document.all.EscondeMenu.style.display = 'none'
					} else {
						document.all.EscondeMenu.style.display = ''
					}
					break;
				}
		}
		
		if(iMenu>0)
			eval('document.all.Menu' + iMenu + '.style.visibility = \'visible\'');
		return true;
	}

	function MostraSubMenu(iMenu, iSubMenu, iMenus) {
		var iContador;
		
		for(iContador=1;iContador<=iMenus;iContador++) {
			for(iContaSub=1;iContaSub<=64;iContaSub++)
				if(eval('document.all.Menu' + iMenu + iContador + iContaSub)) 
					eval('document.all.Menu' + iMenu + iContador + iContaSub + '.style.visibility = \'hidden\'');

			eval('document.all.Menu' + iMenu + iContador + '.style.visibility = \'hidden\'');
		}

		if(iSubMenu) eval('document.all.Menu' + iMenu + iSubMenu + '.style.visibility = \'visible\'');

		return true;
	}




//Função igual ao TRIM
function TiraEspacos(Texto)
{
   if (Texto.length > 0)
   {
      //Tira espaços da esquerda
      while (Texto.charAt(0) == " ")
      {
         Texto = Texto.substring(1, Texto.length)
      }
 
      if (Texto.length > 0)
      {
         //Tira espaços da direita
         while (Texto.charAt(Texto.length - 1) == " ")
         {
            Texto = Texto.substring(0, Texto.length - 1)
         }
      }
   }
   return Texto
}

//Menu Cadastro
function linkmenucliente(pagina)
{
	document.location.href = pagina;
	MM_showHideLayers('cadastrotext','','hide', 'psmenutext', '', 'hide', 'relatoriotext', '', 'hide', 'administrativotext', '', 'hide', 'sttext', '', 'hide')
}
function linkmenu(pagina)
{
	document.location.href = pagina;
	MM_showHideLayers('cadastrotext','','hide', 'psmenutext', '', 'hide', 'relatoriotext', '', 'hide', 'administrativotext', '', 'hide', 'sttext', '', 'hide')
}


//Só permite que números sejam inputados
function verificaletra(e) { 
var key = '';
var len = len2 = 0;
var strCheck = '\'"';
var codigo = (window.Event) ? e.which : e.keyCode;
if (codigo == 13) return true;  // Tecla Enter
key = String.fromCharCode(codigo);  // Pega o valor de "key"
if (strCheck.indexOf(key) != -1) return false;  // Nao é uma tecla valida
}

//Só permite que números sejam inputados
//valida inputs de números
function verificanumeros(element, blninteiro){
	/*if (element.value.indexOf(',') >= 0 && element.value.indexOf(',') < element.value.length){
		if (element.value.substr(element.value.indexOf(',') + 1,element.value.length).length > 1){
			event.returnValue = false;
			return;
		}
	} */

	if (!element.value.length && event.keyCode==44){
		event.returnValue = false;
		return;
	}
	
	if (event.keyCode >= 48 && event.keyCode < 58){
		event.returnValue = true;
		return;
	}
	else
	{
		if ((event.keyCode == 44) && (blninteiro == 'false')){
			if (element.value.indexOf(',') >= 0){
				event.returnValue = false;
				return;
			}
			else{
				event.returnValue = true;
				return;			
			}
		}
		else
		{
			event.returnValue = false;
			return;
		}
	}
	
			
	if (event.keyCode == 8 ){
		return;
	}

}

//Só permite que números sejam inputados
//valida inputs de números
//Recebe por parâmetro o número de casas decimais após a vigula
function verificanumeros2(element, blninteiro, decimais){
	if (element.value.indexOf(',') > 0 && element.value.indexOf(',') < element.value.length){
		if (element.value.substr(element.value.indexOf(',') + 1,element.value.length).length > (decimais-1)){
			event.returnValue = false;
			return;
		}
	}

	if (!element.value.length && event.keyCode==44){
		event.returnValue = false;
		return;
	}
	
	if (event.keyCode >= 48 && event.keyCode < 58){
		event.returnValue = true;
		return;
	}
	else
	{
		if ((event.keyCode == 44) && (blninteiro == 'false')){
			if (element.value.indexOf(',') > 0){
				event.returnValue = false;
				return;
			}
			else{
				event.returnValue = true;
				return;			
			}
		}
		else
		{
			event.returnValue = false;
			return;
		}
	}
	
			
	if (event.keyCode == 8 ){
		return;
	}

}


// Função que retorna true apenas se todos os caracteres do campo
// estejam especificados no parametro 'mascara'
// parametro event = opcional: se for passado no keypress de um campo,
//					 não permite que o valor seja digitado,
//					 se não estiver na mascara
// Usar: onkeypress="return verificaMascara(this, '123456abc/', event)" ...
//		 ou var valido = verificaMascara(elemento, '123456');
function verificaMascara(element, mascara, event){
	var letra;

	if (event!=null) { //se for passado o evento (a letra que está sendo pressionada)
		if (event.keyCode==13) {
			return true;
		} else {
			letra = String.fromCharCode(event.keyCode);
			if (mascara.indexOf(letra) < 0) {
				return false;
			}
		}

		return true;
	}

	for (var i=0; i<element.value.length ; i++ ) {
		letra = element.value.substring(i,i+1);
		if (mascara.indexOf(letra) < 0) {
			return false;
		}
	}

	return true;
}





//Função para formatar Data - Usar no método onKeyPress
function FormataData(Obj, Campo){
	var Data = Campo.value;

	//Verifica o Tamanho da string
	if (Data.length<10){
		// Verifica se é número			
		if (Obj.keyCode>=48 && Obj.keyCode<=57){
			switch(Data.length){
				case 2: Data = Data + "/"; break;
				case 5:	Data = Data + "/"; break;
				case 10: Data = Data + (Obj.keyCode = ""); break;
			}
		}else Obj.keyCode = "";
		
	}else Data = Data + (Obj.keyCode = "");
				
	Campo.value = Data;
	//return Data;
}

//Formata telefone - usar no método onChange
function FormataFoneTraco(Campo){
    if (Campo.value.length >= 7){
       if (Campo.value.substring(Campo.value.length - 5, Campo.value.length - 4) != '-'){
	   Campo.value = Campo.value.substring(0, Campo.value.length - 4) + '-' + Campo.value.substring(Campo.value.length - 4, Campo.value.length);
       }
    }
}


//formata Telefone
function formatatelefone(element){
	if ( (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 ) && (event.keyCode < 33 || event.keyCode > 36 ) && (event.keyCode < 45 || event.keyCode > 46) && (event.keyCode != 8) && (event.keyCode != 9) && (event.keyCode != 13) && (event.keyCode != 110) && (event.keyCode != 190) ){
		event.returnValue = false;
		return;
	}
			
	if (event.keyCode == 8 ){
		return;
	}

	if (element.value.length == 4){
		element.value = element.value + "-";
	}
}


//formata Telefone com ddd (ddd-xxxx-xxxx)
function formatatelefoneddd(element){
	if(!(event.keyCode >= 48 && event.keyCode <= 57)){
		event.returnValue = false;
		return;
	}
			
	if (event.keyCode == 8 ){
		return;
	}

	if (element.value.length == 3 || element.value.length == 8){
		element.value = element.value + "-";
	}
}



//Formata CEP - usar no método onKeyPress
function FormataCep(Obj, Campo){
	var CEP = Campo.value;

	//Verifica o Tamanho da string
	if (CEP.length<9){
		// Verifica se é número			
		if (Obj.keyCode>=48 && Obj.keyCode<=57){
			switch(CEP.length){
				case 5: CEP = CEP + "-"; break;
				case 9: CEP = CEP + (Obj.keyCode = ""); break;
			}
		}else Obj.keyCode = "";
		
	}else CEP = CEP + (Obj.keyCode = "");
				
	Campo.value = CEP;

}


//Function para Validar Data
function ValidaDate(campo,NomeCampo) {
	
	data = campo.value;
	dia = data.substring(0,2);
	mes = data.substring(3,5);
	ano = data.substring(6,10);
	barra1 = data.substring(2,3);
	barra2 = data.substring(5,6);
	nome = campo.name;
	campo.style.color = "black";

	hoje = new Date()
	// hoje.setDate(dia);
	// hoje.setMonth(mes-1);
	
	if (data != ''){
		if ((barra1 != "/") || (barra2 != "/")) {
			alert("O formato do campo "+ NomeCampo +" esta inválido ! Exemplo: dd/mm/aaaa");
			campo.focus();
			return false;
		}
		if ( isNaN(dia) || (dia < 1) || (dia > 31)) {
			alert("O Dia do campo "+ NomeCampo +" é inválido");
			campo.focus();
			return false;
		}
		else if (isNaN(mes) || (mes < 1) || (mes > 12) ) {
			alert("O Mes do campo "+ NomeCampo +" é inválido");
			campo.focus();
			return false;
		}
		else if (isNaN(ano)) {
			alert("O Ano do campo "+ NomeCampo +" contém caracteres inválidos");
			campo.focus();
			return false;
		}
		else if (data.length != 10) {
			alert("O formato do campo "+ NomeCampo +" está inválido ! Exemplo: dd/mm/aaaa");
			campo.focus();
			return false;
		}
		quociente4 = (eval(ano) % 4);
		quociente100 = (eval(ano) % 100);
		quociente400 = (eval(ano) % 400);
		if ((quociente4 == 0) || (quociente100 == 0) && (quociente400 == 0))
			biss = true;
		else
			biss = false;

		if (ano < 1900) {
			alert("O Ano do campo "+ NomeCampo +" não pode ser menor que 1900 !");
			campo.focus();
			return false;
		}
		if (mes == 2) {
			if ((dia == 29) && (biss == false)) {
				alert("O Dia do campo "+ NomeCampo +" é inválido,\npois o ano não e bissexto!");
				campo.focus();
				return false;
			}
			else if ((dia == 30) || (dia == 31)) {
				alert("O Dia do campo "+ NomeCampo +" é inválido para o mês de Fevereiro!");
				campo.focus();
				return false;
			}
		}
		else if ((mes == 4) && (dia == 31)) {
			alert("O Dia do campo "+ NomeCampo +" é inválido para o mês de Abril!");
			campo.focus();
			return false;
		}
		else if ((mes == 6) && (dia == 31)) {
			alert("O Dia do campo "+ NomeCampo +" é inválido para o mês de Junho!");
			campo.focus();
			return false;
		}
		else if ((mes == 9) && (dia == 31)) {
			alert("O Dia do campo "+ NomeCampo +" é inválido para o mês de Setembro!");
			campo.focus();
			return false;
		}
		else if ((mes == 11) && (dia == 31)) {
			alert("O Dia do campo "+ NomeCampo +" é inválido para o mês de Novembro!");
			campo.focus();
			return false;
		}
	}
	return true;
}


//Function para formatar CPF
function FormataCpf(Obj, Campo) {
	var CPF = Campo.value;

	//Verifica o Tamanho da string
	if (CPF.length<14){
		// Verifica se é número			
		if (Obj.keyCode>=48 && Obj.keyCode<=57){
			switch(CPF.length){
				case 3:  CPF = CPF + "."; break;
				case 7:	 CPF = CPF + "."; break;
				case 11: CPF = CPF + "-"; break;
				case 14: CPF = CPF + (Obj.keyCode = ""); break;
			}
		}else Obj.keyCode = "";
		
	}else CPF = CPF + (Obj.keyCode = "");
				
	Campo.value = CPF;
}


//Function para formater CGC
function FormataCgc(Obj, Campo) {
	var CGC = Campo.value;

	//Verifica o Tamanho da string
	if (CGC.length<18){
		// Verifica se é número			
		if (Obj.keyCode>=48 && Obj.keyCode<=57){
			switch(CGC.length){
				case 2:  CGC = CGC + "."; break;
				case 6:	 CGC = CGC + "."; break;
				case 10: CGC = CGC + "/"; break;
				case 15: CGC = CGC + "-"; break;
				case 18: CGC = CGC + (Obj.keyCode = ""); break;
			}
		}else Obj.keyCode = "";
		
	}else CGC = CGC + (Obj.keyCode = "");
				
	Campo.value = CGC;
}

//Function para determinar o Numero máximo de caracteres em um campo
function MaxCaracter(Campo, NStr){
	if (Campo.value.length>NStr){
		event.keyCode = "";
	}	
}

//Function para Validar CPF
function ValidaCPF(campo)
{
	sValor1 = campo.value;
	sValor1 = sValor1.toString();
	sValor = '';
	xpqp = sValor1.length
	for (iputo = 0; iputo < xpqp; iputo++)
	{
		sAux = sValor1.charAt(iputo);
		if (sAux < '0' || sAux > '9')
		{
			if (sAux != '.' && sAux != '-' && sAux != '/'){
				return false;
			}
		}
		else
		{
			sAux = sAux.toString();
			sValor = sValor + '' + sAux;
		}
	}
	if (sValor != '')
	{
		if (isNaN(sValor) || sValor.length != 11){
			return false;
		}
		soma = (sValor.substr(0,1) * 10) + (sValor.substr(1,1) * 9) + (sValor.substr(2,1) * 8) + (sValor.substr(3,1) * 7) + (sValor.substr(4,1) * 6) + (sValor.substr(5,1) * 5) + (sValor.substr(6,1) * 4) + (sValor.substr(7,1) * 3) + (sValor.substr(8,1) * 2);
		dv1 = (soma % 11);
		if (dv1 == 0 || dv1 == 1) 
			dv1 = 0;
		else
			dv1 = 11 - dv1;
		soma = (sValor.substr(0,1) * 11) + (sValor.substr(1,1) * 10) + (sValor.substr(2,1) * 9) + (sValor.substr(3,1) * 8) + (sValor.substr(4,1) * 7) + (sValor.substr(5,1) * 6) + (sValor.substr(6,1) * 5) + (sValor.substr(7,1) * 4) + (sValor.substr(8,1) * 3) + (dv1 * 2);
		dv2 = (soma % 11);
		if (dv2 == 0 || dv2 == 1) 
			dv2 = 0;
		else
			dv2 = 11 - dv2;
		if (sValor.substr(9,1) != dv1 || sValor.substr(10,1) != dv2){
			return false;
		}
	}
	return true;
}



//Function para Validar CGC
function ValidaCGC(campo){

	sValor1 = campo.value;
	sValor1 = sValor1.toString();
	sValor = '';
	xpqp = sValor1.length
	for (iputo = 0; iputo < xpqp; iputo++)
	{
		sAux = sValor1.charAt(iputo);
		if (sAux < '0' || sAux > '9')
		{
			if (sAux != '.' && sAux != '-' && sAux != '/'){
				return false;
			}
		}
		else
			sValor = sValor + sAux
	}
	if (sValor != '')
	{
		if (isNaN(sValor) || sValor.length != 14){
			return false;
		}
		soma = (sValor.substr(0,1) * 5) + (sValor.substr(1,1) * 4) + (sValor.substr(2,1) * 3) + (sValor.substr(3,1) * 2) + (sValor.substr(4,1) * 9) + (sValor.substr(5,1) * 8) + (sValor.substr(6,1) * 7) + (sValor.substr(7,1) * 6) + (sValor.substr(8,1) * 5) + (sValor.substr(9,1) * 4) + (sValor.substr(10,1) * 3) + (sValor.substr(11,1) * 2)
		dv1 = (soma % 11);
		if (dv1 == 0 || dv1 == 1) 
			dv1 = 0;
		else
			dv1 = 11 - dv1;
		soma = (sValor.substr(0,1) * 6) + (sValor.substr(1,1) * 5) + (sValor.substr(2,1) * 4) + (sValor.substr(3,1) * 3) + (sValor.substr(4,1) * 2) + (sValor.substr(5,1) * 9) + (sValor.substr(6,1) * 8) + (sValor.substr(7,1) * 7) + (sValor.substr(8,1) * 6) + (sValor.substr(9,1) * 5) + (sValor.substr(10,1) * 4) + (sValor.substr(11,1) * 3)  + (dv1 * 2)
		dv2 = (soma % 11);
		if (dv2 == 0 || dv2 == 1) 
			dv2 = 0;
		else
			dv2 = 11 - dv2;
		if (sValor.substr(12,1) != dv1 || sValor.substr(13,1) != dv2){
			return false;
		}
	}
	return true;
}

//Função para comparação de Datas
function ComparaData(DataInicio, DataFim, Data1, Data2) { 
	if (DataFim.value != ''){
		var sDataInicioDia = DataInicio.value.substring(0, 2);
		var sDataInicioMes = DataInicio.value.substring(3, 5);
		var sDataInicioAno = DataInicio.value.substring(6, 10);
		var sDataFimDia	   = DataFim.value.substring(0, 2);
		var sDataFimMes    = DataFim.value.substring(3, 5);
		var sDataFimAno    = DataFim.value.substring(6, 10);
		if ((sDataFimAno < sDataInicioAno) || (sDataFimAno <= sDataInicioAno && sDataFimMes < sDataInicioMes) || (sDataFimAno <= sDataInicioAno && sDataFimMes <= sDataInicioMes && sDataFimDia < sDataInicioDia)){
			alert('ATENÇÃO !!!\nA '+ Data2 +' não pode ser inferior a '+ Data1 +'.')
			eval('document.forms[0].' + DataFim.name + '.focus()');
			return false;
		}
	}return true;
}

//Function valida Email - Metodo onSubmit
function Email(campo){
	var i = 1;
	sValor = campo.value
	sLength = sValor.length;

	while ((i < sLength) && (sValor.charAt(i) != '@'))
		i++
	if ((i >= sLength) || (sValor.charAt(i) != '@')) {
		return false;
	}
	else
		i += 2;
	while ((i < sLength) && (sValor.charAt(i) != '.'))
		i++
	if ((i >= sLength - 1) || (sValor.charAt(i) != '.')) {
		return false;
	}
	return true;
}

function geraComboMesBtw(nome, value, sel){
	var strRetorno, i, valor;
	
	strRetorno = '<select name="' + nome + '">';
	strRetorno += '<option value="0">--- Escolha ---</option>'

	valor = value;
	for (i=1; i<=12; i++)
	{
		strRetorno += '<option value="' + valor + '"';
		if ((sel==i))
			strRetorno += ' selected';
		strRetorno  += '>' + DsMes(i) + '</option>'
		valor = valor * 2;
	}

	strRetorno += '</select>'
	return strRetorno;
}

function DsMes(ind){
	switch (ind){
		case 1:
			return "Janeiro";
		case 2:
			return "Fevereiro";
		case 3:
			return "Março";
		case 4:
			return "Abril";
		case 5:
			return "Maio";
		case 6:
			return "Junho";
		case 7:
			return "Julho";
		case 8:
			return "Agosto";
		case 9:
			return "Setembro";
		case 10:
			return "Outubro";
		case 11:
			return "Novembro";
		case 12:
			return "Dezembro";
	}
}

function DsMesResumido(ind){
	switch (ind){
		case 1:
			return "JAN";
		case 2:
			return "FEV";
		case 3:
			return "MAR";
		case 4:
			return "ABR";
		case 5:
			return "MAI";
		case 6:
			return "JUN";
		case 7:
			return "JUL";
		case 8:
			return "AGO";
		case 9:
			return "SET";
		case 10:
			return "OUT";
		case 11:
			return "NOV";
		case 12:
			return "DEZ";
	}
}


/*
Owner: Leandro Berbel
Date: 22/06/2004
Função: Formatar número com x casas decimais
Uso: formataNumero(5000000.2,2) <<retorno>> 5.000.000,20
Modificado em 20/09/2005 por Alexandre Henriques Nunes para
aceitar valores negativos
*/
function formataNumero(numero,x){

	var blSinal=0;

	if(numero<0) {
		blSinal=1;
		numero=-numero; // Inverte o sinal
	}

	if (!isNaN(numero)){//não é número
		numero = Math.round(numero* Math.pow(10,x) );
		numero = parseFloat(numero/ Math.pow(10,x));
	}
	numero=String(numero);
	
	if(isNaN(numero)){//não é número
		str_inteiro="0";
		str_decimal="";					
	} else {	
		if(numero.indexOf('.')==-1){ //não tem casas decimais
			str_inteiro=numero;
			str_decimal="";
		} else { //número com casas decimais
			str_inteiro=numero.substr(0,numero.indexOf('.'));
			str_decimal=numero.substr(numero.indexOf('.')+1,x);	
		}
	}
	
	pos=3; //variável que controla a posição dos pontos
	while(str_inteiro.length>pos){
		numeros=str_inteiro.substr(str_inteiro.length-pos,pos);
		str_inteiro=str_inteiro.substr(0,str_inteiro.length-pos)+"."+numeros;
		pos+=4;//mais 4 pois agora tem o ponto
	}	

	for(i=str_decimal.length;i<x;i++){//completa com zeros
		str_decimal=str_decimal+"0";
	}

	str_total=str_inteiro+","+str_decimal;	//contatena as strings
	if(blSinal) str_total='-'+str_total;
	return str_total;
}

function pow(a,b){
	var i, retorno = a;
	for (i=1; i<b; i++){
		retorno = retorno * a;
	}
	return retorno;
}

function SomatoriaVetor(vetor){
	var i, retorno = 0;
	for(i=0; i<vetor.length; i++){
		retorno += parseInt(vetor[i]);
	}
	return retorno
}


function abrevia(str,tamanho) {
	if (str.length > tamanho)
	{
		return str.substring(0,tamanho) + " ...";
	} else {
		return str;
	}
}

/// Melhorias no método parseFloat
function parseFloatX(texto){
	texto = "" + texto; // força o parametro (que pode ser um número) virar um texto, afim de fazer os replaces
	var retorno = texto.replace(/^0*/,'').replace(/\./g,'').replace(/\,/g,'.');

	retorno = parseFloat(retorno==''?0:retorno);
	if (retorno=="undefined" || isNaN(retorno))
		throw texto + "	não é um número !";

	return retorno;
}

/*
 * Owner: David Franco
 * Date: 01/08/2006
 * Função: Esconde/mostra um objeto alterando a versão 
 * Uso: escondeMostra('id_div', false);
 * 
 * @param id (string ou objeto)
 * @param estado (bool ou string) - opcional. Se nao for setado, faz um toggle, senao muda pro valor setado
 * 									pode ser true/false ou 'none'/'block'
 */
function escondeMostra(obj, estado){
	var objeto;
	if(typeof(obj)=="string") {
		objeto = document.getElementById(obj);
	} else if (typeof(obj)!="object") {
		alert("escondeMostra erro: Objeto inválido");
		return;
	} else {
		objeto = obj;
	}

	if (estado != null) {
		if (estado==true) estado = 'block';
		if (estado==false) estado = 'none';
		objeto.style.display = estado;
	} else {
		objeto.style.display = (objeto.style.display=='none') ? 'block' : 'none';
	}
}


/*
 * Owner: David Franco
 * Date: 01/08/2006
 * Função: Seleciona todos ou nenhum de uma lista de checkboxes
 * Uso: selecionaChecks('checks', 'idBotao');
 * 
 * @param objChecks (string ou objeto) : name dos checkboxes ou um array de checkboxes
 * @param objBotao  (string ou objeto) : id ou objeto do botão
 * @param valor     (boolean) opcional : Se nao for setado, alterna sozinho, senao muda pro valor setado
 */
function selecionaChecks(objChecks, objBotao, valor){
	var checks = (typeof(objChecks)=="string") ? document.getElementsByName(objChecks) : objChecks;
	var botao = (typeof(objBotao)=="string") ? $(objBotao) : objBotao;
	if (valor==null) {
		valor = (botao.value=='X') ? true : false;
	}

	if (botao.value == 'X') {
		botao.value = '';
		botao.title = 'Deselecionar todos';
		valor = true;
	} else {
		botao.value = 'X';
		botao.title = 'Selecionar todos';
		valor = false;
	}
	if (checks.length) {
		for (var i=0; i<checks.length; i++) checks[i].checked = valor;
	} else {
		checks.checked = valor;
	}
}



/* abrePopUp
 * Owner: David Franco
 * Abre uma janela PopUp
 * 
 * Parametros:
 * @link 			(string) página que o PopUp deve abrir
 * @retornaJanela 	(bool) true para que o retorno da funcao seja o objeto Janela - opcional
 * @width 			(string) largura em pixels- opcional
 * @height 			(string) algura em pixels - opcional
 *
 * Retorno: null
 *
 * ex: abrePopUp('produto.asp');
 * ex: abrePopUp('produto.asp', 800); // abre janela com valor default para altura, e 800 de largura
 */
function abrePopUp (link, retornaJanela, width, height) {
	if (width==null) width = "600";
	if (height==null) height = "400";
	if (retornaJanela==null) retornaJanela = false;

	if (link != null) {
		var janela = window.open(link,'janelaPop','location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no,width=' + width + ',height=' + height);
		if (janela != null)
			janela.focus();
	}

	if (retornaJanela) {
		return janela;
	} else {
		return false;
	}
}


/* checksSelecionados
 * Owner: David Franco
 * Conta quantos checkboxes de determinado nome estão selecionados. Útil para validar formulários.
 * 
 * Parametros:
 * @form 			(string ou object) formulário onde estão os checkboxes
 * @checksName		(string ou object) atributo name dos checks, ou coleção já pronta de checks
 *
 * Retorno: inteiro
 *
 * ex: if (checksSelecionados("meuForm", "meusChecks") == 0) { alert('selecione ao menos um item!'); return false; }
 */
function checksSelecionados(objForm, checksName) {
	var form = (typeof(objForm)=="string") ? $(objForm) : objForm;
	var checks = (typeof(checksName)=="string") ? document.getElementsByName(checksName) : checksName;
	var checados = 0;

	if (checks != null) {
		if (checks.length) {
			for (var i = 0; i < checks.length ; i++ ) {
				if (checks[i].checked == true) {
					checados ++;
				}
			}
		} else {
			if (checks.checked == true) {
				checados++;
			}
		}

		return checados;
	} else {
		return 0;
	}
}

