// SpiceFuse AJAX ShoutBox for MyBB
// (c) Asad Niazi, www.spicefuse.com!
//
// Code is copyrighted and does not belong to public domain.
// Copying or reusing in different forms/softwares isn't allowed.
// 
// Yes it uses SF Ajax file.
//

var ShoutBox = {
	refreshInterval: 60,
	lastID: 0,
	totalEntries: 0,
	firstRun: 1,
	MaxEntries: 5,
	DataStore: new Array(),
	lang: ['Shouting...', 'Shout Now!', 'Loading...', 'Flood check! Please try again in <interval> seconds.', 'Couldn\'t shout or perform action. Please try again!', 'Sending message...', 'Send!'],


	showShouts: function() {
		setTimeout("ShoutBox.showShouts();", ShoutBox.refreshInterval * 1000);
		if (typeof Ajax == 'object') {
			new Ajax.Request('xmlhttp.php?action=show_shouts&last_id='+ShoutBox.lastID, {method: 'get', onComplete: function(request) { ShoutBox.shoutsLoaded(request); } });
		}
	},

	shoutsLoaded: function(request) {
		
		var theHTML = "";
		var curData = "";
		var data = request.responseText.split('^--^');
		var theID = parseInt(data[0]);
		var theEntries = parseInt(data[1]);

		if (theID <= ShoutBox.lastID) {
			return;
		}

		// add to data store now...
		curData = data[2].split("\r\n");

		// only 1 message?
		if (curData.length == 1) 
		{
			length = ShoutBox.DataStore.length;
			ShoutBox.DataStore[ length ] = curData[0];
		} 
		else 
		{
			// hush, lots of em
			var collectData = "";
			var length = 0;
			for (var i = curData.length; i >= 0; i--) 
			{
				if (curData[i] != "" && curData[i] != undefined) {
					length = ShoutBox.DataStore.length;
					ShoutBox.DataStore[ length ] = curData[i];
				}	
			}
		}

		ShoutBox.lastID = theID;
		ShoutBox.totalEntries += theEntries;

		if (ShoutBox.firstRun == 1) {
			theHTML = data[2];
			ShoutBox.firstRun = 0;
		} else {

			// the data is more than the limit? hard luck here then... just get it from datastore
			if ((theEntries + ShoutBox.totalEntries) > ShoutBox.MaxEntries) {
				for (var j=0, i = ShoutBox.DataStore.length-1; j < ShoutBox.MaxEntries; i--, j++) {
					theHTML += ShoutBox.DataStore[i];
				}

				ShoutBox.totalEntries = ShoutBox.MaxEntries;

			} else {
				theHTML = data[2] + $("shoutbox_data").innerHTML;
			}

		}

		$("shoutbox_data").innerHTML = theHTML;
		$("shoutbox_sendinfo").innerHTML = data[3];

		// clean up DataStore
		ShoutBox.cleanDataStore();
	},
	
	// copied from MyBB's editor.js
	getSelectedText: function(element)
	{
		element.focus();
		if(document.selection)
		{
			var selection = document.selection;
			var range = selection.createRange();

			if((selection.type == "Text" || selection.type == "None") && range != null)
			{
				return range.text;
			}
		}
		else if(element.selectionEnd)
		{
			var select_start = element.selectionStart;
			var select_end = element.selectionEnd;
			if(select_end <= 0)
			{
				select_end = element.textLength;
			}
			var start = element.value.substring(0, select_start);
			var middle = element.value.substring(select_start, select_end);
			return middle;
		}
	},
	
	pvtAdd: function(uid) {
		var msg = $("shout_data").value;
		$("shout_data").value = '/pvt ' + uid + ' ' + msg;
	},
	
	talkToBot: function() {
		var msg = $("shout_data").value;
		$("shout_data").value = '@mysb_bot ' + msg;
	},
	
	colorAdd: function(color) {
		var msg = $("shout_data").value;
		
		$("shout_data").value = '[color=#' + color + ']' + msg + '[/color]';
	},
	
	mycodeAdd: function(code) {
		var msg = $("shout_data").value;
		
		switch (code)
		{
			case 'S':
				$("shout_data").value = '[s]' + msg + '[/s]';
			break;
			case 'B':
				$("shout_data").value = '[b]' + msg + '[/b]';
			break;
			case 'I':
				$("shout_data").value = '[i]' + msg + '[/i]';
			break;
			case 'U':
				$("shout_data").value = '[u]' + msg + '[/u]';
			break;
		}
	},

	postShout: function() {
		message = $("shout_data").value;
		if (message == "") {
			return false;
		}

		$("shouting-status").value = ShoutBox.lang[0];

		postData = "shout_data="+encodeURIComponent(message).replace(/\+/g, "%2B");
		new Ajax.Request('xmlhttp.php?action=add_shout', {method: 'post', postBody: postData, onComplete: function(request) { ShoutBox.postedShout(request); }});
	},

	postedShout: function(request) {
		
		if (request.responseText == 'deleted') {
			ShoutBox.firstRun = 1;
			ShoutBox.lastID = 0;
			alert("Shouts deleted as requested.");
		}
		else if (request.responseText.indexOf('flood') != -1) {
			var split = new Array();
			split = request.responseText.split('|');			
			var interval = split[1]; 
			
			alert(ShoutBox.lang[3].replace('<interval>', interval));
		}
		else if (request.responseText.indexOf("success") == -1) {
			alert(ShoutBox.lang[4]);
		}

		$("shouting-status").value = ShoutBox.lang[1];
		ShoutBox.showShouts();
	},
	
	sendMessage: function() {
		message = $("send_to").value;
		if (message == "") {
			return false;
		}

		$("sending-status").value = ShoutBox.lang[5];

		postData = "send_to="+encodeURIComponent(message).replace(/\+/g, "%2B");
		new Ajax.Request('xmlhttp.php?action=send_message', {method: 'post', postBody: postData, onComplete: function(request) { ShoutBox.sentMessage(request); }});
	},

	sentMessage: function(request) {
		if (request.responseText == 'already_sent') {
			$("sending-status").value = ShoutBox.lang[6];
			alert(ShoutBox.lang[7]);
			return false;
		}
		else if (request.responseText == 'send_self') {
			$("sending-status").value = ShoutBox.lang[6];
			alert(ShoutBox.lang[10]);
			return false;
		}
		else if (request.responseText == 'send_invalid') {
			$("sending-status").value = ShoutBox.lang[6];
			alert(ShoutBox.lang[9]);
			return false;
		}
		
		$("sending-status").value = ShoutBox.lang[6];
		ShoutBox.showShouts();
	},
	
	deleteMessage: function(mid) {
		new Ajax.Request('xmlhttp.php?action=delete_message&mid='+mid, {method: 'get', onComplete: function(request) { ShoutBox.deletedMessage(request); } });
	},
	
	deletedMessage: function(request) {
		if (request.responseText == 'deleted') {
			alert(ShoutBox.lang[8]);
		}
		ShoutBox.DataStore = new Array();
		ShoutBox.lastID = 0;
		ShoutBox.showShouts();
	},
	
	deleteShout: function(id, type) {
		if (type == 1) {
			$("shoutbox_data").innerHTML = ShoutBox.lang[2];
		}

		new Ajax.Request('xmlhttp.php?action=delete_shout&id='+id, {method: 'get', onComplete: function(request) { ShoutBox.deletedShout(request, id, type); } });
	},
	
	deletedShout: function(request, id, type) {
		if (request.responseText.indexOf("success") == -1) {
			alert("Error deleting shout... Try again!");
		} else if (type == 2) {
			alert("Shout deleted.");
		}

		if (type == 1) {
			ShoutBox.DataStore = new Array();
			ShoutBox.lastID = 0;
			ShoutBox.showShouts();
		} else {
			try {
				$("shout-"+id).style.display = "none";
			} catch (e) { 
				$("shout-"+id).style.display = "hidden";
			}
		}

	},
	
	removeShout: function(id, type) {
		if (type == 1) {
			$("shoutbox_data").innerHTML = ShoutBox.lang[2];
		}

		new Ajax.Request('xmlhttp.php?action=remove_shout&id='+id, {method: 'get', onComplete: function(request) { ShoutBox.deletedShout(request, id, type); } });
	},
	
	removedShout: function(request, id, type) {
		if (request.responseText.indexOf("success") == -1) {
			alert("Error removing shout... Try again!");
		} else if (type == 2) {
			alert("Shout removed.");
		}

		if (type == 1) {
			ShoutBox.DataStore = new Array();
			ShoutBox.lastID = 0;
			ShoutBox.showShouts();
		} else {
			try {
				$("shout-"+id).style.display = "none";
			} catch (e) { 
				$("shout-"+id).style.display = "hidden";
			}
		}

	},
	
	recoverShout: function(id, type) {
		if (type == 1) {
			$("shoutbox_data").innerHTML = ShoutBox.lang[2];
		}

		new Ajax.Request('xmlhttp.php?action=recover_shout&id='+id, {method: 'get', onComplete: function(request) { ShoutBox.recoveredShout(request, id, type); } });
	},
	
	recoveredShout: function(request, id, type) {
		if (request.responseText.indexOf("success") == -1) {
			alert("Error recovering shout... Try again!");
		} else if (type == 2) {
			alert("Shout recovered.");
		}

		if (type == 1) {
			ShoutBox.DataStore = new Array();
			ShoutBox.lastID = 0;
			ShoutBox.showShouts();
		} else {
			try {
				$("shout-"+id).style.display = "none";
			} catch (e) { 
				$("shout-"+id).style.display = "hidden";
			}
		}

	},

	cleanDataStore: function() {
		if (ShoutBox.DataStore.length > ShoutBox.MaxEntries) {
			for (var i = (ShoutBox.DataStore.length - ShoutBox.MaxEntries); i > 0; i--) {
				ShoutBox.DataStore[i] = "";
			}
		}
	},

	disableShout: function() {
		try { 
			$("shouting-status").disabled = true;
		} catch (e) {
			$("shouting-status").readonly = true;
		}
	},
	
	// the 3 functions below were copied from MyBB 1.4.4 editor.js
	
	bindSmilieInserter: function(id) {
		if(!$(id))
		{
			return false;
		}

		var smilies = $(id).select('.smilie');

		if(smilies.length > 0)
		{
			smilies.each(function(smilie)
			{
				smilie.onclick = this.insertSmilie.bindAsEventListener(this);
				smilie.style.cursor = "pointer";
			}.bind(this));
		}
	},

	openGetMoreSmilies: function(editor)
	{
		MyBB.popupWindow('misc.php?action=smilies&popup=true&editor='+editor, 'sminsert', 240, 280);
	},

	insertSmilie: function(e)
	{
		element = Event.element(e);

		if(!element || !element.alt)
		{
			return false;
		}
		
		var textbox = $("shout_data");
		textbox.focus();
		textbox.value += element.alt;
	},
	
 };

