
function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
function write_private_chat(forr,meno){
    mesg=$('#chat_in_'+forr).val().replace(/&/,"{|amp|}");
    mesg=mesg.replace(/\s*$/,'').replace(/^\s*/,'');
    if(mesg!=''){
        $('#chat_in_'+forr).val('');
        var today=new Date();
        var h=today.getHours();
        var m=today.getMinutes();
        var s=today.getSeconds();
        // add a zero in front of numbers<10
        m=checkTime(m);
        s=checkTime(s);
        cas=h+":"+m+":"+s;
        var data = {
          mesg:mesg,
          forr:forr
        }
        $.ajax({
                type: "POST",
                url: homelink + "/chat/write_private_chat",
                data: data,
                dataType: 'json',
                success: function(msg){
                          $('#chat_'+forr).prepend("<span><span class='chatTime'>"+cas+"</span> "+moj_nick+": "+mesg+"</span><br />");
                         }
              });
        
        $('#chat_in_'+forr).focus();
    }
}

function get_history(forr){
    $.ajax({
            type: "POST",
            url: homelink + "/other/get_history",
            data: "&forr="+forr,
            success: function(msg){
                      $('#chat_'+forr).html(msg);
                     }
          });
}

var opened=new Array();
var offsetTop = 30;
var offsetLeft = 200;

function isWindowOpened(userId){
   if(opened[""+userId]==true) return true;
   return false;
}

function setWindowOpened(userId){
  opened[""+userId]=true;
}

function setWindowClosed(userId){
  opened[""+userId]=false;
}
function openedLength(){
    a='';
    l=0;
    for(var i in opened){
    a+=''+opened[i]+' i je '+i+'\n';
        if(opened[i]==true) l++;
    }
    return l;
}


function restoreWindows(){
	
	
		var chatWindows = windowString.split("|");
		  var patt1=new RegExp("(.*?);(.*?);(.*?);(.*?)");
		  
		  if(GetCookie('sidebarOpened')=='true') $('#sideBar').show();
		  
		  for(var i in chatWindows){
		  
		    var w = chatWindows[i];
		    if(w!=''){  
		        data = w.split(";");
		        newChatWindow(data[0],""+data[3]+"");
		    }
		  }
  
  
}


function newChatWindow(forr,meno){
	if(isWindowOpened(forr)==false){
    newWindowCookie = windowString;
    var patt1=new RegExp(forr+";(.*?);(.*?);");
    var top;
    var left;
    if(newWindowCookie.match(patt1)){
      var pos = patt1.exec(newWindowCookie);
      top = pos[1];
      left = pos[2];
    } else{
      top = openedLength()*40+offsetTop;
      left = openedLength()*20+offsetLeft;
    }
    
      
      setWindowOpened(forr);
      $("<div class='chat_place' id='chat_w_"+forr+"' onclick='cancelTitleBlink()'>").load().dialog({
                        title: meno,
                        width: 250,
                        height: 230
        });
      $("#chat_w_"+forr+"").append("<div class='chat_msg'><input onclick='cancelTitleBlink();' id='chat_in_"+forr+"' style='width:70%' class='chat_in' onkeydown=\"if (event.keyCode == 13) document.getElementById('chat_butt_"+forr+"').click()\"/><input id='chat_butt_"+forr+"' type='button' value='Pošli' onclick=\"write_private_chat("+forr+",'"+meno+"')\" /><div id='chat_"+forr+"'></div></div>").parent().css('top',top+'px').css('left',left+'px');
      $("#chat_in_"+forr).livequery(
    		  function(){
    			  $(this).focus(
    					  function() {
    						  $(this).addClass('focused');
    					  }
    			  );
    			  $(this).blur(
    					  function(){
    						  $(this).removeClass('focused');
    					  }
    			  );
    			  
    		  }
      );
      getChatHistory(forr,5);
    }
}
function getChatHistory(forr,limit){
	$.ajax({
        type: 'POST',
        url: homelink + '/Chat/getChatHistory',
        data: 'for='+forr+'&limit='+limit,
        success: function(msg){
          $('#chat_'+forr).append(msg);
        }
		});
}
	

    
function write_public_chat(){

  $.ajax({
              type: 'POST',
              url: homelink + '/Chat/write_public_chat',
              data: 'msg='+$('#input').val(),
              success: function(msg){
                getChat();
                $('#input').val("").focus();
              }
  });
  
}
var t=null;

