/* ##### Plugins ##### */
//Resets a form
$.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = -1;
  });
};

//Gets URL variables
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

/* ##### Namespace ##### */
ECC = {};

//Init!
ECC.init = function() {
	//Bind all links with the attribute "rel" set to "external" to open in a new window
	$("a[rel*='external']").live("click", function(e) {
		//Stop the link from firing
		e.preventDefault();
		
		//Find the link target & open it in a new window
		var href = $(this).attr("href");
		window.open(href);
	});
	
	//Reset any forms (so data doesn't persist)
	$("form#contactForm").clearForm();
	
	//Make textareas autogrow
	$('.autoGrow').elastic();
	
	//Activate the localScroll plugin
	$.localScroll();
}

//Flag a field as either valid or invalid
ECC.toggleFieldFlag = function (inputID, valid) {
	//Check to see if this field is required
	var isRequired = $("#" + inputID).hasClass("requiredField");
	var classToAdd = "";
	var message = "Thanks!";
	
	//Clear any validation message for this input
	$(".validationMessage[rel=" + inputID + "], .thanksMessage[rel=" + inputID + "]").remove();
		
	//Let's set the class we're going to add to the field (either valid or invalid
	if (valid) {
		var classToAdd = "valid";
	} else if (!valid & isRequired) {
		var classToAdd = "invalid";
	}
	
	//Clear any validation message for this input
	$(".validationMessage[rel=" + inputID + "]").remove();
	
	$("#" + inputID).removeClass("valid invalid")
					.addClass(classToAdd);
					
	if (!valid & isRequired) {
		//Figure out what message we're going to add
		switch (inputID) {
			case "firstName": {
				var message = "Please provide your first name.";
				break;
			}
			case "lastName": {
				var message = "Please provide your last name.";
				break;
			}
			case "email": {
				var message = "Please provide a valid email address.";
				break;
			}
			case "telephone": {
				var message = "Please provide your telephone number.";
				break;
			}
		}	
		//Add the validation message
		$("#" + inputID).before("<div class='validationMessage' rel=" + inputID + ">" + message + "</div>");
	} else if (valid) {
		//Add the thank you message
		$("#" + inputID).before("<div class='thanksMessage' rel=" + inputID + ">" + message + "</div>");
		$(".thanksMessage[rel=" + inputID + "]").delay(500).fadeOut("slow", function() {
			$(this).remove();
		});
	}
					
}

//The main function that will scroll to the project on the featured project page
ECC.scrollToWork = function (location, navArray) {
	//Find the viewports
	var thumbnailVP = $("#thumbnailViewport");
	var descriptionVP = $("#descriptionViewport");
	
	//Find the previous and next buttons
	var prevBtn = $("#workControls").find(".workPrev");
	var nextBtn = $("#workControls").find(".workNext");
	
	//Set the quote
	var clientQuote = "";
	
	switch (location) {
		case "met-coal": {
			clientQuote = "ARMOS Metallurgical Coal Project (Partner)<span class='author'><strong>Boyaca</strong>, <em>Colombia</em></span>";
		break;
		}
		case "iron-ore": {
			clientQuote = "ARMOS Iron Ore Project<span class='author'><strong>Northern Chile</strong>, <em>South America</em></span>";
		break;
		}
		case "thermal-coal": {
			clientQuote = "ARMOS Thermal Coal Project (Partner)<span class='author'><strong>Canning Basin</strong>, <em>Western Australia</em></span>";
		break;
		}
		case "mining-products": {
			clientQuote = "ARMOS Magnetite Projects (Partners)<span class='author'><strong>Various Sites</strong>, <em>United States and Queensland, Australia</em></span>";
		break;
		}
	}
	//Scroll the description
	descriptionVP.stop().animate({opacity: 0.25,filter: "alpha(opacity=25)"}, 200, function() {
		$(this).scrollTo("#" + location + "-description", 200).animate({opacity: 1,filter: "alpha(opacity=100)"}, 500);
	});
	
	// Now set the quote
	$("#thumbnailWrapper > p.quote").stop().animate({opacity: 0,filter: "alpha(opacity=0)"}, 200, function() {
		$(this).html(clientQuote);
		
	})
	
	//Scroll the thumbnails
	thumbnailVP.stop().animate({opacity: 0,filter: "alpha(opacity=0)"}, 200, function() {
		$(this).scrollTo("#" + location + "-thumbnail-1", 200).animate({opacity: 1,filter: "alpha(opacity=100)"}, 500);
		$("#thumbnailWrapper > p.quote").delay(200).animate({opacity: 1,filter: "alpha(opacity=100)"}, 500);
	});
	
	
	
	//First reset all buttons
	$("#workControls").find("li").removeClass("inactive");

	//Now figure out if we need to disable a button
	if ($.inArray(location, navArray) == 0) {
		ECC.disableWorkNavButton("prev");
	} else if ($.inArray(location, navArray) == navArray.length-1) {
		ECC.disableWorkNavButton("next");
	}
}

