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);
	//var foo = eval('('+response+')');
	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.prepareModule = function(module)
{
	var divs = $A(module.getElementsByTagName('DIV'));
	divs.map(function(div){
		if ( div.className == 'phi_handle' ) {
			module.handle = div;
		} else if(div.className == 'phi_options') {
			module.options			= div.getElementsByTagName('UL')[0];
			module.options_trigger	= div.getElementsByTagName('H1')[0];
		}
	});

	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.onmouseover = function() {
		if ( this.handle ) {
			this.handle.style.display = 'block';
		}

		if ( this.options ) {
			Element.addClassName(this, 'hover');
		}
	}

	module.onmouseout = function() {
		if ( this.handle ) {
			this.handle.style.display = 'none';
		}

		if ( this.options ) {
			Element.removeClassName(this, 'hover');
		}

	}

	if ( module.options_trigger ) {
		module.options_trigger.onclick = function() {
			if ( typeof module.options != 'undefined' ) {
				module.options.style.display	= module.options.style.display == 'block' ? 'none' : 'block';
				
				/* Big zIndex bug */
				if (module.options.style.display == 'block')
				{
					document.getElementsByClassName('phi_module').map(function(other_module) {
						other_module.style.zIndex = 1;
					});
					module.style.zIndex = 50;
				} else {
					module.style.zIndex = 1;
				}
			}
		}
	}

	if ( module.options ) {
		module.options.onclick = function() {
			Element.hide(this);
		}
	}



		/* Locate the content area */
		module.content = Element.getElementsByClassName(module,'phi_content')[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){
						form.initialOnSubmit = form.onsumbit;
						form.onsubmit = function() {
							if ( !this.initialOnSubmit || (this.initialOnSubmit && this.initialOnSubmit()) )
							{
								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;
							}
						}
					});



					Effect.Appear(module.content,{duration:0.5});
				}
			});
		}

		module.setActivity = function(msg) {
			Element.hide(module.content);
			module.content.innerHTML = '<div class="phi_module_loader"><h1>'+msg+'</h1></div>';
			Effect.Appear(module.content,{duration:0.5});
		}

		module.refresh = function() {
			new Ajax.Request(Phi.url+'instance/run/inst='+this.instance_id+'&page='+Phi.page, {
				onComplete: function(req) {
					dummy = document.createElement('DIV');
					dummy.innerHTML = req.responseText;

					module.setContent(Element.getElementsByClassName(dummy, 'phi_content')[0].innerHTML);
					
					/* set new classname */
					module.className = dummy.firstChild.className;

					if (!Element.getElementsByClassName(dummy, 'phi_title')[0]) {
						module.removeChild(Element.getElementsByClassName(module, 'phi_title')[0]);
					} else if (!Element.getElementsByClassName(module, 'phi_title')[0]) {
						var title = document.createElement('H1');
						title.className = 'phi_title';
						title.innerHTML = Element.getElementsByClassName(dummy, 'phi_title')[0].innerHTML;
						module.insertBefore(title, Element.getElementsByClassName(module, 'phi_content')[0]);
					} else {
						Element.getElementsByClassName(module, 'phi_title')[0].innerHTML = Element.getElementsByClassName(dummy, 'phi_title')[0].innerHTML;
					}
				}
			});
		}




	var menus = Element.getElementsByClassName(module,'phi_options');
	$A(menus).map(function(menu){
		var links = menu.getElementsByTagName('A');
		$A(links).map(function(link){
			if ( Element.hasClassName(link,'phi_modifier') ) {

				/* find the module containing this link */
				var seeker = link.parentNode;
				while(!Element.hasClassName(seeker,'phi_module'))
					seeker = seeker.parentNode;
				link.module = seeker;

				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 {
					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(function(module) {
		Phi.prepareModule(module);
	});
}