var request; //for the XHR object, used by several functions.

/**
 * Creates an XHR. Checks for answer and call the callback function when ready.
 * Set headers and send parameters.
 *
 * @url: The URL to be contacted in the server request (with parameters for the GET method).
 * @callback: The callback function.
 * @meth: Method - POST or GET.
 * @parameters: Parameters for the POST-method or null for the GET method.
 * @request: The XHR object.
 */

function useXMLHttpRequest(url, callback, meth, parameters) {
	request = getXMLHttpRequest();
	request.open(meth,url,true);
	request.onreadystatechange = callback;
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	if (meth == "POST") {
		request.setRequestHeader("Content-length", parameters.length);
		request.setRequestHeader("Connection", "close");
	}
	request.send(parameters);
}

/**
 * Creates a XMLHttpRequest object.
 */
function getXMLHttpRequest() {
	if (window.XMLHttpRequest) { //for FF, Opera, Safari, IE7+ mm.
		return new XMLHttpRequest();
	}

	else { //for older versions of IE
	  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
	  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
	  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
	  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
	  throw ("Din browser understøtter ikke XMLHttpRequest som er krævet på simonkvamm.dk. Opgradér enten til nyere versioner, eller download Firefox gratis på mozilla.com.");
	}
}




/**
 * Get labels when user types entry in search field.
 *
 * @entry: String of text typed in by user.
 * @rand: Random number to avoid cache in browser.
 * @url: URL to use in callback function.
 * @callback: Name of the callback function.
 */

function hent_labels(entry) {
	if (entry.length == 0) {  //if string is empty (e.g. if user deletes the entry)
		document.getElementById("label").innerHTML = "";
	}
	else {  //if string is not empty.
		//Prepare XHR variables and
		rand = Math.floor(Math.random()*1000000);
		url = "php_scripts/hent_labels.php?indtastning="+entry+"&random="+rand;
		callback = vis_labels;
		useXMLHttpRequest(url, callback, "GET", null);
	}
}


/**
 * Show labels beneath the seach field.
 * When call to server is done, readyState equals 4.
 * When call not done (rs = 1-3), do nothing.
 * If call is ok, request status equals 200.
 *
 * @request: XHR object.
 */
function vis_labels() {
	if (request.readyState == 4) {
		if (request.status == 200) {
			document.getElementById("label").innerHTML = request.responseText;  //place labels in relevant element
		}

		else {
			document.getElementById("label").innerHTML = "Fejl. Labels kunne ikke vises. Opdatér venligst browseren. Kontakt snaps@simonkvamm.dk for vedvarende fejl.";
		}
	}
}



/**
 * Shows a fixed number of news set by a constant (at the time, 30).
 * If a label is chosen by user, only news with that label will be shown.
 *
 * @side: The news page. If more than one page, first page will be from news #0 to #29, second page from #30 to #59 an so on.
 * @vlabel: Chosen label. Is only set if the user chose a label.
 * @run_self: If equal 1, php function vis_alle_nyheder() runs by itself (e.g. by first entry by user).
 * @rand: Random number to avoid cache in browser.
 * @url: URL to use in callback function.
 * @callback: Name of the callback function.
 */

var side = 1; //Standard - first page. Will be set according to the users choice. Scope of variable: the next 3 functions.
 
function vis_nyhedsside(side, vlabel) {
	this.side = side;
	if (vlabel == "")
		vlabel = document.getElementById('vlabel').innerHTML;
	run_self = 1; 
	rand = Math.floor(Math.random()*1000000);
	url = "php_scripts/vis_nyheder.php?side="+side+"&run_self="+run_self+"&vlabel="+vlabel+"&random="+rand;
	callback = vis_nyheder;
	useXMLHttpRequest(url, callback, "GET", null);
}


/**
 * Callback function for showing news.
 * Show the news and call the function set_sidetal.
 * When call to server is done, readyState equals 4.
 * When not done (rs = 1-3), show user a pause text.
 * If call is ok, request status equals 200.
 *
 * @request: XHR object.
 * @rs: The readystate for the XHR object.
 */
