/* Code to trigger when page is done loading */
$(window).load(function(){
	// Header Nav JS
	headerNav();
	function headerNav(){
		
		// (Efficiently) Chain together top nav hover/click functionality
		$("#nav").delegate("a", "mouseenter", function(){
			movePos($(this)); // move bg box
		})
		.delegate("a", "mouseleave", function(){
			$(this).animate({color:"#666A64"}); // restore color
		})
		.mouseleave(function(){
			movePos($("#nav .focus")); // restore bg box position
		})
		.delegate("a", "click", function(){
		
			// Keep track of current nav w/ class focus
			$(this).siblings().removeClass("focus");
			$(this).addClass("focus");
			
			// And reveal the appropriate content block
			var alsoFocus = $(this).attr("id");
			alsoFocus = "#" + alsoFocus.replace("Nav", "Holder");
			$(alsoFocus).animate({opacity:1, top:"0"}, {easing:"easeOutExpo", duration:1000})
			.siblings().animate({opacity:0, top:"-600px"}, {easing:"easeOutExpo", duration:1000});
			
			// If you didn't click #workNav...
			if ($(this).attr("id") != "workNav"){
				
				// #workNav's subnav must be hidden
				var $workSub = $("#header .bg.bottom");
				$workSub.removeClass("workSub").animate({
					top: "163px",
					height: "15px"
				}).find("#projectNav").fadeOut();
				
				// Load scribd resume pdf
				if ($(this).attr("id") == "resumeNav"){
					$('#resumeHolder').load('scribd.html');
				}
				// If map hasn't been loaded, load it
				else if (!$("#map").html().length > 0) {
					$('#map').append('<iframe src="map.html" scrolling="no" frameborder="0" style="width:600px; height:400px; border:none;" />');
				}
			}
			// #workNav has a subnav that must be shown
			else {

				function showWorkNav(){
					// Expand and show list of projects
					var $workSub = $("#header .bg.bottom");
					if (!$workSub.hasClass("workSub")){
						$workSub.addClass("workSub").animate({
							top: "151px",
							height: "39px"
						}).find("#projectNav").fadeIn();
					}
				}
				
				// If we haven't yet, load projects nav list
				// (Load via js in case we want to feature something else on the homepage)
				$projectList = $("#projectList");
				var i = 0;
				var initProject;
				if ($projectList.hasClass("unset")){

					$.ajax({
					  url: 'http://brettbarros.com/wordpress/?post_type=projects&json=get_recent_posts&count=20&include=id,title,categories,tags',
					  cache: false,
					  dataType: 'json',
					  success: function(data) {		
						var posts = data.posts;
						// For each post...
						$.each(posts, function(i, post){
							
							// Merge categories into a string
							var cats = '';
							$.each(post.categories, function(i, category){
								cats = cats + " " + category.title;
							});
							
							$projectList.append("<a href='"+post.id+"' class='project "+cats+"' rel='"+post.tags[0].title+"' id='project"+post.id+"' />");
							if (i == 0)
								$("#project"+post.id).click();
							});
						$projectList.removeClass("unset"); //.after("#lArrow")
						showWorkNav();
						i++;
					  }
					});
				}
				else
					showWorkNav();
				


			}
			return false;
		});		
		
		// Initialization
		movePos($("#workNav"));
		$("#workNav").addClass("focus")
		.click(); // We load on homepage by default now		
		
		// Tagline nav hovers/clicks
		
		function catColor($cat){
			$("#projectList a").removeClass("highlight unhighlight");
			var cat = $cat.text();
			$("#projectList").find("a").each(function(){
				$this = $(this); // efficiency var
				if ($this.hasClass(cat)){				
					var colorTo = $this.attr("rel");
					$this.addClass("highlight").stop().animate({
						borderTopColor:colorTo, 
						borderRightColor:colorTo, 
						borderBottomColor:colorTo,
						borderLeftColor:colorTo																	  
					}, {queue:false});													  
				}
				else {
					$this.addClass("unhighlight");
					if (!$this.hasClass("viewing")){
						var colorTo = "#444444";
						$this.stop().animate({
							borderTopColor:colorTo, 
							borderRightColor:colorTo, 
							borderBottomColor:colorTo,
							borderLeftColor:colorTo																	  
						}, {queue:false});								
					}
				}
			});
		}
		
		$("#tagline").delegate("a", "mouseenter", function(){
			catColor($(this));
		}).delegate("a", "mouseleave", function(){
			// If this isn't the clicked one...
			if (!$(this).hasClass("clicked")){
				
				// If there is a clicked one...
				if ($(this).siblings(".clicked").length > 0){
					catColor($(this).siblings(".clicked"));
				}
				
				// If there isn't a clicked one...
				else {
					$("#projectList").find("a").each(function(){
						$(this).removeClass("highlight unhighlight");
						if (!$(this).hasClass("viewing"))
							workOff($(this));
					});
				}
			}
		}).delegate("a", "click", function(){
			
			// Switch to projects view
			if (!$("#workNav").hasClass("focus")){
				movePos($("#workNav"));
				$("#workNav").click();
			}
			
			// Do stuff if it's already clicked?
			if ($(this).hasClass("clicked")){
				$("#projectList").removeClass("highlit");
			}
			// Set the click
			else {
				$(this).siblings(".clicked").removeClass("clicked");
				$("#projectList").addClass("highlit");
				$("#projectList a.highlight:first:not(.viewing)").click();
			}
			
			// Toggle clicked state
			$(this).toggleClass("clicked");
			return false;
		});
				
	}

	// Work Subnav JS
	function workOn($this){
		var colorTo = $this.attr("rel");
		var bRadius = "10px";
		$this.css({
			borderTopColor:colorTo, 
			borderRightColor:colorTo, 
			borderBottomColor:colorTo,
			borderLeftColor:colorTo
		}).animate({
			backgroundColor:colorTo,
			WebkitBorderTopLeftRadius: bRadius, 
			WebkitBorderTopRightRadius: bRadius, 
			WebkitBorderBottomLeftRadius: bRadius, 
			WebkitBorderBottomRightRadius: bRadius, 
			MozBorderRadius: bRadius, 
			BorderRadius: bRadius
		}, {duration: 200, queue:false});		
	}
	function workOff($this){
		var origColor;
		if ($this.hasClass("highlight")){
			origColor = $this.attr("rel");
		}
		else if ($this.hasClass("unhighlight")){
			origColor = "#444444";
		}
		else {
			origColor = "#AAAAAA";
		}
		$this.stop(true, false).animate({
			backgroundColor:"#000000",
			borderTopColor:origColor, 
			borderRightColor:origColor, 
			borderBottomColor:origColor, 
			borderLeftColor:origColor,
			WebkitBorderTopLeftRadius: 0, 
			WebkitBorderTopRightRadius: 0, 
			WebkitBorderBottomLeftRadius: 0, 
			WebkitBorderBottomRightRadius: 0, 
			MozBorderRadius: 0, 
			BorderRadius: 0
		}, {duration: 200, queue:false});		
	}
	function loadProject(id, isBackward){
		// alert ('hi a');
		// fixes an ie6/7 bug:
		id = id.replace("http://brettbarros.com/", "");
		// alert(id);
		$.ajax({
		  url: 'http://brettbarros.com/wordpress/?post_type=projects&json=get_post&include=title,content,attachments,custom_fields&custom_fields=projectLink,linkType&post_id='+id,
		  cache: false,
		  dataType: 'json',
		  success: function(data) {
				
			// Store the image var
			var imgURL;
			if (data.post.attachments[0]){
				imgURL = data.post.attachments[0].url;
				
			}

			// Setup direction flow forward:
			var dirOne = "-200%";
			var dirTwo = "200%";
			if (isBackward){
				dirOne = "200%";
				dirTwo = "-200%";
			}

			  var img = new Image();
			  
			  // wrap our new image in jQuery, then:
			  
			  $("#mainContainer").animate({marginLeft:dirOne}, {easing:"easeInExpo", duration:600, complete:function(){
				  $(img)
					// once the image has loaded, execute this code
					.load(function () {
						
						if (data.post.custom_fields.projectLink){
							
							linkUrl = data.post.custom_fields.projectLink;
							$overlay = $("#linkOverlay");
							$overlay.unbind().removeClass("dontClick").attr("href", linkUrl).fancybox({
								'width'				: '97%',
								'height'			: '95%',
								'titleShow'			: false,
								'autoScale'			: false,
								'type'				: 'iframe'
							});					
							
							if (data.post.custom_fields.linkType == "Video"){
								$("#imgOverlay").attr("src", "http://brettbarros.com/img/play-overlay.png");
							}
							else {			
								$("#imgOverlay").attr("src", "http://brettbarros.com/img/link-overlay.png");
							}
						}
						else {
							$("#imgOverlay").attr("src", "img/trans.gif");
							$overlay.unbind().addClass("dontClick").attr("href", "#")
							.click(function(){return false});
						}
						
						$("#featuredImage").attr("src", imgURL);
						$("#main .rightCol .theTitle").html(data.post.title);
						$("#main .rightCol .theContent").html(data.post.content);
						$('.scroll').jScrollPane({showArrows:true});		
						$("#mainContainer").css({marginRight:"0", marginLeft:dirTwo})
						.animate({marginLeft:"0"}, {easing:"easeOutExpo", duration:600, complete:function(){				
							$('.scroll').jScrollPane({showArrows:true});
						  }
						});							
					})
					
					// if there was an error loading the image, react accordingly
					.error(function () {
					  // notify the user that the image could not be loaded
					})
					
					// *finally*, set the src attribute of the new image to our image
					.attr('src', imgURL);
				}
			  });
		  }
		});
	}
	
	$("#projectList").delegate("a", "mouseenter", function(){
		workOn($(this));
	});
	$("#projectList").delegate("a:not(.viewing)", "mouseleave", function(){
		workOff($(this));
	});
	
	/* prev/next arrow hover and click */
	$("#projectNav").delegate(".arrow", "mouseenter", function(){
		$(this).find("img").animate({opacity:0}, {queue:false});	
	})
	.delegate(".arrow", "mouseleave", function(){
		$(this).find("img").animate({opacity:1}, {queue:false});	
	})
	.delegate(".arrow", "click", function(){
		var $old = $("#projectList .viewing");
		var $new;
		var selector = '';
		
		if ($("#projectList").hasClass("highlit"))
			selector = '.highlight'
		
		if ($(this).attr("id") == "rArrow"){
			$new = $old.nextAll(selector+":first");			
			if($new.length == 0)
				$new = $old.siblings(selector+":first");
		}
		else {			
			$new = $old.prevAll(selector+":first");	
			if($new.length == 0)
				$new = $old.siblings(selector+":last");
		}
		
		
		clickSubnav($new);
		return false;
	});

	function clickSubnav($this){

		// Are we moving forward in the list?
		var isBackward = $this.nextAll(".viewing").length;
		
		
		// Switch viewing class to new selection
		var $unset = $this.parent().find(".viewing");
		$unset.removeClass("viewing");
		$this.addClass("viewing");
		
		// Animate new selection on
		workOn($this);
		
		// Animate the previous selection off
		workOff($unset);
		
		// Load the project into the main div
		loadProject($this.attr("href"), isBackward);
			
	}

	// Work Subnav clicking
	$("#projectList").delegate("a", "click", function(){
		clickSubnav($(this));
		return false;	
	});

	// Other JS
	nonNav();
	function nonNav(){			
		// Logo Hover Glamour 
		$("#logo").hover(function(){
			$('#logo').animate({backgroundPosition: '-200px -30px'}, {easing:"easeOutExpo", duration:2000, queue:false});
		},
		function(){
			$('#logo').animate({backgroundPosition: '0 0'}, {easing:"easeOutExpo", duration:2000, queue:false});
		})
		.click(function(){
			$("#workNav").click();
			movePos($("#workNav"));
		});
		
	}
	
	/* Content */
	$("#main").delegate(".boxShadow", "mouseenter", function(){
		$("#imgOverlay").fadeIn();	
	})
	.delegate(".boxShadow", "mouseleave", function(){
		$("#imgOverlay").fadeOut();			
	})
	.delegate(".boxShadow", "click", function(){
		
		// I haaaaaaaaate ie6, so I hope this makes you smile.
		if($.browser.msie && parseFloat($.browser.version) < 7){
			$(this).find("a").click();
			return;
		} 
	});

	// Get the bg box position for the top nav
	function getPos($this){
		var pos = $this.position().left;
		pos = pos + 32;
		pos = pos + "px";
		return pos;
	}
	// Set the bg box position, coloring & text placement
	function movePos($this){
			$("#bgBox").attr("title", $this.attr("id")).animate({left: getPos($this)}, {easing:"easeOutExpo", duration:1000, queue:false});
			$this.find("span").animate({color:"#ffffff", top:"104px"}, {easing:"easeOutExpo", duration:1000, queue:false});
			$this.siblings().find("span").stop(true, false).animate({color:"#666A64", top:"6px"}, {easing:"easeOutExpo", duration:1000});
	}


});
