//fun��o da tela Identifica��o de Avaliados X Avaliadores
z = 0
textoVisualizarRelacoes=""
relacoes=[]


function doObj(o){
    if(typeof o=="string")
	o=document.getElementById(o)
    return o
}

function addEvent(o,evtype,fn){
    o = doObj(o)
    if(o.addEventListener){
        o.addEventListener(evtype,fn,true)
    }else{
        o.attachEvent("on"+evtype,fn)
    }
}

function i(descricao,nome,id){
  document.write('<tr class="'+['impar', 'par'][z++%2]+'">')
  document.write('<td title="'+descricao+'">'+nome)
  for(var i=0;i<relacoes.length;i++)
    geraRadio(relacoes[i],id)
  document.write('<td><a href="#relacionamento"><img id="visualizarel" src="../imagens/olho.gif" width="30" heigth="18" title="'+ textoVisualizarRelacoes
+'"/></a></td></tr>')
}
function geraRadio(r,i){
  document.write('<td class="tradio"><input title="'+r[0]+'" type="radio" name="rel_'+
                  i+'" value="'+i+'/'+r[1]+'" id="rel_'+i+'/'+r[1]+'" onclick="cria_sessao(this)"></td>')
}


function abrir( sId, sId2 ) {
	var sDiv = document.getElementById( sId );
	var sDiv2 = document.getElementById( sId2 );

	sDiv.style.visibility = "visible";
	sDiv2.style.visibility = "hidden";

}

function habilitar( sId, sId2 ) {
	document.getElementById( sId ).disabled = false
	document.getElementById( sId2 ).disabled = true
}

function formataDinheiro(idcampo,tammax,teclapres) {
		//idcampo = ID do campo que receber� a formata��o
		//tammax = Qtd de numeros permitidos (Usar mesmo valor do maxlength do input)
		//teclapress = � o event

		//Ex de uso:
		//<input id="qualquer um" name="nome" maxlength="11" onKeyPress="formataDinheiro(this.id, 11, event)"  type="text" />

		if(window.event) { // Internet Explorer
			var tecla = teclapres.keyCode; }
		else if(teclapres.which) { // Nestcape / firefox
			var tecla = teclapres.which;
		}

		vr = document.getElementById(idcampo).value;
		vr = vr.toString().replace( "/", "" );
		vr = vr.toString().replace( "/", "" );
		vr = vr.toString().replace( ",", "" );
		vr = vr.toString().replace( ".", "" );
		vr = vr.toString().replace( ".", "" );
		vr = vr.toString().replace( ".", "" );
		vr = vr.toString().replace( ".", "" );
		tam = vr.length;

		if (tam < tammax && tecla != 8){
				tam = vr.length + 1;
		}

		if (tecla == 8 ){
			tam = tam - 1;
		}

		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if (tam <= 2 ){
				document.getElementById(idcampo).value = vr;
			}

			if ( (tam > 2) && (tam <= 5) ){
				document.getElementById(idcampo).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
			}

			if ( (tam >= 6) && (tam <= 8) ){
				document.getElementById(idcampo).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			}

			if ( (tam >= 9) && (tam <= 11) ){
				document.getElementById(idcampo).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			}

			if ( (tam >= 12) && (tam <= 14) ){
				document.getElementById(idcampo).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			}

			if ( (tam >= 15) && (tam <= 17) ){
				document.getElementById(idcampo).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			}
		}
}


function help(event,t, act){
    /* argumentos:
        event = evento (onmouseover ou onmouseout)
        t = texto que deve aparecer
        act = define se esconde ou aparece a mensagem*/
	var divName = 'dimage_help';       // nome da div padrao

	var offX = 20;          // Posi��o X do mouse
	var offY = -10;          // Posi��o Y do mouse

    // define o tamanho que ter� a div para n�o ultrapassar o espa�o trabalhado
	var tam_tela = screen.width;
	var sobra = ((tam_tela - 770)/2) - 70;

	if(t.length < 100){var w = tam_tela - event.clientX - sobra + 100;
	}else{var w = tam_tela - event.clientX - sobra - 30;};

	function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
	function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

	function follow(evt) {
		if (document.getElementById) {
			var obj = document.getElementById(divName).style;
			if (act == '1') {
			     // define estilos da div
				obj.display = 'block';
				obj.left = (parseInt(mouseX(evt))+offX) + 'px';
				obj.top = (parseInt(mouseY(evt))+offY) + 'px';
                obj.width = w + 'px';

                // cria tags internas a div para o IE
            	if(navigator.appName=="Microsoft Internet Explorer"){
            		novoSpan = document.createElement("<span class='msg_help' id='span_help'>")
            		novoTitulo = document.createElement("<h2 class='help' id='h2_help'>")

            	}
            	// cria tags internas da div para o resto dos browsers
				else{
                	novoTitulo = $new("h2")
                	novoTitulo.setAttribute("class", "help")
                	novoTitulo.setAttribute("id", "h2_help")

                    novoSpan = $new("span");
                	novoSpan.setAttribute("class", "msg_help");
                	novoSpan.setAttribute('id', 'span_help')
                    }

                novoSpan.innerHTML=t;
                novoTitulo.innerHTML="HELP !!";

                var pai = $(divName);
                //	remove os elementos caso eles existam
                $remove([$('h2_help'), $('span_help')])
                // cria os elementos internos a div
                $child(pai, novoTitulo);
                $child(pai, novoSpan);


			}
			else {
				obj.display = 'none';
			}
		}
	}
	document.onmousemove = follow;
}


