/**
 * @author Sean Johnstone
 */
function SearchFleet(ref, ref2) {
	for(var i = 0; i < User.Fleet.length; i++)
	   if((User.Fleet[i].ident1orig == ref) && (User.Fleet[i].ident2orig == ref2))
	     return i;
	return -1;
}

var Resource = {
	WorkHTML: ""
}
var User = {
	Username: "",
	Authorisation: "",
	Ability: "",
	Contracts: [],
	Accounts: "",
	EmailAddress: "",
	FiledAs: "",
	Fleet: [],
	SignedIn: false,
	RebuildMenu: function() {
		Resource.WorkHTML = "<ul id=\"MenuOptions\">";
		if (User.SignedIn) {
			Resource.WorkHTML += "<li><a href=\"javascript:User.ViewAccount();\">My Account</a></li>" +
								"<li><a href=\"javascript:User.SignOut();\">Sign Out</a></li>";
			Resource.WorkHTML += "</ul>";			
			Resource.WorkHTML += "<ul id=\"MenuSections\">";
			// Functional Components
			Resource.WorkHTML += "<li><a href=\"javascript:User.ShowFleet();\">My Fleet</a></li>";
			if (User.Ability.indexOf(',useradministration,', 0) >= 0) {
				Resource.WorkHTML += "<li><a href=\"javascript:User.Abilities.ShowUsers();\">Users</a></li>";
			}
			if (User.Ability.indexOf(',maintenance,', 0) >= 0) {
				Resource.WorkHTML += "<li><a href=\"javascript:User.Abilities.MaintenanceDue();\">eServ</a></li>";
			}
		} else {
			Resource.WorkHTML += "<li><a href=\"javascript:User.ShowSignIn();\">Sign In</a></li>" +
								"<li><a href=\"javascript:User.ShowContact();\">Contact Us</a></li>";
			Resource.WorkHTML += "</ul>";
			Resource.WorkHTML += "<ul id=\"MenuSections\">";
			Resource.WorkHTML += "<li><em>Sign In to use actions</em></li>";
		}
		Resource.WorkHTML += "</ul>";
		
		$('#Menu').html(Resource.WorkHTML);
	},
	ShowSignIn: function() {
		User.Interface.Popup(
					"Sign In",
					"<div class=\"error\" style=\"display:none\" />" +
					"<label for=\"ddSIUN\">Username (or email address)</label>" + 
					"<div><input type=\"text\" id=\"ddSIUN\" value=\"\" /></div>" +
					"<label for=\"ddSIPW\">Password</label>" + 
					"<div><input type=\"password\" id=\"ddSIPW\" value=\"\" /></div>",
					"<a href=\"javascript:User.SignIn();\" class=\"button\"><span class=\"icon-signin\"></span> Sign In</a><a href=\"javascript:User.Interface.ClosePopup();\">Cancel</a>",
					300, 200
		);
		$('#ddSIUN').get(0).focus();
	},
	SignOut: function() {
		window.location.reload();
	},
	SignIn: function() {
		var username = $('#ddSIUN').val();
		var password = $('#ddSIPW').val();
		
		$.getJSON("v2/signin.php", {"User": username, "Pass": password, "rnd": (Math.random() * 150000)}, function(data) {
			if (data.status == "success") {
				User.Interface.ClosePopup();
				User.Username = data.Username;
				User.Ability = data.Abilities;
				User.Contracts = data.Contracts;
				User.Accounts = data.Accounts;
				User.EmailAddress = data.EmailAddress;
				User.SignedIn = true;
				User.FiledAs = data.FiledAs;
				User.Authorisation = data.Authorisation;
				$('#SignInButton').fadeOut(300);
				$('<li>Signed in as <strong>' + data.FiledAs + '</strong>. <a href="javascript:User.SignOut();">Sign Out</a></li>').appendTo('#MenuLinks');
				User.RebuildMenu();
				User.FetchFleet();
			} else {
				$('#Popup').find(".error:first").css("display", "none").html("There was an error signing you in. Please try again.").fadeIn("slow");
			}
		});
	},
	ShowContact: function() {
		var rHtml = "";
		rHtml = 
			"<h2>Postal address</h2>" +
			"<p>LD Contract Management<br />Unit 1<br />Thurrock Trade Park<br />Oliver Road<br />West Thurrock<br />RM20 3ED</p>" +
			"<h2>Give us a call</h2>" +
			"<p><strong>LD Contract Management</strong>: 08000 121 455</p>" +
			"<p><strong>PartsServe</strong>: 0800 111 4145</p>" +
			"<h2>Send us an email</h2>" +
			"<label for=\"ddEmail\">Email Address</label>" +
			"<div><input type=\"text\" id=\"ddEmail\" /></div>" +
			"<label for=\"ddSubject\">Subject</label>" +
			"<div><input type=\"text\" id=\"ddSubject\" /></div>" +
			"<label for=\"ddMessage\">Message Body</label>" +
			"<div><textarea id=\"ddMessage\" rows=\"7\" cols=\"24\"></textarea></div>";
		User.Interface.Popup("Contact Us", rHtml, 
					"<a href=\"javascript:User.SubmitContact();\" class=\"button\">Send</a><a href=\"javascript:User.Interface.ClosePopup();\">Cancel</a>",
					450, 400);
		$('#ddEmail').val(User.EmailAddress);
	},
	ContractFleet: {
		Requested: 0,
		Received: 0
	},
	GetContractFleet: function(ContractID) {
		$.getJSON("r.php", {r: "ContractFleet", contract: ContractID.pop() + "", rn: (Math.random() * (12000 * (ContractID.length)))}, function (data, text) {
			$.each(data, function(ID, Item) {
				if (Item.ID != "false") {
					Item.ident1orig = Item.ident1;
					Item.ident2orig = Item.ident2;
					
					var oL = Item.ident2.replace("  ", " ").replace("  ", " ").split(" ");
					var oLoc = "";
					if (oL.length > 1) {
						$.each(oL, function(i, item) {
							if (i > 0) {
								oLoc += item + " ";
							} else {
								Item.ident2 = item;
							}
						});
					} else {
						oLoc = "n/a";
					}
					Item.operatingLocation = oLoc.toUpperCase();
					User.Fleet.push(Item)
				}
			});
			User.ContractFleet.Received += 1;
			$('#ls2monitor').css("width", Math.round((User.ContractFleet.Received / User.ContractFleet.Requested) * 250) + "px");
			// $('#ls2monitor').html(User.ContractFleet.Received + " / " + User.ContractFleet.Requested + "(" + User.Fleet.length + " units)");
			if (ContractID.length > 0) {
				User.GetContractFleet(ContractID);
			}
			if (User.ContractFleet.Received == User.ContractFleet.Requested) {
				User.Fleet.sort(function(a, b) {
					if (a.equipment == "true") {
						if (a.ident1 < b.ident1) {
							return -1;
						} else if (a.ident1 > b.ident1) {
							return 1;
						} else if (a.ident2 < b.ident2) {
							return -1;
						} else {
							return 1;
						}
					} else {
						if (a.ident2 < b.ident2) {
							return -1;
						} else if (a.ident2 > b.ident2) {
							return 1;
						} else if (a.ident1 < b.ident1) {
							return -1;
						} else {
							return 1;
						}
					}
				});	
				window.setTimeout(function() {
					User.Interface.ClosePopup();
					}, 500);
			    User.ShowFleet();
			}
		});
	},
	FetchFleet: function() {
		// Collect fleet units for this customer/account/contract (if LDAM, collect currently selected customer's fleet
		var ContractsToLoad = [];
		$.each(User.Contracts, function(i, item) {
			ContractsToLoad.push(item);
		});
		window.setTimeout( function() {
			User.Interface.Popup("Signed In", '<div style="text-align:center"><h3>You have successfully Signed In.</h3><p>Please wait while we load your fleet from our servers...</p><div id="LoadState"><div id="ls2monitor" /></div></div>', "", 300, 250);
			}, 1000);
		User.ContractFleet.Received = 0;
		User.ContractFleet.Requested = User.Contracts.length;
		User.GetContractFleet(ContractsToLoad);
	},
	ShowFleet: function() {
		// alert("Showing Fleet");
		$('#Content').html("<h1>Your Fleet</h1><p>Your entire managed fleet is shown below. To filter this list, please enter a search term in the textbox at the top of the column. To view more detail on a fleet item, please click on it.</p><p>If you would like more units managed, please contact our electronic services team though the contact us link at the top of the page.</p>");
		$('<table cellspacing="0" cellpadding="0" id="tblContentFleet" class="FleetTable" />').appendTo('#Content');
		$('<tr><th>' + User.Fleet['0'].ident1t + '</th><th>' + User.Fleet[1].ident2t + '</th><th>Contract</th><th>Operating Location</th><th>Type</th><th>Notes</th></tr>').appendTo('#tblContentFleet');
		$('<tr><td><input type="text" class="filterable" filter="ident1" value="" /></td><td><input type="text" class="filterable" filter="ident2" value="" /></td><td><input type="text" class="filterable" filter="contract" value="" /></td><td><input type="text" class="filterable" filter="location" value="" /></td><td><input type="text" class="filterable" filter="type" value="" /></td><td> </td></tr>').appendTo('#tblContentFleet');
		// alert($('#tblContentFleet').html());
		$.each(User.Fleet, function(i, item) {
			if (item) {
				item.type += "n/a";
				$('<tr selectable="true" fleetId="' + item.ID + '" fleetIdx="' + i + '" isequipment="' + item.equipment + '"><td class="ident1">' + item.ident1 + '</td>' +
				'<td class="ident2">' +
				item.ident2 +
				'</td>' +
				'<td class="contract">' +
				item.contract +
				'</td>' +
				'<td class="location">' +
				item.operatingLocation +
				'</td>' +
				'<td class="type">' +
				item.equiptype +
				'</td><td>' + item.Notes + ' ' +
				'</td></tr>').appendTo('#tblContentFleet');
			}
		});
		$('#tblContentFleet tr[selectable=true]').click(function() {
			var idx = $(this).attr('fleetIdx');
			User.ShowFleetUnit(idx);
		});
		$('#tblContentFleet .filterable').keyup(function() {
            var thisval = $(this).val();
            $('#tblContentFleet input.filterable').val("");
            $(this).val(thisval);
            $("#tblContentFleet td." + $(this).attr("filter") + ":contains('" + $(this).val() + "')").parent("tr").css("display", "");
            $("#tblContentFleet td." + $(this).attr("filter") + ":not(:contains('" + $(this).val() + "'))").parent("tr").css("display", "none");
        }); 
	},
	MaintenanceLoaded: false,
	ShowFleetUnit: function(idx) {
		idx = parseInt(idx + "");
		var itemtype = "Vehicle or Trailer";
		var ident = User.Fleet[idx].ident2;
		var ident2 = User.Fleet[idx].ident2;
		var iseq = "";
		if (User.Fleet[idx].equipment == "true") {
			itemtype = "Ancilliary Equipment";
			ident = User.Fleet[idx].ident1;
			ident2 = User.Fleet[idx].ident1;
			iseq = "equipment=1"
		}
		var pL = "<a href=\"javascript:User.ShowFleetUnit(" + (idx - 1) + ");\">Previous Item</a>";
		var nL = "<a href=\"javascript:User.ShowFleetUnit(" + (idx + 1) + ");\">Next Item</a>";
		if (idx == 0) {
			pL = "<span class=\"lnkDisabled\">Previous Item</span>";
		}
		if (idx == User.Fleet.length - 1) {
			nL = "<span class=\"lnkDisabled\">Next Item</span>";
		}
		$('#Content').html("<h1 id=\"detailID\" title=\"Click to display navigation options\">" + ident2 + " <small><a href=\"javascript:User.ShowFleet();\">Back to your fleet</a></small></h1>");
		$('<div class="navigationOptions"><h3>Navigate</h3><div>' + pL + ' or ' + nL + '</div></div>').appendTo('#Content');
		$('#detailID').click(function() {
			$('.navigationOptions').toggle("slow");
		});
		if (User.MaintenanceLoaded) {
			if (User.Fleet[idx].maintenance.length > 1) {
				$('<div class="maintenancestatus">' + User.Fleet[idx].maintenance + '</div>').appendTo('#Content');
			} else {
				$('<div class="maintenancestatus"><img src="res/green.gif" alt="Nothing required" /><br />No maintenance due within your last eServ view.</div>').appendTo('#Content');
			}
		} else {
			$('<div class="maitnenancestatus">You have not yet loaded eServ. To view maintenance status for this equipment, please select eServ from the menu above.</div>').appendTo('#Content');
		}
		$('<table cellspacing="0" cellpadding="0" class="DetailView" id="tblFleetDetail" />').appendTo("#Content");
		$("<tr><th>" + User.Fleet[idx].ident1t + "</th><td>" + User.Fleet[idx].ident1 + "</td><th>" + User.Fleet[idx].ident2t + "</th><td>" + User.Fleet[idx].ident2 + "</td></tr>").appendTo("#tblFleetDetail");
		$("<tr><th>Item Type</th><td>" + itemtype + "</td><th>Make / Model</th><td>" + User.Fleet[idx].equiptype + "</td></tr>").appendTo("#tblFleetDetail");
		$("<tr><th>Contract</th><td>" + User.Fleet[idx].contract + "</td><th>Notes</th><td>" + User.Fleet[idx].Notes + "</td></tr>").appendTo("#tblFleetDetail");
		$("<tr><th>Operating Location</th><td>" + User.Fleet[idx].operatingLocation + "</td><td></td><td></td></tr>").appendTo("#tblFleetDetail");
		if (User.Ability.indexOf(",edocs,") >= 0) {
			$('<h2>Documents</h2>').appendTo("#Content");
			User.Interface.Popup("Loading Data...", '<div style="text-align:center"><h2>Loading Data...</h2><p>Currently loading the documents list for the selected vehicle...</p></div>', '', 300, 200);
			$.getJSON("r.php?" + iseq, {r: "documents", fleet: ident, Rn: Math.random() * 100000}, function(data, text) {
				var docs = [];
				$.each(data, function(i, doc) {
					if (doc.file != "false") {
						docs.push(doc);
					}
				});
				docs.sort(function(a, b) {
					var ad = a.fdate.split("/");
					var bd = b.fdate.split("/");
					if (ad[2] < bd[2]) {
						return -1;
					} else if (ad[2] > bd[2]) {
						return 1;
					} else if (ad[1] < bd[1]) {
						return -1;
					} else if (ad[1] > bd[1]) {
						return 1;
					} else if (ad[0] < bd[0]) {
						return -1;
					} else if (ad[0] > bd[0]) {
						return 1;
					} else {
						return 0;
					}
				});
				$('<table id="tblDocsView" cellspacing="0" cellpadding="0" />').appendTo("#Content");
				$('<tr><th>Document Type</th><th>Document Date</th></tr>').appendTo("#tblDocsView");
				if (docs.length > 0) {
					$.each(docs, function(i, doct) {
						$('<tr class="documentloader" filename="' + escape(doct.file) + '"><td>' + doct.type + '</td><td>' + doct.fdate + '</td></tr>').appendTo("#tblDocsView")
					});
				} else {
					$('<tr><td colspan="2"><center>No documents held for this item.</center></td></tr>').appendTo('#tblDocsView');
				}
				User.Interface.ClosePopup();
				$('.documentloader').click(function() {
					if($('#ifDocuments').length > 0) {
						$('#ifDocuments').remove();
					}
					$("<iframe id=\"ifDocuments\" src=\"http://ld-am.co.uk/f.php?file=" + $(this).attr("filename") + "\"></iframe>").css("display", "none").appendTo("#Content");
				});
			});
		} else {
			$('<p><strong>You do not have permission to view stored documents on this fleet unit.</strong> Please call our interactive services team on 08000 121 455 if you believe you should have access to this resource.</div>').appendTo("#Content");
		}
	},
	Interface: {
		ShowAJAX: true,
		CancelHide: false,
		MenuShown: false,
		ClosePopup: function() {
			$('#Popup').fadeOut("slow", function() {
				$('#Popup').remove();
			});
		},
		Popup: function(title, content, Buttons, width, height) {
			// Display a new popup window.
			if ($('#Popup').length < 1) {
				$('<div id="Popup" class="ui-overlay" />').appendTo("body");
			} else {
				$('#Popup').remove();
				$('<div id="Popup" class="ui-overlay" />').appendTo("body");
			}
			$('#Popup').css("display", "none");
			$('#Popup').css("height", $(document).height());
			$('<div id="PopupOverlay" style="position:absolute; background:url(img/black-background.png) repeat 0 0" />').css("height", height + 10).css("width", width + 10).appendTo("#Popup");
			$('#PopupOverlay').css("left", (Math.round(($(window).width() - width) / 2) - 5) + "px");
			$('#PopupOverlay').css("top", (Math.round(($(window).height() - height) / 2) - 5) + "px");
			$('<div class="PBox" />').css("left", 4).css("top", 4).css("height", height).css("width", width).html("<div class=\"PTitle\"><img class=\"CloseButton\" onclick=\"$('#Popup').fadeOut('slow');\" src=\"img/close.png\" /><h1>" + title + "</h1></div>" + "<div class=\"PContent\">" + content + "</div><div class=\"Buttons\">" + Buttons + "</div>").appendTo("#PopupOverlay");
			$('#Popup').find(".PContent").css("height", height - 78);
			$('#Popup').fadeIn(500);
		}
	},
	Services: function(service) {
		$('#Content').load("Services/" + service + ".php", {random: (Math.random() * 10000)});
	},
	Abilities: {
		DueMaint: [],
		Ed: "",
		Users: [],
		ShowUsers: function() {
			User.Abilities.Users = [];
			$.getJSON("v2/users.php", {act: 'list', Rn: Math.random() * 15000}, function(data) {
				$.each(data, function(i, item) {
					User.Abilities.Users.push(item);
				});
				User.Abilities.Users.sort(function(a, b) {
					if (a.FiledAs < b.FiledAs) {
						return -1;
					} else if (a.FiledAs > b.FiledAs) {
						return 1;
					} else {
						return 0;
					}
				});
				User.Abilities.ShowUserList();
			});
		},
		NewUser: function() {
			$.getJSON("v2/users.php", {Rn: Math.random() * 150000, act: "new"}, function(data) {
				User.Abilities.ShowUsers();
			});
		},
		ShowUserList: function() {
			$('#Content').html("<h1>Users</h1><p>Please use the following links to create and edit users.</p><h3>Options</h3><p><a href=\"javascript:User.Abilities.NewUser();\">Create New User</a></p>");
			$('<table id="tblUsers" cellspacing="0" cellpadding="0">').appendTo('#Content');
			$('<tr>' +
				'<th>Username</th>' +
				'<th>Email Address</th>' + 
				'<th>Filed As</th>' + 
				'<th>Customer Account</th>' +
				'<th>Contracts</th>' +
			  '</tr>').appendTo('#tblUsers');
			$('<tr>' +
				'<td><input class="filterable" filter="username" type="text" value="" /></td>' +
				'<td><input class="filterable" filter="email" type="text" value="" /></td>' +
				'<td><input class="filterable" filter="filedas" type="text" value="" /></td>' +
				'<td><input class="filterable" filter="account" type="text" value="" /></td>' +
				'<td><input class="filterable" filter="contracts" type="text" value="" /></td>' +
			  '</tr>').appendTo('#tblUsers');
			$.each(User.Abilities.Users, function(i, user) {
				$('<tr class="userrecord" userId="' + i + '">' +
					'<td class="username">' + user.Username + '</td>' +
					'<td class="email">' + user.EmailAddress + '</td>' +
					'<td class="filedas">' + user.FiledAs + '</td>' +
					'<td class="account">' + user.Accounts + '</td>' +
					'<td class="contracts">' + user.Contracts + '</td>' +
				  '</tr>').appendTo('#tblUsers');
			});

			$('#tblUsers .filterable').keyup(function() {
	            var thisval = $(this).val();
	            $('#tblUsers input.filterable').val("");
	            $(this).val(thisval);
	            $("#tblUsers td." + $(this).attr("filter") + ":contains('" + $(this).val() + "')").parent("tr").css("display", "");
	            $("#tblUsers td." + $(this).attr("filter") + ":not(:contains('" + $(this).val() + "'))").parent("tr").css("display", "none");
	        });
			$('#tblUsers tr.userrecord').click(function() {
				var idx = $(this).attr('userId');
				User.Abilities.ShowUserRecord(idx);
			}) 			
		},
		ShowUserRecord: function(id) {
			var usr = User.Abilities.Users[id];
			$('#Content').html('<h1>' + usr.FiledAs + '<small><a href="javascript:User.Abilities.ShowUserList();">Back to Users</a></small></h1>');
			$('<table id="tblUserDetail" cellspacing="0" cellpadding="0">').appendTo('#Content');
			$('<tr><th>Username</th><td><input type="text" class="editable" value="' + usr.Username + '" field="Username" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>File As</th><td><input type="text" class="editable" value="' + usr.AddressAs + '" field="AddressAs" userId="'+usr.Id+'" userIdx="'+id+'" /></td></tr>').appendTo('#tblUserDetail');
			$('<tr><th>Customer Account</th><td><input type="text" class="editable" value="' + usr.Accounts + '" field="Accounts" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>Fixed Price Contracts</th><td><input type="text" class="editable" value="' + usr.Contracts + '" field="Contracts" userId="'+usr.Id+'" userIdx="'+id+'" /><a href="javascript:User.Abilities.ShowContracts();">Select...</a></td></tr>').appendTo('#tblUserDetail');
			$('<tr><th>Salutation</th><td><input type="text" class="editable" value="' + usr.Salutation + '" field="Salutation" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>Forename(s)</th><td><input type="text" class="editable" value="' + usr.Forenames + '" field="Forenames" userId="'+usr.Id+'" userIdx="'+id+'" /></td></tr>').appendTo('#tblUserDetail');
			$('<tr><th>Surname</th><td><input type="text" class="editable" value="' + usr.Surname + '" field="Surname" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>Email Address</th><td><input type="text" class="editable" value="' + usr.EmailAddress + '" field="EmailAddress" userId="'+usr.Id+'" userIdx="'+id+'" /></td></tr>').appendTo('#tblUserDetail');
			$('<tr><th>Telephone Number</th><td><input type="text" class="editable" value="' + usr.Phone + '" field="Phone" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>Fax</th><td><input type="text" class="editable" value="' + usr.Fax + '" field="Fax" userId="'+usr.Id+'" userIdx="'+id+'" /></td></tr>').appendTo('#tblUserDetail');
			$('<tr><th>Password</th><td><input type="password" class="editable" value="" field="Password" userId="' + usr.Id + '" userIdx="'+id+'" /></td>' +
			  '<th>Permissions</th><td><input type="text" class="editable" value="'+usr.Abilities+'" field="Abilities" userId="' + usr.Id + '" userIdx="'+id+'" /><a href="javascript:User.Abilities.ShowAbilities();">Select...</a></td></tr>').appendTo('#tblUserDetail');
			  
			$('#tblUserDetail input.editable').blur(function() {
				var newv = $(this).val();
				var field = $(this).attr('field');
				var UID = $(this).attr('userId');
				var userIdx = $(this).attr('userIdx');
				User.Abilities.Users[userIdx][field] = newv;
				User.Abilities.Users[userIdx].FiledAs = User.Abilities.Users[userIdx].AddressAs.replace("{1}", User.Abilities.Users[userIdx].Salutation).replace("{2}", User.Abilities.Users[userIdx].Forenames).replace("{3}", User.Abilities.Users[userIdx].Surname);
				//alert("Updating user " + User.Abilities.Users[userIdx].FiledAs + " - " + field + ":" + newv);
				$.getJSON("v2/users.php", {act: "amend", userId: UID, item: field, newvalue: newv, Rn:Math.random() * 150000}, function(data) {
					//alert("Updated");
				});
			});
		},
		ShowAccounts: function() {
			// Shows accounts for selection in user editing
			User.Interface.Popup("Choose Accounts", "<div id=\"dlgContent\"></div>", "", 450, 500);
			$('#dlgContent').html("<h1>Not Implemented</h1><p>This feature is still in development</p>");
		},
		ShowContracts: function() {
			// Shows accounts for selection in user editing
			User.Interface.Popup("Choose Contracts", "<div id=\"dlgContent\"></div>", "", 450, 500);
			var ccon = $('input[field=Contracts]').val();
			$('#dlgContent').html("<p>Loading Contracts...</p>");
			$.getJSON('r.php', {r: "contracts", Rn: Math.random() * 150000}, function(data) {
				$('#dlgContent').html("<h2>Select Contracts</h2>");
				$('<ul id="contractList" />').appendTo('#dlgContent');
				$.each(data, function(i, item) {
					if (item.Contract != "false") {
						$('<li><label><input type="checkbox" autochange="true" contract="' + item.Contract + '" /> ' + item.Contract + ': ' + item.Customer + ' (' + item.Description + ') - ' + item.Number + ' units</label></li>').appendTo('#contractList');
					}
				});
				var vals = $('input[field=Contracts]').val().split(",");
				$.each(vals, function(o, item) {
					$('#dlgContent input[contract=' + item + ']').attr("checked", true);
				});
				$('#dlgContent input[autochange=true]:checked').parents("li").addClass("highlight");
				$('#dlgContent input[autochange=true]').click(function() {
					$('input[field=Contracts]').val("");
					$('#dlgContent input[autochange=true]').parents("li").removeClass("highlight");
					$('#dlgContent input[autochange=true]:checked').parents("li").addClass("highlight");
					$('#dlgContent input:checked').each(function(item) {
						var rV = $('input[field=Contracts]').val();
						if (rV.length>0) {
							rV = rV + "," + $(this).attr('contract');
						} else {
							rV = $(this).attr('contract');
						}
						$('input[field=Contracts]').val(rV).focus();
					});
				});
			})
		},
		ShowAbilities: function() {
			User.Interface.Popup("Choose Abilities", "<div id=\"dlgContent\"></div>", "", 450, 500);
			$('#dlgContent').html("<h1>Not Implemented</h1><p>This feature is still in development</p>");
		},
		ChangeAccounts: function() {
			// LDAM Internal function
		},
		ChangeContracts: function() {
			// Multi-Customer (TIP/Scania, etc) switching function
		},
		GetMaintenanceContract: function(conts) {
			contract = conts.pop();
			params = {
				r: "maintenance",
				Contract: contract,
				Rn: Math.random() * 14000
			};
			if (User.Abilities.Ed != "") {
				params = {
					r: "maintenance",
					Contract: contract,
					Ed: User.Abilities.Ed,
					Rn: Math.random() * 14000
				};
			}
			$.getJSON("r.php", params, function(data, text) {
				User.ContractFleet.Received += 1;
				$('#ls2monitor').css("width", Math.round((User.ContractFleet.Received / User.ContractFleet.Requested) * 250) + "px");
				if (data.length > 0) {
					$.each(data, function(i, maint){
						User.Abilities.DueMaint.push(maint);
					});
				}
				if (User.ContractFleet.Received >= User.ContractFleet.Requested) {
					// Finished loading!
					User.Interface.ClosePopup();
					User.MaintenanceLoaded = true;
					User.Abilities.DueMaint.sort(function(a, b) {
						var ad = a.duedate.split("/");
						var bd = b.duedate.split("/");
						if ((a.fleet == b.fleet) && (a.registration == b.registration)) {
							// Keep the same fleet unit maintenance items together
							return 0;
						} else if (ad[2] < bd[2]) {
							return -1;
						} else if (ad[2] > bd[2]) {
							return 1;
						} else if (ad[1] < bd[1]) {
							return -1;
						} else if (ad[1] > bd[1]) {
							return 1;
						} else if (ad[0] < bd[0]) {
							return -1;
						} else if (ad[0] > bd[0]) {
							return 1;
						} else {
							return 1;
						}
					});
					$('#Content').html("<h1>Maintenance Due</h1><p>The following table lists by default all maintenance for this week, and any maintenance overdue from previous weeks.</p><p>To view maintenance required for this fleet over a larger timescale, please select one of the following options: <a href=\"javascript:User.Abilities.MaintenanceDue();\">This week (default)</a> <a href=\"javascript:User.Abilities.MaintenanceDueByDate('+1 week');\">Next 7 days</a> <a href=\"javascript:User.Abilities.MaintenanceDueByDate('+2 weeks');\">Next fortnight</a> <a href=\"javascript:User.Abilities.MaintenanceDueByDate('+1 month');\">Next month</a></p>");
					$('<table id="tblMaintenance" cellspacing="" cellpadding="" />').appendTo("#Content");
					$('<tr><th>Status</th><th>Registration</th><th>Fleet</th><th>Maintenance Due</th><th>Due Date</th></tr>').appendTo("#tblMaintenance");
					$('<tr><td><input type="text" class="filterable" filter="status" value="" style="width:80px" /></td>' +
					  '<td><input type="text" class="filterable" filter="ident1" value="" /></td>' +
					  '<td><input type="text" class="filterable" filter="ident2" value="" /></td>' +
					  '<td><input type="text" class="filterable" filter="maintenancetype" value="" /></td>' +
					  '<td><input type="text" class="filterable" filter="duedate" value="" /></td></tr>').appendTo('#tblMaintenance');
					
					var cT1 = new Date();
					var cT = new Date(cT1.getYear(), cT1.getMonth(), cT1.getDay());
					
					$.each(User.Fleet, function(i, item) {
						item.maintenance = "";
					});
					$.each(User.Abilities.DueMaint, function(i, maint) {
						var mD = maint.duedate.split("/");
						var mT = new Date(mD[2], mD[1]-1, mD[0]);
						var statusText = "due"
						var notes = "";
						if (maint.notes.length > 1) {
							notes = "<div class=\"notes\">" + maint.notes + "</div>";
						}
						
						idx = SearchFleet(maint.registration, maint.fleet);

						if (maint.jobnumber > 0) {
							// booked - image should be green
							if (User.Accounts.indexOf("TIP ", 0) >= 0) {
								statusitem = "<img src=\"res/warning.gif\" alt=\"Booked In\" title=\"Booked in on job number " + maint.jobnumber + "\" />";
							} else {
								statusitem = "<img src=\"res/green.gif\" alt=\"Booked In\" title=\"Booked in on job number " + maint.jobnumber + "\" />";
							}
							User.Fleet[idx].maintenance += statusitem + maint.typedesc + " booked in on job number " + maint.jobnumber + "<br />";
							statusText = "booked in"
						} else if (mT < cT) {
							// overdue - display alert 
							statusitem = "<img src=\"res/alert.gif\" alt=\"Overdue\" title=\"Alert: This Maintenance is Overdue\" />";
							User.Fleet[idx].maintenance += statusitem  + maint.typedesc + " overdue<br />";
							statusText = "overdue";
						} else {
							// due, but not yet overdue
							if (User.Accounts.indexOf("TIP ", 0) >= 0) {
								statusitem = "<img src=\"res/warning2.gif\" alt=\"Due\" title=\"Due, not booked in yet\" />";
							} else {
								statusitem = "<img src=\"res/warning.gif\" alt=\"Due\" title=\"Due, not booked in yet\" />";
							}
							User.Fleet[idx].maintenance += statusitem + maint.typedesc + " due - not yet booked in<br />";
							statusText = "due";
						}
						$(	'<tr class="selectable" ident1="' + maint.registration + '" ident2="' + maint.fleet + '"><td class="status"><span style="display:none">' + statusText + '</span>' + statusitem + '</td><td class="ident1">' + maint.registration + '</td><td class="ident2">' +
							maint.fleet + '</td><td class="maintenancetype">' + maint.typedesc + notes + '</td><td class="duedate">' +
							maint.duedate + '</td></tr>').appendTo('#tblMaintenance');
					});
					if (User.Abilities.DueMaint.count == 0) {
						$('<tr><td colspan="5"><center>No maintenance due within the timescale specified</center></td></tr>').appendTo('#tblMaintenance');
					}
					$('#tblMaintenance .filterable').keyup(function() {
			            var thisval = $(this).val();
			            $('#tblMaintenance input.filterable').val("");
			            $(this).val(thisval);
			            $("#tblMaintenance td." + $(this).attr("filter") + ":contains('" + $(this).val() + "')").parent("tr").css("display", "");
			            $("#tblMaintenance td." + $(this).attr("filter") + ":not(:contains('" + $(this).val() + "'))").parent("tr").css("display", "none");
			        });
					$('#tblMaintenance tr.selectable').click(function() {
						var id1 = $(this).attr("ident1");
						var id2 = $(this).attr("ident2");
						var idx2 = SearchFleet(id1, id2);
						if (idx2 > -1) {
							// This item exists
							User.ShowFleetUnit(idx2);
						} else {
							alert("ERROR: Could not cross-refer this maintenance - please report this information to our interactive services team on 08000 121 455.");
						}
					});
				} else {
					User.Abilities.GetMaintenanceContract(conts);
				}
			});
		},
		MaintenanceDue: function() {
			// Show due maintenance
			var loadContr = [];
			User.Abilities.Ed = "";
			$.each(User.Contracts, function(i, item) {
				loadContr.push(item);
			});
			User.Abilities.DueMaint = [];
			User.Interface.Popup("Loading Maintenance", '<div style="text-align:center"><h3>Please Wait...</h3><p>Please wait while we load maintenance required for your fleet from our servers...</p><div id="LoadState"><div id="ls2monitor" /></div></div>', "", 300, 250);
			User.ContractFleet.Received = 0;
			User.ContractFleet.Requested = loadContr.length;
			User.Abilities.GetMaintenanceContract(loadContr);
		},
		MaintenanceDueByDate: function(ed) {
			var loadContr = [];
			User.Abilities.Ed = ed;
			$.each(User.Contracts, function(i, item) {
				loadContr.push(item);
			});
			User.Abilities.DueMaint = [];
			User.Interface.Popup("Loading Maintenance", '<div style="text-align:center"><h3>Please Wait...</h3><p>Please wait while we load maintenance required for your fleet from our servers...</p><div id="LoadState"><div id="ls2monitor" /></div></div>', "", 300, 250);
			User.ContractFleet.Received = 0;
			User.ContractFleet.Requested = loadContr.length;
			User.Abilities.GetMaintenanceContract(loadContr);
		},
		Jobs: function(fleet, isequip) {
			// Show jobs for equipment
		},
		ViewJob: function(jobnumber) {
			// Display job details
		},
		ViewBilling: function() {
			
		},
		ViewDocument: function(filename) {
			// Downlaod a document to be viewed
		},
		ViewContract: function(contract) {
			// Show details for a particular contract
		}
	}
}

