/* Chat.js */

var GBL_NL = (typeof window.event != 'undefined') ? '\r\n' : '\n'; // New line Char

// Param: object {UserID, UserFName, UserID_, UserFName_, Applet}
function init_chatWindow(object) {
	
	if (typeof object.UserID == 'undefined') return false;
	
	//-----------------------------------------------------------------
	// Set Private Properties
	//-----------------------------------------------------------------
	
	// Set a private hold of the object
	var self = this;
	// Initialize Message input txtbox variable
	var miTb = $('#msgInput').get(0);
	var miSBtn = $('#btnSend').get(0);
	// Get others
	var _Applet = object.Applet;
	// Disable Flag
	var _disabled = false;
	
	//-----------------------------------------------------------------
	// Set Public Properties
	//-----------------------------------------------------------------
	
	// User's UserID
	this.UserID = object.UserID;
	// User's First Name
	this.UserFName = object.UserFName;
	// Chatmate UserID
	this.UserID_ = object.UserID_;
	// Chatmate First Name
	this.UserFName_ = object.UserFName_;
	// Initialize inserting of smileys
	this.smileys = new init_smileys(
		$('#smileyLink').get(0),
		$('#smileyListCon').get(0),
		miTb);
	// Initialize Message output container object
	this.mo = new init_chatMsgCanvas(this, $('#msgOutput').get(0));
	// Offline/Online flag
	this.IsOffline = true;
	
	//-----------------------------------------------------------------
	// Set Public Methods
	//-----------------------------------------------------------------
	
	// Send Message
	this.sendMessage = function() {
		if (_disabled) return false;
		if ( ! miTb.value) return false;
		if (miTb.value.length == 1 && miTb.value.indexOf(GBL_NL) >= 0) return false;
		var msg = func_replaceAll(miTb.value,GBL_NL,'{br}');
		
		// Create a unique id for this message
		// Begin
		var Stamp = new Date();
		var H = '00'+Stamp.getHours();
		var m = '00'+Stamp.getMinutes();
		var s = '00'+Stamp.getSeconds();
		var ms = '0000'+Stamp.getMilliseconds();
		
		var MsgID = 
			H.substring(H.length-2, H.length)	+
			m.substring(m.length-2, m.length)	+
			s.substring(s.length-2, s.length)	+
			ms.substring(ms.length-4, ms.length);		
		
		if ( ! this.IsOffline) _Applet.PM(msg, MsgID);
		
		self.mo.addMessage(this.UserFName, msg);
		miTb.value = '';
	};
	// Receive Message
	this.receiveMessage = function(msg, date_received) {
		self.mo.addMessage(this.UserFName_, msg, date_received);
	};
	// Set user offline
	this.goOffline = function(val) {
		if (this.IsOffline == val) return false;
		if (val) {
			//this.disabled(true);
			this.IsOffline = true;
			$('span.user_status').attr('innerHTML', '(offline)');
			$('.WindowChat .left_panel').addClass('offline');
		} else {
			//this.disabled(false);
			this.IsOffline = false;
			$('span.user_status').attr('innerHTML', '(online)');
			$('.WindowChat .left_panel').removeClass('offline');
		}
		return true;
	}
	// Disable Chat
	this.disabled = function(val) {
		if (val == null) return _disabled;
		_disabled = val;
	}
	
	//this.blockUser() { }
	//-----------------------------------------------------------------
	// Initialize
	//-----------------------------------------------------------------
	
	// Initialize Message input txtbox
	miTb.onkeydown = function(e) {
		var e = window.event || e;
		if (e.keyCode == 220) return false;
		if (e.keyCode == 13) {
			if (e.ctrlKey) {
				func_insertText(this, GBL_NL);
			}
			else self.sendMessage();
			return false;
		}
	}
	// Set Message Input txtbox maxlength = 200
	miTb.onkeyup = function() {
		return func_IsMaxlength(this);
	}
	
	// Initialize Message Send button
	miSBtn.onclick = function() {
		self.sendMessage();
	}		
	
	if (typeof object.Message == 'undefined') return;
	self.receiveMessage(object.Message);
}

