var ModalPopup = {
	adjustWaitTime: 0,
	contentOpacity: 0,
	contentTargetOpacity: 0,
	editorName: null,
	initialized: false,
	reloadOnHide: false,
	loadOnHide: false,
	loadOnHideUrl: null,
	opacity: 0,
	params: null,
	speedWidth: 0,
	speedHeight: 0,
	targetOpacity: 0,
	url: '',
	visible: false,
	adjustBackground: function() {
		this.background.style.left = '0px';
		this.background.style.top = '0px';
		this.background.style.width = Math.max(getPageWidth(), getWindowWidth()) + 'px';
		this.background.style.height = Math.max(getPageHeight(), getWindowHeight()) + 'px';
	},
	adjustPopup: function(width, height) {
		this.adjustWaitTime = 0;
		this.speedWidth = 0;
		this.speedHeight = 0;
		if ((typeof(width) == 'number') && (typeof(height) == 'number')) {
			this.popup.targetWidth = Math.floor(width + 20);
			this.popup.targetHeight = Math.floor(height + 20);
		}
		if (typeof(this.timerAdjustPopup) == 'undefined') {
			this.timerAdjustPopup = setInterval(this.onAdjustPopup, 20);
		}
	},
	clearContent: function() {
		if (!this.initialized) { this.init(); }
		
		this.popupContent.innerHTML = '';
	},
	debug: function(text, clearfirst) {
		if (clearfirst) {
			this.background.innerHTML = text+'<br />';
		} else {
			this.background.innerHTML += text+'<br />';
		}
	},
	fadeIn: function() {
		if (!this.initialized) { this.init(); }

		this.targetOpacity = 50;
		if (typeof(this.timerFade) == 'undefined') {
			this.timerFade = setInterval(this.onFade, 20);
		}
	},
	fadeContentIn: function() {
		if (!this.initialized) { this.init(); }

		if (typeof(this.timerContentFade) == 'undefined') {
			this.contentOpacity = 0; 
			this.contentTargetOpacity = 100;
			this.timerContentFade = setInterval(this.onContentFade, 20);
		}
	},
	fadeContentOut: function() {
		if (!this.initialized) { this.init(); }
		
		if (typeof(this.timerContentFade) == 'undefined') {
			this.contentOpacity = 100; 
			this.contentTargetOpacity = 0;
			this.timerContentFade = setInterval(this.onContentFade, 20);
		}
	},
	fadeOut: function() {
		if (!this.initialized) { this.init(); }

		this.targetOpacity = 0;
		if (typeof(this.timerFade) == 'undefined') {
			this.timerFade = setInterval(this.onFade, 20);
		}
	},
	hide: function() {
		if (!this.initialized) { this.init(); }
		
		if (this.visible) {
		  document.body.removeChild(this.popup);
			this.fadeOut();
			this.visible = false;
		}
	},
	hideAndLoad: function(url) {
		if (!this.initialized) { this.init(); }
		
		if (this.visible) {
		  document.body.removeChild(this.popup);
			this.loadOnHide = true;
			this.loadOnHideUrl = url;
			this.fadeOut();
			this.visible = false;
		}
	},
	hideAndReload: function() {
		if (!this.initialized) { this.init(); }
		
		if (this.visible) {
		  document.body.removeChild(this.popup);
			this.reloadOnHide = true;
			this.fadeOut();
			this.visible = false;
		}
	},
	init: function() {
		if (!this.initialized) {
			try { // Firefox, Opera 8.0+, Safari
				this.ajaxRequest = new XMLHttpRequest();
			} catch (e) {
		    try { // Internet Explorer (MSXML v2)
		      this.ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		    }
		    catch (e) {
		      try { // Internet Explorer (MSXML v1)
		        this.ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
		      } catch (e) {
			    document.location = 'notsupported.php';
		      }
		    }
		  }
			
			this.background = document.createElement('div');
			this.background.setAttribute('id', 'ModalPopupBackground');
			this.background.style.backgroundColor = '#000000';
			this.background.style.color = '#FFFFFF';
			this.background.style.position = 'absolute';
			this.background.style.opacity = '0.0';
			this.background.style.filter = 'alpha(opacity = 0)';
			this.background.style.zIndex = '2000';
			Debug.init(this.background);
			
			this.popup = document.createElement('div');
			this.popup.setAttribute('id', 'ModalPopup');
			this.popup.style.position = 'absolute';
			this.popup.actualLeft = ((getWindowWidth() / 2) - (140 / 2) + getScrollX());
			this.popup.actualTop = ((getWindowHeight() / 2) - (70  / 2) + getScrollY());
			this.popup.style.left = this.popup.actualLeft + 'px';
			this.popup.style.top = this.popup.actualTop + 'px';
			this.popup.targetWidth = 140;
			this.popup.targetHeight = 70;
			this.popup.actualWidth = this.popup.targetWidth;
			this.popup.actualHeight = this.popup.targetHeight;
			this.popup.style.width = this.popup.targetWidth + 'px';
			this.popup.style.height = this.popup.targetHeight + 'px';
			this.popup.style.zIndex = '2001';
			this.popup.innerHTML = '<table class="modalPopup"><tr><td class="content" /><div id="ModalPopupContentBackground"><div id="ModalPopupContent"></div></div></td></tr></table>';
			this.popupContentBackground = this.popup.getElementsByTagName('div')[0];
			this.popupContentBackground.style.width = (this.popup.targetWidth-20) + 'px';
			this.popupContentBackground.style.height = (this.popup.targetHeight-20) + 'px';
			this.popupContent = this.popupContentBackground.firstChild;
			this.popupContent.style.width = (this.popup.targetWidth-20) + 'px';
			this.popupContent.style.height = (this.popup.targetHeight-20) + 'px';
			this.popupContent.style.opacity = 0;
			this.popupContent.style.filter = 'alpha(opacity=0)';
			temp = this.popup.firstChild.insertRow(-1);
			this.popupButtons = temp.insertCell(-1);
			this.popupButtons.setAttribute('class','buttons');
			this.popupButtons.className = 'buttons';
			this.popupButtonCancel = document.createElement('a');
			this.popupButtonCancel.setAttribute('class','buttonCancel');
			this.popupButtonCancel.className = 'buttonCancel';
			this.popupButtonCancel.setAttribute('href','javascript:ModalPopup.hide();');
			this.popupButtonCancel.innerHTML = 'Cancel';
			this.popupButtons.appendChild(this.popupButtonCancel);
			this.popupButtonSubmit = document.createElement('a');
			this.popupButtonSubmit.setAttribute('class','buttonSubmit');
			this.popupButtonSubmit.className = 'buttonSubmit';
			this.popupButtonSubmit.setAttribute('href','javascript:ModalPopup.submitForm();');
			this.popupButtonSubmit.innerHTML = 'Submit';
			this.popupButtons.appendChild(this.popupButtonSubmit);
			
			window.onscroll = ModalPopup.onScroll;
			window.onresize = ModalPopup.onResize;

			this.initialized = true;
		}
	},
	load: function() {
		this.adjustPopup();
		try {
			if (this.params	 != null) {
				this.ajaxRequest.open('POST', this.url, true);
				this.ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				this.ajaxRequest.setRequestHeader("Content-Length", this.params.length);
			} else {
				this.ajaxRequest.open('GET', this.url, true);
				this.ajaxRequest.setRequestHeader("Content-Length", 0);
			}
			this.ajaxRequest.setRequestHeader("User-Agent", "ModalPopup");
			this.ajaxRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			this.ajaxRequest.setRequestHeader("Connection", "close");
			this.ajaxRequest.onreadystatechange = this.onAjaxStatusChange;
			this.ajaxRequest.send(ModalPopup.params);
		} catch(e) {
			alert('An error occured loading content: '+e.message);
		}
	},
	onAdjustPopup: function() {
		if (this != ModalPopup) {
			var widthDone = true;
			var heightDone = true;
			var left = parseFloat(ModalPopup.popup.actualLeft);
			var top = parseFloat(ModalPopup.popup.actualTop);
			var width = parseFloat(ModalPopup.popup.actualWidth);
			var height = parseFloat(ModalPopup.popup.actualHeight);

			ModalPopup.popup.style.left = Math.floor((getWindowWidth() / 2) - (ModalPopup.popup.actualWidth / 2) + getScrollX()) + 'px';
			ModalPopup.popup.style.top = Math.floor((getWindowHeight() / 2) - (ModalPopup.popup.actualHeight  / 2) + getScrollY()) + 'px';

			if (Math.abs(width - ModalPopup.popup.targetWidth) > 0) {
				widthDone = false;
				ModalPopup.speedWidth = Math.floor(Math.abs(width - ModalPopup.popup.targetWidth) / 5);
				if (ModalPopup.speedWidth >= 1) {
					if ((width - ModalPopup.popup.targetWidth) > 0) {
						ModalPopup.popup.actualWidth = Math.floor(width - ModalPopup.speedWidth);
					} else {
						ModalPopup.popup.actualWidth = Math.floor(width + ModalPopup.speedWidth);
					}
				} else {
					ModalPopup.popup.actualWidth = Math.floor(ModalPopup.popup.targetWidth);
					widthDone = true;
				}
				ModalPopup.popup.style.width = ModalPopup.popup.actualWidth + 'px';
				ModalPopup.popupContentBackground.style.width = (ModalPopup.popup.actualWidth - 20) + 'px';
				ModalPopup.popupContent.style.width = (ModalPopup.popup.actualWidth - 20) + 'px';
			}
			if (Math.abs(height - ModalPopup.popup.targetHeight) > 0) {
				heightDone = false;
				if (ModalPopup.adjustWaitTime >= 0) {
					ModalPopup.speedHeight = Math.floor(Math.abs(height - ModalPopup.popup.targetHeight) / 5);
					if (ModalPopup.speedHeight >= 1) {
						if ((height - ModalPopup.popup.targetHeight) > 0) {
							ModalPopup.popup.actualHeight = Math.floor(height - ModalPopup.speedHeight);
						} else {
							ModalPopup.popup.actualHeight = Math.floor(height + ModalPopup.speedHeight);
						}
					} else {
						ModalPopup.popup.actualHeight = Math.floor(ModalPopup.popup.targetHeight);
						heightDone = true;
					}
					ModalPopup.popup.style.height = ModalPopup.popup.actualHeight + 'px';
					ModalPopup.popupContentBackground.style.height = (ModalPopup.popup.actualHeight - 20) + 'px';
					ModalPopup.popupContent.style.height = (ModalPopup.popup.actualHeight - 20) + 'px';
				} else {
					ModalPopup.adjustWaitTime++;
				}
			}

			if (widthDone && heightDone) {
				clearInterval(ModalPopup.timerAdjustPopup);
				delete ModalPopup.timerAdjustPopup;
				if (typeof(ModalPopup.tempContent) != 'undefined') {
					ModalPopup.popupContent.innerHTML = ModalPopup.tempContent.innerHTML;
					delete(ModalPopup.tempContent);
					ModalPopup.fadeContentIn();
				}
			}
		}
	},
	onAjaxStatusChange: function() {
		if (ModalPopup.ajaxRequest.readyState == 4) {
			if (ModalPopup.ajaxRequest.status == 200) {
				ModalPopup.popupButtonCancel.innerHTML = 'Cancel';
				ModalPopup.popupButtonSubmit.innerHTML = 'Submit';
				response = ModalPopup.ajaxRequest.responseXML;
				processContent = true;
				ModalPopup.editorName = null;
				try {
					if (response.firstChild.nodeName.toLowerCase() == 'modalpopup') {
						if (response.firstChild.getElementsByTagName('modalaction').length > 0) {
							actions = response.firstChild.getElementsByTagName('modalaction');
							for (i = 0; i < actions.length; i++) {
								switch (actions[i].getAttribute('name')) {
									case 'load':
										ModalPopup.hideAndLoad(actions[i].getAttribute('url'));
										processContent = false;
										break;
									case 'reload':
										ModalPopup.hideAndReload();
										processContent = false;
										break;
									case 'show':
										ModalPopup.show(actions[i].getAttribute('url'));
										processContent = false;
										break;
									case 'hide':
										ModalPopup.hide();
										processContent = false;
										break;
									case 'setcancel':
										ModalPopup.popupButtonCancel.innerHTML = actions[i].getAttribute('value');
										break;
									case 'setsubmit':
										ModalPopup.popupButtonSubmit.innerHTML = actions[i].getAttribute('value');
										break;
									case 'enableeditor':
										ModalPopup.editorName = actions[i].getAttribute('value');
										break;
								}
							}
						} 
						if (processContent) {
							if (response.firstChild.getElementsByTagName('modalcontent').length == 1) {
								ModalPopup.tempContent = document.createElement('div');
								try {
									serializer = new XMLSerializer();
									contentString = serializer.serializeToString(response.firstChild.getElementsByTagName('modalcontent')[0])
								} catch(e) {
									contentString = response.firstChild.getElementsByTagName('modalcontent')[0].xml;
								}
								contentString = contentString.replace(/(<textarea[^<]*)\/>/gi,'$1></textarea>');
								ModalPopup.tempContent.innerHTML = htmlspecialchars_decode(contentString.replace(/<modalcontent>/gi,'').replace(/<\/modalcontent>/gi,''));
								ModalPopup.tempContent.style.visibility = 'hidden';
								if (ModalPopup.tempContent.childNodes.length > 0) {
									document.body.appendChild(ModalPopup.tempContent);
									ModalPopup.adjustPopup(ModalPopup.tempContent.firstChild.clientWidth, ModalPopup.tempContent.firstChild.clientHeight);
									document.body.removeChild(ModalPopup.tempContent);

									var forms = ModalPopup.tempContent.getElementsByTagName('form');
									if (forms.length > 0) {
										actionNode = forms[0].getAttributeNode('action');
										if (actionNode != null) {
											ModalPopup.url = actionNode.value;
											actionNode.value = "Javascript:ModalPopup.submitForm();";
										}
										ModalPopup.popupButtonSubmit.style.visibility = "visible";
									} else {
										ModalPopup.popupButtonSubmit.style.visibility = "hidden";
									}
									
								} else { 
									delete ModalPopup.tempContent;
									alert('[MODALPOPUP ERROR] Invalid Content: modalcontent node is empty');
									ModalPopup.hide();
								}
							} else {
								alert('[MODALPOPUP ERROR] Invalid Content: modalcontent node not found');
								ModalPopup.hide();
							}
						}
					} else { 
						alert('[MODALPOPUP ERROR] Invalid Content: modalpopup node not found');
						ModalPopup.hide();
					}
				} catch(e) {
					alert('[MODALPOPUP ERROR] An Error Occured: '+e.message);
					ModalPopup.hide();
				}
			} else if (ModalPopup.ajaxRequest.status == 302) {
				ModalPopup.ajaxRequest.open('GET', ModalPopup.ajaxRequest.getResponseHeader('location'), true);
				ModalPopup.ajaxRequest.send(null);
			} else if (ModalPopup.ajaxRequest.status == 404) {
					alert('[MODALPOPUP ERROR] An Error Occured: The requested content was not found ("'+ModalPopup.url+'")');
					ModalPopup.hide();
			} else {
				  delete ModalPopup.tempContent;
					alert('[MODALPOPUP ERROR] An Error Occured: Failed to load content with status code: '+ModalPopup.ajaxRequest.status);
					ModalPopup.hide();
			}
		}
	},
	onContentFade: function() {
		if (this != ModalPopup) {
			var done = true;
			if (ModalPopup.contentOpacity < ModalPopup.contentTargetOpacity) {
				ModalPopup.contentOpacity += 15;
				if(ModalPopup.contentOpacity > 100) {
					ModalPopup.contentOpacity = 100;
				}
				ModalPopup.popupContent.style.opacity = ModalPopup.contentOpacity / 100;
				ModalPopup.popupContent.style.filter = 'alpha(opacity = '+ModalPopup.contentOpacity+')';
				done = false;
			}
			if (ModalPopup.contentOpacity > ModalPopup.contentTargetOpacity) {
				ModalPopup.contentOpacity -= 15;
				if(ModalPopup.contentOpacity < 0) {
					ModalPopup.contentOpacity = 0;
				}
				ModalPopup.popupContent.style.opacity = ModalPopup.contentOpacity / 100;
				ModalPopup.popupContent.style.filter = 'alpha(opacity = '+ModalPopup.contentOpacity+')';
				done = false;
			}
			
			if (done) {
				clearInterval(ModalPopup.timerContentFade);
				delete ModalPopup.timerContentFade;
				if (ModalPopup.contentOpacity == 0) {
					ModalPopup.clearContent();
					ModalPopup.load();
				} else {
					try {
						ModalPopup.popupContent.style.removeAttribute('filter');
					} catch(e) {
					}
					if (ModalPopup.editorName != null) {
						Editor.init(document.getElementById(ModalPopup.editorName));
					}
					if (ModalPopup.popupContent.getElementsByTagName('input').length > 0) {
						try {
							ModalPopup.popupContent.getElementsByTagName('input')[0].focus();
						} catch(e) {
						}
					}
				}
			}
		}
	},
	onFade: function() {
		if (this != ModalPopup) {
			var done = true;

			if (ModalPopup.opacity < ModalPopup.targetOpacity) {
//				ModalPopup.opacity += 5;
				ModalPopup.opacity = ModalPopup.targetOpacity; //Temp speed up of fadein
				ModalPopup.background.style.opacity = ModalPopup.opacity / 100;
				ModalPopup.background.style.filter = 'alpha(opacity = '+ModalPopup.opacity+')';
				done = false;
			}
			if (ModalPopup.opacity > ModalPopup.targetOpacity) {
				ModalPopup.opacity -= 5;
				if (!ModalPopup.loadOnHide && !ModalPopup.reloadOnHide) {
					ModalPopup.background.style.opacity = ModalPopup.opacity / 100;
					ModalPopup.background.style.filter = 'alpha(opacity = '+ModalPopup.opacity+')';
				}
				done = false;
			}
			
			if (done) {
				clearInterval(ModalPopup.timerFade);
				delete ModalPopup.timerFade;
				if (ModalPopup.opacity == 0) {
					if (ModalPopup.reloadOnHide) {
						window.location.reload(false);
					} else if (ModalPopup.loadOnHide) {
						window.location.assign(ModalPopup.loadOnHideUrl);
					} else {
						document.body.removeChild(ModalPopup.background);
						ModalPopup.popupContent.style.opacity = 0;
						ModalPopup.popupContent.style.filter = 'alpha(opacity=0)';
					}
				} else {
					document.body.appendChild(ModalPopup.popup);
					ModalPopup.load();
				}
			}
		}
	},
	onScroll: function() {
		ModalPopup.adjustPopup();
	},
	onResize: function() {
		ModalPopup.adjustBackground();
		ModalPopup.adjustPopup();
	},
	resetModjulInfo: function() {
		var infoNode = document.getElementById('modjulInfo');
		if (typeof(infoNode) != 'undefined') {
			infoNode.innerHTML = 'Roll your mouse over a modjul icon to find out more info about that modjul';
		}
	},
	updateModjulInfo: function($parent) {
		var infoNode = document.getElementById('modjulInfo');
		if ((typeof(infoNode) != 'undefined') && (typeof($parent) != 'undefined')) {
			infoNode.innerHTML = '';
			var inputs = $parent.getElementsByTagName('input');
			for (i = 0; i < inputs.length; i++) {
				if (inputs[i].getAttribute('name') == 'modjulName') { infoNode.innerHTML = infoNode.innerHTML + '<h1>' + inputs[i].getAttribute('value') + '</h1>'; }
				if (inputs[i].getAttribute('name') == 'modjulDescription') { infoNode.innerHTML = infoNode.innerHTML + '<span style=\"color: #000000;\">' + inputs[i].getAttribute('value') + '</span>'; }
				if (inputs[i].getAttribute('name') == 'modjulTip') { infoNode.innerHTML = infoNode.innerHTML + '<br /><span style=\"color: #999999;\">' + inputs[i].getAttribute('value') + '</span>'; }
			}
		}
	},
	show: function(url) {
		if (!this.initialized) { this.init(); }

		this.url = String(url);
		this.params = null;
		
		if (this.popupButtonSubmit != null) {
			this.popupButtonSubmit.style.visibility = 'hidden';
		}
		
		if (!this.visible) {
			document.body.appendChild(this.background);
			this.popup.actualLeft = ((getWindowWidth() / 2) - (140 / 2) + getScrollX());
			this.popup.actualTop = ((getWindowHeight() / 2) - (70  / 2) + getScrollY());
			this.popup.style.left = this.popup.actualLeft + 'px';
			this.popup.style.top = this.popup.actualTop + 'px';
			this.popup.targetWidth = 140;
			this.popup.targetHeight = 70;
			this.popup.actualWidth = this.popup.targetWidth;
			this.popup.actualHeight = this.popup.targetHeight;
			this.popup.style.width = this.popup.targetWidth + 'px';
			this.popup.style.height = this.popup.targetHeight + 'px';
			this.popupContentBackground.style.width = (this.popup.targetWidth-20) + 'px';
			this.popupContentBackground.style.height = (this.popup.targetHeight-20) + 'px';
			this.popupContent.style.width = (this.popup.targetWidth-20) + 'px';
			this.popupContent.style.height = (this.popup.targetHeight-20) + 'px';
			this.adjustBackground();
			this.fadeIn();
			this.visible = true;
			this.clearContent();
			this.adjustPopup(120, 50);
		} else {
			this.fadeContentOut();
		}
	},
	submitForm: function() {
		var params = '';
		var formIndex = 0;
		var forms = this.popupContent.getElementsByTagName('form');
		if (formIndex < forms.length) {
			var inputs = forms[formIndex].getElementsByTagName('input');
			for (i=0; i < inputs.length; i++) {
				if ((inputs[i].getAttribute('name') != null) && (inputs[i].getAttribute('name') != '')) {
					if (inputs[i].getAttribute('type') == 'checkbox') {
						if (inputs[i].checked) {
							if (params != '') { params += '&'; }
							params += inputs[i].getAttribute('name') + '=' + encodeURIComponent(inputs[i].value);
						}
					} else {
						if (params != '') { params += '&'; }
						params += inputs[i].getAttribute('name') + '=' + encodeURIComponent(inputs[i].value);
					}
				}
			}
			var textareas = forms[formIndex].getElementsByTagName('textarea');
			for (i=0; i < textareas.length; i++) {
				if ((textareas[i].getAttribute('name') != null) && (textareas[i].getAttribute('name') != '')) {
					if (params != '') { params += '&'; }
					params += textareas[i].getAttribute('name') + '=' + encodeURIComponent(textareas[i].value);
				}
			}
			var selects = forms[formIndex].getElementsByTagName('select');
			for (i=0; i < selects.length; i++) {
				if ((selects[i].getAttribute('name') != null) && (selects[i].getAttribute('name') != '')) {
					if (params != '') { params += '&'; }
					params += selects[i].getAttribute('name') + '=' + encodeURIComponent(selects[i].value);
				}
			}
			this.params = params;
			this.fadeContentOut();
		}
	}
}