/**
* AjaxChat Shoutouts Module for Joomla1.5
* @copyright (c) Fiji Web Design, www.fijiwebdesign.com
* @author gabe@fijiwebdesign.com
* @license http://www.fijiwebdesign.com/
*/

// define ajaxchat namespace
if (typeof(ajaxchat) == 'undefined') {
	ajaxchat = {};
}

/**
 * Shoutouts obj
 */
ajaxchat.shoutouts = {
	
	// global chat html content storage obj
	current_chat: false,
	// global message count
	session_msgs: 0,
	// in request?
	requestMode: false,
	// allow set ping?
	_setTimeout: true,
	
	/**
	 * Load the Shoutouts
	 */
	init: function() {
		ajaxchat.shoutouts.config.serverUrl = ajaxchat.shoutouts.getSameDomain(ajaxchat.shoutouts.config.serverUrl);
		ajaxchat.shoutouts.shoutMsgs();
	},
	
	/**
	 * Add a window Onload Event
	 */
	attachLoadEvent: function(fn) {
		var oldonload = window.onload;
		window.onload = window.onload != 'function' ? fn : function() {
			oldonload();
			fn();
		};
	},
	
	/**
	 * Debugging
	 * @param String 
	 */
	debug: function(txt) {
		if (ajaxchat.shoutouts.config.verbose == '1') {
			if (el = document.getElementById('so_verbose')) {
				el.value = txt+"\r\n"+el.value;
				// pop the last line off when over [this.maxlen] lines
				var arr = el.value.split("\r\n");
				if (arr.length > this.maxlen) {
					arr.pop();
					el.value = arr.concat("\r\n");
				}
			}
		}
	},
	
	/**
	 * Returns the URL with the same domain as document domain (same origin policy)
	 * @param {String} url URL including http://
	 * @return {String} URL with domain portion replaced with current domain
	 */
	getSameDomain: function(url) {
		return url.replace(/^http:\/\/[^\/]+/, window.location.href.match(/^http:\/\/[^\/]+/));
	},
	
	/**
	 * Retrieve Shout Messages
	 */
	shoutMsgs: function() {
		ajaxchat.shoutouts.requestMode = true; // in request
		try {
			ajaxchat.shoutouts.debug('new msgs request: ' + ajaxchat.shoutouts.config.serverUrl + "/index2.php?option=" + encode('com_ajaxchat') + "&no_html=1&task=lastmsgs&roomid=" + encode(ajaxchat.shoutouts.config.roomid) + "&recipient=" + encode(ajaxchat.shoutouts.config.recipient));
			return new AJAXRequest("post", ajaxchat.shoutouts.config.serverUrl + "/index2.php", "option=" + encode('com_ajaxchat') + "&no_html=1&task=lastmsgs&roomid=" + encode(ajaxchat.shoutouts.config.roomid) + "&recipient=" + encode(ajaxchat.shoutouts.config.recipient) + "&total=" + encode(ajaxchat.shoutouts.config.total) + "&r=" + encode((new Date()).getTime()), ajaxchat.shoutouts.handleShoutMsgs);
		} catch(e) {
			alert(e);
		}
	},
	
	/**
	 * Write Message to ui
	 */
	handleShoutMsgs: function(xhr) {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				var xml = xhr.responseXML;
				var text = xhr.responseText;
				ajaxchat.shoutouts.debug('Response text/xml: ' + text);
				
				// parse the xml
				if (xml && xml.documentElement) {
					var messages = xml.documentElement.getElementsByTagName("msg");
					if (messages && messages.length > 0) {
						ajaxchat.shoutouts.addMsgs(messages);
					} else {
						ajaxchat.shoutouts.debug('no msgs to read');
					}
				}
			} else {
				ajaxchat.shoutouts.debug("There was a problem retrieving the XML data:\n" + myAJAX.statusText);
			}
			
			ajaxchat.shoutouts.requestMode = false;
			if (ajaxchat.shoutouts._setTimeout) {
				setTimeout(ajaxchat.shoutouts.shoutMsgs, ajaxchat.shoutouts.config.period * 1000);
			} else {
				ajaxchat.shoutouts._setTimeout = true;
			}
		}
	},
	
	/**
	 * Write the Messages
	 * @param {Array} msgs
	 */
	addMsgs: function(msgs) {
		var shout_msgs = document.getElementById('shout_msgs');
    
	    var html = '<form name="shoutMsgs">';
	    for (var i = 0; i < msgs.length; i++) {
	
	        try { var user = msgs[i].getAttributeNode("user").nodeValue; } catch(e) {}
	        try { var userid = msgs[i].getAttributeNode("userid").nodeValue; } catch(e) {}
	        var msg = decode(msgs[i].firstChild.nodeValue);
	        
	        if (ajaxchat.shoutouts.config.profiles && user != ajaxchat.shoutouts.config.system_user) { // comprofiler
				user =ajaxchat.shoutouts.makeUserProfileUrl(user, userid, ajaxchat.shoutouts.serverUrl);
	        }
	        
	        html += ajaxchat.shoutouts.makeShoutMessage(user, msg);
	    }
	    html += '</form>';
	    shout_msgs.innerHTML = html;
		
	},
	
	/**
	 * Get the Shout Message Template
	 * @param {String} username
	 * @param {String} msg
	 * @param {String} time // todo
	 */
	makeShoutMessage: function(username, msg, time) {
		var post = '';
		if (ajaxchat.shoutouts.config.msg_template) {
			var post = ajaxchat.shoutouts.config.msg_template;
			post = post.replace(/{username}/, username);
			post = post.replace(/{msg}/, msg);
		} else {
			post += '<fieldset>';
			post += '<legend>'+username+'</legend>';
	        post += msg;
	        post += '</fieldset>';
		}
		return post;
	},
	
	/**
	 * Get the Shout Profile URL
	 * @param {Object} username
	 * @param {Object} userid
	 * @param {Object} live_site
	 */
	makeUserProfileUrl: function(username, userid, live_site) {
		if (ajaxchat.shoutouts.config.profile_url) {
			var profile_url = ajaxchat.shoutouts.config.profile_url;
			profile_url = profile_url.replace(/{userid}/, userid);
			profile_url = profile_url.replace(/{username}/, username);
			profile_url = profile_url.replace(/{live_site}/, live_site);
			
			return '<a href="'+profile_url+'"'+(ajaxchat.shoutouts.config.profile_newwin ? ' target="_blank"' : '')+'>'+username+'</a>';
			
		} else {
			return username;
		}
	},
	
	/**
	 * Send Message to server
	 * @param {String} msg
	 * @param {String} roomid
	 * @param {String} recipient
	 */
	shoutPostMsg: function(msg, roomid, recipient) {
		if (msg) {
			ajaxchat.shoutouts._setTimeout = false; // stop polling for this result
		  	ajaxchat.shoutouts.debug('new msgs request: ' + ajaxchat.shoutouts.config.serverUrl + "/index2.php?option=" + encode('com_ajaxchat') + "&no_html=1&task=rwrite&roomid=" + encode(roomid) + "&recipient=" + encode(recipient) + "&msg=" + encode(msg));
		    return new AJAXRequest("post", ajaxchat.shoutouts.config.serverUrl + "/index2.php", "option=" + encode('com_ajaxchat') + "&no_html=1&task=rwrite&roomid=" + encode(roomid) + "&recipient=" + encode(recipient) + "&msg=" + encode(msg) + "&r=" + encode(Math.round(999*Math.random())), ajaxchat.shoutouts.shoutMsgs);
		}
	},
	
	/**
	 * Toggle Element Display
	 * @param {Element} el
	 */
	toggleDisplay: function(el) {
		el = $(el);
		el.style.display = el.style.display == 'none' ? '' : 'none';
	},
	
	/**
	 * View more messages
	 */
	viewMore: function() {
		if (ajaxchat.shoutouts.config.total >= ajaxchat.shoutouts.config.all) {
			alert(ajaxchat.shoutouts.config.max_msgs_reached.replace('%n', ajaxchat.shoutouts.config.all));
		} else {
			ajaxchat.shoutouts.config.total = ajaxchat.shoutouts.config.total + 10;
			ajaxchat.shoutouts.shoutMsgs();
		}
	},
	
	/**
	 * Handle key presses in msg box
	 * @param {Object} e
	 */
	handleMsgKeyDown: function(e) {
		e = e || window.event;
		if (!e.shiftKey && e.keyCode == 13) {
			ajaxchat.shoutouts.handleShout(e);
		}
	},
	
	/**
	 * Handle Shout
	 */
	handleShout: function(e) {
		var input = document.getElementById('shout_msg');
		if (input && input.value) {
			ajaxchat.shoutouts.shoutPostMsg(input.value, ajaxchat.shoutouts.config.roomid, 'all');
			input.value = '';
		} else {
			alert(ajaxchat.shoutouts.config.empty_msg);
		}
	}
		
};

