/*
 * Draconigena - search tool for A Game of Thrones
 * Copyright (C) 2006
 * Michael Isaacson (michael@redlightning.net)
 * Red Lighting Graphics (http://www.redlightning.net)
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 *
 */
 
//Submit forms with text links, not buttons
function submitform(formname)
{
	if(formname == "login")
	{
  		document.loginform.submit();
  	}
}

function setStatus(display, message, autohide)
{
	if(display == null)	
	{
		display = 'none';
		message = 'None.';
		autohide = false;
	}
	
	document.getElementById('statusblock').style.display = display;
	document.getElementById('statusmessage').innerHTML = message;
	
	if(autohide == true)
	{
		setTimeout('setStatus()', 5000);
	}
}
function setWindowStatus(message, autohide)
{
	if (message == null)
	{ 
		message  = "Done.";
		autohide = false;
	}
		
	window.status = message;
	
	if(autohide == true)
	{
		setTimeout('setWindowStatus()', 5000);
	}
}

function login()
{
	var query = "login.php?name=" + document.getElementById('username').value + "\&pass=" + document.getElementById('password').value;
	request.open("GET", query, true);
	request.onreadystatechange = handleHttpResponse;
	request.send(null);	
}

function logout()
{
	request.open("GET", "logout.php", true);
	request.onreadystatechange = handleHttpResponse;
	request.send(null);
}

function updateCollection(card_num)
{
	var want       = "X";
	var count      = 0;
	var field      = "";
	var want_field = "";
	
	//What page and mode are we in?
	if(document.getElementById('pageid').innerHTML == "detail")
	{
		field      = 'collection_have_input';
		want_field = 'collection_want_input';
		count = document.getElementById(field).value;
		want  = document.getElementById(want_field).value;
	}
	else if(document.getElementById('checklist').checked == true)
	{
		field = 'check_collection_input' + card_num;
		count = document.getElementById(field).value;
	}
	else
	{
		field = 'spoiler_collection_input' + card_num;
		count = document.getElementById(field).value;
	}
	
	//Check the values
	if(parseInt(count) < 0 || isNaN(parseInt(count)) == true && count.length > 0)
	{
		document.getElementById(field).value = "";
	}
	if(want !== "X")
	{
		if(parseInt(want) < 0 || isNaN(parseInt(want)) == true && want.length > 0)
		{
				document.getElementById(want_field).value = "";
		}
	}
	if (count.length == 0)
	{
		count = 0;
	}
	if (want.length == 0)
	{
		want = 0;
	}
		
	else 
	{
		//Call php script to update the collection		
		var query = "collection_update.php?card=" + card_num + "&have=" + count + "&want=" + want;
		request.open("GET", query, true);
		request.onreadystatechange = handleHttpResponse;
     	request.send(null);
     }
}


//Update the counts for a card in the active deck
function updateDeck(card_num)
{
	var field_prefix;

	//Are we in checklist or spoiler mode?
	if(document.getElementById('checklist').checked == true)
	{
		field_prefix = 'check_deck_input';
	}
	else
	{
		field_prefix = 'spoiler_deck_input';
	}
	if(document.getElementById('pageid').innerHTML == "decks_view_active" || document.getElementById('pageid').innerHTML == "detail")
	{
		field_prefix = 'deck_input';
	}

	//Get the new value
	var field = field_prefix + card_num;
	var val = document.getElementById(field).value;
	
	if(parseInt(val) < 0 || parseInt(val) > 4 || isNaN(parseInt(val)) == true && val.length > 0)
	{
		document.getElementById(field).value = "";
	}
	else 
	{
		if (val.length == 0)
		{
			val = 0;
		}
		var query = "decks_update.php?card=" + card_num + "&count=" + val;
		request.open("GET", query, true);
		request.onreadystatechange = handleHttpResponse;
     	request.send(null);
     }
}

//Save the active deck for the first time
function saveDeck(deckid)
{
	if(deckid == null)
	{
		//Deck is not yet saved, so save it
		name  = document.getElementById('deckname').value;
		house = document.getElementById('house').options[document.getElementById('house').selectedIndex].value;
		

		
		var query = "decks_save_active.php?deckname=" + name + "&house=" + house;
		request.open("GET", query, true);
		request.onreadystatechange = handleHttpResponse;
     	request.send(null);
	}
	else
	{
		updateDeckProperty("name");
	}
}

//Updates deck name, agena, houses, etc.
function updateDeckProperty(field)
{
	//Get the value from the field or listbox based on field
	switch(field)
	{
		case "house" :
			value = document.getElementById('house').options[document.getElementById('house').selectedIndex].value;
			break;
		case "house2" :
			value = document.getElementById('house2').options[document.getElementById('house2').selectedIndex].value;
			break;
		case "agenda" :
			value = document.getElementById('agenda').options[document.getElementById('agenda').selectedIndex].value;
			//Second house is enabled only on Treaty agenda
			if(value == "Treaty")
			{
				document.getElementById('house2').disabled = false;
			}
			else
			{
				document.getElementById('house2').disabled = true;
				document.getElementById('house2').selectedIndex = 0;
			}
			break;
		case "name" :
			value = document.getElementById('deckname').value;
			break;
	}
	
	var query = "decks_update_property.php?field=" + field + "&value=" + value;
	request.open("GET", query, true);
	request.onreadystatechange = handleHttpResponse;
    	request.send(null);
}

