
/************************************************************************************
* FUNÇÂO: Mascarar os campos dos formulários de cadastro permitindo somente números *
* AUTOR: Ricardo Balk                                                               *
************************************************************************************/
//função que dado um formato, mascara o campo unput do form
function somenteNumeros(evtKeyPress) {
	var retorno = false
	var nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode; 
	if (((nTecla > 47) && (nTecla < 58)) || (nTecla == 37) || (nTecla == 39) || (nTecla == 46) || (nTecla == 188) || (nTecla == 190) || (nTecla == 116) || (nTecla == 8) || (nTecla == 17) || (nTecla == 16) || ((nTecla > 95) && (nTecla < 106)))
		retorno = true;  // números de 0 a 9, ponto ou virgula
	if (retorno) {
		return true;	
	} else {
		evtKeyPress.returnValue  = false;
        evtKeyPress.cancelBubble = true;
        if(document.all) {
            evtKeyPress.keyCode = 0;
        } else {
            evtKeyPress.preventDefault();
            evtKeyPress.stopPropagation();
        }		
		return false;
	}
}
//função que formata o campo de telefone tanto(99)999-9999 quanto (99)9999-9999   



//Use a função  displayDatePicker('Objeto que vai receber a data');
/*
Exemplo:
<input name="ADate" OnKeyUp="mascara_data('data1');" id='data1'> 
<input type=button value="select" onclick="displayDatePicker('ADate');">

Para o uso de estilos:
Classes do Data:
Tabela = Classe do objeto tabela em geral
CabecalhoTabela = Cabecalho da tabela
Input = Botões
a3 = Dias Normais
a2 = Dias Selecionados
*/


var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sa');
var dayArrayMed = new Array('Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab');
var dayArrayLong = new Array('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabado');
var monthArrayShort = new Array('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez');
var monthArrayMed = new Array('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez');
var monthArrayLong = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
  
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";		// common values would be "/" or "."
var defaultDateFormat = "dmy"	// valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate"> 
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the 
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayBelowThisObject,dpPosition, dtFormat, dtSep)
{
  var targetDateField = document.getElementsByName(dateFieldName).item(0);
  var defaultposition = 'right';
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
  
  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;
  
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
  if( dpPosition )
     position = dpPosition;
  else
     position = defaultposition;
  if( position == 'right')
     var x = displayBelowThisObject.offsetLeft;
  else
    var x = displayBelowThisObject.offsetLeft - 150;

  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight;
  
  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop;
  }
  
  drawDatePicker(targetDateField, x, y);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y)
{
  var dt = getFieldDate(targetDateField.value);
  
  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
  if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
    var newNode = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }
  
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.zIndex = 10000;
  
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();
  
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
  
  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table class='tabela_calendario' cols=7 Cellspacing='0' width='210'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr Align='Center' Class='calendario_linha'>";
  var TR_title = "<tr Align='Center'>";
  var TR_days = "<tr Align='Center' Class='calendario_linha'>";
  var TR_todaybutton = "<tr Align='Center' Class='calendario_linha'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td  Class='l2'";	// leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5>";
  var TD_buttons = "<td>";
  var TD_todaybutton = "<td colspan=7>";
  var TD_days = "<td >";
  var TD_selected = "<td Class='calendario_selecionado' ";	// leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div>";
  var DIV_selected = "<div>";
  var xDIV = "</div>";
  
  // start generating the code for the calendar table
  var html = TABLE;
  
  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;
  
  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayMed.length; i++)
    html += TD_days + dayArrayMed[i] + xTD;
  html += xTR;
  
  // now we'll start populating the table with days of the month
  html += TR;
  
  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;
  
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
    
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;
    
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)
  
  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;
  
  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='calendario_botao_interno' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>Mês Atual</button> ";
  html += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  html += "<button class='calendario_botao_interno' onClick='updateDateField(\"" + dateFieldName + "\");'>Fechar</button>";
  html += xTD + xTR;
  
  // and finally, close the table
  html += xTABLE;
  
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth() + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }
  
  return "<button class='calendario_botao_interno' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**

Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
  
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
  
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else {
      dateVal = new Date(dateString);
    }
  } catch(e) {
    dateVal = new Date();
  }
  
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
  
  return dArray;
}

