/**
 * @author Jeroen
 */

// create a namespace for NETQ objects
var NETQ={
	version:"0.1",
	session:null,
	debug:true,
	// additional methods to be appended to elements when they are instantiated by prototype.js
	methods:{
		/**
		 * Lets the element take on behaviour inherited from some class (=function).
		 * 
		 * @param {Object} element
		 * @param {Object} c	the constructor function to be invoked
		 * @param {Object} p	an extra parameter to be passed into the constructor function
		 */
		inherit:function (element,c,p) {
			var sKey="";
			for (sKey in c.prototype) {
				element[sKey]=c[sKey];
			}
			c.call(element,p);
			return element;
		},
		/**
		 * Returns the style object of the element with all applied styles (in stylesheets or inline style attributes)
		 * 
		 * @param {Object} element
		 */
		getComputedStyle:function (element) {
			if (Prototype.Browser.IE) {
				return element.currentStyle;
			} else {
				return window.getComputedStyle(element,"");
			}
		},
		getWidth:function (element) {
			// this overrides the methode defined by prototype.js
			return parseInt(element.getComputedStyle().width,10);
		},
		getHeight:function (element) {
			// this overrides the methode defined by prototype.js
			return parseInt(element.getComputedStyle().height,10);
		},
		getLeft:function (element) {
			return parseInt(element.getComputedStyle().left,10);
		},
		getRight:function (element) {
			return parseInt(element.getComputedStyle().right,10);
		},
		getTop:function (element) {
			return parseInt(element.getComputedStyle().top,10);
		},
		getBottom:function (element) {
			return parseInt(element.getComputedStyle().bottom,10);
		},
		/**
		 * Simulates a mouseclick on the element. IE supports the click() method on any element by default, FF only on form elements.
		 * Therefore dispatch the event for FF properly.
		 * 
		 * @param {Object} element
		 */
		mouseClick:function (element) {
			if (Prototype.Browser.IE) {
				element.click();
			} else {
				var e = document.createEvent("MouseEvents");
				e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				element.dispatchEvent(e);
			}
		},
		getTextContent:function (element) {
			if (Prototype.Browser.IE) {
				return element.innerText;
			} else {
				return element.textContent;
			}
		},
		/**
		 * Returns the first ancestor element that is of the container class.
		 * 
		 * @param {Object} element
		 */
		getContainer:function (element) {
			var a_ancestors=element.ancestors();
			var o_ancestor=null;
			var o_container=null;
			for (var i=0;o_ancestor=a_ancestors[i];i++) {
				if (o_ancestor.hasClassName("container")) {
					o_container=o_ancestor;
				}
			}
			return o_container;
		}
	},
	cancelSelect:function (e) {
		if (!["input","textarea"].include(Event.element(e).nodeName.toLowerCase())) {
			Event.stop(e);
		}
	},
	/**
	 * A wrapper around prototype.js ajax requests, in order to handle sessions.
	 * 
	 * @param	{String}	u	the requested url
	 * @param	{String}	o	the options object (see prototype.js documentation)
	 */
	request:function (u,o) {
		// override the successhandler but keep a reference to the original handler because we need to call it eventually
		var handleResponse=(function (m) {
			return function (transport) {
				// check if the session is still valid
				//debugger;
				var o_json={};
				if (transport.responseJSON) {
					o_json=transport.responseJSON; // this is the json evaluated from the responseText, i.e. Request.response.type="JSON"
				} else if (transport.headerJSON) {
					o_json=transport.headerJSON; // this is json evaluated from the X-JSON header, i.e. Request.response.type="BOTH"
				}

				if (NETQ.session && o_json.session) {
					// there is session information in the json object
					NETQ.session.update(o_json.session);
				}
				// only check for invalid sessions if there is an event parameter and that event is not a session event
				// if the session is not active, the session is not valid
				// if there is json, don't redirect if there is an error
				if (/[\?&]event=/.test(u) && u.indexOf("session")===-1 && 
					NETQ.session && !NETQ.session.isActive() && !o_json.error) {
					// invalidate the current session
					NETQ.session.invalidate();
					// redirect to the homepage
					document.location.href="index.html";
				} else {
					// if there is no error or we are in debug mode, proceed as planned
					if (!o_json.error || NETQ.debug) {
						// call the original success handler, and add a second parameter with the json object if present
						if (m) {
							m(transport,o_json);
						}
					} else {
						// there was an error, notify the user
						alert("An error has occurred on the server. The administrator has been notified and will solve this issue as soon as possible.");
					}
				}
			}
		})(o.onSuccess);
		
		o.onSuccess=handleResponse;
		o.onFailure=o.onFailure || function () {
										if (NETQ.debug) {
											alert("Request error: "+transport.status);
										}
									}
		// append session information
		if (NETQ.session) {
			o.parameters=(o.parameters ? o.parameters + "&" : "") + NETQ.session.serialize();
		}
		new Ajax.Request(u,o);
	}
}

window.onload=function () {
	Element.addMethods(NETQ.methods); // tell prototype.js to append these methods when instantiating
	Element.observe(document,"selectstart",NETQ.cancelSelect);
	if (NETQ.onload) {
		NETQ.onload();
	}
}

/**
 * Redirects to the given url after submitting the given form and receiving the response of that.
 * 
 * @param {Object} url
 * @param {Object} form		the id of the form, or the form object itself
 */
function redirectto(url,form) {
	// create a responder
	// this is an object that listens to any ajax calls done by prototype
	// so with this one, you can catch ending ajax requests and do something else with it
	// in this case: check if the submitted form returned errors; if not the redirect to the url provided
	var responder={
		onComplete: function () {
			// I don't know what the first argument is, but the second one appears to be the xhr object
			// get the json and check if there is a validation error
			var json=arguments[1].headerJSON;
			if (!json || !json.error) {
				// no error, so proceed to the url that should be loaded
				$("content").load(url);
			} else {
				// enable all buttons again
				$("content").select("button").each(function (o) {o.disabled=false;});
			}
			Ajax.Responders.unregister(this);
			//debugger;
		}
	}
	Ajax.Responders.register(responder);
	post($(form));
}

/**
 * Post the given form using the surrounding container.
 * 
 * @param {Object} form		the form object that must be submitted
 */
function post(form) {
	// take the form, extend it, get its containing container object, and tell that container to submit the form
	$(form).getContainer().post(form);
}

function savemessagereminder(form){
	// save message
	post($(form));
	// send reminders
	$('sendreminders').mouseClick();
}

function getTemplateWidth(question){
	var templateWidth;
	var obj;
	if (navigator.appName == "Microsoft Internet Explorer") {
		obj = {str:nl2br(question)};
		templateWidth = window.showModalDialog("getTemplateWidthPopup.html", obj, "dialogHeight: 140px; dialogWidth: 350px;")
	}else{
		templateWidth = prompt(question);
	}
	var length=document.getElementsByName('templatewidth').length;
	for(var i=0; i<length; i++){
		document.getElementsByName('templatewidth')[i].value = templateWidth;
	}
}

function nl2br(text){
	text = escape(text);
	if(text.indexOf('%0D%0A') > -1){
		re_nlchar = /%0D%0A/g ;
	}else if(text.indexOf('%0A') > -1){
		re_nlchar = /%0A/g ;
	}else if(text.indexOf('%0D') > -1){
		re_nlchar = /%0D/g ;
	}
	return unescape( text.replace(re_nlchar,'<br />') );
}
