$(document).ready(function (){
	$("#dt1Diario").datepicker({
		  showOn: 'button',
		  buttonImage: 'imagens/calendar.jpg',
		  buttonImageOnly: true,
		  buttonText: '',
		  showAnim: "fadeIn",
		  gotoCurrent: true,
		  changeYear: true,
		  changeMonth: true,
		  regional : "pt-BR",
		  yearRange : "1950:" + (new Date()).getFullYear(),
		  onSelect: function(dateText, inst){
		    var dataDT = dateText.split("/");
		    $("#dia1").val(dataDT[0]);
		    $("#mes1").val(dataDT[1]);
		    $("#ano1").val(dataDT[2]);
		  }
		});
	$("#dt2Diario").datepicker({
	      showOn: 'button',
		  buttonImage: 'imagens/calendar.jpg',
		  buttonImageOnly: true,
		  buttonText: '',
		  showAnim: "fadeIn",
		  gotoCurrent: true,
		  changeYear: true,
		  changeMonth: true,
		  regional : "pt-BR",
		  yearRange : "1950:" + (new Date()).getFullYear(),
		  onSelect: function(dateText, inst){
		    var dataDT = dateText.split("/");
		    $("#dia2").val(dataDT[0]);
		    $("#mes2").val(dataDT[1]);
		    $("#ano2").val(dataDT[2]);
		  }
		});
	getFields();
	$("#formularioBusca").submit(function(){
		limpaFields();
		partialFields();
		intextNumProcesso();
		return validateDate();
	});
	
	if (($("input.tipoNum:checked").val() == "themis") && ($("select#tipoGrau option:selected").val() == "1")) {
		$("#numProcesso").mask("999/9.99.9999999-9");
	}	
	else if (($("input.tipoNum:checked").val() == "themis") && ($("select#tipoGrau option:selected").val() == "2")) {	
		$("#numProcesso").mask("99999999999");
	}
	else if ($("input.tipoNum:checked").val() == "CNJ") { 
		$("#numProcesso").unmask();
		$("span#grau").addClass("escondido");
	}
	
	$("input.tipoNum").live("change", function() {
		$("#numProcesso").val("");
		if ($(this).val() == "themis") {
			if ($("select#tipoGrau option:selected").val() == "1") {
				$("#numProcesso").mask("999/9.99.9999999-9");
			}
			else {	
				$("#numProcesso").mask("99999999999");
			}
			$("span#grau").removeClass("escondido");
		}
		else {
			$("#numProcesso").unmask();
			$("span#grau").addClass("escondido");
		}
	});
	
	$("select#tipoGrau").live("change", function() {
		$("#numProcesso").val("");
		if ($("input.tipoNum:checked").val() == "themis") {
			$("span#grau").removeClass("escondido");
			if ($("option:selected", $(this)).val() == "1")
				$("#numProcesso").mask("999/9.99.9999999-9");
			else	
				$("#numProcesso").mask("99999999999");
		}
		else {
			$("#numProcesso").unmask();
			$("span#grau").addClass("escondido");
		}
	});
	
	$("#numProcesso").keyup(function() {
		if ($("input.tipoNum:checked").val() == "CNJ") {
			var v = $(this).val();
			if (v.length < 26) {
				v=v.replace(/\D/g,"");  //permite digitar apenas nÃºmeros
				v=v.replace(/(\d{1})(\d{13})$/,"$1-$2");  //coloca hÃ­fen antes dos Ãºltimos 14 digitos
				v=v.replace(/(\d{1})(\d{11})$/,"$1.$2");  //coloca ponto antes dos Ãºltimos 11 digitos
				v=v.replace(/(\d{1})(\d{7})$/,"$1.$2");  //coloca ponto antes dos Ãºltimos 7 digitos
				v=v.replace(/(\d{1})(\d{6})$/,"$1.$2");  //coloca ponto antes dos Ãºltimos 6 digitos
				v=v.replace(/(\d{1})(\d{4})$/,"$1.$2");	//coloca ponto antes dos Ãºltimos 2 digitos
				$(this).val(v);
			}
			else {
				v=v.replace(/\d{1}$/,"") 
				$(this).val(v);
			}
		}	
	});

});
	
	
/*
 * exemplo new Array("nome da meta tag", "id do input") new Array("DT_nome da
 * meta tag") Você pode colocar ids de campos input (type=text) e select
 * Importante! Deixe o daterange por último, ele contém apenas o nome da meta
 * tag e não altere o id dos campos de data!
 */

