var refreshTimeMsg = 500;
var lastMsgId = 0;
var escCounter = 0;


function setUserBox(box,emitor,receptor,userName){

    var boxUser = $('<form>').attr({'id':'user'+receptor,'class':'box_user'});
    
    
    $(document).keypress(function(event){
        if($('#user'+receptor).attr('class') == 'box_user_on'){
            if(event.keyCode == 13){
                escCounter++;
                if(escCounter == 1){
                    sendMsg(emitor,receptor,userName);
                }else{
                    event.preventDefault();
                }
            }
        }
    });

    box.append(boxUser);
    boxUser.append($('<div>').attr({'id':'comunication'+receptor,'class':'chat-comunication'}));
    boxUser.append($('<textarea>').attr({'id':'message'+receptor,'class':'chat-message'}));

}

//sending message
function sendMsg(emitor,receptor,emitorName){

    var msgZone = $('#message'+receptor);
    var textMsg = msgZone.val();
    
    emitorName = (emitorName)? emitorName : 'Yo';

    var newMsg = $("<div>");
    newMsg.html('<b>'+emitorName+'</b> : '+textMsg);
    $('#comunication'+receptor).append(newMsg);

    setTimeout(function(){ msgZone.val(''); },10);
    
    setTimeout(function(){ escCounter = 0; },100);
    
    scrollTextarea(receptor);
  
    if(emitor == receptor) receptor='0';

    $.post(WEBSITE_PATH+"xml/chat?action=send_msg",{
      'message':textMsg,
      'emitor':emitor,
      'receptor':receptor
    });

    refreshTimeMsg = 1000;

}

//get the message
function getMsg(emitor,receptor){
  
    if($('#user'+emitor).attr('class') == 'box_user_on'){
    
        $('#msg_load').html('Cargando mensages :<img src="'+WEBSITE_PATH+'plugins/chat/images/chat_load.gif" alt="" />');

        param = new Array();
        param[0] = emitor;
        param[1] = receptor;
        var advert = false;

        var msgs = $('#comunication'+emitor).find('div');
      
        if(msgs.length > 0){
            var lastId = 0;
            msgs.each(function(){ 
                if($(this).attr('id').indexOf("msg") != -1) lastId = $(this).attr('id').replace('msg','');
            });
      
            if(receptor=='all'){
                var ajax = WEBSITE_PATH+"xml/chat?action=get_all_msg&admin="+emitor+"&last_id="+lastId;
            }else{
                var advert = true;
                var ajax = WEBSITE_PATH+"xml/chat?action=get_msg&emitor="+emitor+"&receptor="+receptor+"&last_id="+lastId;
            }
        }else{
            if(receptor=='all'){
                var ajax = WEBSITE_PATH+"xml/chat?action=get_all_comunication&last_id="+lastMsgId;
            }else{
                $('comunication'+emitor).innerHTML = '';
                var ajax = WEBSITE_PATH+"xml/chat?action=get_comunication&emitor="+emitor+"&receptor="+receptor+"&last_id=0";    
            }
        }
      

        $.ajax({
          type:'GET',
          url: ajax,
          success: function(data){
              setMsg(data,param,advert)
          },
          dataType: 'xml'
        });
    
    }

}

function setMsg(data,param,advert){

    var emitor = param[0];
    var receptor = param[1];
  
    if(!refreshTimeMsg)refreshTimeMsg = 1000;
    else refreshTimeMsg += 100;

    if($('#user'+emitor).attr('class') == 'box_user_on'){
        setTimeout(function(){$('#msg_load').html('Cargando mensages :')},1000);
        setTimeout(function(){getMsg(emitor,receptor)},refreshTimeMsg);
    }
 
    refreshTimeMsg = (refreshTimeMsg>5000)? 5000 : refreshTimeMsg;

    var xml_doc = data;
     
    if($(xml_doc).find('message').first()){

        var msg = $(xml_doc).find('message');
    
        //alert(msg.length);
        if(msg.length>0){
            refreshTimeMsg = 5000;
            if(receptor=='all'){
                //alert('new message');
                msg.each(function(){
                    lastMsgId = $(this).find('id_msg').text();
                });
            }else{
                msg.each(function(){
          
                    var idMsg = $(this).find('id_msg').text();
                    var textMsg = $(this).find('text').text();
                    var emitorName = $(this).find('emitor').text();

                    if(!$('#msg'+idMsg).html()){
                    
                        emitorName = (emitorName.match(/\[[0-9-\s:]*\]/))? 'Yo' : emitorName;

                        var newMsg = $('<div>').attr({'id':'msg'+idMsg});
                        newMsg.html('<b>'+emitorName+'</b> : '+textMsg);
                        $('#comunication'+emitor).append(newMsg);
                        if(advert && !window.isActive) alert('Nuevo mensaje');
          
                    }

                    

                });        
            }
            
            scrollTextarea(emitor);
            
        } 
    }
}

//change name
function changeUserName(numUser,adminId){  
  var newName = $('#user_name'+numUser).val();
  $('#user_name'+numUser).val(newName);
  $.post("xml/chat?action=change_user_name&user="+numUser,{'name':newName});
  refreshTimeMsg = 500; 
  $('#chat').html('');
  $.ajax({
    type: 'GET',
    url: 'xml/chat_session',
    success: chat_user,
    dataType: 'xml'
  });
}

function scrollTextarea(idUser){
  //alert('scroll');
  var comunicationBox = $('#comunication'+idUser);
  if(comunicationBox[0]){
	newScrollTop = ((comunicationBox[0].scrollHeight - comunicationBox.height())+10);
	//alert(newScrollTop);
	if(newScrollTop>0){
	 comunicationBox.scrollTop(newScrollTop);
	}
	}
}

