$(document).ready(function(){
	// Wicked credit to
	// http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
	var scrollElement = 'html, body';
	$('html, body').each(function () {
		var initScrollTop = $(this).attr('scrollTop');
		$(this).attr('scrollTop', initScrollTop + 1);
		if ($(this).attr('scrollTop') == initScrollTop + 1) {
			scrollElement = this.nodeName.toLowerCase();
			$(this).attr('scrollTop', initScrollTop);
			return false;
		}    
	});
	
	// Smooth scrolling for internal links
	$("a[href^='#']").click(function(event) {
		event.preventDefault();

		var $this = $(this),
		   target = this.hash,
		  $target = $(target);

		$(scrollElement).stop().animate({
			'scrollTop': $target.offset().top
		}, 500, 'swing', function() {
			window.location.hash = target;
		});
		
	});


// waypoints
	$('section').waypoint(function(event, direction){
		if(direction === 'up'){
			$('section').waypoint({ offset:-50 });
		} else {
			$('section').waypoint({ offset:100 });
		}
	});

	$('#about').waypoint( function(e, direction){
		$('nav li').removeClass('active');
		$('nav li a.about').parent().addClass('active');
	});

	$('#skills').waypoint( function(e, direction){
		$('nav li').removeClass('active');
		$('nav li a.skills').parent().addClass('active');
	} );

	$('#languages').waypoint( function(e, direction){
		$('nav li').removeClass('active');
		$('nav li a.languages').parent().addClass('active');
	} );

	$('#works').waypoint( function(e, direction){
		$('nav li').removeClass('active');
		$('nav li a.works').parent().addClass('active');
	} );

	$('#contact').waypoint( function(e, direction){
		$('nav li').removeClass('active');
		$('nav li a.contact').parent().addClass('active');
	},{
		offset:200
	});

	// parallax
	$('#about .parallax .um').scrollParallax({
		'speed': -5,
		'axis' : 'y'
	});
	$('#about .parallax .dois').scrollParallax({
		'speed': -4,
		'axis' : 'y'
	});
	$('#about .parallax .tres').scrollParallax({
		'speed': -3,
		'axis' : 'y'
	});
	$('#about .parallax .quatro').scrollParallax({
		'speed': -2,
		'axis' : 'y'
	});

	// form
	$('#sendIt').click(function(){
		var name = $('#contact #name').val(),
				from = $('#contact #from').val(),
			 email = $('#contact #email').val();
		var dataString = 'name='+ name + '&from=' + from + '&email=' + email;  

		$.ajax({  
			type: "POST",  
			url: "theEmailCourier.php",  
			data: dataString,  
			success: function() {  
				$('#contact h3').remove();
				$('#contact form').remove();
				$('#contact section').html("<h3>Your message has been sent and I'll talk to you soon :)</h3>");
			}  
		});  
		return false;  
	});

});


/**
 * author Christopher Blum
 *    - based on the idea of Remy Sharp, http://remysharp.com/2009/01/26/element-in-view-event-plugin/
 *    - forked from http://github.com/zuk/jquery.inview/
 */
(function ($) {
	var inviewObjects = {}, viewportSize, viewportOffset,
	d = document, w = window, documentElement = d.documentElement, expando = $.expando;

	$.event.special.inview = {
		add: function(data) {
			inviewObjects[data.guid + "-" + this[expando]] = { data: data, $element: $(this) };
		},

		remove: function(data) {
			try { delete inviewObjects[data.guid + "-" + this[expando]]; } catch(e) {}
		}
	};

	function getViewportSize() {
		var mode, domObject, size = { height: w.innerHeight, width: w.innerWidth };

		// if this is correct then return it. iPad has compat Mode, so will
		// go into check clientHeight/clientWidth (which has the wrong value).
		if (!size.height) {
			mode = d.compatMode;
			if (mode || !$.support.boxModel) { // IE, Gecko
				domObject = mode === 'CSS1Compat' ?
				documentElement : // Standards
				d.body; // Quirks
				size = {
					height: domObject.clientHeight,
					width:  domObject.clientWidth
				};
			}
		}

		return size;
	}

	function getViewportOffset() {
		return {
			top:  w.pageYOffset || documentElement.scrollTop   || d.body.scrollTop,
			left: w.pageXOffset || documentElement.scrollLeft  || d.body.scrollLeft
		};
	}

	function checkInView() {
		var $elements = $(), elementsLength, i = 0;

		$.each(inviewObjects, function(i, inviewObject) {
			var selector  = inviewObject.data.selector,
			$element  = inviewObject.$element;
			$elements = $elements.add(selector ? $element.find(selector) : $element);
		});

		elementsLength = $elements.length;
		if (elementsLength) {
			viewportSize   = viewportSize   || getViewportSize();
			viewportOffset = viewportOffset || getViewportOffset();

			for (; i<elementsLength; i++) {
				// Ignore elements that are not in the DOM tree
				if (!$.contains(documentElement, $elements[i])) {
					continue;
				}

				var $element      = $($elements[i]),
				    elementSize   = { height: $element.height(), width: $element.width() },
				    elementOffset = $element.offset(),
				    inView        = $element.data('inview'),
				    visiblePartX,
				    visiblePartY,
				    visiblePartsMerged;

				// Don't ask me why because I haven't figured out yet:
				// viewportOffset and viewportSize are sometimes suddenly null in Firefox 5.
				// Even though it sounds weird:
				// It seems that the execution of this function is interferred by the onresize/onscroll event
				// where viewportOffset and viewportSize are unset
				if (!viewportOffset || !viewportSize) {
					return;
				}

				if (elementOffset.top + elementSize.height > viewportOffset.top &&
						elementOffset.top < viewportOffset.top + viewportSize.height &&
						elementOffset.left + elementSize.width > viewportOffset.left &&
						elementOffset.left < viewportOffset.left + viewportSize.width) {
					visiblePartX = (viewportOffset.left > elementOffset.left ?
						'right' : (viewportOffset.left + viewportSize.width) < (elementOffset.left + elementSize.width) ?
						'left' : 'both');
						visiblePartY = (viewportOffset.top > elementOffset.top ? 'bottom' : (viewportOffset.top + viewportSize.height) < (elementOffset.top + elementSize.height) ? 'top' : 'both');
						visiblePartsMerged = visiblePartX + "-" + visiblePartY;
						if (!inView || inView !== visiblePartsMerged) {
							$element.data('inview', visiblePartsMerged).trigger('inview', [true, visiblePartX, visiblePartY]);
						}
					} else if (inView) {
						$element.data('inview', false).trigger('inview', [false]);
					}
				}
			}
		}

		$(w).bind("scroll resize", function() {
			viewportSize = viewportOffset = null;
		});

		// Use setInterval in order to also make sure this captures elements within
		// "overflow:scroll" elements or elements that appeared in the dom tree due to
		// dom manipulation and reflow
		// old: $(window).scroll(checkInView);
		//
		// By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays
		// intervals while the user scrolls. Therefore the inview event might fire a bit late there
		setInterval(checkInView, 250);
})(jQuery);


