// Remy Sharp's HTML5 enabling script
// For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
(function(){if(!/*@cc_on!@*/0)return;var e='abbr,article,aside,audio,canvas,datalist,details,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video'.split(','),i=e.length;while(i--){document.createElement(e[i])}})();


(function($){


// link automations

var ee_affiliate_name = 'brandonkelly',
	external_re = new RegExp('^https?://(?!'+document.location.hostname+')'),
	external_ee_re = new RegExp('^(https?://(secure\\.|www\\.)?expressionengine.com\\/)([^#]*)(#(\\w+))?$'),
	ee_affiliate_re = new RegExp('^index\\.php\\?affiliate='+ee_affiliate_name);

$('a').each(function(){
	// is this an external link?
	if (this.href.match(external_re)) {
		if (! this.target) this.target = '_blank';

		// if this is a link to expressionengine.com
		// but not already an affiliate link, convert it one
		var href = this.href,
			match = href.match(external_ee_re);
		if (match && ! match[3].match(ee_affiliate_re)) {
			this.href = match[1]+'index.php?affiliate='+ee_affiliate_name
			          + (match[3] ? '&page=/'+match[3] : '')
			          + (match[5] ? '&anchor='+match[5] : '');
		}

		// track outbound links
		$(this).click(function(){
			pageTracker._trackPageview('/Outbound/'+href);
		});
	}
});


// iphone header menus

function isCursorOver(event, $element){
	var offset = $element.offset(),
		x1 = offset.left,
		y1 = offset.top,
		x2 = x1 + $element.width(),
		y2 = y1 + $element.height();
	return (event.clientX >= x1 && event.clientX < x2 && event.clientY >= y1 && event.clientY < y2);
}

$('.header .menu').each(function(){
	var menu = this,
		$menu = $(this),
		$items = $('li', $menu),
		$activeItem;

	menu.ontouchstart = function(event) {
		event.preventDefault();

		document.ontouchmove = function(event) {
			if (event.touches.length > 1) return;

			event.preventDefault();
			var touch = event.touches[0];

			var hovering = false;
			$items.each(function(){
				if (isCursorOver(touch, $(this))) {
					if ($activeItem) $activeItem.removeClass('hover');
					$activeItem = $(this).addClass('hover');
					hovering = true;
					return false;
				}
			});
			if (! hovering && $activeItem) {
				$activeItem.removeClass('hover');
				$activeItem = null;
			}
		};

		document.ontouchend = function(event) {
			event.preventDefault();
			document.ontouchmove = null;

			if ($activeItem) {
				document.location.href = $('a', $activeItem).attr('href');
			}
			else {
				$menu.removeClass('hover');
			}
		};
	};
});


window.onload = function(){
	// preloading
	var img = new Image();
	img.src = '../images/bg-gradients/header-navmenu.png';
	img.src = '../images/bg-gradients/header-navmenu-item.png';
};


})(jQuery);