//This function will rebuild the thumbnail indicator dynamically
ECC.updateThumbIndicator = function (nextThumb) {
	//Clear the thumbnail indicator
	$(".thumbIndicator").html("");
	
	//Now loop through each thumbnail in this ul, and add it to the thumbnail indicator
	$("#" + nextThumb).closest(".clientThumbnails").find("li.featuredThumbnail").each(function() {
		if (nextThumb == $(this).attr("id")) {
			thumbClass = "active";
		} else {
			thumbClass = "inActive";
		}
		$(".thumbIndicator").append("<li class='" + thumbClass + "'><a href='#' class='jumpToThumb' rel='" + $(this).attr('id') + "'>Thumbnail</a></li>")
	});
}

ECC.disableWorkNavButton = function(button) {
	//Disable either the previous or next button
	switch (button) {
		case "prev": {
			$("#workControls").find(".workPrev").addClass("inactive");	
			break;
		}
		case "next": {
			$("#workControls").find(".workNext").addClass("inactive");		
			break;
		}
	}
}

ECC.tweetArray = function() {
	var arrTweetNav = [];
	
	//Loop through the description viewport to build a dynamic array
	$("#listOfTweets > li.tweetContainer").each(function() {
		arrTweetNav.push($(this).attr("id"));
	});
	
	return arrTweetNav;
}

