/**
 * energy.js
 * A autoria desta biblioteca de funções java script é de
 * Moacyr Freitas Martins Júnior.
 * energy.js pode ser livremente utilizada, desde que sejam
 * mantidos os direitos de autoria.
 */

var project = 'web';
var controllerClass;
var ie;

/**
 * Use este método para incializar a página.
 */
function load(controller) {
    controllerClass = controller;
    var p = new controllerTo('init');
    p.request();
}

/**
 * Use este método para enviar alguma ação ao servidor.
 * Observe que será usado o último controller.
 */
function action(action, beforeRequest, afterRequest) {
    var p = new controllerTo(action);
    p.setBeforeRequest(beforeRequest);
    p.setAfterRequest(afterRequest);
    p.request();
}

/**
 * Use este método para enviar uma ação para um controller no servidor.
 */
function controller(controller, action, beforeRequest, afterRequest) {
    var currentController = controllerClass;
    controllerClass = controller;
    var p = new controllerTo(action);
    p.setBeforeRequest(beforeRequest);
    p.setAfterRequest(afterRequest);
    p.request();
    controllerClass = currentController;
}

function e$(tagName) {
    return window.document.getElementById(tagName);
}

function tag(name, att, value) {
    var htmlTag = e$(name);
    if (htmlTag==null) { 
        return null;
    }
    if (att==null || att==undefined) {
        if (htmlTag.type=='checkbox') {
            att = 'checked';
        }
        else if (htmlTag.tagName=='INPUT' 
            || htmlTag.tagName=='SELECT'
            || htmlTag.tagName=='TEXTAREA') {
            att = 'value';
        }
        else {
            att = 'innerHTML';
        }
    }
    if (!(value==null || value==undefined)) {
        try {
            if (att.toUpperCase()=='INNERHTML') {
                try {
                    htmlTag.innerHTML = value; 
                }
                catch (e1) {
                    // O IE não aceita que o conteúdo de TABLE seja modificado.
                    // Permite modificar apenas TBODY, mas como são passados COL, 
                    // THEAD e TFOOT, a solução é rescontruir toda a tabela.
                    if (ie && htmlTag.tagName=='TABLE') {
                        var originalTable = htmlTag.cloneNode(false);
                        var newTable = document.createElement('div');
                        newTable.innerHTML = '<table>' + value + '</table>'
                        for (var i=0; i<originalTable.attributes.length; i++) {
                            var attName = originalTable.attributes[i].name;
                            var attValue = originalTable.attributes[i].value;
                            try {
                                if (newTable.firstChild[attName].toString()!=attValue.toString()) {
                                    newTable.firstChild[attName] = attValue;
                                }
                            } catch (e2) {}
                        }
                        var parentTable = htmlTag.parentNode;
                        parentTable.replaceChild(newTable.lastChild, parentTable.lastChild);
                    }
                }
            }
            else if (att.toUpperCase()=='VALUE') {   // O FF passa a não atualizar o atributo 
                if (htmlTag.type=='checkbox') {      // value quando tentei usar setAttribute.
                    htmlTag.checked = (value == 'true');
                }
                else {
                    htmlTag.value = value                              
                }
            }
            else {
                htmlTag[att] = value;   // O método setAttribute() não funciona direito no FF.
            }
        }
        catch (e) {
            alert('Problemas a atribuir o conteúdo da tag ' + name + '\n' + e.toString());
        }
    }
    return htmlTag[att];
}

