// Page-level variable for recording whether it's "dirty". Usable
// for tracking whether warnings are displayed before the page is unloaded
var bIsDirty = false;



// ------------------------ Creates an XmlHttp object ---------------------------------------
function CreateXMLObject() {
	var obj = null;
	try {
		// Try the IE-version-7-and-all-other-browsers mode
		obj = new XMLHttpRequest();
	} catch (e) {
		try {
			obj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				obj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				obj = null;
			}
		}
	}
	return obj;
}

// ---------------------  Standard XmlHttp callback wrapper   ---------------------------------
function newReadyStateHandler(objXML, HandlerFunction) {
  return function () {
  	HandlerFunction(objXML);
  }
}


// ------------------------ Standard body event handlers ---------------------------------------
// ---- All of these attempt to call page-specific handlers in the individual HTML page ----
function BodyLoadHandler(e) {
	try {
		Page_BodyLoad(e);
	}
	catch (e) {}
}
function BodyResizeHandler(e) {
	try {
		Page_BodyResize(e);
	}
	catch (e) {}
}
function BodyMouseDownHandler(e) {
	try {
		return Page_MouseDown(e);
	}
	catch (e) {}
}
function BodyContextMenuHandler(e) {
	try {
		Page_ContextMenu(e);
	}
	catch (e) {}
	return false;
}


function BodyKeyDownHandler(e) {
	try { 
		var k = e.keyCode;
		if (!k) k = e.which;

		// System-wide handling of F1
		if (k ==112) {
			try {

				e.preventDefault();

				e.stopPropagation();
				e.returnValue = false;
				HelpHandler(e);
			}

			catch (err) {}
			return false;
		}

		// System-wide handling of Alt+L for logout
		if (k == 76 && e.altKey) {
			if (confirm("Are you sure you want to log out?")) {
				// Get the location of the logout page. Need to
				// avoid hardcoding the IIS virtual directory into this
				// code in case the directory gets changed.
				var strUrl = document.location.pathname;
				var pSlash = strUrl.lastIndexOf("/");
				strUrl = strUrl.substr(0, pSlash);
				
				// If the current directory is admin or sysadmin we
				// need to go up another level
				if (strUrl.indexOf("/sysadmin") != -1 || strUrl.indexOf("/admin") != -1) {
					pSlash = strUrl.lastIndexOf("/");
					strUrl = strUrl.substr(0, pSlash);
				}
				
				// Add in the logout page
				strUrl += "/logout.asp";
					
				Goto(strUrl);
				return;
			}
		
		}
		
		return Page_KeyDown(k ,e);
	}
	catch (e) {}
}
function BodyKeyPressHandler(e) {
	try { 
		var k = e.keyCode;
		if (!k) k = e.which;
		return Page_KeyPress(k ,e);
	}
	catch (e) {}
}
function BodyScrollHandler(e) {
	try {
		Page_BodyScroll(e);
	}
	catch (e) {}
}


// ---------- RETURNS A FORM'S CONTENTS IN THE FORMAT FOR POSTING (VIA XMLHTTP) ---------------

function GetFormContents(f, bIncludeBlanks) {
	var strValueList = "";
	var strThisValue = "";
	var arrObj = f.getElementsByTagName("INPUT");
	var ctObj = arrObj.length;
	for (var iObj = 0; iObj < ctObj; iObj++) {
		if (arrObj[iObj].name) {
			strThisValue = GetFieldValue(arrObj[iObj]);
			if (strThisValue || bIncludeBlanks) {
				if (strValueList) strValueList += "&";
				strValueList += arrObj[iObj].name + "=" + escape(strThisValue);
			}
		}
	}
	arrObj = f.getElementsByTagName("TEXTAREA");
	ctObj = arrObj.length;
	for (var iObj = 0; iObj < ctObj; iObj++) {
		if (arrObj[iObj].name) {
			strThisValue = GetFieldValue(arrObj[iObj]);
			if (strThisValue || bIncludeBlanks) {
				if (strValueList) strValueList += "&";
				strValueList += arrObj[iObj].name + "=" + escape(strThisValue);
			}
		}
	}
	arrObj = f.getElementsByTagName("SELECT");
	ctObj = arrObj.length;
	for (var iObj = 0; iObj < ctObj; iObj++) {
		if (arrObj[iObj].name) {
			strThisValue = GetFieldValue(arrObj[iObj]);
			if (strThisValue || bIncludeBlanks) {
				if (strValueList) strValueList += "&";
				strValueList += arrObj[iObj].name + "=" + escape(strThisValue);
			}
		}		
	}
	return strValueList;			
}

function GetFieldValue(f) {
	var strTag = f.tagName.toLowerCase();
	var strType = f.type.toLowerCase();
	if (strTag == "input" && (strType == "checkbox" || strType == "radio")) {
		return ((f.checked) ? f.value : "");
	} else if (strTag == "select") {
		var iOpt = f.selectedIndex;
		if (iOpt == -1) {
			return "";
		} else {
			return f.options[iOpt].value;
		}
	} else if (strTag == "input" && strType == "button") {
		return "";
	} else {
		return f.value;
	}
}

