String.prototype.beginsWith = function(t, i) { if (i==false) { return 
(t == this.substring(0, t.length)); } else { return (t.toLowerCase() 
== this.substring(0, t.length).toLowerCase()); } } 

String.prototype.endsWith = function(t, i) { if (i==false) { return (t 
== this.substring(this.length - t.length)); } else { return 
(t.toLowerCase() == this.substring(this.length - 
t.length).toLowerCase()); } } 

function getStyleSheets() {
	var links = new Array();
	
	if (document.styleSheets) {
		var allLinks;
		if( document.getElementsByTagName ) {
			allLinks = document.getElementsByTagName('link');
		} else if( document.styleSheets && document.all ) {
			allLinks = document.all.tags('LINK');
		}
		
		if (allLinks != null) {
			for (var i=0; i < allLinks.length; i++) {
				if (allLinks[i].title) {
					links[links.length] = allLinks[i];
				}
			}
		}
	}
	
	return links;
}

function hideLoading() 
{
	hide(divLoading.e);
}


function messageBox(applicationPath, title, buttons, width, height, buttonWidth, align, valign, objectType, args, resizable) {
	var browser = browserSniff();
	
	switch (browser) {
		case "IE":
			return window.showModalDialog(applicationPath + "/Common/MessageBox.aspx?Title=" + title + "&Buttons=" + buttons + "&ButtonWidth=" + buttonWidth + "&Align=" + align + "&VAlign=" + valign + "&ObjectType=" + objectType, args, "center:yes;dialogWidth:" + width + "px;dialogHeight:" + height + "px;status:no;" + (resizable != null ? "resizable:" + resizable + ";" : "" ));
			break;
		default:
			var button = confirm("Warning any changes will be lost. Continue?");
			
			if (button) {
				return "No";
			} else {
				return "Cancel";
			}
			
			break;
	}
}

function keepSessionAlive() {
	jsrsExecute(Application['ApplicationPath'] + "/ServerScript/Default.aspx", null, "KeepSessionAlive", null);
}

function showToolTip(name) {
	openWindow(Application["ApplicationPath"] + "/Common/ToolTip.aspx?Name=" + name, "ToolTip", "700", "300", "resizable,scrollbars");	
}

function showLoading() 
{
	show(divLoading.e);
}

function validateEmailAddress(emailAddress) {

	emailAddress = trimWhiteSpace(emailAddress);

	if (emailAddress.length == 0) {
		return false;
	}
	
	var charAtPos = emailAddress.indexOf('@');
	
	if (charAtPos == -1) {
		return false;	
	} else {
		var prefix = "";
		var suffix = "";
		
		prefix = emailAddress.substring(0, charAtPos);
		suffix = emailAddress.substring(charAtPos + 1);
		
		if (prefix.length == 0 || suffix.length == 0) {
			return false;
		} 
		
		if (suffix.indexOf('.') == -1) {
			return false;				
		}

	}
	
	return true;
}


function document_onload()
{
	main_document_onload();
}

function main_document_onload()
{
    setHeaderSize();
    if (userLoggedOn) { SetupMenu(); } else {SetupLoggedOutMenu(); }
	if (userLoggedOn || despatchUserLoggedOn) {
		window.setInterval("keepSessionAlive();", 1000 * 60 * keepSessionAliveInterval);
	}
	
	if (document.frmSelectClient != null) {
		if (document.frmSelectClient.cboSessionClientID != null) {
			if (document.frmSelectClient.cboSessionClientID.length <= 1) {
				document.frmSelectClient.cboSessionClientID.disabled = true;
			}
		 }
	}
	
	if (document.frmHead.txtClientDate == null) return;
	document.frmHead.txtClientDate.value = getCurrentDate();
	document.frmHead.txtClientTime.value = getCurrentTime();


	displayClientClock();
		
	if (document.frmHead.txtLoadMessage.value.length > 0) {
		alert(document.frmHead.txtLoadMessage.value);
		document.frmHead.txtLoadMessage.value = "";
	}
	
	setLoginFocus();
	
}

function setLoginFocus() {
	var tmpUserName = document.getElementById('txtUserName');
	if (tmpUserName != null) {
		if (tmpUserName.value.length == 0) {
			setFocus(document.getElementById('txtUserName'));
		} else {
			if (document.getElementById('txtPassword') != null) {
				setFocus(document.getElementById('txtPassword'));
			}
		}
	}
}

function document_onclick()
{
}

function changeClient()
{

	destination = document.frmSelectClient.cboSessionClientID.options[document.frmSelectClient.cboSessionClientID.selectedIndex].value;
	if (destination) {
		location.href = destination;
	}
}



function validateLoginTopMenuBar() {


	if (is_opera5up || is_nav6up || is_gecko || is_ie5_5up)
	{
		// Passes browser checks.
	}
	else
	{
		alert('This site does not fully support your current web broswer version.');
	}

	if (document.frmLogin.txtUserName.value.length == 0) {
		alert("Must enter a user name.");
		document.frmLogin.txtUserName.focus();
		return false;
	}
	if (document.frmLogin.txtPassword.value.length == 0) {
		alert("Must enter a password.");
		document.frmLogin.txtPassword.focus();
		return false;
	}
	
	document.frmLogin.submit();

}

function validateLoginKeyPress(item , keyPressed) {
	if (keyPressed.keyCode == 13) {
	
		// User pressed the enter key
		if (item.name == "txtUserName") {
			document.frmLogin.txtPassword.focus();
			return false;
		} else if (item.name == "txtPassword") {
			//alert(keyPressed.keyCode);
			//keyPressed.keyCode = 0;  //stops the annoying noise!
			validateLoginTopMenuBar();
			//document.frmLogin.submitImage.click();
			return false;
		}
	}
	
	return true;
}


function actionClock() {
	
	var chkDate = getCurrentDate() + " " + getCurrentTime();
	var curDate = document.frmHead.txtClientDate.value + " " + document.frmHead.txtClientTime.value;
	
	timeDiff = dateDiff("n", curDate, chkDate);
	
	if (parseInt(timeDiff) > 0) {
					
		//more than 1 minute passed - so increase the users display..
		var serverDateTime = new Date(addMinutes(document.frmHead.txtServerDate.value + " " + document.frmHead.txtServerTime.value, timeDiff));
		document.frmHead.txtServerTime.value = serverDateTime.getHours() + ":" + serverDateTime.getMinutes() + ":" + serverDateTime.getSeconds();
		document.frmHead.txtServerDate.value = serverDateTime.getDate() + " " + getMonthName(serverDateTime.getMonth() + 1) + " " + serverDateTime.getFullYear();

		//alert(document.frmHead.txtServerDate.value + " " + document.frmHead.txtServerTime.value);

		var clientDateTime = new Date(chkDate);
		//document.frmHead.txtClientTime.value = clientDateTime.getHours() + ":" + clientDateTime.getMinutes() + ":" + clientDateTime.getSeconds();
		//document.frmHead.txtClientDate.value = clientDateTime.getDate() + " " + getMonthName(clientDateTime.getMonth() + 1) + ":" + clientDateTime.getFullYear();

		document.frmHead.txtClientTime.value = getCurrentTime();
		document.frmHead.txtClientDate.value = getCurrentDate();

	}

	displayClientClock();
}

