jQuery(document).ready(function($){

	if($("#join_us").length>0){
		$("#join_us").validate();
	}
	
	// Binds resize modal function to window events	
	$(window).bind({		
		load: function(){
		},
		resize: function(){
			resize_modal();
		},
		scroll: function(){
			resize_modal();
		}
	});
	
	// Setup button function call
	if($(".modal_activate").length>0){
		$(".modal_activate").click(function(e){
			e.preventDefault();
						
			var url = filter_url($(this).attr('href'));
			display_modal(1, url.location, "#" + url.fragment);
		});
	}
	
	
	$("#modal").live("click", function(e){
		var close_class = e.target.className;
		if(e.target.id == $(this).attr("id") || (close_class.indexOf("modal_close") != -1)){
			display_modal(0);                                                                                              
		}
	});
	
	/*if($(".modal_close").length>0){
		$(".modal_close").live("click", function(e){
			alert(e.target.className);
			if(e.target.className === "modal_close"){
				display_modal(0);
			}
		});
	}*/
	
	// Hides modal if ESC key is hit
	$(document).keyup(function(e){
		if(e.keyCode == 27){
			display_modal(0);
	    }
	});
	
	function filter_url(url){
		var tmp = url.split("#");
		return {
			location: tmp[0],
			fragment: tmp[1]
		};
	}
	
	// Resizes modal
	function resize_modal(){
		if($("#modal").length > 0){
			// Resizes box to match current window height
			$("#modal").height($(document).height());
						
			// OPTION to vertically align form using the vertical.align plugin 
			$("#modal .modal_content").vAlign();
		}
	}
		// Loads modal content via AJAX
	function display_modal(toggle, url, fragment){
		if(toggle){
			
			// Adds modal container div
			if($("#modal").length === 0){	
				$("<div id='modal'></div>").appendTo("body");
			}
			
			$("#modal").load(url + " " + fragment, function(response, status, xhr){
				
				// Show error if nothing is returned
				if(status === "error") {
					var msg = "Unable to open " + url + " – Please try again.";
				    $("#error").html(msg + xhr.status + " " + xhr.statusText);
				}
				
				// Show modal and align vertically
				$("#modal").fadeIn(100);
				
				// OPTION to vertically align form using the vertical.align plugin 
				$("#modal .modal_content").vAlign();
				
				// Setup close targets on close button and modal white space
				$("#modal").click(function(e){
					if(e.target.id === $(this).attr("id") || e.target.className === "modal_close" || e.keyCode === 27){
						display_modal(0);
					}
				});				
				
				// Reside modal to fit current page height
				resize_modal();				
			});
		}
		else{
			
			// Hides modal wrapper then removes it
			$("#modal").fadeOut(100, function(){
				$("#modal").remove();				
			});
		}		
	}
});
