(function(){

$(document).ready(function(){
	var menuDown = false, 
		menu = $("#Menu-Content"),
		content = $("#Content"), 
		lastParentIndex = -1
	;

	//Setup header menu
	$(".Menu-Item").each(function(){
		var menu_item = this,
		disp = function(parentIndex){
			menu.children().each(function(){ $(this).hide(); });
		
			$(menu.children().get(parentIndex)).show();
			menu.slideDown();
			menuDown = true;
		};
		$(this).click(function(){
			var parentIndex = $(this).prevAll().length;
			if(parentIndex === lastParentIndex) { return; } 
			else { lastParentIndex = parentIndex; }
			
			if(!menuDown) { disp.call(this, parentIndex); }
			else { menu.slideUp(function(){ disp.call(this, parentIndex); }.bind(this)); }
		});
	});
	
	//Some functions for toggling the menu
	var menuSlideUp = function(cb, clearParentIndex){
		if(clearParentIndex){
			lastParentIndex = -1;
		}
		if(menuDown) {
			$("#Menu-Content").slideUp(cb);
			menuDown = false;
		} else {
			cb();
		}
	};
	//Functions for content
	var contentHide = function(cb) {
		content.fadeOut(250, cb);
	};
	var contentShow = function(cb){
		content.fadeIn(250, cb);
	};
	
	/*
	$("body").append(
		'<script src="https://api.twitter.com/1/statuses/user_timeline.json?' + 
		'include_entities=true&include_rts=true&screen_name=omastudios&count=20' +
		'&callback=twitter.parse" type="text/javascript"></script>'
	);
	*/
	
	Pages.getPage("feed_news");
	
	//EXPORTS
	window.$menu = {
		slideUp: menuSlideUp
	};
	window.$content = {
		hide: contentHide,
		show: contentShow
	};
	
	// Beta form (temporary home)
	window.betaForm = {
			submit: function(){
				var contentBox = $("#beta-form-status"), fullname = $("input[name=fullname]").val(),
					email = $("input[name=email]").val(), twitter = $("input[name=twitter]").val()
				;
				
				var url = "db/beta_submit.php?" + "fullname=" + fullname + "&" +
					"email=" + email + "&" + "twitter=" + twitter
				;
				
				Ajax.get(url, {
					onSuccess: function(xhr){
						console.log(xhr.responseText);
						var result = JSON.parse(xhr.responseText);
						if(result.error){
							contentBox.html(result.errorText);
						} else {
							$("#beta-form-content").html(
								"<div style=\"font-size:1.2em\">" +
								"Your application has been submitted. You will receive an " +
								"email if and when your application is accepted." +
								"</div>"
							);
						}
					},
					onFailure: function(xhr){
						contentBox.html("Error: something went wrong.");
					}
				});
				
			}
		};
});

})();

