//Verifica qual o browser do visitante e armazena na variável púbica browser,
 //Caso Internet Explorer(IE) outros (Other)
 var browser;
 if (navigator.appName.indexOf('Microsoft') != -1){
 	browser = "IE";
 }else{
 	browser = "Other";
 }
/****WENNYS EM 02/09/2007****/
/***
	Classe ValidaForm
	Autor : Wennys Carlos de Sousa
	Data  : 02/09/2007
	Descrição : Classe que Controla a validacao de Formulario HTML (Campos TEXT , TEXTAREA , PASSWORD e SELECT)
****/
function ValidaForm(){ //class ValidaForm
	this.indice = 0; //inicializa o indice do vetor de campos
	this.campo = new Array(); //inicializa o vetor de campos a serem validados
	
	this.addCampo = function addCampo(campo){ // recebe o id do campo a ser validado
		this.campo[this.indice] = campo; //adiciona o id do campo a ser validado ao vetor de campos a serem validados
		this.indice++; //incrementa o indice do vetor de campos
		
	}

	this.validar = function validar(){
		var i , campo , tipo , nome , id; //declaracao de variaveis para evitar alertas no firefox
		this.erros = 0; //inicializa o numero de erros
		for(i = 0 ; i < this.campo.length ; i++){ //percorre o vetor de campos a serem validados
			campo = document.getElementById(this.campo[i]);
			tipo  = campo.type;
			nome  = campo.name;
			id    = campo.id;
			//valor = form.elements[i].value; //soment para campos text , password textarea
			//if(tipo != 'reset' and tipo != 'button' and tipo != 'image' and tipo != 'checkbox' and tipo != 'radio'){
			//if(tipo == 'text' or tipo == 'password' or tipo == 'textarea' or tipo == 'select' or tipo == 'file')
			if(tipo == 'text' || tipo == 'textarea' || tipo == 'password'){
				if(!this.validaText(campo)){ //chama o metodo que valida os campos TEXT , TEXTAREA E PASSWORD
					this.erros++; //incrementa o numero de erros
					return false; //quebra o fluxo
				}
			}

			if(tipo == 'select-one' || tipo == 'select-multiple'){
				if(!this.validaSelect(campo)){ //chama o metodo que valida os campos SELECT
					this.erros++; //incrementa o numero de erros
					return false; //quebra o fluxo
				}
			}
			
		} //fim for
		return true;
	} //fim metodo validar
	
	this.validaText = function validaText(campo){
		var value , label;
		value = campo.value;
		
		if(campo.alt){
			label = campo.alt;
		}else{
			label = campo.id; //pesquisar sobre o elemento <label>
		}
		if(value == "" || value == " "){
			alert("O Campo "+label+" Deve Ser Preenchido!");
			campo.focus();
			return false;
		}else{
			return true;
		}
	
	}

	this.validaSelect = function validaSelect(campo){
		var value;
		value = campo.selectedIndex;
		if(value == 0 || value == ""){
			alert("O Campo Obrigatório deve ser Preenchido!");
			campo.focus();
			return false;
		}else{
			return true;
		}
		
	}

} //fim class ValidaForm

function redirecionar(url){
	if(url == '-1'){
		window.history.go(-1);	
	}else{
		if(url == '1'){
			window.history.go(1);
		}else{
			window.location.assign(url);			
		}
	}
}

