//window onload
jQuery(document).ready(function(){
	jQuery('#chat_content').keydown(function(event){
		if(event.ctrlKey && event.keyCode==13){
			//you can not enter more than 4 lines for message
			if(jQuery(this).val().split("\n").length > max_input_line -1){
				alert('Message size has to be less than 4 lines of words') ;
				return false ;
			}
			
			jQuery(this).attr('value', jQuery(this).val() + "\n ");
			jQuery(this).focus();
		}else if(event.keyCode == 13){
			send_chat_content('chat_content') ;
			return false ;
		}
	}) ;
	jQuery('#private_chat_content').keydown(function(event){
		if(event.ctrlKey && event.keyCode==13){
			//you can not enter more than 4 lines for message
			if(jQuery(this).val().split("\n").length > max_input_line -1){
				alert('Message size has to be less than 4 lines of words') ;
				return false ;
			}
			
			jQuery(this).attr('value', jQuery(this).val() + "\n ");
			jQuery(this).focus();
		}else if(event.keyCode == 13){
			send_private_chat_content(jQuery('#private_chat_window').children('#toNick').html()) ;
			return false ;
		}
	})
	jQuery('#private_chat_send_bt').click(function(){
		send_private_chat_content(jQuery('#private_chat_window').children('#toNick').html()) ;
	}) ;
	if(myNick != ''){
		query_online_user_list() ;
		get_chat_content() ;
		query_private_chat_message() ;
		//Set timer
		chat_message_time = setInterval('query_online_user_list()', update_online_interval) ;
		online_time = setInterval('get_chat_content()', update_chat_message) ;
		private_message_query_time = setInterval("query_private_chat_message()", update_chat_message) ;
	}else{
		//get the guest number 
		if(is_empty(get_cookie('guest_name'))){
			jQuery.ajax({
				url:'chat_query_online_guest_list.php?'+Math.random(),
				type:'GET',
				dataType:'html',
				success:function(data)
				{
					var num = parseInt(eval(data)) ;
					myNick = 'Guest' + (num+1) ;
					set_cookie('guest_name', myNick) ;
					
					//query 
					query_online_user_list() ;
					get_chat_content() ;
					query_private_chat_message() ;
					//Set timer
					chat_message_time = setInterval('query_online_user_list()', update_online_interval) ;
					online_time = setInterval('get_chat_content()', update_chat_message) ;
					private_message_query_time = setInterval("query_private_chat_message()", update_chat_message) ;
				}
			}) ;
		}else{
			myNick = get_cookie('guest_name') ;
			//query 
			query_online_user_list() ;
			get_chat_content() ;
			//Set timer
			chat_message_time = setInterval('query_online_user_list()', update_online_interval) ;
			online_time = setInterval('get_chat_content()', update_chat_message) ;
		}
	}
	//Drag settings
	Drag.init(document.getElementById("private_chat_handle"), document.getElementById("private_chat_window"));
}) ;
//Insert face picture into text field
function insert_face(face, id){
	jQuery('#'+id).setCaret();
	jQuery('#'+id).insertAtCaret('/:'+face+':'); 
	jQuery('#'+id).focus() ;
}
function clear_content(id){
	jQuery('#' + id).attr('value',' ') ;
	jQuery('#' + id).focus() ;
}
//This function hides/shows sidebar 
function toggle_sidebar(id){
	if(jQuery('#toggle_bt').attr('title') == 'Close sidebar'){
		jQuery('#'+id).width('99%') ;
		jQuery('#sidebar').width('1%') ;
		//jQuery('#sidebar').css({'background-color':'#000000', 'border-top':'2px solid #000','border-bottom':'2px solid #000'}) ;
		
		jQuery('#online_user_list').hide() ;
		jQuery('#toggle_bt').attr('src', 'images/chat/open.gif') ;
		jQuery('#toggle_bt').attr('title', 'Open sidebar') ;
		
		//Close timer
		clearInterval(online_time);
		clearInterval(chat_message_time);
		clearInterval(query_private_chat_message) ;
	}else{
		jQuery('#'+id).width('80%') ;
		jQuery('#sidebar').width('20%') ;
		//jQuery('#sidebar').css({'background-color':'#cccccc', 'border-top':'2px solid #ccc','border-bottom':'2px solid #ccc'}) ;
		jQuery('#online_user_list').show() ;
		jQuery('#toggle_bt').attr('src', 'images/chat/close.gif') ;
		jQuery('#toggle_bt').attr('title', 'Close sidebar') ;
		
		query_online_user_list() ;
		get_chat_content() ;
		//Set timer
		online_time = setInterval('get_chat_content()', update_chat_message) ;
		chat_message_time = setInterval('query_online_user_list()', update_online_interval) ;
		private_message_query_time = setInterval("query_private_chat_message()", update_chat_message) ;
	}
}

