//funções comuns
function DataExtenso() 
{
  var months=new Array(13);
  months[1]="janeiro";
  months[2]="fevereiro";
  months[3]="março";
  months[4]="abril";
  months[5]="maio";
  months[6]="junho";
  months[7]="julho";
  months[8]="agosto";
  months[9]="setembro";
  months[10]="outubro";
  months[11]="novembro";
  months[12]="dezembro";
  var time=new Date();
  var h=time.getHours();
  var mensagem="";
  /*if (h >= 0 && h <= 11) mensagem ="Bom Dia! ";
   else if (h >= 12 && h <= 17) mensagem = "Boa Tarde! ";
   else if (h >= 18 && h <= 23) mensagem = "Boa Noite! ";*/
  var lmonth=months[time.getMonth() + 1];
  var date=time.getDate();
  var year=time.getYear();
  if (year < 2000) year = year + 1900; 
  return(mensagem + date + "  de  " +lmonth + "  de " + year);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//-->

function PopEnvia(urlpage) {
    popup=window.open(urlpage,'popup','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,left=150,top=250,width=280,height=235')
}

function valbusca()
{
  if (document.formbusca.txpesquisa.value == '')
  {
    alert("Atenção - Digite algum texto a ser pesquisado!");
    document.formbusca.txpesquisa.focus();
    return false;
  }
  texto = document.formbusca.txpesquisa.value;
  if (texto.length < 3)
  {
    alert("Atenção - Texto a ser pesquisado tem que ter no mínimo 3 dígitos!");
    document.formbusca.txpesquisa.focus();
    return false;
  }
}

function AfficherImage(img){
  Image1= new Image();
  Image1.src=(img);
  Control(img);
}
function Control(img){
  if((Image1.width!=0)&&(Image1.height!=0)){
    VoirImage(img);
  }
  else{
    fonction="Control('"+img+"')";
    intervalle=setTimeout(fonction,20);
  }
}
function showimg(imagem, largura, altura, titulo)
{
    var D=new Date
    pic=window.open("mostrafoto.php?titulo=" + titulo + "&imagem=" + imagem,D.getTime(),"title=itinga,resizable=no,status=no,scrollbars=no,width=" + largura + ",height=" + altura + ",left=100,top=50");
    pic.focus();
} 
function VoirImage(img){
  largeur=Image1.width;
  hauteur=Image1.height;
  proprietes="width="+ largeur +",height="+ hauteur;
  merda = showimg(img, largeur, hauteur, 'Minas AntiDrogas');
}

/**
*
* Javascript Tooltip
*
* @author Rogerio Alencar Lino Filho
* @url http://rogeriolino.wordpress.com
*
*/
/* Configuração */
var id = "minhaTooltip";
var background = "#000000";
var border = "1px solid #999999";
var display = "none";
var font = "10px Verdana, Arial, Sans-serif";
var color = "#ffffff";
var marginX = 13; //distancia do mouse em x
var marginY = 5; //distancia do mouse em y
var opacity = 75; // 0 a 100
var padding = "2px 5px";
var position = "absolute";
var largura = "100px";
var _x = -10;
var _y = -10;
//
function setPos(event) {
	if (document.all) {//IE
		_x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
		_y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		_x += (window.event.clientX+marginX);
		_y += (window.event.clientY+marginY);
	} else {//Good Browsers
		_x = (event.pageX+marginX);
		_y = (event.pageY+marginY);
	}
}
//
function showTip(text) {
	var t = document.getElementById(id);
	t.style.display = "block";
	document.onmousemove = function(event) {
		setPos(event);
		t.innerHTML = text;
		t.style.left = _x+"px";
		t.style.top = _y+"px";
	}
}
//
function hideTip() {
	var t = document.getElementById(id).style;
	t.display = "none";
}
//
function tooltip() {
	var body = document.getElementsByTagName("body");
	body = body[0];
	body.innerHTML += "<div id='"+id+"'></div>";
	var t = document.getElementById(id).style;
	//t.width = largura;
	t.background = background;
	t.border = border;
	t.display = display;
	t.font = font;
	t.color = color;
	t.opacity = opacity/100;
	t.filter = "alpha(opacity="+opacity+")";
	t.padding = padding;
	t.position = position;
	var links = document.getElementsByTagName("a");
	for (i=0; i<links.length; i++) {
		var title = links[i].getAttribute("title");
		if (title) {
			links[i].setAttribute("tptitle", title);
			links[i].removeAttribute("title");
			//links[i].onmouseover = function() { showTip(this.getAttribute("tptitle")+"<br />"+this.href); }
			links[i].onmouseover = function() { showTip(this.getAttribute("tptitle")); }
		} 
		/*else {
			links[i].onmouseover = function() { showTip(this.href); }
		}*/
		links[i].onmouseout = function() { hideTip(); }
	}
}
//

function mascara_float(valor) {
	var x = valor;
	if (x.match(",")) {
		x = x.replace(",",".");
	}
	x = x.toFixed(2);
	alert(x);
	var res = x.replace(".",",");
	return(res);
}

//-- Máscaras
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function masc_fone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function masc_cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function masc_cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function masc_hora(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1:$2") //Coloca dois pontos entre o segundo e o terceiro dígitos
    return v
}

function masc_data(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1/$2") //Coloca barra entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\/(\d{2})(\d)/,"$1/$2/$3") //Coloca uma barra entre o quarto e o quinto dígitos
    return v
}

function masc_cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function masc_romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function masc_site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

function masc_codigo_amb(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{2})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function valida_data(data) {
	//validar data de nascimento
	erro=0;
	hoje = new Date();
	anoAtual = hoje.getFullYear();
	barras = data.split("/");
  	if (barras.length == 3){
   	dia = barras[0];
     	mes = barras[1];
     	ano = barras[2];
     	resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
     	if (!resultado) 
     	   return false;
	  	else if ((mes==2) && ((dia>29) || (((ano%4 != 0) && (ano%100 != 0) && (ano%400 != 0)) && (dia == 29))))
			return false;
		else if (((mes==4) && (mes==6) && (mes==9) && (mes==11)) && (dia == 31))
			return false;
		else
		  	return true;
  	} 
  	else 
  	   return false;
}

function valida_email(email) {
  //Verifical e-mail
  if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) { 
     return false;
  } 
  else {
	  return true;
  }
}