/*!
 * Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * backgroundPosition cssHook for jquery. Necessary to combat different css property names between browsers
 * https://github.com/brandonaaron/jquery-cssHooks
 * Licensed under the MIT License (LICENSE.txt).
 */
(function($) {
	// backgroundPosition[X,Y] get hooks
	var $div = $('<div style="background-position: 3px 5px">');
	$.support.backgroundPosition   = $div.css('backgroundPosition')  === "3px 5px" ? true : false;
	$.support.backgroundPositionXY = $div.css('backgroundPositionX') === "3px" ? true : false;
	$div = null;

	var xy = ["X","Y"];

	// helper function to parse out the X and Y values from backgroundPosition
	function parseBgPos(bgPos) {
		var parts  = bgPos.split(/\s/),
		values = {
			"X": parts[0],
			"Y": parts[1]
		};
		return values;
	}

	if (!$.support.backgroundPosition && $.support.backgroundPositionXY) {
		$.cssHooks.backgroundPosition = {
			get: function( elem, computed, extra ) {
				return $.map(xy, function( l, i ) {
					return $.css(elem, "backgroundPosition" + l);
				}).join(" ");
			},
			set: function( elem, value ) {
				$.each(xy, function( i, l ) {
					var values = parseBgPos(value);
					elem.style[ "backgroundPosition" + l ] = values[ l ];
				});
			}
		};
	}

	if ($.support.backgroundPosition && !$.support.backgroundPositionXY) {
		$.each(xy, function( i, l ) {
			$.cssHooks[ "backgroundPosition" + l ] = {
				get: function( elem, computed, extra ) {
					var values = parseBgPos( $.css(elem, "backgroundPosition") );
					return values[ l ];
				},
				set: function( elem, value ) {
					var values = parseBgPos( $.css(elem, "backgroundPosition") ),
					isX = l === "X";
					elem.style.backgroundPosition = (isX ? value : values[ "X" ]) + " " + 
					(isX ? values[ "Y" ] : value);
				}
			};
			$.fx.step[ "backgroundPosition" + l ] = function( fx ) {
				$.cssHooks[ "backgroundPosition" + l ].set( fx.elem, fx.now + fx.unit );
			};
		});
	}
})(jQuery);

/*!
 * Scroll-based parallax plugin for jQuery
 * Copyright (c) 2011 Dave Cranwell (http://davecranwell.com)
 * Licensed under the MIT License.
 * 2011-05-18
 * version 1.0
 */
(function($){
	$.fn.scrollParallax = function(options) {
		var settings = {
			'speed': 0.2,
			'axis': 'x,y',
			'debug': false
		}

		function debug(msg){
			if(settings.debug && 'console' in window && 'log' in window.console){
				console.log(msg);
			}
		}

		return this.each(function() {
			//defined accessible $this var in standard way for use within functions
			var $this = $(this);

			//extend options in standard way
			if (options) {
				$.extend(settings, options);
			}

			$this.bind('inview', function (event, visible) {
				if (visible == true) {
					$this.addClass("inview");
					debug("in view");
				}else{
					$this.removeClass("inview");
					debug("out of view");
				}
			});

			//find current position so parallax can be relative to it
			var currentPosArray=$this.css("backgroundPosition").split(" ");
			var currentXPos=parseInt(currentPosArray[0].replace(/[^0-9\-]/g, ""));
			var currentYPos=parseInt(currentPosArray[1].replace(/[^0-9\-]/g, ""));

			//recalculate position on scroll
			$(window).bind('scroll', function(){
				if($this.hasClass("inview")){			
					var offset = $this.offset();

					//calculate new position
					if(settings.axis.match(/x/)){
						var Xpos = offset.left - $(window).scrollLeft();
						var newXPos = (-(Xpos) * settings.speed) + currentXPos;
					}else{
						var newXPos = currentXPos;
					}
					if(settings.axis.match(/y/)){
						var Ypos = offset.top - $(window).scrollTop();
						var newYPos = (-(Ypos) * settings.speed) + currentYPos;
					}else{
						var newYPos = currentYPos;
					}

					debug("new X position: "+ newXPos);
					debug("new Y position: "+ newYPos);

					$this.css({'backgroundPosition':  parseInt(newXPos) + "px " + parseInt(newYPos) +"px"}); 
				}
			});
		});
	};
	
})(jQuery);