function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName(dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;
	targetDateField.focus();
  document.getElementById(datePickerDivID).style.visibility = "hidden";
  adjustiFrame();
  
  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  if (!document.getElementById(iFrameDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
    var newNode = document.createElement("iFrame");
    newNode.setAttribute("id", iFrameDivID);
    newNode.setAttribute("src", "javascript:false;");
    newNode.setAttribute("scrolling", "no");
    newNode.setAttribute("frameborder", "0");
    document.body.appendChild(newNode);
  }
  
  if (!pickerDiv)
    pickerDiv = document.getElementById(datePickerDivID);
  if (!iFrameDiv)
    iFrameDiv = document.getElementById(iFrameDivID);
  
  try {
    iFrameDiv.style.position = "absolute";
    iFrameDiv.style.width = pickerDiv.offsetWidth;
    iFrameDiv.style.height = pickerDiv.offsetHeight;
    iFrameDiv.style.top = pickerDiv.style.top;
    iFrameDiv.style.left = pickerDiv.style.left;
    iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
    iFrameDiv.style.visibility = pickerDiv.style.visibility;
  } catch(e) {
  }
}


/*************************************************************************
* FUNÇÂO: Mascarar os campos dos formulários de cadastro                 *
* AUTOR: Ricardo Balk                                                    *
* DATA: 26/11/2003                                                       *
* OBS: Usar no evento onkeypress do input                                *
* Ex1:<input type=text id="cpf" name="cpf" ob="1" desc="O CPF" tipo="cpf"*
*     size="20" maxlength="14" onkeypress="return                        *
*     txtBoxFormat(document.testcad, 'cpf', '999.999.999-99', event);">  *
* EX2:<input type="text" id="fone" name="fone" ob="0" desc=""            *
*     tipo="fone" size="20" maxlength="14"                               *
*     onkeypress="return(TelefoneFormat(this,event));">                  *
*************************************************************************/

//função que dado um formato, mascara o campo unput do form
function txtBoxFormat(strField, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
	nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode; 

	sValue = strField.value;
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;
	
	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;
	
	while (i <= mskLen) {
		bolMask = ((sMask.charAt(i) == ":") || (sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
		if (bolMask) {
			sCod += sMask.charAt(i);
			mskLen++; 
		} else {
			sCod += sValue.charAt(nCount);
			nCount++;
		}
		i++;
	}
	strField.value = sCod;
	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas números...
			return ((nTecla > 47) && (nTecla < 58));  // números de 0 a 9
		} else { // qualquer caracter...
			return true;
		} 
	} else {
		return true;
	}
}
//função que formata o campo de telefone tanto(99)999-9999 quanto (99)9999-9999   


function lib_bwcheck(){ //Browsercheck (needed)
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=this.agent.indexOf("Opera 5")>-1
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
var bw_cursor = new lib_bwcheck()
	
//VERIFICA O NÍVEL DE SEGURANÇA DE UMA SENHA
function verifica_senha(txt, alvo) {
	var numeros = '0123456789';
	var letras = 'abcdefghijklmnoprstuvwxz';
	var maiusculas = 'ABCDEFGHIJKLMNOPQRSTUVWXZ';
	var especiais = '!@#$%&*(){[}]?:><áéíóúàèòùãõÁÉÍÓÚÀÈÌÒÙÃÕ';
	var nota = 0;
	var ver_numeros = false;
	var ver_letras = false;
	var ver_maiusculas = false;
	var ver_especiais = false;
	var x;

	for (x=0;x<txt.length;x++) {
		if (numeros.indexOf(txt[x]) >= 0 && ver_numeros == false){ 
			nota++;
			ver_numeros = true;
		}
		if (letras.indexOf(txt[x]) >= 0 && ver_letras == false){ 
			nota++;
			ver_letras = true;
		}
		if (maiusculas.indexOf(txt[x]) >= 0 && ver_maiusculas == false){ 
			nota++;
			ver_maiusculas = true;
		}
		if (especiais.indexOf(txt[x]) >= 0 && ver_especiais == false){ 
			nota++;
			ver_especiais = true;
		}
	}
	if (txt.lenght >= 6) nota++;

	if (nota == 0) 
		document.getElementById(alvo).innerHTML = '<font color="#CC0000"><b>Nível da Senha: Muito Fraca</b></font>';
	else if (nota == 1)  
		document.getElementById(alvo).innerHTML = '<font color="#FF9900"><b>Nível da Senha: Fraca</b></font>';
	else if (nota == 2)
		document.getElementById(alvo).innerHTML = '<font color="#CCCC00"><b>Nível da Senha: Regular</b></font>';
	else if (nota == 3)
		document.getElementById(alvo).innerHTML = '<font color="#0000CC"><b>Nível da Senha: Boa</b></font>';
	else if (nota >= 4)
		document.getElementById(alvo).innerHTML = '<font color="#00AA00"><b>Nível da Senha: Muito Boa</b></font>';
	
}

function verifica_senha2(senha1, senha2, alvo) {
	var s1 = document.getElementById(senha1).value;
	var s2 = document.getElementById(senha2).value;
	if (s1 == '' && s2 == '') {
		document.getElementById(alvo).innerHTML = '';
	} else if (s1 == s2) {
		document.getElementById(alvo).innerHTML = '<font color="#00AA00"><b>Senhas Iguais</b></font>';
	} else {
		document.getElementById(alvo).innerHTML = '<font color="#AA0000"><b>Senhas Diferentes</b></font>';
	}
}


function abrirpopupcentralizado(vUrl,vName,vPosFimX,vPosFimY,vScrollBars,vResizable,vRetorno)
{
  //calcula posição de abertura da janela em relação à tela
  vPosIniX=((screen.availWidth/2)-(vPosFimX/2));
  vPosIniY=((screen.availHeight/2)-(vPosFimY/2));
  //abre a janela pop up
  window.open(vUrl,vName,'toolbar=0,location=0,directories=0,menubar=0,scrollbars='+vScrollBars+',resizable='+vResizable+',top='+vPosIniY+',left='+vPosIniX+',width='+vPosFimX+',height='+vPosFimY+'');
  if (vRetorno==null)
  {
    //não retorna nada
  }
  else
  {
    //retorna qualquer coisa que você definir em vRetorno 
    //obs.: aplicavel ao caso de querer retornar uma outra função ou o valor de outra função
    return vRetorno;
  };
};

function abrir_popup(url, onde, extras){
	window.open(url,onde,extras);
}

function mostra_cursor(event, imagem, largura, altura) {
	var scrolled=bw_cursor.ns4||bw_cursor.ns6?"window.pageYOffset":"document.body.scrollTop";
	var largura_max = window.innerWidth ? window.innerWidth : document.body.offsetWidth ;
	var altura_max = window.innerHeight ? window.innerHeight: document.body.offsetHeight;
	var modificador = event.clientX < 200 ? -2 : 160;
	xpos=event.clientX;
	ypos=Math.min(altura_max-165, event.clientY);
	document.getElementById("formulario_iframe_movel").style.visibility="visible";
	document.getElementById("formulario_iframe_movel").style.position="absolute";
	document.getElementById("formulario_iframe_movel").style.left=xpos-modificador +'px';
	document.getElementById("formulario_iframe_movel").style.top=parseInt(ypos)+parseInt(2)+eval(scrolled) +'px';
	document.getElementById("formulario_imagem_iframe_movel").src = imagem;
	document.getElementById("formulario_imagem_iframe_movel").width = largura;
	document.getElementById("formulario_imagem_iframe_movel").height = altura;
}
function esconde_cursor() {
	document.getElementById("formulario_iframe_movel").style.visibility="hidden";
}


/************************************************************************************************
TOOLTIPS INICIO
javascript for Bubble Tooltips by Alessandro Fulciniti
- http://pro.html.it - http://web-graphics.com 
************************************************************************************************/
function Tooltipos_enableTooltips(){
	var links,i,h;
	if(!document.getElementById || !document.getElementsByTagName) return;
	links=document.getElementsByTagName("a");
	for(i=0;i<links.length;i++){
		if (links[i].getAttribute("rel") == "show_tip")
		    Tooltips_Prepare(links[i]);
    }
}
function Tooltips_Prepare(el){
	var tooltip,t,b,s,l;
	t=el.getAttribute("title");
	if(t==null || t.length==0) {
		return;
		t="link:";
	}
	el.removeAttribute("title");
	tooltip=Tooltips_CreateEl("span","tooltip");
	s=Tooltips_CreateEl("span","top");
	s.appendChild(document.createTextNode(t));
	tooltip.appendChild(s);
	b=Tooltips_CreateEl("b","bottom");
	l='';
	b.appendChild(document.createTextNode(l));
	tooltip.appendChild(b);
	Tooltips_setOpacity(tooltip);
	el.tooltip=tooltip;
	el.onmouseover=Tooltips_showTooltip;
	el.onmouseout=Tooltips_hideTooltip;
	el.onmousemove=Tooltips_Locate;
}

function Tooltips_showTooltip(e){
	document.getElementById("btc").appendChild(this.tooltip);
	Tooltips_Locate(e);
}

function Tooltips_hideTooltip(e){
	var d=document.getElementById("btc");
	if(d.childNodes.length>0) d.removeChild(d.firstChild);
}

function Tooltips_setOpacity(el){
	el.style.filter="alpha(opacity:80)";
	el.style.KHTMLOpacity="0.80";
	el.style.MozOpacity="0.80";
	el.style.opacity="0.80";
}

function Tooltips_CreateEl(t,c){
	var x=document.createElement(t);
	x.className=c;
	x.style.display="block";
	return(x);
}

function Tooltips_Locate(e){
	var posx=0,posy=0;
	if(e==null) e=window.event;
	if(e.pageX || e.pageY){
		posx=e.pageX; posy=e.pageY;
	} else if(e.clientX || e.clientY){
		if(document.documentElement.scrollTop){
			posx=e.clientX+document.documentElement.scrollLeft;
			posy=e.clientY+document.documentElement.scrollTop;
		} else {
			posx=e.clientX+document.body.scrollLeft;
			posy=e.clientY+document.body.scrollTop;
		}
	}
	var largura_max = window.innerWidth ? window.innerWidth : document.body.offsetWidth ;
	var altura_max = window.innerHeight ? window.innerHeight: document.body.offsetHeight;
	if (parseInt(posx)+185 > largura_max) {
		posx = largura_max - 185;
	}
	if (parseInt(posy)+80 > altura_max) {
		posy = posy - 80;
	 }
	document.getElementById("btc").style.top=(posy+10)+"px";
	document.getElementById("btc").style.left=(posx-20)+"px";
}
/************************************************************************************************
	TOOLTIPS FIM
************************************************************************************************/




//***********************************************************************************************
// LIGHTBOX 
//***********************************************************************************************

// CONFIGURAÇÃO
var loadingImage = 'loading.gif';		
var lightboxcloseButton = 'close.gif';		
var lighbox_pagesize = lightbox_getPageSize();
var iframe_largura = lighbox_pagesize[0] - 200;
var iframe_altura = lighbox_pagesize[1] - 180;
//
// lightbox_getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function lightbox_getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
// lightbox_getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function lightbox_getPageSize(){
	
	var xScroll = 0, yScroll = 0;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		//xScroll = document.body.scrollWidth;
		//yScroll = document.body.scrollHeight;
		xScroll = 0;
		yScroll = 0;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// lightbox_pause(numberMillis)
// lightbox_pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//

function lightbox_pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// lightbox_getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function lightbox_getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ lightbox_hideLightbox(); }
}


//
// listenKey()
//
function listenKey () {	document.onkeypress = lightbox_getKey; }

//
// lightbox_showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function lightbox_showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objIframe = document.getElementById('lightboxIframe');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');
	var arrayPageSize = lightbox_getPageSize();
	var arrayPageScroll = lightbox_getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	objIframe.src = objLink.href;
	var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - iframe_altura) / 2);
	var lightboxLeft = ((arrayPageSize[0] - 20 - iframe_largura) / 2);
	objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";

	objLightboxDetails.style.width = iframe_largura + 'px';
	
	if(objLink.getAttribute('title')){
		objCaption.style.display = 'block';
		objCaption.innerHTML = objLink.getAttribute('title');
	} else {
		objCaption.style.display = 'none';
	}
	
	// A small lightbox_pause between the image loading and displaying is required with IE,
	// this prevents the previous image displaying for a short burst causing flicker.
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		lightbox_pause(250);
	} 

	if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }



	// Hide select boxes as they will 'peek' through the image in IE
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "hidden";
	}


	objLightbox.style.display = 'block';

	// After image is loaded, update the overlay height as the new image might have
	// increased the overall page height.
	arrayPageSize = lightbox_getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
}