function query_online_user_list(){
	jQuery.ajax({
		url:'chat_query_online_user_list.php?user_id='+Math.random()+'&myNick=' + myNick+'&chat_mode='+chat_mode+'&chat_room='+chat_room+'&myID='+myID,
		type:'GET',
		dataType:'html',
		success:function(data)
		{
			//clear data
			if(is_empty(data)){return ;}
			jQuery('#profile_box').hide() ;
			jQuery('#online').empty() ;
			
			
			//Data process
			var online = eval(data) ;
			var new_user = null ;
			var left_user = null ;
			for(var i=0;i<online.length;i++){
				var div = "<div class='user' >" ;
                div += "<div style='float:left'>"+online[i]+"</div>" ;
				if(online[i].match(/guest/i)){
					if(online[i] != myNick){
						//private chat
						div += "<div style='float:right'><img src='images/chat/private_chat.gif' align='absmiddle' hspace='5'" ;
						div += "onclick=\"show_private_chat_window('chat_"+online[i] + "','" + online[i]+ "') ;\" id='chat_"+online[i]+ "' style='cursor:pointer' title=\"Private chat\"/>" ;
						div += "</div>" ;
					}else{
                        div += '<span style="float:right;color:#000">Me</span>' ;
                    }
				}else{
					if(online[i] == myNick){
						//private chat
						div += "<div style='float:right'>" ;
						div += "<img src='images/chat/show_profile.gif' align='absmiddle' " ;
						div += "onclick=\"show_full_profile('" + online[i]+ "') ;\" style='cursor:pointer' title=\"Show "+online[i]+"'s profile\"/>" ;
						div += "</div>" ;
					}else{
						//private chat
						div += "<div style='float:right'><img src='images/chat/private_chat.gif' align='absmiddle' hspace='5'" ;
						div += "onclick=\"show_private_chat_window('chat_"+online[i] + "','" + online[i]+ "') ;\" id='chat_"+online[i]+ "' style='cursor:pointer' title=\"Private chat\"/>" ;
						div += "<img src='images/chat/show_profile.gif' align='absmiddle' " ;
						div += "onclick=\"show_full_profile('" + online[i]+ "') ;\" style='cursor:pointer' title=\"Show "+online[i]+"'s profile\"/>" ;
						div += "</div>" ;
					}
				}
				jQuery('#online').append(div) ; 
				
			}//for	
			//The users just into chatroom
			if(old_online.length > 0 && online.length > 0){
				var new_online = get_new_online(online, old_online) ;
				for(var i=0;i<new_online.length;i++){
					jQuery('#chat_message').prepend('<div style="color:red;border-bottom:1px dotted #ccc ;margin-bottom:2px ;"><img src="images/chat/broadcast.gif" hspace=5/><b>'+new_online[i]+'</b> goes into this chatroom</div>' ) ; 
					//Mark the message line with new_online user as showing
					jQuery('.msg_'+new_online[i]).fadeIn('slow') ;
				}
			}
			//The users just left chatroom
			if(old_online.length > 0 && online.length > 0){
				var left_online = get_left_online(old_online, online) ;
				for(var i=0;i<left_online.length;i++){
					jQuery('#chat_message').prepend('<div style="color:red ;border-bottom:1px dotted #ccc ;margin-bottom:2px ;"><img src="images/chat/broadcast.gif" hspace=5/><b>'+left_online[i]+'</b> have left this chatroom</div>' ) ; 
					//Mark the message line with left_online user as hidden
					jQuery('.msg_'+new_online[i]).fadeOut('slow') ;
				}
			}
			//Save old data
			old_online = online.slice(0) ;
			old_online.length = online.length ;
		}//success
	}) ;
}