/*
|----------------------------------------------------------------------------------------
| Library functions
|----------------------------------------------------------------------------------------
*/
function func_replaceAll(myString, rf, rr) {	
	var regX = new RegExp(rf, 'gi');
	s = new String(myString);
	s = s.replace(regX, rr);
	return s;
}

function func_IsMaxlength(textarea) {
	var mlength=textarea.getAttribute ? parseInt(textarea.getAttribute("maxlength")) : "";
	if (textarea.getAttribute && textarea.value.length>mlength) {
		textarea.value=textarea.value.substring(0,mlength);
		textarea.scrollTop = textarea.scrollHeight;
	}
}

// 
function func_getCursorPosition(obj) {
	var textarea = obj;
	textarea.focus();
	
	// get selection in firefox, opera, …
	if (typeof(textarea.selectionStart) == 'number')
	{ 
		return textarea.selectionStart;
	} else 
	if(document.selection) {
		var selection_range = document.selection.createRange().duplicate();
	
		if (selection_range.parentElement() == textarea) { // Check that the selection is actually in our textarea
			// Create three ranges, one containing all the text before the selection,
			// one containing all the text in the selection (this already exists), and one containing all
			// the text after the selection.
			var before_range = document.body.createTextRange();
			before_range.moveToElementText(textarea); // Selects all the text
			before_range.setEndPoint("EndToStart", selection_range); // Moves the end where we need it
			
			var after_range = document.body.createTextRange();
			after_range.moveToElementText(textarea); // Selects all the text
			after_range.setEndPoint("StartToEnd", selection_range); // Moves the start where we need it
			
			var before_finished = false, selection_finished = false, after_finished = false;
			var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;
			
			// Load the text values we need to compare
			before_text = untrimmed_before_text = before_range.text;
			selection_text = untrimmed_selection_text = selection_range.text;
			after_text = untrimmed_after_text = after_range.text;
		
			// Check each range for trimmed newlines by shrinking the range by 1 character and seeing
			// if the text property has changed. If it has not changed then we know that IE has trimmed
			// a \r\n from the end.
			do {
				if (!before_finished) {
					if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
						before_finished = true;
					} else {
						before_range.moveEnd("character", -1)
						if (before_range.text == before_text) {
							untrimmed_before_text += "\r\n";
						} else {
							before_finished = true;
						}
					}
				}
				if (!selection_finished) {
					if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
						selection_finished = true;
					} else {
						selection_range.moveEnd("character", -1)
						if (selection_range.text == selection_text) {
							untrimmed_selection_text += "\r\n";
						} else {
							selection_finished = true;
						}
					}
				}
				if (!after_finished) {
					if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
						after_finished = true;
					} else {
						after_range.moveEnd("character", -1)
						if (after_range.text == after_text) {
							untrimmed_after_text += "\r\n";
						} else {
							after_finished = true;
						}
					}
				}
				
			} while ((!before_finished || !selection_finished || !after_finished));
			
			// Untrimmed success test to make sure our results match what is actually in the textarea
			// This can be removed once you're confident it's working correctly
			var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
			var untrimmed_successful = false;
			if (textarea.value == untrimmed_text) {
				untrimmed_successful = true;
			}
			// ** END Untrimmed success test
			
			var startPoint = untrimmed_before_text.length;
			return (startPoint);
		}
	}
}

function func_setCursorPosition(obj, pos)
{
	//FOR IE
	if(obj.setSelectionRange)
	{
		obj.focus();
		obj.setSelectionRange(pos,pos);
	}
	// For Firefox
	else
	if (obj.createTextRange)
	{
		var range = obj.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos - (obj.value.substring(0, pos).split(GBL_NL).length - 1));
		range.moveStart('character', pos - (obj.value.substring(0, pos).split(GBL_NL).length - 1));
		range.select();
	}
}

// Insert str2 in textarea obj
function func_insertText(obj, str2) {
	var str1 = obj.value;
	var pos = func_getCursorPosition(obj);
	var val1 = str1.substring(0, pos);
	var val2 = str1.substring(pos, str1.length);
	obj.value = val1+str2+val2;
	func_setCursorPosition(obj, pos+str2.length);
}

