function toggle_visibility(id) 
{
	var e = document.getElementById(id);
	if(e.style.display == 'none')
		e.style.display = 'block';
	else
		e.style.display = 'none';
}

function ValidaFormLogin1()
{
var Form;

	Form = document.loginForm1;
	if(Form.user_login.value.length < 6)
	{
		alert('O campo Login é obrigatório!');
		Form.user_login.focus();
		return false;
	}
	
	if(Form.user_senha.value.length < 6)
	{
		alert('O campo Senha é obrigatório!');
		Form.user_senha.focus();
		return false;
	}
	
	return true;
}

function ValidaFormLogin2()
{
var Form;

	Form = document.loginForm2;
	if(Form.user_login.value.length < 6)
	{
		alert('O campo Login é obrigatório!');
		Form.user_login.focus();
		return false;
	}
	
	if(Form.user_senha.value.length < 6)
	{
		alert('O campo Senha é obrigatório!');
		Form.user_senha.focus();
		return false;
	}
	
	return true;
}

/* ======================Funções genéricas ======================= */
function is_bisexto(ano)
{
        if ((((ano % 4) == 0) && ((ano % 100) != 0)) || ((ano % 400) == 0))
                return true;
        return;
}

// mes de 1 - 12
function get_month_end(ano, mes)
{
var monthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

        if((mes<1) || (mes > 12))
                return 30;

        if ((mes == 2) && (is_bisexto(ano)))
                return 29;
        else
                return monthDays[mes-1];
}

function is_validDate(dia, mes, ano)
{
var dias;

        dias = get_month_end(ano, mes);

        if((mes < 1) || (mes > 12) || (dia < 1) || (dia > dias)|| (ano < 1800))
                return false;

        return true;
}
function is_validTime(horas, min, seg)
{
	if((horas < 0) || (horas > 23))
		return false;
	if((min < 0) || (min > 59))
		return false;
	if((seg < 0) || (seg > 59))
		return false;
	return true;
}

function FechaJanela()
{
        window.close();
}

function AbrirJanela(url, w, h, x, y)
{
var param='toolbar=no,location=no,directories=no,screenX='+x+',screenY='+y+',status=no,menubar=no,scrollbars=yes,resizable=yes,menubar=no,'+'width='+w+',height='+h;
        window.open(url,'janela',param);
}

function openWindow(url, name, w, h, x, y)
{
var param='toolbar=no,location=no,directories=no,screenX='+x+',screenY='+y+',status=no,menubar=no,scrollbars=yes,resizable=yes,menubar=no,'+'width='+w+',height='+h;
        window.open(url,name,param);
}

function screenWidth()
{
var myWidth = 800;

	if (window.screen) 
		myWidth = screen.availWidth;
	
	return myWidth;
}

function screenHeight()
{
var myHeight = 600;

	if (window.screen) 
		myHeight = screen.availHeight;

	return myHeight; 
}

function isDef(S)
{
	return(eval('typeof('+S+')')!='undefined'&&eval('typeof('+S+')')!='unknown')
}

//function getElm(id){return (is.ie4)?d.all[id]:d.getElementById(id)}

// verifica se o campo é numerico
function checaNumeric(valor)
{
	if(valor.length==0)
		return false;
    if (isNaN(valor))
        return false;
	else
		return true
}

function checaDate(campo)
{
	if(campo.length!=10)return false;
	var date=campo.split('/');
	var dia=date[0]*1;
	var mes=date[1]*1;
	var ano=date[2]*1;
		
	return is_validDate(dia, mes, ano);
}

function checaTime(campo)
{
	if(campo.length!=8)return false;
	var time=campo.split(':');
	var hora=time[0]*1;
	var min=time[1]*1;
	var seg=time[2]*1;
		
	return is_validTime(hora, min, seg);
}

function checaEmail(email)
{
        var a=0;
        var p=0;
        for(var i=1;i<email.length;i++)
		{
                if(!email.charAt(i))return false;
                else
					if(email.charAt(i)=='@')
					{
						a++;
						if(email.charAt(i+1)=='')
							return false;
					}
                else
					if(email.charAt(i)=='.')
					{
						p++;
						if(email.charAt(i+1)==''||email.charAt(i+1)=='@'||email.charAt(i-1)=='@')
							return false;
					}
        }
        if(a==1&&p)
			return true;
}