//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// obsoleto.
function setTag(tagName, tagValue, attributeName) {
    try {
        var htmlTag = e$(tagName);
        if (htmlTag!=null) {
            if (attributeName==null || attributeName==undefined) {
                try {
                    htmlTag.innerHTML = tagValue; 
                }
                catch (e1) {
                    // O IE não aceita que o conteúdo de TABLE seja modificado.
                    // Permite modificar apenas TBODY, mas como são passados COL, 
                    // THEAD e TFOOT, a solução é rescontruir toda a tabela.
                    if (ie && htmlTag.tagName=='TABLE') {
                        var originalTable = htmlTag.cloneNode(false);
                        var newTable = document.createElement('div');
                        newTable.innerHTML = '<table>' + tagValue + '</table>'
                        for (var i=0; i<originalTable.attributes.length; i++) {
                            var attName = originalTable.attributes[i].name;
                            var attValue = originalTable.attributes[i].value;
                            try {
                                if (newTable.firstChild[attName].toString()!=attValue.toString()) {
                                    newTable.firstChild[attName] = attValue;
                                }
                            } catch (e2) {}
                        }
                        var parentTable = htmlTag.parentNode;
                        parentTable.replaceChild(newTable.lastChild, parentTable.lastChild);
                    }
                }
            }
            else if (attributeName.toUpperCase()=='VALUE') {   // O FF passa a não atualizar o atributo 
                if (htmlTag.type=='checkbox') {                // value quando tentei usar setAttribute.
                    htmlTag.checked = (tagValue == 'true');
                }
                else {
                    htmlTag.value = tagValue                              
                }
            }
            else {
                htmlTag[attributeName] = tagValue;   // O método setAttribute() não funciona direito no FF.
            }
        }
    }
    catch (e) {
        alert('Problemas a atribuir o conteúdo da tag ' + tagName + '\n' + e.toString());
    }
}

function setWaitMessage(message) {
    setTag('message', "<div id='waitProgress'></div><div id='wait'>" + message + "</div>");
}

function setFocus(tagName) {
    var htmlTag = e$(tagName);
    if (htmlTag!=null) {
        htmlTag.focus();
    }
}

/**
 * Esta classe é responsável por efetuar a comunicação entre
 * o browser e o servidor.
 * Os dados são passados como parâmetros e a resposta é recebida
 * em um documento XML.
 */