function Trim(val) {
	var temp = val.replace(/^[\s]+/g, "");
	temp = temp.replace(/[\s]+$/g, "");
	return temp;
}


// ---------- ASSORTED VALIDATION AND FORMATTING FUNCTIONS ----------------------------
// Age-old text capitalisation function 
function CapitaliseSentences(fd) {
	if (fd.value) {
		if (fd.value == fd.value.toLowerCase()) {
			var newstr = "";
			var mode = 1;
			for (var l=0; l<fd.value.length; l++) {
				var c = fd.value.substr(l,1);

				switch (mode) {
					case 0:
						newstr += c.toLowerCase();
						break;
					case 1:
						newstr += c.toUpperCase();
						break;
					case 2:
						newstr +=c;
						break;
				}
				switch (c) {
					case " ":
						break;
					case ".":
						mode=1;
						break;
					case "'":
						mode = 0;
						if (l>0) {
							if (newstr.substr(l-1,1) == "O") mode=1;							
						}
						break;
					case "c":
						mode = 0;
						if (l>0) {
							if (newstr.substr(l-1,1) == "M") {
								mode = 2;
							} else {
								if (l>1) {
									if (newstr.substr(l-2,2) == "Ma") {
										mode = 2;
									}
								}
							}

						}
						break;
					default:
						mode = 0;
				}
			}

			fd.value = newstr;
		}
	}
}


function CapitaliseText(fd, bNoTrim) {
	if (fd.value) {
		if (!bNoTrim) fd.value = Trim(fd.value);
		if (fd.value == fd.value.toLowerCase()) {
			var newstr = "";
			var mode = 1;

			for (var l=0; l<fd.value.length; l++) {
				var c = fd.value.substr(l,1);

				switch (mode) {
					case 0:
						newstr += c.toLowerCase();
						break;
					case 1:
						newstr += c.toUpperCase();
						break;
					case 2:
						newstr +=c;
						break;
				}


				mode = 0;
				switch (c) {
					case " ":
						mode=1;
						break;
					case "'":
						if (l>0) {
							if (newstr.substr(l-1,1) == "O") mode=1;							
						}
						break;
					case "c":
						if (l>0) {
							if (newstr.substr(l-1,1) == "M") {
								mode = 2;
							} else {
								if (l>1) {
									if (newstr.substr(l-2,2) == "Ma") {
										mode = 2;
									}
								}
							}

						}
						break;
					case "z":
						if (l>2) {
							if (newstr.substr(l-3,3) == "Fitz") mode=2;
						}
						break;
				}
			}

			fd.value = newstr;
		}
	}			
}
function SetInitials(srcfield, destfield) {
	var UFlag = 1;
	var vSrc = srcfield.value;
	var vDest = "";
	for (var n=0; n < vSrc.length; n++) {
		switch (vSrc.substr(n,1)) {
			case " ":
				UFlag=1;
				break;
			default:
				if (UFlag) {
					UFlag=0;
					vDest += vSrc.substr(n,1);					
				}
				break;			
		}
	}
	destfield.value = vDest.toUpperCase();
}
//function ValidateEmail(text) {
//	var p = text.indexOf("@");
//	if (p != -1) p = text.indexOf(".",p);
//	if (p == -1) {
//		return false;
//	} else {
//		return true;
//	}
//}

//New email validation function - email string must not contain leading or trailing spaces.
function ValidateEmail(strEmailAddress) {
    if (window.RegExp) {
        var reg1str = "^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+(?:[A-Z]{2,4}|travel|museum)$";
        var reg1 = new RegExp(reg1str);

        if (!reg1.test(strEmailAddress)) 
            return true;
        return false;
    } else {
        if(strEmailAddress.indexOf("@") >= 0) 
            return true;
        return false;
    }
}




