// JavaScript Document

function _debug(str) {
	$('debug').innerHTML += "<br>"+str;
}

function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

var CARACS_ESPECIAIS;
var CARACS_REMAP;
var REG_ALFA_PT;

CARACS_ESPECIAIS 		= "âêîôûáéíóúãõàèìòùçñäëïöüÁÉÍÓÚÃÕÀÈÌÒÙÇÑÄËÏÖÜÂÊÎÔÛªº";
CARACS_ESPECIAIS_REMAP 	= "aeiouaeiouaoaeioucnaeiouAEIOUAOAEIOUCNAEIOUAEIOUao";
CARACS_SEPARADOR = "'´`~^/?!@#$%¨&*()_+-=";
RE_DIGITOS = "0-9";
RE_ALFA = "a-zA-Z";
RE_ALFA_NUM = eval("/[^"+RE_ALFA+RE_DIGITOS+"]/");
RE_ALFA_PT = eval("/[^"+RE_ALFA+CARACS_ESPECIAIS+"]/");
RE_ALFANUM_PT = eval("/[^"+RE_ALFA+RE_DIGITOS+CARACS_ESPECIAIS+"]/");
RE_SENHA = /[^!-~]/;
RE_NOME = eval("/[^ ."+RE_ALFA+CARACS_ESPECIAIS+"]/");
RE_LOGIN = eval("/[^"+RE_ALFA+RE_DIGITOS+"-_]/");
RE_MAIL = eval("/[^"+RE_ALFA+RE_DIGITOS+"-_\.\@]/");

function restringeChars(limitField, REG) {
	if (typeof(REG) == "undefined") {
		REG = RE_ALFA_PT;
	}
	limitField.value = limitField.value.replace(REG, "");
	//limitField.value = "abc";
}

function trim(msg)
{
    return msg.replace(/(^\s*)|(\s*$)/g, "");
}

function tram(str, simb) {
	simb = notset_defaultsto(simb, "'");
	return simb+str+simb;
}

function myGetElement(id) { // 100% compativel com todos browsers
    if (document.getElementById) {
		return document.getElementById(id);
    } else if (document.all) {
      	return document.all[id];
    } else if(document.layers) {
      	return document[id];
    }
}

function togglediv(divID) { // troca status de visibilidade
  	displaydiv(divID,(myGetElement(divID).style.display == 'none') ? true : false);
}

function displaydiv(divID, visibility) { // visibility (true/false)
	id = myGetElement(divID);
	if (id)
    	id.style.display = (visibility) ? '' : 'none';
}

function ismail( oMail ) {
	// Valida oMail como um e-mail, retorna true/false

	//MyRegExp = new RegExp("^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return (filter.test(oMail));
}

function ispass( pass ) {
	// Valida oMail como um e-mail, retorna true/false

	MyRegExp = new RegExp(RE_SENHA);
	return (!MyRegExp.test(pass) && (pass.length > 3));
}

function islogin( ologin ) {
	// Valida login, retorna true ou false

	MyRegExp = new RegExp(RE_LOGIN);
	return (!MyRegExp.test(ologin) && (ologin.length > 3));
}

function isname( nome ) {
	// Valida nome, retorna true ou false
	nome = trim(nome);
	MyRegExp = new RegExp(RE_NOME);
	return (!MyRegExp.test(nome) && (nome.length > 3));
}

function isminlen( texto, minsize) {
	// Valida texto com tamanho minimo = size, retorna true ou false
	minsize = notset_defaultsto(minsize, 3);
	texto = trim(texto);
	return (texto.length >= minsize);
}

function setFieldStyle(campo, ok) {
	if (ok) {
		campo.style.background="#FFF";
		return true;
	} else {
		campo.style.background= "#FEE";
		return false;
	}
}

function checklogin(campo) {
	return setFieldStyle(campo, islogin(campo.value) );
}

function checkpass(campo) {
	return setFieldStyle(campo, ispass(campo.value) );
}

function checkmail(campo) {
	return setFieldStyle(campo, ismail(campo.value) );
}

function checkname(campo) {
	return setFieldStyle(campo, isname(campo.value) );
}

function checkminlen(campo, size) {
	return setFieldStyle(campo, isminlen(campo.value, size) );
}