$(function() {
	/**
	 * Tag Line Changing
	 */
	window.setInterval(function() {
		$('#TagText').fadeOut(200, function() {
			User.Interface.ShowAJAX = false;
			$('#TagText').load("v2/tags.php", {random: (Math.random() * 10000)}, function() {
				window.setTimeout(function() { $('#TagText').fadeIn(200); }, 200);
			});
		});
	}, 5000);
	window.setInterval(function() {
		if($('.truck').length > 0) {
			$('.truck').removeClass("truck").addClass("spanner");
			return;
		} else if ($('.spanner').length > 0) {
			$('.spanner').removeClass("spanner").addClass("lawdav");
			return;
		} else if ($('.lawdav').length > 0) {
			$('.lawdav').removeClass("lawdav").addClass("truck");
			return;
		}		
	}, 10000);
	/**
	 * table hovering effects
	 */
	$('td').live("mouseover", function() {
		$(this).parents("tr").addClass("highlight")
	});
	$('td').live("mouseout", function() {
		$(this).parents("tr").removeClass("highlight")
	});
	/**
	 * AJAX Events
	 */
	$('#AjaxIndicator').ajaxStart(function() {
		if (User.Interface.ShowAJAX) {
			$(this).fadeIn(200);
		}
	});
	$('#AjaxIndicator').ajaxStop(function() {
		if (User.Interface.ShowAJAX) {
			window.setTimeout(function(){
				$('#AjaxIndicator').fadeOut(200);
			}, 210);
		} else {
			if ($('#AjaxIndicator').css("display") != "none") {
				window.setTimeout(function(){
					$('#AjaxIndicator').fadeOut(200);
				}, 210);
			}
			User.Interface.ShowAJAX = true;
		}
	});
	/**
	 * Menu Behavious
	 */
	$('#Menu').css("display", "none");
	User.RebuildMenu();
	User.Interface.MenuShown = false;
	$('.MenuActions').mouseenter(function() {
		User.Interface.CancelHide = true;
		if (!User.Interface.MenuShown) {
			$('#Menu').fadeIn("slow");
			User.Interface.MenuShown = true;
		}
	});
	$('.MenuActions').mouseleave(function() {
		window.setTimeout(function() {
			if (User.Interface.CancelHide) {
				User.Interface.CancelHide = false;
			} else {
				$('#Menu').fadeOut("slow", function() {
					User.Interface.MenuShown = false;
				});
			}
		}, 600);
	});
	/**
	 * Drop Down Lists
	 */
	$('.DropDown').mouseenter(function() {
		var ddel = "#" + $(this).attr("dropdown");
		$('.DropDownList').fadeOut(200);
		$(ddel).css("left", $(this).offset().left);
		$(ddel).css("top", $(this).offset().top + 21);
		$(ddel).fadeIn(200);
		User.Interface.CancelHide = true;
	});
	$('.DropDown').mouseleave(function() {
		User.Interface.CancelHide = false;
		window.setTimeout(function() {
			if (!User.Interface.CancelHide) {
				$('.DropDownList').fadeOut(200);
			} 
			User.Interface.CancelHide = false;
		}, 500);
	});
	$(".DropDownList").mouseenter(function() {
		User.Interface.CancelHide = true;	
	});
	$('.DropDownList').mouseleave(function() {
		User.Interface.CancelHide = false;
		window.setTimeout(function() {
			if (!User.Interface.CancelHide) {
				$('.DropDownList').fadeOut(200);
			} 
			User.Interface.CancelHide = false;
		}, 500);
	});
});