function ToDate(datevalue, md) {
	var parseit = datevalue.split("/");
	var day =1, month, year;
	if (parseit.length<2) {
		if (datevalue.substr(0,1) != "-") parseit = datevalue.split("-");
		if (parseit.length<2) {
			parseit = datevalue.split(".");
			if (parseit.length<2) {
				if (datevalue.length == 6) {
					parseit = new Array(datevalue.substr(0,2),datevalue.substr(2,2),datevalue.substr(4,2));
				} else if (datevalue.length == 8) {
					parseit = new Array(datevalue.substr(0,2),datevalue.substr(2,2),datevalue.substr(4,4));
				} else {
					// May be abbreviation or number of days
					var t = new Date(), add;
					switch (datevalue.toLowerCase()) {
						case 't':
						case 'today':
							break;
						case 'y':
						case 'yesterday':
							t = new Date(t.valueOf() - 86400000);						
							break;
						case 'm':
						case 'tomorrow':
							t = new Date(t.valueOf() + 86400000);						
							break;						
						default: {
							switch (datevalue.substr(0,1)) {
								case '+':
									add = Zval(datevalue.substr(1));
									t = new Date(t.valueOf() + (add * 86400000));						
									break;									
								case '-':
									add = Zval(datevalue.substr(1));
									t = new Date(t.valueOf() - (add * 86400000));						
									break;
								default:
									return null;
							}
						}
					}
					parseit = new Array(2);
					switch (GetLanguage()) {
						case 'en-us':
							parseit[1] = t.getDate();
							parseit[0] = t.getMonth()+1;
							break;
						default:
							parseit[0] = t.getDate();
							parseit[1] = t.getMonth()+1;
							break;
					}
					parseit[2] = t.getFullYear();
				}
			}
		}
	}


	if (parseit.length == 2) {
		if (md == 1) return null;
		switch (GetLanguage()) {
			case 'en-us':
				day = parseInt(parseit[1],10);
				month = parseInt(parseit[0],10);
				break;
			default:
				day = parseInt(parseit[0],10);
				month = parseInt(parseit[1],10);
				break;
		}
		var dt = new Date();
		year = dt.getFullYear();
	} else {
		switch (GetLanguage()) {
			case 'en-us':
				day = parseInt(parseit[1],10);
				month = parseInt(parseit[0],10);
				break;
			default:
				day = parseInt(parseit[0],10);
				month = parseInt(parseit[1],10);
				break;
		}
		year = parseInt(parseit[2],10);
	}
	if (month<1 || month>12) return null;
	if (day<1 || day>31) return null;
	if (year<100) {
	    var dtnow = new Date();
	    var yearnow = dtnow.getFullYear();
	    yearnow = (yearnow-2000)+1
		if (year<yearnow) {
			year += 2000;
		} else {
			year += 1900;
		}
	}
	if (isNaN(day) || isNaN(month) || isNaN(year)) return null;

	// Check end of month - already done those with 31 days
	switch (month) {
		case 4:
		case 6:
		case 9:
		case 11:
			if (day > 30) return null;
			break;
		case 2:
			if (day > 28) {
				// Slight cheat for the sake of simplicity...
				if (year % 4 !=0) return null;
			}
			break;
	}


	// Date is okay
	return new Date(year, month - 1, day);
}

function CheckDate(testdate, md) {
    
	var d = ToDate(testdate.value, md);
	if (!d) return 0;

	switch (GetLanguage()) {
		case 'en-us':
			testdate.value = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
			break;
		default:
			testdate.value = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
			break;
	}
	return 1;
}

function CompareDates(d1, d2) {
	try {
		// Construct new date objects omitting the time
		var nd1 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate());
		var nd2 = new Date(d2.getFullYear(), d2.getMonth(), d2.getDate());

		var dv1 = nd1.valueOf();
		var dv2 = nd2.valueOf();
		if (dv1 < dv2) return -1;
		if (dv1 > dv2) return 1;
		return 0;
	}
	catch (e) {
		return null;
	}

}

function ValidateDate(fd,md) {
	var ok = CheckDate(fd,md);
	if (ok) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
	} else {
		if (fd.value.length == 0) {
			fd.style.backgroundColor = "";
			fd.style.color = "";
		} else {
			fd.style.backgroundColor = "#FF0000";
			fd.style.color = "#FFFFFF";
		}
	}
	return ok;
}
function GetDateFromField(f) {
	if (!CheckDate(f)) return null;

	// Rely on the above setting the format
	var strDateText = f.value;
	var arrDate = strDateText.split("/");

	var objDate;	
	switch (GetLanguage()) {
		case 'en-us':
			objDate = new Date(arrDate[2], arrDate[0]-1, arrDate[1]);
			break;
		default:
			objDate = new Date(arrDate[2], arrDate[1]-1, arrDate[0]);
			break;
	}
	return objDate;

}