// Get Date (hh:mm:ss AM/PM)
function func_GetDate(isfull) {
	// Get Date
	var Stamp = new Date();
	var H = Stamp.getHours() % 12;
	var m = Stamp.getMinutes();
	var s = Stamp.getSeconds();
	var t = (Stamp.getHours() >= 12) ? 'pm' : 'am';
	if (H == 0) H = 12;
	if (H < 10) H = '0' + H;
	if (m < 10)	m = '0' + m;
	if (s < 10)	s = '0' + s;
	
	if (isfull)
		return (Stamp.getMonth()+1)+'/'+Stamp.getDate()+'/'+Stamp.getFullYear()+' '+H+':'+m+t;
	else
		return H+':'+m+t;
}

// Filter smileys
function	func_filterSmileys(msg) {
	var si = 0;
	var i = msg.indexOf('{~~', si);
	var S = '';
	var img = '';
	while(i >= 0) {
		if (msg.substr(i+4,1) == '}') {
			img = msg.substring(i+3,i+4);
			S += msg.substring(si, i) + '<img src="'+GBL_site_folder+'/images/smileys/'+img+'.gif" align="absmiddle"/>';
			si = i+5;
		} else
		if (msg.substr(i+5,1) == '}') {
			img = msg.substring(i+3,i+5);			
			S += msg.substring(si, i) + '<img src="'+GBL_site_folder+'/images/smileys/'+img+'.gif" align="absmiddle"/>';
			si = i+6;
		}
		i = msg.indexOf('{~~', i+3);
	}
	return S + msg.substr(si);
}

// Show the html link for chatting
function func_PM_Link(UserID, isIcon) {
	if ( ! isIcon) {
		document.write(
			'<span id="PM_Button'+UserID+'" class="im_offline">' +
				'<a href="#0" onClick="func_PM({UserID_:'+UserID+'})" class="im_online_show">' +
					'<label style="float:left">I\'m online</label>' +
					'<img src="'+GBL_site_folder+'/images/chat/im_online-icon.gif" title="I\'m online!" style="float:right"/>' +	
				'</a>' + 
				'<span class="im_offline_show">' + 
					'<label style="float:left">I\'m offline</label>' +
					'<img src="'+GBL_site_folder+'/images/chat/im_offline-icon.gif" title="I\'m offline!" style="float:right"/>' + 
				'</span>' + 
				'<br clear="all">' + 
			'</span>'
		);
	} else {
		document.write( 
			'<span id="PM_Button'+UserID+'" class="im_offline">' + 
				'<a href="#0" onClick="func_PM({UserID_:'+UserID+'})" class="im_online_show">' + 
					'<img src="'+GBL_site_folder+'/images/chat/im_online-icon.gif" class="im_online_show" title="I\'m online!" align="left"/>' + 
				'</a>' + 
				'<span class="im_offline_show">' + 
					'<img src="'+GBL_site_folder+'/images/chat/im_offline-icon.gif" class="im_offline_show" title="I\'m offline!" align="left"/>' + 
				'</span>' + 
			'</span>'
		);
	}
	document.getElementById('UsersToCheckIfOnline').value += UserID + ';';
}

