﻿// JScript File
function verificaSessao(res)
{
    if(res != null && !res.error)
    {
        return res.value;
    }
    
    trace('verificaSessao() :: ' + (res == null? 'return null' : res.error.message));
  
    alert('Sua sessão expirou. Efetue o login novamente.');
    
    window.location = window.location.href.substring(0,window.location.href.lastIndexOf('/')) + '/login.aspx'; 
}

function verificaCaracteresNumeros(Texto, Mensagem) {

    var padrao = new RegExp("\\D");

    if (!padrao.test(Texto) || Texto == "") {
        return true;
    }

    alert(Mensagem);
    return false;

}

function VerificaPadraoData(Texto) {

    var padrao = new RegExp("\\d\\d/\\d\\d/\\d\\d\\d\\d");

    if ((padrao.test(Texto) && Texto.length == 10) || Texto == "") {
        return true;
    }

    alert('Preencha o campo "Início" no formato dd\\mm\\aaaa.');
    return false;

}

function VerificaCampoObrigatorio(Texto, Mensagem) {

    if (Texto == "") {
        alert(Mensagem);
        return false;
    }

    return true;
}

function onPressEnter(element, func) {
    simpleAddEvent(element, 'keypress', function (e) {
        if (getKeyCode(e) == 13) { // enter
            func();
        }
    });
}



// cross browser keycode read
function getKeyCode(_event) {
    
    if(this.event)//IE
    {
        return _event.keyCode;
    }
    else
    {
        if(_event.which)//FIREFOX
        {
            return _event.which;
        }
        else
        {
            if (_event != null)
            {
                return _event.keyCode;
            }
        }
    }

    return 0;
    
}


///////////////////////////////////////
//   P A G I N A Ç Ã O

function PaginacaoFocoPagSel(posScroll,t)
{
    try
    {
        $('divPaginacaoScroll').scrollLeft = posScroll;
    }
    catch(e) 
    {
        //tenta algumas vezes encontrar o div "divPaginacaoScroll"
        if(t < 2000)
        {
            window.setTimeout('PaginacaoFocoPagSel('+ posScroll +','+ (t+50) +');',50);
        }
    }
}

function PaginacaoListas(nreg,pagSel,funcaoRender,width)
{
    var maxp = Math.ceil(nreg/regPorPag);
    if(maxp == 1) return ''; //se só houver uma página, não há necessidade da estrutura de paginação para a tal lista
    
    if(width == null) width = ''; else width = 'width:'+width+'px;';
    
    
    
    var sb = new StringBuilder();
    sb.append('<div id=divPaginacaoScroll style=overflow:auto;height:32px;'+width+'> <span class=pgnacaoFundo>');
    
    for( c=0 ; c < maxp ; c++ )
    {
        if(pagSel == c)
        {
            sb.append('&nbsp;<span class=pgnacaoSel>');
        }
        else
        {
            sb.append('&nbsp;<span class=pgnacao onclick="'+ funcaoRender +'('+ c +');">');    
        }
        sb.append(c+1 + '</span>');
    }
     
    
    if(pagSel > 0)
    {
        indirectRun(function() {
            PaginacaoFocoPagSel($('divPaginacaoScroll').scrollLeft, 0);
        });
    }
    
    sb.append('</span></div>');
  
    return sb.toString();
}