function generateWindowsString(){
  var positions = getWindowsPositions();
  var newWindowCookie='';
  for(var i in positions){
    var w = positions[i];
    var name = $('#ui-dialog-title-chat_w_'+w.id).text();
    newWindowCookie+="|"+w.id+";"+w.top+";"+w.left+";"+name;
  }
  return newWindowCookie;
  //SetCookie('windowCookie',newWindowCookie,'','/');
}

function storeWindowsServer() {
	windowString = generateWindowsString();
	var data = {
			windowString: windowString
	}
	
	$.ajax({
        type: "POST",
        url: homelink + "/chat/storeWindowsServer",
        data: data,
        dataType: 'json'
      });
	
}

function getWindowsPositions(){
  var result ={};
  
  var i = 0;
  $('.chat_place').each(function(){
    
      var id = ""+$(this).attr('id').replace('chat_w_','');
      result[i] = {
        id: id,
        top: $(this).parent().css('top').replace('px',''),
        left: $(this).parent().css('left').replace('px','')
      }
      i++;
  });
  return result;
}

function getChat(){
    var data ={
      publicChat: publicChat,
      windowString: generateWindowsString()
    }
    $.ajax({
              type: 'POST',
              url: homelink + '/Chat/get_chat',
              dataType: 'json',
              data: data,
              success: function(msg){
                var code="";
                if(publicChat) {
                	$('#chat_place').html('');
                	var ssss='';
                	for(var i in msg.publicChat) {
                		line = msg.publicChat[i];
                		ssss+="<div><span style='font-size:7pt'>"+line.datum+"</span>: <span style='color:green;'>"+line.od+"</span>: "+line.text+"</div>";	
                	}
                	$('#chat_place').html(ssss);
                	
                }
                for(var i in msg.online) {
                    data = msg.online[i];
                    
                    if(isWindowOpened(data.id)) {
                      code+="<span style='color:green'>"+data.meno+"</span><br />";
                    } else {
                      code+="<a href='#' onclick=\"newChatWindow("+data.id+",'"+data.meno+"');return false;\">"+data.meno+"</a><br>";
                    }
                
                }
                $('#online').html("<b>Online sú:</b><br />"+code);

                for(var i in msg.osobne){
                    var data = msg.osobne[i];
                    if(isWindowOpened(data.from)==true){
                    }
                    else{
                        newChatWindow(data.from,data.meno);
                        setTitleBlink();
                    }
                    if(!$("#chat_in_"+data.from).hasClass('focused')) {
                    	setTitleBlink();
                    }
                    $('#chat_'+data.from).prepend("<span style='color:green'>"+data.text+"</span>");
                }
                
                  clearTimeout(t);
                  t=setTimeout("getChat()",5000);
                  //storeWindowsPosition();
              }
  });
}

var blinkedSwith = false;
var blinking = false;
var blinkTimer = null;
function setTitleBlink() {
	if(blinking) {
		return;
	}
	
	if(blinkedSwith) $('title').text('Dokan chat - Nová správa');
	else $('title').text(title);
	blinkedSwith = !blinkedSwith;
	//blinking = true;
	clearTimeout(blinkTimer);
	blinkTimer = setTimeout('setTitleBlink()', 1000)
}

function cancelTitleBlink() {
	clearTimeout(blinkTimer);
	blinking = false;
	$('title').text(title);
}