function notset_defaultsto(theVar, theDefault) {
	if (typeof(theVar)=="undefined") {
		theVar = theDefault;
		return theDefault;
	} else {
		return theVar;
	}
}

function atribuiEvento(obj, evType, fn){
	if (obj.addEventListener) obj.addEventListener(evType, fn, true)
	if (obj.attachEvent) obj.attachEvent("on"+evType, fn)
}

// eventos #####################################################################

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
	elm.addEventListener(evType, fn, useCapture);
	return true;
	}
	else if (elm.attachEvent) {
	var r = elm.attachEvent('on' + evType, fn);
	EventCache.add(elm, evType, fn);
	return r;
	}
	else {
	elm['on' + evType] = fn;
	}
}
function getEventSrc(e) {
	if (!e) e = window.event;

	if (e.originalTarget)
	return e.originalTarget;
	else if (e.srcElement)
	return e.srcElement;
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
	window.onload = func;
	} else {
	window.onload =
		function() {
		oldonload();
		func();
		}
	}
}
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,

		add : function(node, sEventName, fHandler, bCapture){
			listEvents.push(arguments);
		},

		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];

				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};

				/* From this point on we need the event names to be prefixed with 'on" */
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};

				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};

				item[0][item[1]] = null;
			};
		}
	};
}();

addEvent(window,'unload',EventCache.flush, false);






/**
 * debugFunctions.js
 *
 * This file contains a collection of debug functions for javascript.
 *
 * This source file is subject to version 2.1 of the GNU Lesser
 * General Public License (LPGL), found in the file LICENSE that is
 * included with this package, and is also available at
 * http://www.gnu.org/copyleft/lesser.html.
 * @package     Javascript
 *
 * @author      Dieter Raber <dieter@dieterraber.net>
 * @copyright   2004-12-27
 * @version     1.0
 * @license     http://www.gnu.org/copyleft/lesser.html
 *
 */

/**
 * TOC
 *
 * - getObjectProperties
 * - print_ob
 * - alert_ob
 * - window_ob
 *
 * - format_r
 * - print_r
 * - alert_r
 * - window_r
 */

/**
 * showProps
 *
 * Shows the properties of an given object
 *
 * object object
 * return array
 *
 * Use print_ob(), alert_ob() or window_ob() to display the result
 */
function getObjectProperties(item)
{
  var retVal = '';
  for (var prop in item)
  {
    if (item[prop].constructor != Function)
    {
      retVal += prop + ' => ' + item[prop] + "\n";
    }
  }
  return retVal;
}




/**
 * showProps
 *
 * Shows the properties of an given object
 *
 * object object
 * return array
 *
 * Use print_ob(), alert_ob() or window_ob() to display the result
 */
function getUserFunctions()
{
  var retVal = '';
  for (var prop in document)
  {
//    if (document[prop].constructor == Function)
//    {
//      retVal += prop + ' => ' + document[prop] + "\n";
//    }
  }
  return document;
}



/**
 * print_ob(), alert_ob(), window_ob()
 *
 * These three functions are different ways to display the result of getObjectProperties()
 * print_ob uses document.write and can hence only be called onload
 * alert_ob displays the result in an alert box
 * window_ob opens a popup window and writes the results there
 */
function alert_ob(expr)
{
  alert(getObjectProperties(expr))
}

function window_ob(expr)
{
  win = window.open('', 'format','width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable');
  win.document.open();
  win.document.write('<pre>' + getObjectProperties(expr) + '</pre>');
  win.document.close()
  win.focus();
}

function print_ob(expr)
{
  document.write('<pre>' + getObjectProperties(expr) + '</pre>');
}


/**
 * format_r
 *
 * Returns human-readable information about a variable
 *
 * format_r() returns information about a variable in a way that's readable by humans.
 * If given a string, integer or float, the value itself will be printed.
 * If given an array, values will be presented in a format that shows keys and elements.
 *
 * example:
 *   test = new Array ('foo', 'bar', 'foobar')
 *   format_r(test)
 *   returns: Array
 *            {
 *                 [0] => foo
 *                 [1] => bar
 *                 [3] => foobar
 *            }
 *
 */