function PaginacaoListasReduzida(nreg, pagSel, funcaoRender, width) {
    var maxp = Math.ceil(nreg / regPorPag);
    if (maxp == 1) return ''; //se só houver uma página, não há necessidade da estrutura de paginação para a tal lista

    if (width == null) width = ''; else width = 'width:' + width + 'px;';

    var sb = new StringBuilder();
    sb.append('<div id=divPaginacaoScroll style=overflow:auto;padding-top:15px;height:20px;text-align:center;' + width + '> <span class=pgnacaoFundo>');


    var minimo = pagSel - 4;
    if (minimo > 1){
        sb.append('<span class=pgnacaoRed onclick="' + funcaoRender + '(0);">Primeira</span>');
        sb.append('<span>...</span>');
    }
    else minimo = 0;

    var maximo = pagSel + 5;
    if (maximo >= maxp - 1) maximo = maxp;

    for (c = minimo; c < maximo; c++) {
        if (pagSel == c) {
            sb.append('<span class=pgnacaoSelRed>');
        }
        else {
            sb.append('<span class=pgnacaoRed onclick="' + funcaoRender + '(' + c + ');">');
        }
        sb.append(c + 1 + '</span>');
    }


    if (maximo < maxp - 1) {
        sb.append('<span>...</span>');
        sb.append('<span class="pgnacaoRed" onclick="' + funcaoRender + '(' + (maxp - 1) + ');">Última</span>');
    }


    if (pagSel > 0) {
        indirectRun(function () {
            PaginacaoFocoPagSel($('divPaginacaoScroll').scrollLeft, 0);
        });
    }

    sb.append('</span></div>');

    return sb.toString();
}



//   P A G I N A Ç Ã O
///////////////////////////////////////



// alternador
// exemplo de uso:
// var z = new Alternador(['claro','escuro']);
// for (var i=0; i<100; i++) {
//   sb.Append("<tr class='"+z.getNext()+"'>");
//   // ...
// }
var Alternador = function (pValores) {
    try {
        if (pValores.length < 1) {
            pValores = [];
        }
    } catch (e) {
        pValores = [];
    }
    
    this.valores = pValores;
    
    this.i = -1;
    
    this.getNext = function () {
        this.i++;
        
        if (this.i >= this.valores.length) { 
            this.i = 0;
        }
        
        return this.valores[this.i];
        
        
    };
}


GetCampo = function(id){
    try {
        var oObj = $(id);
        if (oObj.type == "checkbox" || oObj.type == "radio") {
            if (oObj.checked) {
                return true;                    
            }else{
                return false;
            }

        } else if (oObj.type == "select-one") {
            return oObj.options[oObj.selectedIndex].value;
        
        } else {
            return oObj.value;
        }
    } catch (e) {
    
        return null;
    }
}

SetCampo = function(id, vl){
	var oObj = $(id);
	if (oObj.type == "checkbox" || oObj.type == "radio") {
        if(vl==true){
            oObj.checked = true;    
        }
    }else{            
        oObj.value = vl;    
    }
}

SelecionaCor = function(div, nome, vl){
    var divAtual, valorAtual;
    switch(nome)
    {
        case "wms":
            divAtual = wms.divAtual;
            wms.vlAtual = vl;
            wms.divAtual = div;
            if(wms.Modo == 0) EditarWMS();
            break;
        case "gwms":
            divAtual = gwms.divAtual;
            gwms.vlAtual = vl;
            gwms.divAtual = div;
            if(gwms.Modo == 0) EditarGrupoWMS();
            break;
        case "dgwms":
            divAtual = dgwms.divAtual;
            dgwms.vlAtual = vl;
            dgwms.divAtual = div;
            if(dgwms.Modo == 0) EditarDistribuicaoGrupoWMS();
            break;
        case "pplivres":
            divAtual = pplivres.divAtual;
            pplivres.vlAtual = vl;
            pplivres.divAtual = div;
			if(pplivres.Modo == 0) EditarPPLivre();
            break;
        case "usuarios":
            divAtual = usuarios.divAtual;
            usuarios.vlAtual = vl;
            usuarios.divAtual = div;
			if(usuarios.Modo == 0) EditarUsuario();
            break;
        case "sites":
            divAtual = sites.divAtual;
            sites.vlAtual = vl;
            sites.divAtual = div;
            if(sites.Modo == 0) EditarSite();
            break;
        case "ips":
            divAtual = ips.divAtual;
            ips.vlAtual = vl;
            ips.divAtual = div;
			if(ips.Modo == 0) EditarIP();
            break;
        case "contvivo":
            divAtual = contvivo.divAtual;
            contvivo.vlAtual = vl;
            contvivo.divAtual = div;
			if(contvivo.Modo == 0) EditarContVivo();
            break;
        case "contgravado":
            divAtual = contgravado.divAtual;
            contgravado.vlAtual = vl;
            contgravado.divAtual = div;
			if(contgravado.Modo == 0) EditarContGravado();
            break;
        case "arquivosgravados":
            divAtual = arquivosgravados.divAtual;
            arquivosgravados.vlAtual = vl;
            arquivosgravados.divAtual = div;
			//if(arquivosgravados.Modo == 0) EditarArquivoGravado();
            break;
        case "aces":
            divAtual = aces.divAtual;
            aces.vlAtual = vl;
            aces.divAtual = div;
            if(aces.Modo == 0) editaAces();
            break;
                   
        default:
            divAtual = null;
    }
    
    try{
        if(divAtual!=null){
            $(divAtual).style.backgroundColor = '#ffffff';
        }        
    }catch(e) {}
    
    $(div).style.backgroundColor = '#cccccc';
}

