
(function ($) {
	


	function balanceNavArrows () {
		var navLinks = $('#primary-nav a');
		var seenCurrent = false;
		navLinks.each(function (idx, link) {
			var me = $(link);
			if (me.hasClass('current')) {
				seenCurrent = true;
				return;
			}
			if (seenCurrent) {
				me.removeClass('up');
				me.addClass('down');
			} else {
				me.removeClass('down');
				me.addClass('up');
			}
		});
	}

	var links = null;
	function updateProcessSubNav () {
		if (links == null) links = $('.subnav a');
		var seenCurrent = false;
		links.each(function (idx, elem) {
			var link = $(this);
			var target = $(link.attr('href'));
			if (!seenCurrent && target.offset().left > 0) {
				link.addClass('current');
				$('#position').text((idx + 1) + '/4');
				seenCurrent = true;
			} else {
				link.removeClass('current');
			}
		});
	}
	


	function lazyLoadImage (_idx, img) {
		img = $(img);
		img.wrap('<div style="position: relative"></div>');
		var placeholder = $('<div class="placeholder"></div>');
		placeholder.css({width: img.width() || "100%", left: img.css('margin-left') || 0});
		img.parent().append(placeholder);
		var url = img.attr('src');
		// img.attr('src', "images/boom.png");
		var newImage = new Image();
		newImage.onload = function (e) {
			img.parent().find('div.placeholder').fadeOut();
		};
		newImage.src = url;
	}

	function perPageBindings () {

		
		$('#content img').each(function () {
		    lazyLoadImage(this);	
		        
		});
		
		// "home" page bindings
		$('#home').each(function (idx, el) {
			
			$(function() {
				var targetgallery = jQuery('.phoenixgallery');
					targetgallery.css('opacity',0);
					
				initMediaGallery();

					function initMediaGallery(){
						targetgallery.phoenixgallery({
						nav_type:"none",
						nav_position:"down",
						transition_type:"fade",
						settings_slideshow:'on',
						thumb_width:65,
						thumb_height:40,
						thumb_space:9,
						nav_space:55,
						nav_arrow_size:40,
						settings_shadow:"off",
						settings_autoresize:"off",
						transition_strips_x:10,
						transition_strips_y:5,
						arrows_normal_alpha:0.6
						})
					}
			});


		});
					
		// "views" page bindings
		$('#views').each(function (idx, el) {
			$(function() {
				var targetgallery = jQuery('.phoenixgallery');
					targetgallery.css('opacity',0);
					
				initMediaGallery();

					function initMediaGallery(){
						targetgallery.phoenixgallery({
						nav_type:"thumbs",
						nav_position:"down",
						transition_type:"fade",
						thumb_width:65,
						thumb_height:40,
						thumb_space:9,
						nav_space:770,
						nav_arrow_size:35,
						settings_shadow:"off",
						settings_autoresize:"off",
						transition_strips_x:10,						
						transition_strips_y:5,
						arrows_normal_alpha:0.6
						})
					}
			});


		});
					
		// "work" page bindings
		$('#work').each(function () {

			$(function() {
				var targetgallery = jQuery('.phoenixgallery');
					targetgallery.css('opacity',0);
					
				initMediaGallery();

					function initMediaGallery(){
						targetgallery.phoenixgallery({
						nav_type:"thumbs",
						nav_position:"down",
						transition_type:"fade",
						thumb_width:65,
						thumb_height:40,
						thumb_space:9,
						nav_space:770,
						nav_arrow_size:35,
						settings_shadow:"off",
						settings_autoresize:"off",
						transition_strips_x:10,						
						transition_strips_y:5,
						arrows_normal_alpha:0.6
						})
					}
			});
		});
		
		

	}
	



	IMAGES_TO_PRELOAD = [
		"/images/front/front_slide_01.jpg",
		"/images/front/front_slide_02.jpg",
		"/images/front/front_slide_04.jpg",
		"/images/feat/cox.gif",
		"/images/feat/momentum.gif",
		"/images/feat/redhawk.gif",
		"/images/feat/sonic.gif"
		

	];
	IMAGES_DICT = {
		'': [
			"/images/ghost.gif",
			"/images/main_arrow_left.png",
			"/images/main_arrow_left.png",
			"/images/spinner.gif"
		],
		'/pages/home': [
			"/images/ghost.gif",
			"/images/main_arrow_left.png",
			"/images/main_arrow_left.png",
			"/images/spinner.gif"

		]
	}; 
	
	var key = window.location.hash.replace(/#!/, '');
    var PRELOAD_IMAGES = (key in IMAGES_DICT) 
                            ? IMAGES_DICT[key].concat(IMAGES_TO_PRELOAD)
                            : IMAGES_TO_PRELOAD;
	
	var idx;
	var images = [];
	for (idx=0; idx < PRELOAD_IMAGES.length; idx++) {
		var img = new Image();
		img.src = PRELOAD_IMAGES[idx];
		images.push(img);
	}


	$(function () {
	
		
		// START PAGE TRANSITION CODE
		var PAGE_TRANSITION_SPEED = 600;
		var viewport = $('#viewport');
				
				
		function callCallback(callbacks, name, self, args) {
		    if (callbacks[name]) callbacks[name].apply(self, args);
		    
		}
		
        function slideOutOldPage(content, direction, callbacks) { 
            var contentHeight = Math.max(content.height(), 
                                         new Number(content.attr('data-fallback-height') 
                                                    || 0));
        	var targetHeight = Math.max(contentHeight, $(window).height());
        	viewport.height(targetHeight);

        	content.css({position: 'relative', height: contentHeight});
        	var targetTop;
        	if ('down' == direction) {
        		targetTop = 0 - contentHeight;
        	} else {
        		targetTop = targetHeight;
        	}
        	content.animate({top: targetTop}, PAGE_TRANSITION_SPEED, function () {
        		$(this).hide().remove();
        		
        		callCallback(callbacks,"oncomplete", null, []);
        	});
        }


        
        function whenContentHasLoaded(newContent, callback) {
        	
            // delay calculating metrics till the page has properly loaded/rendered.
            var images = newContent.find("img");
            var remaining = images.length;
            
            if (remaining <= 0) return callback();
            
            function complete () {
                if (--remaining > 0) return;
                
                setTimeout( callback, 0);
            }
            images.load(complete);
        }
        
            
        function resizeViewport(newContent) {
            whenContentHasLoaded(newContent, function () {
                var newHeight = ($("#content").height());
                viewport.animate({height: newHeight});
            });
        }
        
        function setPageMeta (content) {
			// set up title and meta description (meta is probably useless here)
			var newTitle = content.find('#title').text();
			var newDescription = content.find('#meta-description').attr('content');
			var newKeywords = content.find('#meta-keywords').attr('content');
			$('head meta[name=description]').attr('content', newDescription);
			$('head meta[name=keywords]').attr('content', newKeywords);
            document.title = newTitle;
        }
     
       	

        function slideInNewMajorPage(text, direction, animationTime) {
            
			viewport.html('');
            
            var newHTML = $(text);
			var newContent = newHTML.find('#content')
			    .hide()
			    .css({position: 'relative', visibility: 'hidden'})
			    .show();
			viewport.append(newContent);
			var newHeight = newContent.attr('data-fallback-height')
			                ? new Number(newContent.attr('data-fallback-height')) 
			                : newContent.height();

			if ('down' == direction) {
				newContent.css({top: viewport.height()});
			} else {
				newContent.css({top: - newHeight});
			}
			newContent.css({visibility: 'visible'}).animate({top: 0}, animationTime, function () {
				// $('body,html').animate({scrollTop: 0}, animationTime);
			});

            // if 
			if (newContent.attr('data-fallback-height')) {
			    viewport.animate({height: newHeight});
			}
			else {
			    resizeViewport(newContent);
			}


			
            setPageMeta(newHTML);
           	perPageBindings();

        } 

       
        function onLinkClicked (e) {
			var me = $(this);
            
            if (!me.attr("href")) return;
                        
            if ( !!me.attr("href").match(/^[a-z]+:/) 
              || !me.attr("href").match(/#!/)
              || me.parent().hasClass("social")) return;

            e.preventDefault();
            e.stopImmediatePropagation();
            e.stopPropagation();

			var url = me.attr('href').replace(/#!/, '');
			
			// indirect page loading via the hash poll
			window.location.hash = me.attr('href');
			//return loadResource(url);
        }
        
        function loadResource(url, options) {
            options = options || { force: false };
            
            var me = $('a[href=#!'+url+']');
            
            var hash = (window.location.hash || "").match(/#!?(.*)/);
            if (hash) hash = hash[1] // thanks IE;
            
			/*if ( !options.force && url == hash) {
			    return;
			}*/
			
			$('a').removeClass('current');
			me.addClass('current');

			var animationTime = $('#content').hasClass('page-not-loaded')
				? 0
				: PAGE_TRANSITION_SPEED;

		
			var direction = me.hasClass('up') ? 'up' : 'down';
			var content = $('#content');

			// START LOADING THE NEW PAGE
			var exitFinished = false;

			var loadingBlogPage = !!url.match(/^\/blog\//);
			if (loadingBlogPage) $("#blog-link").addClass("current");

			$.ajax({
				url: url + '?v1',
				
				// cache: false,
				dataType: 'html',
				success: function (text, status, request) {

					function insertNewPage () {
						// DON'T SLIDE IN THE NEW PAGE UNTIL THE OLD PAGE HAS GONE
						if (!exitFinished) {
							return window.setTimeout(insertNewPage, 10);
						}

						// SLIDE IN THE NEW PAGE
						var pageTransition = slideInNewMajorPage;
						
						if (loadingBlogPage) {
						    pageTransition = slideInNewBlogPage;
						}
						
						pageTransition(text, direction, animationTime);
					}
					insertNewPage();
				},
				error: function () {
				    
				}
			});

			// SLIDE OUT THE OLD PAGE
			var pageOutTransition = slideOutOldPage;
			if (loadingBlogPage && $("#blog").length > 0) {
			    pageOutTransition = slideOutBlogPage;
			}
			
    		pageOutTransition(content, direction, { oncomplete: function () { 
    		    exitFinished = true; }
    		});

			balanceNavArrows();
			// if ("home-link" != me.attr('id')) {
		    	window.location.hash = '!' + url;
			// } else {
			// 	window.location.hash = '!';
			// }
		}
				
				
		$('nav a').click(onLinkClicked);
		
		viewport.height($(window).height());

		if (window.location.hash && window.location.hash != '#') {
			var url = window.location.hash.match(/#!?(.*)/)[1];
			//$('nav a[href=#!'+url+']').click();
			loadResource(url, {force:true});
		} else {
			loadResource($('#home-link')
			                .attr("href")
			                .match(/#!?(.*)/)[1], {force:true});
		}
		
		// we poll the hash to make sure all browsers support the back button.
		//
		// horrific.
		var oldHash = window.location.hash;
		setInterval(function () {
		
            var hash = window.location.hash || "#!/pages/home";
		    
		    if (hash == oldHash) return;

		    var url = hash.match(/#!?(.*)$/);
		    if (url) loadResource(url[1]);
		    oldHash = hash;
		    
		}, 250);
		
		// END PAGE TRANSITION CODE
	});
	


	})(jQuery);
	
	
	
