//This is happy script yay
var windowDrag = false;
var startCoordX = 0;
var startCoordY = 0;
var mouseCoordX = 0;
var mouseCoordY = 0;
var windowZIndex = 2; //Start it off a little above everything else

var rodentX = 0;
var rodentY = 0;

//Window setup, attaches the click functions to the titlebar and resize handles.
function setupWindows() {
	$(".titlebar").mousedown(function (e) { 
   		  if (!windowDrag)
		  {
		      //$(this).css("background-color", "yellow");
			  
			  //Set up the coords
			  mouseCoordX = e.pageX;
			  mouseCoordY = e.pageY;
			  var position = $(this).parent(".window").position();
			  startCoordX = position.left;
			  startCoordY = position.top;
			  
			  
			  //Give this window the "dragging" class so the mousemove function knows to adjust its position
			  $(this).parent(".window").addClass("moving");
			  
			  windowDrag = true;
			  
			  $(".maskLayerThing").show();
			  
			  //Move this window to the top of the stack, since we're not going to trigger it normally. '
		          $(this).parent(".window").css("z-index", windowZIndex++);
				  //$(this).children(".status").html($(this).parent(".window").css("z-index"));
		  }
		  return false;
   });
   
   
   
   $(".resizeArea").mousedown(function (e) { 
   		  if (!windowDrag)
		  {
		      $(this).css("background-color", "yellow");
			  
			  //Set up the coords
			  mouseCoordX = e.pageX;
			  mouseCoordY = e.pageY;
			  startCoordX = $(this).parent(".window").width();
			  startCoordY = $(this).parent(".window").height();
			  
			  //Give this window the "dragging" class so the mousemove function knows to adjust its position
			  $(this).parent(".window").addClass("resizing");
			  
			  windowDrag = true;
			  
			  $(".maskLayerThing").show();
			  
			  //Move this window to the top of the stack, since we're not going to trigger it normally. '
		          $(this).parent(".window").css("z-index", windowZIndex++);
			  
			  
		  }
		  return false;
   });
   
	$(".closeWindow").click(function (e) {
		$(this).parent().hide(300, function() {
			$(this).remove();
		});
	});
	
	$(".window").mousedown(function (e) {
		//Bring the window to the front.
		$(this).css("z-index", windowZIndex++);
	});
}

function updateMouseCoords(e)
{	
	if (!windowDrag)
	{
		
		$("#mouseCoords").html(e.clientX + ", " + e.clientY + "&nbsp;");
		rodentX = e.clientX; //This way, we keep *accurate* screen coordinates at all times, regardless of whatever else happens.
		rodentX = e.clientY;
		
		if (dragActive)
			updateDrag(e);
	}
}

$(document).ready(function(){
   $("body").css("background-color","#000000");
   
   $(".menuItem").click(function () {
   	$(this).children(".subMenu").toggle();
   });
   
   setupWindows();
   fixForms();
   
   //Spawn a news center at the start
   spawnNewWindow('?action=news', 'News and Updates', 'news');
});

//This catch-all function actually handles window movement
$(document).mousemove(function(e){
	//$("#mouseCoords").html(e.pageX + ", " + e.pageY);
	
	updateMouseCoords(e);
	
	//If there are any windows currently being dragged (as indicated by their extra CSS class)
	//then update their current position.
	if (windowDrag)
	{
		//Are we moving something? Update its position. Note: don't let it go outside the bounds of the window.
		//Note: the "magic number" 3 is the width of the border on both sides plus one extra padding pixel.
		$(".moving").css("left", 
			Math.max(0, 
				 Math.min($(document).width() - 3 - $(".moving").width(), startCoordX + (e.pageX - mouseCoordX)  )
			)
		);
		
		$(".moving").css("top",  
			Math.max(32, 
				 Math.min($(document).height() - 3 - $(".moving").height(), startCoordY + (e.pageY - mouseCoordY)  )
			)
		);
		
		var pos = $(".resizing").position();
		if (!pos) { 
			//This block shuts the browser up when there's no object with the .resizing class.
			//I know perfectly good and well that the passed "undefined" values aren't getting
			//used in that jQuery function, but the browser just doesn't seem to want to listen...
			pos = new Object();
			pos.left = 0; 
			pos.top = 0;
		}
		//Are we resizing the window? Let's handle that here too
		$(".resizing").css("width", 
			Math.max(50, 
				  Math.min($(document).width() - 3 - pos.left, startCoordX + (e.pageX - mouseCoordX)  )
			)
		);
		
		$(".resizing").css("height", 
			Math.max(50, 
				  Math.min($(document).height() - 3 - pos.top, startCoordY + (e.pageY - mouseCoordY)  )
			)
		);
		
	}
	
});

