var FS = {};

(function(context) {
	
	jQuery(document).ready(function() {
		context.background.init();
		context.nav.init();
		context.validator.init();
	});
	
	context.settings = {
		frame: (jQuery.browser.webkit) ? 'body' : 'html',
		fixed_position_supported: true
	};
	

	context.nav = {
		init: function() {
			var self = this;
			
			if (jQuery(".home-page").size() > 0) {
				self.check_position_fixed();
				self.capture_nav_clicks();
				self.watch_scroll();				
			}
		},
		check_position_fixed: function() { 
					
			var container = document.body;
			
			if (document.createElement && container && container.appendChild && container.removeChild) {
				var el = document.createElement('div');
				
				if (!el.getBoundingClientRect) return null;				
				
				el.innerHTML = 'x';
				el.style.cssText = 'position:fixed;top:100px;';
				container.appendChild(el);
			
				var originalHeight = container.style.height,
					originalScrollTop = container.scrollTop;
			
				container.style.height = '3000px';
				container.scrollTop = 500;
			
				var elementTop = el.getBoundingClientRect().top;
				container.style.height = originalHeight;
				
				var isSupported = (elementTop === 100);
				container.removeChild(el);
				container.scrollTop = originalScrollTop;
			
				context.settings.fixed_position_supported = isSupported;
			}			
		},
		capture_nav_clicks: function() {
			var self = this;
			
			jQuery("nav a.internal, .logo a").click(function(event) {
				var href = jQuery(this).attr("href");
				var id = href.split("#");
				
				self.slide_page(id[1]);
				self.update_location(id[1]);
				
				event.preventDefault();
			});
			
		},
		watch_scroll: function() {	
		
			if (context.settings.fixed_position_supported) {
				var self = this;
				
				var possibles = jQuery("nav a.internal");
				var sections = [];
				
				jQuery(possibles).each(function() {
					var section = {};
					
					var href = jQuery(this).attr("href");
			
					// strip stuff before hash
					var href = href.split("#");
					
					section.id = href[1];
					section.offset = jQuery("#" + section.id).offset();
					
					sections.push(section);
				});
				
				var buffer = jQuery(window).height() / 3;
	
				jQuery(document).everyTime(100, "scroll", function() {
					
					var scroll_top = jQuery(context.settings.frame).scrollTop();
					var target;
					var last = jQuery(sections).size() - 1;
					
					jQuery(sections).each(function(index, section) {
						// If we've scrolled past the beginning of the zone
						if ( scroll_top > (sections[index].offset.top - buffer) ) {
							// But not into the next zone
							if (
								scroll_top > (sections[last].offset.top - buffer)
								||
								scroll_top < (sections[index + 1].offset.top - buffer)
							) 
							{
								target = jQuery("nav a:eq(" + index + ")");
							}
						}
					});
					
					self.set_active(target);
				});
			}
		},
		set_active: function(el) {
			jQuery("nav .active").removeClass("active");
			jQuery(el).addClass("active");
		},
		slide_page: function(target) {
			var container_offset = jQuery("#" + target).offset();
			var true_offset = container_offset.top - 80;
			
			jQuery(context.settings.frame).animate({scrollTop: true_offset}, 1000);
		},
		update_location: function(frag) {
			var hist_api_supported = !!(window.history && history.pushState);
			
			debugger;

			if (frag != undefined) {
				if (hist_api_supported) {
					history.pushState(null, "", "#" + frag);
				}
				else {
					window.location.href = "#" + frag;
				}
			}
		}
	};
		
	context.validator = {
		init: function() {
			var self = this;
			
			$("#contact-form").submit(function(event) {
				self.validate();
				event.preventDefault();
			});
		},
		validate: function() {
			var self = this;
			
			var $fields = $("#contact-form input[required=required], #contact-form textarea[required=required]");
			
			var errors = [];
			
			$fields.each(function(index, el) {
								  
				var error = [];	
				
				if (self._isBlank($(el).val())) {
					error.push("blank");
				}
				
				if ($(el).attr("type") == "email") {				
					if (self._isNotProperlyFormatted($(el).val())) {
						error.push("improperly formatted");
					}
				}
					
				if (error.length > 0) {
					$(el).data("error", error);
					errors.push(error);
				}
				else {
					$(el).removeData();
				}
			});
			
			if (errors.length > 0) {
				self.displayErrors();			
			}
			else {
				self.submitForm();
			}
		},
		displayErrors: function() {
			$fields = $("#contact-form input[required=required], #contact-form textarea[required=required]");
			
			/* If there is an error, add the error text and move the window offset to just above the error. */				
			$fields.each(function(index, el) {
				
				// If an error is present
				if ($(el).data("error")) {
					// If no error message is present
					if ($(el).siblings(".label").find(".error").size() == 0) {
						$(el).siblings(".label").append("<span class='error'>Whoops, you messed this one up.</span>");					
					}
				}
				else {
					if ($(el).siblings(".label").find(".error").size() > 0) {
						$(el).siblings(".label").find(".error").remove();					
					}
				}
				
			});
			
			var offset = jQuery(".error:first").offset();
			jQuery(context.settings.frame).animate({scrollTop: offset.top - 60}, 500);
		},
		submitForm: function() {
			var name = $("#contact-name").val(); 
			var email = $("#contact-email").val();
			var phone = $("#contact-phone").val();
			var company = $("#contact-company").val();
			var message = $("#contact-message").val();
			
			var data_string = "contact-name=" + name + "&contact-email=" + email + "&contact-phone=" + phone + "&contact-company=" + company + "&contact-message=" + message;	

			$.ajax({
			  	url: "contact.php",
			  	data: data_string,
				type: "POST",
				success: function() {
					$(".thank-you").fadeIn("slow", function() {
						$("#contact-form input[type=text], #contact-form input[type=email], #contact-form input[type=tel], #contact-form textarea").val("");
						
						$(document).oneTime("5s", "thank-you", function() {
							$(".thank-you").fadeOut();
						})
					});
				}
			});
		},
		_isBlank: function(str) {
			return (str == "") ? true : false
		},
		_isNotProperlyFormatted: function(str) {
			var myregex = /@.*\./;
			var mymatch = myregex.exec(str);
			
			return (mymatch == null) ? true : false;
		}
	};
	
	context.background = {
		init: function() {			
			var $bg = $(".background-image img");
			
				if ($bg[0].complete) {
					$bg.fadeIn("slow");
				}
				else {
					$bg.load(function() {
						$bg.fadeIn("slow");
					});
				}
		}
	};

})(FS);