function IsBlank(fd) {
	if (fd.value == "") {
		return true;
	} else {
		return false;
	}
}
function IsSpecific(fd) {
	var i = fd.options.selectedIndex;
	if (fd.options[i].specific == "1") {
		return true;
	} else {
		return false;
	}
}
function IsSpecificWithArray(fd,arrX) {
	var i = fd.options.selectedIndex;
	if (i == -1) return false;
	var v = fd.options[i].value;
	for (i=0;i<arrX.length;i++) {
		if (v = arrX[i]) return true;
	}
	return false;
}
function CapitaliseAddress(fd) {
	if (CheckPostcode(fd)) {
		document.getElementById("postcode").value = fd.value;
		fd.value = "";
		// Look for town
		if (document.getElementById("addresstown").value == "") {
			for (var i=3;i!=1;i--) {
				if (document.getElementById("address" + i).value != "") {
					document.getElementById("addresstown").value = document.getElementById("address" + i).value;
					document.getElementById("address" + i).value = "";
					i = 2;
				}
			}
		}
	} else {
		return CapitaliseText(fd);
	}
}
function c_is_numeric(x) {
	if (x>='0' && x<='9') return 1; else return 0;
}
function c_is_alphabetic(x) {
	if ((x>='A' && x<='Z') || (x>='a' && x<='z')) return 1; else return 0;
}
function CheckPostcode(fd) {
	if (fd.value) {
		fd.value = fd.value.toUpperCase();

		// Trim all spaces
		var pc = "";
		for (var n=0;n<fd.value.length;n++) {
			var tc = fd.value.substr(n,1);
			if ( c_is_alphabetic(tc) || c_is_numeric(tc) ) {
				pc += tc;
			} else {
				if (tc!=' ') {
					return 0;
				}
			}
		}
		var l = pc.length;
		if (l<5 || l>7) {
			return 0;
		}

		// Check last three characters
		if (!c_is_alphabetic(pc.substr(l-1,1))) return 0;			
		if (!c_is_alphabetic(pc.substr(l-2,1))) return 0;			
		if (!c_is_numeric(pc.substr(l-3,1))) return 0;			
		if (!c_is_alphabetic(pc.substr(0,1))) return 0;			

		pc = pc.substr(0,l-3) + " " + pc.substr(l-3,3);
		fd.value = pc;			
		return 1;
	}			
	return 0;
}

function ValidatePostcode(fd) {
	var ok = CheckPostcode(fd);
	if (ok) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
	} else {
		if (fd.value.length == 0) {
			fd.style.backgroundColor = "";
			fd.style.color = "";
		} else {
			fd.style.backgroundColor = "#FF0000";
			fd.style.color = "#FFFFFF";
		}
	}
	return ok;
}

function Xval(x, AllowStartWithNonAlpha) {
	try {
	var v = 0;
	var m = 0;
	var f = 1;
	var g = 0;
	for (var i=0;i<x.length;i++) {
		var c = x.substr(i,1);
		switch (c) {
			case ' ':
			case '\240':
				break;

			case '-':
				if (g) return 0;
				g++;
				f = -1;
				break;

			case ',':	
				g++;
				break;

			case '.':
				if (m) return 0;
				g++;
				m=10;
				break;

			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				g++;
				if (!m) {
					v = v * 10;
					v = v + parseInt(c);
				} else {
					v = v + (parseInt(c) / m);
					m = m * 10;
				}
				break;
			default:
				if (g || !AllowStartWithNonAlpha) return 0;
				break;
		}
	}
	return v * f;	
	}
	catch (e) {
	}
}

function Zval(x, md) {
	var v = Xval(x, md);
	if (isNaN(v)) return 0;
	if (v <= 0) return 0;
	return v;
}

function GetComboNumericValue(fd) {
	return Zval(GetComboValue(fd));
}

function GetComboValue(fd) {
	if (fd.selectedIndex == -1)  {
		return "";
	} else {
		return fd.options[fd.selectedIndex].value;
	}
}

function ZZ(x) {
	if (x < 10) {
		return "0" + x;
	} else {
		return x;
	}
}

function CheckTime(fd) {
	// Split into two parts
	var x = fd.value;
	var parseit = x.split(":");
	if (parseit.length!=2)	parseit = x.split(".");
	if (parseit.length!=2)	parseit = x.split("-");

	// Allow entry of hour only
	if (parseit.length == 1) {
		var x = parseit[0];
		parseit = new Array(2);
		parseit[0] = x;
		parseit[1] = 0;
	}
	if (parseit.length!=2) return false;
	// Check that the parts are consistent
	var h = parseInt(parseit[0]);
	if (isNaN(h)) return false;
	// Adjust hour if not probable, and not explicitly specified
	if (h < 7 && parseit[0].length == 1) h+=12;	
	var m = parseInt(parseit[1]);
	if (isNaN(m)) return false;
	if (h<0 || h>23) return false;
	if (m<0 || m >59) return false;
	fd.value = ZZ(h) + ":" + ZZ(m);
	return true;
}
function ValidateTime(fd) {
	var ok = CheckTime(fd);
	if (ok) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
	} else {
		if (fd.value.length == 0) {
			fd.style.backgroundColor = "";
			fd.style.color = "";
		} else {
			fd.style.backgroundColor = "#FF0000";
			fd.style.color = "#FFFFFF";
		}
	}
	return ok;
}
function CheckNINumber(fd) {
	if (fd.value) {
		fd.value = fd.value.toUpperCase();
		if (fd.value.length == 9) {
			if (!c_is_alphabetic(fd.value.substr(0,1))) return false;
			if (!c_is_alphabetic(fd.value.substr(1,1))) return false;
			for (var i =2; i < 8; i++) {
				if (!c_is_numeric(fd.value.substr(i,1))) return false;
			}
			if (!c_is_alphabetic(fd.value.substr(8,1))) return false;
			return true;
		}
	}
}
function ValidateNINumber(fd) {
	var ok = CheckNINumber(fd);
	if (ok) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
	} else {
		if (fd.value.length == 0) {
			fd.style.backgroundColor = "";
			fd.style.color = "";
		} else {
			fd.style.backgroundColor = "#FF0000";
			fd.style.color = "#FFFFFF";
		}
	}
	return ok;
}