InsOptionsBox = function(inserir, listaOrigemID, listaDestinoID)
{
    function procuraValorLista(lista,valor)
    {
        for(var i = 0; i < lista.length; i++)
        {
            if(lista.options[i].value == valor)
            {
                return i;
            }
        }
        return -1;
    }
    
    
    var listaOrigem = $(listaOrigemID);
    var listaDestino = $(listaDestinoID);
    
    if(inserir)
    {
        for(var io = 0; io < listaOrigem.length; io++)
        {
            if(!listaOrigem.options[io].selected) { continue; }
            
            if(procuraValorLista(listaDestino,listaOrigem.options[io].value) == -1)
            {
                listaDestino.options[listaDestino.length] = new Option(listaOrigem.options[io].text, 
                                                                       listaOrigem.options[io].value);
                listaOrigem.options[io].style.color = "#d5d5d5";
            }
        }
    }
    else
    {
        var arrayText = new Array();
        var arrayValue = new Array();
        var idxArrays = -1;
        
        for(var id = 0; id < listaDestino.length; id++)        
        {
            if(!listaDestino.options[id].selected) 
            { 
                idxArrays++;
                arrayText[idxArrays] = listaDestino.options[id].text;
                arrayValue[idxArrays] = listaDestino.options[id].value;
            }
            else
            {
                if(listaOrigem != null)
                {
                    var io = procuraValorLista(listaOrigem, listaDestino.options[id].value);
                    if(io != -1)
                    {
                        listaOrigem.options[io].style.color = "#000000";
                    }
                }
            }
        }
        
        listaDestino.length = 0;
        for(var ida = 0; ida <= idxArrays; ida++)
        {
            listaDestino.options[ida] = new Option(arrayText[ida], arrayValue[ida]);
        }
    }
    
    if(listaOrigem != null) { listaOrigem.selectedIndex = -1;}
    listaDestino.selectedIndex = -1;
}


function LimpaCorpo(){
	iCorpo.location.href = 'branco.htm';
}


function olhaCampo(_oCampo, _oFunction, _oInstancia){
    this.oCampo = _oCampo;
    this.oFunction = _oFunction;
    this.OnKeyUp = onkeyup;
    this.Tick = tick;

    this.TimeOutId = 0;

    this.oCampo.onkeyup = this.OnKeyUp;

    function onkeyup(){
        if(this.TimeOutId != 0){
            clearTimeout(this.TimeOutId);
        }

        if(_oInstancia == null)
            _oInstancia = 'OlhaCampo';

        this.TimeOutId = setTimeout( _oInstancia + '.Tick()', 800);
    }
    
    function tick(){
       this.oFunction(this.oCampo.value);
    }
}

function Seconds2Hour(countsec){
	var nMin = parseInt(countsec / 60);
	var nSec = parseInt(countsec % 60);
	var nHou = parseInt(nMin / 60);
	var nMin = parseInt(nMin % 60);
	var ret = "";
	ret = (nHou < 10) ? "0" + nHou + ":" : nHou + ":";
	ret += (nMin < 10) ? "0" + nMin + ":" : nMin + ":";
	ret += (nSec < 10) ? "0" + nSec : nSec;
	return(ret);
}

