// JavaScript Document
var RequiredFields, AllFields, NumericFields;

window.addEvent('domready', function()
{
	RequiredFields = $$('.required');
	AllFields = $$('input, select');	
	
	if (window.location.pathname == "/removalsquote.asp")
	{	
		// Select Removal Month
		$('Removal_Month').value = new Date().getMonth() + 1;
		
		// Populate Removal Day
		PopulateDays();
		$('Removal_Day').value = new Date().getDate();
		
		// Populate Removal Year
		var Year = new Date().getFullYear();
		$('Removal_Year').remove(0);
		for (var i = Year; i <= Year + 10; i++)
		{
			var Dropdown = $('Removal_Year');
			var Option = document.createElement('option');
			Option.value = i;
			Option.text = i;
			Dropdown.options.add(Option);
		}
	}
});

// This function takes the string and trims leading and following spaces
function trim(str) {
	return str.replace(/^\s*|\s*$/g,'');
}

function SelectSingleNode(xmlDoc, elementPath)
{
	if(window.ActiveXObject)
	{
		return xmlDoc.selectSingleNode(elementPath);
	}
	else
	{
	   var xpe = new XPathEvaluator();
	   var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
	   var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
	   return results.singleNodeValue; 
	}
}

function GetAjax()
{
	var ajaxRequest;
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	
	return ajaxRequest;
}

function ValidateForm(thePage)
{
	var RequiredData = true, NumericData = true;
	var OffendingFields = "";
	
	// Cycle through required fields detecting if they have been entered or not
	RequiredFields.each(function(field, i)
	{
		if (trim(field.value) == "")
		{
			OffendingFields += field.name + "\r\n";
			RequiredData = false;
		}
	});
	
	// If not all required fields are entered, break the chain and alert, otherwise check validaty of data
	if (!RequiredData)
	{
		AlertError('Please enter all required fields', OffendingFields);
		return false;
	}
	
	ProcessForm(thePage);
}

function AlertError(Caption, OffendingFields)
{
	var message = Caption + "\r\nThe following fields have errors:\r\n\r\n" + OffendingFields.replace(/_/g, ' ');
	alert(message);			
}

function ProcessForm(thePage)
{
	var parameters = "";
	
	AllFields.each(function(field)
	{
		switch (field.name)
		{
			case "Full_Packing_Service":
			case "From_Lift":
			case "From_Access_Through_Windows":
			case "To_Lift":
			case "To_Access_Through_Windows":
				if (field.checked)
					parameters += field.name + "=" + field.value + "||";
			break;
			
			default:
				parameters += field.name + "=" + trim(field.value).replace(/ /g, '_') + "||";
			break;
		}
	});	
	
	// Remove final delimiter
	parameters = parameters.substring(0, parameters.length - 2);
	
	// Create AJAX Object
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			if (AJAX.responseText != "success")
			{
				alert("There was an error\r\n" + AJAX.responseText);
			}
			else
			{	
				document.location.href = "lounge.asp";
			}
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=adddetails&arguments=" + parameters);
}

function AddItem(ItemName, RoomName)
{
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			if (AJAX.responseText.indexOf("success") < 0)
			{
				alert("There was an error\r\n" + AJAX.responseText);	
			}
			else
			{
				var ReturnArray = AJAX.responseText.replace(/success\|\|/g, "");
				ReturnArray = ReturnArray.split("=");
				$(ReturnArray[0]).value = ReturnArray[1];
				
				UpdateInventory(RoomName);
			}
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=additem&arguments=ItemName=" + ItemName + "||RoomName=" + RoomName);
}