function formatClockTime(timeString) {
	timeString = formatDate(timeString, "hh:nn:ss");
	return formatDate(timeString,"h:nn tt").split(".").join("").toUpperCase()
}

function formatClockDate(dateString) {
	var tmpDate;
	var convDate = formatDate(dateString,"mm/dd/yyyy")
		
	tmpDate = (getDatePart(convDate, "ddd", "").toUpperCase()) + " " + getDatePart(dateString, "d", "");
	tmpDate += getDatePart(dateString, "o", "").toUpperCase();
	return tmpDate;
}

function displayClientClock() {

	window.setTimeout("actionClock();", 10000);  // set to 10 seconds

	var curDate = document.frmHead.txtServerDate.value;
	var curTime = document.frmHead.txtServerTime.value;
			
	var tmpDate = "<div class=\"dayDate\" align=\"right\">"
	tmpDate += formatClockDate(curDate);
	//tmpDate += "<BR><B>" + formatClockTime(curTime) +"</B>" // Time
	tmpDate += "&nbsp;<b>" + formatClockTime(curTime) +"</b>" // Time
	tmpDate += "</div>"

	if (document.all) {
		if (document.getElementById("spnClock") != null) {
			document.getElementById("spnClock").innerHTML=tmpDate;
		}
	} else if (document.getElementById){
		if (document.getElementById("spnClock") != null) {
			document.getElementById("spnClock").innerHTML = tmpDate;
		}
	} else if (document.layers) {
		if (document.layers.spnClock != null) {
			document.layers.spnClock.document.write(tmpDate);
			document.layers.spnClock.document.close();
		}
	} else {
		// we have a problem as date / time wont display
	}
}


function numericOnly (point){
	if (!point && window.event.keyCode == 46){
		window.event.returnValue = false;
	}
	if ((window.event.keyCode < 45 || window.event.keyCode > 57) && window.event.keyCode != 47){
		window.event.returnValue = false;
	}
}


function isDecimal(s, allowDecimal)
{   
	var i;
	var foundDecimal = false;
	if (!allowDecimal) foundDecimal = true;
	
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {
			if (c == ".") {
				if (foundDecimal) {
					return false;
				} else {
					foundDecimal = true;
				}
			} else {
				return false;
			}
		}
		
    }
    // All characters are numbers.
    return true;
}

function decimalPlaces(field, dp){
	var endRange;

	if (dp == 0 && window.event.keyCode == 46){
		window.event.returnValue = false;
		return;
	}
	
	// CATCH INVALID CHARACTERS
	if ((window.event.keyCode < 47 || window.event.keyCode > 57) && window.event.keyCode != 45 && window.event.keyCode != 46) {
		window.event.returnValue = false;
		return;
	}	
	
	if (document.selection.type == "None") {
		// WHEN TEXT NOT SELECTED
		
		endRange = document.selection.createRange();
		endRange.moveEnd("textedit");

		// CATCH MULTIPLE -'S
		if (window.event.keyCode == 45 && (field.value.indexOf("-") != -1 || (field.value.length - endRange.text.length) != 0)) {
			window.event.returnValue = false;
			return;
		}
		
		if (dp != 0) {	
		
			// CATCH DECIMAL POINTS 
			if (window.event.keyCode == 46 && (field.value.indexOf(".") != -1 || endRange.text.length > dp)) {
				window.event.returnValue = false;
				return;
			}	

			// CATCH DECIMAL PLACES 
			if (window.event.keyCode != 45 && window.event.keyCode != 46 && endRange.text.indexOf(".") == -1 && getDecimalPlaces(field.value) >= dp) {
				window.event.returnValue = false;
				return;
			}
		}
		
	} else if (document.selection.type == "Text"){
		// WHEN TEXT SELECTED
	
		endRange = document.selection.createRange();	

		// CATCH MULTIPLE -'S
		if (window.event.keyCode == 45 && (field.value.indexOf(endRange.text) > 0) || (endRange.text.indexOf("-") == -1 && field.value.indexOf("-") != -1)) {
			window.event.returnValue = false;
			return;
		}
		
		if (dp != 0) {
		
			// CATCH DECIMAL POINTS 
			if (window.event.keyCode == 46 && endRange.text.indexOf(".") == -1 && field.value.indexOf(".") != -1) {
				window.event.returnValue = false;
				return;
			}	
					
		}
	}
}


function getSecondsDocumentOpen() {
	var clientDateTime;
	clientDateTime = new Date(document.frmHead.txtClientDate.value + " " + document.frmHead.txtClientTime.value);
	
	var nowDateTime;
	nowDateTime = new Date(getCurrentDateTime());

	var difference;
	
	//milliseconds difference
	difference = nowDateTime.valueOf() - clientDateTime.valueOf();
	
	//seconds difference
	difference /= 1000;
	
	return difference;
}


function changeImageSource(image, newPath) {
	image.src = newPath;
}

function javascriptError(pageName, errorMessage, errorNumber) {
	alert("An error has occurred - please forward this message to Urgent Couriers:\n\n" + pageName + " #" + errorNumber + "\n\n" + errorMessage);

	var rspage = Application["ApplicationPath"] + "/ServerScript/Default.aspx";
	var callback = null;
	var func = "LogException";
	var parms = new Array(pageName + " #" + errorNumber + "\n\n" + errorMessage);
	var callbackArgs = null;
	var visibility = null;
	
	jsrsExecute(rspage, callback, func, parms, callbackArgs, visibility);	
}

function javascriptErrorNoAlert(pageName, errorMessage, errorNumber) {

	var rspage = Application["ApplicationPath"] + "/ServerScript/Default.aspx";
	var callback = null;
	var func = "LogException";
	var parms = new Array(pageName + " #" + errorNumber + "\n\n" + errorMessage);
	var callbackArgs = null;
	var visibility = null;
	
	jsrsExecute(rspage, callback, func, parms, callbackArgs, visibility);	
}

function getChildNode(node) {
	var childNode = null;
	
	for (i=0; i < node.childNodes.length; i++) {
	    if (node.childNodes[i].nodeType == 1) {
	        childNode = node.childNodes[i];
	        break;
	    }
	}

    return childNode;
}
function getStyleSheets() {
	var links = new Array();
	
	if (document.styleSheets) {
		var allLinks;
		if( document.getElementsByTagName ) {
			allLinks = document.getElementsByTagName('link');
		} else if( document.styleSheets && document.all ) {
			allLinks = document.all.tags('LINK');
		}
		
		if (allLinks != null) {
			for (var i=0; i < allLinks.length; i++) {
				if (allLinks[i].title) {
					links[links.length] = allLinks[i];
				}
			}
		}
	}
	
	return links;
}

