function validavirgula(field) {
	var valid = "0123456789,"
	var ok = true;
	var temp;
	var virgula = 0;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (temp == ',') virgula += 1;
		if (virgula > 1) valid = "0123456789";
		ok = (valid.indexOf(temp) == "-1");		
	}
	if (ok) {
	field.value = field.value.substring(0, field.value.length-1);
	field.focus();
   }
}

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 validate(field) {
	var valid = "0123456789,"
	var ok = true;
	var temp;
	var virgula = 0;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (temp == ',') virgula += 1;
		if (virgula > 1) valid = "0123456789";
		ok = (valid.indexOf(temp) == "-1");		
	}
	if (ok) {
	field.value = field.value.substring(0, field.value.length-1);
	field.focus();
   }
}

function limita(field,validos) {
	var valid = "" + validos
	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();
   }
}


function saindo() {
	window.onbeforeunload = function (evt) {
		var message = 'Você ainda não salvou os dados preenchidos.';
		if (typeof evt == 'undefined') {
			evt = window.event;
		}
	  	if (evt) {
			evt.returnValue = message;
	  	}
	  	return message;
	}
}


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();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};

/*
<form action="">
    <fieldset>
    <legend>Máscara Genérica</legend>
    <label>telefone "(99)9999-9999"</label><input type="text" name="fone" />
    <label>data "99/99/9999"</label><input type="text" name="data" />
    <label>máscara = letra + letra sem acento + 2 números + tracinho + qualquer digito + letra "Cc99-*C"</label><input type="text" name="etc" />
    <label>permite qualquer coisa menos a, b ou c "E^abc"</label><input type="text" name="except" />
    <label>permite somente a, b ou c "O^abc"</label><input type="text" name="only" />
    <label>somente letras "C^"</label><input type="text" name="letra" />
    <label>somente letras e, tb espaço em branco "C^ "</label><input type="text" name="letra2" />
    <label>somente números e, as letras a, b e c "9^abc"</label><input type="text" name="numero" />
    </fieldset>
</form>

<script type="text/javascript">
//<![CDATA[

var f = document.forms[0];
MaskInput(f.fone, "(99)9999-9999");
MaskInput(f.data, "99/99/9999");
MaskInput(f.etc, "Cc99-*C");
MaskInput(f.except, "E^abc");
MaskInput(f.only, "O^abc");
MaskInput(f.letra, "C^");
MaskInput(f.letra2, "C^ ");
MaskInput(f.numero, "9^abc");

//]]>
</script>

MaskInput(field: HTMLInputElement, mask: String): void 
Adiciona máscara a um campo. 
fieldcampo que vai receber a máscara 
maskmáscara que será aplicada 
Regras Padrões
a = A-Z e 0-9 
A = A-Z, acentos e 0-9 
9 = 0-9 
C = A-Z e acentos 
c = A-Z 
* = qualquer coisa 
Regras Especiais
E = (Except) exceção 
O = (Only) somente 
Criação de Máscaras
Máscara simples: nesse tipo de máscara o usuário pode digitar no máximo a mesma quantidade de caracteres que a máscara contém. 
Exemplo: 
Telefone = (99)9999-9999 
Data = 99/99/9999 

Máscara especial "regra^exceções": esse tipo de máscara é composto por 2 partes, separadas por "^", o lado esquerdo especifica a regra e o direito as exceções para a regra selecionada. 
Exemplo: 
9^abc = a regra é aceitar somente números "9" e a exceção são os caracteres a, b e c 
c^123 = aceita somente caracteres de a-z e a exceção são os números 1, 2 e 3 

Uso das regras especiais: ela é semelhante a máscara especial, porém o lado esquerdo tem um significado diferente, podendo ser "E" (qualquer coisa, exceto...) ou "O" (somente...) 
Exemplo: 
E^abc: aceita qualquer coisa, menos a, b e c 
O^123: só permite os caracteres 1, 2 e 3 

*/


