
/* RUN IMMEDIATELY ------------------------------------------------------- */

// Preload CSS image assets
cssImages = [
	'background_000000_90.png',
	'background_1A1A1A_90.png',
	'checkbox.png',
	'globalnav_background_ie.png',
	'globalnav_background.png',
	'loader.gif',
	'nav_arrow_active.png',
	'nav_arrow_down.png',
	'nav_arrow.png',
	'nav_breadcrumb_background.png',
	'nav_down_arrow.png',
	'nav_up_arrow.png',
	'search.png',
	'splash_screen.png',
	'x.gif'
];

/* RUN WHEN DOM IS LOADED ------------------------------------------------ */

jQuery(function($) {
	// Add hashed path for AJAXification
	if (location.pathname != '/') {
		window.location = location.protocol + '//' + location.host + '/#' + location.pathname + (location.hash ? location.hash : '');
	}
	
	// Remove trailing slashes
	if (location.hash && location.href.substr(location.href.length-1) == '/') {
		window.location = location.href.substr(0, location.href.length-1);
	}
	
	// Set custom variables
	custom.title = document.title;
	custom.breadcrumb = $('#breadcrumb .text').html();
	custom.domain = location.protocol + '//' + location.host;
	custom.url = location.pathname;
	custom.search = location.search.substr(1);
	custom.hash = location.hash;
	custom.referrer = '/';
	custom.subnav = '';
	
	// Initialize AJAXed history
	$.history.init(custom.ajaxNav);
	
	// Featured Projects
	custom.featuredProjects();
	
	// Google analytics
	if (typeof pageTracker == "function") pageTracker._trackPageview(custom.url);
	
	$(':not(iframe) a').live('click', function(e) {
		
		// Strip out domain from url if present
		href = $(this).attr('href');
		// And again for IE :P
		if (href.indexOf(custom.domain) == 0) {
			href = href.substr(custom.domain.length);
		}
		
		// Check whether loading print page or not
		if (href.indexOf('format=print') > -1) {
		
		}
		// Link to actual file
		else if (href.indexOf('.') > -1) {
			$(this).attr('target', '_blank');
			if (typeof pageTracker == "function") pageTracker._trackPageview(href);
		}
		// Load content
		else if (href.indexOf('/') == 0) {
			custom.addHistory(href);
			return false;
		}
		// Valid hash
		else if (href.indexOf('#') == 0) {
			return false;
		}
		
	});
	
	// Setup globalnav
	custom.globalnav();
	if (custom.url = '/') custom.globalnav.init();
	
	// Run on window load
	$(window).load(function() {
		// Splash screen
		$('#splash').delay(2000, function() {
			$('#splash').fadeOut(400);
		});
	});
	
});

custom = new Object;

custom.addHistory = function(url)
{
	url = url ? url : '';
	$.history.load(url);
	if (typeof pageTracker == "function") pageTracker._trackPageview(url);
};

/* GLOBAL NAVIGATION INTERACTION ----------------------------------------- */