function format_r(expr)
{
  var dim    = 0;
  var padVal = '\xA0\xA0\xA0\xA0\xA0';

  switch(typeof expr)
  {
    case 'string':
    case 'number':
      retVal = expr;
      break;
    case 'object':
      retVal = 'Array\n{\n' + outputFormat(expr, dim) + '\n}';
      break;
    default:
      retVal = false;
  }

  function pad(dim)
  {
    padding = '';
    for (i = 0; i < dim; i++)
    {
      padding += padVal;
    }
    return padding;
  }

  function outputFormat(expr, dim)
  {
    var retVal = '';
    for (var key in expr)
    {
        if (typeof expr[key] == 'object' && expr[key].constructor == Array)
        {
          retVal += padVal + pad(dim) + '[' + key + '] => Array\n'
                  + padVal + pad(dim) + '{\n'
                  + outputFormat(expr[key], dim + 1) + padVal + pad(dim) + '}\n';
        }
        else if (expr[key].constructor == Function)
        {
          continue;
        }
        else
        {
          retVal = retVal + padVal + pad(dim) + '[' + key + '] => ' + expr[key] + '\n';
        }
    }
    return retVal;
  }
  return retVal;
}

/**
 * print_r(), alert_r(), window_r()
 *
 * These three functions are just different ways to display the result of format_r()
 * print_r uses document.write and can hence only be called onload
 * alert_r displays the result in an alert box
 * window_r opens a popup window and writes the results there
 */
function alert_r(expr)
{
  alert(format_r(expr))
}

function window_r(expr)
{
  win = window.open('', 'format','width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable');
  win.document.open();
  win.document.write('<pre>' + format_r(expr) + '</pre>');
  win.document.close()
  win.focus();
}

function print_r(expr)
{
  document.write('<pre>' + format_r(expr) + '</pre>');
}

function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function ieTableHover(tabid, color1, color2) {
	if (navigator.appVersion.match(/\bMSIE\b/)) {
		//alert("ieTableHover"+tabid+" "+color1);
		for(var i=0; i<document.getElementsByTagName('table').length; i++){
			 if(document.getElementsByTagName('table')[i].id==tabid){
				for(var j=0; j<document.getElementsByTagName('table')[i].getElementsByTagName('tr').length; j++){
					if(document.getElementsByTagName('table')[i].getElementsByTagName('tr')[j].getElementsByTagName('th').length==0){
						document.getElementsByTagName('table')[i].getElementsByTagName('tr')[j].onmouseover=function(){
							this.style.backgroundColor=color1;
							this.style.color=color2;
						};
						document.getElementsByTagName('table')[i].getElementsByTagName('tr')[j].onmouseout=function(){
							this.style.backgroundColor='';
							this.style.color='';
						};
					}
				}
			 }
		}
	}

}
function alertError(strErro, width, height) {
	w = notset_defaultsto(width, 250);
	if (height == null) {
		tamMsg = strErro.length;
		charsporlinha = 40;
		h = 100 + (parseInt(tamMsg / charsporlinha)*15);
	} else {
		h = notset_defaultsto(height, 110);
	}
	Dialog.alert("<img src='"+imgPath+"important.png' /><br>"+strErro, {buttonClass: "btok", windowParameters: {className: wintheme, width: w, height: h}, showProgress: true});
}

/* ------------------------------------------------------------------------------------------- */
function abrejanela(theURL,winName,features) {
    ip = notset_defaultsto(imgPath, '');
	width = 0;
	height = 0;
	ar = features.split(",");
	for(var i=0; i<ar.length; i++){
		prop = (ar[i].split("="));
		if (!isNaN(parseInt(prop[1]))) {
			eval(prop[0]+" = " + prop[1]);
		}
	}
	if ( (width != 0) || (height != 0) ) {
		features += ","+centerWindow(width, height);
	}
	window.open(ip+'news/'+theURL,winName,features);
}


//------------------------------------
//-- Funcao que centraliza a janela
//------------------------------------
function centerWindow(largura,altura)
{
    if (document.layers) {
        var xMax = window.outerWidth, yMax = window.outerHeight;
	} else {
	    var xMax = screen.width, yMax = screen.height;
	    if (isNaN(xMax)) xMax = 800;
	    if (isNaN(yMax)) yMax = 600;
	}

    var xOffset = (xMax - largura)/2, yOffset = (yMax - altura)/2;
	return ("top="+ yOffset +",left="+ xOffset +"");
}