function UpdateInventory()
{
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			var XMLDoc = AJAX.responseXML.documentElement;
			
			if (XMLDoc.childNodes.length > 0)
			{
				for (var j = 0; j < XMLDoc.childNodes.length; j++)
				{
					var RoomName = XMLDoc.childNodes[j].nodeName;
					
					if (RoomName != "ContactDetails")
					{
						// Remove Children
						while ($(RoomName).hasChildNodes())
							$(RoomName).removeChild($(RoomName).firstChild);
		
						var RoomNode = SelectSingleNode(XMLDoc, RoomName);
						if (RoomNode.hasChildNodes())
						{
							for (var i = 0; i < RoomNode.childNodes.length; i++)
							{
								var ItemName = document.createTextNode(RoomNode.childNodes[i].nodeName.replace(/_/g, " "));
								var Quantity = document.createTextNode(RoomNode.childNodes[i].lastChild.nodeValue);
								var Remove = document.createElement('span');
								Remove.appendChild(document.createTextNode('Remove'));
								Remove.style.cursor = "pointer";
								Remove.style.fontSize = "80%";
								Remove.id = "Node" + RoomNode.childNodes[i].nodeName;
								Remove.onmouseover = function()
								{
									this.style.textDecoration = "underline";	
								}
								Remove.onmouseout = function()
								{
									this.style.textDecoration = "none";	
								}
								Remove.onclick = function()
								{
									RemoveItem(RoomName, this.id.replace(/Node/g, ''));
								}
								
								$(RoomName).appendChild(ItemName);
								$(RoomName).appendChild(document.createTextNode(' = '));
								$(RoomName).appendChild(Quantity);		
								$(RoomName).appendChild(document.createTextNode('   '))
								$(RoomName).appendChild(Remove);
								$(RoomName).appendChild(document.createElement('br'));
							}
						}
					}
				}
			}
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=getxml");
}

function RemoveItem(RoomName, ItemName)
{
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			PopulateForm(RoomName);	
			UpdateInventory(RoomName);
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=removeitem&arguments=ItemName=" + ItemName + "||RoomName=" + RoomName);
}

function PopulateForm(RoomName)
{
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			var XMLDoc = AJAX.responseXML.documentElement;
			
			if (XMLDoc.hasChildNodes())
			{
				var NodeList = SelectSingleNode(XMLDoc, RoomName);
				if (NodeList != null)
				{
					for (var i = 0; i < NodeList.childNodes.length; i++)
					{
						$(NodeList.childNodes[i].nodeName).value = NodeList.childNodes[i].lastChild.nodeValue;	
					}
				}
				
				UpdateInventory();
			}
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=getxml");
}

function DeliverQuote(theStatusObject)
{
	var AJAX = GetAjax();
	AJAX.onreadystatechange = function()
	{
		if (AJAX.readyState == 4)
		{
			switch (AJAX.responseText)
			{
				case "success":
					$(theStatusObject).innerHTML = "Your quote has been successfully delivered. Someone from our quotes department will contact you shortly";
					ClearQuote();
					break;
				case "nocontactdetails":
					if(confirm('No contact details have been entered. Click \'OK\' to enter them now, or click \'Cancel\'\r\nPlease note: Clicking \'Cancel\' will not send your quote to our team'))
						document.location.href = 'removalsquote.asp';
					break;
				default:
					alert(AJAX.responseText);
			}
		}
	}
	
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=deliverquote");
}

function ClearQuote()
{
	var AJAX = GetAjax();
		
	// Create send functions
	AJAX.open("POST", "quotebase.asp", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("command=clearxml");
}

function GetDaysInMonth(theMonth)
{
	var DaysInMonth = new Array(12);
    DaysInMonth[1] = 31;
	DaysInMonth[2] = 28;
    DaysInMonth[3] = 31;
    DaysInMonth[4] = 30;
    DaysInMonth[5] = 31;
    DaysInMonth[6] = 30;
    DaysInMonth[7] = 31;
    DaysInMonth[8] = 31;
    DaysInMonth[9] = 30;
    DaysInMonth[10] = 31;
    DaysInMonth[11] = 30;
    DaysInMonth[12] = 31;
	
	return DaysInMonth[theMonth];
}

// February has 29 days in any year evenly divisible by four
// EXCEPT for centurial years which are not also divisible by 400
function DaysInFebruary(year)
{
    return ((year % 4 == 0) && (!(year % 100 == 0)) || (year % 400 == 0) ? 29 : 28);
}

function PopulateDays()
{
	var Month = $('Removal_Month').value;
	var Year = $('Removal_Year').value;
	var Days;
	if (Month == 2)
		Days = DaysInFebruary(Year);
	else
		Days = GetDaysInMonth(Month);
		
	// Clear the Days
	$('Removal_Day').options.length = 0;
	
	// Populate Removal Day
	for (var i = 1; i <= Days; i++)
	{
		var Dropdown = $('Removal_Day');
		var Option = document.createElement('option');
		Option.value = i;
		Option.text = i;
		Dropdown.options.add(Option);
	}
}