function hideLoading() 
{
	hide(divLoading.e);
}


function messageBox(applicationPath, title, buttons, width, height, buttonWidth, align, valign, objectType, args, resizable) {
	var browser = browserSniff();
	
	switch (browser) {
		case "IE":
			return window.showModalDialog(applicationPath + "/Common/MessageBox.aspx?Title=" + title + "&Buttons=" + buttons + "&ButtonWidth=" + buttonWidth + "&Align=" + align + "&VAlign=" + valign + "&ObjectType=" + objectType, args, "center:yes;dialogWidth:" + width + "px;dialogHeight:" + height + "px;status:no;" + (resizable != null ? "resizable:" + resizable + ";" : "" ));
			break;
		default:
			var button = confirm("Warning any changes will be lost. Continue?");
			
			if (button) {
				return "No";
			} else {
				return "Cancel";
			}
			
			break;
	}
}

function keepSessionAlive() {
	jsrsExecute(Application['ApplicationPath'] + "/ServerScript/Default.aspx", null, "KeepSessionAlive", null);
}

function showToolTip(name) {
	openWindow(Application["ApplicationPath"] + "/Common/ToolTip.aspx?Name=" + name, "ToolTip", "700", "300", "resizable,scrollbars");	
}

function showLoading() 
{
	show(divLoading.e);
}

function validateEmailAddress(emailAddress) {

	emailAddress = trimWhiteSpace(emailAddress);

	if (emailAddress.length == 0) {
		return false;
	}
	
	var charAtPos = emailAddress.indexOf('@');
	
	if (charAtPos == -1) {
		return false;	
	} else {
		var prefix = "";
		var suffix = "";
		
		prefix = emailAddress.substring(0, charAtPos);
		suffix = emailAddress.substring(charAtPos + 1);
		
		if (prefix.length == 0 || suffix.length == 0) {
			return false;
		} 
		
		if (suffix.indexOf('.') == -1) {
			return false;				
		}

	}
	
	return true;
}


function document_onload()
{
	main_document_onload();
}

function main_document_onload()
{
    setHeaderSize();
    $("#mnu41 a:first").click(function(event) {
        event.preventDefault();
        ShowRateScheduleOptions();
        
    });
    if (userLoggedOn) { SetupMenu(); } else { SetupLoggedOutMenu(); }
	if (userLoggedOn || despatchUserLoggedOn) {
		window.setInterval("keepSessionAlive();", 1000 * 60 * keepSessionAliveInterval);
	}
	
	if (document.frmSelectClient != null) {
		if (document.frmSelectClient.cboSessionClientID != null) {
			if (document.frmSelectClient.cboSessionClientID.length <= 1) {
				document.frmSelectClient.cboSessionClientID.disabled = true;
			}
		 }
	}
	
	if (document.frmHead.txtClientDate == null) return;
	document.frmHead.txtClientDate.value = getCurrentDate();
	document.frmHead.txtClientTime.value = getCurrentTime();


	displayClientClock();

	if (document.frmHead.txtLoadMessage.value.length > 0) {
	    var m = document.frmHead.txtLoadMessage.value;
	    if (m.endsWith('|pub', false) == true) {
	        m = m.replace('|pub', '');
	        alert(m);
	        window.location = Application['ApplicationPath'] + "/public/default.aspx";		
	    }	
	    else
	    {		  
		    alert(document.frmHead.txtLoadMessage.value);
		    document.frmHead.txtLoadMessage.value = "";
		}

	}
	
	setLoginFocus();
	
}

function setLoginFocus() {
	var tmpUserName = document.getElementById('txtUserName');
	if (tmpUserName != null) {
		if (tmpUserName.value.length == 0) {
			setFocus(document.getElementById('txtUserName'));
		} else {
			if (document.getElementById('txtPassword') != null) {
				setFocus(document.getElementById('txtPassword'));
			}
		}
	}
}

function document_onclick()
{
}

function changeClient()
{

	destination = document.frmSelectClient.cboSessionClientID.options[document.frmSelectClient.cboSessionClientID.selectedIndex].value;
	if (destination) {
		location.href = destination;
	}
}



function validateLoginTopMenuBar() {


	if (is_opera5up || is_nav6up || is_gecko || is_ie5_5up)
	{
		// Passes browser checks.
	}
	else
	{
		alert('This site does not fully support your current web broswer version.');
	}

	if (document.frmLogin.txtUserName.value.length == 0) {
		alert("Must enter a user name.");
		document.frmLogin.txtUserName.focus();
		return false;
	}
	if (document.frmLogin.txtPassword.value.length == 0) {
		alert("Must enter a password.");
		document.frmLogin.txtPassword.focus();
		return false;
	}
	
	document.frmLogin.submit();

}

function validateLoginKeyPress(item , keyPressed) {
	if (keyPressed.keyCode == 13) {
	
		// User pressed the enter key
		if (item.name == "txtUserName") {
			document.frmLogin.txtPassword.focus();
			return false;
		} else if (item.name == "txtPassword") {
			//alert(keyPressed.keyCode);
			//keyPressed.keyCode = 0;  //stops the annoying noise!
			validateLoginTopMenuBar();
			//document.frmLogin.submitImage.click();
			return false;
		}
	}
	
	return true;
}


function actionClock() {
	
	var chkDate = getCurrentDate() + " " + getCurrentTime();
	var curDate = document.frmHead.txtClientDate.value + " " + document.frmHead.txtClientTime.value;
	
	timeDiff = dateDiff("n", curDate, chkDate);
	
	if (parseInt(timeDiff) > 0) {
					
		//more than 1 minute passed - so increase the users display..
		var serverDateTime = new Date(addMinutes(document.frmHead.txtServerDate.value + " " + document.frmHead.txtServerTime.value, timeDiff));
		document.frmHead.txtServerTime.value = serverDateTime.getHours() + ":" + serverDateTime.getMinutes() + ":" + serverDateTime.getSeconds();
		document.frmHead.txtServerDate.value = serverDateTime.getDate() + " " + getMonthName(serverDateTime.getMonth() + 1) + " " + serverDateTime.getFullYear();

		//alert(document.frmHead.txtServerDate.value + " " + document.frmHead.txtServerTime.value);

		var clientDateTime = new Date(chkDate);
		//document.frmHead.txtClientTime.value = clientDateTime.getHours() + ":" + clientDateTime.getMinutes() + ":" + clientDateTime.getSeconds();
		//document.frmHead.txtClientDate.value = clientDateTime.getDate() + " " + getMonthName(clientDateTime.getMonth() + 1) + ":" + clientDateTime.getFullYear();

		document.frmHead.txtClientTime.value = getCurrentTime();
		document.frmHead.txtClientDate.value = getCurrentDate();

	}

	displayClientClock();
}

