function debug(what){
	/* if(window.console && window.console.firebug){
		console.log(what);
	}	
	else{
		alert(what);
	} */
}

///
var setup = false;
var initial_bookmark = null;
var wm = new WindowManager();
var urlfilter = /http:\/\/www.nauiokaspark.com/g;
// maybe make this flexible

$(document).ready(function(){

	// check if there is a bookmark in the url
	var url = window.location.href;
	if (url.indexOf('#') > -1) {
		bookmark = url.substring(url.indexOf('#')+2,url.length);
		initial_bookmark = bookmark;
		setTimeout('doBookmark()',400);
	}
	
	
	
	var nav = $('#nav li a').add('.nav-supp li a');
	hijackNav(nav);

	$('input#query').focus(function(){
		if($(this).val() == 'Keywords...') {
			$(this).val('');
		}
	});
	$('input#query').blur(function(){
		if($(this).val() == '') {
			$(this).val('Keywords...');
		}
	});
	
	var search = $('#search-form').submit(function(me){
		me.preventDefault();
		var windowname = 'search';
		var query = $(this).find('input#query').val();
		query = escape(query);
		wm.gotoWindow(windowname,query);
		
		return false;
	});


	// paginator bar with scallable width
	// count the amount of list items
	setUpSearchBar();
	setUpSubscriptionForm();
	
	var existingbox = $('.box');
	wm.setUpWindow(existingbox,existingbox.attr('id'),true);
	setup = true;
});

function doBookmark() {
	if (setup) {
		wm.gotoAddress(bookmark);
	} else {
		setTimeout('doBookmark()',400);
	}
}


function setUpSubscriptionForm() {
	debug($('form#subscribe-form'));
	$('form#subscribe-form').submit(function(me){
		me.preventDefault();
		debug('formsubmit');
		$('#nav').after('<div id="contacttemp" style="display:none;"></div>');
		url = $(this).attr('action');
		email= $(this).find('input#email').val();
		myobj = $(this);
		$('#contacttemp').load('/dynamic.php?url='+url,{email:email,subscribe:'subscribe'},function(){
			var error = $(this).find('span.error').html();
			if($(this).find('form#subscribe-form').length > 0) {
				myobj.parent().parent().find('div.join p').html('<span class="error">'+error+'</span>');
				debug('error');
				// we have an error
			} else {
			   // we don't....
			   error = $(this).find('div.content-confirmation').html();
			   if (error != null) {
			  		myobj.parent().parent().find('div.join p').html('<span class="error">'+error+'</span>');
			  	} else {
			  		myobj.parent().parent().find('div.join p').html('<span class="error">Your email address has been added to our mailing list and you will now receive regular newsletters. </span>');
			  	}
			   debug('no error');
			   removeDom(myobj);
			}
			removeDom($(this));
		});
		
		
		return false;
	});
	
}


function setUpSearchPager() {
$('.paginator li a').click(function(me){
	me.preventDefault();
	var url = $(this).attr('href');
	url = url.replace(urlfilter,'');
	url = url.replace(/\?/g,'&');
	//url = url.substring(1,url.length);
	//query = url.substring(url.indexOf('query=')+6,url.length);
	$('#nav').after('<div id="searchtemp" style="display:none"></div>');
	$('#searchtemp').load('/dynamic.php?url='+url,function(){
		wobj.find('div.search-content').html($(this).find('div.search-content').html());
		removeDom($(this));
		setUpSearchResults();
		setUpSearchBar();
		setUpSearchPager();
	});
	//var windowname = 'search';
	//wm.gotoWindow(windowname,query);	
	return false;
});

}

function setUpSearchResults() {
	$('.search-result a').click(function(me){
		me.preventDefault();
		var url = $(this).attr('href');
		url = url.replace(urlfilter,'');
		url = url.substring(1,url.length);
		wm.gotoAddress(url);
		return false;
	});
}


function setUpSearchBar() {
	var listitems = $('.paginator li');
	// multiply total list items by the individual list item widths
	var listwidth = listitems.length * 25;
	// subtract this total from 518px (width of the paginator)
	var barwidth = 518 - listwidth;
	// add the bar and assign it the value from the total above
	$('.paginator ol').append('<li class="bar" style="width:'+barwidth+'px"></li>').css(
	{
		"background" : "url(/layout/img/paginator-rbit.png) no-repeat right"
	});
}

