// JavaScript

//*************************************************************************************************************************//
// método que formata a entrada para o tipo data (ex: 01/01/2006)
	function dateFormat(origem,e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		// se não for o navegador Opera
		if(navigator.userAgent.toLowerCase().indexOf('opera') == -1){
			//se for TAB ou DEL ou BACKSPACE ou ENTER
			if (key != 9 && key != 46 && key != 8 && key != 13){
				if (origem.value.length == 2) origem.value += '/';
				if (origem.value.length == 5) origem.value += '/';
			
				onlyChars('0123456789',e);
			}
		}
	}

//*************************************************************************************************************************//
// método que restringe apenas um conjunto de caracteres ao digitar no campo data. Parâmetro são os números que serão permitidos
	function onlyChars(cadeia,e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		//se for TAB ou DEL ou BACKSPACE ou ENTER
		if (key == 9 || key == 46 || key == 8 || key == 13) return;

		var chars = cadeia;
		var ev = String.fromCharCode(key);

		if(chars.indexOf(ev) == -1){
			if (e != null){				
				if (window.event) {
					window.event.keyCode = 0;
				} else
					e.which = 0;
			} else
				if (window.event)
					window.event.keyCode = 0;
		}
	}

//***************************************************************************************************************
// método que adiciona numeros ZERO antes de dias/meses que são menores que 10.
// Entrada: 5/6/2005 --> Saída: 05/06/2005
	function addZeroDate(oDate){
		var newDate = "";
		var date = oDate.split("/");
		if (date.length != 3) return "";
		
		for (var i = 0; i < date.length; i++){
			newDate += (parseInt(date[i]) < 10) ? "0" + date[i] : date[i];
			if (i < date.length - 1) newDate += "/";
		}
		
		return newDate;
	}

//***************************************************************************************************************
// método retorna a diferença em dias entre duas datas. Funciona para um período máximo de 1 ano
	//dIni = 10/12/2005
	//dFim = 15/12/2005
	//type = (true) retorno de dias para próxima data / (false) retorno negativo para datas que já se passaram
	function dateDiff(dIni,dFim,type){
		dIni = dIni.split("/");
		dFim = dFim.split("/");
		//Set the two dates
		var today = new Date(dFim[2],dFim[1] - 1,dFim[0]);
		var christmas = new Date(dIni[2], dIni[1] - 1, dIni[0]); //Month is 0-11 in JavaScript
		
	 	//se já passou da data
		if (type)
			if (today.getMonth() == dFim[1] - 1 && today.getDate() > dFim[0])
				christmas.setFullYear(christmas.getFullYear()+1); //calculate next year's Christmas

		//Set 1 day in milliseconds
		var one_day = 1000*60*60*24;

		//Calculate difference btw the two dates, and convert to days
		var res = Math.ceil((christmas.getTime()-today.getTime())/(one_day));
//		alert("Today: " + today + "\nChristmas: " + christmas + "\n\n Data Prevista: " + dIni + "\nData Entrega: " + dFim + "\nResultado: " + res);
		return res;
	}

//***************************************************************************************************************
// muda a qtde de dias do campo dia ao alterar o mes para a pesquisa
//restrição: a TD q possui o list/menu precisa der o ID "tdDia"
//			 o nome do list/menu que tem os dias sempre será "selDia"
	function changeDay(cMonth){
		var newValue = '<select name="selDia" class="form" id="selDia" style="width: 90px">';
		for (var i = 1; i <= getDaysOfMonth(cMonth-1,currentYear()); i++){
			if (i == currentDay())		
				newValue += '<option value="' + i + '" selected>' + i + '</option>';
			else
				newValue += '<option value="' + i + '">' + i + '</option>';
		}
		newValue += '</select>';

		document.getElementById("tdDia").innerHTML = newValue;
	}