function Minutes2Hour(countmin) {
    var nHou = parseInt(countmin / 60);
    var nMin = parseInt(countmin % 60);
    
    var ret = "";
    ret = (nHou < 10) ? "0" + nHou : nHou;
    ret += "h ";
    ret += (nMin < 10) ? "0" + nMin : nMin;
    ret += "min ";
    
    return (ret);
}

function formataData(data) {
    if (!data.getDate || typeof data.getDate != "function") {
        return data;
    }

    var ret = "";
    
    var d = data.getDate();
    var m = data.getMonth() + 1;
    var h = data.getHours();
    var n = data.getMinutes();
    
    ret += ((d < 10) ? "0" + d : d);
    ret += "/" + ((m < 10) ? "0" + m : m);
    ret += "/" + data.getFullYear();
    ret += " " + ((h < 10) ? "0" + h : h);
    ret += ":" + ((n < 10) ? "0" + n : n);

    return ret;
}

function FixDecimals(num, decimals, decimal_separator) {
    if (!decimal_separator) {
        decimal_separator = '.';
    }
    
    // number to string;
    num = num + '';
    
    // find separator position
    var sep_pos = num.indexOf(decimal_separator);

    if (sep_pos < 0) {
        // there is no separator, add one;
        sep_pos = num.length;
        num = num + decimal_separator;

    } else if (sep_pos == 0) {
        // separator is at beggining
        num = '0' + num;
        sep_pos = 1;

    }
    
    // if decimals == 0, keep only the integer part
    if (decimals == 0) {
        return num.substr(0, sep_pos);
    }
    
    // count how much decimals there are
    var dec_part_len = num.substr(sep_pos + 1).length;
    
    // decimals length is already correct
    if (dec_part_len == decimals) {
        return num;
    }
    
    // decimals length is bigger, chop extra numbers
    if (dec_part_len > decimals) {
        return num.substr(0, sep_pos + 1 + decimals);
    }

    var zeroes = '';
    // decimals length is smaller, add extra zeroes
    for (var i = 0; i < decimals - dec_part_len; i++) {
        zeroes += '0';
    }

    return num + zeroes;
    
}



/// ************************************
/// **** TRACE *************************
/// ************************************
/* @author Eric Jun Kinoshita */

// trace popup reference
var TracePopup = {};
var TracePopupEnabled = 0; // -1=disabled / 0=not set / 1=enabled
var TracePopupBlocked = false;

// displays tracing messages
function trace(message) {

    if (TracePopupEnabled == -1 || TracePopupBlocked == true) {
        return;
    }

    if (TracePopupEnabled == 0) {
        TracePopupEnabled = Request.queryString("Debug") == "true" ? 1 : -1;
    }

    if (TracePopupEnabled < 1 || typeof(message) == "undefined") {
	    return;
	}
	
	
	
	// get the tracing element
	
	// to skip on access deny
	var popItUp = false;
	try {TracePopup.document} catch(e) {popItUp = true;}
	
	if (popItUp || !TracePopup.document) // create the tracing message container
	{
        
        TracePopup = window.open('','TRACER','height=500,width=700,scrollbars=yes');

        if (TracePopup == null) {
            TracePopupBlocked = true;
            
            alert("Trace Popup could not be opened.\nCheck if your popup blocker is activated.");
            
            return;
        }
        
		TracePopup.document.write("<html><head><style>BODY{background:black;color:lime;font-family:monospace} DIV{margin:10px;}</style></head><body id='tracec'></body></html>");
        TracePopup.document.close();
        TracePopup.focus();
        		
		//trace("<B>LampBox TRACING TOOL</B>");

var t = "";
t += "  __                          __                   \n";
t += " |  |.---.-..--------..-----.|  |--..-----..--.--. \n";
t += " |  ||  _  ||        ||  _  ||  _  ||  _  ||_   _| \n";
t += " |__||___._||__|__|__||   __||_____||_____||__.__| \n";
t += "  __                  |__| __                      \n";
t += " |  |_ .----..---.-..----.|__|.-----..-----. \n";
t += " |   _||   _||  _  ||  __||  ||     ||  _  | \n";
t += " |____||__|  |___._||____||__||__|__||___  | \n";
t += "  __                  __             |_____| \n";
t += " |  |_ .-----..-----.|  | \n";
t += " |   _||  _  ||  _  ||  | \n";
t += " |____||_____||_____||__| \n\n";
                         
trace("<pre>"+t+"</pre>");                         


	}
    
    
    var tracec = TracePopup.document.getElementById('tracec');
    
    // auto scroll stuff
    var autoscroll = (tracec.scrollTop == tracec.scrollHeight - tracec.clientHeight);
    if (tracec.scrollTop == 0) {
        autoscroll = true;
    }
    
	// put tracing message
	var obj = TracePopup.document.createElement('DIV');
	obj.innerHTML = message ;// +'<hr style="height:1px; border: 1px solid #009900;"/>';
	tracec.appendChild(obj);
    
    
    // if autoscoll, scoll to bottom
    if (autoscroll) {
        tracec.scrollTop = tracec.scrollHeight;   
    }
    
    
};