/* ##### Once the document has loaded... ##### */
$(document).ready(function() {
	//Init the document
	ECC.init();
		
	$("ul#navBar > li").bind("click", function(e) {
	//e.preventDefault();
		//First Clear all active elements
		$("ul#navBar").find("li").removeClass("active");
		//Now highlight the clicked element
		$(this).addClass("active");
	});
	
	//Set up the slider for the contact form
	$(function() {
		var budgetSlider = $("#budgetSlider");
		var arrBudget = ["", "$10k-$50k", "$50k-$100k", "$100k-$250k", "$250k-$500k", "$500k-$750k", "$750k-$1M", "$1M-$1.5M", "$1.5M-$2M+"];
		
		ECC.adjustSliderValue = function (val) {
			budgetSlider.slider({value: val});
			$("#budgetAmount").val(arrBudget[budgetSlider.slider("value")]);
		}
		
		if (budgetSlider.length) {
			budgetSlider.slider({
				range: "min",
				value:0,
				min: 0,
				max: 8,
				step: 1,
				slide: function(event, ui) {
					$("#budgetAmount").val(arrBudget[ui.value]);
				}
			}).find(".ui-slider-handle").addClass("sliderHandle");
			$("#budgetAmount").val(arrBudget[budgetSlider.slider("value")]);

		}
		
		$(".smallBudget").bind("click", function(e) {
			e.preventDefault();
			ECC.adjustSliderValue(0);
			
		});
		
		$(".mediumBudget").bind("click", function(e) {
			e.preventDefault();
			ECC.adjustSliderValue(3);
		});
		
		$(".largeBudget").bind("click", function(e) {
			e.preventDefault();
			ECC.adjustSliderValue(6);
		});
	});
	
	//Blur the first/last name elements when the input is focused
	$(function() {
		$(".fieldContainer > input").bind("focus", function() {
			$(this).next("small").fadeOut("fast");		
		}).bind("blur", function() {
			if ($(this).val() == "") {
				$(this).next("small").fadeIn("fast");
			}
		});
	}); 
	
	//Validate the contact form
	$(function() {
		$("#contactForm").find("input, textarea").bind("blur", function() {
			var thisVal = $(this).val();
			var thisID = $(this).attr("id");
			var emailPattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
			//Only validate non-readonly inputs
			if (!$("#" + thisID).attr("readonly")) {
				//Check to make sure there is a value
				if (thisVal != "") {
					ECC.toggleFieldFlag(thisID, 1);
				} else {
					ECC.toggleFieldFlag(thisID, 0);
				}
				
				
				if (thisID == "email") {
					if (emailPattern.test(thisVal)) {
						ECC.toggleFieldFlag(thisID, 1);
					} else {
						ECC.toggleFieldFlag(thisID, 0);
					}
				}
			}
		});
		
		$("#contactForm").bind("submit", function(e) {
			e.preventDefault();
			var target = $(this).attr("action");
			var formData = $(this).serializeArray();
			
			$("#contactForm").find("input, textarea").each(function() {
				$(this).triggerHandler("blur");
			});
			
			//If no inputs are flagged as invalid,...
			if ($("input.invalid").length == 0) {
				//Submit the form
				$.post(target, formData, function(data) {
					if (data) {
						$("#contactFormOverlay").fadeIn();
						$.scrollTo("#contactFormOverlay", 500);						
					} else {
						alert("We seem to be experiencing technical difficulties.  Your message was not sent.");
						$("#contactForm").clearForm();
					}	
				});
				
			}
			
		});
	});
	
	//Handle the featured work scrolling
	$(function () {
		var thumbnailVP = $("#thumbnailViewport");
		var descriptionVP = $("#descriptionViewport");
		var arrWorkNav = [];
		
		//Loop through the description viewport to build a dynamic array
		descriptionVP.find("li.featuredDescription").each(function() {
			arrWorkNav.push($(this).attr("id").replace("-description", ""));
		});
		
		if (arrWorkNav.length) {
			//Set the hash
			if (location.hash == "") {
				location.hash = arrWorkNav[0];
			}
						
			//Now scroll to it.
			ECC.scrollToWork(location.hash.replace("#", ""), arrWorkNav);
			
			//Update the thumbnail indicator
			ECC.updateThumbIndicator(location.hash.replace("#", "") + "-thumbnail-1");
		}
		
		$("a.scrollTo").bind("click", function(e) {
			e.preventDefault();
			
			//Find the location to scroll to
			var scrollLocation = $(this).attr("rel");
			
			// If the next or prev buttons are pressed, increment the scroll location
			if (scrollLocation == "next" || scrollLocation == "prev") {
				//Find the location of the value of the hash in the work nav array
				var currentLocation = $.inArray(location.hash.replace("#",""), arrWorkNav);
								
				switch (scrollLocation) {
					case "next": {
						if (currentLocation >= arrWorkNav.length - 1) {
							scrollLocation = 0;
						} else {
							scrollLocation = arrWorkNav[currentLocation + 1]
						}						
						break;
					}
					case "prev": {
						if (currentLocation <= 0) {
							scrollLocation = 0;
						} else {
							scrollLocation = arrWorkNav[currentLocation - 1]
						}						
						break;
					}					
				}				
			}
			
			if (scrollLocation) {
				//Set the hash
				location.hash = scrollLocation;
				
				//Scroll to the description
				ECC.scrollToWork(scrollLocation, arrWorkNav);	
				
				//Update the thumbnail indicator
				ECC.updateThumbIndicator(scrollLocation + "-thumbnail-1");
							
			}
		}).bind("mousedown", function() {
			$(this).closest("li").addClass("click");
		}).bind("mouseup", function() {
			$(this).closest("li").removeClass("click");
		});
		
		//Thumbnail navigation
		$("ul.thumbControls > li > a").bind("click", function(e) {
			e.preventDefault();
			var currentThumb = $(this).closest(".featuredThumbnail").attr("id");
			var arrCurrentThumb = currentThumb.split("-");
			var currPos = Number(arrCurrentThumb[arrCurrentThumb.length-1]);
			
			//Either increment or decrement the last element in the array			
 			if ($(this).closest("li").hasClass("thumbPrev")) {
				arrCurrentThumb[arrCurrentThumb.length-1] = currPos-1;
			} else if ($(this).closest("li").hasClass("thumbNext")) {
 				arrCurrentThumb[arrCurrentThumb.length-1] = currPos+1;
 			} 			
 			
 			//Now put it all back together
 			var nextThumb = arrCurrentThumb.join("-");
 			
 			//If that element exists, scroll to it
 			if ($("#" + nextThumb).length) { 			
	 			thumbnailVP.stop().scrollTo("#" + nextThumb, 200);
 			}
 			
			ECC.updateThumbIndicator(nextThumb);
		});
		
		$("ul.clientThumbnails > li > a").bind("click", function(e) {
			e.preventDefault();
			var currentThumb = $(this).closest(".featuredThumbnail").attr("id");
			var arrCurrentThumb = currentThumb.split("-");
			var currPos = Number(arrCurrentThumb[arrCurrentThumb.length-1]);
			
			//Increment the last element in the array
 			arrCurrentThumb[arrCurrentThumb.length-1] = currPos+1;
 			
 			//Now put it all back together
 			var nextThumb = arrCurrentThumb.join("-");
 			
 			//If that element exists, scroll to it
 			if ($("#" + nextThumb).length) { 			
	 			thumbnailVP.stop().scrollTo("#" + nextThumb, 200);
 			}
 			
			ECC.updateThumbIndicator(nextThumb);
		});
		
		$("a.jumpToThumb").live("click", function(e) {
			e.preventDefault();
			
			var theThumb = $(this).attr("rel");
			
			//If that element exists, scroll to it
 			if ($("#" + theThumb).length) { 	
	 			thumbnailVP.stop().scrollTo("#" + theThumb, 200);
				
				//Now update the thumbnail indicator
				ECC.updateThumbIndicator(theThumb);
			}
		});
		
	});
	
	//Handle the scrolling of the tweets in the footer
	$(function () {
		var tweetVP = $("#footerTweetsViewport");
		arrTweetNav = ECC.tweetArray();
				
		thisTweetID = arrTweetNav[0];
		
		$("ul#tweetControls > li").bind("click", function(e) {
			e.preventDefault();

			var thisPos = $.inArray(thisTweetID, arrTweetNav);
			
			if ($(this).hasClass("tweetPrev")) {
				nextPos = thisPos - 1;				
			} else {
				nextPos = thisPos + 1;
			}
			nextID = arrTweetNav[nextPos];
			
			//If that tweet exists in the DOM...
			if ($("#listOfTweets > #" + nextID).length) {
				//Reset the inactive buttons
				$("ul#tweetControls > li").removeClass("inactive");
				//Scroll to the destination
				tweetVP.scrollTo("#" + nextID, 200);
				//Set the thisID to the value of the nextID
				thisTweetID = nextID;
			}
			
			//Disable the controls if we're on the first or last tweet
			if (nextPos == arrTweetNav.length-1) {
				$("ul#tweetControls > li.tweetNext").addClass("inactive");
			} else if (nextPos == 0) {
				$("ul#tweetControls > li.tweetPrev").addClass("inactive");
			}
		}).bind("mousedown", function() {
			$(this).closest("li").addClass("click");
		}).bind("mouseup", function() {
			$(this).closest("li").removeClass("click")
		});
		
	});
	
	//Search the dom for twitter containers that need tweets loaded for
	$(function() {
		$(".globalTweetWrapper").each(function() {
			var thisUsername = $(this).attr("class").replace("globalTweetWrapper ", "");
			var tweetContainer = $(this);
			var loadTweets = tweetContainer.find(".loadTweets");
			//Detect if we're going to flush the tweets
			var flushTweets = $.getUrlVar("flushTweets");
			if (flushTweets != 1) {
				flushTweets = 0;
			}
			
			$.getJSON("get-tweets.cfm?username=" + thisUsername + "&flushTweets=" + flushTweets, function(data) {
				if (data.length && loadTweets.length) {
					loadTweets.remove();
					
					$.each(data, function(i,item) {
						if (tweetContainer.attr("id") == "listOfTweets") {
							tweetContainer.append("<li class='tweetContainer' id='" + item.ID + "'>" + item.TWEET + "<small class='darkGray'>" + item.DATE + "</small></li>");
						} else {
							tweetContainer.append("<p class='tweetContainer'>" + item.TWEET + "</p><small class='darkGray'>" + item.DATE + "</small>");
							if (i == 1) return false;
						}
					});
					
					//Rebuild the tweet array
					arrTweetNav = ECC.tweetArray();
					thisTweetID = arrTweetNav[0];
				}
			});
		});
	});
	
	//Get the flickr photofeed for the about us page
	$(function () {
		$.getJSON("#", function(data) {
			$.each(data.items, function(i,item){
				$("<img />").attr("src", item.media.m).appendTo("li.photofeed").attr("class", "flickrPhoto").wrap("<a href='" + item.link + "' rel='external'></a>");
				if ( i == 7 ) return false;
			});
        });
	});
	
});