function controllerTo(action) {
    var requester = getRequester();
    var beforeRequestFunction = null;
    var afterRequestFunction = null;
    var pageParameters = '';
    var contentType = 'application/x-www-form-urlencoded';
    
    function getRequester() {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(e1) {
            try {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e2) {
                try {
                    return new XMLHttpRequest();
                }
                catch(e3) {
                    alert('Não foi encontrado suporte para Ajax neste navegador!\n' + e3.toString());
                    return null;
                }
            }
        }
    }

    this.request = function() {
        setWaitMessage('Entrando em contato com o servidor, aguarde...');
        setTag('error', '');
        this.addParameter('controllerClass', controllerClass);
        this.addParameter('page', document.location.pathname);
        this.addParameter('action', action);
        if (beforeRequestFunction!=null) {
            try {
                beforeRequestFunction(this);
            } catch (e) {
                // Para mostrar caso o usuário tenha definido algo
                // que resulte em erro.
                alert('Problemas antes de requerer acesso ao servidor!\n' + e.toString() + "\n" + beforeRequestFunction);
            }
        }
        try {
            // Prepara a chamada Ajax...
            requester.open('POST', '/' + project + '/controller', true);
            requester.onreadystatechange = readyStateChange;
            requester.setRequestHeader('Content-type', contentType);
            requester.setRequestHeader('Connection', 'close');
            requester.setRequestHeader('Content-length', pageParameters.length);
            requester.send(pageParameters);
        } 
        catch (e) {
            alert('Problemas ao acessar o servidor!\n' + e.toString());
            setTag('message', 'Problemas! (' + e.toString() + ')');
        }
    }
    
    function readyStateChange() {
        if (requester.readyState==4) {
            if (requester.status == 200) {
                innerAfterRequest();
            }
            else {
                setTag('message', 'Problemas! (' + requester.statusText + ')');
            }
        }
        else {
            setWaitMessage('Esperando a resposta do servidor, aguarde...');
        }
    }
    
    function innerAfterRequest() {
        setWaitMessage('Interpretando a resposta do servidor, aguarde...');
        var parsedXML = requester.responseXML;
        if (!parsedXML || !parsedXML.documentElement) { 
            parsedXML = getXML(requester.responseText);
        }
        
        // Para passar o limite de 4096 caracteres em um único node.
        // Esta limitação não existe no ie.
        if (!ie) {
            try {
                parsedXML.normalize();
            } catch (e) {}
        }
        
        var xml = new myXML(parsedXML);
        
        // Se houver um estilo a ser aplicado...
        if (xml.hasStyleDefinition()) {
            //            setStyle('systemStyle', 'sistema');
            setStyle('userStyle', xml.styleDefinition()); 
        }
        
        // Por enquanto, ao receber um scriptCode, o mesmo é 
        // imediatamente executado, presupondo-se que foi
        // enviado pelo init(). Se for preciso mandar outros
        // scripts, precisaremos mudar algo aqui.
        if (xml.hasScriptCode()) { 
            addScriptCode(xml.scriptCode()); 
            afterRequestFunction = afterInit;
        }
        
        if (xml.ok()) { 
            if (afterRequestFunction!=null) {
                try {
                    afterRequestFunction(xml); 
                }
                catch (e) {
                    // Mostra o erro caso o usuário tenha definido
                    // algo errado na função pós request.
                    alert('Problemas após a resposta do servidor!\n' + e.toString());
                }
            }
            processActions(xml);
            setTag('message', xml.message());
        }
        else {
            alert(xml.error().replace('<br>', '\n'));
            setTag('error', xml.stackError());
            setTag('message', xml.message());
            setFocus(xml.focus());
        }
    }
    
    this.setBeforeRequest = function(beforeRequest) {
        beforeRequestFunction = beforeRequest;
    }
    
    this.setAfterRequest = function(afterRequest) {
        afterRequestFunction = afterRequest;
    }
    
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    this.parameter = function(tagName, attributeName) {
        if (tagName.search('-')==-1) {
            var tagNames = tagName.split('.');
            addListParameter('', tagNames, attributeName);
        }
        else {
            addTagParameter(tagName, attributeName);
        }
    }
    
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    function addListParameter(root, next, attributeName) {
        if (next.length>1) {
            root = root + next[0] + '-';
            next.shift();
            for (var row=1;; row++) {
                try {
                    if (!addListParameter(root + row + '.', next.clone(), attributeName)) {
                        return false;
                    }
                }
                catch (e) {
                    // Se houver erro já na primeira linha, é porque a tag não existe...
                    if (row==1) {
                        // Então o loop pode ser interrompido.
                        return false;
                    }
                    else {
                        // Se o erro ocorreu depois sa primeira linha, continua
                        // na próxima linha da tag anterior.
                        // Por exemplo, se titulo-1.lancamento-2.valor-2 não existir,
                        // irá tentar titulo-1.lancamento-3.valor-1
                        break;
                    }
                }
            }
        }
        else {
            var tagName = root + next[0]; 
            addTagParameter(tagName, attributeName);
        }
        return true;
    }

    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    function addTagParameter(tagName, attributeName) {
        var attributeValue;
        var htmlTag = e$(tagName);
        if (attributeName==null || attributeName==undefined) {
            if (htmlTag.type=='checkbox') { // por ser um input, deve vir antes.
                attributeValue = htmlTag.checked.toString();
            }
            else if (htmlTag.tagName=='INPUT' 
                || htmlTag.tagName=='SELECT'
                || htmlTag.tagName=='TEXTAREA') {
                attributeValue = htmlTag.value;
            }
            else {
                attributeValue = htmlTag.innerHTML;
            }
        }
        else {
            attributeValue = htmlTag[attributeName];
            // alert(tagName + "\n" + attributeName + "\n" + attributeValue);
            tagName += '__' + attributeName;
        }
        if (attributeValue==undefined) {
            attributeValue = '';
        }
        addParameter(tagName, attributeValue);
    }

    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    this.addParameter = addParameter;
    function addParameter(parameterName, parameterValue) {
        if (pageParameters) {
            pageParameters += '&';
        }
        // alert(parameterName + "\n" + parameterValue + "\n" + $.trim(parameterValue) + "\n" + escape($.trim(parameterValue)));
        pageParameters += parameterName;
        pageParameters += '=';
        pageParameters += escape($.trim(parameterValue));  // escape para permitir % por exemplo.
    }
    
    function addScriptCode(scriptCode) {
        var e;
        e = document.createElement('script');
        e.text = scriptCode;
        document.getElementsByTagName('head').item(0).appendChild(e);
    }

    function setStyle(styleId, styleName) {
        if (e$(styleId)==null) {
            var style;
            style = document.createElement('link');
            style.id = styleId;
            style.setAttribute('rel', 'stylesheet');
            style.setAttribute('type', 'text/css');
            //            style.setAttribute('href', '/web/estilo/' + styleName + '/style.css');
            style.setAttribute('href', styleName);
            document.getElementsByTagName('head').item(0).appendChild(style);
        }
    }

    function getXML(textXML) {
        if (!window.DOMParser) {
            ie = true;
            var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ];
            for (var i = 0; i < progIDs.length; i++) {
                try {
                    var xmlDOM = new ActiveXObject(progIDs[i]);
                    xmlDOM.async = false;
                    xmlDOM.loadXML(textXML);
                    xmlDOM.setProperty('SelectionLanguage', 'XPath');
                    return xmlDOM;
                } catch (e) {}
            }
        }
        else { // Mozilla browsers have a DOMParser
            ie = false;
            try {
                var domParser = new window.DOMParser();
                return domParser.parseFromString(textXML, 'text/xml');
            } catch (e) {}
        }
        return null;
    }

    function processActions(xml) {
        var actions = xml.actions();
        if (actions!=undefined) {
            for (i=0; i<actions.childNodes.length; i++) {
                processAction(actions.childNodes[i]);
            }
        }
    }

    function processAction(action) {
        if (action.firstChild!=null) {
            var act = (action.getAttribute('act')==null? 'set' : action.getAttribute('act'));
            if (act=='execut') {
                eval(action.firstChild.nodeValue);
            }
            else {
                var tag = e$(action.getAttribute('id'));
                var att = (action.getAttribute('att')==null? 'value' : action.getAttribute('att'));
                if (tag[att]!=action.firstChild.nodeValue) {
                    if (ie && att.toUpperCase()=='INNERHTML' && tag.tagName=='TABLE') {
                        // O IE não aceita que o conteúdo de TABLE seja modificado.
                        // Permite modificar apenas TBODY, mas como são passados COL, 
                        // THEAD e TFOOT, a solução é rescontruir toda a tabela.
                        var originalTable = tag.cloneNode(false);
                        var newTable = document.createElement('div');
                        newTable.innerHTML = '<table>' + action.firstChild.nodeValue + '</table>'
                        for (var i=0; i<originalTable.attributes.length; i++) {
                            var attName = originalTable.attributes[i].name;
                            var attValue = originalTable.attributes[i].value;
                            try {
                                if (newTable.firstChild[attName].toString()!=attValue.toString()) {
                                    newTable.firstChild[attName] = attValue;
                                }
                            } catch (e2) {}
                        }
                        var parentTable = tag.parentNode;
                        parentTable.replaceChild(newTable.lastChild, parentTable.lastChild);
                    }
                    else {
                        // Este é o normal.
                        tag[att] = action.firstChild.nodeValue;
                    }
                }
            }
        }
    }
}