// MyPlaza's popup menu
var ShoutboxPopupMenu = Class.create();

ShoutboxPopupMenu.prototype = {

	initialize: function(id, openFunc, closeFunc)
	{
		document.currentMenu = "";

		if(!$(id))
		{
			return false;
		}
		this.id = id;
		var element = $(id);
		
		var popupMenu = element.id+"_popup";
		if(!$(popupMenu))
		{
			return false;
		}
		
		this.menu = $(popupMenu);
		
		if(openFunc)
			this.openFunc = openFunc;
		if(closeFunc)
			this.closeFunc = closeFunc;
		
		this.mouseHovered = false;
		document.lockMenu = false;
		this.menu.style.display = "none";
		element.onclick = this.openMenu.bindAsEventListener(this);
		this.menu.onmouseover = this.mouseOver.bindAsEventListener(this);
		this.menu.onmouseout = this.mouseOut.bindAsEventListener(this);
	},
	
	mouseOver: function(e)
	{
		if(document.currentMenu == this.id)
			this.mouseHovered = true;
	},
	mouseOut: function(e)
	{
		if(document.currentMenu == this.id)
			this.mouseHovered = false;
	},
	
	openMenu: function(e)
	{
		Event.stop(e);
		//this.mouseHovered = false;
		if(document.lockMenu) return;
		if(document.currentMenu == this.id)
		{
			this.closeMenu(document.currentMenu);
			return false;
		}
		else if(document.currentMenu != "")
		{
			this.closeMenu(document.currentMenu);
		}
		
		offsetTop = offsetLeft = 0;
		var element = $(this.id);
		do
		{
			offsetTop += element.offsetTop || 0;
			offsetLeft += element.offsetLeft || 0;
			element = element.offsetParent;
		} while(element);
		element = $(this.id);
		this.menu.style.position = "absolute";
		this.menu.style.zIndex = 100;
		this.menu.style.top = (offsetTop+element.offsetHeight-1)+"px";
		// Bad browser detection - yes, only choice - yes.
		if(MyBB.browser == "opera" || MyBB.browser == "safari")
		{
			this.menu.style.top = (parseInt(this.menu.style.top)-2)+"px";
		}
		this.menu.style.left = offsetLeft+"px";
		this.menu.style.visibility = 'hidden';
		this.menu.style.display = '';
		if(this.menu.style.width)
		{
			menuWidth = parseInt(this.menu.style.width);
		}
		else
		{
			menuWidth = this.menu.offsetWidth;
		}
		if(this.menu.style.height)
		{
			menuHeight = parseInt(this.menu.style.height);
		}
		else
		{
			// doesn't work properly :( :(
			menuHeight = this.menu.offsetHeight;
		}
		pageSize = DomLib.getPageSize();
		if(offsetLeft+menuWidth >= pageSize[0])
		{
			this.menu.style.left = (offsetLeft-menuWidth-2)+"px";
			if(MyBB.browser == "ie")
			{
				this.menu.style.left = (parseInt(this.menu.style.left)-2)+"px";
			}
		}
		if(offsetTop+menuHeight >= pageSize[1] - 2)
		{
			this.menu.style.top = (offsetTop-menuHeight)+"px";
			if(MyBB.browser == "ie")
			{
				this.menu.style.top = (parseInt(this.menu.style.top)-2)+"px";
			}
		}
		this.menu.style.display = '';	
		this.menu.style.visibility = 'visible';

		fadeInElement(this.menu.id, 0, 0.3, 1);
		document.currentMenu = element.id;
		//Event.observe(document, 'click', this.closeMenu.bindAsEventListener(this));
		document.onclick = this.closeMenu.bindAsEventListener(this);
		
		if(this.openFunc)
			this.openFunc();
	},
	
	closeMenu: function()
	{
		if(!this.mouseHovered && document.currentMenu && !document.lockMenu)
		{
			menu = document.currentMenu;
			menu = $(menu+"_popup");
			fadeOutElement(document.currentMenu+"_popup", 1, 0.4, 0, function(){
				menu.style.display = "none";
			});
			document.currentMenu = "";
			document.onclick = function() { };
			
			if(this.closeFunc)
				this.closeFunc();
		}
	}
};