function formatClockTime(timeString) {
	timeString = formatDate(timeString, "hh:nn:ss");
	return formatDate(timeString,"h:nn tt").split(".").join("").toUpperCase()
}

function formatClockDate(dateString) {
	var tmpDate;
	var convDate = formatDate(dateString,"mm/dd/yyyy")
		
	tmpDate = (getDatePart(convDate, "ddd", "").toUpperCase()) + " " + getDatePart(dateString, "d", "");
	tmpDate += getDatePart(dateString, "o", "").toUpperCase();
	return tmpDate;
}

function displayClientClock() {

	window.setTimeout("actionClock();", 10000);  // set to 10 seconds

	var curDate = document.frmHead.txtServerDate.value;
	var curTime = document.frmHead.txtServerTime.value;
			
	var tmpDate = "<div class=\"dayDate\" align=\"right\">"
	tmpDate += formatClockDate(curDate);
	//tmpDate += "<BR><B>" + formatClockTime(curTime) +"</B>" // Time
	tmpDate += "&nbsp;<b>" + formatClockTime(curTime) +"</b>" // Time
	tmpDate += "</div>"

	if (document.all) {
		if (document.getElementById("spnClock") != null) {
			document.getElementById("spnClock").innerHTML=tmpDate;
		}
	} else if (document.getElementById){
		if (document.getElementById("spnClock") != null) {
			document.getElementById("spnClock").innerHTML = tmpDate;
		}
	} else if (document.layers) {
		if (document.layers.spnClock != null) {
			document.layers.spnClock.document.write(tmpDate);
			document.layers.spnClock.document.close();
		}
	} else {
		// we have a problem as date / time wont display
	}
}


function numericOnly (point){
	if (!point && window.event.keyCode == 46){
		window.event.returnValue = false;
	}
	if ((window.event.keyCode < 45 || window.event.keyCode > 57) && window.event.keyCode != 47){
		window.event.returnValue = false;
	}
}


function isDecimal(s, allowDecimal)
{   
	var i;
	var foundDecimal = false;
	if (!allowDecimal) foundDecimal = true;
	
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {
			if (c == ".") {
				if (foundDecimal) {
					return false;
				} else {
					foundDecimal = true;
				}
			} else {
				return false;
			}
		}
		
    }
    // All characters are numbers.
    return true;
}

function decimalPlaces(field, dp){
	var endRange;

	if (dp == 0 && window.event.keyCode == 46){
		window.event.returnValue = false;
		return;
	}
	
	// CATCH INVALID CHARACTERS
	if ((window.event.keyCode < 47 || window.event.keyCode > 57) && window.event.keyCode != 45 && window.event.keyCode != 46) {
		window.event.returnValue = false;
		return;
	}	
	
	if (document.selection.type == "None") {
		// WHEN TEXT NOT SELECTED
		
		endRange = document.selection.createRange();
		endRange.moveEnd("textedit");

		// CATCH MULTIPLE -'S
		if (window.event.keyCode == 45 && (field.value.indexOf("-") != -1 || (field.value.length - endRange.text.length) != 0)) {
			window.event.returnValue = false;
			return;
		}
		
		if (dp != 0) {	
		
			// CATCH DECIMAL POINTS 
			if (window.event.keyCode == 46 && (field.value.indexOf(".") != -1 || endRange.text.length > dp)) {
				window.event.returnValue = false;
				return;
			}	

			// CATCH DECIMAL PLACES 
			if (window.event.keyCode != 45 && window.event.keyCode != 46 && endRange.text.indexOf(".") == -1 && getDecimalPlaces(field.value) >= dp) {
				window.event.returnValue = false;
				return;
			}
		}
		
	} else if (document.selection.type == "Text"){
		// WHEN TEXT SELECTED
	
		endRange = document.selection.createRange();	

		// CATCH MULTIPLE -'S
		if (window.event.keyCode == 45 && (field.value.indexOf(endRange.text) > 0) || (endRange.text.indexOf("-") == -1 && field.value.indexOf("-") != -1)) {
			window.event.returnValue = false;
			return;
		}
		
		if (dp != 0) {
		
			// CATCH DECIMAL POINTS 
			if (window.event.keyCode == 46 && endRange.text.indexOf(".") == -1 && field.value.indexOf(".") != -1) {
				window.event.returnValue = false;
				return;
			}	
					
		}
	}
}


function getSecondsDocumentOpen() {
	var clientDateTime;
	clientDateTime = new Date(document.frmHead.txtClientDate.value + " " + document.frmHead.txtClientTime.value);
	
	var nowDateTime;
	nowDateTime = new Date(getCurrentDateTime());

	var difference;
	
	//milliseconds difference
	difference = nowDateTime.valueOf() - clientDateTime.valueOf();
	
	//seconds difference
	difference /= 1000;
	
	return difference;
}


function changeImageSource(image, newPath) {
	image.src = newPath;
}

function javascriptError(pageName, errorMessage, errorNumber) {
	alert("An error has occurred - please forward this message to Urgent Couriers:\n\n" + pageName + " #" + errorNumber + "\n\n" + errorMessage);

	var rspage = Application["ApplicationPath"] + "/ServerScript/Default.aspx";
	var callback = null;
	var func = "LogException";
	var parms = new Array(pageName + " #" + errorNumber + "\n\n" + errorMessage);
	var callbackArgs = null;
	var visibility = null;
	
	jsrsExecute(rspage, callback, func, parms, callbackArgs, visibility);	
}

function getChildNode(node) {
	var childNode = null;
	
	for (i=0; i < node.childNodes.length; i++) {
	    if (node.childNodes[i].nodeType == 1) {
	        childNode = node.childNodes[i];
	        break;
	    }
	}

    return childNode;
  }
  
function setHeaderSize(){
    var h = screen.height;
    if (h <= 768){
    var s = $("#header").attr("src");
    var n = s.replace('header', 'headersmall');
    $("#header").attr("src", n);
    $(".clock").css("top", "78");
        
    }
}

function setupAd() { $(document).everyTime(duration, function() { $("#mautad").fadeOut("slow", function() { switchAd(); }); }) }