var mt = new Array(
				   new Array("NumeroEdicao", "numEdicao"),
				   new Array("CodigoTipoCaderno", "codTipoCaderno"),
				   new Array("DataPublicacao") /* daterange */
);

function trim(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function getFullMonth(month)
{
	switch(month.toString())
	{
		case "1":
			return "01";
		case "2":
			return "02";
		case "3":
			return "03";
		case "4":
			return "04";
		case "5":
			return "05";
		case "6":
			return "06";
		case "7":
			return "07";
		case "8":
			return "08";
		case "9":
			return "09";
		default:
			return month;
			
	}
}
function getFullDay(day)
{
	switch(day.toString())
	{
		case "1":
			return "01";
		case "2":
			return "02";
		case "3":
			return "03";
		case "4":
			return "04";
		case "5":
			return "05";
		case "6":
			return "06";
		case "7":
			return "07";
		case "8":
			return "08";
		case "9":
			return "09";
		default:
			return day;
	}
}
function todayDate()
{
	var today = new Date();
	document.TJRSSearch.dia2.value = getFullDay(today.getDate());
	document.TJRSSearch.mes2.value = getFullMonth(today.getMonth() + 1);
	document.TJRSSearch.ano2.value = today.getFullYear();
}


function getTodayDate()
{
	var today = new Date();
	return today.getFullYear() + "" + getFullMonth(today.getMonth() + 1) + "" + getFullDay(today.getDate());
}

function validateDate() {

	erro = 0;
	var z = document.formularioBusca;
	dia1 = getFullDay(document.getElementById("dia1").value);
	mes1 = getFullMonth(document.getElementById("mes1").value);
	ano1 = document.getElementById("ano1").value;
	dia2 = getFullDay(document.getElementById("dia2").value);
	mes2 = getFullMonth(document.getElementById("mes2").value);
	ano2 = document.getElementById("ano2").value;
	var isValidDate;

	//data = ano1 + '-' + mes1 + '-' + dia1;
	data = dia1 + "-" + mes1 + "-" + ano1; 
	datahj = new Date();
	dataHJcomp = datahj.getFullYear() + ""
			+ getFullMonth(datahj.getMonth() + 1) + ""
			+ getFullDay(datahj.getDate());
	data1Comp = ano1 + "" + getFullMonth(mes1) + "" + getFullDay(dia1);
	data2Comp = ano2 + "" + getFullMonth(mes2) + "" + getFullDay(dia2);
	
	if ((dia1 != '') && (mes1 != '') && (ano1 != '')) {
		if (!data
				.match(/^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/)) {
			alert('Data ' + dia1 + '/' + mes1 + '/' + ano1 + ' Inválida!');
			return false;
		} else if (ano1 > datahj.getFullYear()) {
			alert('Data ' + dia1 + '/' + mes1 + '/' + ano1 + ' Inválida!');
			return false;
		} else if ((dataHJcomp - data1Comp) < 0) {
			alert('Data ' + dia1 + '/' + mes1 + '/' + ano1 + ' Inválida!');
			return false;
		} else {
		}
	}
	//data = ano2 + '-' + mes2 + '-' + dia2;
	data = dia2 + "-" + mes2 + "-" + ano2;
	if ((dia2 != '') && (mes2 != '') && (ano2 != '')) {
		if (!data
				.match(/^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/)) {
			alert('Data ' + dia2 + '/' + mes2 + '/' + ano2 + ' Inválida!');
			return false;
		} else if (ano2 > datahj.getFullYear()) {
			alert('Data ' + dia2 + '/' + mes2 + '/' + ano2 + ' Inválida!');
			return false;
		} else if ((dataHJcomp - data2Comp) < 0) {
			alert('Data ' + dia2 + '/' + mes2 + '/' + ano2 + ' Inválida!');
			return false;
		} else {
		}
	}
	if ((dia1 != '') && (mes1 != '') && (ano1 != '')) {
		if ((dia2 != '') && (mes2 != '') && (ano2 != '')) {
			if ((data2Comp - data1Comp) < 0) {
				alert('Data de início do período maior que data de final');
				return false;
			} else
			{
				if (z.as_q.value.length > 0)
					z.as_q.value += " ";
				z.as_q.value += 'inmeta:' + mt[mt.length - 1]
						+ ':daterange:' + ano1 + '-' + getFullMonth(mes1) + '-'
						+ getFullDay(dia1) + '..' + ano2 + '-'
						+ getFullMonth(mes2) + '-' + getFullDay(dia2);
			}
		} else {
			if (z.as_q.value.length > 0)
				z.as_q.value += " ";
			z.as_q.value += 'inmeta:' + mt[mt.length - 1]
					+ ':daterange:' + ano1 + '-' + getFullMonth(mes1) + '-'
					+ getFullDay(dia1) + '..' + datahj.getFullYear() + '-'
					+ getFullMonth(datahj.getMonth() + 1) + '-'
					+ getFullDay(datahj.getDate());
		}
	} else if ((dia2 != '') && (mes2 != '') && (ano2 != '')
			&& (data2Comp != dataHJcomp)) {
		if (z.as_q.value.length > 0)
			z.as_q.value += " ";
		z.as_q.value += 'inmeta:' + mt[mt.length - 1] + ':daterange:'
				+ '..' + ano2 + '-' + getFullMonth(mes2) + '-'
				+ getFullDay(dia2);
	}
	
}

function intextNumProcesso()
{
	if ($("#numProcesso").val() != "") {
		valor = $("#numProcesso").val();
		q = $("input[name='q']").val();
		var expressao = /^(\d{3}\/\d{1}\.\d{2}\.\d{7}-\d{1})$|^(\d{11})$|^(\d{0,7}-?\d{0,2}\.?\d{0,4}\.?\d{0,1}\.?\d{0,2}\.?\d{0,4})$/;
		if (valor.match(expressao)) {
			if (q.length > 0) 
				$("input[name='q']").val(q + " " + "intext:" + valor);
			else
				$("input[name='q']").val("intext:" + valor);
		}
	}
}


function utf8Decode(utftext) 
{
	var string = "";
	if (utftext != null)
	{
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) 
		{
			c = utftext.charCodeAt(i);
			if (c < 128) 
			{
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c > 224)) 
			{
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else 
			{
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
	}
	while(string.indexOf("+") != -1)
		string = string.replace("\+", " ");
	return string;
}

function utf8Encode(string) 
{
	var utftext = "";
	if (string != null)
	{
		string = string.replace(/\r\n/g,"\n");
		for (var n = 0; n < string.length; n++) 
		{
			var c = string.charCodeAt(n);
			var ch = string.charAt(n);
			if (c < 128) 
			{
				utftext += String.fromCharCode(c);
				
			} else if((c > 127) && (c < 2048)) 
			{
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else 
			{
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
	}
	return utftext;
}

function URLEncode(string) 
{
	var returnString = escape(this.utf8Encode(string));
	returnString = returnString.replace(/\./g, "%2E");
	returnString = returnString.replace(/\|/g, "%7C");
	return returnString.replace(/:/g, "%3A");
}

function URLDecode(string) 
{
	return this.utf8Decode(unescape(string));
}

function partialFields()
{
	$("#as_q").val("");
	var mtValue;
	var partFields = document.getElementById("partialfields");
	
	for (x = 0; x < mt.length - 1; x++)
	{
		if (document.getElementById(mt[x][1]).tagName.toLowerCase() == "input")
			mtValue = trim(document.getElementById(mt[x][1]).value);
		else if (document.getElementById(mt[x][1]).tagName.toLowerCase() == "select")
		{
			mtValue = trim(document.getElementById(mt[x][1]).options[document.getElementById(mt[x][1]).selectedIndex].value);
		}
		if (mtValue != '')
		{
			while (mtValue.indexOf(".") != -1)
				mtValue = mtValue.replace("\.", "");
			if(partFields.value != '')
			{
				partFields.value += "." + mt[x][0] + ":" + escape(utf8Encode(mtValue));
			}
			else
			{
				partFields.value += mt[x][0] + ":" + escape(utf8Encode(mtValue));
			}
		}
	}
}

function checkForInt(e) {
   var charCode = ( e.which != null ) ? e.which : event.keyCode;
   return (charCode < 32 || (charCode >= 48 && charCode <= 57));
}

function checkForString(e) {
	var k;
	document.all ? k = e.keyCode : k = e.which;
	return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}

function selecionaOp(elId, op)
{
	var el = document.getElementById(elId);
	for (var i = 0; i < el.options.length; i++)
		if (el.options[i].value.toLowerCase() == op.toLowerCase())
		{
			el.selectedIndex = i;
			break;
		}
}

function getFields()
{
	var urlBusca = window.location.href;
	var pFields = unescape(urlBusca.substring(urlBusca.lastIndexOf("partialfields=") + 14));
	if (pFields.indexOf("&") != -1)
		pFields = pFields.substring(0, pFields.indexOf("&"));
	var camposPartial = pFields.split(".");
	urlBusca = unescape(urlBusca);
	
	/* pega os dados do partialfields */
	if (camposPartial.length > 0 && pFields != ''){
		for (y = 0; y < camposPartial.length; y++)
		{
			for (x = 0; x < mt.length - 1; x++)
			{
				if (camposPartial[y].search(mt[x][0]) != -1){
					if (document.getElementById(mt[x][1]).tagName.toLowerCase() == "input")
					{
						document.getElementById(mt[x][1]).value = utf8Decode(unescape(camposPartial[y].substring(camposPartial[y].indexOf(':') + 1)).toLowerCase()).toLowerCase();
					}
					else if (document.getElementById(mt[x][1]).tagName.toLowerCase() == "select")
					{
						selecionaOp(mt[x][1], utf8Decode(unescape(camposPartial[y].substring(camposPartial[y].indexOf(':') + 1)).toLowerCase()).toLowerCase());
					}
					break;
				}
			}
		}
	}
	
	/* pega as datas do inmeta */
	var data1 = null;
	var data2 = null;
	if(urlBusca.search("inmeta:" + mt[mt.length - 1][0]) != -1)
	{
		inmeta = urlBusca.substring(urlBusca.indexOf("inmeta:" + mt[mt.length - 1][0] + ":daterange:") + 18 + mt[mt.length - 1][0].length);
		if (inmeta.indexOf("&") != -1)
			inmeta = inmeta.substring(0, inmeta.indexOf("&"));
		inmeta = inmeta.split("..");
		if(inmeta.length == 2)
		{
			data1 = inmeta[0];
			data2 = inmeta[1];
		}
		else
			data2 = inmeta[0];
		if (data1 != "" && data1 != null)
		{
			$("#dt1Diario").datepicker("setDate", $.datepicker.parseDate("yy-mm-dd", data1));

			data1 = data1.split("-");
			document.getElementById("ano1").value = data1[0];
			document.getElementById("mes1").value = data1[1];
			document.getElementById("dia1").value = data1[2];
					}
		if (data2 != "" && data2 != null)
		{
			$("#dt2Diario").datepicker("setDate", $.datepicker.parseDate("yy-mm-dd", data2));
			data2 = data2.split("-");
			document.getElementById("ano2").value = data2[0];
			document.getElementById("mes2").value = data2[1];
			document.getElementById("dia2").value = data2[2];
			
		}
	}
	
	/* pega os dados do nº processo */
	
	if(urlBusca.search("intext:") != -1)
	{
		var numProcesso = urlBusca.substring(urlBusca.indexOf("intext:") + 7);
		if (numProcesso.indexOf("&") != -1)
			numProcesso = numProcesso.substring(0, numProcesso.indexOf("&"));
		
		$("#numProcesso").val(numProcesso);
	}
	
	if(urlBusca.search("tipoNum=") != -1)
	{
		var tipoNum = urlBusca.substring(urlBusca.indexOf("tipoNum=") + 8);
		if (tipoNum.indexOf("&") != -1)
			tipoNum = tipoNum.substring(0, tipoNum.indexOf("&"));
				
		$("input.tipoNum").each(function(){
			if ($(this).val() == tipoNum)
				$(this).attr("checked", 'checked');
		});
		
		if (tipoNum == "CNJ")
			$("span#grau").addClass("escondido");
	}
		
	if(urlBusca.search("grau=") != -1)
	{
		var grau = urlBusca.substring(urlBusca.indexOf("grau=") + 5);
		if (grau.indexOf("&") != -1)
			grau = grau.substring(0, grau.indexOf("&"));
		
		selecionaOp("tipoGrau", grau);
	}
	
}

function limpaFields()
{
	document.getElementById("partialfields").value = "";
}

function limpaFiltros()
{
	for (x = 0; x < mt.length - 1; x++)
	{
		if (document.getElementById(mt[x][1]).tagName.toLowerCase() == "input")
			document.getElementById(mt[x][1]).value = "";
		else
			document.getElementById(mt[x][1]).selectedIndex = 0;
	}
	document.getElementById("dia1").value = "";
	document.getElementById("mes1").value = "";
	document.getElementById("ano1").value = "";
	document.getElementById("dia2").value = "";
	document.getElementById("mes2").value = "";
	document.getElementById("ano2").value = "";
	$("#dt1Diario").val("a");
	$("#dt2Diario").val("a");
	
	$("#numProcesso").val("").mask("999/9.99.9999999-9");
	$("input.tipoNum").each(function(){
		if ($(this).val() == "themis")
			$(this).attr("checked", 'checked');
	});
	selecionaOp("tipoGrau", "1");
	$("span#grau").removeClass("escondido");
	
}
