/**
* Shout Outs Functions - requires the ajaxchat component
* (c) www.fijiwebdesign.com
*/

//common = new commonLib(); // instatiate common functions lib

function so_debug(txt) {
  if (so_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");
		}
	}
  }
}

// hack for debugging
//_debug = so_debug;

var current_chat = ''; // global chat html content storage obj
var session_msgs = '0'; // global message count
var requestMode = false; // in request?
var _setTimeout = true; // allow set ping?

/**
* Retrieve msgs
*/
function shoutMsgs() {

    requestMode = true; // in request
	try {
		so_debug('new msgs request: ' + so_serverUrl + "/index2.php?option=" + encode('com_ajaxchat') + "&no_html=1&task=lastmsgs&roomid=" + encode(so_roomid) + "&recipient=" + encode(so_recipient));
		return new AJAXRequest("post", so_serverUrl + "/index2.php", "option=" + encode('com_ajaxchat') + "&no_html=1&task=lastmsgs&roomid=" + encode(so_roomid) + "&recipient=" + encode(so_recipient) + "&total=" + encode(so_total) + "&r=" + encode((new Date()).getTime()), shoutShowMsgs);
	} catch(e) {
		// trap error
	}
}

/**
* Write msgs
*/
function shoutShowMsgs(myAJAX) { 

        if (myAJAX.readyState == 4) {

        try {
        	myAJAX.status;

			if (myAJAX.status == 200) {
				var xml = myAJAX.responseXML;
				var text = myAJAX.responseText;
				so_debug('Response text/xml: ' + text);
	
				// parse the xml
				if (xml) {
				  if (xml.documentElement) {
					var messages = xml.documentElement.getElementsByTagName("msg");
					//logger(messages);
	
					try {
						var msgs_len = messages.length;
					} catch (e) {
						var msgs_len = 0;
					}
	
					if (msgs_len > 0) {
	
						addMsgs(messages);
	
					} else {
					  so_debug('no msgs to read');
	
					}
				  }
				}
			} else {
				so_debug("There was a problem retrieving the XML data:\n" + myAJAX.statusText);
			}
			
			requestMode = false;
			if (_setTimeout)
			setTimeout(shoutMsgs, so_period*1000);
			else _setTimeout = true;
		
		 } catch(e) {
			 try {
            	so_debug('error: '+e);
			 } catch(e) {}
            return false;
        }
    }
}

/**
* Write msgs
*/
function addMsgs(msgs) { so_debug('add 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 (so_profiles && user != so_system_user) { // comprofiler
			user = so_makeUserProfileUrl(user, userid, so_serverUrl);
        }
        
        html += so_makeShoutMessage(user, msg);
    }
    html += '</form>';
    shout_msgs.innerHTML = html;
}

/**
* Return the message created from template
*/
function so_makeShoutMessage(username, msg) {
	var post = '';
	if (so_msg_template && so_msg_template != '') {
		var post = so_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;
}

/**
* Return the users profile link
*/
function so_makeUserProfileUrl(username, userid, live_site) {
	if (so_profile_url != '') {
		var profile_url = so_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+'"'+(so_profile_newwin ? ' target="_blank"' : '')+'>'+username+'</a>';
		
	} else {
		return username;
	}
}

/**
* Write msgs
*/
function shoutPostMsg(msg, roomid, recipient) {
	_setTimeout = false; // stop polling for this result
  	so_debug('new msgs request: ' + so_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", so_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())), shoutMsgs);

}