trace("Tracing activated");

/// *** END TRACE ***







var TabelaHtml = function (css_class, aditionalProperties) {
    this.sb = new StringBuilder();

    this.currentRow = -1;
    this.currentCellTag = "td";

    this.z = new Alternador(['', "zebra"]);

    this.headerRow = function () {
        if (this.currentRow < 0) {
            // pass
        } else {
            this._closeRow();
        }
        this.currentRow++;

        this.currentCellTag = "th";

        this._openRow();

    };

    this.addRow = function () {
        if (this.currentRow < 0) {
            // pass
        } else {
            this._closeRow();
        }
        this.currentRow++;

        this.currentCellTag = "td";

        this._openRow(this.z.getNext());

    };

    this.addCell = function (content, css_class, aditionalCellProperties) {

        css_class = this._convertToString(css_class);
        aditionalCellProperties = this._convertToString(aditionalCellProperties);

        this.sb.append("<" + this.currentCellTag);
        if (css_class.length > 0) {
            this.sb.append(" class='" + css_class + "' ");
        }
        if (aditionalCellProperties.length > 0) {
            this.sb.append(" " + aditionalCellProperties + " ");
        }
        this.sb.append(">");

        if (this.currentCellTag == "th") {
            this.sb.append("<b>" + content + "</b>");

        } else {
            this.sb.append(content);

        }

        this.sb.append("</" + this.currentCellTag + ">");
    };


    this._openRow = function (css_class) {
        css_class = this._convertToString(css_class);

        if (css_class.length > 0) {
            this.sb.append("<tr class='" + css_class + "'>");
        } else {
            this.sb.append("<tr>");
        }

    };

    this._closeRow = function () {
        this.sb.append("</tr>");
    };

    this._convertToString = function (input) {
        if (input == undefined || input == null) {
            return "";
        }

        return input + "";
    };

    this.toString = function () {

        this._closeRow();
        this.sb.append("</table>");

        return this.sb.toString();


    };


    css_class = this._convertToString(css_class);
    aditionalProperties = this._convertToString(aditionalProperties);

    this.sb.append("<table");

    if (css_class.length > 0) {
        this.sb.append(" class='" + css_class + "'");
    }
    if (aditionalProperties.length > 0) {
        this.sb.append(" " + aditionalProperties);
    }

    this.sb.append(">");


}








// runs a function, if it is a function
// still not passing parameters to handler
function funcRun (functionHandler) 
{
    if (functionHandler == null) 
    {
    	trace('[NOTICE] funcRun: functionHandler is null');
    	return;
    }
    
    if (typeof functionHandler != 'function') {
        trace('[ERROR] funcRun: function expected');
        /*trace('[ERROR] funcRun: got '+(typeof functionHandler)
        	+', function expected');*/
        return;
    }
    
    return functionHandler();
};