/**
 * Esta classe é responsável por interpretar o documento XML
 * recebido como resposta do servidor. 
 */
function myXML(xml) {
    var doc = (xml == null? null : xml.getElementsByTagName('XMLReturn')[0]);

    this.getNode = function(nodeName) {
        try {
            return doc.getElementsByTagName(nodeName)[0];
        } catch (e) { 
            return null;
        }
    }
    
    this.get = function(nodeName) {
        try {
            var node = this.getNode(nodeName);
            return node.firstChild.nodeValue;
        } catch (e) { 
            return '';
        }
    }
    
    this.has = function(nodeName) {
        return (this.get(nodeName) != '');
    }
    
    this.ok = function() {
        return (this.has('error') == '');
    }
    
    this.hasScriptCode = function() {
        return (this.has('scriptCode') != '');
    }
    
    this.scriptCode = function() {
        return this.get('scriptCode');
    }
    
    this.hasStyleDefinition = function() {
        return (this.has('style') != '');
    }
    
    this.styleDefinition = function() {
        return this.get('style');
    }
    
    this.hasError = function() {
        return (this.has('error') != '');
    }
    
    this.error = function() {
        var errorMessage = this.get('error');
        if (errorMessage.indexOf('Processos:')>0) {
            errorMessage = errorMessage.substr(0,errorMessage.indexOf('Processos:'));
        }
        return errorMessage;
    }
    
    this.stackError = function() {
        var errorMessage = this.get('error');
        while (errorMessage.indexOf('\n')>0) {
            errorMessage = errorMessage.replace('\n', '<br>');
        }
        return errorMessage;
    }
    
    this.message = function() {
        return this.get('message');
    }

    this.actions = function() {
        var node = this.getNode('actions');
        return node;
    }

    this.focus = function() {
        return this.get('focus');
    }
    
    this.init = function(tagName) {
        try {
            setTag(tagName, this.get(tagName));
        } catch (e) {
            alert('Problemas ao inicializar a página!\nO conteúdo da tag ' + tagName + ' não foi atualizado!\n' + e.toString());
        }
    }
    
    this.read = function() {
        for (i=0; i<doc.childNodes.length; i++) {
            var xmlTag = doc.childNodes[i];
            var tagName = xmlTag.tagName;
            var tagValue;
            try {
                tagValue = xmlTag.firstChild.nodeValue;
            }
            catch (e) {
                tagValue = '';
            }
            var attributeName = xmlTag.getAttribute('att');
            setTag(tagName, tagValue, attributeName);
        }
    }
    
    this.readNewRow = function(tableName) {
        var table = e$(tableName);
        var tbody = table.getElementsByTagName('TBODY')[0];
        var tr = document.createElement('TR');
        var firstField = null;
        var cols = table.getElementsByTagName('THEAD')[0].childNodes[0].childNodes.length;
        for(i = 0; i<cols; i++) {
            var td = document.createElement('TD');
            td.innerHTML = this.get('newColumn' + i);
            td.className = this.get('cellStyleClass');
            
            /**
             * O Alinhamento deveria ser feito apenas em
             * TableColumn, mas o FF não interpreta isto
             * corretamente. Deve faltar algum detalhe :(
             */
            if (this.has('styleNewColumn' + i)) { 
                td.style.textAlign = this.get('styleNewColumn' + i);
            }
            
            tr.appendChild(td);
            if (i==1) {
                firstField = td.firstChild;
            }
        }
        tr.className = this.get('rowStyleClass');
        tbody.appendChild(tr);
        firstField.focus();
    }
}