function novo(){
	var protocolo , hostname , pathname , path;
	protocolo = window.location.protocol;
	hostname  = window.location.hostname;
	pathname  = window.location.pathname;
	path = protocolo+"//"+hostname+pathname;
	window.location.assign(path);
}
function cancelar(){
	window.document.forms[0].reset();	
}
function fechar(janela){
	if(janela == "self" || janela == null){
		window.self.close();
	}

	if(janela == "top"){
		window.top.close();
	}

	if(janela == "parent"){
		window.parent.close();
	}

	if(janela == "top.opener"){
		window.top.opener.close();
	}	
}
function recarregar(janela){
	if(janela == "self" || janela == null){
		window.self.location.reload(true);
	}

	if(janela == "top"){
		window.top.location.reload(true);
	}

	if(janela == "parent"){
		window.parent.location.reload(true);
	}

	if(janela == "top.opener"){
		window.top.opener.location.reload(true);
	}

}
function submeter(janela){
	if(janela == "self" || janela == null){
		window.document.forms[0].submit();
	}

	if(janela == "top"){
		window.top.document.forms[0].submit();
	}

	if(janela == "parent"){
		window.parent.document.forms[0].submit();
	}

	if(janela == "top.opener"){
		window.top.opener.document.forms[0].submit();
	}

}
function imprimir(){
	window.print();
}
/****************************/
//##################################################################################################################
//funcao para abrir popups no centro da tela
function abrirPopup(url, nome, w, h, scroll) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    //var winl = (794 - w) / 2;
    //var wint = (660 - h) / 2;
    propriedades = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes,status=yes,location=no';
    var win = window.open(url, nome, propriedades);

    if (parseInt(navigator.appVersion) >= 4){
        win.window.focus();
    }
}
// igual à funcao acima. mantida por questao de compatibilidade com versoes anteriores do framework
// funcao para abrir popups no centro da tela
function abrir_popup(url, nome, w, h, scroll) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    //var winl = (794 - w) / 2;
    //var wint = (660 - h) / 2;
    propriedades = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes,status=yes';
    var win = window.open(url, nome, propriedades);

    if (parseInt(navigator.appVersion) >= 4){
        win.window.focus();
    }
}


//##################################################################################################################
//FUNCAO QUE MASCARA OS CAMPOS TEXTO
function mascara(event,formatacao){
    var tecla;    //variavel q recebera a tecla digitada
    var codigo_tecla;  //variavel q receberá o codigo ASCII da tecla
    
	if(browser == "IE" )
		codigo_tecla=event.keyCode;  //recebe o codigo ASCII da tecla digitada
	else
		codigo_tecla=event.charCode;  //recebe o codigo ASCII da tecla digitada
		
		
    tecla = String.fromCharCode(codigo_tecla);  //recebe a tecla

    return valida_caractere(tecla,event,formatacao); //chama a funcao valida_tecla, que
                                      //retorna true se a tecla for válida e false se não for
}

//FUNCAO QUE VALIDA TECLA (É CHAMADA PELA FUNCAO MASCARA)
function valida_caractere(caractere,event,formatacao){
    //conjunto de caracteres válidos//
    var caracteres_validos;
	
	if(browser == "IE" )
		codigo_tecla=event.keyCode;  //recebe o codigo ASCII da tecla digitada
	else
		codigo_tecla=event.charCode;  //recebe o codigo ASCII da tecla digitada

   
   
   switch(formatacao){
        case "NUMEROS" :

            caracteres_validos = "0123456789";
            break;

        case "CONSULTA" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%";
            break;

        case "ABCDE" :

            caracteres_validos = "ABCDEabcde";
            break;

        case "0|1|2" :

            caracteres_validos = "012";
            break;

        case "4|5" :

            caracteres_validos = "45";
            break;

        case "EDITAL" :

            caracteres_validos = "01234567/89";
            break;

        case "MAIUSCULAS" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\ÁáÂâÃãÉéÊêÍíÓóÔôÕõÚúÇç()°";
            break;
			
        case "ALFANUM" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-ÁáÂâÃãÉéÊêÍíÓóÔôÕõÚú/\Çç()°";
            break;

        case "S|N" :

            caracteres_validos = "snSN"; //sim ou nao
            break;

        case "NUMEROSPOSITIVOS" :

            caracteres_validos = "123456789";
            break;

        default :
            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123\456789/-°()";
    }
    
	
	if( caracteres_validos.indexOf(caractere) != -1 || codigo_tecla < 31){
		return true ;
	}else{
		return false;
	}
   
}//fim da funcao valida_caractere

//#########################################################################################################################

//funcao para tornar o valor de um campo em maiusculas
function upperCase(campo){
	campo.value = campo.value.toUpperCase();
}

//#########################################################################################################################
//FUNCAO PARA FORMATAR CAMPOS DE DATA,HORA,ETC...