custom.ajaxNav = function(url)
{
	url = url.replace(/'/g,'').replace(/"/g,'').replace(/>/g,'').replace(/</g,'');
	// Parse out page vs. toggle section requests
	if (match = url.match(/^([a-z0-9_\/-]+)(\#|\%23)([a-z0-9_-]+)(\/[a-z0-9_\/-]+)?$/i)) {
		url    = match[1] ? match[1] : '/';
		if (search = url.match(/(\?[a-z0-9_-]+)$/i)) {
			search = search[1].substr(1);
		} else {
			search = '';
		}
		hash   = match[3] ? match[3] : '';
		subnav = match[4] ? match[4].substr(1) : '';
	} else { 
		url    = url ? url : '/';
		if (args = url.match(/([a-z0-9_\/-]+)(\?.*)$/i)) {
			search = args[2].substr(1);
		} else {
			search = '';
		}
		hash   = '';
		subnav = '';
	}
	// Load new page
	if (url != custom.url || url == '/') {
		custom.url = url;
		
		// Show progress indicator
		$('#progress').show();
		$('#nav.open').removeClass('open');
		
		// Update wayfinding
		$('#globalnav a.selected:not([href="'+ url +'"])').removeClass('selected');
		// Find direct match
		if ($('#globalnav a[href="'+ url +'"]')[0]) {
			$('#globalnav a[href="'+ url +'"]').addClass('selected').parents('li').addClass('active');
		}
		// Otherwise, if detail page not directly in Main Menu, find an available parent
		else {
			url_path = url.substr(1,url.length - search.length - 2).split('/');
			path = '';
			for (i=0,ln=url_path.length;i<ln;i++) {
				path += '/' + url_path[i];
				$('#globalnav a[href="'+ path +'"]').addClass('selected').parents('li').addClass('active');
			}
		}
		
		// Reset menu
		$('#nav .text').animate({
			paddingLeft: "8px"
		}, 200);
		$('#globalnav:visible, #breadcrumb .background:visible, #breadcrumb .arrow-down:visible').fadeOut(400);
		
		// Load new content
		$.getJSON(url, { format: 'json', referrer: custom.referrer }, function(response, textStatus) {
			custom.globalnav.init();
			if (response.status == 'success') {
				$('body').attr('id', response.controller + '_' + response.action);
				$('#view').html(response.content.main).each(function () {
					
					// Run module JS, if available
					$('.module').each(function () {
						if (type = $(this).eq(0).attr('class').match(/module_([a-z]+)/)) {
							var func = window["module_"+type[1]];
							if (typeof func === 'function'){
								var obj = new func($(this)[0]);
								//func.apply(func,[$(this)[0]]);
							}
						}
					});
					
					// Decrypt stuff
					var tA = $('#view a[class="em_encrypted_native"]');
					for(var i=0;i<tA.length;i++){
						var obj = tA[i];
						var encA = $(obj).attr('rev').split('_');
						var str = des(response.data._em_key,hexToString('0x' + encA[2]),0,1,hexToString('0x' + encA[3]),0).substring(0,Number(encA[1]));
						$(obj).attr('rev',str);
						if($(obj).attr('rel') == 'nofollow'){
							$(obj).html(str);
						}
						$(obj).bind('click', function () {
							window.location = 'mailto:' + $(this).attr('rev');
							return false;
						});
					}
					
					// Featured Projects
					custom.featuredProjects();
					
					// Prep toggle sections
					$('#sections .section .module').hide();
					$('#sections .section').hide().children('.col').hide();
					
					// Select localnav item
					if (hash) {
						$('#localnav a[href$="#'+ hash +'"]').addClass('selected');
						$('#sections #' + hash).show().children('.col:first').show().find('.module:hidden').show();
					} else {
						$('#localnav a:first').addClass('selected');
						$('#sections .section:first').show().children('.col:first').show().find('.module:hidden').show();
					}
					
					// Select subnav item
					if (subnav) {
						$('#sections #' + hash +' .module_subnav a[href$="'+ hash +'/'+ subnav +'"]').addClass('selected');
						//FIXME: for IE!
						$('#sections #' + hash +' .col').each(function(index){
							if(index){
								$(this).show(400, function(){
									$(this).find('#' + hash + '--' + subnav).slideDown(600);
								});
							}
						});
						
						/*
						$('#sections #' + hash +' .col:not(:first-child):hidden').show(400, function() {
							$(this).find('#' + hash + '--' + subnav).slideDown(600);
						});
						*/
					}
					
				// Init action items
				$('#actions .print').attr('target', '_blank');
					
				}).delay(500, function() {
					$('#progress:visible').fadeOut(400);
				});
				
				document.title = 'Cannon Design - ' + response.data.title;
				
			} else {
				// Display error
				alert(response.status.toUpperCase() + ': ' + response.message);
			}
		});
	}
	
	// Toggle section
	if (hash != custom.hash) {
		custom.hash = hash;
		
		// Prep toggle sections
		// $('#sections .section:visible').fadeOut(200).find('.col, .module').hide();
		if (hash) {
			$('#sections .section:not(#'+hash+')').fadeOut(200).find('.col, .module').hide();
		}
		
		// Select localnav item
		$('#localnav a.selected:not([href$="#'+ hash +'"])').removeClass('selected');
		
		if (hash) {
			$('#sections .section:not(#'+hash+')').fadeOut(200).find('> .col, > .module').hide();
			$('#sections:hidden').fadeIn(400);
			$('#localnav a[href$="#'+ hash +'"]').addClass('selected');
			$('#sections #' + hash +':hidden .col:first').show();
			$('#sections #' + hash +':hidden').show(400, function() {
				$(this).find('.col:first .module:hidden').slideDown(600);
			}).children('.col:first').show();
		} else {
			$('#sections .section').fadeOut(200).find('> .col, > .module').hide();
			$('#localnav a:first').addClass('selected');
			$('#sections .section:first:hidden .col:first').show();
			$('#sections .section:first:hidden').show(400, function() {
				$(this).find('.col:first .module:hidden').slideDown(600);
			});
		}
		
	}
	
	// Toggle subnav
	if (subnav != custom.subnav) {
		custom.subnav = subnav;
		
		// Prep toggle sections
		if (hash) {
			//FIXME: for IE!
			//$('#sections #' + hash +' .col:not(:first-child):visible').fadeOut(200).find('.module').hide(1);
			$('#sections #' + hash +' .col').each(function(index){
				if(index){
					$(this).fadeOut(200).find('.module').hide(1);
				}
			});
		}
		
		// Select localnav item
		$('#sections .module_subnav a').removeClass('selected');
		if (subnav) {
			$('#sections #' + hash +' .module_subnav a[href$="'+ hash +'/'+ subnav +'"]').addClass('selected');
			$('#sections #' + hash +' .col:not(:first)').show(400, function() {
				$(this).find('#' + hash + '--' + subnav).slideDown(600);
			});
		}
	}
	
	custom.referrer = url+(hash ? '#'+hash : '')+(subnav ? '/'+subnav : '');
	
};

custom.globalnav = function()
{
	// Init nav
	$('a.mainmenu').bind('click', function(event){
		event.stopImmediatePropagation();
		return false;
	});
	
	// Toggle globalnav
	$('#nav').hover(
		function () {
			$('html.ie6 #content, html.ie7 #content').css({zIndex: -1});
			$(this).addClass('hover');
			hoverOver = setTimeout(function () {
				$('#nav.hover #breadcrumb .background, #nav.hover #globalnav, $nav.hover #breadcrumb .arrow-down').fadeIn(200, function() {
					$('#nav').addClass('open');
				});
				$('#nav.hover .text').animate({ 
					paddingLeft: "16px"
				}, 100);
			}, 300);
		},
		function () {
			$(this).removeClass('hover');
			hoverOut = setTimeout(function () {
				$('#nav:not(.hover) #globalnav').fadeOut(400, function() {
					if ($('#nav.open')[0]) custom.globalnav.init();
					$('#nav.open').removeClass('open');
					$('html.ie6 #content, html.ie7 #content').css({zIndex: 0});
				});
				$('#nav:not(.hover) #breadcrumb .background, #nav:not(.hover) #breadcrumb .arrow-down').fadeOut(400);
				$('#nav:not(.hover) .text').animate({ 
					paddingLeft: "8px"
				}, 200);
			}, 300);
		}
	);
	
	// Toggle nav items
	$('#globalnav a, #globalnav span').mouseover(function () {
		$(this).parent().siblings().find('a').removeClass('active');
		$(this).parent().siblings().find('span').removeClass('active').animate({ 
			paddingRight: "12px"
		}, 100);
		if ($(this).next('ul')[0]) {
			$(this).addClass('active').animate({
				paddingRight: "15px"
			}, 100);
		}
		$(this).parent().siblings().find('ul').fadeOut(200);
		$(this).next('ul').fadeIn(200);
	});
	
};

custom.globalnav.init = function()
{
	// Clear all visuals
	$('#globalnav ul ul').hide();
	$('#globalnav span').removeClass('active').css({'padding-right':'12px'});
	
	// Update wayfinding
	$('#globalnav a.selected').parents('ul').show();
	var breadcrumb = [];
	$('#globalnav a.selected').parents('li').children('span').each(function() {
		$(this).addClass('active').css({'padding-right':'15px'});
		breadcrumb.push($(this).html());
	});
	breadcrumb.reverse();
	if (current = $('#globalnav a.selected').html()) {
		breadcrumb.push('<strong>' + current + '</strong>');
	} else {
		breadcrumb.push(custom.breadcrumb);
	}
	$('#breadcrumb .text').html(breadcrumb.join(' / '));
	
	// Fix IE6 breadcrumb background width issues. #FAIL
	$('html.ie6 #breadcrumb .background').css({width: $('#breadcrumb .text').width()+18 + 'px'});
	$('html.ie6 #wrapper').css({marginTop: (ieheight = $(window).height() - 630) > 0 ? ieheight/2 : 0 + 'px'});
};

custom.featuredProjects = function()
{
	$('#slideshow li:not(:first)').hide();
	if ($('#slideshow_controls')[0]) {
		
	} else if ($('#slideshow li')[1]) {
		
		if (window.autoSlideshow != undefined) window.clearInterval(autoSlideshow);
		
		imgUrl = $('#slideshow li').eq(1).attr('rel');
		image = $('<img />').attr('src', imgUrl);
		$('#slideshow li').eq(1).css('background-image', 'url('+imgUrl+')');
		
		if ($('html:not(.ie6)')[0] || $('html.ie6 body#index_index')[0]) autoSlideshow = window.setInterval(function () {
			$('#slideshow li:visible').fadeOut(1000, function() {
				$(this).clone().insertAfter('#slideshow li:last');
			}).next().fadeIn(1000, function() {
				$(this).prev().remove();
				imgUrl = $(this).next().attr('rel');
				image = $('<img />').attr('src', imgUrl);
				$(this).next().css('background-image', 'url('+imgUrl+')');
			});
		}, 10000);
		
	}
};

function navigateToUrl(url)
{
	//wrapper, because of External Interface limitation for targeting object reliably
	custom.addHistory(url);
}
