(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 ) {
		return false;
	}

	// Wait for Document
	$(function(){
		$("img.qtipper").each(function()
		{
			$(this).parents('a').hover(function(e)
				{
					$(this).children('.enlarge').show();
				},
				function(e)
				{
					$(this).children('.enlarge').hide();
				})
				.click(function(e){
					return false;
				});
			$enlarge_icon = $('<span class="enlarge"></span>').click(function(e)
			{
				$("img.qtipper").trigger('click');
			});
			$(this).parents('a').css('position','relative').append($enlarge_icon);
			$(this).qtip({
				content: {
					text: $('#qtipper_content'),
					title: {
						text: $(this).attr('title'),
						button: 'x'
						}
					},
				style: {
					width: {
						max: 550
					},
					height: {
						max: 550
					},
					border: {
						width: 1,
						color: '#b5b5b5'
					},
					button: {
						'border-width': '1px',
						'border-color': '#b5b5b5',
						'border-style': 'solid',
						'height': '1.25em',
						'width': '1em',
						'line-height': '1em',
						'padding-left': '.25em',
						'display': 'block'
					},
					name: 'light'
				},
				position: {
					corner:
					{
						target: 'centerRight',
					 	tooltip: 'centerLeft'
					},
					adjust: { screen: true } 
				},
				show: { when: { event: 'click' } },
				hide: { when: { event: 'unfocus' } },
				api: {
					onContentLoad: function() { this.updateWidth(); }
				}
			});
		});
		
		
		// Prepare Variables
		var
			/* Application Specific Variables */
			contentSelector = '#main_product',
			gallerySelector = '#gallery #scroll-container',
			galleryPaginationSelector = '#gallery #nav-below'
			$content = $(contentSelector).filter(':first'),
			contentNode = $content.get(0),
			$gallery = $(gallerySelector).filter(':first'),
			$galleryPagination = $(galleryPaginationSelector).filter(':first'),
			activeClass = 'active selected current youarehere',
			activeSelector = '.active,.selected,.current,.youarehere',
			galleryChildrenSelector = '> li,> ul > li',
			/* 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 || (/[^\:]/).test(url);
			
			// 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)/gi,'<div class="document-$1"')
				.replace(/<\/(html|head|body|title|meta|script)/gi,'</div')
			;
			
			// Return
			return result;
		};
		
		// Ajaxify Helper
		$.fn.ajaxify = function(){
			// Prepare
			var $this = $(this);
			// Ajaxify if it's not the top-level nav
			$this.find('a:internal:not(".level-1>a"):not(".product_link")').click(function(event){
					// Prepare
					var
						$this = $(this),
						url = $this.attr('href'),
						title = $this.attr('title')||null;
					// 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;
			});
			$('body').top_level_nav();
			$('body').iefix();
			// Chain
			return $this;
		};
		
		// url obfuscation helper
		$.fn.nospam = function(){
			$('del').each(function(i){
			    var protected_email = $(this).html();
			    protected_email = protected_email.replace(" [at] ","@");
			    protected_email = protected_email.replace(" [dot] ",".");

				var subject = $(this).attr('title');
				var link_text =  protected_email;

				href = '<a href="mailto:'+protected_email+'?subject='+subject+'">'+link_text+'</a>';
				$(this).replaceWith(href);
			});
		}

		// disable top-level nav helper
		$.fn.top_level_nav = function(){
			$('.level-1>a').live('click',function(e){e.preventDefault();});
		}
		// ie fixer helper
		$.fn.iefix = function(){
			if(ie7)
			{
				$('#product_info').prepend('<span class="ie7_shim"></span>').children('.centering_shim').wrap('<span class="ie_centering_shim"></span>');
			}
		}
		
		
		$body.nospam();
		
		// Ajaxify our Internal Links
		$('#content.products #nav-below').ajaxify();
		
		// Hook into State Changes
		$(window).bind('statechange',function(){
			// Prepare Variables
			var
				State = History.getState(),
				url = State.url,
				title = State.title,
				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.animate({opacity:0},800);
			
			// Ajax Request the Traditional Page
			$.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'),
						$datagallery = $dataBody.find(gallerySelector).filter(':first'),
						$datagallerypagination = $dataBody.find(galleryPaginationSelector).filter(':first'),
						$galleryChildren, contentHtml, $scripts;
					
					// Fetch the scripts
					$scripts = $dataContent.find('.document-script').detach();

					// Fetch the content
					contentHtml = $dataContent.html()||$data.html();
					if ( !contentHtml ) {
						document.location.href = url;
						return false;
					}
					$newgallery = $datagallery.children('ul');

					galleryPaginationHtml = $datagallerypagination.html();
			//		alert($datagallery.html());
					
					// Update the gallery
					if(title.indexOf('Permalink')<0)
					{
						$galleryPagination.html(galleryPaginationHtml).ajaxify();
						$galleryChildren = $gallery.find(galleryChildrenSelector);
						$galleryChildren.filter(activeSelector).removeClass(activeClass);
						$galleryChildren = $galleryChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
						if ( $galleryChildren.length === 1 ) { $galleryChildren.addClass(activeClass); }
						if(title.indexOf('Next')<0)
						{
							$gallery.append($newgallery.css({left:'246px'}).ajaxify()).children('ul')
							.animate(
								{left:'-=246px'},
								{
									complete: function()
									{
										$newgallery.siblings().remove();
									}
								});
							
						}
						else
						{
							$gallery.prepend($newgallery.css({left:'-246px'}).ajaxify()).children('ul')
							.animate(
								{left:'+=246px'},
								{
									complete: function()
									{
										$newgallery.siblings().remove();
									}
								});
						}
					}
					// Update the content
				//	$content.stop(true,true);
					if(title.indexOf('Permalink')>=0)
					{
						$content.html(contentHtml).ajaxify().css('opacity',100).fadeIn('fast',function()
						{
							// Add the scripts
							$scripts.each(function(){
								var $script = $(this), scriptText = $script.html(), scriptNode = document.createElement('script');
								if(scriptText != '')
								{
									scriptNode.appendChild(document.createTextNode(scriptText));
									contentNode.appendChild(scriptNode);
								}
							});
						}); /* you could fade in here if you'd like */
					}
					

					// Complete the change
					if ( $body.ScrollTo||false ) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
					$body.removeClass('loading');
	
					// Inform Google Analytics of the change
					if ( typeof window.pageTracker !== 'undefined' ) {
						window.pageTracker._trackPageview(relativeUrl);
					}
					$('body').nospam();
					$('body').iefix();
				},
				error: function(jqXHR, textStatus, errorThrown){
					document.location.href = url;
					return false;
				}
			}); // end ajax

		}); // end onStateChange	
		
	}); // end onDomLoad

})(window); // end closure