function limita(field,validos) {
	var valid = "" + validos
	final = ""
	var temp;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) != "-1") final = final + temp;
	}
	field.value = final
}

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 valnumero(campo) {
	campo.style.border="1px solid #cccccc";
	var i;
	valor = 0
 for (i = 0; i < campo.value.length; i++){ 
 var c = campo.value.charAt(i);
 if (((c < "0") || (c > "9"))) valor = 1;
 }
	if (valor == 0){
		campo.style.border="1px solid #ff0000";
		campo.focus();
		return 1;
	}
}

function valselectmult(campo) {
	campo.style.border="1px solid #cccccc";
	for (var i = 0; i < campo.options.length; i++) {
		if (campo.options[i].selected) {
			return 
		}
	}
		campo.style.border="1px solid #ff0000";
	campo.focus();
	return 1;
}

function valcheckboxmulti(campo) {
	campo.style.border="1px solid #cccccc";
	for (var i = 0; i < campo.options.length; i++) {
		if (campo.options[i].checked) {
			return 
		}
	}
		campo.style.border="1px solid #ff0000";
	campo.focus();
	return 1;
}


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 valhora(campo){
	campo.style.backgroundColor="";
	campo.style.borderWidth="";	
	horario = campo.value.split(':')
	if (horario.length == 2) {
	tamanho = horario[0].length
	tamanho2 = horario[1].length
	hora = Number(horario[0])
	minuto = Number(horario[1])
	
		if (tamanho < 2 && tamanho != 0) {
			campo.value = '0' + campo.value
			horario = campo.value.split(':')
			tamanho = horario[0].length
			tamanho2 = horario[1].length
			hora = Number(horario[0])
			minuto = Number(horario[1])
		}

		if (tamanho == 2 && tamanho2 == 2) {
			if (hora >= 0 && hora <= 23 && minuto >= 0 && minuto <= 59){
				return	
			}		
		}
	}
/*	if (horario.length > 1){
		if (Number(horario[0]) >= 0 && Number(horario[0]) <= 23){
			if (Number(horario[1]) >= 0 && Number(horario[1]) <= 59) {
				return; 
			}
		}
	}
}*/
	campo.style.backgroundColor="#ffbbbb";
	campo.style.borderWidth="1";
	campo.focus();
	return 1;	
}

function valdata(campo){
	campo.style.backgroundColor="";
	campo.style.borderWidth="";
	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.backgroundColor="#ffbbbb";
		campo.style.borderWidth="1";
		campo.focus();
		return 1;
	}
	if (strMonth.length<1 || month<1 || month>12){
		campo.style.backgroundColor="#ffbbbb";
		campo.style.borderWidth="1";
		campo.focus();
		return 1;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		campo.style.backgroundColor="#ffbbbb";
		campo.style.borderWidth="1";
		campo.focus();
		return 1;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		campo.style.backgroundColor="#ffbbbb";
		campo.style.borderWidth="1";
		campo.focus();
		return 1;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		campo.style.backgroundColor="#ffbbbb";
		campo.style.borderWidth="1";
		campo.focus();
		return 1;
	}
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
 return true
}

function alternate(id){ 
 if(document.getElementsByTagName){  
   var table = document.getElementById(id);   
   var rows = table.getElementsByTagName("tr");   
   for(i = 0; i < rows.length; i++){           
 //manipulate rows 
     if(i % 2 == 0){ 
       rows[i].className = "fundo_branco"; 
     }else{ 
       rows[i].className = ""; 
     }       
   } 
 } 
}

function subcat(){
	var ajax = createXMLHTTP();
	ajax.open("post", "AjaxSubCat.asp", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.onreadystatechange=function(){
	   if (ajax.readyState==4){	
	   		document.getElementById('ajaxselect').innerHTML = ajax.responseText
	   }
	}
	ajax.send("cod=" + document.getElementById('categoria').value);
}
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);
};
