var resolveds = new Object();

function chatReload() {    
    executeActionNull("ChatController", "check", function(retorno) {
        if(retorno.sucess) {
            if(retorno.entity!=undefined) {                
                if(retorno.entity.presencas!=undefined && retorno.entity.temPresenca=="true") {
                    var presencas = JSON.parse(retorno.entity.presencas);
                    var div= document.getElementById("users");
                    var sele =''; //<select id="usuario" name="usuario" size="5">';
                    for(var i=0; i<presencas.length; i++) {
                        sele += '<div  onmouseover="this.style.backgroundColor = \'#78844F\';"  onmouseout="this.style.backgroundColor =\'#FFFFFF\';"  style="display : block; margin : 5px;" onclick="showChatWindow(\'' + presencas[i] + '\',\'' + resolveName(presencas[i]) + '\')">' + resolveName(presencas[i]) + '</div>';
                    }
                    //sele += '</select>';
                    div.innerHTML=sele;
                }
                if(retorno.entity.conversas!=undefined && retorno.entity.temConversa=="true") { 
                    var conversas = JSON.parse(retorno.entity.conversas);
                     for(var j=0; j<conversas.length; j++) {
                      var from = conversas[j].substring(0,conversas[j].indexOf(":")) ;                      
                      var msg = conversas[j].substring(conversas[j].indexOf(":")+1);
                      _chat_recivemsg(from, resolveName(from), msg);
                    }
                }
            }
        }        
        chatReload();
    });
}

function sendMsg() {
    var fElements = new Array();
    var msg = document.getElementById('msg');
    var usuario = document.getElementById('usuario');

    fElements.push(usuario);
    fElements.push(msg);
    var params = fieldsToObject(fElements);
    
    executeActionParams("ChatController", "sendMsg", params, function(retorno) {
        if(retorno.sucess) {
            msg.value='';            
        } else {
            alert(retorno.message);
        }
        msg.focus();
    });    
}

function resolveName(name) {
  if(resolveds[''+name] == undefined) {
    ajaxRequestInternalSync('resolveName.jsp?ra='+name,'', function(retorno,sucesso) {
        if(sucesso) {
          resolveds[''+name] = retorno;
        }
    })  
  }
  if(resolveds[''+name] == undefined) {
      for(var i=0; i<10000; i++) {          
          var a = new Object();
      }
  }
  return resolveds[''+name];
}


var chatContainerId = 'chatContainer';

function showChatWindow(username, fullname) {
        var chatWindow = document.getElementById('chatWindow_' + username);
        if(chatWindow!=undefined) {
                chatWindow.style.display = '';
        } else {
                _createChatWindow(username, fullname);
        }
}

function _createChatWindow(username, fullname) {
        var window = '';
        window += '<div class="chatWindow" id="chatWindow_' + username + '" style="height: 435px;" >\n';
        window += '<div class="chat_back" style="display : none">\n';
        window += '</div>\n';


        window += '<div class="chat_topo">\n';
        window += '<table width="100%" cellpadding="3">\n';
        window += '<tr>\n';
        window += '<td width="13" align="center">\n';
        window += '<img src="images/chat_topo_icon.png" />\n';
        window += '</td>\n';
        window += '<td style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;">\n';
        window += fullname + '\n';
        window += '</td>\n';
        window += '<td width="14" align="center">\n';
        window += '<img src="images/chat_topo_minimize.png"  onclick="javascript: chatWindow_minimize(\'' + username + '\');" />\n';
        window += '</td>\n';
        window += '<td width="14" align="center">\n';
        window += '<img src="images/chat_topo_close.png" onclick="javascript: chatWindow_close(\'' + username + '\');"  />\n';
        window += '</td>\n';
        window += '</tr>\n';
        window += '</table>\n';
        window += '</div>\n';
        window += '<div class="chat_mensagens">\n';
        window += '<table>\n';
        window += '<tr>\n';
        window += '<td>\n';
        window += '<textarea style="height: 365px; width: 315px; border:none;" id="chatArea_' + username + '" readonly="readonly"></textarea>\n';
        window += '</td>\n';
        window += '</tr>\n';
        window += '</table>\n';
        window += '</div>\n';
        window += '<div class="chat_editor">\n';
        window += '<table cellpadding="3" width="100%">\n';
        window += '<tr>\n';
        window += '<td>\n';
        window += '<input type="hidden" id="username_' + username + '" name="usuario" value="' + username + '" style="width:100%; height:20px;" />\n';
        window += '<input type="text" id="chatText_' + username + '" name="msg" style="width:100%; height:20px;" />\n';
        window += '</td>\n';
        window += '<td width="60" align="center">\n';
        window += '<input type="button" onclick="javascript: chat_sendmsg(\''+ username +'\');" value="Enviar"/>\n';
        window += '</td>\n';
        window += '</tr>\n';
        window += '</table>\n';
        window += '</div>\n';
        window += '</div>\n';
        document.getElementById(chatContainerId).innerHTML += window;
}