function hijackNav(nav) {
	nav.each(function(){
		var url = $(this).attr('href');
		url = url.replace(urlfilter,'');
		var windowname = url.substring(1,url.length);
		$(this).attr('id','window_'+windowname);
		$(this).click(function(me){
			me.preventDefault();
			wm.gotoWindow(windowname);
			return false;
		});
	});

}

// main window manager
function WindowManager() {
	// we keep track of windows with this object
	this.openWindows = new Array();
	this.namesArray = new Array();
	this.activeWindow = -1;
	
	this.waitingFor = new Array();
	this.subNavActive = new Array();
	
	return this;
}
WindowManager.prototype.setUpWindow = function(which,name,isFirstWindow) {
	// where is it positioned top: 150px; left: 130px;
	
	
	
	// debug('window setup :'+name);
	if (this.openWindows.length > 0) {
		lw = this.openWindows[this.openWindows.length-1].which;
		lwt = lw.css('top');
		lwt = parseInt(lwt.substr(0,lwt.length-2));
		lwl = lw.css('left');
		lwl = parseInt(lwl.substr(0,lwl.length-2));
	} else {
		lwt = 130;
		lwl = 110;
	}
	which.css('top',lwt+20+'px');
	which.css('left',lwl+20+'px');
	var wurl = '#/'+name;
	// debug(wurl);
	this.openWindows.push(new WindowObj(which,name,null,null,wurl));
	// debug(this.openWindows[this.openWindows.length-1]);
	var obj = this;
	var windowname = name;
	//which.draggable({handle:'.title-bar',containment:'body',cursor:'default',
	which.draggable({handle:'.title-bar',cursor:'default',
		cancel:'.close',
		start:function(event,ui) {
			obj.focusWindow(windowname);
			which.find('.title-bar').addClass('active');
			which.attr('role',1);
		},
		stop:function(event,ui) {
			which.find('.title-bar').removeClass('active');
			which.attr('role',-1);
		}
	});
		
	which.find('.title-bar .close').click(function() {
		//debug('close window');
		obj.closeWindow(windowname);
	});

	var titlebarc = which.find('.title-bar .content');
	titlebarc.append('<p>Click &amp; drag to move this window</p>');
	which.find('.title-bar').hover(function() {
		if ($(this).attr('rel') == 1) {
			$(this).addClass('active');
			titlebarc.find('p').show();
			//titlebarc.append('<p>Click &amp; drag to move this window</p>');
		}
	},function(){
		if (which.attr('role') != 1) {
			$(this).removeClass('active');
			titlebarc.find('p').hide();
		}
	});
	which.find('.title-bar').attr('rel',1);

	var nav = which.find('.nav-supp li a');
	if (nav.length > 0) {
		hijackNav(nav);
	}
	this.getSubNav(which,this.openWindows.length-1,isFirstWindow);
	
	
	which.show();
	
	this.blurActiveWindow();
	this.activeWindow = this.openWindows[this.openWindows.length-1].name;
	this.changeURL(this.openWindows[this.openWindows.length-1].windowURL);
	// active window blur
	// set new active window
	setUpSubscriptionForm();
	// adjust depths
	this.adjustDepths();
	this.checkWaiting(windowname);
}

WindowManager.prototype.getSubNav = function(which,wobj,isFirstWindow) {
	// debug(wobj);
	windowname = this.openWindows[wobj].name;
	var windowobj = wobj;
	obj = this;
	if (isFirstWindow) {
		$('#main').append('<div class="box" id="temp" style="display:none"></div>');
		var newsubnav = '';
		$('#temp').load('/dynamic.php?url='+windowname,function(){

			$('#'+windowname).find('.nav-secondary').html($('#temp').find('.nav-secondary').html());
			removeDom($('#temp'));
			var subNav = $('#'+windowname).find('.nav-secondary')
			obj.parseSubNav(windowobj,subNav);
			
			
		});

	} else {


		var subNav = $(this.openWindows[wobj].which).find(".nav-secondary");
		obj.parseSubNav(windowobj,subNav);
	}
}

WindowManager.prototype.parseSubNav = function(wobj,subNavObj) {
	obj = this;
	cnt = 0;
	var windowobj = wobj;
	if (subNavObj.length > 0 ) {
		subNavObj.find('a').each(function(){
			var href = $(this).attr('href');
			href = href.replace(urlfilter,'');
			var linkurl = href.substring(1,href.length);
			$(this).attr('id',parseURLtoID(linkurl));
			if (cnt == 0) {
				obj.activateSubNav(linkurl);
			}
			obj.openWindows[windowobj].subNav.push(new SubNavObj(this,linkurl));
			var myobj = obj;
			$(this).click(function(me){
				me.preventDefault();
				myobj.gotoAddress(linkurl);
				return false;
			});
			cnt++;
		});
	
		
		//this.openWindows[windowobj].subNav.reverse();
		this.openWindows[windowobj].subNavFlag = true;
		// debug(this.openWindows[windowobj]);
	} 
}