function ValidateCardDate(f,bForExpiry) {
	var v = f.value;
	if (!v) return false;
	var r = CheckCardDate(v,bForExpiry);
	if (r=="") {
		f.style.backgroundColor = "#FF0000";
		f.style.color = "#FFFFFF";
		f.style.fontWeight = "bold";
		return false;
	} else {
		f.style.backgroundColor = "";
		f.style.color = "";
		f.style.fontWeight = "";
		f.value = r;
		return true;
	}
}
function CheckCardDate(v, bForExpiry) {
	var arrD = v.split("/");
	var bOk = false;

	if (arrD.length == 2) {
		var m = parseInt(arrD[0]);
		var y = parseInt(arrD[1]);
		if (m > 1 && m < 13) {
			var d = new Date();
			var thisy = d.getFullYear();
			var thism = d.getMonth() + 1;

			var testy = y;
			if (y > 50) {
				testy +=1900;
			} else {
				testy+= 2000;
			}
			
			if (bForExpiry) {
				if (testy < thisy || (testy == thisy && m < thism)) return "";
			} else {
				if (testy > thisy || (testy == thisy && m > thism)) return "";
			}

			// Okay
			return ZZ(m) + "/" + ZZ(y);
		}
	}
	return "";
}

function NumberCommas(f) {
	var x = f.value;
	var n = Math.abs(parseFloat(x));
	if (!isNaN(n)) {
		var arrF = new Array(12);
		for (var i=10; i > -3; i--) {
			var iF = Math.pow(10, i);
			arrF[i+2] = Math.floor(n / iF);
			n -= (arrF[i+2] * iF);
		}
		
		var tx = "", bStart = false;
		for (var i=10; i >= 0; i--) {
			if (arrF[i+2] || bStart) {
				tx += arrF[i+2];
				if (i == 3 || i==6 || i==9 || i==12) tx += ",";
				if (arrF[i+2]) bStart = true;
			}
		}
		if (arrF[1]!=0 || arrF[0]!=0) {
			tx += "." + arrF[1] + arrF[0];
		}

		f.value = tx;
	}	

}

function ValidateAndCapitalise(fd, bNoTrim) {
	CapitaliseText(fd, bNoTrim);
	if (fd.value.length) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
		return true;
	} else {
		fd.style.backgroundColor = "#FF0000";
		fd.style.color = "#FFFFFF";
		return false;
	}
}

function ValidateAndCapitaliseSentences(fd) {
	CapitaliseSentences(fd);
	if (fd.value.length) {
		fd.style.backgroundColor = "";
		fd.style.color = "";
		return true;
	} else {
		fd.style.backgroundColor = "#FF0000";
		fd.style.color = "#FFFFFF";
		return false;
	}
}


function ValidateEmailField(fd) {
	if (ValidateEmail(fd.value)) {
		fd.value = fd.value.toLowerCase();
		fd.style.backgroundColor = "";
		fd.style.color = "";
		return true;
	} else {
		fd.style.backgroundColor = "#FF0000";
		fd.style.color = "#FFFFFF";
		return false;
	}
}


function IsValidYear(f, bAllowFuture) {
	var l = Zval(f.value);
	if (!l) return false;
	if (l < 100) {
		if (l < 10) {
			l += 2000;
		} else {
			l += 1900;
		}
		f.value = l;
	}
	if (l < 1930) return false;
	if (!bAllowFuture) {
		var d = new Date();
		if (l > d.getFullYear()) return false;
	}
	return true;
}


function EncodeForUrl(strX) {
	var strQ = strX.replace(/[+]/g, "%2B");
	strQ = strQ.replace(/[ ]/g, "+");
	strQ = strQ.replace(/[&]/g, "%26");
	return strQ;
}
function nothing(){}

function FormatNumber(val, DecimalPlaces, SeparateThousands) {
	if (isNaN(val)) return "";

	
	if (!SeparateThousands || (val < 1000 && val > -1000)) {
		return val.toFixed(DecimalPlaces);
	} else {
		// nasty, nasty, nasty
		var strNum = Math.abs(val).toFixed(0);
		var strNewNum = "";
		var szNum = strNum.length;
		for (var i = szNum -1; i >=0 ;i--) {
			strNewNum =  strNum.substr(i,1) + strNewNum;
			if (i && ((szNum - i) % 3) == 0) strNewNum = "," + strNewNum;
		}
		// Restore sign and decimal places
		if (val < 0) strNewNum = "-" + strNewNum;
		if (DecimalPlaces > 0) {
			var strDec = val.toFixed(DecimalPlaces);
			var p = strDec.lastIndexOf(".");
			strNewNum += strDec.substr(p, strDec.length - p);
		}
		return strNewNum;		
	}
}