function vis_nyheder() {
  rs = request.readyState;

	if (rs == 4) {
		if (request.status == 200) {
		  document.getElementById("alle_nyheder").innerHTML = request.responseText;
			set_sidetal();
		}

		else {
			document.getElementById("alle_nyheder").innerHTML = "Fejl. Nyheder kunne ikke vises. Opdatér venligst browseren. Kontakt snaps@simonkvamm.dk ved vedvarende fejl.";
		}
	}
	else {
	  if (rs == 1)
  	  document.getElementById("alle_nyheder").innerHTML = "Henter nyheder - vent venligst .";
	  else if (rs == 2)
  	  document.getElementById("alle_nyheder").innerHTML = "Henter nyheder - vent venligst ..";
	  else if (rs == 3)
  	  document.getElementById("alle_nyheder").innerHTML = "Henter nyheder - vent venligst ...";
	}
}

/**
 * Show the chosen news page. One page equals (at the time) 30 news.
 * First entry on site will show the first page (news #0-29). 
 * @side: The current page.
 * @antal: Number of news per page (is taken from the user database. Standard and only option at the time is 30).
 * @antal_ialt: Total number of news.
 * @sider_ialt: Total number of pages (antal_ialt divided by antal). 
 * @a1, a2, a4, a5: The pages. a3 is the current page and therefore referred to as this.
 */

function set_sidetal() {
	side = parseInt(side);
	antal = document.getElementById('pref_antalnyheder').innerHTML;
	antal_ialt = document.getElementById('antal_nyheder').innerHTML;

  //Make sure the site numbers are at least 1
	a2 = side-1;  //a2 is the page below the current page
	a1 = a2-1;  //a1 is the page below a2
	if (a2 < 1)  //if the current page is page 1
		a2 = "";  //hide a2
	if (a1 < 1)  //if a2 or the current page is page 1
		a1 = "";  //hide a1

	//Calculates the following pagenumbers.
	sider_ialt = Math.ceil(antal_ialt/antal);
	a4 = side+1;  //a4 is the page above the current page.
	a5 = a4+1;  //a5 is the page above a3
	if (a4 > sider_ialt)  //if there are no more pages to show
		a4 = "";  //hide a4
	if (a5 > sider_ialt)  //if there are no more pages to show after a3
		a5 = "";  //hide a5

	//Place number of current page + the calculated pagenumbers around current page on website.
	document.getElementById("aktuel").innerHTML = side;  //set current page to chosen page.
	document.getElementById("a1").innerHTML = a1;
	document.getElementById("a2").innerHTML = a2;
	document.getElementById("a4").innerHTML = a4;
	document.getElementById("a5").innerHTML = a5;
}


/**
 * Get comments associated with the displayed news.
 *
 * @nyhedsdiv: The div element withholding the displayed news. The variable scope includes the function vis_kommentarer.
 * @kommuid: The unique id for the comment. The variable scope includes the function vis_kommentarer.
 * @nyh_uid: The unique id for the news. 
 *
 * @rand: Random number to avoid cache in browser.
 * @url: URL to use in callback function.
 * @callback: Name of the callback function.
 */
var nyhedsdiv = null;
var kommuid = null;

function hent_kommentarer(nyh_uid, nyhedsdiv) {
	this.nyhedsdiv = nyhedsdiv;
	this.kommuid = "k" + nyh_uid;

	rand = Math.floor(Math.random()*1000000);
	url = "php_scripts/vis_kommentarer.php?nyh_uid="+nyh_uid+"&random="+rand;
	callback = vis_kommentarer;

	useXMLHttpRequest(url, callback, "GET", null); 
}

/**
 * Callback function for hent_kommentarer.
 * Show comments associated the diplayed news.
 *
 * When call to server is done, readyState equals 4.
 * When call not done (rs = 1-3), do nothing.
 * If call is ok, request status equals 200.
 * Create new element with attributes, append it to the news element and style it.
 *
 * @request: The XHR object.
 * @element: Element for the comments.
 * @child: Element set to be the child of the news element. Absorbs the created comment element.
 *
*/

function vis_kommentarer() {
	if (request.readyState == 4) {
		if (request.status == 200) {
		  if (request.responseText != "") {
				var element = null;
				try {  //create new element with attributes for IE
			    element = document.createElement("<div id='"+kommuid+"' class='kommentarer'></div>");
				} catch (e) {  //create new element and attributes for Firefox
			    element = document.createElement("div");
			    element.setAttribute("id", kommuid);
			    element.setAttribute("class", "kommentarer");
				}

				child = nyhedsdiv.appendChild(element);
				child.style.position = "absolute";
				child.style.top = "0px"; 
				child.style.zIndex = 10;
				child.innerHTML = "<b>Kommentarer</b><br /><br />" + request.responseText;
			}
		}

		else {
			document.getElementById("alle_nyheder").innerHTML = "Fejl. Kommentarer kunne ikke vises. Opdatér venligst browseren. Kontakt snaps@simonkvamm.dk ved vedvarende fejl.";
		}
	}
}

