// JavaScript Document

//Manipulador de Eventos
//Adiciona uma função quando ocorrer determinado evento no objeto. 
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

MaskInput = function(f, m){
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
	//alert(f)
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);

};


function valtexto(campo) {
	campo.style.border="1px solid #cccccc";
	if (campo.value == ""){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
}
function valselect(campo) {
	campo.style.border="1px solid #cccccc";
	if (campo.selectedIndex == 0){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
}
function valemail(campo) {
	campo.style.border="1px solid #cccccc";
	var mail=campo.value;
    apos=mail.indexOf("@");
	dotpos=mail.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) {
		campo.style.border="1px solid #ff0000";

		campo.focus();
		return 1;
	}
}
function valradio(campo) {
	for (var x=campo.length-1; x > -1; x--) {
			campo[x].style.backgroundColor="";
    }
    var cnt = -1;
    for (var i=campo.length-1; i > -1; i--) {
        if (campo[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) {
		return 0;
	}
    else {
		for (var v=campo.length-1; v > -1; v--) {
			campo[v].style.backgroundColor="#ffbbbb";
    	}
		return 1;
	}
}

function numero(field) {
	var valid = "0123456789"
	var ok = "yes";
	var temp;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
		field.value = field.value.substring(0, field.value.length-1);
		field.focus();
   }
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
 for (i = 0; i < s.length; i++){ 
 // Check that current character is number.
 var c = s.charAt(i);
 if (((c < "0") || (c > "9"))) return false;
 }
 // All characters are numbers.
 return true;
}

function stripCharsInBag(s, bag){
	var i;
 var returnString = "";
 // Search through string's characters one by one.
 // If character is not in bag, append to returnString.
 for (i = 0; i < s.length; i++){ 
 var c = s.charAt(i);
 if (bag.indexOf(c) == -1) returnString += c;
 }
 return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
 // EXCEPT for centurial years which are not also divisible by 400.
 return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
 } 
 return this
}

function valdata(campo){
	campo.style.border="1px solid #cccccc";
	var dtStr = campo.value
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
	if (strMonth.length<1 || month<1 || month>12){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
}
function formatadata(campo) {
	var valor = campo.value;
	if (valor.length == 2 && valor.substr(1,1) == "/") {
		campo.value = "0" + valor
	}
	if (valor.length == 3 && valor.substr(2,1) != "/") {
		campo.value = valor.substr(0,2) + "/" + valor.substr(2)
	}
	if (valor.length == 5 && valor.substr(4,1) == "/") {
		campo.value = valor.substr(0,3) + "0" + valor.substr(3)
	}
	if (valor.length == 6 && valor.substr(5,1) != "/") {
		campo.value = valor.substr(0,5) + "/" + valor.substr(5)
	}
	
	/*
	if (valor.length == 2 && valor.substr(1,1) == "/" ) {
		campo.value = "0" + valor
	}*/
}

function validarBusca()
{
var searchstring = document.formbusca.criterioDeBusca.value;
if (searchstring.trim('both') == "" || searchstring.trim('both').length < 3) {
alert("Preencha o campo com pelo menos trÃªs caracteres para realizar a busca!");

document.formbusca.criterioDeBusca.focus();
return (false);
}
return (true);
}


function buscaRastreamentoHome()
{
if(document.rastreamentohome.tipo) {
//nacional
var theurl = "http://websro.correios.com.br/sro_bin/txect01$.QueryList" + "?" + "P_LINGUA=" + document.rastreamentohome.P_LINGUA.value + "&P_TIPO=" + document.rastreamentohome.P_TIPO.value + "&P_COD_UNI=" + document.rastreamentohome.P_COD_UNI.value ;
//alert(theurl);
//alert(document.rastreamentohome.tipo[0].checked)
window.open(theurl);
//document.rastreamentohome.submit();
return (false);
}

if(document.rastreamentohome.P_COD_UNI.value.substr(0,2)=='XM' || document.rastreamentohome.P_COD_UNI.value.substr(0,2)=='VC'){
window.open("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_COD_UNI="+document.rastreamentohome.P_COD_UNI.value.substr(0,13)+"&P_TIPO=001&P_LINGUA=001","SRO","width=550,height=400,scrollbars=yes,resizable=no,toolbar=no");
document.rastreamentohome.P_COD_UNI.value = "";
return (false);
}

if(document.rastreamentohome.tipo[1].value) {
//internacional
var theurl = "http://www.correios.com.br/servicos/rastreamento/internacional/resultado.cfm"
alert(theurl);
document.rastreamentohome.method = "post";
document.rastreamentohome.action = theurl;
var pname = document.createElement("input");
pname.type="hidden";
pname.value="P";
pname.name = "Idioma";
document.rastreamentohome.appendChild(pname);

pname = document.createElement("input");
pname.type="hidden";
pname.value="Pesquisar"
pname.name = "Consultar";
document.rastreamentohome.appendChild(pname);

pname = document.createElement("input");
pname.type="hidden";
pname.value= document.rastreamentohome.P_COD_UNI.value
pname.name = "Consulta";
document.rastreamentohome.appendChild(pname);

//alert(document.rastreamentohome.Consulta.value);
//alert(document.rastreamentohome.tipo[1].checked)

 //document.rastreamentohome.submit();
return (true);
}

}
function limita(field,validos) {
	var valid = "" + validos
	var temp;
	var final = "";
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) != "-1") final += temp;
	}
	if (field.value != final) field.value = final;
}
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

