String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,'');
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,'');
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,'');
}
   
$(document).ready(function(){
	if (!$("input[@type='radio'][@name='tipoPesquisa'][@value='numprocesso']").attr("checked")) {
		$("#divNomeexato").show();
		$("input[@name=parametro]").unmask();
	} else {
		$("#divNomeexato").hide();
		$("input[@name=parametro]").unmask();
		$("input[@name=parametro]").mask("999999999999",{placeholder:" "});
	}
	
	function showNomeexato() {
		$("#divNomeexato").show();
	}
	
	function hideNomeexato() {
		$("#divNomeexato").hide();
	}

	$("input[@type='radio'][@name='tipoPesquisa']").each(function(){
		switch ($(this).attr("value")) {
			case "numprocesso":
				$(this).click(function(){
					hideNomeexato();
					$("input[@name=parametro]").unmask();
					$("input[@name=parametro]").mask("999999999999",{placeholder:" "});
					$("input[@name=parametro]").focus();
				}); 
				break;
			case "parte":
			case "advogado":
				$(this).click(function(){
					showNomeexato();
					$("input[@name=parametro]").unmask();
					$("input[@name=parametro]").focus();
				});
				break;
		}
	});
	function tirarAcentos(texto) {
		var acento = "áÁéÉíÍóÓúÚàÀèÈìÌòÒùÙâÂêÊîÎôÔûÛäÄëËïÏöÖüÜãÃõÕçÇñÑ";
 		var normal = "aAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAoOcCnN";

		var retorno = texto;
		for(i=0;i<acento.length;i++)
			retorno = retorno.replace(acento.substr(i,1),normal.substr(i,1));
		return retorno;
	}
	function validaNome(campo) {
        if (campo.attr("value")==null) {
            alert("Por Favor, digite um nome antes de realizar a consulta!");
            campo.focus();
            return false;
   	    }
		
		campo.attr("value",tirarAcentos(campo.attr("value")));

        if (campo.attr("value").length == 0) {
            alert("Por Favor, digite o nome antes de realizar a consulta!");
            campo.focus();
            return false;
   	    }
			
		if (campo.attr("value").indexOf(" ") == -1) {
            alert("Esta consulta requer um nome e no mínimo um sobrenome!");
   	        campo.focus();
       	    return false;
       	}
			
        if (campo.attr("value").substring(0,1) == " ") {
			alert("O nome não deve começar com espaços em branco!");
           	campo.focus();
           	return false;
       	}
			
       	if (campo.attr("value").indexOf("  ") != -1) {
            alert("Nome inválido! O nome não deve conter dois ou mais espaços em branco entre cada palavra!");
   	        campo.focus();
       	    return false;
       	}

       	if (campo.attr("value").substring(campo.attr("value").length-1) == " ") {
            alert("Nome inválido! O nome não deve terminar com espaços em branco!");
            campo.focus();
           	return false;
       	}

       	return true;
	}
	function soPalavras(evt) {
      if (document.all) { // IE
	  	var key = event.keyCode;
	  } else { // Firefox
	  	var key = evt.charCode;
	  }	
      if ((key<20) || ((key >64) && (key<91) && (key>96) && (key<123))) {
	  	return true;
	  }
      alert("Não são aceitos caracteres especiais. Digite apenas letras.");
	  return false;
	}	
	
	$("#form1grau").submit(function(){
          var inputs = [];
          var parametro = $("input[@name=parametro]");
          var isNumprocesso = $("input[@type='radio'][@name='tipoPesquisa'][@value='numprocesso']").attr("checked");          
          if (isNumprocesso==null)
          	isNumprocesso=false;          
          if (isNumprocesso) {
          	texto = parametro.attr("value");
          	if ((texto==null) || (texto.trim()=="")) {
	          	alert('Informe o número do processo');
    	      	parametro.focus();
        	  	return false;
          	} else if (texto.trim().length<12) {
	          	alert('Informe um número de processo válido (12 dígitos)');
    	      	parametro.focus();
        	  	return false;
          	}
          }          
          if (!isNumprocesso) {
          	if (!validaNome(parametro))
          		return false;
          }          
          $(":input", $(this)).each(function() {
	          if ($(this).attr("value") != null) {
	          	  if (($(this).attr("name")=="tipoPesquisa")) {
	          	  	if ($(this).attr("checked")) {
			          inputs.push($(this).attr("name") + '=' + escape($(this).attr("value")));
			        }
			  	  } else if (($(this).attr("name")=="nomeexato")) {
	          	  	if ($(this).attr("checked")) {
			          inputs.push($(this).attr("name") + '=1');
			        } else {
			          inputs.push($(this).attr("name") + '=0');
			        }
			      } else {
			          inputs.push($(this).attr("name") + '=' + escape($(this).attr("value")));
			      }
		      }
          });
          $.ajax({
			type: "POST",
			url: $(this).attr("action"),
			dataType: "html",
			data: inputs.join('&'),
			success: function(msg){
						$("#loading").hide();
						$("#resultado").html(msg);
						if ($("#tabela")!=null) {
							$("#tabela").tablesorter({sortList: [[0,0]], widthFixed: false, widgets: ['zebra']});
							$("#tabela").tablesorterPager({container: $(".pager"), positionFixed: false});
						}						
						$(".pagesize").change(function(){
							$(".pagesize").attr("value", $(this).attr("value"));
						});
						$("#resultado").show();
						setAjaxLinks();
					 },
			beforeSend: function(){
							$("#resultado").hide();
							$("#loading").show();
						}			
		  });
		return false;
	});
	function setAjaxLinks() {
		$("#menuLinks > a").each(function(i){
			$(this).click(chamaPagina);	
		});
		$("a.linkProcesso").each(function(i){
			$(this).click(chamaPagina);	
		});
	}
	function chamaPagina(){
          $.ajax({
			type: "GET",
			url: $(this).attr("href"),
			dataType: "html",
			success: function(msg){
						$("#loading").hide();
						$("#resultado").html(msg);
						if ($("#tabela")!=null) {
							$("#tabela").tablesorter({sortList: [[0,0]], widthFixed: false, widgets: ['zebra']});
							$("#tabela").tablesorterPager({container: $(".pager"), positionFixed: false});
						}				
						$(".pagesize").change(function(){
							$(".pagesize").attr("value", $(this).attr("value"));
						});
						$("#resultado").show();
						setAjaxLinks();
					 },
			beforeSend: function(){
							$("#loading").show();
						}			
		});
		return false;
	}; 	
	$("input[@name=parametro]").focus();
});