function checaUrl(url, validparam)
{
	var reg;
	
	if(validparam==false)
		reg = new RegExp("^http(s)?://[_a-z0-9-]+(\.[_a-z0-9-]+)*(.*)$");
	else
		reg = new RegExp("^http(s)?://[_a-z0-9-]+(.*)/(.)+$");
		
	if (reg.test(url))
		return true;
	else
		return false;
}

function checaCpf(cpf)
{
        var s=null;
        var r=null;
        if(cpf.length!=11||
                cpf=='00000000000'||cpf=='11111111111'||cpf=='22222222222'||cpf=='33333333333'||cpf=='44444444444'||
                cpf=='55555555555'||cpf=='66666666666'||cpf=='77777777777'||cpf=='88888888888'||cpf=='99999999999')
			return false;

        s=0;
        for(var i=0;i<9;i++)
			s+=parseInt(cpf.charAt(i))*(10-i);
        r=11-(s%11);
        if(r==10||r==11)
			r=0;
        if(r!=parseInt(cpf.charAt(9)))
			return false;
        s=0;
        for(var i=0;i<10;i++)
			s+=parseInt(cpf.charAt(i))*(11-i);
        r=11-(s%11);
        if(r==10||r==11)
			r=0;
        if(r!=parseInt(cpf.charAt(10)))
			return false;
        return true;
}

// sem pontoação
function validaCPF()
{
	cpf = document.validacao.cpfID.value;
	erro = new String;
	if (cpf.length != 11) 
		erro += "Sao necessarios 11 digitos para verificacao do CPF! ";
	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf))
		erro += "A verificacao de CPF suporta apenas numeros! ";

	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
		erro += "Numero de CPF invalido!"

	var a = [];
	var b = new Number;
	var c = 11;
	for (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]))
		erro +="Digito verificador com problema!";
	if (erro.length > 0)
	{
		alert(erro);
		return false;
	}
	return true;
}
// ex. 03.335.456/0001-45
function validaCNPJ()
{
	CNPJ = document.validacao.CNPJID.value;
	erro = new String;
	if (CNPJ.length < 18) 
		erro += "É necessario preencher corretamente o número do CNPJ!";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
	{
		if (erro.length == 0) 
			erro += "É necessário preencher corretamente o número do CNPJ!";
	}

	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4)
	{
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x;
	}
	else
	{
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ))
		erro += "A verificação de CNPJ suporta apenas números!";
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++)
	{
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2)
		a[12] = 0;
	else
		a[12] = 11-x;
	b = 0;
	for (y=0; y<13; y++)
		b += (a[y] * c[y]);
	if ((x = b % 11) < 2)
		a[13] = 0;
	else
		a[13] = 11-x;
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]))
		erro +="Dígito verificador com problema!";
	if (erro.length > 0)
	{
		alert(erro);
		return false;
	}
	else
		alert("CNPJ valido!");
	return true;
}

function getIndex(input)
{
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
	{
        if (input.form[i] == input)
			index = i;
        else
			i++;
        return index;
    }
    return true;
}

