
	// to_id -> chat user receive id

	var chat_refresh_time_inactive	= 3000
	var chat_refresh_time_active 	= 800
	var user_online_refresh_time	= 6000
	var open_box = new Array()
	var chat_name = ''
	var chat_id   = 0
	var chat_last_time = 0
	
	var chat_file = 'index.server.php'
	
	var chat_user_online = null

	$(document).ready(function(){	
		$("body").append( '<div id="chat_box" align="center"><div id="chat_box_area"></div></div>' )
		$("body").append( '<div id="user_online"><div class="close"><a href="javascript:showHideChat();">x</a></div><div class="user_list"></div></div>' )
		var first_time = true
		getUserOnline()
		chatRefresh( first_time )
	});

	function getUserOnline( ){
		$.getJSON( chat_file, {module:'chat', cp:'user/online'}, function(data){
			if( data['user_online'] && data['user_online'].length > 0 ){
				if( !chat_user_online ){
					$("body").append( '<div id="chat"><a href="javascript:showHideChat();void(0);">Chat (<span id="chatNUserOneline">0</span>)</a></div>' )
					chat_user_online = true
				}
				user_online = data['user_online']
				var html_user_online = ''
				for( i in user_online )
					html_user_online += '<a href="javascript:chatCreateBox(\''+user_online[i]['name']+'\','+user_online[i]['user_where_is_id']+');showHideChat();">'+user_online[i]['name']+'</a>'		
				
				$('#user_online>.user_list').html( html_user_online );
				$('#chatNUserOneline').html( user_online.length )
			}
			else
				chat_user_online = false
				
			setTimeout( "getUserOnline()", user_online_refresh_time );
		});
	}
	
	function showHideChat(){
		if($('#user_online').css('display')=='none') 
			$('#user_online').fadeIn(); 
		else 
			$('#user_online').fadeOut();
	}

	// get the list of active chat
	function chatRefresh( first_time ){
		$.getJSON( chat_file, { module:'chat', cp: 'chat/refresh', last_time: chat_last_time }, function( data ){
			if( data['return'] ){

				chat_name = data['chat_name']
				chat_id = data['chat_id']

				if( data['chat'] ){
					chat_last_time = data['last_time']

					for( to_id in data['chat'] ){
						var time = data['chat'][to_id]['t']
						var name = data['chat'][to_id]['n']
	
						if( !open_box[to_id] ){
							chatCreateBox( name, to_id )
							first_time = 1
						}
						else if( !open_box[to_id] || time != open_box[to_id]['t'] )
							chatGet( to_id, first_time )
					}					
				}
			}
			
			var data = new Date()
			var time = data.getTime() / 1000
			if( time - chat_last_time > 60 )
				setTimeout( "chatRefresh()", chat_refresh_time_inactive );
			else
				setTimeout( "chatRefresh()", chat_refresh_time_active );
		})
	}




	// create the chat box
	function chatCreateBox( name, to_id ){
		// if there's no chatbox i create one
		if( !$("#chat_" + to_id ).html() ){
			$.getJSON( chat_file, { module:'chat', cp: 'chat/open', to_id: to_id }, function( data ){
				if( data['return'] ){
					var name = data['name']
					var last_time = data['last_time']

					open_box[to_id] 	 = new Array()
					open_box[to_id]['n'] = name
					open_box[to_id]['t'] = last_time
					open_box[to_id]['lt'] = 0
					open_box[to_id]['ls'] = 0
					
					var html = '<div class="chat_box" id="chat_'+to_id+'"><div class="chat_box_info"></div><div class="chat_box_header"><div class="chat_box_name" onclick="chatMinimize('+to_id+')">'+name+'</div> <div class="chat_box_tools"><a href="admin.php?module=user#guest='+to_id+'" onmouseover="chatUserInfo('+to_id+')">?</a> <a href="javascript:chatMinimize('+to_id+');">_</a> <a href="javascript:chatClose('+to_id+')">x</a></div></div><div class="chat_box_msg"></div><div class="chat_box_textarea"><textarea onkeydown="chatOnKeyDown(event,this,'+to_id+');"></textarea></div></div>';
					$("#chat_box_area").append( html );

					organizeChatBox()
					chatGet( to_id, 1 )
				}
			})
			
		}
	}

	
	function organizeChatBox(){
		var i = 0
		var chat_box = $(".chat_box")
		var width = 0
		for( var toId in open_box ){
			$("#chat_"+toId).css("right", width + 100 )
			width += parseInt($("#chat_"+toId).width() ) + 10
			i++
		}
	}


	// read all msg of one active chat
	function chatGet( to_id, first_time ){
		
		var last_time = !first_time ? open_box[to_id]['t'] : 0;
		
		$.getJSON( chat_file, { module:'chat', cp: 'chat/get', to_id: to_id, last_time: last_time }, function( data ){
			if( data['chat'] ){
				var html = ""
				var name = open_box[to_id] ? open_box[to_id]['n'] : null
				
				for( var i=0; i < data['chat'].length; i++ ){
					
					var chat = data['chat'][i]
					var chat_to_name = to_id == chat['t'] ? chat_name : name
						
					html += chatAddMsg( to_id, chat_to_name , chat )
					
				}
				open_box[to_id]['t'] = chat['s']

				if( last_time )
					$('#chat_'+to_id+'>.chat_box_msg').append( html )
				else
					$('#chat_'+to_id+'>.chat_box_msg').html( html )
					
				var h = $('#chat_'+to_id+'>.chat_box_msg').height()
				var sh = $('#chat_'+to_id+'>.chat_box_msg').attr("scrollHeight")
				var sp = $('#chat_'+to_id+'>.chat_box_msg').scrollTop()
				var offset = ( sh - h )

				if( !$('#chat_'+to_id).attr("onmouseover") )
					$('#chat_'+to_id).attr( "onmouseover", "$('#chat_box_"+to_id+">.chat_box_header').removeClass('chat_box_header_new')" )				

				if( offset - sp <= 50 || first_time ){
					$('#chat_'+to_id+'>.chat_box_msg').animate({scrollTop:999999})
					$('#chat_'+to_id+'>.chat_box_header').addClass( 'chat_box_header_new' )
				}
			}
		})
	}
	
	
	
	// write msg in the chatBox
	function chatAddMsg( to_id, name, chat ){

		var html = ''
		html += '<div class="chat_box_msg_div">'
		if( open_box[to_id]['lt'] != chat['t'] ){	
			html += '<div class="chat_box_msg_space"></div>';
			//you sent the msg
			if( chat['t'] == to_id )
				html += '<span class="chat_box_from">' + name + ': </span>'
			else
				html += '<span class="chat_box_to">' + name + ': </span>'

			if( chat['s'] )
				var date = chat_time_format( chat['s'] )
		}
		
		if( chat['s'] && ( chat['s'] - open_box[to_id]['ls'] ) > 60*3 )
			var date = chat_time_format( chat['s'] )

			
		open_box[to_id]['lt'] = chat['t']
		open_box[to_id]['ls'] = chat['s']
		
		html += '<span class="chat_box_msg_text">' + chat['m'] + '</span>'
		if( date )
			html += '<div class="chat_box_msg_time">' + date + '</div>'
		html += '</div>'
		return html
	}
	
	
	
	
	// send a msg
	function chatMsg( to_id, msg ){
	
	// write the msg
		var chat = new Array()
		chat['m'] = msg
		chat['t'] = to_id

		html = chatAddMsg( to_id, chat_name, chat )

		$('#chat_'+to_id+'>.chat_box_msg').append( html )
			
		var h = $('#chat_'+to_id+'>.chat_box_msg').height()
		var sh = $('#chat_'+to_id+'>.chat_box_msg').attr("scrollHeight")
		var sp = $('#chat_'+to_id+'>.chat_box_msg').scrollTop()
		var offset = ( sh - h )

		if( !$('#chat_'+to_id).attr("onmouseover") )
			$('#chat_'+to_id).attr( "onmouseover", "$('#chat_box_"+to_id+">.chat_box_header').removeClass('chat_box_header_new')" )				

		if( offset - sp <= 50 || first_time ){
			$('#chat_'+to_id+'>.chat_box_msg').animate({scrollTop:999999})
			$('#chat_'+to_id+'>.chat_box_header').addClass( 'chat_box_header_new' )
		}
	//!write the msg
		
		$.getJSON( chat_file, { module:'chat', cp: 'chat/msg', to_id: to_id, msg: msg }, function( data ){
			if( data['return'] ){
				chat_name = data['chat_name']
				open_box[to_id]['n'] = data['name']
				open_box[to_id]['t'] = data['time']-1
			}
		})
	}
	
	
	
	// read when the textarea is pressed
	function chatOnKeyDown( event, obj, to_id ){
		if(event.keyCode == 13 && event.shiftKey == 0)  {
			chatMsg( to_id, obj.value )
			obj.value = ""
			obj.blur()
		}
	}

	
	
	function chatMinimize( id ){
		if( $('#chat_'+id+'>.chat_box_msg').css("display") == 'none' ){
			$('#chat_'+id+'>.chat_box_msg').show()
			$('#chat_'+id+'>.chat_box_textarea').show()
			$('#chat_'+id+'>.chat_box_header>.chat_box_name').html( open_box[id]['n'] )
			$('#chat_'+id ).css( 'width', 220 )
			
		}
		else{
			$('#chat_'+id ).css( 'width', 120 )
			$('#chat_'+id+'>.chat_box_msg').hide()
			$('#chat_'+id+'>.chat_box_textarea').hide()
			$('#chat_'+id+'>.chat_box_header>.chat_box_name').html( cut( open_box[id]['n'], 7 ) )
		}
		
		organizeChatBox()
	}
	
	function chatClose( to_id ){
		$('#chat_'+to_id).hide()
		$('#chat_'+to_id).remove()
		delete open_box[to_id]		
		organizeChatBox()
		$.get( chat_file, { module:'chat', cp: 'chat/close', to_id: to_id } )
	}
	
	function debug( html ){
		$("#debug").append( html + ' <br>' )
	}
	
	function chatUserInfo( to_id ){
		$.getJSON( chat_file, {module:'chat', cp: 'user/info', to_id: to_id }, function( data ){
			if( data['user_info'] ){
				var user = data['user_info'];
				var html = '<p><b>'+user.name+'</b></p>'
				html += '<p><a href="index.php?'+user.url+'">index.php?'+user.url+'</a></p>'

				$('#chat_'+to_id+'>.chat_box_info').html( html )
				$('#chat_'+to_id+'>.chat_box_info').fadeIn()
			}
		});
	}
	
	function chatUserInfoClose( to_id ){
		$('#chat_'+to_id+'>.chat_box_info').fadeOut()
	}
	
	
	
	
	function chat_time_format( time ){
		var dt = new Date( time * 1000 );
		var hour = dt.getHours()
		var min = dt.getMinutes()
		
		if( hour > 12 ){
			hour = (hour-12)
			var daylight = 'PM'
		}
		else
			var daylight = 'AM'
			
		
		if( hour < 10 )
			hour = "0" + hour
		if( min < 10 )
			min = "0" + min
			
		return hour + ":" + min + " " + daylight
	}