function chatWindow_close(chatWindowId) {
        var chatWindow = document.getElementById('chatWindow_' + chatWindowId);
        //chatWindow.parentNode.removeChild(chatWindow);
        chatWindow.style.display = 'none';
}

function chatWindow_minimize(chatWindowId) {
        var cw = document.getElementById('chatWindow_' + chatWindowId);
        var els = cw.childNodes;

        if(cw.minimized == true) {
                cw.minimized = false;
        } else {
                cw.minimized = true;
        }

        for(var i=0; i<els.length; i++) {
                if(els[i].tagName == 'DIV') {
                        if(els[i].className == 'chat_mensagens' || els[i].className == 'chat_editor') {
                                els[i].style.display = cw.minimized ? 'none' : '';
                        } else if(els[i].className == 'chat_back') {
                                els[i].style.display = cw.minimized ? '' : 'none';
                        }
                }
        }
}

/*function chat_sendmsg(username) {
        var msgEl = document.getElementById('chatText_' + username);
        if(msgEl.value != '') {
                _chat_sendmsg(username , msgEl.value);
                msgEl.value = '';
        }
}*/

function chat_sendmsg(username) {
    var fElements = new Array();
    var user = document.getElementById('username_' + username);
    var msg = document.getElementById('chatText_' + username);

    fElements.push(user);
    fElements.push(msg);
    var params = fieldsToObject(fElements);
    
    executeActionParams("ChatController", "sendMsg", params, function(retorno) {
        if(retorno.sucess) {
            msg.value='';            
        } else {
            alert(retorno.message);
        }
        msg.focus();
    });    
}


function _chat_recivemsg(username, fullname, msg) {
        showChatWindow(username, fullname);
        document.getElementById('chatArea_' + username).innerHTML += msg + '\n\n';
}

function fieldsToObject(elementos) {
    var retorno = new Object();
    for(var i=0; i < elementos.length; i++) {
        if((elementos[i].name != undefined)&&(elementos[i].name!='')&&(elementos[i].name.indexOf('$toString')<0)) {
            if(elementos[i].type != 'checkbox') {
                if(getStyle(elementos[i], 'text-transform')=='uppercase') {
                    retorno[elementos[i].name] = elementos[i].value.toUpperCase();
                } else {
                    retorno[elementos[i].name] = elementos[i].value;
                }
            }else {
                retorno[elementos[i].name] = elementos[i].checked;
            }
        }
    }
    return retorno;
}


function executeActionParams(controllerVar, action, params, retFunction) {    
    var sendObj = new Object();
    sendObj.action = action;
    sendObj.controller = controllerVar;
    sendObj.params = params;
    var sendData = JSON.stringify(sendObj);
    ajaxRequest("../../RequestServlet", sendData , retFunction, action);
}

function getStyle(x,styleProp) 	{
    var y;
    if (x.currentStyle) {
        y = x.currentStyle[styleProp];
    } else if (window.getComputedStyle) {
        y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    }
    return y;
}