WindowManager.prototype.checkWaiting = function(windowname) {
	while(this.waitingFor.length > 0) {
		toeval = this.waitingFor.pop();
		eval(toeval[1]);
	}
	
}

WindowManager.prototype.gotoAddress = function(address,callback) {
	debug('goto '+address);
	var levels = address.split('/');
	if(callback) {
		// debug('callback');	
		//var sublevel = address.substring(address.indexOf('/')+1,address.length);
		var windowdiv = $('#'+levels[0]);
		var contentbox = $('#'+levels[0]).find('.box-content');
		contentbox.after('<div id="subtemp" style="display:none;"></div>');
		windowdiv.find('#subtemp').load('/dynamic.php?url='+address,function(){
			content = windowdiv.find('#subtemp').find('.col-right').html();
			//debug(content);
			contentbox.find('.col-right').html(content);
			var title = windowdiv.find('#subtemp').find('.title-bar h1').html();
			windowdiv.find('h1').html(title);
			
			removeDom($('#subtemp'));
		});
		//debug(address);
		//debug('#'+parseURLtoID(address));
		/*$('#'+parseURLtoID(address)).parent().addClass('active');
		var levelup = address.substring(0,address.lastIndexOf('/'));
		$('#'+parseURLtoID(levelup)).parent().addClass('active');
		levelup = levelup.substring(0,levelup.lastIndexOf('/'));
		$('#'+parseURLtoID(levelup)).parent().addClass('active');*/
		this.activateSubNav(address);
		//$('#wrap').prepend(address);
		var position = this.getPosition(levels[0]);
		if (position > -1) {
			this.openWindows[position].windowURL = '#/'+address;
		}
		// change url
		this.changeURL('#/'+address);
		
	} else {
		this.waitingFor.push([levels[0],'this.gotoAddress("'+address+'",true)']);
		this.gotoWindow(levels[0]);
		//debug('window'+levels[0]);
		
	}


}

WindowManager.prototype.changeURL = function(url) {
	var existing = window.location.href;
	// check if we have a #
	var hash = existing.indexOf('#/');
	if (hash > 0) {
		existing = existing.substring(0,hash);
	}
	window.location.href = existing+url;
}

WindowManager.prototype.activateSubNav = function(address) {
	// first deactivate everything that was active: this.subNavActive	
	debug('activateSubNav: '+ address);
	while(this.subNavActive.length > 0) {
		//debug(this.subNavActive[i]);
		$('#'+parseURLtoID(this.subNavActive.pop())).parent().removeClass('active');
	}

	// now activate recursivly
	var activate = address;
	debug($('#'+parseURLtoID(activate)).parent().addClass('active'));
	$('#'+parseURLtoID(activate)).parent().addClass('active');
	this.subNavActive.push(activate);
	while (activate.lastIndexOf('/') >  -1) {
		activate = activate.substring(0,activate.lastIndexOf('/'));
		$('#'+parseURLtoID(activate)).parent().addClass('active');
		this.subNavActive.push(activate);
	}
	
	

}


WindowManager.prototype.gotoWindow = function(windowname,query) {
	// check if this window already exists if yes just focus it
	// get the first part of url
	if (query != null) {
		var position = this.getPosition(windowname);
		if (position > -1) {
			this.closeWindow(windowname);
		}
	}
	var obj = this;
	var thisname = windowname;
	var windowref = null;
	for (i in this.openWindows) {
		if (this.openWindows[i].name == windowname) {
			windowref = i;
		}
	}
	if (windowref == null) {
		debug('no it doesnt '+windowname);
		
		$('#main').append('<div class="box" id="'+windowname+'"></div>');
		$('#'+windowname).hide();
		
		if (query != null) {
			
			$('#'+windowname).load('/dynamic.php?url=/home/search&query='+query,function(){
				//debug('window loaded');
				// here we hijack the links...
				wobj = $(this);
				setUpSearchResults();
				
				// here the pager
				setUpSearchPager();
				
				obj.setUpWindow($(this),thisname);
				setUpSearchBar();
			});
		} else {
			$('#'+windowname).load('/dynamic.php?url='+windowname,function(){
				//debug('window loaded');
				obj.setUpWindow($(this),thisname);
				
			});		
		}
	} else {
		debug('yes it exists'+windowname);
		// bring it in focus
		this.focusWindow(windowname);
		this.checkWaiting(windowname);
		
	}
	
}



