// JavaScript Document
// code obtained from tutorial at http://www.yourhtmlsource.com/javascript/ajax.html written by Ross Shannon
// modified a lot by me, BogusRed
/* Once the page loads, loop through form elements and finds 
forms with the class "ajaxify" to listen 
for submits from these forms*/


// create new cross-browser compatible object through Sarissa class

function init_ajax_forms() {
    if (!Sarissa || !document.getElementsByTagName){
		alert("Initialization cancelled.");
		return;
	}
    // this array stores info on all the forms on the page
    var formElements = document.getElementsByTagName('form');
	// loop through all form elements and add event listener on those with proper class name
	
    for (var i = 0; i < formElements.length; i++) {
        if (formElements[i].className.match("userchatboxform")) {
            addEvent(formElements[i], 'submit', submit_userchatbox, false);
        } else if(formElements[i].className.match("publicchatboxform")){
			addEvent(formElements[i], 'submit', submit_public_chatbox, false);
		} else if(formElements[i].className.match("groupchatboxform")){
			addEvent(formElements[i], 'submit', submit_group_chatbox, false);
		}
    }
}



function chatbox_loading_feedback(elementId){
	document.getElementById(elementId).innerHTML = '<p><img src="/images/icons/loading2.gif" width="13" height="13"> Loading Chatbox...</p>';
}
function load_publicchatbox_contents(){
	chatbox_loading_feedback('publicchatbox');
	load_chatbox_contents('publicchatbox', '/scripts/ajax/publicchatboxdisplay.php', 'action=getposts');
}
function load_groupchatbox_contents(){
	chatbox_loading_feedback('groupchatbox');
	load_chatbox_contents('groupchatbox', '/scripts/ajax/groupchatboxdisplay.php', 'group_id='+group_id);
}
function load_userchatbox_contents(){
	chatbox_loading_feedback('userchatbox');
	load_chatbox_contents('userchatbox', '/scripts/ajax/userchatboxdisplay.php', 'chatboxowner='+chatboxowner);
}

/* works with both chatboxes */
function load_chatbox_contents(elementId, scriptSrc, postData){
	var xmlhttp_chatboxget =  new XMLHttpRequest();
	//alert('loading chatbox contents');
	// get latest contents of chatbox
    xmlhttp_chatboxget.open('POST', scriptSrc, true);

    xmlhttp_chatboxget.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp_chatboxget.send(postData);
	//
    /* set chatbox contents */
    xmlhttp_chatboxget.onreadystatechange = function() {
        if (xmlhttp_chatboxget.readyState == 4) {
            if (xmlhttp_chatboxget.status == 200){
				document.getElementById(elementId).innerHTML = '';
				//loop through and get all of the children
				node = xmlhttp_chatboxget.responseXML.getElementsByTagName('display')[0].firstChild;
				chatboxtext = '';
				while(node != null){
					chatboxtext += node.data;
					node = node.nextSibling;
				}
				document.getElementById(elementId).innerHTML = chatboxtext;
            }
        }
    }
}
function submit_userchatbox(e){
    /* Cancel the submit event, and find out which form was submitted */
    knackerEvent(e);
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target){
		return;
    }
	
	var postData = 'post='+target.elements['userchatboxpost'].value+'&action=post&chatboxowner='+chatboxowner;

	submit_chatbox(target, 'userchatbox', 'userchatboxstatus', '/scripts/ajax/userchatboxpost.php', postData);
	// refresh chatbox contents:
	load_userchatbox_contents();	
	// reset form inputs
	document.getElementById('userchatboxpost').value = '';
}
function submit_group_chatbox(e){
    /* Cancel the submit event, and find out which form was submitted */
    knackerEvent(e);
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target){
		return;
    }
	
	var postData = 'post='+target.elements['groupchatboxpost'].value+'&action=post&group_id='+group_id;

	submit_chatbox(target, 'groupchatbox', 'groupchatboxstatus', '/scripts/ajax/groupchatboxpost.php', postData);
	//wait a second for submit to be successful
	// refresh chatbox contents after 3 seconds
	setTimeout('load_groupchatbox_contents();',1000);
		
	// reset form inputs
	document.getElementById('groupchatboxpost').value = '';
}
function submit_public_chatbox(e){
    /* Cancel the submit event, and find out which form was submitted */
    knackerEvent(e);
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target){
		return;
    }

	//need to use escape because of the unicode characters that may be present
	postStr = escape(target.elements['publicchatboxpost'].value);

	var postData = 'post='+postStr+'&action=post';
	submit_chatbox(target, 'publicchatbox', 'publicchatboxstatus', '/scripts/ajax/publicchatboxpost.php', postData);
	// refresh chatbox contents:
	setTimeout('load_publicchatbox_contents();',1000);

	// reset form inputs
	document.getElementById('publicchatboxpost').value = '';
}

function submit_chatbox(target, elementId, statusId, scriptSrc, postData) {
	var xmlhttp_chatboxsubmit =  new XMLHttpRequest();

    /* Set up the request */
    xmlhttp_chatboxsubmit.open('POST', scriptSrc, true);
    
    
    // Send the POST request
    xmlhttp_chatboxsubmit.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp_chatboxsubmit.send(postData);
    
	// Add temporary feedback that the request has been sent  

	document.getElementById(statusId).innerHTML = '';
	document.getElementById(statusId).innerHTML = '<p style="margin: 0px;">Submitting...</p>';
	target.ajaxInProgress = true;

    /* The callback function */
    xmlhttp_chatboxsubmit.onreadystatechange = function() {
        if (xmlhttp_chatboxsubmit.readyState == 4) {
            if (xmlhttp_chatboxsubmit.status == 200){
                reset_chatbox_form(statusId);
            } else{
                target.submit();
			}
        }
    }

}

function reset_chatbox_form(elementId){
	// Free up the form to go again
	document.getElementById(elementId).innerHTML = '';
	document.getElementById(elementId).innerHTML = '<input type="submit" name="Submit" value="Post Message">';
	target.ajaxInProgress = false;
}

