Ajax.abortError		= false;
Ajax.errorCallback	= function(){};
Ajax.responseObject = {};

Ajax.analyzeResponse = function(response, onError)
{
	if ( typeof onError != 'undefined' )
		Ajax.errorCallback	= onError;

	setTimeout("Ajax.throwError('Incorrect response')", 300);
	Ajax.abortError = true;
	Ajax.responseObject = ({code:200, body:response});
	return true;
}

Ajax.throwError = function(message)
{
	if ( !Ajax.abortError ) {
		alert(message);
		Ajax.errorCallback();
	}

	Ajax.abortError = false;
}

Phi = {};

Phi.dictionary	= [];
Phi.language	= 'en';

Phi.lang = function(word)
{
	return Phi.dictionary[word] ? Phi.dictionary[word] : word;
}

Phi.page = 0;
Phi.url = 'http://'+location.hostname;

Phi.removeModule = function(module) {
	module = ($(module) || $('phimodule_'+module));
	Effect.Fade(module, {
		duration: 0.5,
		afterfinish: function() {
			module.parentNode.removeChild(module);
		}
	});
}

Phi.copyModule = function(module, target) {
	new Ajax.Request(target);
}

Phi.cutModule = function(module, target) {
	new Ajax.Request(target, {
		onComplete: function(req) {
			Phi.removeModule(module);
		}
	});
}