function in_online_array(element, online){
	for(var i=0;i<online.length;i++){
		if(element == online[i]){
			return true ;
		}
	}
	
	return false ;
}

function get_new_online(new_online, old_online){
	var _new = new Array() ;
	var k = 0 ;
	for(var i=0;i<new_online.length;i++){
		if(!in_online_array(new_online[i], old_online)){
			_new[k++] = new_online[i];
		}
	}//for
	
	return _new ;
}

function get_left_online(old_online, new_online){
	var _left = new Array() ;
	var k = 0 ;
	for(var i=0;i<old_online.length;i++){
		if(!in_online_array(old_online[i], new_online)){
			_left[k++] = old_online[i] ;
		}
	}//for
	
	return _left ;
}
//Query private live message
function query_private_chat_message(){
	jQuery.ajax({
		url:'query_private_chat_message.php?user_id='+Math.random()+'&myNick=' + myNick,
		type:'GET',
		dataType:'html',
		success:function(data)
		{
			//alert('return='+data ) ;
			if(data == null || data== ''){return ;}
			var msg = eval(data) ;
			if(msg != null && msg != 'null'){
				for(var i=0;i<msg.length;i++){
					jQuery('#chat_' + msg[i].myNick).attr('src', 'images/chat/incoming.gif') ; 
					jQuery('#chat_' + msg[i].myNick).attr('title',  msg[i].myNick+' sent you a message') ; 
				}	
			}
		}
	}) ;
}

//Show slected nick's profile
function show_profile(id, nick){
	toggle_div('profile_box', id, 20, -230) ;
	if(jQuery('#'+id).attr('src').match(/show_profile/i)){
		jQuery('#'+id).attr('src', 'images/chat/bt_close.gif') ;
		jQuery('#'+id).attr('title', 'Show '+nick+'\'s profile') ;
	}else{
		jQuery('#'+id).attr('src', 'images/chat/show_profile.gif') ;
		jQuery('#'+id).attr('title', 'Close window') ;
		return ;
	}
	
	jQuery('#profile_loading').show() ;
	//Ajax request
	jQuery.ajax({
		url:'get_v_profile.php?nick=' + nick,
		type:'GET',
		dataType:'html',
		success:function(data)
		{
			jQuery('#profile_loading').hide() ;
			jQuery('#profile_data').html(data) ;
		}
	}) ;
}
function show_full_profile(nick){
	jQuery('#container').css({visibility:'hidden'}) ;
	jQuery('#show_full_profile').attr('href', 'v_following_bookmarked.php?width=650&height=460&modal=true&username='+nick).click() ;
}
function show_private_chat_window(id, nick){
	jQuery('#container').css({visibility:'hidden'}) ;
	show_div('private_chat_window', id, 20, -500) ;
	jQuery('#'+id).attr('src', 'images/chat/private_chat.gif') ;
	//Get chat message
	jQuery('#private_chat_content').attr('value',' ').focus() ;
	jQuery('#private_chat_window').children('#toNick').html(nick) ;
	jQuery('#private_chat_title').html('<img src="images/chat/private_chat.gif" align="absmiddle" hspace=5/>Private chat with <b style="color:red ;">' + nick + '</b>') ;

	private_topID = 0 ;
	get_private_chat_content(nick) ;
	//Set timer
	private_message_time = window.setInterval(function(){get_private_chat_content(nick) ;}, update_chat_message) ;
	//clear private_message_query_time
	clearInterval(private_message_query_time) ;
}

