/*
*	 Título: Uso comum
*	Criação: 05/06/2008
*	  Autor: Jean Pierri Braga
*	 E-mail: webmaster@biosweb.net
*/

//Prototypes ---------------------------------------------------------------------------------------
String.prototype.trim = function() {
	var r = this;
	var er = /^\s|\s$/;
	while (er.test(r)) r = r.replace(/^\s|\s$/g,"");
	return r;
}
//---------------------------------//---------------------------------
//Verifica se valor existe no Array
Array.prototype.isValueExist = function(v) {
	var b = false;
	for (var i=0;i<this.length;i++) {
		if (this[i].toUpperCase()==v.toUpperCase()) b = true;
	}	
	return b;
}
//------------------------------------------------//------------------------------------------------
//------------------------------------------------//------------------------------------------------

//Diversos -----------------------------------------------------------------------------------------

//Retorna tipo e versão de navegadores
function getNav() {
    var nv = navigator.userAgent;
    var vs = navigator.appVersion;
    var q = "IE";
    if (nv.indexOf("Opera")>-1) q = "OPERA";
    if (nv.indexOf("Firefox")>-1) q = "FIREFOX";
    if (nv.indexOf("Netscape")>-1) q = "NETSCAPE";
    if (nv.indexOf("Mozilla")>-1 && nv.indexOf("Netscape")==-1 && nv.indexOf("MSIE")==-1) q = "MOZILLA";
    
    if (q=="IE") {
        var avs = vs.split(";");
        vs = parseFloat(avs[1].substring(5));
    }
    
    var r = { n: q, v: vs };
    
    return r;
}
var NV = getNav();
//---------------------------------//---------------------------------
//Retorna posições absolutas reais do elemento
function getAbsolutePos(el) {
    var SL = el.scrollLeft;
    var ST = el.scrollTop;
    var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
    if (el.offsetParent) { //Passa por cada elemento parent até chegar no último, o que será usado como parametro de posição
        var tmp = this.getAbsolutePos(el.offsetParent);
        r.x += tmp.x; //Left
        r.y += tmp.y; //Top
    }
    return r;
}
//---------------------------------//---------------------------------
//Verifica se "d" é uma data válida
function isDate(d) { 
    //Separa valores
    var dd = d.substring(0,d.indexOf("/"));	
    var mm = d.substring(d.indexOf("/")+1,d.lastIndexOf("/"));
    var aa = d.substring(d.lastIndexOf("/")+1,10);
    //alert(dd + " - " + mm + " - " + aa);

    //Inverter data para valor inglês, e cria data
    var dt = new Date(mm+"/"+dd+"/"+aa);
    var ddd = dt.getDate();
    var mmm = (dt.getMonth()+1);
    var aaa = dt.getFullYear();            
    //alert(ddd + " - " + mmm + " - " + aaa);

    return ( (dd==ddd & mm==mmm & aa==aaa) & parseInt(aa) > 1900 ) ? true : false;
}
//---------------------------------//---------------------------------
//verifica se valor existe no el (Array), se não existir adiciona-o
function setAddArray(el,v) {
    var i=0;
    for (i=0;i<el.length;i++) {
        if (el[i].toUpperCase()==v.toUpperCase()) break;
    }
    if (i==el.length || el.length==0) el.push(v);
}
//---------------------------------//---------------------------------
function addOptions(cp,valor,texto) {	
    var oOption = document.createElement("Option");
    oOption.value = valor;
    oOption.text = texto;
    try { cp.add(oOption, null); } // NS/FF
    catch(e) { cp.add(oOption); } // IE
    return oOption;
}
//---------------------------------//---------------------------------
function removeOptions(el) {
    var idx = null;
    try { 
        idx = el.selectedIndex;
        el.options.length = 0;
    } catch(e) {  }
    return idx;
}
//---------------------------------//---------------------------------
function clearInputs(f) {	
	var e = null;
    for (var a = 0; a < f.elements.length; a++) {
		e = f.elements[a];
        if (e.selectedIndex) e.options[0].selected = true;
        if (e.type.indexOf("checkbox")>-1) {
			if (e.value.toUpperCase()=="N" || e.value.toUpperCase()=="S") e.value="N";
			e.checked = false;
		}
        if (e.type.indexOf("text")>-1 || e.type.indexOf("password")>-1 || e.type.indexOf("textarea")>-1) e.value = "";
    }
}
//---------------------------------//---------------------------------
//Retorna somente numeros
function getOnlyNumber(e) {
	e.value = e.value.replace(/\D/g,"");
}
//---------------------------------//---------------------------------
//Usado para eventos keyup, acionando função apenas em N segundos
var KEYUPTIME = null;
function setKeyUpTime(func,tmp) {
    clearTimeout(KEYUPTIME);
    KEYUPTIME = setTimeout(func,tmp);
}
//---------------------------------//---------------------------------
//Marca e desmarca campo Radio
function setRadioChecked(rd) {
	rd.checked = rd.checked ? false : true;
}
//---------------------------------//---------------------------------
//Comverte caracter ascii 13 (quebra de linha - "Enter") para cod-caracter "{13}"
function getChar13(s) {
	var ql = String.fromCharCode(13);
	if (s.indexOf(ql)>-1) {
		while (s.indexOf(ql)>-1) {
			s = s.replace(ql,"{13}");      
			s = s.replace(String.fromCharCode(9),"");  
			s = s.replace(String.fromCharCode(10),""); 
		}
	}
	return s;
}
//---------------------------------//---------------------------------
function goFormPost(url,tgt) {    
    var qs = "";    
    var f = document.createElement("form");
    f.action = (url.indexOf("?")>-1) ? url.substring( 0, url.indexOf("?") ) : url;
    f.method = "post";
    f.target = tgt;
    
    //Criar campos hidden 
    var qs = url.substring( url.indexOf("?")+1 ).split("&");
    var ch = new Array();
    for (var i=0;i<qs.length;i++) {
        ch[i] = document.createElement("input");
        ch[i].type = "hidden";
        ch[i].name = qs[i].substring( 0, qs[i].indexOf("=") );
        ch[i].value = qs[i].substring( qs[i].indexOf("=")+1 );
        f.appendChild(ch[i]);        
    }    
    f = document.body.appendChild(f);
    f.submit();    
}
//---------------------------------//---------------------------------
//Execute função caso seja precionado algumas das teclas de code: aCC
function getKeyCode(evt,funcao,aCC) {
    var s="",fnc=null;
    var f = (NV.n=="IE") ? evt.srcElement : evt.target; //alert('Elm: ' + f.tagName);
    var c = evt.keyCode;
    for (var i=0;i<aCC.length;i++) {
        if (c==parseInt(aCC[i]) & f.tagName!="TEXTAREA") fnc = eval(funcao);
    }
    return false;
}
//---------------------------------//---------------------------------
//Troca caracter usado para marcar quebra de linha por uma quebra de linha 
 function getQuebrasLinha(s,c) {
    if (s.indexOf(c)>-1) {
        while (s.indexOf(c)>-1) {
            s = s.replace(c,String.fromCharCode(13));        
        }
    }
    return s;
 }