Phi.prepareModule = function(module)
{
	var divs = $A(module.getElementsByTagName('DIV'));
	divs.map(function(div){
		if(div.className == 'phi_options') {
			module.options					= div;
			Element.hide(module.options);

			module.options.onclick = function(e) {
				module.hideOptions(e);
			}

		} else if(div.className == 'phi_tooltip') {
			module.tooltip = div;
			module.invoker = module.tooltip.getElementsByTagName('H1')[0];

			module.tooltip.onmouseover = function(e) {
				Element.addClassName(this,'toolhover');
			}
			module.tooltip.onmouseout = function(e) {
				Element.removeClassName(this,'toolhover');
			}

			module.invoker.onclick = function(e) {
				if (!e)e=event;
				module.toggleOptions(e);
			}
		}
	});

	if ( module.options ) {
		$A(module.options.getElementsByTagName('LI')).map(function(item){
			if ( item.getElementsByTagName('UL').length > 0 ) {
				item.onmouseover = function() {
					item.getElementsByTagName('UL')[0].style.display = 'block';
				}

				item.onmouseout = function() {
					item.getElementsByTagName('UL')[0].style.display = 'none';
				}
			}
		});
	}

	module.showTT = function(e)
	{
		return;

		if (!this.tooltip || !this.validateOver(e)) return;
		//module.tooltip.style.width	= module.offsetWidth-4+"px";
		//Effect.Appear(this.tooltip, {duration:0.2});
		this.tooltip.style.width = this.offsetWidth+'px';
		Element.show(this.tooltip);
	}

	module.hideTT = function(e)
	{
		return;

		if (!this.tooltip || !this.validateOut(e)) return;
		//Effect.Fade(this.tooltip, {duration:0.1});
		Element.hide(this.tooltip);
	}

	module.showOptions = function(e)
	{
		if (!this.options) return;
		//this.options.style.top = Event.pointerY(e)+'px';
		//this.options.style.left = Event.pointerX(e)+'px';
		//Element.show(this.options);

		/*set zindex all the way up*/
		var tmp = this.options;
		while (tmp.nodeName != 'BODY'){
			tmp.style.zIndex = 15;
			tmp = tmp.parentNode;
		}

		//Effect.SlideDown(this.options, {duration: 0.2});
		Element.show(this.options);
	}

	module.hideOptions = function()
	{
		if (!this.options) return;
		//Element.hide(this.options);

		/*set zindex all the way up*/
		var tmp = this.options;
		while (tmp.nodeName != 'BODY'){
			tmp.style.zIndex = 1;
			tmp = tmp.parentNode;
		}


		//Effect.SlideUp(this.options, {duration: 0.1});
		Element.hide(this.options);
	}

	module.toggleOptions = function(e)
	{
		if (!this.options) return;
		if (Element.visible(this.options))
			this.hideOptions(e);
		else
			this.showOptions(e);
	}


	module.validateOver = function(e)
	{
		return 1;
		var tg		= (window.event) ? e.srcElement : e.target;
		var reltg	= (e.relatedTarget) ? e.relatedTarget : e.fromElement;
		
		var chkr = reltg;
		while (chkr.id != this.id && chkr.nodeName != 'HTML') {
			chkr = chkr.parentNode;
		}
		if ( chkr.id == this.id )
			return false;

		while (reltg != tg && reltg.nodeName != 'HTML') {
			reltg = reltg.parentNode;
		}
		if (reltg == tg)
			return false;
		return true;
	}

	module.validateOut = function(e)
	{
		return 1;
		var tg		= (window.event) ? e.srcElement : e.target;
		var reltg	= (e.relatedTarget) ? e.relatedTarget : e.toElement;

		var chkr = reltg;
		while (chkr.id != this.id && chkr.nodeName != 'HTML')
			chkr = chkr.parentNode;
		if ( chkr.id == this.id )
			return false;

		while (reltg != tg && reltg.nodeName != 'HTML') {
			reltg = reltg.parentNode;
		}
		if (reltg == tg)
			return false;
		return true;
	}

	/* Register Mouse events */
	module.onmouseover = function(e) {
		if (!this.tooltip) return;
		if (!e)e=event;
		//this.addClassName('hover');
		this.showTT(e);
		//this.style.zIndex = 9999;
	}

	module.onmouseout = function(e) {
		if (!this.tooltip) return;
		if (!e)e=event;
		//this.removeClassName('hover');
		this.hideTT(e);
		//this.style.zIndex = 1;
	}


	/* Locate the content area */
	module.content = document.getElementsByClassName('phi_content',module)[0];

	module.instance_id = module.id.match(/[0-9]+/);

	module.loadContent = function(url) {
		module.setActivity(Phi.lang('loading'));
		new Ajax.Request(url,{
			method: 'get',
			onComplete: function(req) {
				/* Think of this as a catch-try block (yes.. in that order) */
				if ( Ajax.analyzeResponse(req.responseText, function() {
					module.setContent(req.responseText);
				})){
					module.setContent(Ajax.responseObject.body);
				}
			}
		});			
	}

	module.setContent = function(content) {
		Effect.Fade(module.content, {
			duration: 0.5,
			afterFinish: function() {
				module.content.innerHTML = content;

				/* Look for forms */
				frms = module.getElementsByTagName('FORM');
				$A(frms).map(function(form){

					var _onsubmit	= form.onsubmit;
					form._onsubmit	= _onsubmit;

					form.onsubmit = function() {
						if ( !this._onsubmit || this._onsubmit() )
						{
							module.setActivity(Phi.lang('sending'));
							
							new Ajax.Request(this.action,{
								parameters: Form.serialize(this),
								onComplete: function(req) {
									module.refresh();
									/* Refresh children */
									if (req.responseText) {
										req.responseText.split(',').map(function(id){
											if ($('phimodule_'+id)) {
												$('phimodule_'+id).refresh();
											}
										});
									}
								}
							});
						}
						return false;
					}
				});

				/* Look for cancel buttons */
				btns = module.getElementsByTagName('INPUT');
				$A(btns).map(function(button){
					if ( button.type == 'button' && button.value.toLowerCase() == Phi.lang('cancel').toLowerCase() ) {
						button.onclick = function() {
							module.refresh();
							return false;
						}
					}
				});

				/*global_tmp = module.content;
				setTimeout('Effect.Appear(global_tmp,{duration:0.7})', 100);*/
				Effect.Appear(module.content,{duration:0.5});
			}
		});
	}

	module.setActivity = function(msg) {
		//Element.hide(module.content);
		Effect.Fade(module.content,{duration:0.5, afterFinish: function() {
			module.content.innerHTML = '<div class="phi_module_loader"><h1>'+msg+'</h1></div>';
			Effect.Appear(module.content,{duration:0.5});
		}});
		//module.content.innerHTML = '<div class="phi_module_loader"><h1>'+msg+'</h1></div>';
		//Effect.Appear(module.content,{duration:0.5});
	}

	module.refresh = function() {
		var module_string = Phi.url_rw ? Phi.url+'instance/run/inst=' : Phi.linkbase+'instance/run&inst='; 
		new Ajax.Request(module_string+this.instance_id+'&page='+Phi.page, {
			onComplete: function(req) {
				dummy = document.createElement('DIV');
				dummy.innerHTML = req.responseText;

				module.setContent(document.getElementsByClassName('phi_content',dummy)[0].innerHTML);
				
				/* set new classname */
				module.className = dummy.firstChild.className;

				if (!document.getElementsByClassName('phi_title',dummy)[0]) {
					module.removeChild(document.getElementsByClassName('phi_title',module)[0]);
				} else if (!document.getElementsByClassName('phi_title',module)[0]) {
					var title = document.createElement('H1');
					title.className = 'phi_title';
					title.innerHTML = document.getElementsByClassName('phi_title',dummy)[0].innerHTML;
					module.insertBefore(title, document.getElementsByClassName('phi_content',dummy)[0]);
				} else {
					document.getElementsByClassName('phi_title',module)[0].innerHTML = document.getElementsByClassName('phi_title',dummy)[0].innerHTML;
				}
			}
		});
	}

	if (module.options) {
		var links = module.options.getElementsByTagName('A');
		$A(links).map(function(link){
			if ( Element.hasClassName(link,'phi_modifier') ) {

				/* find the module containing this link */
				link.module = module;

				if ( Element.hasClassName(link,'phi_modifier_instance_kill') ) {
					link.onclick = function() {
						
						if ( !confirm(Phi.lang('remove this module')+' ?') )
							return false;
						
						new Ajax.Request(this.href, {
							onComplete: function(req) {
								Phi.removeModule(link.module);
								req.responseText.split(',').map(Phi.removeModule);
							}
						});
						return false;
					}
				} else if ( Element.hasClassName(link,'phi_modifier_instance_audit') ) {
					//.. nothing
				} else if ( Element.hasClassName(link,'phi_modifier_instance_cut') ) {
					link.onclick = function() {
						Phi.cutModule(link.module, this.href);
						return false;
					}
				} else if ( Element.hasClassName(link,'phi_modifier_instance_copy') ) {
					link.onclick = function() {
						Phi.copyModule(link.module, this.href);
						return false;
					}
				} else {
					link.onclick = function() {
						this.module.loadContent(this.href);
						return false;
					}				
				}

			}
		});
	}

}



/* Attach loading event */
if ( typeof window.attachEvent != "undefined" )
	window.attachEvent( "onload", phiInitializeNavigator );

if ( typeof window.addEventListener != "undefined" )
	window.addEventListener( "load", phiInitializeNavigator, false );


function phiInitializeNavigator()
{
	document.getElementsByClassName('phi_module').map(Phi.prepareModule);
}