function close_private_window(id){
	jQuery('#'+id).hide() ;
	jQuery('#container').css({visibility:'visible'}) ;
	jQuery('#chat_'+jQuery('#private_chat_window').children('#toNick').html()).attr('title', 'Private chat with '+jQuery('#private_chat_window').children('#toNick').html()) ;
	clearInterval(private_message_time) ;
	private_message_query_time = setInterval("query_private_chat_message()", update_chat_message) ;
}
//Send my chat content
function send_chat_content(){
	if(is_empty(jQuery('#chat_content').val())){return ;}
	jQuery('#chat_loading').show() ;
	jQuery.ajax({
		url:'get_chat_message.php'+'?chat_mode='+chat_mode+'&chat_room='+chat_room,
		type:'POST',
		data:'myNick='+myNick+'&msg='+ jQuery('#chat_content').attr('value') + '&topID='+topID, 
		dataType:'html',
		success:function(data)
		{
			jQuery('#chat_loading').hide() ;
			jQuery('#chat_content').attr('value',' ') ;
			jQuery('#chat_content').focus() ;
			/*
			var tmp = eval('('+data+')') ;
			if(!is_empty(tmp.topID) && !is_empty(tmp.msg)){
				if(topID == 0){jQuery('#chat_message').html('') ;}
				topID = tmp.topID ;
				jQuery('#chat_message').prepend(tmp.msg) ;
			}
			*/
		}
	}) ;
}
//Starting to chat with somebody
function send_private_chat_content(nick){
	if(is_empty(jQuery('#private_chat_content').val())){return ;}
	jQuery('#private_chat_loading').show() ;
	jQuery.ajax({
		url:'get_chat_message.php',
		type:'POST',
		data:'myNick='+myNick+'&toNick='+nick+'&msg='+ jQuery('#private_chat_content').attr('value')+'&topID='+private_topID, 
		dataType:'html',
		success:function(data)
		{
			jQuery('#private_chat_loading').hide() ;
			jQuery('#private_chat_content').attr('value',' ') ;
			jQuery('#private_chat_content').focus() ;
			/*
			var tmp = eval('(' + data + ')') ;
			if(!is_empty(tmp.topID) && !is_empty(tmp.msg)){
				if(private_topID == 0){jQuery('#private_chat_message').html('') ;}
				private_topID = tmp.topID ;
				jQuery('#private_chat_message').prepend(tmp.msg) ;
			}
			*/
		}
	}) ;
}
//Get all public chat content
function get_chat_content(){
	jQuery.ajax({
		url:'get_chat_message.php'+'?chat_mode='+chat_mode+'&chat_room='+chat_room+'&login_time='+login_time,
		type:'POST',
		data:'myNick='+myNick + '&topID=' + topID, 
		dataType:'html',
		success:function(data)
		{
			if(data == null || data == ''){return ;}
			var tmp = eval('(' + data + ')') ;
			if(topID == 0){jQuery('#chat_message').html('') ;}
			if(!is_empty(tmp.topID) && !is_empty(tmp.msg)){
				topID = tmp.topID ;
				jQuery('#chat_message').prepend(tmp.msg) ;
			}
		}
	}) ;
}
function get_private_chat_content(nick){
	jQuery.ajax({
		url:'get_chat_message.php',
		type:'POST',
		data:'myNick='+myNick+'&toNick='+nick+'&topID='+private_topID, 
		dataType:'html',
		success:function(data)
		{
			if(data == null || data == ''){return ;}
			var tmp = eval('(' + data + ')') ;
			if(private_topID == 0){jQuery('#private_chat_message').html('') ;}
			if(!is_empty(tmp.topID) && !is_empty(tmp.msg)){
				private_topID = tmp.topID ;
				jQuery('#private_chat_message').prepend(tmp.msg) ;
			}
		}
	}) ;
}
