// Thank to:
// https://gist.github.com/854622

if(Modernizr.history)
(function(window,undefined){

	// Prepare our Variables
	var
		History = window.History,
		$ = window.jQuery,
		document = window.document;

	// Check to see if History.js is enabled for our Browser
	if ( !History.enabled || (screen.width < 768)) {
		return false;
	}
		
	// Wait for Document
	$(function(){
		// Prepare Variables
		var
			/* Application Specific Variables */
			contentSelector = '#frame',
			$content = $(contentSelector).filter(':first'),
			contentNode = $content.get(0),
			$menu = $('#menu, #isotope');//.filter(':first'),
			activeClass = 'selected',
			activeSelector = '.selected',
			menuChildrenSelector = 'li, article',
			/* Application Generic Variables */
			$body = $(document.body),
			rootUrl = History.getRootUrl(),
			scrollOptions = {
				duration: 800,
				easing:'swing'
			};
		
		// Ensure Content
		if ( $content.length === 0 ) {
			$content = $body;
		}
		
		// Internal Helper
		$.expr[':'].internal = function(obj, index, meta, stack){
			// Prepare
			var
				$this = $(obj),
				url = $this.attr('href')||'',
				isInternalLink;
			
			// Check link
			isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;
			
			// Ignore or Keep
			return isInternalLink;
		};
		
		// HTML Helper
		var documentHtml = function(html){
			// Prepare
			var result = String(html)
				.replace(/<\!DOCTYPE[^>]*>/i, '')
				.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
				.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>')
			;
			
			// Return
			return result;
		};
		
		// Ajaxify Helper
		$.fn.ajaxify = function(){
			// Prepare
			var $this = $(this);
			
			// Ajaxify
			$this.find('a:internal:not(.no-ajax)').click(function(event){
				// Prepare
				var
					$this = $(this),
					url = $this.attr('href'),
					title = $this.attr('title')||null;
				
				if( $this.parents("ul").length || ($this.attr("id") == "toggle-featured") )
				{
					if($this.attr("id") == "toggle-featured")
					{
						filter_actions($this);
						$("#frame").off();
					}
					
					/*else if($this.parents("#menu").length)
					{
						$menu.find(".selected").removeClass("selected");
					}*/
					
					$menu = $this.parents("ul");
					$menu.find(".selected").removeClass("selected");
					$this.addClass("selected");
								
					if($("body").hasClass("filter-open") && ($menu.parent().attr("id") == "menu"))
					{					
						/*if($this.parent().hasClass("work") && (window.location.href.substr(-4, 4) == "work"))
						{
							$("#find").trigger("click");
						}
						else*/
						if($this.attr("id") != "find")
						{
							$("body").addClass("hide-filter");
							$("#find").removeClass("selected");	
							$("#filter").css("opacity", 0);						
							$("#frame").off();
						}
					}
				}
				else
				{
					$menu = $('#isotope');
					
					if($("body").hasClass("filter-open"))
					{
						$("body").addClass("hide-filter");
						//$("#find").removeClass("selected");	
						$("#filter").css("opacity", 0);
						$("#frame").off();
					}
				}						
				// Continue as normal for cmd clicks etc
				if ( event.which == 2 || event.metaKey ) { return true; }
								
				// Ajaxify this link
				History.pushState(null,title,url);
				event.preventDefault();
				return false;
			});
			
			// Chain
			return $this;
		};
		
		// Ajaxify our Internal Links
		$body.ajaxify();
		
		// Hook into State Changes
		$(window).bind('statechange',function(){
			// Prepare Variables
			var
				State = History.getState(),
				url = State.url,
				relativeUrl = url.replace(rootUrl,'');
						
			// Set Loading
			//$body.addClass('loading');

			// Start Fade Out
			// Animating to opacity to 0 still keeps the element's height intact
			// Which prevents that annoying pop bang issue when loading in new content
			$content.css("opacity", 0);
			
			if($("body").hasClass("filter-open") && (url.indexOf("categories") == -1) && (url.indexOf("all") == -1) && (url.substr(-4, 4) != "work") && (url.indexOf("clients") == -1))
			{
				$("body").addClass("hide-filter");
				//$("#find").removeClass("selected");	
				$("#filter").addClass("just_opacity").css("opacity", 0);
				$("#frame").off();
			}
			
			setTimeout(function(){
			// Ajax Request the Traditional Page
			
			$("#loading").remove();
			$body.append(loading_html);
			
			setTimeout(function(){
				if($("#loading").length)
					$("#loading").css("display", "block");
			}, 1000);
			
			if($("body").hasClass("hide-filter"))
			{
				$("body").addClass("no_transition").removeClass("filter-open hide-filter");
				//$("#filter").addClass("just_opacity").css("opacity", 1);
			}
			
			$.ajax({
				url: url,
				success: function(data, textStatus, jqXHR){
					// Prepare
					var
						$data = $(documentHtml(data)),
						$dataBody = $data.find('.document-body:first'),
						$dataContent = $dataBody.find(contentSelector).filter(':first'),
						dataClass = $dataContent.attr("data-class"),
						dataFiltered = $dataContent.attr("data-filtered"),
						menuSelect = $dataContent.attr("data-menu"),
						dataFilteredID = $dataContent.attr("data-id"),
						$menuChildren, contentHtml, $scripts;
					
					// Fetch the scripts
					$scripts = $dataContent.find('.document-script');
					if ( $scripts.length ) {
						$scripts.detach();
					}

					// Fetch the content
					contentHtml = $dataContent.html()||$data.html();
					if ( !contentHtml ) {
						document.location.href = url;
						return false;
					}
										
					// Add custom page classes
					$("body").removeClass("home about contact text_page work single no_transition").addClass(dataClass);
					
					/*if(url.substr(-4, 4) == "work")
					{
						dataFiltered = "featured";
					}*/
					
					var menuSelected = $("#menu").find(".selected");
										
					if((menuSelect != menuSelected.parent().attr("class")) && (menuSelected.attr("id") != "find"))
					{
						menuSelected.removeClass("selected no-ajax");
						$("." + menuSelect, "#menu").find("a").addClass("selected");
					}
								
					if(dataFiltered)
					{					
						var cur_el = $("#filter .header .selected");
						
						if(cur_el.length)
						{
							var cur_id = cur_el.attr("id").replace("toggle-","");
						
							$(".selected", "#filter").removeAttr("class");
							cur_el.removeClass("selected");
						}
						//$("#find").addClass("selected");
						
						$("#" + dataFilteredID).addClass("selected");
						
						$("#toggle-" + dataFiltered).addClass("selected");
									
						$("#" + cur_id).removeClass("open").addClass("hidden");
						$("#" + dataFiltered).removeClass("hidden").addClass("open");									
					}
					//$("#filter").addClass("just_opacity");
					
					// Add custom page classes
					/*$("body").removeClass("home").removeClass("about").removeClass("contact").removeClass("work");
					
					if(relativeUrl.match("index"))
					{
						$("body").addClass("home");
					}
					else if(relativeUrl.match("about"))
					{
						$("body").addClass("about");
					}
					else if(relativeUrl.match("contact")) 
					{
						$("body").addClass("contact");
					}
					else
					{
						$("body").addClass("work");
						$menu.find(".work a").addClass("selected");
					} */
					
					$("html, body").scrollTop(0);
										
					// Update the menu
					/*$menuChildren = $menu.find(menuChildrenSelector);
 					$menuChildren.find("a").filter(activeSelector).removeClass(activeClass);
					$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
					if ( $menuChildren.length === 1 ) { $menuChildren.find("a").addClass(activeClass); }*/

					// Update the content
					$content.stop(true,true);
					$content.html(contentHtml).ajaxify(); /* you could fade in here if you'd like */
										
					// Add custom page classes after content is appended
					// if($("#single").length && $("body").hasClass("work")) $("body").addClass("single");
					
					/* reselect filters */
			
					/*if(!el.hasClass("selected"))
					{*/			
						/*var cur_el = $("#filter .header .selected");
						var cur_id = cur_el.attr("id").replace("toggle-","");
						var futured_id = $("#frame").attr("data-filtered");
						var future_el = $("#toggle-" + futured_id);
						
						console.log(futured_id);
						
						$(".selected", "#filter").removeAttr("class");
						
						cur_el.removeClass("selected");
						future_el.addClass("selected");
									
						$("#" + cur_id).removeClass("open");
									
						var waitForOpacity2 = setTimeout(function(){
							$("#" + cur_id).addClass("hidden");
							$("#" + futured_id).removeClass("hidden")
							
							var waitForHiding = setTimeout(function(){
								$("#" + futured_id).addClass("open");
								clearTimeout(waitForHiding);
							}, 100);
							clearTimeout(waitForOpacity2);
						}, 300);*/
					/*}*/
					
					/* reselect filter */
					
					setTimeout(function(){
						$content.css("opacity", 1);
						
						if($("body").hasClass("filter-open"))
							$("#filter").css("opacity", 1);
					}, 250);
					
					// Update the title
					document.title = $data.find('.document-title:first').text();
					try {
						document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
					}
					catch ( Exception ) { }
					
					// Add the scripts
					$scripts.each(function(){
						var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
						scriptNode.appendChild(document.createTextNode(scriptText));
						contentNode.appendChild(scriptNode);
					});

					// Complete the change
					//if ( $body.ScrollTo||false ) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
					
					if($("#loading").length)
						$("#loading").remove();
					//$body.removeClass('loading');
	
					// Inform Google Analytics of the change
					_gaq.push(['_trackPageview', relativeUrl]);
					
					/*if ( typeof window.pageTracker !== 'undefined' ) {
						window.pageTracker._trackPageview(relativeUrl);
						
					}*/
					
					// Init custom Sennep content
					reinitialise_content();
					
					// Resize elements
					resize_magic();
					
					/*if($("#isotope").length)
						$("#isotope").diagonalFade({
							time: 150,
							fadeDirection_x: 'left-right',
							fadeDirection_y: 'top-bottom',
							fade: 'in',
							complete: null
						});
					*/
				},
				error: function(jqXHR, textStatus, errorThrown){
					document.location.href = url;
					return false;
				}
			}); // end ajax
			}, 400);

		}); // end onStateChange

	}); // end onDomLoad

})(window); // end closure