/*******************************************************************************
 * Funçõees para o tratamento de datas.
 */

function setToday(tagName) {
    var htmlTag = e$(tagName);
    var d = new Date();
    var s;
    s = d.getUTCDate() + '/';
    s += (d.getUTCMonth() + 1) + '/';
    s += d.getUTCFullYear();
    htmlTag.value = s;
}

function setNow(tagName) {
    var htmlTag = e$(tagName);
    var d = new Date();
    var s;
    s = d.getUTCDate() + '/';
    s += (d.getUTCMonth() + 1) + '/';
    s += d.getUTCFullYear() + ' ';
    s += d.getHours() + ':';
    s += d.getMinutes();
    htmlTag.value = s;
}

/*******************************************************************************
 * Array.clone
 */

Array.prototype.clone = function () {
    var c = new Array(); 
    for (var property in this) {
        c[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property];
    } 
    return c;
}

/*******************************************************************************
 * String: padLeft e padRight
 */

function padLeft(s, length) {
    s = s.substring(0, length);
    length -= s.length;
    var pad = '';
    while (pad.length < length) { 
        pad += ' ';
    }
    return (pad + s);
}

function padRight(s, length) {
    s = s.substring(0, length);
    length -= s.length;
    var pad = '';
    while (pad.length < length) { 
        pad += ' ';
    }
    return (s + pad);
}