//-- Máscaras de valores financeiros
//-- <input type="text" onkeypress="reais(this,event)" onkeydown="backspace(this,event)">
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
   var t = this; if(c == undefined) c = 2;		
   var p, d = (t=t.split("."))[1].substr(0, c);
   for(p = (t=t[0]).length; (p-=3) >= 1;) {
	 	t = t.substr(0,p) + "." + t.substr(p);
   }
   return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
	/*
	* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
	* casas decimais
	*/
	var val2 = '';
	var strCheck = '0123456789';
	var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if (val2.length==0) return "0.00";
		if (val2.length==1) return "0.0" + val2;
		if (val2.length==2) return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
		/* currency é false: retornamos os valores COM os zeros à esquerda, 
		* sem considerar os últimos 2 algarismos como casas decimais 
		*/
		val3 ="";
		for(var k=0; k < len; k++){
			if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
		}			
		return val3;
	}
}

function reais(obj,event){
	var whichCode = (window.Event) ? event.which : event.keyCode;
	/*
	Executa a formatação após o backspace nos navegadores !document.all
	*/
	if (whichCode == 8 && !documentall) {	
		/*
		Previne a ação padrão nos navegadores
		*/
		if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
		}
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		obj.value= demaskvalue(x,true).formatCurrency();
		return false;
	}
	/*
	Executa o Formata Reais e faz o format currency novamente após o backspace
	*/
	FormataReais(obj,'.',',',event);
} // end reais

function backspace(obj,event){
	/*
	Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
	O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
	Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
	*/

	var whichCode = (window.Event) ? event.which : event.keyCode;
	if (whichCode == 8 && documentall) {	
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		var y = demaskvalue(x,true).formatCurrency();

		obj.value =""; //necessário para o opera
		obj.value += y;
	
		if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
		}
		return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
	if (whichCode == 0 ) return true;
	if (whichCode == 9 ) return true; //tecla tab
	if (whichCode == 13) return true; //tecla enter
	if (whichCode == 16) return true; //shift internet explorer
	if (whichCode == 17) return true; //control no internet explorer
	if (whichCode == 27 ) return true; //tecla esc
	if (whichCode == 34 ) return true; //tecla end
	if (whichCode == 35 ) return true;//tecla end
	if (whichCode == 36 ) return true; //tecla home
	
	/*
	O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
	*/

	if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
	}

	var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

	/*
	Concatenamos ao value o keycode de key, se esse for um número
	*/
	fld.value += key;

	var len = fld.value.length;
	var bodeaux = demaskvalue(fld.value,true).formatCurrency();
	fld.value=bodeaux;

	/*
	Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
	*/
	if (fld.createTextRange) {
   	var range = fld.createTextRange();
		range.collapse(false);
		range.select();
	}
	else if (fld.setSelectionRange) {
   	fld.focus();
		var length = fld.value.length;
		fld.setSelectionRange(length, length);
	}
  	return false;
}

/* remover item da lista */
function remove_options(selectbox) {
	var i;
	for(i=selectbox.options.length-1;i>=0;i--) {
		if(selectbox.options[i].selected) selectbox.remove(i);
	}
}

/* mover de um select(combobox) para outro */
function move_de_lista_pra_lista(MenuOrigem, MenuDestino){
    var arrMenuOrigem = new Array();
    var arrMenuDestino = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < MenuDestino.options.length; i++){
        arrLookup[MenuDestino.options[i].text] = MenuDestino.options[i].value;
        arrMenuDestino[i] = MenuDestino.options[i].text;
    }
    var fLength = 0;
    var tLength = arrMenuDestino.length;
    for(i = 0; i < MenuOrigem.options.length; i++){
        arrLookup[MenuOrigem.options[i].text] = MenuOrigem.options[i].value;
        if (MenuOrigem.options[i].selected && MenuOrigem.options[i].value != ""){
            arrMenuDestino[tLength] = MenuOrigem.options[i].text;
            tLength++;
        }
        else{
            arrMenuOrigem[fLength] = MenuOrigem.options[i].text;
            fLength++;
        }
    }
    arrMenuOrigem.sort();
    arrMenuDestino.sort();
    MenuOrigem.length = 0;
    MenuDestino.length = 0;
    var c;
    for(c = 0; c < arrMenuOrigem.length; c++){
        var no = new Option();
        no.value = arrLookup[arrMenuOrigem[c]];
        no.text = arrMenuOrigem[c];
        MenuOrigem[c] = no;
    }
    for(c = 0; c < arrMenuDestino.length; c++){
        var no = new Option();
        no.value = arrLookup[arrMenuDestino[c]];
        no.text = arrMenuDestino[c];
        MenuDestino[c] = no;
   }
}