MaskInput = function(f, m){
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
	//alert(f)
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};
function createXMLHTTP() {
	var ajax;
	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
			alert(ajax);
		}
		catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			}
			catch(exc) {
				 alert("Esse browser não tem recursos para uso do Ajax");
				 ajax = null;
			}
		}
		return ajax;
	}
	
	var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	for (var i=0; i < arrSignatures.length; i++) {
		try {
			var oRequest = new ActiveXObject(arrSignatures[i]);
			return oRequest;
		} 
		catch (oError) {}
	}
	throw new Error("MSXML is not installed on your system.");
}
function createXMLHTTP() {
	var ajax;
	try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } 
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
			alert(ajax);
		}
		catch(ex) {
			try { ajax = new XMLHttpRequest(); }
			catch(exc) {
				 alert("Esse browser não tem recursos para uso do Ajax");
				 ajax = null;
			}
		}
		return ajax;
	}
	var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
						"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
						"Microsoft.XMLHTTP"];
	for (var i=0; i < arrSignatures.length; i++) {
		try {
			var oRequest = new ActiveXObject(arrSignatures[i]);
			return oRequest;
		} 
		catch (oError) {}
	}
	throw new Error("MSXML is not installed on your system.");
}

function preenchecidade(opcao,cod) {
	
		var ajax = createXMLHTTP();
		ajax.open("post", "verifica.asp", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.onreadystatechange=function() {
			if (ajax.readyState==4)
			{
				if (ajax.responseText != "erro")
				{
					if (cod == 1)
					{
						
						document.getElementById('cidade').value = ajax.responseText;
					}else{ 
					
						document.getElementById('comboEstado').innerHTML = ajax.responseText;
					}
				
				}
			 }
		}
		ajax.send("cep=" + opcao + "&cod=" + cod);
}

function preencheEndereco(opcao){
	for (var cod = 1; cod<3;cod++){
		preenchecidade(opcao,cod)
	}
}
function preenchecidade2(opcao,cod) {
	
		var ajax = createXMLHTTP();
		ajax.open("post", "ajaxcompra.asp", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.onreadystatechange=function() {

			if (ajax.readyState==4)
			{
				//alert(ajax.responseText)
				if (ajax.responseText != "erro")	{
					if (cod == 1)
					{
						
						document.getElementById('cidade').value = ajax.responseText;
					}
					if (cod == 2)
					{
						document.getElementById('bairro').value = ajax.responseText;
					}
				    if (cod == 3)
					{
						document.getElementById('comboEstado').innerHTML = ajax.responseText;
					}
					if (cod == 4)
					{
						document.getElementById('combologr').innerHTML = ajax.responseText;
					}
					if (cod == 5)
					{
						document.getElementById('endereco').value = ajax.responseText;
					}
				
				}
			 }
		}
		ajax.send("cep=" + opcao + "&cod=" + cod);
}

function preencheEndereco2(opcao){
	for (var cod = 1; cod<6;cod++){
		preenchecidade2(opcao,cod)
	}
}


