/*
 * depeds on jquery. more doco yet to come after i finish developing this thingy
 */

(function(){
	var DEBUG = true;
	function Error(err) {
		if (DEBUG) {
			if (window.console) {
				console.log('Error: "' + err.message + '"');
			}
			else {			
				alert('Error: "' + err.message + '"');	
			}
		}
		else { return false }
	}

	/* 
	 * Portfolio object
	 * @description: switches pages within the portfolio tab
	 * @settings = {
	 *		itemClass : default class name for each item
	 *		rootItemId : id of the containing element
	 *		curItem : the currently displayed item (the first item displayed need not be the first in the DOM)
	 *		navItemSelector : the CSS3 selector for each navigation item
	 *	}
	 */
	function Portfolio(settings){
		this.settings = settings;
		this.allItems = $("."+this.settings.itemClass, $("#"+this.settings.rootItemId));
		try {
			if (!this.allItems.length) { throw('no items in portfolio') }
		}
		catch(err) {
			Error({message: err});
		}
	}
	
	/* 
	 * displays the next or previous item
	 * @opts = {
	 *		direction : string 'prev' || 'next' 
	 *		itemPrefix : prefix used as the id of each nav element 
	 */
	Portfolio.prototype.slide = function(opts){
		if (!this.allItems) {
			this.allItems = $("."+this.settings.itemClass, $("#"+this.settings.rootItemId));
		}
		var fwd = (opts.direction && opts.direction == 'prev') ? 0 : 1; // default to fwd if no param supplied
		if (fwd) {
			var nextItem = (this.settings.curItem === this.allItems.length-1) ? 0 : parseInt(this.settings.curItem, 10) + 1;
		}
		else {
			var nextItem = (this.settings.curItem === 0) ? this.allItems.length - 1 : parseInt(this.settings.curItem, 10) - 1;
		}
		this.allItems.eq(this.settings.curItem).hide();
		this.allItems.eq(nextItem).show();
		this.settings.curItem = nextItem;
		this.updateNav(opts.itemPrefix + nextItem);
	}
	/*
	 * updates the navigation to indicate the current item
	 */
	Portfolio.prototype.updateNav = function(itemId){
		$(this.settings.navItemSelector).removeClass('selected');
		$("#"+itemId).addClass('selected');
	}
	/*
	 * displays the indicated item
	 * @opts = {
	 * 		id : ID of the item to jump to
	 * 		itemId : ID of the navigation element clicked
	 * }
	 */
	Portfolio.prototype.jump = function(opts){
		
		if (!this.allItems) {
			this.allItems = $("."+this.settings.itemClass, $("#"+this.settings.rootItemId));
		}
		id = opts.id * 1; // parse to integer
		this.allItems.eq(this.settings.curItem).hide();
		this.allItems.eq(id).show();
		this.settings.curItem = id;
		this.updateNav(opts.itemId);
	}

	
	/*
	 * switches tabs in the main menu
	 * @settings = {
	 *		container : jQuery element containing tabs
	 *		effect: 'fade' - in the future this can be extended to include other transitions
	 *		tab_prefix: prefix for each tab ID
	 *		tab_class: class name for each tab
	 * }
	 */
	function TabLoader(settings){
		try {
			if (!settings.container) {
				throw('container not defined')
			}
			if (!settings.container.length) {
				throw('container not in DOM')
			}
		}
		catch(err) {
			Error({message: err});
		}
		this.settings = {
			effect: 'fade',
			tab_prefix: 'tl_tab_',
			tab_class: 'tl_tab'
		};
		$.extend(this.settings, settings);
		this.ajaxSettings = {
			type: "GET",
			dataType: "html",
			error: function(){ alert('error occurred'); }
		};
		this.curTab = '';
	}
	TabLoader.prototype.setCurTab = function(tab){
		var curTab = $("#" + this.settings.tab_prefix + tab);
		if (curTab.length) {
			this.curTab = curTab;
		}
	}
	// item is optional: used for portfolio tam only at the mo
	TabLoader.prototype.switchTab = function(id, callback, item){
		var that = this;
		var item = item || 0;
		var showItem = function(id) {
			if (window.app) { // the application is running
				if (!app.portfolio) {
					app.portfolio = new app.Portfolio({
						curItem: id,
						rootItemId: "portfolio_scroll",
						itemClass: 'portfolio_item',
						navItemSelector: 'li.project a'
					});					
				}
				app.portfolio.jump({id: item, itemId: 'pItem_'+id});
			}
		}
		var moveToTab = function(tab) {	
			switch(that.settings.effect) {
				/* slider effect
				case 'slider': 
					var index = tab.prevAll().length;
					var leftOffset = tab.width() * index * -1;
					that.settings.container.animate({'left':leftOffset+'px'}, 600);	
					break;
				*/
				case 'fade':
					tab.hide();
					if (that.curTab){ 
						that.curTab.fadeOut(function(){
							tab.fadeIn(function(){
								$(this).attr('style','display:block;');
							});
						});
					}
					else {
						tab.fadeIn(function(){
							$(this).attr('style','display:block;');
						});
					}
					that.curTab = tab;
					break;
				default: // fade is default
					tab.hide();
					if (that.curTab){ 
						that.curTab.fadeOut(function(){
							tab.fadeIn(function(){
								$(this).attr('style','display:block;');
							});
						});
					}
					else {
						tab.fadeIn(function(){
							$(this).attr('style','display:block;');
						});
					}
					that.curTab = tab;
					break;
			}
			if (callback && typeof callback == 'function') {
				callback();
			}
		}
		var newTab = $("#" + this.settings.tab_prefix + id);
		if (newTab.length) {
			// switch tabs only if different tabs
			if (that.curTab.attr('id') != newTab.attr('id')) {
				moveToTab(newTab);
				if (item) {
					showItem(item);
				}
			}
			else { return false; }
		}
		else { 
		//load tab contents
			
			// callback function
			var success = function(html){
				var newTab = $('<div id="' + that.settings.tab_prefix + id + '" class="' + that.settings.tab_class + '">' + html + '</div>').appendTo(that.settings.container);
				moveToTab(newTab);
				if (item) {
					showItem(item);
				}
			}
			var opts = this.ajaxSettings;
			opts.success = success;
			opts.url = 'index.php';
			opts.data = 'short=1&page='+id;
			$.ajax(opts);
		}
		return true;
	};

	// helper function to read params from url
	function getParam(param, url) {
		var paramVal = "";
		var url = url || window.location.href; // if no url passed assume it's the page url
		if ( url.indexOf("?") > -1 ) {
			var query = url.substr(url.indexOf("?")).toLowerCase();
			var params = query.split("&");
			for ( var i = 0; i < params.length; i++ ) {
				if (params[i].indexOf(param.toLowerCase() + "=") > -1 ) {
					var paramPair = params[i].split("=");
					paramVal = paramPair[1];
					break;
				}
			}
		}
		return unescape(paramVal);
	} 
	
	// assign to global variable
	window.app = {
		TabLoader: TabLoader,
		Portfolio: Portfolio,
		getParam: getParam
	};
	
	
})();

$(document).ready(function(){
	var icon = $("#ajax_loader");
	icon.ajaxStart(function(){
		$(this).show();
	});
	icon.ajaxStop(function(){
		$(this).hide();
	});
	app.tabs = new app.TabLoader({container: $("#tabs")});
	// handler function for tab links within the page
	app.switchTabs = function(e){
		e.preventDefault();
		// get params from url
		var page = app.getParam('page', $(this).attr('href')) || 'index';
		var item = app.getParam('item', $(this).attr('href'));
		
		// trigger the TabLoader handler function
		app.tabs.switchTab(page, function(){
			$("#main .selected").removeClass('selected');
			$("#main #menuItem_"+page).addClass('selected');
			$("#tl_tab_"+page+" a.load").click(app.switchTabs);
		},item);
		return false;
	}
	$("a.load").click(app.switchTabs);
});