function FormataCampo(Campo,teclapres,mascara){
    
	//escolhe a funcao de acordo com o navegador
	if(browser == "IE")
		tecla = teclapres.keyCode;
	else
		tecla = teclapres.charCode;
		
	//pegando o tamanho do texto da caixa de texto com delay de -1 no event
    //ou seja o caractere que foi digitado não será contado.
	//teclapres = window.event;
	strtext = Campo.value
    tamtext = strtext.length
    //pegando o tamanho da mascara
    tammask = mascara.length
    //criando um array para guardar cada caractere da máscara
    arrmask = new Array(tammask)
    //jogando os caracteres para o vetor
    for (var i = 0 ; i < tammask; i++){
        arrmask[i] = mascara.slice(i,i+1)
    }
    //alert (tecla)
    //começando o trabalho sujo
    if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){
        if ((tecla >= 37 && tecla <= 40)||(tecla >= 48 && tecla <= 57)||(tecla >= 96 && tecla <= 105)||(tecla == 8)||(tecla == 9) ||(tecla == 46) ||(tecla == 13)){
            Organiza_Casa(Campo,arrmask[tamtext],tecla,strtext)
        }
        else{
            Detona_Event(Campo,strtext)
        }
    }
    else{//Aqui funcionaria a mascara para números mas eu ainda não implementei
        if ((arrmask[tamtext] == "A"))    {
            charupper = event.valueOf()
            //charupper = charupper.toUpperCase()
            Detona_Event(Campo,strtext)
            masktext = strtext + charupper
            Campo.value = masktext
        }
    }
}
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){
    if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){
        separador = arrpos
        masktext = strtext + separador
        Campo.value = masktext
    }
}
function Detona_Event(Campo,strtext){
    
    if (strtext != "") {
        Campo.value = strtext
    }
	return false;
}


function Bloqueia_Caracteres(evnt){
 //Função permite digitação de números
 	if (browser == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false;
 		}
 	}else{
 		if (( (evnt.charCode > 31 && evnt.charCode < 48 ) || evnt.charCode > 57) && evnt.charCode == 0){
 			return false;
 		}
 	}
 }
 
 //#################################################################################################################
 

//funcao que verifica se as datas foram digitadas corretamente

function Verifica_Data(data, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
  //var data = document.getElementById(data);
 	var strdata = data.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
 			alert("Formato da data não é válido.Formato correto: dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
 			alert("Formato da data não é válido. Formato correto: dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		dia = strdata.substr(0,2)
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Formato do dia não é válido.");
 			data.focus();
 			return false
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mês informado não possui 31 dias.");
 				data.focus();
 				return false
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mês informado possui somente 29 dias.");
 					data.focus();
 					return false
 				}
 			}else{
 				if (dia > 28){
 					alert("O mês informado possui somente 28 dias.");
 					data.focus();
 					return false
 				}
 			}
 		}
 	//Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
 			alert("Formato do mês não é válido.");
 			data.focus();
 			return false
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Formato do ano não é válido.");
 			data.focus();
 			return false
 		}
 	}
 }
 
//######################################################################################################################

//funcao que verifica se as horas foram digitadas corretamente
function Verifica_Hora(hora, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var hora = document.getElementById(hora);
 	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){
 		if(hora.value.length < 5){
 			alert("Formato da hora inválido.Por favor, informe a hora no formato correto: hh:mm");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){
 			alert("Formato da hora inválido.");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
 			alert("Formato do minuto inválido.");
 			hora.focus();
 			return false
 		}
 	}
 }

//#######################################################################################################


//funcao que mascara os campos de moeda colocando automaticamente os pontos e as virgulas
function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13 || whichCode < 31 ) return true;
key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt
(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
fld.value= fld.value;

}
return false;
}

//###################################################################################################

//funcao que verifica se os emails foram digitados corretamente
function Verifica_Email(email, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var email = document.getElementById(email);
 	if((obrigatorio == 1) || (obrigatorio == 0 && email.value != "")){
 		if(!email.value.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.[a-zA-Z0-9._-]+)/gi)){
 			alert("Informe o e-mail corretamente.");
 			email.focus();
 			return false
 		}else{ return true;}
 	}
 }
 
//###################################################################################################

