// ------------------------------------------
// CLASS   : mcms_div_popup
// descr.  : manages the div-popup function
// author  : Richard Lagerström (+46 739 39 19 10)
// website : http://www.empty.se, http://www.mediatroop.se
// date    : 2007-04-05
// ------------------------------------------
function html_entity_decode(str)
{
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}

function mcms_ajax()
{
	// -------------------------------------------
	// properties
	// -------------------------------------------
		/* xml http request holder
		 * @var boolean
		*/
		this.xmlhttp = "";						// this is changed during run time
		this.readystate = "";					// this is changed during run time
		this.seconds = 0;						// number of seconds trying to fetch data without luck. this is changed during run time
		this.objInterval = null;				// interval holder for trying to fetch data
		this.feedback_type = "";				// type of feedback (alert etc)
		this.objPreloader = null;				// preloader object
		
	// -------------------------------------------
	// methods
	// -------------------------------------------
		/* initialized the preloader
		 * @param 
		 * @return void
		*/
		this.initPreloader = function()
		{
			// create preloader if it does not exist
			if(!mcmsAjax.objPreloader) this.createPreloader();
			
			// make sure we got the preloader object
			if(mcmsAjax.objPreloader)
			{	
				// show preloader
				mcmsAjax.objPreloader.style.display = "block";
				
				// clear the preloader
				mcmsAjax.objPreloader.innerHTML = "<b>Skickar uppgifter</b><br/>";
				
				// make preloader follow mouse
				//document.onmousemove = mcmsAjax.preloaderFollowMouse;
			}
			else
			{
				alert("Could not create preloader object.");
			}
		}
		
		
		/* load url
		 * @param 
		 * @return void
		*/
		this.loadUrl = function(url, method, post_data, feedback_type)
		{
			// store feedback type for this load
			this.feedback_type = feedback_type;
			
			// set method to POST/GET
			if(method.toLowerCase() == "post") method = "POST"; else method = "GET";
			
			// if method is GET, then append querystring to url
			if(method == 'GET') url = url+'?'+post_data;
			
			// declare xmlhttp holder
			this.xmlhttp=null;
			
			// code for Mozilla, etc.
			if(window.XMLHttpRequest)
			{
				this.xmlhttp = new XMLHttpRequest();
			}
			// code for IE
			else if(window.ActiveXObject)
			{
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			if (this.xmlhttp != null)
			{
				// The async parameter specifies whether the request should be handled asynchronously or not. 
				// True means that script continues to run after the send() method, without waiting for a response from the server. 
				// false means that the script waits for a response before continuing script processing. 
				// By setting this parameter to false, you run the risk of having your script hang if there is a network or server problem, 
				// or if the request is long (the UI locks while the request is being made) a user may even see the "Not Responding" message. 
				// It is safer to send asynchronously and design your code around the onreadystatechange event!
				this.xmlhttp.onreadystatechange = this.readyStateChanged;
				this.xmlhttp.open(method , url, true);
				this.xmlhttp.setRequestHeader("Method", ""+method+" " + "" + " HTTP/1.1");
				if(method == "POST") this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-4");
				if(method == "GET")  this.xmlhttp.setRequestHeader("Content-Type", "text/html;charset=iso-8859-4");
				this.xmlhttp.setRequestHeader("Pragma", "no-cache");
				this.xmlhttp.setRequestHeader("Cache-Control", "no-cache, must revalidate");
				this.xmlhttp.send(this.escapeSpecialChars(post_data));
			}
			else
			{
				alert("Your browser does not support XMLHTTP.");
			}
		}
		
		
		/* THIS METHOD IS MORE LIKE A TEMPLATE TO BUILD CUSTOME ONES
		 * events on ready state changed
		 * @param 
		 * @return void
		*/
		this.readyStateChanged = function()
		{
			// grab readystate
			mcmsAjax.readystate = mcmsAjax.xmlhttp.readyState;
			
			// set status responses for live feature
			var live 	= new Array(5);
			live[0] 	= "Initialiserar ...";
			live[1] 	= "Slar upp URL ...";
			live[2] 	= "Ok";
			live[3] 	= "Laddar ...";
			live[4] 	= "Ok ";
			
			// get preloader contents
			if(mcmsAjax.objPreloader) var preloader_html = mcmsAjax.objPreloader.innerHTML.toString(); else preloader_html = "";
			
			// xmlhttp.readystate conversions
			// 0 = uninitialized
			// 1 = loading
			// 2 = loaded
			// 3 = interactive
			// 4 = complete 
			// check for readystate
			if(mcmsAjax.readystate == 0)
			{
				if(mcmsAjax.objPreloader && preloader_html.indexOf(live[0]) == -1) mcmsAjax.objPreloader.innerHTML = live[0] + "<br/>";
			}
			else if(mcmsAjax.readystate == 1)
			{
				if(mcmsAjax.objPreloader && preloader_html.indexOf(live[1]) == -1) mcmsAjax.objPreloader.innerHTML += live[1] + "";
			}
			else if(mcmsAjax.readystate == 2)
			{
				if(mcmsAjax.objPreloader && preloader_html.indexOf(live[2]) == -1) mcmsAjax.objPreloader.innerHTML += live[2] + "<br/>";
			}
			else if(mcmsAjax.readystate == 3)
			{
				if(mcmsAjax.objPreloader && preloader_html.indexOf(live[3]) == -1) mcmsAjax.objPreloader.innerHTML += live[3] + "";
			}
			else if (mcmsAjax.readystate == 4)
			{
				// COMPLETED REQUEST
					// if "OK"
					if (mcmsAjax.xmlhttp.status==200)
					{
						if(mcmsAjax.objPreloader && preloader_html.indexOf(live[4]) == -1) mcmsAjax.objPreloader.innerHTML += live[4] + "<br/>";
					
						// hide preloader
						if(mcmsAjax.objPreloader) 
						{
							// show preloader/status box a few seconds if we print any messages in it instead of alerts
							if(mcmsAjax.feedback_type == 'preloader')
							{
								setTimeout('mcmsAjax.objPreloader.style.display = "none";', 4000);
							}
							else
							{
								mcmsAjax.objPreloader.style.display = "none";
							}
						}
					
						// grab response text
						var response_text = mcmsAjax.xmlhttp.responseText.toString();
						
						// check if we got a javascript code in response text that should be obeyed
						if(response_text.indexOf('<script') != -1)
						{
							// javascript found, use it
							eval(mcmsAjax.strip_tags(response_text));
						}
						else
						{
							// give back the response depending on what feedback type was chosen
							if(mcmsAjax.feedback_type == 'alert') alert(html_entity_decode(response_text));
							else if(mcmsAjax.feedback_type == 'preloader') { if(mcmsAjax.objPreloader) mcmsAjax.objPreloader.innerHTML += "<br/><b>Meddelande</b><br/>"+html_entity_decode(response_text)+"<br/>"; }
							else if(mcmsAjax.feedback_type == '') alert('No feedback type chosen.');
							else 
							{
								// user has send a custom <div> id into which the response text will be written)
									// make sure custom id exists
									if(document.getElementById(mcmsAjax.feedback_type))
									{
										// put response text into its innerhtml
										document.getElementById(mcmsAjax.feedback_type).innerHTML = html_entity_decode(URLDecode(response_text));
									}
							}
						}
					}
					else
					{
						alert("Problem retrieving XML data ("+mcmsAjax.xmlhttp.status+"): " + mcmsAjax.xmlhttp.statusText);
					}
			}
		}

		
		/* removes all html tags from given string
		 * @param 
		 * @return void
		*/
		this.strip_tags = function(htmlString)
		{
	 		var strInputCode = htmlString;
	 		/* 
	  			This line is optional, it replaces escaped brackets with real ones, 
	  			i.e. < is replaced with < and > is replaced with >
	 		*/	
	 	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
	 		 	return (p1 == "lt")? "<" : ">";
	 		});
	 		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
	 		return strTagStrippedText;
		}

		/* sends a get qury
		 * @param 
		 * @return void
		*/
		this.ahref = function(obj)
		{
			// grab href
			var href = obj.href;
			
			// break up AHREF into <url>?<querystring>
			var arr = href.split('?');
			var href = arr[0] ? arr[0] : '';
			var querystring = arr[1] ? arr[1] : '';
			
			href = href.toString();
			querystring = querystring.toString();
			
			// send data in form to defined url with defined sending mechanism (get/post)
			mcmsAjax.loadUrl(href, 'get', querystring, 'alert');	
		}
		
		
		/* function to send data using regular <form> (sends as POST or GET) 
		 * EXAMPLE: <form action="receivers/login.php" method="post" onsubmit="sendData(this); return false;">
		 * @param 
		 * @return void
		*/
		this.sendData = function(obj, response_type)
		{
			// initialize the preloader
			if(response_type == 'preloader') this.initPreloader();
			
			// grab form attributes (action, target etc)
			var form_action = (obj.action != "" && obj.action != "undefined" && obj.action != undefined) ? obj.action : '';
			var form_method = (obj.method != "" && obj.method != "undefined" && obj.method != undefined) ? obj.method : 'get';
			
			// declare querystring holder
			var querystring = "";
			
			// grab all post data
				// grab all form elements/fields
				var form_fields = obj.elements;
				 
				// iterate all form fields
				for(i = 0; i < form_fields.length; i++)
				{
					// build querystring
					if(form_fields[i].type == 'text') querystring += form_fields[i].name+"="+URLEncode(form_fields[i].value)+"&";
					if(form_fields[i].type == 'hidden') querystring += form_fields[i].name+"="+URLEncode(form_fields[i].value)+"&";
					if(form_fields[i].type == 'password') querystring += form_fields[i].name+"="+URLEncode(form_fields[i].value)+"&";
					if(form_fields[i].type == 'textarea') querystring += form_fields[i].name+"="+URLEncode(form_fields[i].value)+"&";
					if(form_fields[i].type == 'radio')
					{
						var radio_len = eval("obj."+form_fields[i].name+".length");
						
						for (var z = 0; z < radio_len; z++)
						{
							if(form_fields[i].checked)
							{
								querystring += form_fields[i].name+"="+URLEncode(form_fields[i].value)+"&";
								z = radio_len;
							}
						}
					}
					if(form_fields[i].type == 'select-one')
					{
						querystring += form_fields[i].name+"="+URLEncode(form_fields[i].options[form_fields[i].selectedIndex].value)+"&";
					}
					if(form_fields[i].type == 'checkbox')
					{
						querystring += form_fields[i].name+"="+(form_fields[i].checked ? URLEncode(form_fields[i].value) : '')+"&";
					}
				}
			
			// send data in form to defined url with defined sending mechanism (get/post)
			mcmsAjax.loadUrl(form_action, form_method, querystring, response_type);	
		}
							
							
		/* escape special chars
		 * @param 
		 * @return void
		*/
		this.escapeSpecialChars = function(str)
		{
			str = str.replace(/ç/g,escape("ç"));
			str = str.replace(/Ç/g,escape("Ç"));
			str = str.replace(/ð/g,escape("ð"));
			str = str.replace(/Ð/g,escape("Ð"));
			str = str.replace(/ý/g,escape("ý"));
			str = str.replace(/Ý/g,escape("Ý"));
			str = str.replace(/ö/g,escape("ö"));
			str = str.replace(/Ö/g,escape("Ö"));
			str = str.replace(/þ/g,escape("þ"));
			str = str.replace(/Þ/g,escape("Þ"));
			str = str.replace(/ü/g,escape("ü"));
			str = str.replace(/Ü/g,escape("Ü"));
			return str;
		}
		
		/* decode special chars
		 * @param 
		 * @return void
		*/
		this.getSpecialChars = function(str)
		{
			str = str.replace(/%E7/g,"ç");
			str = str.replace(/%C7/g,"Ç");
			str = str.replace(/%F0/g,"ð");
			str = str.replace(/%D0/g,"Ð");
			str = str.replace(/%FD/g,"ý");
			str = str.replace(/%DD/g,"Ý");
			str = str.replace(/%F6/g,"ö");
			str = str.replace(/%D6/g,"Ö");
			str = str.replace(/%FE/g,"þ");
			str = str.replace(/%DE/g,"Þ");
			str = str.replace(/%FC/g,"ü");
			str = str.replace(/%DC/g,"Ü");
			return unescape(str);
		}
		
		/* make preloader follow mouse move
		 * @param 
		 * @return void
		*/
		this.preloaderFollowMouse = function(ev)
		{
			if(mcmsAjax.objPreloader)
			{
				ev = ev || window.event;
				var x = ev.clientX;
				var y = ev.clientY;
				var pl = mcmsAjax.objPreloader;
				if(y <= 590 && x <= 900)
				{
					pl.style.left = (x + 10);
					pl.style.top = (y + 10);
				}
			}
		}
		
		/* create preloader container
		 * @param 
		 * @return void
		*/
		this.createPreloader = function()
		{
			// generate unique id
			var unique_id = 'preloaderContainer';
			
			// create new div
			var divElement = document.createElement("div");
			divElement.setAttribute('id', unique_id);
			
			// append div to body
			var divParent = document.getElementsByTagName("body");
			divParent = divParent[0];
			divParent.appendChild(divElement);
			this.divParent = divParent;
			
			// set content of this div
			document.getElementById(unique_id).innerHTML = "";
			
			// set style attribute on this new div
			document.getElementById(unique_id).style.position = "absolute";
			document.getElementById(unique_id).style.overflow = "auto";
			document.getElementById(unique_id).style.width = "200px";
			document.getElementById(unique_id).style.height = "100px";
			document.getElementById(unique_id).style.margin = "0px";
			document.getElementById(unique_id).style.background = "white";
			document.getElementById(unique_id).style.border = "1px solid black";
			document.getElementById(unique_id).style.left = "100px";
			document.getElementById(unique_id).style.top = "100px";
			document.getElementById(unique_id).style.padding = "5px";
			document.getElementById(unique_id).style.zIndex = 1;
			
			// put preloader object into property
			mcmsAjax.objPreloader = document.getElementById(unique_id);
		}
}
var mcmsAjax = new mcms_ajax();