// ######################################################
// Miscellaneous GUI functions
// ######################################################

function KillKeyPress(e) {
	try {
		e.returnValue = false;
		e.cancelBubble = true;
		if (whichBrs() == "Internet Explorer") {
			e.keyCode = 0;
		} else {
			e.preventDefault();
			e.stopPropagation();
		}
		return false;
	}
	catch (e) {return false;}
}


// Time-honoured image replacement functions
function MM(fd) {
	var img = fd.src;
	var re = /u_/g;
	img=img.replace(re, "s_");
	fd.src = img;
}
function MO(fd) {
	var img = fd.src;
	var re = /s_/g;
	img=img.replace(re, "u_");
	fd.src = img;
}

// Generic function for showing and hiding a section
function ShowHideSection(sectionname, f) {
	var s = document.getElementsByName(sectionname);
	if (!s.length) {
		ShowHideRecursive(document.body, sectionname, f);
	} else {
		for (var iS = 0; iS < s.length; iS++) {
			if (f) {
				s[iS].style.display = (f.checked ? "" : "none");
			} else {
				if (s[iS].style.display == "none") {
					s[iS].style.display = "";
				} else {
					s[iS].style.display = "none";
				}
			}
		}
	}
}
function ShowHideRecursive(objRoot, sectionname,f) {
	if (objRoot.childNodes) {
		var cC = objRoot.childNodes.length;
		for (var iC =0; iC < cC; iC++) {
			ShowHideRecursive(objRoot.childNodes.item(iC), sectionname, f);
			if (objRoot.childNodes.item(iC).name) {
				if (objRoot.childNodes.item(iC).name == sectionname) {
					if (f) {
						objRoot.childNodes.item(iC).style.display = (f.checked ? "" : "none");
					} else {
						if (objRoot.childNodes.item(iC).style.display == "none") {
							objRoot.childNodes.item(iC).style.display = "";
						} else {
							objRoot.childNodes.item(iC).style.display = "none";
						}
					}
				} else {
				}
			}
		}
	}
}

// Retrieves the x and y coordinates of an object in terms of pixels from the
// top left of the page
function getXY(Obj) 
{
var sumTop=0;
var sumLeft=0;
var bStop = false;
while (!bStop) {
	sumTop +=Obj.offsetTop;
	sumLeft +=Obj.offsetLeft;
	Obj=Obj.offsetParent;
	if (!Obj) {
		bStop = true;
	} else {
		if (Obj==document.body) bStop = true;
	}

}
return {left:sumLeft,top:sumTop}
}


// Handles the showing/hiding of an element with a plus/minus button.
function ShowHideRT(elemname) {
	try {
		var elem = document.getElementById(elemname);
		if (elem) {

			var img = document.getElementById("img" + elemname);
			var imgroot = img.src.substr(0,img.src.lastIndexOf('/'));
			var state = 1;
			if (elem.style.display == "none") {
				elem.style.display = "";
				img.src = imgroot + "/rtup.gif";
			} else {
				elem.style.display = "none";
				img.src = imgroot + "/rtdown.gif";
				state = 0;
			}
		}
	}
	catch(excep) {
		var dummy=0;
	}
	return;
}

function HideParentDiv(elemname) {
try {
			var e = window.parent.document.getElementById(elemname);
			if (e) e.style.display = "none";
		}
		catch(excep) {
			var gk=0;
		}
		return;					
}
function ElemShowHide(elemname) {
try {
			var e = document.getElementById(elemname);
			if (e) {
				if (e.style.display == "none") {
					e.style.display = "";
				} else {
					e.style.display = "none";
				}
			}
		}
		catch(excep) {
			var gk=0;
		}
		return;					
}


// ######################################################
// Cookie functions
// ######################################################

function SetCookie(sName, sValue)
{
	var cexp = new Date(); 
	cexp.setTime(cexp.getTime() + (3600000 * 24 * 300)); 
	document.cookie = sName + "=" + escape(sValue) + "; expires=" + cexp.toGMTString() +"; path=/; ";
}

function SetSessionCookie(sName, sValue)
{
	document.cookie = sName + "=" + escape(sValue) + "; path=/;";
}

function DeleteCookie(sName) { 
	var cexp = new Date(); 
	cexp.setTime(cexp.getTime() - 1); 
	document.cookie = sName + "=;expires=" + cexp.toGMTString() + "; path=/; ";
}

function GetCookie(sName) {
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++) {
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) return unescape(aCrumb[1]);
	}
	return "";
}

// Tests to see if the user's browser is prepared to accept session cookies
function CheckForSessionCookies() {
	// Test cookies
	var d = new Date();
	var t = d.valueOf();
	document.cookie = "spcookietest=" + t + ";path=/";
	return (document.cookie.indexOf("spcookietest=" + t) != -1);
}


// ######################################################
// Status window functions.
// ######################################################

