// Retorna um objeto atraves do id
function $id(id) {
	return document.getElementById(id);
}

// Validaçao padrao
function validacaoPadrao(form, regras) {
	var f = form;
	var msg = "";
	if (!f) {
		return false;
	}
	for (var i = 0; i < regras.length; i++) {
		arr = regras[i].split("|");
		var campo = f[arr[0]];
		if (campo) {
			switch (arr[2]) {
				case "required":
					if (campo.value == "") {
						msg += arr[1] + " required." + "\n";
					}
					break;
				case "integer":
					if ( (isNaN(campo.value)) || (campo.value == "") ) {
						msg += arr[1] + " not a number." + "\n";
					}
					break;
			}
		}
	}
	if (msg != "") {
		msg = "Errors:\n" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}

// Obtem um objeto via Ajax
function setInfoAjax(ajaxUrl, funcaoRetorno, poForm) {
	var obj;
	// Verifica se foi passado a url
	if (ajaxUrl == "") {
		return false;
	}
	// Verifica a função que vai ser chamada
	if (typeof(funcaoRetorno) == "undefined") {
		return false;
	}
	
	var req = null;
	// Procura por um objeto nativo (Mozilla/Safari)
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", ajaxUrl, true);
		req.send(null);
	// Procura por uma versao ActiveX (IE)
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", ajaxUrl, true);
			req.send();
		}
	}
	
	function processReqChange() {
		var funcao = eval(funcaoRetorno);
		if (req.readyState == 4) {
			if ((req.status == 200) && ((req.responseText) != "UNKNOWN")) {
				var json = eval("(" + req.responseText + ")");
				return funcao(json["Result"], poForm);
			} else {
				//alert("Houve um problema ao obter os dados:\n" + req.statusText);
				return funcao(null);
			}
		}
	}
}

// Carrega os valores quando muda o tipo
function changeCompany(idCompany, data, idAppointment, poForm) {
	var f = poForm;
	f.txtHora.length = 0;
	cria_option(f.txtHora, "Carregando...", 0, false);
	setInfoAjax("ajax_time.php?id=" + idCompany + "&_data=" + data + "&txtAgendamento=" + idAppointment, "setCompanyTimes", poForm);
}

// Seta os valores no campo Select
function setCompanyTimes(obj, poForm) {
	if ((obj != null) && (typeof(obj) != "undefined")) {
		var f = poForm;
		f.txtHora.length = 0;
		cria_option(f.txtHora, "", "", false);
		for (var i = 0; i < obj.length; i++) {
			if (obj[i].hora) {
				cria_option(f.txtHora, obj[i].hora, obj[i].hora, false);
			}
		}
	}
}

// Cria uma opçao num campo select
function cria_option(campo, texto, valor, seleciona) {
	if ((campo != null) && (campo.options != null)) {
		campo.options[campo.options.length] = new Option(texto, valor, false, seleciona);
	} 
}

function dataPorExtenso(data) {
	if ( (isDate(data)) && (data != "") ) {
		var barras = data.split("/");
		var dia = barras[0];
		var mes = barras[1];
		var ano = barras[2];
		var oData = new Date(ano, Number(mes) - 1, dia);
		var dayArray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturay");
		var monthArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		dataExtenso = oData.getDate() + ', ' + monthArray[oData.getMonth()] + ', ' + oData.getFullYear() + ' - ' + dayArray[oData.getDay()];
		return dataExtenso;
	} else {
		return "";
	}
}

// Verifica a quantidade de dias em fereveiro
function DiasInFevereiro (pnAno) {
    return (  ((pnAno % 4 == 0) && ( (!(pnAno % 100 == 0)) || (pnAno % 400 == 0) ) ) ? 29 : 28 );
}

// Validar Data
function isDate(data) {
	if (data == "") {
		return false;
	}
	var barras = data.split("/");
	if (barras.length == 3) {
		var dia = barras[0];
		var mes = barras[1];
		var ano = barras[2];
		var resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4));
		if (!resultado) {
			return false;
		}
		if (ano.length != 4) {
			return false;
		}
		dias = new Array(13);
		dias[1] = 31;
		dias[2] = DiasInFevereiro(ano);   // deve ser verificado o caso de anos bissextos
		dias[3] = 31;
		dias[4] = 30;
		dias[5] = 31;
		dias[6] = 30;
		dias[7] = 31;
		dias[8] = 31;
		dias[9] = 30;
		dias[10] = 31;
		dias[11] = 30;
		dias[12] = 31;
		if (parseInt(dia) > dias[parseInt(mes)]) {
			return false;
		}
	} else {
		return false;
	}
	
	return true;
}

// Validar Data
function ValidaData(field) {
	if (field.value == "") {
		return true;
	}
	var hoje = new Date();
	var anoAtual = hoje.getFullYear();
	var barras = field.value.split("/");
	if (barras.length == 3) {
		var dia = barras[0];
		var mes = barras[1];
		var ano = barras[2];
		var resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4));
		if (!resultado) {
			alert("Invalid date format. Ex.: (dd/mm/yyyy)");
			field.focus();
			field.select();
			return false;
		}
		if (ano.length != 4) {
			alert("The year must have 4 digits.");
			field.focus();
			field.select();
			return false;
		}
		//if (ano < anoAtual) {
		//	alert("O ano não pode ser menor que o ano atual.");
		//	field.focus();
		//	field.select();
		//	return false;
		//}
		dias = new Array(13);
		dias[1] = 31;
		dias[2] = DiasInFevereiro(ano);   // deve ser verificado o caso de anos bissextos
		dias[3] = 31;
		dias[4] = 30;
		dias[5] = 31;
		dias[6] = 30;
		dias[7] = 31;
		dias[8] = 31;
		dias[9] = 30;
		dias[10] = 31;
		dias[11] = 30;
		dias[12] = 31;
		if (dia > dias[mes]) {
			alert("Dia inválido.");
			field.focus();
			field.select();
			return false;
		}
	} else {
		alert("Invalid date format. Ex.: (dd/mm/yyyy)");
		field.focus();
		field.select();
		return false;
	}
}

// Valida hora e minuto
function ValidaHora(field) {
	if (field.value == "") {
		return true;
	}
	if (field.value.length != 5) {
		alert("Invalid hour format. Ex.: (hh:mm)");
		field.focus();
		field.select();
		return false;
	}
	var barras = field.value.split(":");
	if (barras.length == 2) {
		var hora = barras[0];
		var minuto = barras[1];
		var resultado = (!isNaN(hora) && (hora >= 0) && (hora < 24)) && (!isNaN(minuto) && (minuto >= 0) && (minuto < 60));
		if (!resultado) {
			alert("Invalid hour format. Ex.: (hh:mm)");
			field.focus();
			field.select();
			return false;
		}
	}
	else {
		alert("Invalid hour format. Ex.: (hh:mm)");
		field.focus();
		field.select();
		return false;
	}
}

// Verifica o email
function ValidaEmail(field) {
	var mail='';
	if (field.value == '') { return false; }
	else { mail = field; }
	
	if (mail.value == "") {
		alert("Enter your email address.");
		mail.focus();
		mail.select();
		return false;
	}
	else {
		prim = mail.value.indexOf("@")
		if (prim < 2) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("@",prim + 1) != -1) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf(".") < 1) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf(" ") != -1) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("zipmeil.com") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("hotmeil.com") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf(".@") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("@.") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf(".com.br.") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("/") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("[") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("]") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("(") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf(")") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
		if (mail.value.indexOf("..") > 0) {
			alert("Please check the entered email address.");
			mail.focus();
			mail.select();
			return false;
		}
	}
	return true;
}