//this function is a basic Ajax request which takes in encoded form data
//parameters: the page to send the request to and the data to send to it
function requestAJAX(page, data) {
	////if the page or data parameters are blank
	if (page=="" || data=="") {
		//return nothing
		return;
	} 
  	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	//the on ready state change function is assigned here
	xmlhttp.onreadystatechange=function() {
		//once the state is set correctly and a successful http status is returned
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			//create a function called responseTextHandler with a string as parameter
			//inside this function do whatever you want
			responseTextHandler(xmlhttp.responseText);
		}
	}
	//open the http request. method is set to POST (as we are posting form data)
	xmlhttp.open("POST",page,true);
	//the type of content is going to be an encoded form
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
	//the length of the data is the string length of the parameter data
	xmlhttp.setRequestHeader("Content-length", data.length);
	xmlhttp.setRequestHeader("Connection", "close");
	//alert("Sending: " + data);
	//send the data
	xmlhttp.send(data);
}

//disables a forms ability to submit and sets the submit button to make an ajax request instead.
//(assumes that submit buttons have their name attribute set to "submit")
//parameters: the form to disable, the ajax page
function setAjaxFormSubmit(form,page) {
	//set the forms submit function to false
	form.onsubmit = function() {return false;};
	//get all the elements of the form
	submits = form.elements;
	//for each element
	for(var j = 0; j < submits.length; j++) {
		//if the element's name is submit
		if (submits[j].name == "submit") {
			//set the attribute "onclick" to encode the form and send it by ajax request
			submits[j].setAttribute("onclick","requestAJAX('"+page+"',encodeForm(this.form,this))");
		}
	}
}
//Encodes an entire form by
//parameters: The enclosing form and the submit button pressed
function encodeForm(form,submitButton) {
	//blank string which will hold the encoded data
	var str = '';
	//gets all the elements in the form
	var elem = form.elements;
	//for each element
	for(var i = 0; i < elem.length; i++) {
		//if the element is not a submit
		if (elem[i].type != "submit") {
			//start a name value pair
			str += elem[i].name + "=" ;
			if (elem[i].type == "textarea") {
				//if the element is a textarea then it should be initialized as a TinyMCE editor
				//this means we can use getContent() because when using TinyMCE innerHTML is erroneous
				str += encodeURIComponent(tinyMCE.get(elem[i].name).getContent()) + "";
			} else {
				//if the element is a regular input then simply encode the value
				str += encodeURIComponent(elem[i].value) + "";
			}
			//and ampersand for the next name value pair
			str += "&";
		}
	}
	//finally encode the submit buttons value. It is important
	//that only the supplied submit button parameter is encoded
	//as regular posting of form data will only post the submit button that is pressed
	//and ignore others if present.
	str += submitButton.name + "=" ;
	str += encodeURIComponent(submitButton.value) + "";
	return str;
}

//sets all delete buttons of the forms generated by the php class library's admin functions
//to show a confirm box before submitting the delete command
function disableDeleteSubmit() {
	//finds the submit buttons named "submitBlog" which deal with submitting blog posts
	//in the admin section
	var submits = document.getElementsByName("submitBlog");
	//for each submit button
	for(var i = 0; i < submits.length; i++) {
		//get the current form
		var currForm = submits[i].form;
		//get the title value
		var title = currForm.elements.title.value;
		//if the value attribute is set to Delete
		if (submits[i].getAttribute("value") == "Delete") {
			//set the onclick function to return a confirm alert box
			//taking in a string telling the user which blog post they are about to delete
			submits[i].setAttribute("onClick",'return confirmSubmit("Are you sure you want to delete the entry '+title+'?")');
		}
	}
	//finds the submit buttons named "submitUsers" and carries out the same procedure for the blog form.
	//these submits deal with submitting users
	submits = document.getElementsByName("submitUsers");
	//for each submit button
	for(var i = 0; i < submits.length; i++) {
		//get the current form
		var currForm = submits[i].form;
		//get the username value
		var username = currForm.elements.username.value;
		//if the value attribute is set to Delete User
		if (submits[i].getAttribute("value") == "Delete User") {
			//set the onclick function to return a confirm alert box
			//taking in a string telling the user which user they are about to delete
			submits[i].setAttribute("onClick",'return confirmSubmit("Are you sure you want to delete the user '+username+'?")');
		}
	}
	//finds the submit buttons named "submitPages" and carries out the same procedure for the users form.
	//These submits deal with submitting pages to sort blog posts
	submits = document.getElementsByName("submitPages");
	//for each submit button
	for(var i = 0; i < submits.length; i++) {
		//get the enclosing form
		var currForm = submits[i].form;
		//get the pageName value
		var pagename = currForm.elements.pageName.value;
		//if the value attribute is set to delete
		if (submits[i].getAttribute("value") == "Delete") {
			//set the onclick function to return a confirm alert box
			//taking in a string telling the user which page they are about to delete
			submits[i].setAttribute("onClick",'return confirmSubmit("Are you sure you want to delete the page '+pagename+'?")');
		}
	}
}