function abrirJanelaTransmissao (destino) {
    window.open(destino,'_blank','width=807,height=600,resizable=yes,status=no,menubar=no,toolbar=no,scrollbars=yes');
}

function abrirJanelaConferencia (destino){

    window.open(destino,'_blank','width=800,height=600,resizable=no,status=no,menubar=no,toolbar=no,scrollbars=no');
    /*var width, height;
    if(screen.width < 1024 && screen.height < 768) {
        width = 800; height = 525;
    } else {
        width = 1018; height = 695;
    }

    window.open(destino,'_blank','width='+width+',height='+height+',resizable=no,status=no,menubar=no,toolbar=no,scrollbars=no');*/
}


// check if there is any equal value in array
// (unstrict equality)
function in_array(arr, value) {

    // loops over input array
    for (var i=0; i < arr.length; i++) {
    
        // check for equal values
        if (arr[i] == value) {
            return true;
        }
        
    }
    
    return false;
}



function indirectRun(f){ setTimeout(f,250); }



// cross browser
// adiciona um evento (abstrai microsoft/w3c)
function simpleAddEvent(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}
// remove um evento (abstrai microsoft/w3c)
function simpleRemoveEvent(obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
}


function SetVisibilityIfExists(element, visible) {
    if (element == null || element.style == null) {
        return;
    }

    element.style.visibility = visible;
}



/////////////////////////////////////
// CARREGADOR AUTOMÁTICO DE PÁGINAS
var AutoCargaPaginas = {

    // quando faltar _loadTriggerMark pixels, carrega outra página
    _MarcaAcionamento: 200,

    _itensPorPagina: 20,

    _paginaAtual: 0,

    _fnCarga: null,
    _ativo: false,
    _carregando: false,

    // verifica se é para carregar mais uma página ou não
    VerificaScroll: function (event) {
        var ACP = AutoCargaPaginas;

        var doc = document.body;
        var scrollBottom = getDocumentScrollBottom();

        if (!ACP._ativo || scrollBottom > ACP._MarcaAcionamento) {
            return;
        }

        if (ACP._carregando) {
            return;
        }
        ACP._carregando = true;

        indirectRun(ACP.ExecutaCarga);

    },

    // define qual será a função de carga
    FuncaoCarga: function (fn) {
        var ACP = AutoCargaPaginas;
        ACP.Limpa();

        ACP._fnCarga = fn;

        if (typeof ACP._fnCarga == 'function') {
            ACP._ativo = true;
        }

        indirectRun(ACP.VerificaScroll);
    },

    // limpa as informações e pára o funcionamento do script
    // se a função de carga retornar 0 (zero), essa função é 
    // executada automaticamente
    Limpa: function () {
        var ACP = AutoCargaPaginas;
        ACP._fnCarga = null;
        ACP._paginaAtual = 0;
        ACP._ativo = false;
        ACP._carregando = false;
    },

    // executa a carga de uma nova página
    ExecutaCarga: function () {
        var ACP = AutoCargaPaginas;

        var resposta = ACP._fnCarga(ACP._paginaAtual);

        ACP._paginaAtual++;

        if (resposta == 0) {
            ACP.Limpa();
        } else {
            indirectRun(ACP.LiberaAcionamento);
        }
    },

    // impede que carregue mais vezes
    LiberaAcionamento: function () {
        var ACP = AutoCargaPaginas;
        ACP._carregando = false;
        indirectRun(ACP.VerificaScroll);
    }

};
simpleAddEvent(window, 'scroll', AutoCargaPaginas.VerificaScroll);