WindowManager.prototype.blurActiveWindow = function() {
	if (this.activeWindow != -1) {
		this.blurWindow(this.activeWindow);
	}
}
WindowManager.prototype.closeWindow = function(windowname) {
	// remove window
	//var close = this.closeBox();
	var nextactive = null;
	if (this.openWindows.length > 1) {
		var nextactive = this.openWindows[this.openWindows.length-2].name;
	} 
	var position = this.getPosition(windowname);
	var todelete = this.openWindows[position].which;
	var trash = this.openWindows.splice(position,1);
	
	////debug(todelete);
	todelete.remove();
	if (nextactive != null) {
		this.focusWindow(nextactive);
	}
	trash = null;
	// remove from open windows array
	//var remove = this.hide(openWindows);
	// adjust depths
	$('#window_'+windowname).parent().removeClass('active');
	this.adjustDepths();
}
WindowManager.prototype.blurWindow = function(windowname) {
	// debug('blurring: '+windowname);
	// and click of entire element to call focus
	// pos contains the window position it the open window array
	var position = this.getPosition(windowname);
	if (position > -1) {
		var obj = this;
		var me = this.openWindows[position].which;
		var name = windowname
		me.find('.title-bar').attr('rel',-1);
		//me.draggable('disable');
		me.click(function(){
			obj.focusWindow(name);
		});
	}	
}
WindowManager.prototype.getPosition = function(windowname) {
	var windowref = null;
	for (i in this.openWindows) {
		if (this.openWindows[i].name == windowname) {
			windowref = i;
		}
	}
	if (windowref == null) {
		return -1;
	} else {
		return windowref;
	}
}


WindowManager.prototype.focusWindow = function(windowname) { 
	//debug('focus window:'+windowname);
	if (this.activeWindow != windowname) {
	
		this.blurActiveWindow();
		// active window blur
		var position = this.getPosition(windowname);
		// change array
		//debug(position);
		if (position > -1) {
			this.changeURL(this.openWindows[position].windowURL);
			var windowtomove = this.openWindows[position];
			windowtomove.which.find('.title-bar').attr('rel',1);
			this.openWindows.push(new WindowObj(windowtomove.which,windowtomove.name,windowtomove.subNav,windowtomove.subNavFlag,windowtomove.windowURL));
			this.activeWindow = windowtomove.name;
			windowtomove.which.unbind('click');
			//windowtomove.which.draggable('enable');
			var trash = this.openWindows.splice(position,1);
			//debug(this.openWindows);
			this.adjustDepths();
		}
		
	}
	

	
	
	// set new active window
	// adjust depths	
}
WindowManager.prototype.adjustDepths = function() {
	// change the z-index values of all windows according to the array
	for (i in this.openWindows) {
		this.openWindows[i].which.css('z-index',10+i);
		if (i == this.openWindows.length - 1) {
			this.openWindows[i].which.fadeTo(100,1);
			$('#window_'+this.openWindows[i].name).parent().addClass('active');
		} else {
			this.openWindows[i].which.fadeTo(100,.65);
			$('#window_'+this.openWindows[i].name).parent().removeClass('active');
		}
	}


}
function WindowObj(which,name,subNav,subNavFlag,windowURL){
	this.which = which;
	this.name = name;
	if (subNav == null) {
		this.subNav = new Array();
	} else {
		this.subNav = subNav;
	}
	if (subNavFlag == null) {
		this.subNavFlag = false;
	} else {
		this.subNavFlag = subNavFlag;
	}
	if (windowURL == null) {
		this.windowURL = false;
	} else {
		this.windowURL = windowURL;
	}
	return this;
}
function SubNavObj(which,href) {
	this.which = which;
	this.href = href;
	return this;
}
function removeDom(obj) {
	obj.remove();
}
function parseURLtoID(what) {
	var unders = '_';
	what = 'link_'+what.replace(/\//g,unders);
	return what;
}
function parseIDtoURL(what) {
	what.replace('_','/');
	return what.substring(what.indexOf('link/')+1,what.length);
}

/*	set active states on main nav
	loop through window names
	get the href id i.e. about-us
	apply class of active to the current active window
*/