var objStatusWindow;
var tmrStatusWindow;
function CreateStatusWindow(StatusText, ContextUrl, width, height) {
	clearInterval(tmrStatusWindow);
	tmrStatusWindow = setInterval("CreateStatusWindow2(\42" + StatusText + "\42)", 1);
}

function CreateStatusWindow2(StatusText) {
	clearInterval(tmrStatusWindow);

	var objDiv = document.getElementById("LoadingBar");
	if (!objDiv) {
		objDiv = document.createElement("DIV");
		objDiv.id = "LoadingBar";
		objDiv.style.position = "absolute";
		objDiv.style.backgroundColor = "#FFFFF0";
		objDiv.style.color = "black";
		objDiv.style.border = "solid 1px #C0C0C0";
		objDiv.style.padding = "2px";
		objDiv.style.display = "none";
		objDiv.style.fontSize = "8pt";
		objDiv.style.textAlign = "center";
		objDiv.style.verticalAlign = "middle";
		objDiv.style.whiteSpace = "nowrap";
		document.body.appendChild(objDiv);
	}
	var w = document.body.offsetWidth;
	
	objDiv.style.top = "0px";
	objDiv.style.height = "15px";
	objDiv.innerHTML = StatusText;
	objDiv.style.display = "";

	objDiv.style.left = (w - objDiv.offsetWidth) + "px";
	objDiv.style.zIndex = 100;
}

function KillStatusWindow() {
	clearInterval(tmrStatusWindow);
	var objDiv = document.getElementById("LoadingBar");
	if (objDiv) {
		objDiv.style.display = "none";
	}
}


function IsCtrlPressed() {
	var bYesNo = false;
	try {
		if (event.ctrlKey) bYesNo = true;
	}
	catch(excep) {
		bYesNo = false;
	}
	return bYesNo;
}


function SelectAllTextField(f) {
	try {
		f.select();
	}
	catch (e) {}
}

// ######################################################
// Misc service functions
// ######################################################

function Goto(x) {
	document.location = RefreshableUrl(x);
}


function OnMouseover(elem) {
	var strClass = elem.className;
	if (strClass.indexOf("MouseOver") == -1) {
		strClass += (strClass ? " " : "") + " MouseOver";
		elem.className = strClass;
	}
}
function OnMouseout(elem) {
	var strClass = elem.className;
	if (strClass.indexOf("MouseOver") != -1) {
		strClass = Trim(strClass.replace(/MouseOver/g,""));
		elem.className = strClass;
	}
}



// Checks the availability of XMLHTTP. The (optional) first parameter specifies
// whether or not to do a check for setRequestHeader, which isn't implemented by Opera
function CheckXMLHTTP(bDoRequestHeaderCheck) {
	try {
		var objX = CreateXMLObject();
		objX.open("GET", "test.htm", false);
		if (bDoRequestHeaderCheck) objX.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		if (objX.readyState) {
			return true;
		} else {
			return false;
		}
	}
	catch (e) {
		return false;
	}
}

// Checks which browser we're dealing with. Note the need
// to check for things which masquerade as IE before IE itself
function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
	return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else return 'Netscape';} else return navigator.userAgent.substr(0,agt.indexOf(' '));
}


function RefreshableUrl(x) {
	var d = new Date();
	var strAddTx = "refresh=" + d.valueOf();
	if (x.indexOf("?") != -1) {
		return x + "&" + strAddTx;
	} else {
		return x + "?" + strAddTx;
	}
}


function GetLanguage() {
	return strBrowserLanguage;
}

function SetDirty() {
	bIsDirty = true;
}


function AllowCM(e) {
	e.returnValue = true;
	e.cancelBubble=true;
	return true;
}

function QuoteLink(elem, e) {
	var h = 600;
	var w = 800;
	var t = (screen.availHeight - h) / 2;
	var l = (screen.availWidth - w) / 2;

	var objW = window.open(elem.href, "", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",resizable=yes");
	if (!objW) {
		alert("Your browser software is preventing new windows from being opened. Please turn off your popup blocker.");
	} else {
		e.returnValue = false;
		return false;
	}
}

function IsMac() {
	if (navigator.platform.indexOf("Mac") == 0) {
		return true;
	} else {
		return false;
	}
}

function HelpHandler(e) {
	try {
		e.returnValue = false;

		// Get the help topic id
		var strTopicId = "";
		if (document.getElementById("helptopic")) {
			strTopicId = document.getElementById("helptopic").value;
		}
        OpenHelpPage(strTopicId);

	}
	catch (ex) {}
}

function OpenHelpPage(TopicId)
{
		// Work out the page location
		var hWindow = screen.availHeight * 0.8;
		var wWindow = screen.availWidth * 0.9;

		var tWindow = (screen.availHeight - hWindow) / 2;
		var lWindow = (screen.availWidth - wWindow) / 2;

		var strUrl = RefreshableUrl(strContextPath + "help.asp?topic=" + TopicId);
		var objW = window.open(strUrl, "HelpWindow", "top=" + tWindow + ",left=" + lWindow + ",width=" + wWindow + ",height=" + hWindow + "");
		if (!objW) {
			alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see the help file.");
		}
		objW.focus();
}