// classe para montar pseudolinkOptions,
// para exemplo, vide js/VisualizarTransmissao.js
function PseudolinkOptions(input_id) {

    // Constructor
    var po_object = this;

    this.input = null;
    this.input_id = input_id;
    this.total_items = 0;

    this._exec_on_render = [];
    this._htmlContent = new StringBuilder();

    this._exec_on_render.push(function () { po_object.input = $(input_id); });

    this._onChangeFunction = null;
    // constructor end

    // deseleciona todos os itens
    this.UnselectAll = function () {
        var total = po_object.total_items;
        for (var i = 0; i < total; i++) {
            $(po_object.input_id + "_po" + i).className = 'pseudolink';
        }
    };

    // seleciona um item em específico
    this.Select = function (item_id, value) {
        po_object.input.value = value;
        po_object.UnselectAll();
        $(item_id).className = 'strong';

        // executa o onchange
        if (typeof po_object._onChangeFunction == 'function') {
            po_object._onChangeFunction();
        }
    };

    this.AddLevel = function () {
        po_object._htmlContent.append('<li class="SubOptions">&nbsp;<ul>');
    };

    this.RemoveLevel = function () {
        po_object._htmlContent.append('</ul></li>');
    };

    // adiciona uma opção
    this.AddItem = function (value, text, selected) {
        // monta o id da opção
        var item_id = po_object.input_id + "_po" + po_object.total_items;

        // monta o html da opção
        po_object._htmlContent.append('<li><span id="' + item_id + '" ');

        po_object._htmlContent.append('class="'
            + (selected ? 'strong' : 'pseudolink')
            + '">');

        po_object._htmlContent.append(text);
        po_object._htmlContent.append('</span></li>');

        
        po_object._exec_on_render.push(function () {
            simpleAddEvent($(item_id), 'click', function () { po_object.Select(item_id, value); });
        });

        if (selected == true) {
            po_object._exec_on_render.push(function () { po_object.input.value = value; });
        }

        po_object.total_items++;
    };

    this.OnChange = function (func) {
        po_object._onChangeFunction = func;
    };


    this.getHtmlContent = function () {

        // executa indiretamente as funções de binding
        indirectRun(function () {
            var func;
            for (var i = 0; i < po_object._exec_on_render.length; i++) {
                po_object._exec_on_render[i]();
            }
        });

        // monta o html final
        var output = '<input type="hidden" id="' + po_object.input_id + '" />';
        output += '<ul class="POptions">';
        output += po_object._htmlContent.toString();
        output += '</ul>';

        return output;
    }

}




function getDocumentHeight() {
    var D = document;
    return MathMax(
        MathMax(D.body.scrollHeight, D.documentElement.scrollHeight),
        MathMax(D.body.offsetHeight, D.documentElement.offsetHeight),
        MathMax(D.body.clientHeight, D.documentElement.clientHeight)
    );
}
function getDocumentScrollTop() {
    var D = document;

    return MathMax(
        MathMax(window.pageYOffset, //Netscape compliant
            D.body.scrollTop), //DOM compliant
        //IE6 standards compliant mode
        D.documentElement.scrollTop
    );

}
function MathMax (a, b) {
    if (typeof a != 'number') { a = 0 }
    if (typeof b != 'number') { b = 0 }

    return a > b ? a : b;
}

function getDocumentScrollBottom() {
    var inner_size = GetInnerSize()[1];
    return getDocumentHeight() - getDocumentScrollTop() - inner_size;
}   


function GetInnerSize () {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
}

function ResizeToInner(w, h) {
    try {
        if (window.frameElement == null) {
            // get the inner dimensions.  the offset is the difference.
            var inner = GetInnerSize();
            window.resizeBy(w - inner[0], h - inner[1]);
        } else {
            trace('tools.js error: ResizeToInner(w, h) window is in a frameElement');
        }
    } catch (e) {
        trace('tools.js error: ResizeToInner(w, h)');
    }
}








function CopyToClipboard(text) 
{ 
    window.clipboardData.setData("Text", text);
}












function nl2br (str, is_xhtml) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
 
    var breakTag = '';
 
    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }
 
    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}



function loadExternalJs(fileName) {
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = fileName;
    oHead.appendChild(oScript);
}

function getFlashMovieObject(movieName){
	if (window.document[movieName]){
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName];
	}
	else{
		return document.getElementById(movieName);
	}
}

 