//This catch-all mouse release function disables any dragging action, finalizing the
//window's final position.
$(document).mouseup(function(e){
	windowDrag = false;
	
	//Remove the moving class(es) from *all* windows
	$(".window").removeClass("moving");
	$(".window").removeClass("resizing");
	
	$(".titlebar").css("background-color","green");
	$(".resizeArea").css("background-color","transparent");
	
	//Get rid of that mask thing
	$(".maskLayerThing").hide();
	
	//Kill any drag operations that are going on
	killDrag();
});

//The following functions are useful for spawning a new window.
//You can spawn a window with a string, or with a URL that its contents
//should be filled with. Warning: the contents should *not* contain
//html headers, although html is allowed of course.

function spawnNewWindow(url, title, type)
{
	//Does another window with that particular type already exist?
	//If so, just point it at the new link without actually spawning a new window.
	var cancelSpawn = false;
	if ( $('.windowType_'+type).length )
	{
		//Update the SRC attribute for the iframe contained within the window. This should effectively
		//reload the window too.
		$('.windowType_'+type).children("iframe").attr("src", "/window.php"+url);
	} else {


	//First, create the window
	$("body").append(
	"<div class='window size-"+type+"'> \
	<div class='resizeArea'></div> \
	<div class='titlebar'>"+title+" <span class='status'></span></div> \
	<div class='closeWindow'></div> \
	<div class='windowContent newspawn' id='"+type+"'><iframe class='windowFrame' name='"+type+"' style='position: absolute; left: 0px; top: 0px; bottom: 0px; right: 0px;' src='/window.php"+url+"' frameborder='0' width='100%' height='100%' scrolling='auto'></iframe></div> \
	</div>");
	
	//Move this window to the top of the stack
	$(".newspawn").parent(".window").css("z-index", windowZIndex++);
	
	//Set the data for this window's type, will be used to prevent copy windows being open later
	$(".newspawn").addClass("windowType_"+type);
	
	//Set up the window for moving and resizing and other stuff
	setupWindows();
	
	//Finally, remove the "newspawn" flag from the window, since it has content and we don't need work with it anymore.
	$(".newspawn").removeClass("newspawn");
	
	}
}

//Hmm. We need a form handler. This, given a form, should hook the submit button
//on that form and instead of submitting it the normal way, submit it through
//ajax and grab the results. It should then check the results for certain tags that
//indicate behavior differences, and if there are none it should spit the results
//back out in the same window.

function fixForms()
{
	$("input[type='submit']").click(function(e) {
		$(".throbber").show();
		//Gather the form data
		var stuff = $(this).parent("form").formToArray();
		
		//Submit the form, according to the attribute "action" in the form. Assume post.
		$.post(
		$(this).parent("form").attr("action"), //Grab the URL
		stuff, 
		yellBack, 
		"text");

		//??? - PROFIT  */
		
		return false;
	});
	
	
}

var loginTimerThing;

function yellBack(text, status) {
	$(".throbber").hide();
	//Check the login status.
	if (status == "success")
	{
		//alert(text);
		if (text == "normal" || text == "admin")
		{
			//alert("Glad to have you back, enjoy your stay. ^_^");
			$(".signUpButton").hide();
			$("#logInForm").hide();
			$(".userButton").show();
			$(".logInExtra").append("<a onclick='logUserOut();'>Log Out</a>");
			
			//Set up a login refresh timer
			loginTimerThing = window.setInterval(loginPing, 60000);
		}
		if (text == "admin")
		{
			$(".adminButton").show();
		}
		if (text == "failuser")
		{
			alert("You haven't verified your account yet. Check your email! More details at the Portal.");
			$("input[name='user']").attr("value", "");
			$("input[name='pass']").attr("value", "");
		}
		if (text == "failcombo")
		{
			alert("Either your username or password is incorrect. ");
			$("input[name='user']").attr("value", "");
			$("input[name='pass']").attr("value", "");
		}
		if (text == "join")
		{
			alert("Thanks for logging in. If you'd like to play DarkNova 4.0, just click Join top-right and you're all set.");
			$("#logInForm").hide();
			$(".logInExtra").append("<a onclick='joinUser();'>Join</a>");
			$(".logInExtra").append("&nbsp;&nbsp;-&nbsp;&nbsp;<a onclick='logUserOut();'>Log Out</a>");
			
		}
	} else {
		alert("Something went wrong in a weird way. Maybe try again, or the server may be down...");
	}
}

function joinUser()
{
	
	$.post(
		"/join.php", //Grab the URL
		{id: ""},
		joinYellBack, 
		"text");
}