function XshowModalDialog(Url, ReturnValue, Settings) {
	try {
		return window.showModalDialog(Url, ReturnValue, Settings);
	}
	catch (err) {
		alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see this screen.");
	}
}

// Information about the AKG (ratingtype=1), Moodys, and S&P ratings
function RatingsInfo(RatingType) {
	// Work out the page location
	var hWindow = screen.availHeight * 0.7;
	var wWindow = screen.availWidth * 0.8;

	var tWindow = (screen.availHeight - hWindow) / 2;
	var lWindow = (screen.availWidth - wWindow) / 2;

	var strUrl = "";
	switch (RatingType) {
		case 1:
			strUrl = "http://www.akg.co.uk";
			break;
		
		case 2:
			strUrl = "http://www.moodys.com";
			break;
			
		case 3:
			strUrl = RefreshableUrl(strContextPath + "sandp.asp");
			break;
	}
	var objW = window.open(strUrl, "Ratings", "top=" + tWindow + ",left=" + lWindow + ",width=" + wWindow + ",height=" + hWindow + ",menubar=1,location=1,resizable=1,scrollbars=1,status=0,titlebar=1,toolbar=1");
	if (!objW) {
		alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see the help file.");
	}
	objW.focus();
}

function NotLicensed() {
	alert("Your firm has not bought a licence for this area of the software. Please contact your Synaptic account manager to upgrade your system.");
}

function HidePageScrollbars() {
	document.body.style.overflow = "hidden";
	document.body.parentNode.style.overflow = "hidden";
}

// Tests to see if a fund ID is a user portfolio ID
function FundIdIsPortfolio(X) {
	if (X.length == 32) {
		return true;
	} else {
		return false;
	}
}

//Qaisar Report printing errors flag to set whether Word 2000 or lower
var intword2000 = 0;
function IsWord2000(e) {

	if (e.checked) {
		intword2000 = 1;
		if (document.getElementById("Word2000a")){
		    document.getElementById("Word2000a").value = "Word2000"
		}
		if (document.getElementById("Word2000b")){
		    document.getElementById("Word2000b").value = "Word2000"
		}
	} else {
		intword2000 = 0;
		if (document.getElementById("Word2000a")){
		    document.getElementById("Word2000a").value = "not"
		}
		if (document.getElementById("Word2000b")){
		    document.getElementById("Word2000b").value = "not"
        }
	}
}

var bNoLoadingFlag = false;
function NoLoadMsg() {
	bNoLoadingFlag  = true;
}

function OnBeforeUnload(e) {
	try {
		if (Page_OnBeforeUnload(e)) return;
	}
	catch (err) {}

	if (bNoLoadingFlag) {
		bNoLoadingFlag = false;
	} else {
		//CreateStatusWindow("Loading...");
	}
}

function OnUnload() {
	KillStatusWindow();
}

function BespokeRatingToText(strFieldVal) {
	var lVal = Xval(strFieldVal);
	if (strFieldVal == "") {
		// Null
		return "";
	} else if (lVal >= 2) {
		return "Very good";
	} else if (lVal >= 1) {
		return "Good";
	} else if (lVal >= 0) {
		return "Neutral";
	} else if (lVal >= -1) {
		return "Bad";
	} else  {
		return "Awful";
	}
}

function BespokeRatingTextToValue(X) {
	switch (X.toLowerCase()) {
		case "awful":
			return -2;
		case "bad":
			return -1;
		case "neutral":
			return 0;
		case "good":
			return 1;
		case "very good":
			return 2;
	}
}

function BringOutSurvey(X,Y,Z) {
    //Survey Display Function Qaisar 
	// Work out the page location
	var hWindow = screen.availHeight * 0.8;
	var wWindow = screen.availWidth * 0.65;

	var tWindow = (screen.availHeight - hWindow) / 2;
	var lWindow = (screen.availWidth - wWindow) / 2;
	var strFeatures = "location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no";
	strFeatures += ",top=" + tWindow + ",left=" + lWindow + ",width=" + wWindow + ",height=" + hWindow;
    //Now depending on what is sent send to different surveys this is for fund and product only customers
    //This is for 1684 and may be removed
    
	if (Z==0) {
		var strUrl = "http://www.synaptic.co.uk/Surveys/FullIncentive/default.asp?user=" + X + "&organisation=" + Y + "&firmtype=" + Z;
	} else if (Z==1)  {		
		var strUrl = "http://www.synaptic.co.uk/Surveys/freefunds/default.asp?user=" + X + "&organisation=" + Y + "&firmtype=" + Z;
	} else {
	    var strUrl = "http://www.synaptic.co.uk/Surveys/freeproduct/default.asp?user=" + X + "&organisation=" + Y + "&firmtype=" + Z;
	}
	var objW = window.open(strUrl, "", strFeatures);
	if (!objW) {
		alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see the survey.");
	}
}

