window.mhsChat = window.mhsChat || {};

jQuery(function($) {
	var pub = mhsChat;


	var url = URL + ROOT + 'chat_ajax.php?ajax';
	var msgDefaults = {name:'', date:'', avatar:'', text:'<empty/>', setStatus: false};
	var queueDefaults = {id:0, name:'', date:'', avatar:'', text:'<empty/>', setStatus: true};
	var pingRate = 5000;
	var timeoutTime = 60 * 1000;
	var flashTime = 10 * 1000;
	var numUsers = 0;
	var lastTimestamp = 0;
	var lastQueueLength = 0;
	var sumMsgs = 0;
	var chatID = $('#mhs-chat input[name=chat_session_id]').val();
	var pingTimer;

	var template = (function() {var c={};return function(str,data){var fn=!/\s/.test(str)?c[str]=c[str]||arguments.callee(document.getElementById(str).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return data?fn(data):fn;};})();


	var timeoutTimer;
	var resetTimeout = function() {
		clearTimeout(timeoutTimer);
		timeoutTimer = setTimeout(function() {
			flash('warning', 'You have not recieved a message from the server in over '+(timeoutTime/1000)+' seconds. You may need to <a href="javascript:location.reload();">refresh the page</a> to continue getting updates.');
		}, timeoutTime);
	};


	var send = function(data, fn) {
		$.extend(data, {chatID: chatID, timestamp: lastTimestamp});
		$.ajax({
			type: 'post',
			dataType: 'json',
			url: url,
			data: data,
			success: fn || processJSON,
			error: function(xhr, status, error) {
				flash('error', error || status);
			}
		})
	};

	var flash = function(type, msg) {
		var $msg = msg ? $('<div class="message '+type+'"><p>'+msg+'</p></div>') : $(type);
		$msg
			.hide()
			.appendTo('#mhs-chat .chat-notices')
			.slideDown()
		setTimeout(function() {
			$msg.slideUp();
		}, flashTime);
	}

	var validStatus = {'pending':true, 'active':true, 'closed':true};
	var processJSON = function(res) {
		clearTimeout(pingTimer);
		resetTimeout();

		if(validStatus[res.status]) {
			var html;
			var scroll = lastTimestamp === 0 || atBottom();

			// Login
			if(res.login_valid === true) {
				$('#mhs-chat .chat-login').slideUp();
				$('#mhs-chat .chat-message').slideDown();
			} else if(res.login_valid === false) {
				$('#mhs-chat .chat-login').slideDown();
				$('#mhs-chat .chat-message').slideUp();
			}


			// Process Messages
			if(res.messages && res.messages.length) {
				sumMsgs += res.messages.length;
				html = [];
				$.each(res.messages, function(i, msg) {
					lastTimestamp = Math.max(lastTimestamp, msg.posted);
					msg = $.extend({}, msgDefaults, msg);
					html.push(template('chat-log-template', msg));
				});
				if(html.length > 0) {
					$(html.join('')).appendTo('#chat-log-box');
					if(scroll) scrollToBottom();
				}
				$('#live-total').html('('+sumMsgs+')');
			}

			// Process Queue
			if(res.queue && res.queue.length !== lastQueueLength) {
				if(lastQueueLength < res.queue.length) {
					// Flash Tab
				}
				lastQueueLength = res.queue.length;
				
				html = [];
				$.each(res.queue, function(i, queue) {
					queue = $.extend({}, queueDefaults, queue);
					html.push(template('chat-log-template', queue));
				});
				if(html.length > 0) $('#chat-queue-box').html(html.join(''));
				$('#queue-total').html('('+lastQueueLength+')');
			}

			// Process Users
			$('#users-total').html('('+res.num_users+')');

			if(res.success) flash(res.success);
			if(res.error) flash(res.error);

			// Get Status Variables
			pingRate = res.ping_rate || pingRate;
			numUsers = res.num_users || numUsers;

			if(res.status != 'closed') pingTimer = setTimeout(pingServer, pingRate);
		}


		// Invalid Status
		else if(typeof res === 'xml') {
			flash(res.toString());
			pingTimer = setTimeout(pingServer, pingRate);
		}


		// Who knows, just give up...
		else {
			flash('warning', 'An error occured processing the response from the server.');
			pingTimer = setTimeout(pingServer, pingRate);
		}
	};




	var atBottom = function() {
		var $box = $('#chat-log-box');
		var height = 0;
		$box.find('.chat-log').each(function() {
			height += $(this).outerHeight();
		});
		return height - 50 < $box.height() + $box.scrollTop();
	};

	var scrollToBottom = function() {
		$('#chat-log-box').scrollTop(10000000);
	};


	var pingServer = function() {
		send({action: 'ping'});
	};



	var stopPingServer = function() {
		clearTimeout(pingTimer);
	};



	// Submit Form On Return
	var returnKeys = {13:true};
	$('#mhs-chat :input.chat-input, #mhs-chat textarea.chat-message-input').live('keypress', function(e) {
		if(!returnKeys[e.keyCode]) return true;
		$(this).closest('.chat-form').find('.chat-submit').click();
		return false;
	});

	// Auto-expand Textareas
	$('#mhs-chat textarea.chat-message-input').live('keypress', function() {
		var that = this;
		setTimeout(function() {
			while(that.scrollHeight > that.offsetHeight) that.rows++;
		}, 10);
	});

	// Detect Login
	$('#mhs-chat .chat-signin').live('click', function() {
		var $form = $(this).closest('.chat-form');
		var $name = $form.find(':input[name=name]');
		var $email = $form.find(':input[name=email]');
		send({
			action: 'login',
			name: $name.val(),
			email: $email.val()
		});
	});


	// Detect Logout
	$('#mhs-chat .chat-signout').live('click', function() {
		send({action: 'logout'});
	});



	// Detect Send Message
	$('#mhs-chat .chat-send').live('click', function() {
		var $form = $(this).closest('.chat-form');
		var $text = $form.find(':input[name=text]')
		send({
			action: 'send',
			text: $text.val()
		});
		$text.val('');
		$text.focus();
		$text.attr('rows', 1);
	});



	// Detect Tabs
	var tabChangeTimer;
	$('#chat-tabs .tab-link').live('click', function() {
		clearTimeout(tabChangeTimer);
		var $this = $(this);
		var $tabs = $this.closest('#chat-tabs');
		$tabs.find('.tab-active').removeClass('tab-active');
		tabChangeTimer = setTimeout(function() {
			$this.addClass('tab-active');
			$tabs.find(location.hash).addClass('tab-active');
		}, 100);
	});



	$('#queue .status-box').live('click', function() {
		var $this = $(this);
		var $queue = $this.closest('.chat-log');
		send({
			action: $this.is('.approve') ? 'approve' : 'deny',
			msgID: $queue.find(':input[name=msgID]').val()
		})
		$queue.slideUp();
	});


	// Set Session Variables
	send({action: 'join'});

});
