
var AAF = {
	
	History: null,
	$: null,
	categories: [],
	companies: [],
	slides: [],
	segments: [],
	currentCategory: null,
	
	init: function(){
		
		AAF.History = window.History;
		AAF.$ = window.jQuery;
		AAF.categories = CATEGORIES ? CATEGORIES : [];
		
		if (AAF.History.enabled)
			AAF.history();

		// Attach events to arrows
		$("#menu .arrow.down a").hover(
			function(){
				AAF.navScroll.down();	
			},
			function(){
				AAF.navScroll.stop();
			}
		);
			
		$("#menu .arrow.up a").hover(
			function(){
				AAF.navScroll.up();	
			},
			function(){
				AAF.navScroll.stop();
			}	
		);
			

		// Attach events to arrows
		$("#companies .arrow.down a").hover(
			function(){
				AAF.companyScroll.down();	
			},
			function(){
				AAF.companyScroll.stop();
			}	
		);
		$("#companies .arrow.up a").hover(
			function(){
				AAF.companyScroll.up();	
			},
			function(){
				AAF.companyScroll.stop();
			}	
		);
		
		// Preload IE category images
		if ( ! Modernizr.csstransforms) {
			for( var c in AAF.categories ) {
				$("<img>").attr("src", AAF.History.getRootUrl()+"media/images/categories/"+c+"_png8.png");
			}
		}

		
		AAF.resize();
		AAF.refresh(1000);

	},
	
	history: function() {
	
		var	rootUrl = AAF.History.getRootUrl();

		// Override a tags
		$("a.deep").live("click", function(event){
			
			// Continue as normal for cmd clicks etc
			if ( event.which == 2 || event.metaKey ) { return true; }
			
			// Ajaxify this link
			var $this = $(this), 
				url = $this.attr("href"), 
				title = titleCaps( $this.attr("title") ) + " | AAF Tucson" || null;
			AAF.History.pushState(null, title, url);
			event.preventDefault();

			return false;
		});
		
		// Initialize segments
		AAF.segments = AAF.History.getState().url.replace(rootUrl, "").split("/");
		
		// Bind Hashchange event
		$(window).bind("statechange", function(e) {
			
			var	State = AAF.History.getState(),
				url = State.url,
				relativeUrl = url.replace(rootUrl,""),
				segments = relativeUrl.split("/");
				
			// Routing
			if (segments.length < 3) {
			
				// Set default TODO: change
				segments = ["home", "category", "advertising"]; 	
			}

			// Open company
			if (segments[3]){
				
				// If the company has changed
				if (segments[3] != AAF.segments[3]) {
					AAF.loadSlides( segments[2], segments[3], segments[4] ); 
				} else if (segments[4] && segments[4] != AAF.segments[4]) {
					AAF.changeSlide( segments[4] );
				}

			// Load company list
			} else {
				AAF.loadCompanies( segments[2] );
				AAF.hideLogo();
			}
			
			// Inform Google Analytics of the change
			if ( typeof _gaq !== "undefined" && typeof _gaq._getAsyncTracker == "function" ) {
				var pageTracker = _gaq._getAsyncTracker();
				pageTracker._trackPageview(relativeUrl);
			}
			
			AAF.segments = segments;
		});		
	},
	
	resize: function() {

		$(window).resize(function(){
			
			var category = $("#category div");
			
			// Get height
			var H = $(window).height();
			
			$('#target1').animate({color: "white"}, 50, 'linear', function()
			{
				$('#target2').animate({color: "white"}, 50, 'linear', function()
				{
					$('#target3').animate({color: "white"}, 50, 'linear', function()
					{
						$('#target4').fadeOut('fast', function()
						{
							$('#preloader').css('display', 'none');
						});
					});
				});
			});
		
			
		
			// Set bounds
			if (H < 600) H = 600; // TODO Make this a constant
			
			// Set all .resizable to window height
			$(".resizable").height( H );
			
			// Resize menu width
			$("#menu nav").width( H -  120);
			
			// Move Menu Down Arrow
			$("#menu .arrow.down").css("marginTop", H - 140);
			
			// Resize company nav height
			$("#company_list nav").height( H -  120);			
			
			// Resize category 
			// Calculate scale values based on height and width
			category.css("transform", "scaleX(1) scaleY(1)");
			var scaleX = H / category.width();
			var scaleY = $("#category").width() / category.height() * (1 + 2/3);
			category.css("transform", "rotate(90deg) scaleX("+scaleX+") scaleY("+scaleY+")");
			category.css("marginLeft", $("#category").width() * 1.25 ); // 1.25 is a fudge factor
				
			category.fadeTo(300, 1);
			
			// Resize and display graphic for IE
			$(".no-csstransforms #category img").width(1);
			$(".no-csstransforms #category img").height(1);
			$(".no-csstransforms #category img").width( $("#category").width() );
			$(".no-csstransforms #category img").height( H );
			$(".no-csstransforms #category img").css("display","block");			
			//$(".no-csstransforms #category img").fadeTo(300, 1)
			
			// Add small version tags
			if ($(window).width() < 1200) {
				$("html").addClass("narrow");
			} else {
				$("html").removeClass("narrow");
			}
			
			if (H < 700) {
				$("html").addClass("short");
			} else {
				$("html").removeClass("short");
			}
			
			// Resize vertical elements
			if (H > 600) {				
				$(".resizableTopMargin").css("marginTop", H > 600+100 ? 60 : (H-600)/4+10);
			
			}
			
			/*
			// Resize text elements
			if ($(window).width() < 1012) {
				$("#join .about").css("font-size", "0.9em");				
			} else {
				$("#join .about").css("font-size", "1em");
			}
			
			
			// Hide news body when height shrinks
			if (H < 700) {
				$("#news article p:visible").hide();
			} else {
				$("#news article p:hidden").show();
			}
			*/
			
		});
		
		// Trigger resize
		AAF.refresh();
		AAF.refresh(100);
	},
	
	refresh: function( delay ){
		if (delay) {
			setTimeout(function(){$(window).resize();}, delay);
		} else {
		$(window).resize();			
		}
	},
	
	loadCompanies: function(category){
		
		// Close slide frame
		if ($("#frame").hasClass("slide_open")) {
			
			$("#companies").animate({"width" : "20%"}, 600);
			$("#category").animate({"width" : "20%"}, 600);
			$("#menu").animate({"width" : "20%"}, 600, function(){
				AAF.loadCompanies(category);
				
				// Empty slides section
				$("#slide_frame").empty();
			});
			
			// Remove slide_open class
			$("#frame").removeClass("slide_open");
			
			// Change category text
			if (AAF.companies[ category ]) {
				//$("#category div").text(AAF.categories[category].toUpperCase());
				//AAF.currentCategory = category;
				//AAF.refresh();
			}

		// Load companies
		} else {
			if (AAF.companies[ category ]) {
				// Set category text
				if (AAF.currentCategory != category)
				{
					if (Modernizr.csstransforms) {
						$("#category div").fadeTo(300, 0, function(){
							$("#category div").text(AAF.categories[category].toUpperCase());
							AAF.currentCategory = category;
						});
					} else {
						//$("#category img").fadeTo(300, 0, function(){
							$("#category img").attr("src", AAF.History.getRootUrl()+"media/images/categories/"+category+".png");
							AAF.currentCategory = category;
						//});
					}
					
					// Load companies
					if (Modernizr.csstransforms) {
						$("#company_list nav div").fadeTo(300, 0, function(){
							$("#company_list nav div span").html( AAF.companies[ category ]);
							AAF.companyScroll.top();
							
							$("#company_list nav div").fadeTo(300, 1);
							AAF.refresh();
							AAF.refresh(10);
						});
						
					} else {					
						$("#company_list nav div span").html( AAF.companies[ category ]);
						AAF.companyScroll.top();						
						AAF.refresh();
						AAF.refresh(10);
					}
				}
			} else {
				$.ajax({
					url: AAF.History.getRootUrl() + "home/companies/" + category,
					dataType: "json",
					success: function(resp) {
						if (resp.success) {													
							AAF.companies[ category ] = resp.data;
							AAF.loadCompanies( category );
						}
					}
				});
			}
		}
		
	},
	
	loadSlides: function(category, company, slide){

		slide = slide ? slide : 1;
		
		if (AAF.slides[category+company]) {
			
			// Load slides html
			if ($("#frame").hasClass("slide_open")) {
				$("#slide_frame").html( AAF.slides[category+company] ).fadeIn();
				
				AAF.changeSlide( slide );
			} else {
				
				// Animate slide opening
				$("#companies").animate({"width" : "53%"}, 600);
				$("#category").animate({"width" : "0%"}, 600);
				$("#menu").animate({"width" : "7%"}, 250, function(){
					AAF.loadSlides(category, company, slide);
				});
				
				// Add slide_open class
				$("#frame").addClass("slide_open");
			}
			
		} else {
			$.ajax({
				url: AAF.History.getRootUrl() + "home/slides/" + category + '/' + company + '/' + slide,
				dataType: "json",
				success: function(resp) {
					if (resp.success) {													
						AAF.slides[ category+company ] = resp.data;
						AAF.loadSlides( category, company, slide );
					}
				}
			});
		}
	},
	
	changeSlide: function( slide ){
		
		if ($("#slides .slide:nth-child("+slide+")").css("display") == "none") {
			$("#slides .slide:visible").fadeOut(300, function(){
				$("#slides .slide:nth-child("+slide+")").fadeIn(300);
			});
		}
		
		$("#slide_frame nav a.current").removeClass("current");
		$("#slide_frame nav a:nth-child("+slide+")").addClass("current");
	},
	
	navScroll : {
		
		initialVelocity: 1,
		velocity: 1,
		defaultFactor: 5000,
		speedTimer: null,
		
		down: function() {
			$("#menu nav div").stop(true);
			
			// Calculate duration
			var dest = $("#menu nav").width() - $("#menu nav div span").width();
			if($.browser.msie)
			{
				var dest = $("#menu nav").width() - $("#menu nav div span").width() + 668;
			}
			var dist = Math.abs( dest - parseInt($("#menu nav div").css("marginLeft")) );
			var dur   = (dist / $("#menu nav div span").width()) * (AAF.navScroll.defaultFactor * AAF.navScroll.velocity); // Factor in velocity value
			
			$("#menu nav div").animate({marginLeft: dest}, dur, "easeInCirc");
			
			AAF.navScroll.speedTimer = setTimeout(AAF.navScroll.speedUp, 1000);
		},
		
		up: function() {
			$("#menu nav div").stop(true);
			
			// Calculate duration
			var dest = 0;
			var dist  = Math.abs( dest - parseInt($("#menu nav div").css("marginLeft")) );
			var dur   = (dist / $("#menu nav div span").width()) * (AAF.navScroll.defaultFactor * AAF.navScroll.velocity);
			
			$("#menu nav div").animate({marginLeft: dest}, dur, "easeInCirc");
			
			AAF.navScroll.speedTimer = setTimeout(AAF.navScroll.speedUp, 1000);
		},
		
		stop: function() {
			$("#menu nav div").stop(true);
			AAF.navScroll.speedTimer = null;
			AAF.navScroll.velocity = AAF.navScroll.initialVelocity;
		},
		
		speedUp: function() {
			AAF.navScroll.velocity++;
			//AAF.navScroll.down();
			//AAF.navScroll.up();
		}
		
	},
	
	companyScroll : {
		
		initialVelocity: 1,
		velocity: 1,
		defaultFactor: 5000,
		
		down: function() {
			$("#company_list nav div").stop(true);
			
			// Calculate duration
			var dest = $("#company_list nav").height() - $("#company_list nav div span").height();
			var dist  = Math.abs( dest - parseInt($("#company_list nav div").css("marginTop")) );
			var dur   = dist / $("#company_list nav div span").height() * AAF.companyScroll.defaultFactor;
			
			$("#company_list nav div").animate({marginTop: dest}, dur, "easeInCirc");
		},
		
		up: function() {
			$("#company_list nav div").stop(true);
			
			// Calculate duration
			var dest = 0;
			var dist  = Math.abs( dest - parseInt($("#company_list nav div").css("marginTop")) );
			var dur   = dist / $("#company_list nav div span").height() * AAF.companyScroll.defaultFactor;
			
			$("#company_list nav div").animate({marginTop: dest}, dur, "easeInCirc");
		},
		
		stop: function() {
			$("#company_list nav div").stop(true);
			AAF.companyScroll.velocity = AAF.companyScroll.initialVelocity;
		},
		
		top: function() {
			$("#company_list nav div").css("marginTop", 0);
		}
		
	},
	
	expandLogo: function( link ) {
		
		var clone = $(link).find('img').clone();
		clone.css("position","absolute").prependTo("#companies").hide();
		clone.offset($(link).offset());
		clone.addClass("expandedLogo");
		clone.show();
		
		clone.animate(
			{
				top: 0
			}, 600, function() {
				$(this).css("left","");
			}
		)
	},
	
	hideLogo: function() {
		$(".expandedLogo").fadeOut("fast", function(){ $(this).remove(); })
	},
	
	toggleNews: function( classTag ) {
		$("#news .content article").hide();
		$("#news .content article."+classTag).show();
		$("#news .toggle .active").removeClass("active");
		$("#news .toggle ."+classTag).addClass("active");
	}
};

$(document).ready(function(){
	AAF.init();
});