//funcao que verifica se os ceps foram digitados corretamente
 function Verifica_Cep(cep, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var cep    = document.getElementById(cep);
 	var strcep = cep.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
 		if (strcep.length != 9){
 			alert("CEP informado inválido.");
 			cep.focus();
 			return false
 		}else{
 			if (strcep.indexOf("-") != 5){
 				alert("Formato de CEP informado inválido.");
 				cep.focus();
 				return false
 			}else{
 				if (isNaN(strcep.replace("-","0"))){
 					alert("CEP informado inválido.");
 					cep.focus();
 					return false
 				}
 			}
 		}
 	}	  
 }
 
 
//##############################################################################################################

//funcao que mascara os campos de cep colocando o '-'
function Ajusta_Cep(input, evnt){
 //Ajusta máscara de CEP e só permite digitação de números
 	if (input.value.length == 5){
 		if(browser == "IE"){
 			input.value += "-";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "-";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }
 
//#####################################################################################################


 function valida_cpf_cnpj(form) {
	var invalid, s;
	invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

	var s;

// inicio de verificacao de cnpj ou cpf
	
	s = form.value;
	
	
	// CHECA SE EH CPF	
	if (s.length == 11) {
		if (valida_cpf(form.value) == false ){
			alert("O CPF  "+form.value+"  não é válido !\n        Tente novamente !");
		   document.form_candidato.cpf.focus();
            return false;	
            }
     }

     //CHECA SE EH CNPJ
	else if (s.length == 14) {
		if (valida_cnpj(form.value) == false ) {
			alert("O CNPJ  "+form.value+"  não é válido !\n       Tente novamente !");
			document.form_candidato.cpf.focus();
            return false;
        }
	}else{
			alert("O CPF  "+ form.value+"  não é válido !\n     Tente novamente !");
			document.form_candidato.cpf.focus();
			return false;
    }
		
     return true;
}
// FIM DA FUNCAO VALIDA_CPF_CNPJ(), FUNCAO PRINCIPAL


function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}
//FIM DA FUNCAO LIMPA_STRING()


////funcao que valida só o CPF
function valida_cpf(s)	{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}
////fim funcao valida_CPF

///funcao que valida só o CNPJ
function valida_cnpj(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
	return true;
}
////FIM DO BLOCO DE FUNCOES PARA VALIDACAO DO CPF/CNPJ////

//##############################################################################################################

//funcao que mascara os campos de cep colocando o '-'
function validaEdital(input, evnt){
 
 	if(input.value != ''){
			inicio = input.value.indexOf('/');
			fim = input.value.length - 1;
			str = input.value.substr(inicio , fim) ;
			
			if(str.length != 5 || inicio == -1){
				alert("Digite um Número de Edital na Forma n°edital/Ano");
				//input.focus();
			}
	}else{
		alert("Digite um Número de Edital/Ano");
		//input.focus();
	}
	
 	
 	
 	
 }
 
//#####################################################################################################

function Ajusta_Hora(input, evnt){
 //Ajusta máscara de Hora e só permite digitação de números
 	if (input.value.length == 2){
 		if(browser == "IE"){
 			input.value += ":";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += ":";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }

//FUNCAO TIGRA TABLES ...ativa cor diferente no evento onmouseover de linhas de tabelas//////
// Title: tigra tables
// URL: http://www.softcomplex.com/products/tigra_tables/
// Version: 1.1
// Date: 08/15/2005
// Notes: Permission given to use this script in any kind of applications if
//    header lines are left unchanged.

function tigra_tables (
		str_tableid, // table id (req.)
		num_header_offset, // how many rows to skip before applying effects at the begining (opt.)
		num_footer_offset, // how many rows to skip at the bottom of the table (opt.)
		str_odd_color, // background color for odd rows (opt.)
		str_even_color, // background color for even rows (opt.)
		str_mover_color, // background color for rows with mouse over (opt.)
		str_onclick_color // background color for marked rows (opt.)
	) {

	// validate required parameters
	if (!str_tableid) return alert ("No table(s) ID specified in parameters");
	var obj_tables = (document.all ? document.all[str_tableid] : document.getElementById(str_tableid));
	if (!obj_tables) return alert ("Can't find table(s) with specified ID (" + str_tableid + ")");

	// set defaults for optional parameters
	var col_config = [];
	col_config.header_offset = (num_header_offset ? num_header_offset : 0);
	col_config.footer_offset = (num_footer_offset ? num_footer_offset : 0);
	col_config.odd_color = (str_odd_color ? str_odd_color : '#ffffff');
	col_config.even_color = (str_even_color ? str_even_color : '#dbeaf5');
	col_config.mover_color = (str_mover_color ? str_mover_color : '#6699cc');
	col_config.onclick_color = (str_onclick_color ? str_onclick_color : '#4C7DAB');
	
	// init multiple tables with same ID
	if (obj_tables.length)
		for (var i = 0; i < obj_tables.length; i++)
			tt_init_table(obj_tables[i], col_config);
	// init single table
	else
		tt_init_table(obj_tables, col_config);
	return true;
}

function tt_init_table (obj_table, col_config) {
	var col_lconfig = [],
		col_trs = obj_table.rows;
	if (!col_trs) return;
	for (var i = col_config.header_offset; i < col_trs.length - col_config.footer_offset; i++) {
		col_trs[i].config = col_config;
		col_trs[i].lconfig = col_lconfig;
		col_trs[i].set_color = tt_set_color;
		col_trs[i].onmouseover = tt_mover; 
		col_trs[i].onmouseout = tt_mout;
		col_trs[i].onmousedown = tt_onclick;
		col_trs[i].order = (i - col_config.header_offset) % 2;
		col_trs[i].onmouseout();
	}
}
function tt_set_color(str_color) {
	this.style.backgroundColor = str_color;
}

// event handlers
function tt_mover () {
	if (this.lconfig.clicked != this)
		this.set_color(this.config.mover_color);
}
function tt_mout () {
	if (this.lconfig.clicked != this)
		this.set_color(this.order ? this.config.odd_color : this.config.even_color);
}
function tt_onclick () {
	if (this.lconfig.clicked == this) {
		this.lconfig.clicked = null;
		this.onmouseover();
	}
	else {
		var last_clicked = this.lconfig.clicked;
		this.lconfig.clicked = this;
		if (last_clicked) last_clicked.onmouseout();
		this.set_color(this.config.onclick_color);
	}
}
// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 (American date format)
// Date: 10/14/2002 (mm/dd/yyyy)
// Feedback: feedback@softcomplex.com (specify product title in the subject)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.html
// About us: Our company provides offshore IT consulting services.
//    Contact us at sales@softcomplex.com if you have any programming task you
//    want to be handled by professionals. Our typical hourly rate is $20.

// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;

function calendar2(obj_target) {

	// assing methods
	this.gen_date = cal_gen_date2;
	this.gen_time = cal_gen_time2;
	this.gen_tsmp = cal_gen_tsmp2;
	this.prs_date = cal_prs_date2;
	this.prs_time = cal_prs_time2;
	this.prs_tsmp = cal_prs_tsmp2;
	this.popup    = cal_popup2;

	// validate input parameters
	if (!obj_target)
		return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null)
		return cal_error("Error calling the calendar: parameter specified is not valid tardet control");
	this.target = obj_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	calendars[this.id] = this;
}

function cal_popup2 (str_datetime) {
	this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
	if (!this.dt_current) return;

	var obj_calwindow = window.open(
		'../calendario/calendario.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
		'Calendar', 'width=200,height='+(this.time_comp ? 215 : 190)+
		',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}

// timestamp generating function
function cal_gen_tsmp2 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// date generating function
function cal_gen_date2 (dt_datetime) {
	return (
		(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
		+ (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time2 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
		+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// timestamp parsing function
function cal_prs_tsmp2 (str_datetime) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// date parsing function
function cal_prs_date2 (str_date) {

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return alert ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd-mm-yyyy.");
	if (!arr_date[1]) return alert ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[0]) return alert ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return alert ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return alert ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);
//alert(arr_date[0]);
	if (arr_date[1] < 1 || arr_date[1] > 12) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[1]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[1]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}

// time parsing function
function cal_prs_time2 (str_time, dt_date) {

	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');

	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0])) 
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
	else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
	
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}
