/* Initialize */
jQuery(function ($) {
	$.Body = $('body');
	$.Window = $(window);
	$.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
	$.Mobile = ($.Body.hasClass('webkit-mobile') || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
	$.Unsupported = $.Body.hasClass('unsupported-browser');
	$.Body
	.Keyboard();

	$('[data-controller]').Instantiate();
}); // Initialize

/* Events */
(function ($) {
	$.Events = {
		SECTION_ENTER: 'sectionEnter',

		SCROLL_TO: 'scrollTo',

		SCROLL: 'windowScroll',
		SCROLL_ENTER: 'windowScrollEnter',
		SCROLL_LEAVE: 'windowScrollLeave',

		KEY_UP: 'keyUp',
		KEY_DOWN: 'keyDown',
		KEY_LEFT: 'keyLeft',
		KEY_RIGHT: 'keyRight',
		KEY_ESC: 'keyEsc',
		KEY_SPACE: 'keySpace'
	};
})(jQuery); // Events

/* Auto Instantiate */
(function ($) {
	$.fn.Instantiate = function (settings) {

		var config = {};

		if (settings) {
			$.extend(config, settings);
		}

		this.each(function () {
			var $self = $(this),
			  $controller = $self.attr('data-controller');

			if ($self[$controller]) {
				$self[$controller]();
			}
		});
	}
})(jQuery); // Auto Instantiate

/* Navigation */
(function ($) {
	$.fn.MainNav = function () {
		this.each(function () {
			var $self = $(this),
			$ul = $('<ul/>').appendTo($self),
			$sections = $('[data-nav]'),
			_sections = new Array(),
			$navs = new Array(),
			_active = 0;
			
			if (!$.Mobile && !$.Unsupported) {
				$sections.each(function (i) {
					_sections.push($(this));
					$('<li/>').appendTo($ul).DotNav({ id: $(this).attr('id'), name: $(this).attr('data-nav') });
				});
				$self.css({ marginTop: -$self.height() / 2 });
			}

			$.Body
			.bind($.Events.SECTION_ENTER, function (e, id) {
				$sections.each(
				function (i) {
					if ($(this).attr('id') == id) {
						_active = i;
					}

				})
			})
			.bind($.Events.KEY_RIGHT, function (e) {
				_active++;
				if (_active > $sections.length - 1) {
					_active = $sections.length - 1;
				}
				_seek();
			})
			.bind($.Events.KEY_LEFT, function (e) {
				_active--;
				if (_active < 0) {
					_active = 0;
				}
				_seek();
			});

			function _seek() {
				$.Body.triggerHandler($.Events.SCROLL_TO, _sections[_active].attr('id'));
			}
		});

		return this;

	} // MainNav

	$.fn.DotNav = function (settings) {

		var config = {};

		if (settings) {
			$.extend(config, settings);
		}

		this.each(function () {
			var $self = $(this),
			$a = $('<a/>'),
			$h1 = $('<h1/>').appendTo($self),
			$span = $('<span/>').html(config.name).appendTo($h1),
			$id = config.id;

			$a
			.attr('href', '#' + config.name.split(' ').join('_'))
			.html($id)
			.appendTo($self)
			.bind('click', function (e) {
				$.Body.triggerHandler($.Events.SCROLL_TO, $id);
				e.preventDefault();
			});

			$self.attr('data-id', $id);

			$a
			.bind('mouseenter', function (e) {
				if ($('._playing').length == 0)
				{
					$h1.stop().css({ display: 'block' }).animate({ right: 30, opacity: 1 }, 450);
				}
			})
			.bind('mouseleave', function (e) {
				$h1.stop().animate({ right: 15, opacity: 0 }, 450, function () { $h1.stop().css({ display: 'none' }) });
			});

			$.Body
			.bind('sectionEnter', function (e, id) {
				if (id == $id) {
					$self.addClass('active');
				}
				else {
					$self.removeClass('active');
				}
			});
		});

		return this;

	} // DotNav
	
	$.fn.NextNav = function () {
		this.each(function () {
//			$('[data-navnextsection]').each(function (i) {
				var $text = $(this).attr('data-navnexttext'),
				$link = $(this).attr('data-navnextlink'),
				$nextSection = $(this).attr('data-navnextsection'),
				$a = $('<a/>');

				$a
				.attr('href', "#" + $link.split(' ').join('_'))
				.html($text)
				.appendTo($(this))
				.bind('click', function (e) {
					$.Body.triggerHandler($.Events.SCROLL_TO, $nextSection);
					e.preventDefault();
				});
//			});
		});

		return this;
	} // NextNav
})(jQuery); // Navigation

/* SiteScroll */
(function ($) {
	$.fn.SiteScroll = function () {
		this.each(function () {
			var $self = $(this);
			$.Body
			.bind($.Events.SCROLL_TO, function (e, id) {
				var $element = $('#' + id),
				  $header = $element.find('header'),
				  _align = $element.attr('data-align'),
				  _offset = $element.attr('data-scrolloffset') ? parseInt($element.attr('data-scrolloffset')) : 50,
				  _top = $element.offset().top;

				if ($header.length > 0 && _align != "top") {
					_top = $header.offset().top + $header.height() / 2 - $.Window.height() / 2;
					if (_top > $header.offset().top) {
						_top = $header.offset().top - 50;
					}
				}

				if (_align == "center" && $element.height() > $.Window.height()) {
					_top = $element.offset().top + ($element.height() - $.Window.height()) / 2;
				}

				$.Scroll
				.stop()
				.animate(
					{ 'scrollTop': _top },
					800
				);
			})
		});

		return this;
	}
})(jQuery); // SiteScroll

/* Scrollable */
(function ($) {
	$.fn.Scrollable = function (settings) {
		var config = { threshold: -100, offset_scroll: 6, offset_intertia: .15 };

		if (settings) {
			$.extend(config, settings);
		}

		this.each(function () {
			var $self = $(this),
			$id = $self.attr('id');

			config.threshold = 0;

			if ($.Mobile || $.Unsupported) {
				$self.css({ backgroundAttachment: 'scroll' });
			} else {
				$.Window
				.bind('scroll', function (e) {
					if ($.inview($self, { threshold: config.threshold })) {
						if (!$self.hasClass('_active')) {
							$self.addClass('_active');

							if (config.is_nav) {
								$.Body.triggerHandler($.Events.SECTION_ENTER, $id);
							}
							$self.triggerHandler($.Events.SCROLL_ENTER);
						}
//						_scroll_background();
						$self.triggerHandler($.Events.SCROLL, $.distancefromfold($self, { threshold: config.threshold }) - config.threshold);
					} else {
						if ($self.hasClass('_active')) {
							$self.removeClass('_active');
							$self.triggerHandler($.Events.SCROLL_LEAVE);
						}
					}
				});
			}

			function _scroll_background() {
				var _x = '50% ';
				var bpos = _x + (-($.distancefromfold($self, { threshold: config.threshold }) - config.threshold) * config.offset_intertia) + 'px';
				$self.css({ 'backgroundPosition': bpos });
			}
		});

		return this;
	} // Scrollable

	$.fn.StoryHome = function() {
		this.each(function() { 
			var $self = $(this),
				_threshold = -200;
		
			$self.Scrollable({threshold: _threshold, is_nav : true});
		});
		return this;
	} // StoryHome

	$.fn.StoryMobile = function() {
		this.each(function() { 
			var $self = $(this),
				_threshold = -200;
		
			$self.Scrollable({threshold: _threshold, is_nav : true});
		});
		return this;
	} // StoryMobile
	
	$.fn.StoryInteractive = function() {
		this.each(function() { 
			var $self = $(this),
				_threshold = -200;
		
			$self.Scrollable({threshold: _threshold, is_nav : true});
		});
		return this;
	} // StoryInteractive
	
	$.fn.StoryWeb = function() {
		this.each(function() { 
			var $self = $(this),
				_threshold = -200;
		
			$self.Scrollable({threshold: _threshold, is_nav : true});
		});
		return this;
	} // StoryWeb
	
	$.fn.StoryContactUs = function() {
		this.each(function() { 
			var $self = $(this),
				_threshold = -200;
		
			$self.Scrollable({threshold: _threshold, is_nav : true});
		});
		return this;
	} // StoryContactUs
})(jQuery);	// Scrollable

/* Keyboard */
(function ($) {
	$.fn.Keyboard = function (settings) {
		var config = {};

		if (settings) {
			$.extend(config, settings);
		}

		this.each(function () {
			var $self = $(this);
			$(document).bind('keydown', on_keydown);

			function on_keydown(e) {
				var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
				switch (key) {
					case 27: //escape
						$.Body.triggerHandler($.Events.KEY_ESC);
						break;
					case 32: //space
						$.Body.triggerHandler($.Events.KEY_SPACE);
						break;
					case 38: //top
						$.Body.triggerHandler($.Events.KEY_UP);
						break;
					case 39: //right
						$.Body.triggerHandler($.Events.KEY_RIGHT);
						e.preventDefault();
						break;
					case 40: ///bottom
						$.Body.triggerHandler($.Events.KEY_DOWN);
						break;
					case 37: //left
						$.Body.triggerHandler($.Events.KEY_LEFT);
						break;
				} //switch
			} //keydown
		});
	
		return this;
	}

})(jQuery); // Keyboard

/* Worker */
(function ($) {
	$.distancefromfold = function ($element, settings) {
		if (settings.container === undefined || settings.container === window) {
			var fold = $(window).height() + $(window).scrollTop();
		} else {
			var fold = $(settings.container).offset().top + $(settings.container).height();
		}
		return (fold + settings.threshold) - $element.offset().top;
	};

	$.belowthefold = function ($element, settings) {
		if (settings.container === undefined || settings.container === window) {
			var fold = $(window).height() + $(window).scrollTop();
		} else {
			var fold = $(settings.container).offset().top + $(settings.container).height();
		}
		return fold <= $element.offset().top - settings.threshold;
	};

	$.rightoffold = function ($element, settings) {
		if (settings.container === undefined || settings.container === window) {
			var fold = $(window).width() + $(window).scrollLeft();
		} else {
			var fold = $(settings.container).offset().left + $(settings.container).width();
		}
		return fold <= $element.offset().left - settings.threshold;
	};

	$.abovethetop = function ($element, settings) {
		if (settings.container === undefined || settings.container === window) {
			var fold = $(window).scrollTop();
		} else {
			var fold = $(settings.container).offset().top;
		}
		return fold >= $element.offset().top + settings.threshold + $element.height();
	};

	$.leftofbegin = function ($element, settings) {
		if (settings.container === undefined || settings.container === window) {
			var fold = $(window).scrollLeft();
		} else {
			var fold = $(settings.container).offset().left;
		}
		return fold >= $element.offset().left + settings.threshold + $element.width();
	};

	$.inview = function ($element, settings) {
		return ($.abovethetop($element, settings) != true && $.belowthefold($element, settings) != true)
	};

	$.extend($.expr[':'], {
		"below-the-fold": "$.belowthefold(a, {threshold : 0, container: window})",
		"above-the-fold": "!$.belowthefold(a, {threshold : 0, container: window})",
		"right-of-fold": "$.rightoffold(a, {threshold : 0, container: window})",
		"left-of-fold": "!$.rightoffold(a, {threshold : 0, container: window})"
	});

})(jQuery); // Worker


function setupDialog() {
	$("#inquiry-received").dialog({
		autoOpen: false,
		width: 400,
		modal: true,
		resizable: false,
		draggable: false,
		buttons: {
			Ok: function () {
				$(this).dialog("close");
			}
		}
	});

	$("#inquiry-failure").dialog({
		autoOpen: false,
		width: 400,
		modal: true,
		resizable: false,
		draggable: false,
		buttons: {
			Ok: function () {
				$(this).dialog("close");
			}
		}
	});

	var validator = $("#contact-form").validate({
		errorPlacement: function (error, element) {
			error.appendTo(element.prev("label"));
		}
	});

	$("#contact-form").submit(function (event) {
		if ($("#contact-form").valid()) {
			$("#contact-form").block({ message: null });
			$.ajax({
				type: "post",
				url: "NetSuiteSubmissionService.svc/SubmitLead",
				data: JSON.stringify({
					firstName: $('#firstname').val(),
					lastName: $('#lastname').val(),
					companyName: $('#company').val(),
					email: $('#email').val(),
					website: $('#url').val(),
					inquiry: $('#description').val()
				}),
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (msg) {
					$("#contact-form").unblock();
					if (msg.d == true) {
						$('#inquiry-received').dialog('open');
						validator.resetForm();
					} else {
						$('#inquiry-failure').dialog('open');
					}
				},
				error: function () {
					$("#contact-form").unblock();
					$('#inquiry-failure').dialog('open');
				}
			});
			return false;
		}
	});
}

/* Parallax scrolling */
$(document).ready(function () {
	// Cache the Window object
	$window = $(window);

	if ($('html').hasClass('ie6')) {
		DD_belatedPNG.fix('.spritePhone, .spriteInteractive, .spriteWeb, nav#main a, nav#main h1');
	}

	// Cache the Y offset and the speed of each sprite
	$('[data-type]').each(function () {
		$(this).data('offsety', parseInt($(this).attr('data-offsety')));
		$(this).data('positionx', $(this).attr('data-positionx'));
		$(this).data('speed', $(this).attr('data-speed'));
	});

	// For each element that has a data-type attribute
	$('section[data-type="background"]').each(function () {
		// Store some variables based on where we are
		var $self = $(this),
			offsetCoords = $self.offset(),
			topOffset = offsetCoords.top;

		// When the window is scrolled...
		$(window).scroll(function () {
			// If this section is in view
			if (($window.scrollTop() + $window.height()) > (topOffset) &&
				 ((topOffset + $self.height()) > $window.scrollTop())) {

				// Scroll the background at var speed
				// the yPos is a negative value because we're scrolling it UP!								
				var yPos = -($window.scrollTop() / $self.data('speed'));

				// If this element has a Y offset then add it on
				if ($self.data('offsety')) {
					yPos += $self.data('offsety');
				}

				// Put together our final background position
				var coords = $self.data('backgroundpositionx') + ' ' + yPos + 'px';

				// Move the background
				$self.css({ backgroundPosition: coords });

				// Check for other sprites in this section	
				$('[data-type="sprite"]', $self).each(function () {
					// Cache the sprite
					var $sprite = $(this);

					// Use the same calculation to work out how far to scroll the sprite
					var yPos = -($window.scrollTop() / $sprite.data('speed'));
					var coords = $sprite.data('positionx') + ' ' + (yPos + $sprite.data('offsety')) + 'px';

					$sprite.css({ backgroundPosition: coords });

				}); // sprites

				// Check for any Videos that need scrolling
				$('[data-type="video"]', $self).each(function () {
					// Cache the video
					var $video = $(this);

					// There's some repetition going on here, so 
					// feel free to tidy this section up. 
					var yPos = -($window.scrollTop() / $video.data('speed'));
					var coords = (yPos + $video.data('offsety')) + 'px';

					$video.css({ top: coords });
				}); // video	
			}; // in view
		}); // window scroll
	}); // each data-type


	// Activate the first nav button
	$.Body.triggerHandler($.Events.SECTION_ENTER, 'story-home');

	/*	$script = $('<script/>');
	$script
	.attr('type', 'application/javascript')
	.attr('src', "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js")
	.appendTo($.Body);

	$script = $('<script/>');
	$script
	.attr('type', 'application/javascript')
	.attr('src', "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js")
	.appendTo($.Body);
	*/
	setupDialog();
});     // document ready