function lightbox_showLighImage(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImagem = document.getElementById('lightboxImagem');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');
	var arrayPageSize = lightbox_getPageSize();
	var arrayPageScroll = lightbox_getPageScroll();
	document.getElementById('lightboxIframe').style.display = 'none';

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	objImagem.src = objLink.href;
	var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - iframe_altura) / 2);
	var lightboxLeft = ((arrayPageSize[0] - 20 - iframe_largura) / 2);
	objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";

	objLightboxDetails.style.width = objImagem.width + 'px';
	
	if(objLink.getAttribute('title')){
		objCaption.style.display = 'block';
		objCaption.innerHTML = objLink.getAttribute('title');
	} else {
		objCaption.style.display = 'none';
	}
	
	// A small lightbox_pause between the image loading and displaying is required with IE,
	// this prevents the previous image displaying for a short burst causing flicker.
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		lightbox_pause(250);
	} 

	if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }



	// Hide select boxes as they will 'peek' through the image in IE
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "hidden";
	}


	objLightbox.style.display = 'block';

	// After image is loaded, update the overlay height as the new image might have
	// increased the overall page height.
	arrayPageSize = lightbox_getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
}

//
// lightbox_hideLightbox()
//
function lightbox_hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}

	document.getElementById('lightboxIframe').src = '';;
	document.getElementById('lightboxImagem').src = '';;

	// disable keypress listener
	document.onkeypress = '';
}