function joinYellBack(text, status)
{
	//Confirm the joinage
	//alert("Join was...");
	if (status == "success")
	{
		if (text == "fail")
		{
			window.alert("It failed for some reason. Weird. Best to *refresh*.");
		}
		
		if (text == "success")
		{
			window.alert("Thanks for joining DarkNova 4.0!");
			$(".signUpButton").hide();
			$("#logInForm").hide();
			$(".userButton").show();
			$(".logInExtra").empty();
			$(".logInExtra").append("<a onclick='logUserOut();'>Log Out</a>");		
			
			//Set up a login refresh timer
			loginTimerThing = window.setInterval(loginPing, 60000);	
		}
	} else {
		window.alert("The join action failed for a server related issue. Maybe we're down? Try again later...");
	}
	
}

function loginPing()
{
	//Grab the results of the "loginCheck" page. Essentially, calling this page will return the current login status of the users session.
	//Based on the results, we determine if the session is still active. Ideally it should always be active if the page is still open,
	//but in case the user changes their password or something, this will cancel out any sessions that are still active.
	
	//As an added bonus, checking the loginCheck every few minutes will auto-renew the session, which should keep a user with the window open
	//logged in until they close the window.
	$(".throbber").show();
	
	$.ajax({
	   type: "GET",
	   url: "/ping_status.php",
	   success: function(msg){
	     $(".throbber").hide();
	     //Check the msg returned. If its blank or "loggedout", log them out. If not, do other things.
	     if (msg == "" || msg == "loggedout")
	     {
	     	logUserOut();	     	
	     } else {
	     	
	     }
	     
	   },
	   error: function(msg){
	     //If this happens, the users browser failed to get the page. Most likely the internet is lost. Sad.
	     //In any case, log the client out.
	     logUserOut();
	   }
	 });

}

function logUserOut()
{
	//...*sigh* do I really need to comment this?
	$(".throbber").hide();
	alert("You have been logged out by the system.");
	$(".userButton").hide();
	$(".signUpButton").show();
	$(".adminButton").hide();
	$("#logInForm").show();
	$(".logInExtra").empty();
	
	clearInterval(loginTimerThing);
}

var dragActive = false;
var dragData = "";
var dragClass = ""; //Used to store the iFrame that the drag was dropped into.

//Happy Drag+Drop Functions. Yay!
function startDrag(data)
{
	//To test, "data" is just the color to "drop" onto the location. It's a string representing a hex color.
	dragData = data;
	dragActive = true;
	//Display the drag indicator, but show it offscreen. The drag updater will initialize it to the correct location.
	$(".dragHolder").css("top", "-100px");
	$(".dragHolder").css("left", "-100px");
	$(".dragHolder").css("background-color", data);
	$(".dragHolder").show();
	//Show the mask, so all the mouse events during the drag happen in the parent frame
	$(".maskLayerThing").show();
}

var dragLocalX = 42;
var dragLocalY = 42;
function updateDrag(e)
{
	//Offset, so we get the dragged object in the middle
	//dragClass = classType;
	
	//The big piddle: we don't know what the mouse is over, so we get to figure it out manually.
	//We need to know if the mouse is inside an iframe, so we need to position check and account
	//for z-index and all. *fun*.
	
	dragClass = "";
	var currentZIndex = -1;
	var coordsX = 42;
	var coordsY = 42;
	
	$(".windowContent").each(function () {
		var position = $(this).offset();
		var width = $(this).width();
		var height = $(this).height();
		if (
		e.clientX >= position.left && e.clientX <= position.left + width && 
		e.clientY >= position.top  && e.clientY <= position.top  + height && 
		parseInt($(this).parent(".window").css("z-index")) > parseInt(currentZIndex))
		{
			dragClass = $(this).attr("id");
			currentZIndex = $(this).parent(".window").css("z-index");
			
			//Now, for use in a second, store the current mousecoords relative to the iFrame.
			coordsX = e.clientX - position.left;
			coordsY = e.clientY - position.top;
		}
    });
	
	//Given the current class name, we need to update the "drop" coordinates for the contained iFrame.
	//UPDATE: Don't store them directly, just remember them locally
	dragLocalX = coordsX;
	dragLocalY = coordsY;
	
	e.clientX -= 25;
	e.clientY -= 25;
	$(".dragHolder").css("left", e.clientX+"px");
	$(".dragHolder").css("top", e.clientY+"px");
	$(".maskLayerThing").show();
}

function killDrag()
{
	$(".dragHolder").hide(); //Pretty simple, no?
	if (dragActive) {
		dragActive = false;
		//alert(dragClass);
		if (dragClass != "")
		try {
			window.frames[dragClass].takeDrop(dragData, dragLocalX, dragLocalY);
		} catch(err) {
			alert("Something strange happened...");	
		}
	}
}