// Script Tab automatico para formularios
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e)
{
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

    if(input.value.length >= len && !containsElement(filter,keyCode))
	{
        input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
}

function containsElement(arr, ele)
{
    var found = false, index = 0;
    while(!found && index < arr.length)
	{
		if(arr[index] == ele)
			found = true;
		else
			index++;
	}

    return found;
}

function toId(S)
{
        S=S.toLowerCase();
        S=S.replace(/[áàãâ]/g,'a');
        S=S.replace(/[éèêë&]/g,'e');
        S=S.replace(/[íìîï]/g,'i');
        S=S.replace(/[óòõôö]/g,'o');
        S=S.replace(/[úùûü]/g,'u');
        S=S.replace(/[ç]/g,'c');
        S=S.replace(/[ \.:,\+\-\*\'\"\\\/<>]/g,'');
        if(S.indexOf('?')!=-1)
			S=S.substring(0,S.indexOf('?'));
        return S;
}

/**
 * Install a search engine (opensearch)
 * Returns false in case of success (sic!) because that will keep the file link
 * from being followed.
 */
function addSearchBarFirefox(url)
{ 	 
	 if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) 
	 { 
		window.sidebar.addSearchEngine(
		url,
		"http://www.realtrading.com.br/images/realtrading.gif",
		"RealTrading",
		"Search Bar");
	 } else {
        alert(error_opensearch_unsupported);
    }
}

function addSearchBarIE(url)
{ 	 
	 if (window.external.AddSearchProvider) 
	 { 
		window.external.AddSearchProvider(url);
	 } else {
        alert(error_opensearch_unsupported);
    }
}

function addOpenSearch(url)
{
  if ((typeof window.external == "object") && ((typeof window.external.AddSearchProvider == "unknown") || (typeof window.external.AddSearchProvider == "function"))) 
  {
    // See bugs 430058/430067/430070 for Camino
    if (((typeof window.external.AddSearchProvider == "unknown") || (window.navigator.vendor == 'Camino'))&& meth == "p") 
    {
      alert("This plugin uses POST which is not currently supported by your browser's implementation of OpenSearch.");
    }
    else 
    {
      window.external.AddSearchProvider(url);
    }
  }
  else
  {
    alert("Você necessita de um browser ao qual suporte OpenSearch para instalar este plugin de busca.");
  }
}

function abrirPlantaoBovespa(id)
{
	var wid=690, hei=500;
	var x=(screenWidth()-wid)/2, y=(screenHeight()-hei)/2;
 
	openWindow('planbovview.php?id='+id, '_blank', wid, hei, x, y);
	return false;
}

function Enviar()
{
        document.form.submit();
}

function openPopup(url,w,h,other)
{
        urlatual = this.location.href;
        if (url.substring(0,5)=="https")
		{
                if (urlatual.substring(0,5)=="http:")
				{
                        urlopener = "https" + urlatual.substring(4,urlatual.length);
                        this.location.href=urlopener;
                }
        }

        url=url.replace(/[ ]/g,'%20');
        popup=window.open(url,'popup_'+toId(url),'left=18,top=18,width='+w+',height='+h+',scrollbars=1'+((other)?','+other:''));
        other=other||'';
        if(is.ie&&other.indexOf('fullscreen')!=-1)
			popup.moveTo(0,0);popup.resizeTo(screen.width,screen.height);
        popup.focus();
}


// url_encode version 1.0 
function url_encode(str) {
    var hex_chars = "0123456789ABCDEF"; 
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/; 
    var n, strCode, hex1, hex2, strEncode = ""; 

    for(n = 0; n < str.length; n++) { 
        if (noEncode.test(str.charAt(n))) { 
            strEncode += str.charAt(n); 
        } else { 
            strCode = str.charCodeAt(n); 
            hex1 = hex_chars.charAt(Math.floor(strCode / 16)); 
            hex2 = hex_chars.charAt(strCode % 16); 
            strEncode += "%" + (hex1 + hex2); 
        } 
    } 
    return strEncode; 
} 

// url_decode version 1.0 
function url_decode(str) { 
    var n, strCode, strDecode = ""; 

    for (n = 0; n < str.length; n++) { 
        if (str.charAt(n) == "%") { 
            strCode = str.charAt(n + 1) + str.charAt(n + 2); 
            strDecode += String.fromCharCode(parseInt(strCode, 16)); 
            n += 2; 
        } else { 
            strDecode += str.charAt(n); 
        } 
    } 
    return strDecode; 
}  

function numEncode(str)
{
	return encodeURI(str);
}

function textEncode(str)
{
		return url_encode(str);
}

function formatMoney(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + num + '.' + cents);
}

function formatNumeric(num, precisao)
{
	var valor = parseFloat(num);
	return valor.toFixed(precisao);
}

/*
 * day_of_week:
 * Calculates the weekday for a given date.
 * Input parameters:
 *     Year (must be >0)
 *     Month (1..12)
 *     Day (1..31)
 * Returns:
 *     0 for Sunday, 1 for Monday, 2 for Tuesday, etc.
 */
function day_of_week(year, month, day)
{
    var a = Math.floor((14 - month) / 12);
    var y = year - a;
    var m = month + 12*a - 2;

    return  (day + y + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) + Math.floor((31*m)/12)) % 7;
}

//window.boxNews.scrollTo(0, 100);