// JavaScript Document

/**
** Bom senhores, pelo visto, esta será nossa bibliteca padrão
** Então, por favor, qualquer alteração no script, vamos adicioar comentários de quem fez
** a alteração, quando e o motivo para que possamos deixar o script mais completo e compreensivo
** possível.
**
** NOTE: Marcos(03/05/07) - A princípio, estamos usando muito para Ajax. A função criada ainda é simples, pois não tive muito tempo
** de incrementá-la mas as rotinas básicas estão sendo executadas (lol)... ps: Se alguém descobrir o pq do FF não ler o responseXML,
** procure a mim ou ao Everton(Alemão) pra podermos alterar o script... Cya
**
**/
if(typeof System == "undefined") var System = {};

if(typeof IE == "undefined") var IE = document.all ? true : false;

System.namespace = function(){
	var a = arguments, o = null, i, j, d;
	for(i=0;i<a.length; i++){
		d = a[i].split(".");
		o = System;
			
		for (j=(d[0] == "System") ? 1 : 0; j<d.length; j=j+1){
			o[d[j]]=o[d[j]] || {};
			o=o[d[j]];
		}
	}
	return o;
};

System.Type = {
	//VERIFICA SE O OBJETO É OBJECT
	isObject: function(obj){
		return typeof obj == "object";
	},
	
	//VERIFICA SE O OBJETO É NULL
	isNull: function(obj){
		return obj == null;
	},
	
	//VERIFICA SE O OBJETO É FORM
	isForm: function(obj)
	{
		return obj.tagName == "FORM";
	},
	
	//VERIFICA SE O OBJETO É XMLHttpRequest
	isXMLHttp: function(obj){
		var type;
		try{
			type = typeof obj == XMLHttpRequest();
		}
		catch(ee){
			try{
				type = typeof obj == ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				try{
					type = typeof obj == ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(E){
					type = false;
				}
			}
		}
		return type;
	},
	
	isNumber: function(obj){
		return typeof obj == "number" && isFinite(obj);
	},
	
	isFunction: function(obj){
		return typeof obj == "function"
	},
	
	//VERIFICA SE OBJ É UM NÚMERO
	isNumberOnly: function(e){
		var keynum, keychar, numcheck;
		
		if(IE) keynum = e.keyCode; //IE
		else keynum = e.which; //MOZILLA, OPERA, ETC...
		keychar = String.fromCharCode(keynum);
		numcheck = /\d/;

		return numcheck.test(keychar);
	},
	
	//VERIFICA SE O CPF É VÁLIDO
	isCPF: function(obj,displayMsg){
		
		var cpf = obj.value, digit1, digit2, a=[], b=0, c=11, msg=displayMsg,strReturn = true;
		
		
        /*if (cpf == "000.000.000-00" || cpf == "111.111.111-11" || cpf == "222.222.222-22" || cpf == "333.333.333-33" || cpf == "444.444.444-44" || cpf == "555.555.555-55" || cpf == "666.666.666-66" || cpf == "777.777.777-77" || cpf == "888.888.888-88" || cpf == "999.999.999-99")
        {
			//setTimeout(function(){obj.focus();},100);
			System.Message.Error(1,msg);
		    strReturn = false;
		}*/
		
		if (cpf.length == 14)
		{
		    
            if (cpf == "000.000.000-00" || cpf == "111.111.111-11" || cpf == "222.222.222-22" || cpf == "333.333.333-33" || cpf == "444.444.444-44" || cpf == "555.555.555-55" || cpf == "666.666.666-66" || cpf == "777.777.777-77" || cpf == "888.888.888-88" || cpf == "999.999.999-99")
            {
                setTimeout(function(){obj.focus();},100);
			    System.Message.Error(1,msg);
			    strReturn = false;
		    }
		    
			cpf = cpf.replace(/\./g,"");
			cpf = cpf.replace(/\-/g,"");
			
			for(var i=0;i<11;i++){
				a[i] = cpf.charAt(i);
				if(i<9) b+=(a[i]*--c);
			}
			
			if ((x=b%11)<2) a[9] = 0;
			else a[9]=11-x;
			
			b = 0;
			c = 11;
			
			for(y=0;y<10;y++) b+=(a[y]*c--);
			
			if ((x=b%11)<2) a[10] = 0;
			else a[10] = 11-x;
			
			if((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
			{
				setTimeout(function(){obj.focus();},100);
				System.Message.Error(1,msg);
				strReturn = false;
			}
 			return strReturn;
		}
	},
	
	isDate: function(obj,displayMsg){
		var dia,mes,ano,today,msg=displayMsg,strReturn = true;
		
		if(obj.value.length < 10 && obj.value.length > 0){
			System.Message.Error(3,msg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		
		today = new Date();
		
		dia = obj.value.split("/")[0];
		mes = obj.value.split("/")[1];
		ano = obj.value.split("/")[2];
		
		
		if (ano >= today.getFullYear()-9){
			System.Message.Error(3,msg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		
		if(dia > 31 || mes > 12 || (ano < 1900 || ano > today.getFullYear())){
			System.Message.Error(3,msg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		
		if(dia > 29 && mes == 2 || (ano < 1900 || ano > today.getFullYear())){
			System.Message.Error(3,msg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		
		if(dia > 30 && mes == 6 || (ano < 1900 || ano > today.getFullYear())){
			System.Message.Error(3,msg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		
		return strReturn;
	},
	
	isCEP: function(obj,displayMsg){
		var ifen = obj.value.charAt(5),msg = displayMsg,strReturn = true;
		if(ifen != "-"){
			System.Message.Error(4,msg);
			obj.focus();
			strReturn = false;
		}
		if(obj.value.length < 9){
			System.Message.Error(4,msg);
			obj.focus();
			strReturn = false;
		}
		return strReturn;
	},
	
	isEmail: function(obj,displayMsg){
		var msg = displayMsg,strReturn = true;
		testeEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
		if (obj.value.length > 0){
			OKEmail = testeEmail.test(obj.value);
			if (!OKEmail){
				System.Message.Error(5,msg)
				setTimeout(function(){
								obj.focus();
								},100);
				strReturn = false;
			}
			else{
				System.Message.Error("",msg)
			}
			return strReturn;
		}
	},
	
	Compare: function(obj1,obj2){
		return obj1.value == obj2.value;
	},
	
	isFone: function(obj,displayMsg){
		var strReturn = true;
		if(obj.value.length > 0 && obj.value.length < 14){
			System.Message.Error(6,displayMsg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		return strReturn;
	},
	
	isMatricula: function(obj,displayMsg){
		var strReturn = true;
		if(obj.value.length < 1){
			System.Message.Error(8,displayMsg);
			setTimeout(function(){
							obj.focus();
							},100);
			strReturn = false;
		}
		return strReturn;
	}
	
	
};

System.Web = {
	//MONTA O PARAMETROS COM TODOS OS CAMPOS DO FORM
	getForm: function(form){
		var strFields = new String();
		for(x=0;x<form.elements.length;x++){
			if(strFields.length == 0){
				if(form.elements[x].type == 'checkbox'){
					if(form.elements[x].checked == true)
						strFields = form.elements[x].name+"="+escape(form.elements[x].value);
					else
						strFields = form.elements[x].name+"=";
				}
				else
					strFields = form.elements[x].name+"="+escape(form.elements[x].value);
			}
			else{
				if(form.elements[x].type == 'checkbox'){
					if(form.elements[x].checked == true)
						strFields += "&"+form.elements[x].name+"="+escape(form.elements[x].value);
					else
						strFields += "&"+form.elements[x].name+"=";
				}
				else
					strFields += "&"+form.elements[x].name+"="+escape(form.elements[x].value);
			}
		}
		return strFields;
	},
	
	//CRIA COOKIE
	setCookie: function(c_name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
	},
	
	//RETORNA O COOKIE CRIADO
	getCookie:	function(c_name){
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=")
			if (c_start!=-1){ 
				c_start=c_start + c_name.length+1 
				c_end=document.cookie.indexOf(";",c_start)
							
				if (c_end==-1) c_end=document.cookie.length
							
				return unescape(document.cookie.substring(c_start,c_end))
			} 
		}
		return;
	},
	
	getEvent: function(e){
		if(IE)
			return window.event;
		else
			return e;
	},
	
	stopEvent: function(e){
		if(e != null){
			if(!IE) {
				e.preventDefault();
				e.stopPropagation();
			}
			else{
				e.cancelBubble = true;
				e.returnValue = false;
			}
		}
	},
	
	AddEvent: function(evt,func,obj){
		if(obj.addEventListener)
			obj.addEventListener(evt,func,true);
		else if(obj.attachEvent)
			obj.attachEvent('on'+evt,func);
	}
};

System.Form = {
	//VALIDA O FORM
	AuthForm: function(form){
		var a = arguments, v = true;
		
		if(System.Type.isForm(form)){
			for(i=1;i<a.length;i++){
				if(a[i].value.length == 0){
					v = false;
					break;
				}
			}
		}
		return v;
	},
	
	//FORMATA O DADO PARA CPF
	toCPF: function(obj,displayMsg){
		var msg = displayMsg, e;
		
		obj.maxLength = 14;
		
		System.Web.AddEvent('keypress',function(e){
											e = System.Web.getEvent(e);
											System.Format.CPF(obj,msg,e)
										},obj);
		System.Web.AddEvent('blur',function(){
										System.Type.isCPF(obj,msg);
									},obj);
		
	},
	
	toDate: function(obj,displayMsg){
		var msg = displayMsg, e;

		obj.maxLength = 10;
		
		System.Web.AddEvent('keypress',function(e){
												e = System.Web.getEvent(e);
												System.Format.Date(obj,msg,e);
												},obj);
		System.Web.AddEvent('blur',function(){
												System.Type.isDate(obj,msg);
											},obj);
	},
	
	toCEP: function(obj,displayMsg){
		var msg = displayMsg, e;
		
		obj.maxLength = 9;
		
		System.Web.AddEvent('keypress',function(e){
												e = System.Web.getEvent(e);
												System.Format.CEP(obj,msg,e);
												},obj);
		System.Web.AddEvent('blur',function(){
											System.Type.isCEP(obj,msg);
											},obj);
	},
	
	toFone: function(obj,displayMsg){
		var msg = displayMsg,e;
		
		obj.maxLength = 14;
		
		System.Web.AddEvent('keypress',function(e){
												e = System.Web.getEvent(e);
												System.Format.Fone(obj,msg,e);
												},obj);
		System.Web.AddEvent('blur',function(){
											System.Type.isFone(obj,msg);
											},obj);
	},
	toMatricula: function(obj,displayMsg){
		var msg = displayMsg,e;
		
		obj.maxLength = 14;
		
		System.Web.AddEvent('keypress',function(e){
												e = System.Web.getEvent(e);
												System.Format.Matricula(obj,msg,e);
												},obj);
		System.Web.AddEvent('blur',function(){
											System.Type.isMatricula(obj,msg);
											},obj);
	},
	
	toEmail: function(obj,displayMsg){
		var msg = displayMsg,e;
		
		System.Web.AddEvent('blur',function(){
											System.Type.isEmail(obj,msg);
											},obj);
		System.Web.AddEvent('keypress',function(){
											msg.innerHTML = '';
											},obj);
	}
};

System.Format = {
	CPF: function(obj,objMsg,e){
		var str = obj.value, msg=objMsg;
		obj.maxLength = 14;
		
		if(System.Type.isNumberOnly(e)){
			msg.innerHTML = "";
			if(str.length == 3) str = str + ".";
			if(str.length == 7) str = str + ".";
			if(str.length == 11) str = str + "-";
			obj.value = str;
		}
		else{
			if(str.length < 14){
				if(!IE){
					if(e.which != 8 && e.which != 0 && e.which != 13){
						System.Message.Error(0,msg);
						System.Web.stopEvent(e);
					}
				}
				else{
					System.Message.Error(0,msg);
					System.Web.stopEvent(e);
				}
			}
		}
	},
	
	Date: function(obj,objMsg,e){
		var str = obj.value, msg=objMsg;
		
		if(System.Type.isNumberOnly(e)){
			msg.innerHTML = "";
			if(str.length == 2) str = str + "/";
			if(str.length == 5) str = str + "/";
			return obj.value = str;
		}
		else{
			if(str.length < 10){
				if(!IE){
					if(e.which != 8 && e.which != 0 && e.which != 13){
						System.Message.Error(0,msg);
						System.Web.stopEvent(e);
					}
				}
				else{
					System.Message.Error(0,msg);
					System.Web.stopEvent(e);
				}
			}
		}
	},
	
	CEP: function(obj,objMsg,e){
		var str = obj.value,msg=objMsg;
		
		if(System.Type.isNumberOnly(e)){
			msg.innerHTML = '';
			if(str.length == 5) str += "-";
			obj.value = str;
		}
		else{
			if(!IE){
				if(e.which != 8 && e.which != 0 && e.which != 13){
					System.Message.Error(0,msg);
					System.Web.stopEvent(e);
				}
			}
			else{
				System.Message.Error(0,msg);
				System.Web.stopEvent(e);
			}
		}
	},
	
	Fone: function(obj,objMsg,e){
		var str = obj.value,msg=objMsg;
		
		if(System.Type.isNumberOnly(e)){
			msg.innerHTML = '';
			if(str.length == 1) str = "(" + str;
			if(str.length == 3) str += ") ";
			if(str.length == 9) str += "-";
			obj.value = str;
		}
		else{
			if(!IE){
				if(e.which != 8 && e.which != 0 && e.which != 13){
					System.Message.Error(0,msg);
					System.Web.stopEvent(e);
				}
			}
			else{
				System.Message.Error(0,msg);
				System.Web.stopEvent(e);
			}
		}
	},
	Matricula: function(obj,objMsg,e){
		var str = obj.value,msg=objMsg;
		
		if(System.Type.isNumberOnly(e)){
			msg.innerHTML = '';
			
			obj.value = str;
		}
		else{
			if(!IE){
				if(e.which != 8 && e.which != 0 && e.which != 13){
					System.Message.Error(0,msg);
					System.Web.stopEvent(e);
				}
			}
			else{
				System.Message.Error(0,msg);
				System.Web.stopEvent(e);
			}
		}
	}
};

System.DOM = {
	//CONVERTE DE STRING PARA XML
	ParserXML : function (str) {
		if (window.ActiveXObject){
			var doc=new ActiveXObject("Microsoft.XMLDOM");
			doc.async="false";
			doc.loadXML(str);
		}
		// code for Mozilla, Firefox, Opera, etc.
		else{
			var parser = new DOMParser();
			var doc = parser.parseFromString(str,"text/xml");
		}
		return doc;
	}
};

System.Ajax = {
	//CRIA O OBJETO XMLHttpRequest
	CreateObject: function(obj){
		try{
			obj = new XMLHttpRequest();
			if(obj.overrideMimeType)
				obj.overrideMimeType("text/html");
		}
		catch(ee){
			try{
				obj = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				try{
					obj = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(E){
					obj = null;
				}
			}
		}
		return obj;
	},
	
	Error: function(errNumber,func){
		
		if(errNumber >= 400 && errNumber <= 417){
			var msg = "<p>Um erro foi encontrado."+
					  "<br>Por favor, tente novamente mais tarde.</p>";
		}
		
		if(errNumber >= 500 && errNumber <= 505){
			var locat=location.pathname.split("/");
			var pageName = locat[locat.length-1];
			var msg = "<span style=\"font-family:Verdana; font-size:11px;\">"+
						  "<p>Um erro interno foi encontrado."+
						  "<br>Por favor, informe os seguintes dados ao administrador do site:</p>"+
						  "<ul>"+
						  	"<li>Nº Erro: "+errNumber+"</li>"+
						  	"<li>Página: "+pageName+"</li>"+
						  "</ul>"+
					  "</span>";
			func(msg);
			return false;
		}
	},
	
	Send: function(obj,url,par,method,func){
		
		var xmlhttp;
		var type;
		if(arguments.length > 5)
			type=arguments[5];
			 
		if(!System.Type.isObject(obj)){
			xmlhttp = System.Ajax.CreateObject(obj);
		}
		else{
			if(!System.Type.isXMLHttp(obj)){
				alert("O objeto "+obj+" não é do tipo XMLHttp.");
				return false;
			}
			else{
				xmlhttp = obj;
			}
		}

		if(!System.Type.isNull(xmlhttp)){

			if(System.Type.isFunction(func)){
				xmlhttp.onreadystatechange = function(){
					if(xmlhttp.readyState == 4){					  	
						if(xmlhttp.status == 200){
						 if(typeof type != "undefined")
							func(System.DOM.ParserXML(xmlhttp.responseText)); 
						 else
						    func(xmlhttp.responseText); 						   
						}
						// Desablitei a função de tratamento de erro para que eu pudesse ver os erros de retorno do ASP...
						// mas se já estiver seguro de que não há erros, comente o document.write(xmlhttp.responseText)
						// e use a função System.Ajax.Error(xmlhttp.status,func) que tem um tratamento melhor para erros.
						else System.Ajax.Error(xmlhttp.status,func); //document.write(xmlhttp.responseText) //System.Ajax.Error(xmlhttp.status,func);
					}
				}
			}
		
			if(method == "GET"){
				if(!System.Type.isForm(par)){
					if(par != "") url+="?"+par+"&"+Math.random();
					else url += "?"+Math.random();
					xmlhttp.open("GET",url,true);				
					xmlhttp.send(null);
				}else{
					var form = par;
					par = System.Web.getForm(form);
					System.Ajax.Send(obj,url,par,"POST",func);
				}
			}
			else if(method == "POST"){			
				if(System.Type.isForm(par)){
					var form = par;					
					par = System.Web.getForm(form);
				}
				
				xmlhttp.open("POST",url,true);
				xmlhttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded; charset=iso-8859-1");		
				xmlhttp.setRequestHeader("Content-length", par.length);
				xmlhttp.setRequestHeader("Connection", "close");
				xmlhttp.send(par);
			}
			else{
				alert("O metodo "+method+" de envio é inválido");
				return false;
			}
		}
	}
	
};

System.Message = {
	Error: function(num,obj){
		
		var errorNumber=[], msg;
		
		errorNumber[0] = "Somente números são permitidos neste campo.";
		errorNumber[1] = "O CPF digitado é inválido.";
		errorNumber[2] = "Os campos em vermelho são obrigatórios.";
		errorNumber[3] = "A data digitada é inválida.";
		errorNumber[4] = "O CEP digitado é inválido.";
		errorNumber[5] = "O E-mail digitado é inválido.";
		errorNumber[6] = "O Telefone digitado é inválido.";
		errorNumber[7] = "Informe primeiro o seu CEP que o endereço será preenchido automaticamente.";
		errorNumber[8] = "Matrícula digitada inválida.";

		if(!document.getElementById("msgText")){
			msg = document.createElement("FONT");
			msg.face = "Verdana, Arial, Helvetica, sans-serif";
			msg.size = -1;
			msg.color = "#FF0000";
			msg.id = "msgText";
			
			if(System.Type.isNumber(num))
				msg.innerHTML = errorNumber[num];
			else
				msg.innerHTML = num;
	
			obj.innerHTML = '';
			obj.appendChild(msg);
		}
		else{
			if(System.Type.isNumber(num))
				document.getElementById("msgText").innerHTML = errorNumber[num];
			else
				document.getElementById("msgText").innerHTML = num;
		}
	}
};