function switchAd() {
  if (ad == 3) { ad = 1 } else { ad += 1; }
  var src = Application["ApplicationPath"] + "/Image/MA_UT_BlackAd_state" + ad + ".jpg";
  $("#mautad a").attr("href", "http://www.mobileadvert.co.nz");
  if (ad == 3) { src = Application["ApplicationPath"] + "/Image/urgenttonight.gif"; $("#mautad a").attr("href", "http://www.urgenttonight.co.nz"); }
  $("#ad").attr("src", src);

  $("#mautad").fadeIn("slow");
  if (ad > 1) {
    $(document).stopTime();
    duration = "4s";
    $(document).everyTime(duration, function() { $("#mautad").fadeOut("slow", function() { switchAd(); }); })
  }
  else {
    $(document).stopTime();
    duration = "14s";
    $(document).everyTime(duration, function() { $("#mautad").fadeOut("slow", function() { switchAd(); }); })
  }

};
  
 function setupAdInternal() {
//    if (ad == 1) {
//        $("#mautad a").attr("href", "#"); 
        //$("#mautad a").bind("click", function(e) { e.preventDefault(); });
//    }
//   if (($.browser.msie) && ($.browser.version.substr(0,1) <= 6 ) &&!window.XMLHttpRequest) {
//        var src = Application["ApplicationPath"] + "/Image/MA_UT_Ad_state1-ds.png";
//        $("#ad").attr("src", src);
//    } 

    if ($.fn.bgiframe) {
        DD_belatedPNG.fix('.adi');
        src = Application["ApplicationPath"] + "/Image/Twitter-ds.png"; 
        $("#ad").attr("src", src);
        src = Application["ApplicationPath"] + "/Image/Facebooknew-ds.png"; 
        $("#ad2").attr("src", src);
        
        }
    $(document).oneTime(duration, function() { 
        switchAdInternal();
        //$("#mautad").fadeOut("fast", function() { switchAdInternal(); }); 
    }) 
 }

function switchAdInternal() {
  if (ad == 4) { ad = 1 } else { ad += 1; }
  if (($.browser.msie) && ($.browser.version.substr(0,1) <= 6 )&&!window.XMLHttpRequest) {
    if(ad == 3){
        var src = Application["ApplicationPath"] + "/Image/MA_UT_Ad_state3-ds.png";
    }
    else if (ad == 2){
        var src = Application["ApplicationPath"] + "/Image/MA_UT_Ad_state2-ds.png";
    };

  }
  else

  {
    var src = Application["ApplicationPath"] + "/Image/MA_UT_Ad_state" + ad + ".png";
  };


  $("#mautad a").attr("href", "http://www.mobileadvert.co.nz");
  if (ad != 1) {
    $("#ad2").hide(); 
    $("#ad").css('width', '354px')
    }
  if (ad == 3){$("#mautad a").unbind("click"); };
  if (ad == 4) { src = Application["ApplicationPath"] + "/Image/urgenttonight.gif"; $("#mautad a").attr("href", "http://www.urgenttonight.co.nz"); $("#mautad a").unbind("click"); }
  if (ad == 2) {$("#mautad a").attr("href", Application["ApplicationPath"] + "/AboutUs/SustainabilityReports.aspx"); $("#mautad a").unbind("click"); }
  //if (ad == 1) {$("#mautad a").attr("href", "#"); $("#mautad a").bind("click", function(e) { e.preventDefault(); });}
  if (ad == 1) {
    if ($.fn.bgiframe) {
        src = Application["ApplicationPath"] + "/Image/Twitter-ds.png"; 
    }
    else{
        src = Application["ApplicationPath"] + "/Image/Twitter.png"; 
    }
    $("#mautad a:first").attr("href", "http://www.twitter.com/UrgentCouriers"); 
    $("#mautad a:last").attr("href", "http://www.facebook.com/UrgentCouriers"); 
    $("#mautad a").unbind("click"); $("#ad").css('width', '177px');
    $("#ad2").show(); 
    
  }
    $("#ad").attr("src", src);
    $("#ad").show();
  
     


  //$("#mautad").fadeIn("fast");
  if (ad > 1) {
    //$(document).stopTime();
    //duration = "10s";
    $(document).oneTime(duration, function() { 
        switchAdInternal(); 
        //$("#mautad").fadeOut("fast", function() { switchAdInternal(); }); 
    })
  }
  else {
    //$(document).stopTime();
    duration = "15s";
    $(document).oneTime(duration, function() { 
        switchAdInternal(); 
        //$("#mautad").fadeIn("fast", function() { switchAdInternal(); }); 
    })
  }

};

function SetupLoggedOutMenu() {
  IERemoveLinkBorders();
  SetupMALink();
  //**Locate active page menu**
  var currentDiv;
  if (window.location.pathname + window.location.search == Application["ApplicationPath"] + '/AboutUs/ContactDetails.aspx') {
    path = Application["ApplicationPath"] + "/AboutUs/ContactDetails.aspx";
    $(".menuContainerLO > ul > li > a[href^='" + path + "']").parent().addClass("current");
  } else {   
      var currentLink = $(".subMenuContainerLO > ul > li > a[href^='" + window.location.pathname + window.location.search + "']"); //first try full path and querystring
      if ((currentLink == null) || (currentLink.length == 0)) {
        var currentLink = $(".subMenuContainerLO > ul > li > a[href^='" + window.location.pathname + "']"); //second try just path
      }
      if ((currentLink == null) || (currentLink.length == 0)) { //third try special cases
        var path = "";
        if (window.location.pathname == Application["ApplicationPath"] + 'Maintenance/Contact.aspx') {
          path = Application["ApplicationPath"] + "/Maintenance/MyProfile.aspx";
          var currentLink = $(".subMenuContainerLO > ul > li > a[href^='" + path + "']");
        }
        if (window.location.pathname == Application["ApplicationPath"] + '/News/Article.aspx') {
          path = Application["ApplicationPath"] + "/News/Default.aspx";
          var currentLink = $(".subMenuContainerLO > ul > li > a[href^='" + path + "']");
        }
        if (window.location.pathname ==  Application["ApplicationPath"] + '/Courier/CourierRequest.aspx') {
          currentDiv = $("#ReqCo")[0];      
        };
        if (window.location.pathname ==  Application["ApplicationPath"] + '/Default.aspx') {
          var r = $(".menuContainer > ul > li > a[href^='" + window.location.pathname + "']").attr("rel"); 
          currentDiv = $("#" + r)[0];
        };

        if (window.location.pathname == Application["ApplicationPath"] + '/TrackTrace/') {
          path = Application["ApplicationPath"] + "/TrackTrace";
          $(".menuContainerLO > ul > li > a[href^='" + path + "']").parent().addClass("current");
        }    
      }
  };
  //**Set Highlight for active page menus
  if ((currentLink != null) && (currentLink.length > 0)) {
    $(".subMenuContainerLO > ul > li").attr("class", ""); //remove hl from sub menu
    //**set top level hl
    currentDiv = currentLink[0].parentNode.parentNode.parentNode;
    var s = currentLink.selector;
    $(s + ':first').parent().addClass("current");

  };
  
  //**
  if (currentDiv != null) { //show current submenu
    ShowSubMenu(currentDiv.id)
    if ($("ul > li > a[rel^='" + currentDiv.id + "']").length > 0) {
      //set highlight on parent menu (2nd or 1st level)
      $("ul > li > a[rel^='" + currentDiv.id + "']:first").parent().addClass("current");
    };
  };

  $("#MainTab > li  > a").click(function(event) {
    //event.preventDefault();
    $("#MainTab > li").attr("class", ""); //remove hl class from main menu
    $(this).parent().attr("class", "current"); //hl current clicked
    $(".subMenuContainerLO > ul > li").attr("class", ""); //remove hl from sub menu
    $(".subMenuContainerLO").hide();
    var r = $(this).attr("rel");
    if ((r != null) && (r.length > 0)) {
      ShowSubMenu(r);  //show current clicked submenu
      $("#" + r + " > ul > li > a").click(function() {
        $(".subMenuContainerLO > ul > li").attr("class", "");
        $(this).parent().attr("class", "current");
      });
    }
  });
}