//
// lightbox_initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//

function lightbox_initLightbox() {
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {
				lightbox_showLightbox(this); return false;
			}
		}
		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "light_image")){
			anchor.onclick = function () {
				lightbox_showLighImage(this); return false;
			}
		}

		
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//		<a href="#" onclick="lightbox_hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	//		<a href="#" onclick="lightbox_hideLightbox(); return false;" title="Click anywhere to close image">
	//			<img id="lightboxcloseButton" />		
	//			<iframe id="lightboxIframe" />
	//		</a>
	//		<div id="lightboxDetails">
	//			<div id="lightboxCaption"></div>
	//		</div>
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = lightbox_getPageSize();
	var arrayPageScroll = lightbox_getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {lightbox_hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);

	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);


	// cria botão de fechar
	var objLink = document.createElement("input");
	objLink.setAttribute('id','lightboxClose');
	objLink.setAttribute('type','button');
	objLink.setAttribute('title','Fechar');
	objLink.onclick = function () {lightbox_hideLightbox(); return false;}
	objLightboxDetails.appendChild(objLink);

	// criar o iframe
	var objIframe = document.createElement("iframe");
	objIframe.setAttribute('id','lightboxIframe');
	objIframe.setAttribute('width',iframe_largura);
	objIframe.setAttribute('height','600');
	objLightboxDetails.appendChild(objIframe);
	
	//criar imagem
	var objImagem = document.createElement("img");
	objImagem.setAttribute('id','lightboxImagem');
	objImagem.setAttribute('align', 'middle');
	objLightboxDetails.appendChild(objImagem);
	
}

//
// lightbox_addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function lightbox_addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
			oldonload();
			func();
		}
	}

}

lightbox_addLoadEvent(lightbox_initLightbox);	// run lightbox_initLightbox onLoad

//***********************************************************************************************
// LIGHTBOX FIM
//***********************************************************************************************