//replaces all the children of one element with another element
//parameters: the element to empty, the new element to fill the old element
function removeReplace(element, newElement) {
	//remove all children from the old element
	while ( element.childNodes.length >= 1 ) {
		//remove first child until there are none left
        element.removeChild( element.firstChild );       
    }
	//append the new elements children to the old element
	while ( newElement.childNodes.length >= 1 ) {
		//appending the child of another element will mvoe it and not copy it
		//so append children until the new element is empty
		element.appendChild(newElement.firstChild);
		//newElement.removeChild(newElement.firstChild); 
	}
}

//returns a string of the date now (local to client) in the format DD/MM/YYYY
function getDateNow() {
	//new date object
	var d = new Date();
	//the 0 is added to getDate and getMonth and then the string sliced in order to get just the last two characters
	//e.g. the date 4 becomes 04 and the date 10 remains 10 (because only the last two characters count)
	return ('0'+(d.getDate())).slice(-2)+"/"+('0'+(d.getMonth()+1)).slice(-2)+"/"+d.getFullYear();
}
//returns a string of the time now (local to client) in the format HH:MM
function getTimeNow() {
	var d = new Date();
	//the 0 is added to getHours and getMinutes and then the string sliced in order to get just the last two characters
	//e.g. the hour 7 becomes 07 and the minute 34 remains 34 (because only the last two characters count)
	return ('0'+d.getHours()).slice(-2)+":"+('0'+d.getMinutes()).slice(-2);
}

//sets the time and date inputs in the blog post form to be the clients time (as the default is the servers time)
function setTimeDateInputs() {
	//if there is not a postID input present then the form is not altering an existing post
	//and the the time and date can safelt be set to now
	if (document.forms['blogForm'] && !document.forms['blogForm'].elements["postID"] ) {
		//get the time and date elements in the blogForm and use the getTimeNow and  getDateNow
		//in order to set them
		if (document.forms['blogForm'].elements["entry"].innerHTML == "" && document.forms['blogForm'].elements["entrySummary"].innerHTML == ""
			&& document.forms['blogForm'].elements['title'].value == "" && document.forms['blogForm'].elements['categories'].value == "") {
			document.forms['blogForm'].elements["time"].value = getTimeNow();
			document.forms['blogForm'].elements["date"].value = getDateNow();
		}
	}
}

//generates a confirm alert box
//can be used to ask the user if they are sure before deleting something for example.
//parameters: the string to display in the confirm box
function confirmSubmit(str) {
	//generate confirm
	var agree=confirm(str);
	//return true or false after the user decides
	if (agree)
		return true ;
	else
		return false ;
}

//sets the display style property to "block" in order to show the element
//parameters: The id of the element to show
function showStuff(id) {
	document.getElementById(id).style.display = 'block';
}
//sets the display style property to "none" in order to hide the element
//parameters: The id of the element to hide
function hideStuff(id) {
	document.getElementById(id).style.display = 'none';
}
//toggles an elements display style property between "block" and "none"
//parameters: The id of the element
function toggleHide(id) {
	var element;
	element = document.getElementById(id);
	if(element.style.display == 'block') {
		element.style.display = 'none';
	} else if (element.style.display == 'none') {
		element.style.display = 'block';
	}
}

//gets the blog tinyMce editors and clears their content
function clearMCE() {
	if (document.forms['blogForm'] && !document.forms['blogForm'].elements["postID"]) {
		if(document.forms['blogForm'].elements["entry"].innerHTML == "") {
			tinyMCE.get('entry').setContent('');
		}
		if(document.forms['blogForm'].elements["entrySummary"].innerHTML == "") {
			tinyMCE.get('entrySummary').setContent('');
		}
	}
}