//Clear the session of deck information
function newActiveDeck(deckid)
{
	//No deck id, so this deck hasn't been saved yet
	if(deckid == null)
	{
		var answer = confirm("Deck will be lost! Clear deck data?");
		if(answer)
		{
			window.location = "http://agot.redlightning.net/decks_clear_active.php";
		}
	}
	else
	{
		window.location = "http://agot.redlightning.net/decks_clear_active.php";
	}
}

//Go go gadget AJAX!
function getHTTPObject()
{
	var xmlHttpReq = false;

	// Mozilla/Safari
	if (window.XMLHttpRequest)
	{
		xmlHttpReq = new XMLHttpRequest();
		xmlHttpReq.overrideMimeType('text/xml');
	}
	// IE
	else if (window.ActiveXObject)
	{
		try 
		{
			xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) 
		{
	  		try 
	  		{
				xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (E) 
			{
	   			xmlHttpReq = false;
	  		}
 		}
	}
	return xmlHttpReq;
}

//AJAX Processing
function handleHttpResponse()
{
	if (request.readyState == 4)
	{
		var xmlDoc = request.responseXML;

		//Damn IE! Convert the response text into an XML document
		if(xmlDoc.documentElement == null) 
		{
			xmlDoc.async = "false";
			xmlDoc.loadXML(request.responseText);
		}

		var markers = xmlDoc.documentElement.getElementsByTagName("result"); 
		for (var i = 0; i < markers.length; i++)
		{
			if(markers[i].getAttribute("name") == "login")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					document.getElementById('loginblock').style.display     = 'none';
					document.getElementById('loginerror').style.display     = 'none';
					document.getElementById('loggedinlinks').style.display  = 'block';
					document.getElementById('limittocollectionblock').style.display    = 'block';
					document.getElementById('logoutlink').style.display    = 'block';
				}
				else
				{
					document.getElementById('loginerror').style.display = 'block';
				}
			}
			if(markers[i].getAttribute("name") == "logout")
			{
				document.getElementById('loginblock').style.display     = 'block';
				document.getElementById('loginerror').style.display     = 'none';
				document.getElementById('loggedinlinks').style.display = 'none';
				document.getElementById('limittocollectionblock').style.display    = 'none';
				document.getElementById('logoutlink').style.display    = 'none';
			}
			if(markers[i].getAttribute("name") == "updatecollection")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					setWindowStatus("Collection Updated.", true);
				}
				
				if(markers[i].getAttribute("value") == "0")
				{
					setStatus('block', '<span style="color:red;">There was a problem!</span><br/>' + markers[i].getAttribute("message"), true);
				}
			}
			if(markers[i].getAttribute("name") == "updatedeck")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					setWindowStatus("Deck Updated.", true);
					document.getElementById("charactercount").innerHTML  = markers[i].getAttribute("characters");
					document.getElementById("locationcount").innerHTML   = markers[i].getAttribute("locations");
					document.getElementById("attachmentcount").innerHTML = markers[i].getAttribute("attachments");
					document.getElementById("eventcount").innerHTML      = markers[i].getAttribute("events");
					document.getElementById("plotcount").innerHTML       = markers[i].getAttribute("plots");
					document.getElementById("totalcount").innerHTML      = markers[i].getAttribute("total");
				}
				if(markers[i].getAttribute("value") == "0")
				{
					setStatus('block', '<span style="color:red;">There was a problem!</span><br/>' + markers[i].getAttribute("message"), true);
				}
			}
			if(markers[i].getAttribute("name") == "updatedeckproperty")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					setWindowStatus("Deck Updated.", true);
				}
			}
			if(markers[i].getAttribute("name") == "updatemessage")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					if(markers[i].getAttribute("status") == "R")
					{
						document.getElementById('status' + markers[i].getAttribute("message_id")).innerHTML = "Read";
					}
					else
					{
						document.getElementById('status' + markers[i].getAttribute("message_id")).innerHTML = "Replied";
					}
				}
			}
			if(markers[i].getAttribute("name") == "sendmessage")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					setStatus('block', 'Message Sent!', true);
					if(markers[i].getAttribute("messageid") != "trade_request")
					{
						updateMessageStatus(markers[i].getAttribute("messageid"), "E");
					
						//New Messsage block and fields
						document.getElementById('composemessage').style.display = "none";
						document.getElementById('newto').value    = "";
						document.getElementById('newtitle').value = "";
						document.getElementById('newbody').value  = "";
					}
				}
				else
				{
					setStatus('block', 'Error sending message!<br />' + markers[i].getAttribute("message"), true);
				}
			}
			if(markers[i].getAttribute("name") == "deletemessage")
			{
				if(markers[i].getAttribute("value") == "1")
				{
					document.getElementById('row' + markers[i].getAttribute("messageid")).style.display = 'none';
				}
				else
				{
					setStatus('block', 'Error deleting message!', true);
				}
			}
		}
	}
}