/*
Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)
This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
loader.womAdd('chat.initChat();');

var chat = {

	windowFocus : true, 
	username : '', 
	display_name : '',
	chatHeartbeatCount : 0, 
	minChatHeartbeat : 1000, 
	maxChatHeartbeat : 33000, 
	chatHeartbeatTime : 1000, 
	originalTitle : '', 
	blinkOrder : 0, 
	
	chatboxFocus : new Array(), 
	newMessages : new Array(), 
	newMessagesWin : new Array(), 
	chatBoxes : new Array(), 

	initChat : function() {
		
		if ( logged ) {		
			chat.originalTitle = document.title;
			chat.startChatSession();
		
			$([window, document]).blur( function() {
				chat.windowFocus = false;
			}).focus( function() {
				chat.windowFocus = true;
				document.title = chat.originalTitle;
			});
		}
	}, 

	startChatSession : function() {  
		$.ajax({	
				url: loader.baseUrl+"/chat/messenger/init",
				cache: false,
				type: "post", 
				dataType: "json",
				success: function(data) {
						chat.username = data.username;
						chat.display_name = data.display_name;
						$.each(data.items, function(i,item) {
							if (item)	{ // fix strange ie bug
								chatboxtitle = item.f;
								if ($("#chatbox_"+chatboxtitle).length <= 0) {
									chat.createChatBox(chatboxtitle, item.dn, 1, item.o);
								}
								if (item.s == 1) {
									item.f = username;
								}
								if (item.s == 2) {
									$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
								} else {
									$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.w+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
								}
							}
						});
	
						for (i=0;i < chat.chatBoxes.length;i++) {
							chatboxtitle = chat.chatBoxes[i];
							$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	
							setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
	
						}
						setTimeout('chat.chatHeartbeat();',chat.chatHeartbeatTime);
	
				}
		});
	},

	createChatBox : function (chatboxtitle, chatbox_display_name, minimizeChatBox, user_status) {

		if ($("#chatbox_"+chatboxtitle).length > 0) {
			if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
				$("#chatbox_"+chatboxtitle).css('display','block');
				restructureChatBoxes();
			}
			$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
			return;
		}

		$(" <div />" ).attr("id","chatbox_"+chatboxtitle)
			.addClass("chatbox")
			.html('<div class="chatboxhead"><img src="'+loader.baseUrl+'/assets/img/bullet-'+user_status+'.png" alt="'+user_status+'"> <a href="'+loader.baseUrl+'/author/'+chatboxtitle+'">'+chatbox_display_name+'</a><div class="chatboxoptions"><a href="javascript:void(0)" class="chat-but-minimize" onclick="javascript: chat.toggleChatBoxGrowth(\''+chatboxtitle+'\')">-</a> <a href="javascript:void(0)" class="chat-but-close" onclick="javascript: chat.closeChatBox(\''+chatboxtitle+'\')">&nbsp;</a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript: return chat.checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>')
			.appendTo($( "body" ));			   
		$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	
		chatBoxeslength = 0;
		for (x in chat.chatBoxes) {
			if ($("#chatbox_"+chat.chatBoxes[x]).css('display') != 'none') {
				chatBoxeslength++;
			}
		}

		if (chatBoxeslength == 0) {
			$("#chatbox_"+chatboxtitle).css('right', '20px');
		} else {
			width = (chatBoxeslength)*(275+7)+20;
			$("#chatbox_"+chatboxtitle).css('right', width+'px');
		}
		chat.chatBoxes.push(chatboxtitle);

		if (minimizeChatBox == 1) {
			minimizedChatBoxes = new Array();
	
			if ($.cookie('chatbox_minimized')) {
				minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
			}
			minimize = 0;
			for (j=0;j<minimizedChatBoxes.length;j++) {
				if (minimizedChatBoxes[j] == chatboxtitle) {
					minimize = 1;
				}
			}
			if (minimize == 1) {
				$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
				$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
			}
		}
		chat.chatboxFocus[chatboxtitle] = false;

		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
			chat.chatboxFocus[chatboxtitle] = false;
			$("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
		}).focus(function(){
			chat.chatboxFocus[chatboxtitle] = true;
			chat.newMessages[chatboxtitle] = false;
			$('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
			$("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
		});

		$("#chatbox_"+chatboxtitle).click(function() {
			if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
				$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
			}
		});

		$("#chatbox_"+chatboxtitle).show();

		$("#chatbox_"+chatboxtitle)
        .bind('dragstart', function( event ) { return $(event.target).is('.chatboxhead'); })
        .bind('drag',function( event ){
                $( this ).css({
                        top: event.offsetY,
                        left: event.offsetX
                });
         });
	},

	chatHeartbeat : function() {

		var itemsfound = 0;
		if (chat.windowFocus == false) {

			var blinkNumber = 0;
			var titleChanged = 0;

			for (x in chat.newMessagesWin) {				
				if (chat.newMessagesWin[x] == true) {
					
					++blinkNumber;
					if (blinkNumber >= chat.blinkOrder) {
						document.title = x+' says...';
						titleChanged = 1;
						break;	
					}
				}
			}
	
			if (titleChanged == 0) {
				document.title = chat.originalTitle;
				chat.blinkOrder = 0;
			} else {
				++chat.blinkOrder;
			}
		} else {
			for (x in chat.newMessagesWin) {
				chat.newMessagesWin[x] = false;
			}
		}
	
		for (x in chat.newMessages) {
			if (chat.newMessages[x] == true) {
				if (chat.chatboxFocus[x] == false) {
					//FIXME: add toggle all or none policy, otherwise it looks funny
					$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
				}
			}
		}

		$.ajax({
				url: loader.baseUrl+"/chat/messenger/chatheartbeat",
				cache: false,
				type: "post", 
				dataType: "json",
				success: function(data) {
							$.each(data.items, function(i,item){
								if (item)	{ // fix strange ie bug
									chatboxtitle = item.f;
									if ($("#chatbox_"+chatboxtitle).length <= 0) {
										chat.createChatBox(chatboxtitle, item.dn, 1, item.o);
									}
									if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
										$("#chatbox_"+chatboxtitle).css('display','block');
										chat.restructureChatBoxes();
									}
									if (item.s == 1) {
										item.f = username;
									}
									if (item.s == 2) {
										$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
									} else {
										chat.newMessages[chatboxtitle] = true;
										chat.newMessagesWin[chatboxtitle] = true;
										$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.dn+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
									}
									$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
									itemsfound += 1;

								}
							});
							chat.chatHeartbeatCount++;



							if (itemsfound > 0) {
								chat.chatHeartbeatTime = chat.minChatHeartbeat;
								chat.chatHeartbeatCount = 1;
							} else if (chat.chatHeartbeatCount >= 10) {
								chat.chatHeartbeatTime *= 2;
								chat.chatHeartbeatCount = 1;
								if (chat.chatHeartbeatTime > chat.maxChatHeartbeat) {
									chat.chatHeartbeatTime = chat.maxChatHeartbeat;
								}
							}
							setTimeout('chat.chatHeartbeat();',chat.chatHeartbeatTime);
						}
		});
	}, 

	chatWith : function(chatuser, chat_displayname, user_status) {
		chat.createChatBox(chatuser, chat_displayname, 1 , user_status);
		$("#chatbox_"+chatuser+" .chatboxtextarea").focus();
	}, 

	restructureChatBoxes : function() {
		align = 0;
		for (x in chat.chatBoxes) {
			chatboxtitle = chat.chatBoxes[x];	
			if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
				if (align == 0) {
					$("#chatbox_"+chatboxtitle).css('right', '20px');
				} else {
					width = (align)*(275+7)+20;
					$("#chatbox_"+chatboxtitle).css('right', width+'px');
				}
				align++;
			}
		}
	}, 


	checkChatBoxInputKey : function (event, chatboxtextarea, chatboxtitle) {

		if (event.keyCode == 13 && event.shiftKey == 0)  {

			message = $(chatboxtextarea).val();
			message = message.replace(/^\s+|\s+$/g,"");

			$(chatboxtextarea).val('');
			$(chatboxtextarea).focus();
//			$(chatboxtextarea).css('height','44px');
			if (message != '') {
				$.post(loader.baseUrl+"/chat/messenger/sendchat", { to: chatboxtitle, message: message} , function(data){
					message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+chat.display_name+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				});
			}
			chat.chatHeartbeatTime = chat.minChatHeartbeat;
			chat.chatHeartbeatCount = 1;
			return false;
		}

		var adjustedHeight = chatboxtextarea.clientHeight;
		var maxHeight = 94;

		if (maxHeight > adjustedHeight) {
			adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
			if (maxHeight) { adjustedHeight = Math.min(maxHeight, adjustedHeight); }
			if (adjustedHeight > chatboxtextarea.clientHeight) { $(chatboxtextarea).css('height',adjustedHeight+8 +'px'); }
		} else {
			$(chatboxtextarea).css('overflow','auto');
		}
	}, 

	closeChatBox : function(chatboxtitle) {

		$('#chatbox_'+chatboxtitle).css('display','none');
		chat.restructureChatBoxes();

		$.post(loader.baseUrl+"/chat/messenger/closechat", { chatbox: chatboxtitle} , function(data){});
	},

	toggleChatBoxGrowth : function(chatboxtitle) {

		if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
			var minimizedChatBoxes = new Array();
			if ($.cookie('chatbox_minimized')) {
				minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
			}
			var newCookie = '';
			for (i=0;i<minimizedChatBoxes.length;i++) {
				if (minimizedChatBoxes[i] != chatboxtitle) {
					newCookie += chatboxtitle+'|';
				}
			}
			newCookie = newCookie.slice(0, -1)
			$.cookie('chatbox_minimized', newCookie);
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
			$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
		} else {
			var newCookie = chatboxtitle;
			if ($.cookie('chatbox_minimized')) {
				newCookie += '|'+$.cookie('chatbox_minimized');
			}
			$.cookie('chatbox_minimized',newCookie);
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}


}
	


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
                }
            }
        }
        return cookieValue;
    }
};