function SetupMenu() {
  IERemoveLinkBorders();
  SetupMALink();
  var hlcurrent = true;
  var currentLink;
  //**Locate active page menu**
  if (window.location.search.endsWith('International', false) == true){
    currentLink = $(".subMenuContainer > ul > li > a[href='" + window.location.pathname + "?JobEntryType=International" + "']"); //first try full path and querystring
  }else
  {
    currentLink = $(".subMenuContainer > ul > li > a[href='" + window.location.pathname + window.location.search + "']"); //first try full path and querystring
  };
  if ((currentLink == null) || (currentLink.length == 0)) {
    var currentLink = $(".subMenuContainer > ul > li > a[href='" + window.location.pathname + "']"); //second try just path
  }
  if ((currentLink == null) || (currentLink.length == 0)) { //third try special redirects
    var path = "";
    var s = window.location.search;
    if ((window.location.pathname == Application["ApplicationPath"] + '/Maintenance/Contact.aspx') && (s.match("Profile=1") != null)) {
      path = Application["ApplicationPath"] + "/Maintenance/MyProfile.aspx";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
    }else
    if (window.location.pathname ==  Application["ApplicationPath"] + '/Courier/CourierRequest.aspx') {
      currentDiv = $("#ReqCo")[0];      
    }else
    if (window.location.pathname ==  Application["ApplicationPath"] + '/Default.aspx') {
      var r = $(".menuContainer > ul > li > a[href^='" + window.location.pathname + "']").attr("rel"); 
      currentDiv = $("#" + r)[0];
      $("ul > li > a[rel^='" + currentDiv.id + "']:first").parent().addClass("current");
    }else
    if (window.location.pathname ==  Application["ApplicationPath"] + '/News/Article.aspx') {
      path = Application["ApplicationPath"] + "/News/Default.aspx";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
    }else
    if (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Service/', true) == true) {
      path = Application["ApplicationPath"] + "/Service/Default.aspx";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
    }else
    if ((window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Default.aspx', true) == true) && (window.location.search == '?Period=Today')) {
      path = Application["ApplicationPath"] + "/Job/?Period=Today";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
    }else
    if (window.location.pathname == Application["ApplicationPath"] + '/Job/ClientAddressBook/Default.aspx') {
      path = Application["ApplicationPath"] + "/Job/ClientAddressBook/";
      var currentLink = $(".subMenuContainer > ul > li > a[href='" + path + "']");
      
    }else       
    if ((window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Default.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Search.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Detail.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/PrebookDetail.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/', true) == true)  ) {
      path = Application["ApplicationPath"] + "/Job/?Period=Today";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
      hlcurrent = false;
    }else
    
    if ((window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Default.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Search.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/Detail.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/PrebookDetail.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Job/', true) == true)  ) {
      path = Application["ApplicationPath"] + "/Job/?Period=Today";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
      hlcurrent = false;
    }else 
    
    if ((window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Maintenance/ClientContact.aspx', true) == true) || (window.location.pathname.beginsWith(Application["ApplicationPath"] + '/Maintenance/Contact.aspx', true) == true)) {
      path = Application["ApplicationPath"] + "/Maintenance/MyProfile.aspx";
      var currentLink = $(".subMenuContainer > ul > li > a[href^='" + path + "']");
      hlcurrent = false;
    };        
    

   
    


  }
  //**Set Highlight for active page menus
  if ((currentLink != null) && (currentLink.length > 0)) {
    $(".subMenuContainer > ul > li").attr("class", ""); //remove hl from sub menu
    //**set top level hl
    var currentDiv = currentLink[currentLink.length - 1].parentNode.parentNode.parentNode;

    if ($("ul > li > a[rel^='" + currentDiv.id + "']").length > 0) {
      if (currentDiv.id.substring(0, 3) == 'pop') {   //if third level find second level menu & display also
        $("div[id^='pop']").hide(); //hide all popup sub menus
        if (($.browser.msie) && ($.browser.version.substr(0,1) <= 6 ) && !window.XMLHttpRequest) {
            $("ul > li > a[rel^='" + currentDiv.id + "']").css({ 'color': 'black', 'background-image': "url('../Image/submenuhl-DS.png')", 'background-position': 'right', 'outline': 'none' }); //set hl for current
        } 
        else {
            $("ul > li > a[rel^='" + currentDiv.id + "']").css({ 'color': 'black', 'background-image': "url('../Image/submenuhl2.png')", 'background-position': 'right', 'outline': 'none' }); //set hl for current
        };
        
        var subLevelDiv = $("ul > li > a[rel^='" + currentDiv.id + "']")[0].parentNode.parentNode.parentNode;
        if (subLevelDiv != null) {
          //set highlight on parent menu (top level)
          $("ul > li > a[rel^='" + subLevelDiv.id + "']:first").parent().addClass("current");
          ShowSubMenu(subLevelDiv.id)//show current 2nd level menu
        };
      };
      //set highlight on parent menu (2nd or 1st level)
      $("ul > li > a[rel^='" + currentDiv.id + "']:first").parent().addClass("current");
    };

    var s = currentLink.selector;
    if (hlcurrent == true){ $(s).parent().addClass("current");};

  };
  
  //**
  if (currentDiv != null) { //show current submenu
    if (currentDiv.id.substring(0, 3) == 'pop') {   //if third level position properly
      PositionPopupMenu(currentDiv.id);
    }
    ShowSubMenu(currentDiv.id)
  };

  if ((currentLink != null) && (currentLink.length > 0)) {
    if (currentLink[currentLink.length - 1].rel.substring(0, 3) == 'pop') { //if this has third level menu defined
        var r = currentLink[currentLink.length - 1].rel;
        $("div[id^='pop']").hide(); //hide all popup sub menus
        PositionPopupMenu(r);
        ShowSubMenu(r); // show current popup submenu
     }
  };

  
  //** Setup hover and click events for main 2 levels
  $("#MainTab > li  > a").click(function() {
    $("#MainTab > li").attr("class", ""); //remove hl class from main menu
    $(this).parent().attr("class", "current"); //hl current clicked
    $(".subMenuContainer > ul > li").attr("class", ""); //remove hl from sub menu
    HideSubMenus();
    var r = $(this).attr("rel");
    if ((r != null) && (r.length > 0)) {
      ShowSubMenu(r);  //show current clicked submenu
      $("#" + r + " > ul > li > a").click(function() {
        $(".subMenuContainer > ul > li").attr("class", "");
        $(this).parent().attr("class", "current");
      });
    };
  }, null);

  //Setup hover and click events for first menu Home.
  $(".subMenuContainer:first > ul > li  > a").click(function() {
    //$(".subMenuContainer:first > ul > li  > a").css('background-image', "url('../Image/submenudivider.png')");//clear hl from all
    if (($.browser.msie) && ($.browser.version.substr(0,1) <= 6 &&!window.XMLHttpRequest )) {
        $(this).css({ 'color': '#fff', 'background-image': "url('../Image/submenuhl-DS.png')", 'background-position': 'right', 'outline': 'none' });//set hl for current
    }
    else
    {
        $(this).css({ 'color': '#fff', 'background-image': "url('../Image/submenuhl.png')", 'background-position': 'right', 'outline': 'none' });//set hl for current
    };
    var r = 'pop' + $(this).text().replace(" ", "_");
    $("div[id^='pop']").hide(); //hide all popup sub menus
    PositionPopupMenu(r);
    ShowSubMenu(r); // show current popup submenu

  }, function() {
    //
  });
}

function HideSubMenus() {
    $(".subMenuContainer").hide();
}

function ShowSubMenu(id) {
  $("#" + id).show();
}

function PositionPopupMenu(id) {
//  if (($.browser.msie) && ($.browser.version.substr(0,1) <= 6 )) {
//    $("#" + id + '> ul > li > a').css({ 'background-image': "url('../Image/menudividerTop-DS.png')", 'background-position': 'right', 'outline': 'none' }); //set hl for current
//  } 
  $("#" + id).css('margin-top', '0');
  $("#" + id).css('width', '998');
  $("#" + id).css('background-color', '#999999');
}

function IERemoveLinkBorders() {
    $('a').mousedown(function(){this.blur();return false;});
    $('a').click(function(){this.blur();});
    $('a').focus(function(){this.blur();});
    
    $('area').mousedown(function(){this.blur();return false;});
    $('area').click(function(){this.blur();});
    $('area').focus(function(){this.blur();});
    
}

function Stripe() {
    var x = 0;
    $(".jt tr:odd:not(.jt tr:first)").each(function (){
        if (x == 0){
            $(this).addClass('tditemwhite');
            $(this).next("tr").addClass('tditemwhite');
            x = 1;
        }
        else {
            $(this).addClass('tdjtodd');
            $(this).next("tr").addClass('tdjtodd');
            x = 0;        
        };
    });

}

function FetchPrebooks(){
    document.frmJobHead.submit();
};

function VoidJobBooking(jbid, user, jnum, clientID, fromAd){
    $('body').css('cursor', 'wait'); 
    $.ajax({
      type: "Get",
      url: "../GenericHandlers/Jobs.ashx?MethodName=VoidJobBooking",
      data: {JobBookingID: jbid, UserName: user, JobNum: jnum, ClientID: clientID, FromAd:fromAd},
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      cache: false,
      success: function(status) {
        if (status.status == 'warn'){
            alert('Thank you, your cancel job request has been sent to Urgent Couriers.');
        }
        else {
            alert('Your job has now been cancelled');
        };
        document.frmJobHead.submit();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Sorry, an unexpected error occured trying to cancel this job. Urgent Couriers Customer Services have been notified');
      },
      complete: function(XMLHttpRequest, textStatus) {
        $('body').css('cursor', 'default'); 

      }
    });    
}

function open_RateGuideWindow(url)
{
    window.open(url,"_blank","toolbar=yes, location=yes, directories=no, status=yes, menubar=yes, scrollbars=no, resizable=yes, copyhistory=yes, width=500, height=200");
}

function findValueCallback(event, data, formatted) {
    $("#txtSuburbID").val(!data ? "No match!" : data.id);
}

function ShowRateScheduleOptions() {
    $('body').css('cursor', 'wait');
    $.ajax({
      type: "Get",
      url: "../GenericHandlers/Reports.ashx?MethodName=RateScheduleOptions",
      contentType: "text/html; charset=utf-8",
      dataType: "html",
      cache: false,
      success: function(data) {
        $("body").prepend(data);
        //window.location = "../Job/Confirmation.aspx?JobID=" + s[1];
        //Get the screen height and width  
        var maskHeight = $(document).height() - 50; 
        var maskWidth = $(window).width();

        //Set height and width to mask to fill up the whole screen  
        $('#mask2').css({'width':maskWidth,'height':maskHeight});  
            
        //transition effect       
        $('#mask2').fadeIn(1000);      
        $('#mask2').fadeTo("fast",0.83);
        if ($.fn.bgiframe) { $('#mask2').bgiframe(); }    

        //Get the window height and width  
        var winH = $(window).height();  
        var winW = $(window).width();  
                  
        //Set the popup window to center
        $("#dialog2").css('top', winH / 2 - ($("#dialog2").height() / 2) - 100);
        $("#dialog2").css('left', winW / 2 - $("#dialog2").width() / 2);  
        
        //Set up autocomplete for suburbs
        $("#txtSuburb").autocomplete(suburbs, {
            minChars: 0,
            width: 110,
            matchContains: "word",
            autoFill: false,
            formatItem: function (row, i, max) {
              return row.name;
            },
            formatMatch: function (row, i, max) {
              return row.name;
            }

        });
        //Set up autocomplete callback for suburbs
        $("#txtSuburb").result(findValueCallback);

        //transition effect  
        $("#dialog2").fadeIn(1000);   
           
        //if close button is clicked  
        $('.window .close').click(function (e) {  
          //Cancel the link behavior  
          e.preventDefault();
          $('#mask2, .window').hide();
          $('#boxes2').remove();
        });

        $('.window .send').click(function(e) {
          e.preventDefault();
          var pv = 0;
          var gst = 0;
          var ppd = 0;
          var subid = "";
          var ap = "../";
          if ($("#chkGST:checked").length == 1){gst = 1};
          if ($("#rd1:checked").length == 1){pv = 1};
          if ($("#chkPPD:checked").length == 1){ppd = 1};
          if ($("#apppath").val().length > 0) {ap = $("#apppath").val()};
          if ($("#txtSuburbID").val() != "No match!") {subid = $("#txtSuburbID").val()};
          var link = ap + '/Download/RateSchedule.aspx?PriceVariation=' + pv + "&GST=" + gst + "&PPD=" + ppd 
          if (subid != "") { link = link + "&subid=" + subid};
          open_RateGuideWindow(link);
          $('#mask2, .window').hide();
          $('#boxes2').remove();

         });          
        
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Sorry, an unexpected error occured trying to load report options. Please contact Urgent Couriers Customer Services if this problem persists');
      },
      complete: function(XMLHttpRequest, textStatus) {
        $('body').css('cursor', 'default');

      }
    });    
}


function ReadyNow(jbid, jnum){
    $('body').css('cursor', 'wait');
    $.ajax({
      type: "Get",
      url: "../GenericHandlers/Jobs.ashx?MethodName=ReadyNow",
      data: { JobBookingID: jbid, JobNum: jnum },
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      cache: false,
      success: function(status) {
        var s = status.status.split(";");
        if (s[0].beginsWith("True", true)) {
          var chkDate = getCurrentDate();
          var ddif = dateDiff("d", chkDate, s[2])
          if (ddif >=1) {
            alert("The cut off time for Economy jobs has been reached. Your job has now been rebooked for " + s[2] + " with a start time of " + s[0].replace("True", "") + ".\nPlease call customer services on 09 307 3555 if you have any questions regarding this booking.");
          }
          else
          {         
            //alert('Your job has been booked with a start time of ' + s[0].replace("True", ""));
          }
        }
        else {
          alert('Your job has just been moved into our despatch system with with a start time of ' + s[0].replace("False", ""));
        }
        //document.frmJobHead.submit();
        window.location = "../Job/Confirmation.aspx?JobID=" + s[1];
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Sorry, an unexpected error occured trying to book this job. Please contact Urgent Couriers Customer Services if this problem persists');
      },
      complete: function(XMLHttpRequest, textStatus) {
        $('body').css('cursor', 'default');

      }
    });    
}

function SetupMultiLineGridHL(){
    $(".jt2 tr:even").mouseover(function() {
        var tdi = "";
        if (y ==0){
            tdi = "tditemwhite"; 
            y = 1;
        }
        else{
            tdi = "tdjtodd";
            y = 0;
        };
        $(this).removeClass(tdi); 
        $(this).addClass("overjs"); 
        $("td", this).css("color", "black"); 
        $(this).next("tr").removeClass(tdi); 
        $(this).next("tr").addClass("overjs"); 
        $(this).next("tr").find("td").css("color", "black"); 
    }).mouseout(function() { 
        $(this).removeClass("overjs"); 
        $("td", this).css("color", "white");  
        $(this).next("tr").removeClass("overjs"); 
        $(this).next("tr").find("td").css("color", "white");  
        Stripe(); 
    });
    
    $(".jt2 tr:odd").mouseover(function() {
        var tdi = "";
        if (y ==1){
            tdi = "tditemwhite"; 
            y = 0;
        }
        else{
            tdi = "tdjtodd";
            y = 1;
        };
        $(this).removeClass(tdi); 
        $(this).addClass("overjs"); 
        $("td", this).css("color", "black"); 
        $(this).prev("tr").removeClass(tdi); 
        $(this).prev("tr").addClass("overjs"); 
        $(this).prev("tr").find("td").css("color", "black"); 
    }).mouseout(function() { 
        $(this).removeClass("overjs"); 
        $("td", this).css("color", "white");  
        $(this).prev("tr").removeClass("overjs"); 
        $(this).prev("tr").find("td").css("color", "white");  
        Stripe(); 
    });
  };

  function SetupMALink() {
    if ($(".innerRight").length > 0) {
        var bi = $(".innerRight").css('background-image');
        if (bi.endsWith('innerpagePromo.png")', false) == true || bi.endsWith('innerpagePromo.png)', false) == true ) {
            $(".innerRight").css('cursor', 'Pointer');
            $(".innerRight").click(function(event) {
                event.preventDefault();
                window.open('http://www.MobileAdvert.co.nz');
            });
        }
        else {
            $(".innerRight").css('cursor', 'Default');
        };
     }
  }
  
  function SetInnerRight() {
    var images = ["url('../Image/innerpagehelpdesk.png')", "url('../Image/innerpagePromo.png')", "url('../Image/innerpagePromo2.png')", "url('../Image/innerpagePromo3.png')"];
    var random_pos = Math.round(Math.random() * images.length-1);
    $('.innerRight').css('background-image', images[random_pos]);
    var ie6 = $.browser.msie&&($.browser.version.substr(0,1) <= 6)&&!window.XMLHttpRequest;
    if (ie6){DD_belatedPNG.fix('.innerRight');};
}

function ConfirmReadyNow(dfwt, wt, qty, size, refb, toad, tosub, refa, jbid, jnum, alturl) {
  //stop refresh timer
  $(document).stopTime();
  $("#txtJobNumber").text(jnum);
//  $("#hdnJobNumber").text(jbid);
  $("#txtDeliverTo").text(toad);
  $("#txtSuburb").text(tosub);
  $("#txtClientRefa").text(refa);
  $("#txtClientRefb").text(refb);
  if (parseFloat(wt) != 0) { $("#txtWeight").val(parseInt(wt)); } else { $("#txtWeight").val("(If over " + dfwt + "Kg)"); };
  $("#txtQuantity").val(qty);
  $("#cboSize").val(size);
  
  //Get the screen height and width  
  var maskHeight = $(document).height() - 50;
  var maskWidth = $(window).width();

  //Set height and width to mask to fill up the whole screen  
  $('#mask').css({'width':maskWidth,'height':maskHeight});  
    
  //transition effect       
  $('#mask').fadeIn(1000);      
  $('#mask').fadeTo("fast",0.83);    

  //Get the window height and width  
  var winH = $(window).height();  
  var winW = $(window).width();  
          
  //Set the popup window to center
  $("#dialog").css('top', winH / 2 - ($("#dialog").height() / 2) - 100);
  $("#dialog").css('left', winW / 2 - $("#dialog").width() / 2);  

  //transition effect  
  $("#dialog").fadeIn(1000);   
   
  //if close button is clicked  
  $('.window .close').click(function (e) {  
    //Cancel the link behavior  
    e.preventDefault();
    $('#mask, .window').hide();
    SetupRefresh();
  });

  $('.window .send').click(function(e) {
    e.preventDefault();
    $('#mask, .window').hide();
    var weightToSend;
    if ($("#txtWeight").val() == "(If over " + dfwt + "Kg)") {
      weightToSend = 0;
    }
    else {
      weightToSend = parseInt($("#txtWeight").val());
    }
    SaveBooking(jbid, $("#cboSize").val(), weightToSend, parseInt($("#txtQuantity").val()), jnum);
  });  
    
  //if mask is clicked  
//  $('#mask').click(function () {  
//      $(this).hide();  
//      $('.window').hide();  
//  });           

}

function SaveBooking(jbid, size, wt, qty, jnum){
    $('body').css('cursor', 'wait'); 
    $.ajax({
      type: "Get",
      url: "../GenericHandlers/Jobs.ashx?MethodName=SaveBooking",
      data: { JobBookingID: jbid, Size: size, Weight: wt, Qty: qty },
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      cache: false,
      success: function(status) {
        ReadyNow(jbid, jnum);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Sorry, an unexpected error occured trying to save your job booking. Please contact Urgent Couriers Customer Services if this problem persists');
        SetupRefresh();
      },
      complete: function(XMLHttpRequest, textStatus) {
        $('body').css('cursor', 'default');

      }
    });
        
}