/*******************************************************************************
 * UPLOAD - AJAX IFRAME METHOD (AIM)
 * http://www.webtoolkit.info
 */

var AIM = {
    frame : function(c) {
        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="' + n + '" name="' + n + '" onload="AIM.loaded(\'' + n + '\')"></iframe>';
        document.body.appendChild(d);
        var i = document.getElementById(n);
        if (c && typeof(c.onComplete)=='function') {
            i.onComplete = c.onComplete;
        }
        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        }
        else {
            return true;
        }
    },

    loaded : function(id) {
        var d;
        var i = document.getElementById(id);
        if (i.contentDocument) {
            d = i.contentDocument;
        }
        else if (i.contentWindow) {
            d = i.contentWindow.document;
        }
        else {
            d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }
        if (typeof(i.onComplete) == 'function') {
            if (ie) {
                i.onComplete(d.body.innerHTML);
            }
            else {
                i.onComplete(d.body.textContent);
            }
        }
    }
}

/*******************************************************************************
 * UPLOAD
 * Funções auxiliares, executas antes de depois da transmissão do arquivo.
 */
function beforeUpload() {
    return true;
}

function afterUpload(response) {
    e$('uploadResult').innerHTML = response;
}

/*******************************************************************************
 * STYLE CHANGE
 */
function changeStyle(ruleName, property, value) {
    if (!document.styleSheets) return;
    for (var s=document.styleSheets.length; s>=0; --s) {
        var theRules;
        try {
            if (document.styleSheets[s].cssRules) {
                theRules = document.styleSheets[s].cssRules
            }
            if (document.styleSheets[s].rules) {
                theRules = document.styleSheets[s].rules
            }
        }
        catch (e) {}
        //        alert(s);
        try {
            var theRule;
            for (var r=0; r<theRules.length; r++) {
                theRule = theRules[r];
                if (theRule.selectorText==ruleName) {
                    theRule.style[property] = value;
                    return;
                }
            }
        }
        catch (e2) {}
    }
}

/*******************************************************************************
 * INTEGRAÇÃO COM O SISTEMA
 */

/**
 * Mostra a identificação de registro apagado.
 */
function showDeleted(deleteTagName) {
    if (this.idStatus=='deleted') {
        e$(deleteTagName).value = e$(deleteTagName).value.replace('\u25cf', '\u25cb');
        this.idStatus = 'normal';
    }
    else {
        e$(deleteTagName).value = e$(deleteTagName).value.replace('\u25cb', '\u25cf');
        this.idStatus = 'deleted';
    }
}

/**
 * Muda entre a apresentação de dados pessoa física e pessoa jurídica.
 */
function mostraTipoDePessoa(tagName) {
    if(e$(tagName).checked){
        changeStyle('.pessoaFisica', 'display', 'none');
        changeStyle('.pessoaJuridica', 'display', 'table-row');
    }
    else{
        changeStyle('.pessoaFisica', 'display', 'table-row');
        changeStyle('.pessoaJuridica', 'display', 'none');
    }
}

//
///*******************************************************************************
// * Para usar o ENTER como TAB.
// */
//if (window.captureEvents) { // ff
//    window.captureEvents(Event.KEYUP);
//    window.onkeyup=processKey;
//}
//else { // ie
//    document.onkeyup=processKey;
//}
//function processKey(e){
//    var evento;
//    var tag;
//    if ((typeof event=='undefined')) { // ff
//        evento=e;
//        tag=e.target;
//    }
//    else { // ie
//        evento=event;
//        tag=event.srcElement;
//    }
//    if (evento.keyCode==13) {
//        processEnterKey(tag);
//    }
//}
//function processEnterKey(tag) {
//    if (tag.type!='textarea') {
//        tag=tag.nextSibling;
//        while (tag!=null) {
//            if (tag.type=='text') {
//                tag.focus();
//                break;
//            }
//            else {
//                tag=tag.nextSibling;
//            }
//        }
//    }
//}