//***************************************************************************************************************
// imprime os options dentro dos combos/selects/pulldown's, ou seja lá o que for
	function returnDates(origem){
		switch (origem){
			case "day":
				for (var i = 1; i <= getDaysOfMonth(currentMonth(),currentYear()); i++){
					if (i == currentDay())
						document.write("<option value='"+i+"' selected>"+i+"</option>");
					else
						document.write("<option value='"+i+"'>"+i+"</option>");
				}
			break;
			case "month":
				var newMonth = null;
				for (var i = 1; i <= 12; i++){
					newMonth = getMonthName(i-1);
					if (i-1 == currentMonth())
						document.write("<option value='"+i+"' selected>"+newMonth+"</option>");
					else
						document.write("<option value='"+i+"'>"+newMonth+"</option>");
				}
			break;
			case "year":
				for(var i = 2004; i <= currentYear(); i++){
					if (i == currentYear())
						document.write("<option value='"+i+"' selected>"+i+"</option>");
					else
						document.write("<option value='"+i+"'>"+i+"</option>");
				}
			break;
		}
	}

//***************************************************************************************************************
// retorna a data atual no formato: dd/mm/aaaa
	function setCurrentDate(objeto){
		var hj = new Date();
		var novaData = (hj.getDate() < 10) ? ("0" + hj.getDate() + "/") : (hj.getDate() + "/");
		novaData += (hj.getMonth() + 1 < 10) ? ("0" + (hj.getMonth() + 1) + "/") : ((hj.getMonth() + 1) + "/");
		novaData += (navigator.appVersion.indexOf("MSIE") != -1) ? hj.getYear() : hj.getYear() + 1900;
		objeto.value = novaData;
	}

//***************************************************************************************************************
// - Método padrão que gera uma máscara automático em um campo tipo data
	function dateMask(local,string){
		if(local.value.length == 2 ) local.value += "/";
		if(local.value.length == 5 ) local.value += "/";
	}

//***************************************************************************************************************
// - Método que converte um campo tipo data dd/mm/yyyy para yyyy-mm-dd o qual for a separação 
	function convDataDB(data,tipo){
		if (!data || !tipo) return false;

		var novaData = data.split("/");
		return novaData[2]+tipo+novaData[1]+tipo+novaData[0];
	}

//***************************************************************************************************************
	function currentDay(){
		var newDate = new Date();
		return newDate.getDate();
	}

//***************************************************************************************************************
	function currentMonth(){
		var newDate = new Date();
		return newDate.getMonth();
	}

//***************************************************************************************************************
	function currentYear(){
		var newDate = new Date();
		return (navigator.appVersion.indexOf("MSIE") != -1) ? newDate.getYear() : newDate.getYear() + 1900;
	}

//***************************************************************************************************************
	function getDaysOfMonth(month,year) {
		 return 32 - new Date(year, month, 32).getDate();
	}

//***************************************************************************************************************
	function getMonthName(month){
		switch(month){
			case 0: return "Janeiro"; break;
			case 1: return "Fevereiro"; break;
			case 2: return "Março"; break;
			case 3: return "Abril"; break;
			case 4: return "Maio"; break;
			case 5: return "Junho"; break;
			case 6: return "Julho"; break;
			case 7: return "Agosto"; break;
			case 8: return "Setembro"; break;
			case 9: return "Outubro"; break;
			case 10: return "Novembro"; break;
			case 11: return "Dezembro"; break;
		}
	}

//***************************************************************************************************************

//***************************************************************************************************************
//***************************************************************************************************************
	function getClockTime(){
		var now    = new Date();
		var hour   = now.getHours();
		var minute = now.getMinutes();
		var second = now.getSeconds();
		var ap = "AM";
		if (hour   > 11) { ap = "PM";             }
		if (hour   > 12) { hour = hour - 12;      }
		if (hour   == 0) { hour = 12;             }
		if (hour   < 10) { hour   = "0" + hour;   }
		if (minute < 10) { minute = "0" + minute; }
		if (second < 10) { second = "0" + second; }
		var timeString = hour +
						':' +
						minute +
						':' +
						second +
						" " +
						ap;
	   	return timeString;
	} // function getClockTime()
//***************************************************************************************************************