function fadeInElement(elemId, alpha, rate, targetAlpha, completeFunc)
{
	if((alpha += rate) > targetAlpha) alpha = targetAlpha;
	setOpacity(document.getElementById(elemId), alpha);
	if(alpha < targetAlpha)
		setTimeout(function(){fadeInElement(elemId, alpha, rate, targetAlpha, completeFunc);}, 50);
	else if(completeFunc)
		completeFunc();
}

function fadeOutElement(elemId, alpha, rate, targetAlpha, completeFunc)
{
	if((alpha -= rate) < targetAlpha) alpha = targetAlpha;
	setOpacity(document.getElementById(elemId), alpha);
	if(alpha > targetAlpha)
		setTimeout(function(){fadeOutElement(elemId, alpha, rate, targetAlpha, completeFunc);}, 50);
	else if(completeFunc)
		completeFunc();
}

// this function copied and modified from effects.js
function setOpacity(element, value)
{
	if (value == 1)
	{
		element.style.opacity = (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : null;
		if(/MSIE/.test(navigator.userAgent))
			element.style.filter = element.style.filter.replace(/alpha\([^\)]*\)/gi,'');  
	}
	else
	{
		if(value < 0.00001) value = 0;
		element.style.opacity = value;
		if(/MSIE/.test(navigator.userAgent))  
			element.style.filter = element.style.filter.replace(/alpha\([^\)]*\)/gi,'') +"alpha(opacity="+value*100+")";  
	}
}
