// Set a namespace for our code
window.iPhone = window.iPhone || {};
(function() {
	// Local shorthand variable
	var $i = this;
	// Shared utilities
	$i.utils = {
		// Adds class name to element
		addClass : function(element, elClass) {
			var curr = element.className;
			if (!new RegExp(("(^|\\s)" + elClass + "(\\s|$)"), "i").test(curr)) {
				element.className = curr + ((curr.length > 0) ? " " : "") + elClass;
			}
			return element;
		},
		// Removes class name from element
		removeClass : function(element, elClass) {
			if (elClass) {
				element.className = element.className.replace(elClass, "");
			} else {
				element.className = "";
				element.removeAttribute("class");
			}
			return element;
		},
	};
	// Initialize
	$i.init = function() {
		// Sniff for orientation property
		if (typeof window.orientation !== "undefined") {
			// Fire events in onload namespace
			for (var key in $i.onload) {
				$i.onload[key]();
			}
			
			// Can't prevent user from tapping status bar
			// So instead, readjust fixed positions
			window.addEventListener("scroll", function() {
				$i.utils.addClass(document.body, "scrolled");
			}, false);
			
			// Remove scroll class on orientation change
			window.addEventListener("orientationchange", function() {
				$i.utils.removeClass(document.body, "scrolled");
			}, false);
		}
	};
	
	$i.onload = {
		// Mimic native footer UI
		nativeFooter : function() {
			
			// Target element
			var footer = document.querySelector("#footertab");
			if (footer) {
				
				// Grab all 'tabs'
				var tabs = footer.getElementsByTagName("li");
				for (var i = 0, j = tabs.length; i < j; i++) {
					var tab = tabs[i];
					
					// Add active class on touch
					tab.addEventListener("touchstart", function() {
						
						// Remove classes from other active nodes
						for (var k = 0, l = tabs.length; k < l; k++) {
							$i.utils.removeClass(tabs[k], "active");
						}
						
						// Add active to self
						$i.utils.addClass(this, "active");
					}, false);
				}
			}
		}
	};
	
	// Fire on load
	window.addEventListener("load", $i.init, false);
	
}).call(window.iPhone); // Initialize