function enter(event){
	if(navigator.appName=="Microsoft Internet Explorer"){
		tag = window.event.srcElement.tagName}
	else{
		tag = event.target.tagName}
	if (event.keyCode == 13 && tag != 'TEXTAREA' )
	{
		return false
	}
}


//Verifica e remove espa�os vazios a esquerda e a direita
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function desabilita_campos(val,ids){
    if (ids.length && typeof ids != "string"){
        for(var i=0; i<ids.length; i++){
	       elemento = $(ids[i]);
	       if (val == "1"){
				if ($('ind') || $('pfunc')){
					if ($('ind').checked == true)
						{elemento.disabled = false}
					if ($('pfunc').checked)
						{if (ids[i] == "avaliacaoIni" || ids[i] == 'avaliacaoFinal' || ids[i] == 'clienteIni' || ids[i] == 'clienteFinal')
							{elemento.disabled = true}
						else
							{elemento.disabled = false}}}
				else
				{elemento.disabled = false}
			}
		   if(val == "2"){
		   elemento.disabled = true;}
		   if (val == "3"){
				if (ids[i] == "filial"){
					elemento.disabled = false;}
				else{
					elemento.disabled = true;}
					}
	}}}

function focusFirstField(){
var Campo;if(document.forms.length > 0){for (var i=0; i < document.forms[0].elements.length; ++i){Campo = document.forms[0].elements[i];
if((Campo.type!="hidden")&&(Campo.type!="submit")&&Campo.tagName!="FIELDSET"){
if (Campo.disabled!=true){Campo.focus();break;};};};};
};

//As funções abaixo validam o cpf matematicamente pelo seu dígito verificador
function valida(numero){
	s = limpa_string(numero);
	param = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,2);
	if (s.length == 11) {
		if (valida_CPF(param) == false ) {
			return false;
		}
	} else {
		return false;
	}
}

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
		}
	}

	return temp
}
// fim da funcao

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;
}

/*função que valida o maxlength do textarea. Essa função é chamada quando o textarea tem o maxlength declarado*/
jQuery('textarea[maxlength]').keyup(function(){
    var limit = parseInt(jQuery(this).attr('maxlength')); //obtem o limite do atributo maxlength
    if (limit != -1){
      var text = jQuery(this).val(); // obtem o texto atual do textare
      var chars = text.length; //conta o numero de caracteres no texto

      //verificar se existem mais caracteres permitido então
      if(chars > limit){
          //e se há utilização do substr para obter o texto antes do limite
          var new_text = text.substr(0, limit);

          //e alterar o texto atual com o novo texto
          jQuery(this).val(new_text);
      }
    }
});


/*
	a função checkAll faz a manipulação de Selecionar um conjunto de checkbox, se os checkbox estiverem false vai para true e vice-versa.
	Essa função pode ser chamada no onclick do checkbox manipulador ou no onclick de um botão
	Os parametros:
		* checkedStatus --> recebe um valor booleano; por exemplo se o checkbox manipulador estiver selecionado os outros checkbox também serão selecionados ou vice-versa; se for vazio é porque o elemento que está fazendo a seleção não é um checkbox
		* objCheckeds --> recebe a direção de onde está os checkbox's a serem selecionados; por exemplo na customtags flexgrid do lasagna a tabela tem a funcionalidade de selecionar todos os checkbox's, o parametro objCheckeds receberá a direção da coluna da tabela e seus respectivos checkbox's. O exemplo do que foi passado para esse parametro na flexgrid:
					''' onclick="checkAll(this.checked,'#checkbox_all :input[@type=checkbox]')"'''
*/
function checkAll(checkedStatus,objCheckeds) {
	if(checkedStatus==""){var selecionar = jQuery(objCheckeds).is(':checked'); var checkbox=false;
	}else{ var selecionar = checkedStatus; var checkbox=true;}

	jQuery(objCheckeds).each(function(){
		if(checkbox){this.checked = selecionar;}
		else{
			if(selecionar){this.checked = false;}
			else{ this.checked = true;};};
	});
}

/*
	a função confirmAndDel faz a verificação se pode deletar o registro, se tiver registro para deletar roda o arquivo flexgrid.pt da pasta ajax para deletar o registro.
	Se o retorno do ajax for false e aparecer a mensagem "Registro não pode ser deletado." é porque a tabela a ser deletada tem foreignKeys com o registro relacionado, para fazer esse processo é necessário inserir a propriedade cascade=True na ForeignKey da tabela filha na model.py.
*/
function confirmAndDel(table, element) {
	var selecionar = false;
	var ids = '';

	jQuery(element).each(function(){
		if(this.checked){
			selecionar=true;
			if(ids)ids+=',';
			ids+=this.id;
		}
	});

	if (!selecionar){
		try{
			jQuery.modal.close();
			carregaEventos();}
		catch(err){}
		alert('Por favor, selecione o(s) registro(s) que desejas excluir.');
     }else{
		if (confirm('Tem certeza que deseja excluir o(s) registro(s) selecionado(s)?') == true) {

			jQuery.ajax({
				type: 'POST',
				url: '../control/ajax/flexgrid.pt',
				data: {tipo:'1', ids:ids, table:table},
				dataType: "json",
				success: function (result){
					if(result){window.location.href=window.location.href;
					}else{
						try{
							jQuery.modal.close();
							carregaEventos();}
						catch(err){}
						alert('Há Tabelas Relacionadas, Registro Não Pode Ser Excluido!')}}
			});

		}else{
			try{
				jQuery.modal.close();
				carregaEventos();}
			catch(err){}
		};
	};
};