//---------------------------------//---------------------------------
function maxLength(cp,mx) {
	var v = cp.value;
	if (v.length>mx) cp.value = v.substring(0,mx);
}
//---------------------------------//---------------------------------
//Formata value do campo para valor decimal
function setValueDecimal(f,vMax) {
	var mx = vMax;
	var dc = mx.indexOf(".")>-1 ? mx.substring(mx.indexOf(".")+1).length : 0; 
	maxChar = mx.replace(/\D/g,"").length;
	formatDecimal(f,dc);
	var v = f.value.trim().replace(",",".");;
	v = parseFloat(v)>parseFloat(vMax) ? mx : v;
	v = v.replace(".",",");
    f.value = v.substring(0, v.indexOf(",")==-1?maxChar:maxChar+1 );		
}
//---------------------------------//---------------------------------
//Evitar que conteudo seja selecionado
function notSeletionDocument(evt,f) { 
	var e = (NV.n=="IE") ? event.srcElement : evt.target; 
	var t = e.tagName.toLowerCase();
	try {
		if (f==true && t!="input" && t!="textarea") {
			if (NV.n=="IE") {
				document.selection.empty(); 
			} else {
				var selection = window.getSelection(); 
				selection.removeAllRanges();
			}
		}
	} catch(e) {};
}
//---------------------------------//---------------------------------
//Configura evento chamador da função para elemento com id
function setEvent(evt,id,func) {
	var r = eval( "document.getElementById('" + id + "')" );
	r = r!=null ? eval( "document.getElementById('" + id + "').on" + evt + " = function() { " + func + " }" ) : null;
	return r;
}
//---------------------------------//---------------------------------
//Verifica se email é válido (de acordo com formato str)
function isEmail(str_email) {
		// Caracteres inválidos para o campo e-mail
		var invalidos = "\/:,;|=+*#%!§¬¹²³£¢><°ºª"			
		var ok = true;
		
		// Verifica a existência de caracteres inválidos no email_contato digitado
		for (i=0; i < invalidos.length; i++) {
			x = invalidos.charAt ( i )
			if (str_email.indexOf ( x , 0 ) > -1 ) {
				    ok = false;
			}
		}
		
		// Confere a existência do arroba "@" no email_contato digitado, se existe mais de um "@"
		// e se existe um "." com pelo menos dois caracteres após (Ex.: '.com' ou '.br')
		arroba = str_email.indexOf ( "@" , 1 )
		ponto = str_email.indexOf ( "." , arroba )
		
		if ( arroba == -1 || str_email.indexOf ( "@" , arroba+1 ) != -1 || ponto == -1 || ponto+3 > str_email.length ) {
			ok = false;
		}
		return ok;
}
//---------------------------------//---------------------------------
function setRollOver(evt,prefx,cssOver,cssDown) {
    var e = (NV.n=="IE") ? evt.srcElement : evt.target;
	try{ //ERRO DESCONHECIDO CAUSADO POR CAMPO DE FORM COM NOME DE ID!
		if (e.id!=null && e.id.indexOf(prefx)>-1 && e.onmouseover == null && !e.disabled) { //alert(prefx);
			var cssOut = e.className;
			e.className = cssOver;
			e.onmouseover = function() { this.className = cssOver };
			e.onmouseout = function() { this.className = cssOut };
			if (cssDown!=null) e.onmousedown = function() { this.className = cssDown };
			e.onmouseup = function() { this.className = cssOver };
		}
	} catch(e) {};
}
//---------------------------------//---------------------------------
//função retorna altura do conteudo "ct" em px
function getWHContent(s) {
	var g = document.createElement("span");
	with(g.style) {	visible = "hidden";	position = "absolute"; top = "0px"; left = "0px"; }
	document.body.appendChild(g);
	g.innerHTML = s;
	var r = { width: parseInt(g.offsetWidth), height: parseInt(g.offsetHeight) };
	document.body.removeChild(g);
	return r;
}
//---------------------------------//---------------------------------
//IEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIE
//Executa transparencia de arquivos PNG no IE
function validaAlphaPNG() {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);    
    if ((version >= 5.5) && (document.body.filters)) {
        for(var i=0; i<document.images.length; i++) {
            var img = document.images[i];
            var imgName = img.src.toUpperCase();
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : "";
                var imgClass = (img.className) ? "class='" + img.className + "' " : "";
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
                var imgStyle = "display:inline-block;" + img.style.cssText ;
                if (img.align == "left") imgStyle = "float:left;" + imgStyle;
                if (img.align == "right") imgStyle = "float:right;" + imgStyle;
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
                var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
                img.outerHTML = strNewHTML;
                i-=1;
            }
        }
    }
}
setEvents("window.onload","validaAlphaPNG()",true);
//IEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIEIE
