function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function get_browser()
{
	if(document.all)
	{
		return "IE";
	}
	else if(document.getElementById)
	{
		return "NN";
	}
}

// get the browser type
var browser = get_browser();

function getXmlHttpRequestObject()
{
	if (window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		return false;
	}
}

var xml_request = getXmlHttpRequestObject();

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function()
{
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function()
{
	return this.replace(/\s+$/,"");
}

function slash_single_quote(str)
{
	str = str.replace(/\'/g, "\\'");

	return str;
}

function get_element_position(element)
{
	var top = 0;
	var left = 0;

	if (element.offsetParent)
	{
		left = element.offsetLeft;
		top = element.offsetTop;

		while (element = element.offsetParent)
		{
			left += element.offsetLeft
			top += element.offsetTop
		}
	}

	return [top, left];
}

function load_xml_from_string(string)
{
	// code for IE
	if (window.ActiveXObject)
	{
		var doc = new ActiveXObject("Microsoft.XMLDOM");
		doc.async = "false";
		doc.loadXML(string);
	}
	// code for Mozilla, Firefox, Opera, etc.
	else
	{
		var parser = new DOMParser();
		var doc = parser.parseFromString(string, "text/xml");
	}
	
	return doc;
}

var ModalDialogWindow;
var ModalDialogInterval;
var ModalDialog = new Object;

ModalDialog.value = '';
ModalDialog.eventhandler = '';

function refresh_page()
{
	document.location.replace(document.location.href);
}

function ModalDialogMaintainFocus()
{
	try
	{
		if (ModalDialogWindow.closed)
		{
			window.clearInterval(ModalDialogInterval);
			eval(ModalDialog.eventhandler);
			return;
		}

//			ModalDialogWindow.focus();
	}
	catch (everything)
	{

	}
}

function ModalDialogRemoveWatch()
{
	ModalDialog.value = '';
	ModalDialog.eventhandler = '';
}

function ModalDialogShow(page_to_show, do_refresh)
{
	var do_refresh = (do_refresh == null) ? true : do_refresh;

	ModalDialogRemoveWatch();

	if(do_refresh === true)
	{
		ModalDialog.eventhandler = "refresh_page()";
	}

	var args='width=800,height=610,left=325,top=300,toolbar=0,';
	args += 'location=0,status=0,menubar=0,scrollbars=1,resizable=0'; 

	ModalDialogWindow=window.open("","",args);
	ModalDialogWindow.document.open('');
	ModalDialogWindow.document.location = page_to_show;
	ModalDialogWindow.document.close();
	ModalDialogWindow.focus();
	ModalDialogInterval = window.setInterval("ModalDialogMaintainFocus()", 5);
}

function get_cursor_positions(event)
{
	var x, y;

	if(browser == "IE")
	{
		x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	else if(browser == "NN")
	{
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	
	return new Array(x, y)
}

function hide_window(item_id)
{
	if(document.getElementById(item_id))
	{
		document.getElementById(item_id).style.visibility = "hidden";
	}
}

function show_window(event, item_id)
{
	var cursor_position = get_cursor_positions(event);

	if(document.getElementById(item_id))
	{
		var the_window = document.getElementById(item_id);

		the_window.style.visibility = "visible";
		the_window.style.left = cursor_position[0] + "px";
		the_window.style.top = cursor_position[1] + 20 + "px";
	}
}

function hide_help(destination_id)
{
	if(document.getElementById(destination_id))
	{
		document.getElementById(destination_id).innerHTML = "";
	}
}

function show_help(item_id, destination_id)
{
	if(document.getElementById(item_id) && document.getElementById(destination_id))
	{
		document.getElementById(destination_id).innerHTML = document.getElementById(item_id).innerHTML;
	}
}

function find_address()
{
	// get the postcode
	var postcode = document.getElementById('search_postcode').value;

	if(valid_postcode(postcode, false, true) === false)
	{
		alert("Please enter a valid postcode to search for an address.");
		document.getElementById('search_postcode').focus();
	}
	else
	{
		get_postcode_addresses(postcode);
	}
}

function get_postcode_addresses(postcode)
{
	if (xml_request.readyState == 4 || xml_request.readyState == 0)
	{
		xml_request.open("GET", "/find_address.php?postcode=" + escape(postcode), false);
		xml_request.send(null);

		// get the address list
		var address_list = document.getElementById('address_list');

		// get the xml document from the returned xml string
		var doc = xml_request.responseXML;

		var root_node = doc.documentElement;
		var child_nodes = root_node.childNodes;

		// check to see if any addresses have been found
		var found_addresses = false;

		for(var i = 0; i < child_nodes.length; i++)
		{
			var node = child_nodes[i];

			if(node.nodeType == 1)
			{
				found_addresses = true;
				break;
			}
		}

		if(found_addresses === false)
		{
			alert("The postcode you entered did not produce any results. Please fill in the address form manually or enter an alternate postcode.");
		}
		else
		{
			// empty the current list
			address_list.options.length = 0;
	
			// add a "please select address" option as default selected
			address_list.options[0] = new Option("Please select an address...", "");
	
			// loop through all the addresses
			var options_count = 1;
	
			for(var i = 0; i < child_nodes.length; i++)
			{
				var node = child_nodes[i];
	
				if(node.nodeType == 1)
				{
					var id = node.getElementsByTagName('id');
					var description = node.getElementsByTagName('description');
	
					// add an entry to the address list
					address_list.options[options_count] = new Option(description[0].firstChild.nodeValue, id[0].firstChild.nodeValue);
					options_count++;
				}
			}
			
			alert("Found "+(options_count - 1)+" addresses in the selected postcode. Please select one from the list to fill the address form.");
		}
	}
}

function select_address()
{
	// get the currently selected address
	var current_address = document.getElementById('address_list').selectedIndex;
	var address_id = document.getElementById('address_list').options[current_address].value;
	
	if(address_id != "")
	{	
		get_address_from_id(address_id);
	}
}

function clear_address_fields()
{
	var fields_to_clear = new Array("building_name_or_number", "sub_building_name", 
									"thoroughfare_name_descriptor", "dependent_locality", 
									"post_town", "county", "postcode");

	for(var i = 0; i < fields_to_clear.length; i++)
	{
		var current_field = fields_to_clear[i];
		if(document.getElementById(current_field))
		{
			document.getElementById(current_field).value = "";
		}
	}
}

function get_address_from_id(address_id)
{
	if (xml_request.readyState == 4 || xml_request.readyState == 0)
	{
		xml_request.open("GET", "/get_address.php?address_id=" + escape(address_id), false);
		xml_request.send(null);

		var doc = xml_request.responseXML;

		var root_node = doc.documentElement;
		var child_nodes = root_node.childNodes;

		// clear the current address fields
		clear_address_fields();

		// loop through all the child nodes and replace the content into the fields on the page
		for(var i = 0; i < child_nodes.length; i++)
		{
			var node = child_nodes[i];

			if(node.nodeType == 1)
			{
				if(node.nodeName == "id")
				{
					document.getElementById("paf_reference").value = node.firstChild.nodeValue;
				}
				else if(node.nodeName == "thoroughfare_name")
				{
					document.getElementById("thoroughfare_name_descriptor").value = node.firstChild.nodeValue;
				}
				else if(node.nodeName == "thoroughfare_descriptor")
				{
					document.getElementById("thoroughfare_name_descriptor").value += " " + node.firstChild.nodeValue;
				}
				else if(node.nodeName == "organisation_name")
				{
					var organisation_name = node.firstChild.nodeValue;
				}
				else
				{
					if(document.getElementById(node.nodeName))
					{
						document.getElementById(node.nodeName).value = node.firstChild.nodeValue;
					}
				}
			}
		}
		
		// check if the paon has been filled in...if not then fill with organisation name
		if(document.getElementById('building_name'))
		{
			if(document.getElementById('building_name').value == "")
			{
				document.getElementById('building_name').value = organisation_name;
			}
		}

		// check if town is London and the county is empty
		if(document.getElementById('post_town'))
		{
			if(document.getElementById('post_town').value == "London")
			{
				document.getElementById('county').value = "London";
			}
		}

		// check if town is Bristol
		if(document.getElementById('post_town'))
		{
			if(document.getElementById('post_town').value == "Bristol")
			{
				document.getElementById('county').value = "Bristol";
			}
		}
	}
}

function renew_session()
{
	if (xml_request.readyState == 4 || xml_request.readyState == 0) 
	{
		xml_request.open("POST", "renew_session.php", true);
		xml_request.onreadystatechange = function()
		{
		};
		xml_request.send(null);
	}
}

// renew the session every 10 minutes
var renew_session_timer = setInterval("renew_session()", 100000);



//temporary function to not break normal add tenancy form

if (typeof disable_add_button != "function") {
	function disable_add_button(){
	
	}
}


function check_tenancy(tenancy_id, element){
	inputs = document.getElementsByTagName('input');
	
	for (i = 0; i < inputs.length; i++) {
		input = inputs[i];
		
		if (input.type == "checkbox" && input.name == tenancy_id) {
			if (input.checked) {
				input.checked = false;
				apply_element_style(element, "fontWeight", "");
			}
			else {
				input.checked = true;
				apply_element_style(element, "fontWeight", "bolder");
			}
		}
	}
}

function highlight(element, highlighting, color){
	if (highlighting == true) {
		var new_color = color;
	}
	else {
		var new_color = "";
	}
	
	children = element.getElementsByTagName('td');
	for (i = 0; i < children.length; i++) {
		child = children[i];
		child.style.backgroundColor = new_color;
	}
}


function apply_element_style(element, style, value){
	if(element){
		eval("element.style."+style+" = '"+value+"'");
	}
}

function unix_timestamp(date){
	date = date.toString();
	
	if (date.indexOf("-") > -1) {
		date = date.split("-");
		date_object = new Date(Date.UTC(date[0], date[1]-1, date[2]));
	}
	else if (date.indexOf("/") > -1) {
		date = date.split("/");
		date_object = new Date(Date.UTC(date[2], date[1]-1, date[0]));
	}
	else {
		alert(false)
	}
	
	
	timestamp = (date_object.getTime() / 1000.0);
	
	return timestamp;
}

function unix_to_human(timestamp){
	var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
		
	start_date_obj = new Date(timestamp*1000)
	d = start_date_obj.getDate();
	month = months[start_date_obj.getMonth()];
	year = start_date_obj.getFullYear();
	
	if (d == 1 || d == 21 || d == 31) {
		sup = "st";
	}
	else if (d == 2 || d == 22) {
		sup = "nd";
	}
	else if (d == 3 || d == 23) {
		sup = "rd";
	}
	else {
		sup = "th";
	}
	
	human_date = d + sup + " " + month + " " + year;
	
	return human_date;
}