/**
 * Hide comments if news is hidden by user.
 *
 * @kuid: The unique id for the comment.
 */
function skjul_kommentarer(kuid) {
  document.getElementById(kuid).parentNode.removeChild(document.getElementById(kuid));
}




/**
 * Get text from html form (news, update, comment).
 *
 * @form2: Html form filled in by the user. Scope is for next function as well.
 * @type1: The type - news, update or comment.
 * @parameters: Variables for the POST method of the XHR object.
 * @tekst: Text from the forms - makes breaks with html tags and escape everything.
 *
 * --- news variables ---
 * @nyh_type: ??
 * @nyhlink_uid: ?? If set, the news already exists and therefore it's an update or comment to that specific news.
 * @nyhlink: ??
 *
 * @rubrik: News header typed by user.
 * @link1-3: The three links typed by user.
 * @labels: The labels typed by user.
 * @billurl: URL for the image chosen/uploaded by user. Image function does not work yet.
 *
 * @loginnavn: User information.
 * @inde: User information.
 *
 * @rand: Random number to avoid cache in browser.
 * @url: URL to use in callback function.
 * @callback: Name of the callback function.
 */

var form2 = null;

function get_nyhelementer(form2, type1) {
	this.form2 = form2;
	var parameters = "";
	var tekst = form2.tekst.value.replace(/\n/g,'<br />');
	tekst = escape(tekst);
	var rand = Math.floor(Math.random()*1000000);
	var nyh_type = escape(form2.nyh_type.value);
	var loginnavn = document.getElementById("loginnavn").innerHTML;  //henter brugernavn fra span-element da sessions slettes
	var inde = document.getElementById("inde").innerHTML;  //henter login ok fra div-element

	if (form2.nyhlink_uid) {  //hvis det er en opdatering eller kommentar
		var nyhlink = escape(form2.nyhlink_uid.value);
		if (nyhlink == "") {
			alert("Du skal vælge en nyhed i oversigten inden du gemmer.")
			return false;
		}
	}

	if (type1 == "kommenter") {  //hvis det er en kommentar, er der kun tekst og uid
		parameters = "tekst="+tekst+"&nyhlink="+nyhlink+"&nyh_type="+nyh_type+"&random="+rand+"&inde="+inde+"&loginnavn="+loginnavn;
	}

	else {  //hvis det er en ny nyhed eller opdatering, er der flere variabler der skal hentes
		var rubrik = escape(form2.rubrik.value);
		var link1 = escape(form2.link1.value);
		var link2 = escape(form2.link2.value);
		var link3 = escape(form2.link3.value);
		var labels = escape(form2.labels.value);
		var billurl = null;
		parameters = "rubrik="+rubrik+"&tekst="+tekst+"&link1="+link1+"&link2="+link2+"&link3="+link3+"&labels="+labels+"&nyhlink="+nyhlink+"&billurl="+billurl+"&nyh_type="+nyh_type+"&loginnavn="+loginnavn+"&random="+rand+"&inde="+inde;
	}

	url = "php_scripts/nyhed_gem.php";
	callback = gem_nyhed;

	useXMLHttpRequest(url, callback, "POST", parameters);
}

/**
 * Callback function for get_nyhelementer.
 * Save and confirm typed in news, obtain updated news list and list it in div element.
 *
 * When call to server is done, readyState equals 4.
 * When call not done (rs = 1-3), do nothing.
 * If call is ok, request status equals 200.
 * Call clear form after ok status is confirmed and clear confirm status in response div (created in php function).
 * 
 * @request: XHR object.
 * @form2: Html form from previously function - used for clear form function. 
 */
function gem_nyhed() {
	if (request.readyState == 4) {
		if (request.status == 200) {
		  document.getElementById("alle_nyheder").innerHTML = request.responseText;
			clear_form(form2);
			setTimeout("document.getElementById('response').innerHTML = ''", 5000);
		}

		else {
			document.getElementById("dynamisk_skriv_div").innerHTML = "Fejl " + request.statusText + " . Kontakt venligst snaps@simonkvamm.dk.";
		}
	}
}
