(function(){

var tylerault = window.tylerault || {};
window.tylerault = tylerault;

tylerault.isSmall = function(){
	return ($(window).width() < 600);
};

tylerault.useAjax = function( href ){
	return ( href.search( /(^http|^\/admin|\.rss$)/i ) < 0 );
};

tylerault.SiteController = new function(){

	var Utils = tylerault.Utils;
	var controller = this;

	this.init = function(){
		$('#content').css({visibility:'hidden'});

		tylerault.MainNav.init();


		$.address.init( function(e){
			var hash = e.value;
			var path = window.location.pathname;
			if( path !== "/" && ( typeof hash == 'undefined' || hash == "/" ||
				  hash === null ||  hash.length < 1 ) ){
				if( tylerault.useAjax( path ) ){
					window.location = "/#" + path;
				} else {
					$('#content').css({visibility:'visible'});
				}
				return;
			}
			$.address.change( onAddressChange );
			tylerault.MainNav.update(); 
		});

		if( window.location.pathname.search( /^\/admin/i ) >= 0 ){
			$(".add_tag_list").click( controller.onAddTagClick );
		} else {
			this.bindLinks('body');
		}
	};

	this.toString = function(){
		return "SiteController";
	};

	this.bindLinks = function( selector ){
		$(selector + " a").click( function(e){ tylerault.SiteController.onLinkClick(e); } );
	};


	this.onLinkClick = function( e ){
		
		var href = $( e.target ).attr('href');

		if( tylerault.useAjax( href ) ){
			e.preventDefault();
			$.address.value( href );

		}
	};

	this.onSectionLoaded = function( response ){
		try{
			var html = $.trim( response ),
				content = $('#content');

			content.css({visibility:'visible'}).stop( true, true ); // clear queue, go to end
			content.empty().html( html );
			 
			var title = content.find( '.sectionTitle' ).val();
			$.address.title( title ); 

			this.bindLinks('#content');

			if( tylerault.isSmall() ){
				content.css( { opacity:1.0 } ); 
			} else {
				content.animate( {opacity:1.0} );
			}

		} catch( err ){
			Utils.log( "onSectionLoaded: error: " + err );
		}
	};

	this.onAddTagClick = function( e ){
		e.preventDefault();
		var href = e.target.href;
		var tag = href.substr( href.lastIndexOf( "#" ) + 1 );
		var input = $(".tags_input")[0];
		var value = $(input).val();
		value = ( !value || value == "" ) ? tag : value + ", " + tag;
		$(input).val( value );
	};

	var onAddressChange = function( e ){

		var value = e.value;

		if( value === "" || value === null ) { return };

		if( tylerault.isSmall() ){
			$('#content').css({visibility:'hidden'});
		} else {
			$('#content').animate( { opacity: 0.0 }, 200 );
		}

		$.ajax( {
			url: value + ".ajax",
			dataType: "text",
			success: function( data ){ tylerault.SiteController.onSectionLoaded( data ); },
			error: function( jqXHR, status, error ){ Utils.log( "AJAX ERROR: " + status ); }
		} );
		
		tylerault.MainNav.update(); 

		e.preventDefault(); 
	};

};

tylerault.MainNav = new function(){

	this.animate = false;
	this.hilight = null;
	var nav = this;

	this.init = function(){
		$(window).resize( function( e ){
			tylerault.MainNav.evaluateMode();
		});
		this.evaluateMode();
	};

	this.update = function(){

		var pathNames = $.address.pathNames(),
			basePath, pathIndex;
		
		if( pathNames.length > 0 ){
			pathIndex = pathNames[0] == 'admin' ? 1 : 0;
			basePath = '/' + pathNames[ pathIndex ];
		} else {
			basePath = '/portfolio';
		}

		if( this.animate ){
		    updateAnimated( basePath );
		}

	 	var items = $('#main_nav a').each(function(){
	 		$(this).removeClass('active');
	 		if( $(this).attr('href') == basePath ){
	 			$(this).addClass('active');
	 		}
	 	});
	};
	
	var updateAnimated = function( basePath ){
		var target = $('#main_nav a[href="' + basePath + '"]'),
			current = $('#main_nav a.active'),
			list = $('#main_nav ul'),
			pos = target.position(),
			listPos = list.position(),
			listBottom = list.css('bottom'),
			hilight = nav.hilight,
			time, dest;

		if( !hilight || target.length < 1 ){ return; }

		dest = { left: ( pos.left + listPos.left ),
			width: target.outerWidth() };

		if( current.length < 1 || hilight.css( 'bottom' ) != listBottom ){
			hilight.css( { left: dest.left + "px",
				width: dest.width + "px",
				bottom: listBottom, 
				height: target.height() + "px"
			});
		} else {
			var cx = listPos.left + current.position().left,
				diffX = Math.abs( dest.left - cx ),
				dir = dest.left - cx,
				middleX = dir < 0 ? dest.left : cx,
				middleW = diffX + ( dir < 0 ? current.outerWidth() : dest.width );

			var finish = function(){
				$(this).animate( { left: dest.left + "px", width: dest.width + "px" },
						125, 'easeInOutCubic' );
			}

			hilight.stop( true, true ).animate( { left: middleX + "px", width: middleW + "px" },
					125, 'easeInOutCubic', finish );
		}

	};

	this.evaluateMode = function(){
		var small = tylerault.isSmall();
		if( this.animate == !small ){ return; }
		this.animate = ( !small && tylerault.useAjax( window.location.pathname ));
		if( small ){
			if( this.hilight ){ this.hilight.hide(); }
			$('#main_nav').removeClass('animated').addClass('instant');
		}
		else {
			$('#main_nav').addClass("animated").removeClass("instant");
			$('#main_nav a').removeClass("active"); 
			if( !this.hilight ){ 
				$('#main_nav').prepend('<div class="nav_hilight" />');
				this.hilight = $('.nav_hilight');
			} else {
				this.hilight.show();
			}
		}
		this.update();
	};

	
}

$(document).ready(function(){ tylerault.SiteController.init() });

})();