// func_PM
// Params:
//	- UserID : string (current user's UserID)
//	- UserID_ : string (chatmate's UserID)
//	- UserFName : string
//	- Message : String - message from this chatmate
var GBL_arr_visible_popups = Array();
function func_PM(object) {

	if (window.name != 'Chat_Window_'+object.UserID_) {
		if (object.Message) {
			$.ajax(
				{
					type: 'POST',
					url: GBL_site_folder+'/chat/new_msg_popup/'+object.UserID_+'/',
					data: 'msg='+object.Message+'&datetimeSent='+func_GetDate('FULL')+'&msgID='+object.MessageID,
					
					success: function(html) {
						var div = $('#NewMessagePanel'+object.UserID_);
						if ( ! div.get(0)) {
							var div = $("<div></div>").attr({
									id : 'NewMessagePanel'+object.UserID_,
									className : 'new_message_panel',
									innerHTML : html
								}
							);
							$('#HiddenTaskbar').append(div);
							$('div.content .right_pane', div).click(
								function() {
									var _parent = $(this).parent().parent().get(0);
									div.animate({ opacity: 'hide' }, 'fast');
									eval('Chat_Window_'+object.UserID_+" = wopen('"+GBL_site_folder+"/chat/index/'+object.UserID_+'/', 'Chat_Window_'+object.UserID_, 350, 470)");
									for (var i =0; i<GBL_arr_visible_popups.length; i++) {
										if (GBL_arr_visible_popups[i] == _parent) {
											GBL_arr_visible_popups.splice(i,1);
											return false;
										}
									}
								}
							);
							$('div.content a.btn_close', div).click(
								function() {
									var _parent = $(this).parent().parent().get(0);
									div.animate({ opacity: 'hide' }, 'fast');
									for (var i =0; i<GBL_arr_visible_popups.length; i++) {
										if (GBL_arr_visible_popups[i] == _parent) {
											GBL_arr_visible_popups.splice(i,1);
											return false;
										}
									}
									return false;
								}
							);
						}
						if ($(div).is(':hidden')) {
							if (GBL_arr_visible_popups.length > 0)
								var bottom = parseInt($(GBL_arr_visible_popups[GBL_arr_visible_popups.length-1]).css('bottom'))+60+2;
							else
								var bottom = 0;
							
							$(div).css('bottom', bottom+'px');
							$('div.content span.message_container', div).attr('innerHTML', func_filterSmileys(func_replaceAll(object.Message,'{br}','<br>')));
							$(div).slideToggle("slow");
							GBL_arr_visible_popups.push(div.get(0));
						}
					}
				}
			);
		} else {		
			eval('Chat_Window_'+object.UserID_+" = wopen('"+GBL_site_folder+"/chat/index/'+object.UserID_+'/', 'Chat_Window_'+object.UserID_, 350, 470)");
		}
	} else {
		if (typeof WinChat != 'undefined') {
			WinChat.mo.addMessage(WinChat.UserFName_, object.Message);
		}
	}
}

// func_PM_UserIsOnLine
// Params:
//	- UserID : integer - chatmate's UserID
//	- IsOffline : boolean
function func_PM_UserIsOnLine(object) {
	
	var iOfflineNotificationDelay = 3000; // 3 seconds
	
	if ( ! object.IsOffline)
		if (typeof GBL_timeoutID != 'undefined') clearTimeout(GBL_timeoutID);
	
	if (typeof WinChat != 'undefined') {
		
		if ( ! object.UserID) {
			WinChat.goOffline(object.IsOffline);
		} else {
			if (object.IsOffline) { // is Offline
				GBL_timeoutID = setTimeout(function() {
						WinChat.goOffline(true);
					}, 
					iOfflineNotificationDelay
				);
			} else {
				WinChat.goOffline(false);
			}
		}				
	} else {
		if ( ! object.UserID) return false;
		
		if (object.IsOffline) { // is Offline
			GBL_timeoutID = setTimeout(function() {
					$('#PM_Button'+object.UserID).attr('class', 'im_offline');
				}, 
				iOfflineNotificationDelay
			);
		} else {
			$('#PM_Button'+object.UserID).attr('class', 'im_online');
		}
	}		
}

function func_Block_Notification(val) {
	// 
	if (val == 1) {
		if (WinChat.disabled()) return;
		WinChat.mo.addAdminMessage("You've been blocked by this member", 'ERROR');
		WinChat.disabled(true);
	} else {
		if (WinChat.disabled()) return;
		WinChat.mo.addAdminMessage("This member was added to your block list", 'ERROR');
		WinChat.disabled(true);
	}
}

//this won't make the taskbar button flash in changing colours, 
//but the title will blink on and off until they move the mouse. 
//This should work cross platform, and even if they just have it in a different tab.
GBL_timeoutId = null;
function newExcitingAlerts() {
	var oldTitle = document.title;
	var msg = "New message!";
	if (GBL_timeoutId != null) return;
	GBL_timeoutId = setInterval(function() {
		document.title = document.title == msg ? oldTitle : msg;
	}, 1000);
	document.onmousemove = function() {
		clearInterval(GBL_timeoutId);
		document.title = oldTitle;
		document.onmousemove = null;
		GBL_timeoutId = null;
	};
}
