/* */
var myTips;

var hide_filters;
var show_filters;
var mclassic_left;
/* */

/* */
var bodyOnload = function ()
	{
		setFilterToggles ();
		
		myTips = new Tips($$('.tooltip'));
	}
	
var setFilterToggles = function ()
	{
		hide_filters = $('hide_filters');
		show_filters = $('show_filters');
		mclassic_left = $('mclassic_left');

		positionField (hide_filters,mclassic_left,'bottomRight');
		positionField (show_filters,mclassic_left,'topRight');
		
		var filter_section = $('filter_section');
		
		if (filter_section)
		{		
			hide_filters.addEvent('click',function()
			{
				hide_filters.setStyle('display','none');
				
				var temp_filter_section = $('filter_section');
				
				temp_filter_section.set('slide',
					{
						onComplete: function()
							{
								show_filters.setStyle('display','block');
							}
					});
					
				temp_filter_section.slide('out');
			});
			
			show_filters.addEvent('click',function()
			{
				show_filters.setStyle('display','none');
			
				var temp_filter_section = $('filter_section');
				
				temp_filter_section.set('slide',
					{
						onComplete: function()
							{
								hide_filters.setStyle('display','block');
							}
					});
				
				temp_filter_section.slide('in');
			});
			
			show_filters.setStyle('display','none');
			hide_filters.setStyle('display','block');
		}
		else
		{
			hide_filters.set('style','display:hidden;');
			show_filters.set('style','display:hidden;');
		}
	}
	

/* */

var browser_name;
var browser_version;
id_browser();
function id_browser(){
	if (navigator.userAgent.indexOf('Opera') != -1) {
		if (navigator.userAgent.indexOf('Opera/') != -1) {  // Opera as Opera
			browser_name = 'Opera';
			browser_version = navigator.appVersion;}
		
		if (navigator.userAgent.indexOf('Opera ') != -1) {   // Opera identifying as somebody else
			browser_name = 'Opera';
			temp = navigator.userAgent.split("Opera")
			browser_version = temp[1];
		}
	}else{    // if it is not opera check the others
	var mozilla = navigator.appCodeName;
	if (navigator.appName == "Netscape" && mozilla != "Mozilla"){// determine mozilla based version
		browser_name = "Netscape";
		browser_version = navigator.appVersion;}
	if (mozilla=="Mozilla"){
		browser_name	= "Mozilla Firefox";
		browser_version = '';}

	if (navigator.appVersion.indexOf("MSIE")!=-1){  // determine IE version
		browser_name = "IE";
		temp = navigator.appVersion.split("MSIE");
		browser_version = temp[1];}
	}
	return browser_name, browser_version;
}

var ajaxRunning = false;	//ajax variable to state that an ajax request is running
var accordion;				//accordion variable for toggling

var monthDays, weekDays
monthDays = "1^2^3^4^5^6^7^8^9^10^11^12^13^14^15^16^17^18^19^20^21^22^23^24^25^26^27^28^29^30^31"
weekDays = "1^2^3^4^5^6^7"
<!-- Original:  Sandeep Tamhankar (stamhankar@hotmail.com) -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
/* Here's the list of tokens we support:
   m (or M) : month number, one or two digits.
   mm (or MM) : month number, strictly two digits (i.e. April is 04).
   d (or D) : day number, one or two digits.
   dd (or DD) : day number, strictly two digits.
   y (or Y) : year, two or four digits.
   yy (or YY) : year, strictly two digits.
   yyyy (or YYYY) : year, strictly four digits.
   mon : abbreviated month name (April is apr, Apr, APR, etc.)
   Mon : abbreviated month name, mixed-case (i.e. April is Apr only).
   MON : abbreviated month name, all upper-case (i.e. April is APR only).
   mon_strict : abbreviated month name, all lower-case (i.e. April is apr 
         only).
   month : full month name (April is april, April, APRIL, etc.)
   Month : full month name, mixed-case (i.e. April only).
   MONTH: full month name, all upper-case (i.e. APRIL only).
   month_strict : full month name, all lower-case (i.e. april only).
   h (or H) : hour, one or two digits.
   hh (or HH) : hour, strictly two digits.
   min (or MIN): minutes, one or two digits.
   mins (or MINS) : minutes, strictly two digits.
   s (or S) : seconds, one or two digits.
   ss (or SS) : seconds, strictly two digits.
   ampm (or AMPM) : am/pm setting.  Valid values to match this token are
         am, pm, AM, PM, a.m., p.m., A.M., P.M.
*/
// Be careful with this pattern.  Longer tokens should be placed before shorter
// tokens to disambiguate them.  For example, parsing "mon_strict" should 
// result in one token "mon_strict" and not two tokens "mon" and a literal
// "_strict".

var tokPat=new RegExp("^month_strict|month|Month|MONTH|yyyy|YYYY|mins|MINS|mon_strict|ampm|AMPM|mon|Mon|MON|min|MIN|dd|DD|mm|MM|yy|YY|hh|HH|ss|SS|m|M|d|D|y|Y|h|H|s|S");

// lowerMonArr is used to map months to their numeric values.

var lowerMonArr={jan:1, feb:2, mar:3, apr:4, may:5, jun:6, jul:7, aug:8, sep:9, oct:10, nov:11, dec:12}

// monPatArr contains regular expressions used for matching abbreviated months
// in a date string.

var monPatArr=new Array();
monPatArr['mon_strict']=new RegExp(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/);
monPatArr['Mon']=new RegExp(/Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec/);
monPatArr['MON']=new RegExp(/JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC/);
monPatArr['mon']=new RegExp("jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec",'i');

// monthPatArr contains regular expressions used for matching full months
// in a date string.

var monthPatArr=new Array();
monthPatArr['month']=new RegExp(/^january|february|march|april|may|june|july|august|september|october|november|december/i);
monthPatArr['Month']=new RegExp(/^January|February|March|April|May|June|July|August|September|October|November|December/);
monthPatArr['MONTH']=new RegExp(/^JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER/);
monthPatArr['month_strict']=new RegExp(/^january|february|march|april|may|june|july|august|september|october|november|december/);

// cutoffYear is the cut-off for assigning "19" or "20" as century.  Any
// two-digit year >= cutoffYear will get a century of "19", and everything
// else gets a century of "20".

var cutoffYear=50;

// FormatToken is a datatype we use for storing extracted tokens from the
// format string.

function FormatToken (token, type) {
this.token=token;
this.type=type;
}

function parseFormatString (formatStr) {
var tokArr=new Array;
var tokInd=0;
var strInd=0;
var foundTok=0;
    
while (strInd < formatStr.length) {
if (formatStr.charAt(strInd)=="%" &&
(matchArray=formatStr.substr(strInd+1).match(tokPat)) != null) {
strInd+=matchArray[0].length+1;
tokArr[tokInd++]=new FormatToken(matchArray[0],"symbolic");
} else {

// No token matched current position, so current character should 
// be saved as a required literal.

if (tokInd>0 && tokArr[tokInd-1].type=="literal") {

// Literal tokens can be combined.Just add to the last token.

tokArr[tokInd-1].token+=formatStr.charAt(strInd++);
}
else {
tokArr[tokInd++]=new FormatToken(formatStr.charAt(strInd++), "literal");
      }
   }
}
return tokArr;
}

/* buildDate does all the real work.It takes a date string and format string,
 tries to match the two up, and returns a Date object (with the supplied date
 string value).If a date string doesn't contain all the fields that a Date
 object contains (for example, a date string with just the month), all
 unprovided fields are defaulted to those characteristics of the current
 date. Time fields that aren't provided default to 0.Thus, a date string
 like "3/30/2000" in "%mm/%dd/%yyyy" format results in a Date object for that
 date at midnight.formatStr is a free-form string that indicates special
 tokens via the % character.Here are some examples that will return a Date
 object:

 buildDate('3/30/2000','%mm/%dd/%y') // March 30, 2000
 buildDate('March 30, 2000','%Mon %d, %y') // Same as above.
 buildDate('Here is the date: 30-3-00','Here is the date: %dd-%m-%yy')

 If the format string does not match the string provided, an error message
 (i.e. String object) is returned.Thus, to see if buildDate succeeded, the
 caller can use the "typeof" command on the return value.For example,
 here's the dateCheck function, which returns true if a given date is
 valid,and false otherwise (and reports an error in the false case):

 function dateCheck(dateStr,formatStr) 
 {
	var myObj=buildDate(dateStr,formatStr);
	
	if (typeof myObj=="object") {
	// We got a Date object, so good.
	return true;
	} else {
 // We got an error string.
 alert(myObj);
 return false;
 }
 }

*/

function buildDate(dateStr,formatStr) {
// parse the format string first.
var tokArr=parseFormatString(formatStr);
var strInd=0;
var tokInd=0;
var intMonth;
var intDay;
var intYear;
var intHour;
var intMin;
var intSec;
var ampm="";
var strOffset;

// Create a date object with the current date so that if the user only
// gives a month or day string, we can still return a valid date.

var curdate=new Date();
intMonth=curdate.getMonth()+1;
intDay=curdate.getDate();
intYear=curdate.getFullYear();

// Default time to midnight, so that if given just date info, we return
// a Date object for that date at midnight.

intHour=0;
intMin=0;
intSec=0;

// Walk across dateStr, matching the parsed formatStr until we find a 
// mismatch or succeed.

while (strInd < dateStr.length && tokInd < tokArr.length) {

// Start with the easy case of matching a literal.

if (tokArr[tokInd].type=="literal") {
if (dateStr.indexOf(tokArr[tokInd].token,strInd)==strInd) {

// The current position in the string does match the format 
// pattern.

strInd+=tokArr[tokInd++].token.length;
continue;
}
else {

// ACK! There was a mismatch; return error.

return "\"" + dateStr + "\" does not conform to the expected format: " + formatStr;
   }
}

// If we get here, we're matching to a symbolic token.
switch (tokArr[tokInd].token) {
case 'm':
case 'M':
case 'd':
case 'D':
case 'h':
case 'H':
case 'min':
case 'MIN':
case 's':
case 'S':

// Extract one or two characters from the date-time string and if 
// it's a number, save it as the month, day, hour, or minute, as
// appropriate.

curChar=dateStr.charAt(strInd);
nextChar=dateStr.charAt(strInd+1);
matchArr=dateStr.substr(strInd).match(/^\d{1,2}/);
if (matchArr==null) {

// First character isn't a number; there's a mismatch between
// the pattern and date string, so return error.

switch (tokArr[tokInd].token.toLowerCase()) {
case 'd': var unit="day"; break;
case 'm': var unit="month"; break;
case 'h': var unit="hour"; break;
case 'min': var unit="minute"; break;
case 's': var unit="second"; break;
}
return "Bad " + unit + " \"" + curChar + "\" or \"" + curChar +
nextChar + "\".";
}
strOffset=matchArr[0].length;
switch (tokArr[tokInd].token.toLowerCase()) {
case 'd': intDay=parseInt(matchArr[0],10); break;
case 'm': intMonth=parseInt(matchArr[0],10); break;
case 'h': intHour=parseInt(matchArr[0],10); break;
case 'min': intMin=parseInt(matchArr[0],10); break;
case 's': intSec=parseInt(matchArr[0],10); break;
}
break;
case 'mm':
case 'MM':
case 'dd':
case 'DD':
case 'hh':
case 'HH':
case 'mins':
case 'MINS':
case 'ss':
case 'SS':

// Extract two characters from the date string and if it's a 
// number, save it as the month, day, or hour, as appropriate.

strOffset=2;
matchArr=dateStr.substr(strInd).match(/^\d{2}/);
if (matchArr==null) {

// The two characters aren't a number; there's a mismatch 
// between the pattern and date string, so return an error
// message.

switch (tokArr[tokInd].token.toLowerCase()) {
case 'dd': var unit="day"; break;
case 'mm': var unit="month"; break;
case 'hh': var unit="hour"; break;
case 'mins': var unit="minute"; break;
case 'ss': var unit="second"; break;
}
return "Bad " + unit + " \"" + dateStr.substr(strInd,2) + 
"\".";
}
switch (tokArr[tokInd].token.toLowerCase()) {
case 'dd': intDay=parseInt(matchArr[0],10); break;
case 'mm': intMonth=parseInt(matchArr[0],10); break;
case 'hh': intHour=parseInt(matchArr[0],10); break;
case 'mins': intMin=parseInt(matchArr[0],10); break;
case 'ss': intSec=parseInt(matchArr[0],10); break;
}
break;
case 'y':
case 'Y':

// Extract two or four characters from the date string and if it's
// a number, save it as the year.Convert two-digit years to four
// digit years by assigning a century of '19' if the year is >= 
// cutoffYear, and '20' otherwise.

if (dateStr.substr(strInd,4).search(/\d{4}/) != -1) {

// Four digit year.

intYear=parseInt(dateStr.substr(strInd,4),10);
strOffset=4;
}
else {
if (dateStr.substr(strInd,2).search(/\d{2}/) != -1) {

// Two digit year.

intYear=parseInt(dateStr.substr(strInd,2),10);
if (intYear>=cutoffYear) {
intYear+=1900;
}
else {
intYear+=2000;
}
strOffset=2;
}
else {

// Bad year; return error.

return "Bad year \"" + dateStr.substr(strInd,2) + 
"\". Must be two or four digits.";
   }
}
break;
case 'yy':
case 'YY':

// Extract two characters from the date string and if it's a 
// number, save it as the year.Convert two-digit years to four 
// digit years by assigning a century of '19' if the year is >= 
// cutoffYear, and '20' otherwise.

if (dateStr.substr(strInd,2).search(/\d{2}/) != -1) {

// Two digit year.

intYear=parseInt(dateStr.substr(strInd,2),10);
if (intYear>=cutoffYear) {
intYear+=1900;
}
else {
intYear+=2000;
}
strOffset=2;
} else {
// Bad year; return error
return "Bad year \"" + dateStr.substr(strInd,2) + 
"\". Must be two digits.";
}
break;
case 'yyyy':
case 'YYYY':

// Extract four characters from the date string and if it's a 
// number, save it as the year.

if (dateStr.substr(strInd,4).search(/\d{4}/) != -1) {

// Four digit year.

intYear=parseInt(dateStr.substr(strInd,4),10);
strOffset=4;
}
else {

// Bad year; return error.

return "Bad year \"" + dateStr.substr(strInd,4) + 
"\". Must be four digits.";
}
break;
case 'mon':
case 'Mon':
case 'MON':
case 'mon_strict':

// Extract three characters from dateStr and parse them as 
// lower-case, mixed-case, or upper-case abbreviated months,
// as appropriate.

monPat=monPatArr[tokArr[tokInd].token];
if (dateStr.substr(strInd,3).search(monPat) != -1) {
intMonth=lowerMonArr[dateStr.substr(strInd,3).toLowerCase()];
}
else {

// Bad month, return error.

switch (tokArr[tokInd].token) {
case 'mon_strict': caseStat="lower-case"; break;
case 'Mon': caseStat="mixed-case"; break;
case 'MON': caseStat="upper-case"; break;
case 'mon': caseStat="between Jan and Dec"; break;
}
return "Bad month \"" + dateStr.substr(strInd,3) + 
"\". Must be " + caseStat + ".";
}
strOffset=3;
break;
case 'month':
case 'Month':
case 'MONTH':
case 'month_strict':

// Extract a full month name at strInd from dateStr if possible.

monPat=monthPatArr[tokArr[tokInd].token];
matchArray=dateStr.substr(strInd).match(monPat);
if (matchArray==null) {

// Bad month, return error.

return "Can't find a month beginning at \"" +
dateStr.substr(strInd) + "\".";
}

// It's a good month.

intMonth=lowerMonArr[matchArray[0].substr(0,3).toLowerCase()];
strOffset=matchArray[0].length;
break;
case 'ampm':
case 'AMPM':
matchArr=dateStr.substr(strInd).match(/^(am|pm|AM|PM|a\.m\.|p\.m\.|A\.M\.|P\.M\.)/);
if (matchArr==null) {

// There's no am/pm in the string.Return error msg.

return "Missing am/pm designation.";
}

// Store am/pm value for later (as just am or pm, to make things
// easier later).

if (matchArr[0].substr(0,1).toLowerCase() == "a") {

// This is am.

ampm = "am";
}
else {
ampm = "pm";
}
strOffset = matchArr[0].length;
break;
}
strInd += strOffset;
tokInd++;
}
if (tokInd != tokArr.length || strInd != dateStr.length) {

/* We got through the whole date string or format string, but there's 
 more data in the other, so there's a mismatch. */

return "\"" + dateStr + "\" is either missing desired information or has more information than the expected format: " + formatStr;
}

// Make sure all components are in the right ranges.

if (intMonth < 1 || intMonth > 12) {
return "Month must be between 1 and 12.";
}
if (intDay < 1 || intDay > 31) {
return "Day must be between 1 and 31.";
}

// Make sure user doesn't put 31 for a month that only has 30 days

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && intDay == 31) {
return "Month "+intMonth+" doesn't have 31 days!";
}

// Check for February date validity (including leap years) 

if (intMonth == 2) {

// figure out if "year" is a leap year; don't forget that
// century years are only leap years if divisible by 400

var isleap=(intYear%4==0 && (intYear%100!=0 || intYear%400==0));
if (intDay > 29 || (intDay == 29 && !isleap)) {
return "February " + intYear + " doesn't have " + intDay + 
" days!";
   }
}

// Check that if am/pm is not provided, hours are between 0 and 23.

if (ampm == "") {
if (intHour < 0 || intHour > 23) {
return "Hour must be between 0 and 23 for military time.";
   }
}
else {

// non-military time, so make sure it's between 1 and 12.

if (intHour < 1|| intHour > 12) {
return "Hour must be between 1 and 12 for standard time.";
   }
}

// If user specified amor pm, convert intHour to military.

if (ampm=="am" && intHour==12) {
intHour=0;
}
if (ampm=="pm" && intHour < 12) {
intHour += 12;
}
if (intMin < 0 || intMin > 59) {
return "Minute must be between 0 and 59.";
}
if (intSec < 0 || intSec > 59) {
return "Second must be between 0 and 59.";
}
return new Date(intYear,intMonth-1,intDay,intHour,intMin,intSec);
}
function dateCheck(dateStr,formatStr) {
var myObj = buildDate(dateStr,formatStr);
if (typeof myObj == "object") {

// We got a Date object, so good.

return true;
}
else {

// We got an error string.

alert(myObj);
return false;
   }
}
function dateCheck_NoAlert(dateStr,formatStr) 
{
	var myObj = buildDate(dateStr,formatStr);
	if (typeof myObj == "object") 
		return true;	// We got a Date object, so good.
	else 
		return false;	// We got an error string.
}

/*Katja 15/01/2008

The following code defines functions
	insertAdjacentElement
	insertAdjacentHTML
	insertAdjacentText
if they do not already exist, ie. if browser is not Internet Explorer.
Source: http://www.faqts.com/knowledge_base/view.phtml/aid/5756
*/
if(typeof HTMLElement!="undefined" && !
HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function
(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) 
this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function
(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function
(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}
/*end Katja 15/01/2008*/

function LoadSourcePage(field, strLocation, myForm, column) 
{	
	//Going to the Name Page?
	if (strLocation == 'name.asp')
	{
		//strLocation = '../01dName/Name.asp?Menu=NoMenu&NameTypeId=2&oOrd=NameID&NameID=' + myForm.NAMEID.value + '&F=' + myForm.name + '&O=NAMEID&Search=' + myForm.NAMEID.value
		strLocation = '../01dName/Name.asp?A=Fetch_Name&Menu=NoMenu&NameID=' + myForm.NAMEID.value + '&Form=' + myForm.name
	}
	
	var win = window.open('', field, '');
	
	with (win.document) 
	{
		location = strLocation + '&sel=true' + '&fetchfield=' + field + '&fetchcolumn=' + column+ '&fetchform='+ myForm.name;
		win.focus();
	}
}

//Gary 02/11/06
function LoadDetailsPage2(field, strLocation, bolXName, displayName, bolLoadPage, strLoadDetailsWith) 
{
		//Gary return if Allow_Fetch_Link = false
		//Ie don't load the fetch details page		
		if (!bolLoadPage)
		{	
			alert('Fetch Details is disabled'); 
			return; 
		}
	
    	var win = window.open('', field.name, '');

		var fieldid, strType,fieldValue,fieldName,formName;
    	
    	if (typeof(field.type)=='undefined')
	    {
			if (field.length>0)
				strType = field[0].type
		}
		else
			strType = field.type
	    
	    switch (strType)
	    {
    		case "checkbox":
    					var total = 0;
    					if (field.length>0)
    					{
    						for (var i=0;i<field.length;i++)
    						{ 
    							if (field[i].checked)
    								total++;
    						}
    								
    						fieldid		= field[0].name
							fieldName	= field[0].name
							formName	= field[0].form.name
    					}
    					else if (field.checked)
    					{ 
							total		= 1;
							fieldValue	= field.value;
							fieldid		= field.name
							fieldName	= field.name
							formName	= field.form.name
						}
 						break;
 			   default:
 						fieldValue	= field.value;
 						fieldid		= field.name
 						fieldName	= field.name
						formName	= field.form.name
 						break;
		}
    	
    	with (win.document) 
    	{
    		if(strLocation.search("[\?]")!=-1)
    			strLocation = strLocation + '&';
    		else
    			strLocation = strLocation + '?';
    		
    		var match
    			match = "Name.asp";
    			
    		var bolMatch
    			bolMatch = false;
    			    		
    		if(strLocation.indexOf(match) != -1)
    		{
    			bolMatch	= true;
    			fieldid		= "NAMEID"
    			
    			if(bolXName==true)
    			{	
    				fieldid = "XNAMEID"
    			}
    		}
			
			if (strLocation.indexOf('Menu=') < 0)	//Katja 11/06/2007
			{
				strLocation = strLocation + 'Menu=NoMenu&';
			}
			
			strLocation = strLocation + 'sel=true&NameID=' + fieldValue + '&FetchForm=' + formName + '&FetchColumn=FULLNAME&FetchField=' + fieldName;

			if (strLoadDetailsWith)
			{
				if(strLoadDetailsWith.length > 0)
				{
					var LoadWith1 = new Array ();
					var LoadWith2 = new Array ();
						
					if (strLoadDetailsWith.indexOf('^') > -1)
					{
						LoadWith1 = strLoadDetailsWith.split('^');
						
						if (LoadWith1.length > 0)
						{
							for (i=0;i<LoadWith1.length;i++)
							{						
								if (LoadWith1[i].indexOf('|') > -1)
								{
									LoadWith2 =  LoadWith1[i].split('|');
									
									if (document.getElementById(LoadWith2[0]))
										strLocation = strLocation + '&' + LoadWith2[1] + '=' + document.getElementById(LoadWith2[0]).value;
								}
								else
									strLocation = strLocation + '&' + LoadWith1[i] + '=' + document.getElementById(LoadWith1[i]).value;
							}
						}
					}
					else
					{
						if (strLoadDetailsWith.indexOf('|') > -1)
						{
							LoadWith2 = strLoadDetailsWith.split('|');
							
							if (document.getElementById(LoadWith2[0]))
								strLocation = strLocation + '&' + LoadWith2[1] + '=' + document.getElementById(LoadWith2[0]).value;
						}
						else
							strLocation = strLocation + '&' + strLoadDetailsWith + '=' + document.getElementById(strLoadDetailsWith).value;
					}
				}
			}
			
			//If this is to fetch a name id. This QueryString item tells the grid that is is looking for a name
			if (bolMatch == true)
				strLocation = strLocation + '&FetchPage=Name.asp'
			
			location = strLocation;
        	win.focus();
      }
}

//Gary 03/09/07
function LoadDetailsPage(field, strLocation, bolXName, displayName, bolLoadPage, strLoadDetailsWith, MasterName) 
{	
	if (!field)
	{
		alert('Field is undefined. Please report this error.');
		return;
	}
	
	var intMasterNameId;
	
	var MasterNameField;
		MasterNameField = $(MasterName);
		
	if (MasterNameField)
	{
		if (MasterNameField.value)
			intMasterNameId = MasterNameField.value;
		else
			intMasterNameId = 0;
	}
	
		//Gary return if Allow_Fetch_Link = false
		//Ie don't load the fetch details page		
		if (!bolLoadPage)
		{	
			alert('Fetch Details is disabled'); 
			return; 
		}
	
		var fieldid, strType,fieldValue,fieldName,formName;
    	
    	if (typeof(field.type)=='undefined')
	    {
			if (field.length>0)
				strType = field[0].type
		}
		else
			strType = field.type
	    
	    if (strType.toLowerCase() == 'checkbox')
	    {
    		var total = 0;
    		if (field.length>0)
    		{
    			for (var i=0;i<field.length;i++)
    			{ 
    				if (field[i].checked)
    					total++;
    			}
    					
    			fieldid		= field[0].name
				fieldName	= field[0].name
				formName	= field[0].form.name
    		}
    		else if (field.checked)
    		{ 
				total		= 1;
				fieldValue	= field.value;
				fieldid		= field.name
				fieldName	= field.name
				formName	= field.form.name
			}
		}
		else
		{
			fieldValue	= field.value;
 			fieldid		= field.id;
 			fieldName	= field.name;
			formName	= field.form.name
		}
    	
    	if(strLocation.search("[\?]")!=-1)
    		strLocation = strLocation + '&';
    	else
    		strLocation = strLocation + '?';
    		
    	if (strLocation.indexOf('Menu=') < 0)	//Katja 11/06/2007
		{
			strLocation = strLocation + 'Menu=NoMenu&';
		}
			
		if (intMasterNameId > 0)
			strLocation = strLocation.replace("Name.asp","Name_Grouped.asp")
		
		//strLocation = strLocation + 'MasterNameId='+intMasterNameId+'&sel=true&NameID=' + fieldValue + '&FetchForm=' + formName + '&FetchColumn=FULLNAME&FetchField=' + fieldName;
		strLocation = strLocation + 'MasterNameId='+intMasterNameId+'&sel=true&' + fieldName + '=' + fieldValue + '&FetchForm=' + formName + '&FetchColumn=FULLNAME&FetchField=' + fieldName;
    		
    	var bolMatch
    		bolMatch = false;
    			    	
    	if(strLocation.indexOf("Name.asp") != -1 || strLocation.indexOf("Name_Grouped.asp") != -1)
    	{
    		bolMatch	= true;
    		fieldid		= "NAMEID"
    		
    		if(bolXName==true)
    		{	
    			fieldid = "XNAMEID"
    		}

    		strLocation = strLocation + '&FetchPage=Name.asp'
    	}
		
		if (strLoadDetailsWith)
		{
			if(strLoadDetailsWith.length > 0)
			{
				var LoadWith1 = new Array ();
				var LoadWith2 = new Array ();
					
				if (strLoadDetailsWith.indexOf('^') > -1)
				{
					LoadWith1 = strLoadDetailsWith.split('^');
					
					if (LoadWith1.length > 0)
					{
						for (i=0;i<LoadWith1.length;i++)
						{						
							if (LoadWith1[i].indexOf('|') > -1)
							{
								LoadWith2 =  LoadWith1[i].split('|');
								
								if (document.getElementById(LoadWith2[0]))
									strLocation = strLocation + '&' + LoadWith2[1] + '=' + document.getElementById(LoadWith2[0]).value;
							}
							else
								strLocation = strLocation + '&' + LoadWith1[i] + '=' + document.getElementById(LoadWith1[i]).value;
						}
					}
				}
				else
				{
					if (strLoadDetailsWith.indexOf('|') > -1)
					{
						LoadWith2 = strLoadDetailsWith.split('|');
						
						if (document.getElementById(LoadWith2[0]))
							strLocation = strLocation + '&' + LoadWith2[1] + '=' + document.getElementById(LoadWith2[0]).value;
					}
					else
						strLocation = strLocation + '&' + strLoadDetailsWith + '=' + document.getElementById(strLoadDetailsWith).value;
				}
			}
		}
		new_window ('_blank',strLocation,'',0,0);
}

function isEmail_WithAlert(object,DisplayName)
{
	if (object.value !='' )
	{
		var testresults;
		
		var filter=/^([a-zA-Z0-9_\.\-\&])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/;
		
		if (!filter.test(object.value.trim()))
		{
			if(DisplayName==undefined)
				alert('Please input a valid email address');
			else
				alert('Please input a valid email address for ' + DisplayName);

			object.focus();
			highlight(object);
			return false;
		}
		else
			return true;
	}
	else
		return true;
}

function isMinLength(object, length, DisplayName)
{
  if (object.value!=''){
  	if (object.value.length<length){
  		alert(DisplayName + ' must be at least ' + length + ' characters');
  		highlight(object)
  		return false;
  	}
  	else return true;
  }else return true;
}

function isNumeric(object,displayName)
{
	var accept = /^(-)?(\d*)(\d*)$/;
	
	var result = object.value.match(accept);
	
	if (!result)
	{	
		if (isNaN(object.value))
		{
			if(displayName)
  			{
  				alert('Invalid entry in field ' + displayName + ': Only digits allowed. No spaces');           
  				object.focus();
  				highlight(object);
  			}
  		}
  		else
  		{
  			result = true;
  		}
  	}
	 
	return result;
}  

function isNumeric2(object)
{	
	var match = /^(-)?(\d*)(\d*)$/;
	return object.value.match(match);
}

function isNumeric3(value)
{	
	var match = /^(-)?(\d*)(\d*)$/;
	return value.match(match);
} 

function isDecimal(object)
{
	return isNaN(object.value);
}

function isEmail(object)
{
	var filter=/^([a-zA-Z0-9_\.\-\&])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/;
	return object.value.trim().match(filter);
}

function isTime(field) 
{ 
	entered = field;
	with (entered) 
	{ 
		diffpos = value.indexOf(":"); 
		lastpos = value.length - 1; 

		var last_index_of = value.lastIndexOf(":"); 
		var hours = new Number(value.substring(0,diffpos)); 
		var minutes = new Number(value.substring((last_index_of+1),value.length)); 
		if (diffpos != 2 || (lastpos - diffpos) != 2 || hours > 23 || minutes > 59) 
			return false; 
		else
			return true;
	}
}

function isDecimal(object,DisplayName)
{
	if (isNaN(object.value)==true)
	{
		alert( 'Invalid entry in field ' + DisplayName + ': Only digits and decimals allowed');           
		object.focus();
		highlight(object)
		return false;
	}
	return true;
}  

function isTime(field, DisplayName) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
	timeStr = field.value
	if (timeStr == "hh:mm:ss"){timeStr == ""}
	if (timeStr!=""){
		var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

		var matchArray = timeStr.match(timePat);
		
		if (matchArray == null) 
		{
			alert("Time is not in a valid format for " + DisplayName);
			return false;
		}
		hour	= matchArray[1];
		minute	= matchArray[2];
		second	= matchArray[4];
		ampm	= matchArray[6];

		if (second=="") { second = null; }
		if (ampm=="") { ampm = null }

		if (hour < 0  || hour > 23) {
			alert("Hour must be between 1 and 12. (or 0 and 23 for military time) for " + DisplayName);
			return false;
		}
		if (hour <= 12 && ampm == null) {
			if (confirm("Please indicate for " +  DisplayName + " which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
				alert("You must specify AM or PM.");
				return false;
			}
		}
		if  (hour > 12 && ampm != null) {
			alert("You can't specify AM or PM for military time for " +  DisplayName);
			return false;
		}
		if (minute<0 || minute > 59) {
			alert ("Minute must be between 0 and 59 for " +  DisplayName);
			return false;
		}
		if (second != null && (second < 0 || second > 59)) {
			alert ("Second must be between 0 and 59 for " +  DisplayName);
			return false;
		}
		highlight(object)
		return false;
		
	}
	return true;
}

function isParentOpen ()
{
	var bolOpen = false;
	
	if (window.opener != null && !window.opener.closed && window.opener.open)
		bolOpen = true;
	
	return bolOpen;
}

function go(myForm){
	
	if (!myForm)
	{
		myForm = document['Form1'];
	}
	
	if (myForm.submitTask) // if/else added by Katja 07/12/2005 for refresh from clsGrid
	{
		myForm.submitTask.value = 'Refresh';
		displayTask(myForm);
		myForm.submit();
	}
	else
	{
		if (isParentOpen())
		{
			if (self.opener.myForm.onsubmit.toString().indexOf('goGrid') != -1)
			{
				goGrid(myForm);
			}
		}
		else if (myForm.onsubmit.toString().indexOf('goGrid') != -1)
		{
			goGrid(myForm);
		}
	}
}  
function displayTask(myForm){
	if (document.getElementById('wait'))
	{
		var task
		switch (myForm.submitTask.value){
					case "Refresh": 
						task = "Refreshing"
						break;
					case "Save": 
						task = "Saving"
						break;
					case "Save & New": 
						task = "Saving. Will load new form"
						break;
					case "Abort": 
						task = "Aborting"
						break;
					default :
						task = "Processing";
		}
		document.getElementById('wait').innerHTML = task + ". Please wait.....</span>"
		window.document.body.style.cursor = 'wait';
		myForm.style.display='none';
		document.getElementById("wait").style.display='block';
		window.setInterval('wait()', 400)
	}
}

function getAttributes(field)
{
	field = $(field);
	var attributes = {	onchange:		field.getProperty('onchange'),
						onclick:		field.getProperty('onclick'),
						onmouseover:	field.getProperty('onmouseover'),
						onmouseout:		field.getProperty('onmouseout'),
						title:			field.getProperty('title'),
						xclass:			field.getProperty('class') };								
	return attributes;		
}

function compareAttributes (field,attribute,compare)
{
	var bolEqual = false;
	
	if (compare == field.getProperty(attribute))
		bolEqual = true;
		
	return bolEqual;
}

function setAttributes(field,attributes)
{
	field = $(field);
	
	for (var attribute in attributes)
	{
		if(attributes[attribute]!=null)
		{
			if (compareAttributes (field,attribute,attributes[attribute]) == false)
				field.setProperty(attribute,attributes[attribute]);
		}
	}
}

function setOptions(field,options,selected)
{
	field = $(field);
	
	if (selected.length < 1 || selected==null)
		selected = 0;
		
	var zero_option = {id:0,name:field.options[0].text};
	
	var current_Selected = field.value;
	
	field.options.length = 0;
	
	field.options.add(new Option(zero_option.name,zero_option.id));
	
	if (options)
	{
		if (options.length > 0)
		{
			var option_array = returnArray(options,'^');
		
			option_data	= returnArray(option_array[0],'~');
		
			var option_data;
			for (var i=0; i<option_array.length; i++)
			{
					if(option_array[i]!=null)
					{		
						option_data	= returnArray(option_array[i],'~');
						
						var new_option = new Option(URLDecode(option_data[1]),option_data[0]);
									
						field.options.add(new_option);
						
							if (selected == option_data[0])
							{
								field.selectedIndex = i+1;
								if (selected > 0 && selected != current_Selected)
									eval(field.getProperty('onchange'));
							}
					}
			}
		}
	}
	
	function URLDecode(psEncodeString) 
	{
		var lsRegExp = /\+/g;
		return unescape(String(psEncodeString).replace(lsRegExp, " "));
	}	
	
	/*for (var option in options)
	{
		//leave zero option
		if(options[option]!=null)
		{
			field.options.add(new Option(options[option].name,options[option].id));
			
			if (selected == options[option].id)
			{
				field.selectedIndex = option+1;
				if (selected > 0)
					eval(field.getProperty('onchange'));
			}
		}
	}*/
}

function getName(field)
{
	if (field.value)
	{
		if(field.value.length > 0)
			if(isNumeric2(field))
				go(field.form);
	}
}

function getFullName (field)
{
	var field = $Get(field);
	
	if (field.value)
	{
		var field_value = field.value;
		if(field_value.length > 0)
		{
			if(isNumeric2(field_value))
			{
				updateName ('MESSAGE'+field,'MESSAGE'+field,field_value+'|7');
			}
		}
	}
}

function setLoadingOn (object)
{
	if (object)
		object.addClass('ajax_loading_small');
	else
		alert('Please inform the Merlin Support Staff that the setLoadingOn function has reported an error');
}

function setLoadingOff (object)
{
	object.removeClass('ajax_loading_small');
	object.setStyle('display','inline');
}

function setLoadingOff_Array (arr)
{
	for (i=0;i<arr.length;i++)
		setLoadingOff ($(arr[i].toUpperCase()));
}

function setLoadingOn_Array (arr)
{
	for (i=0;i<arr.length;i++)
		setLoadingOn ($(arr[i].toUpperCase()));
}

function returnArray (str,sep)
{	
	//alert(str);
	//alert(sep);
	
	if (str == null)
		str = '';
		
	var return_array = new Array(10);

	if (str.test(sep))
		return_array = str.split(sep);
	else
		return_array[0] = str;
		
	//alert(return_array.length-1);
	//alert(return_array[return_array.length-1]);
	//alert(return_array[return_array.length-1].length);
	
	if (return_array[return_array.length-1])
	{
		if(return_array[return_array.length-1].length < 1)
		{
			var trim_return_array = new Array(return_array.length-1);
			
			for (var i=0;i<trim_return_array.length;i++)
			{
				trim_return_array[i] = return_array[i];
			}
			
			return_array = trim_return_array;
		}
	}
		
	return return_array;
}
 
function CompareFields(field1, compare, field2, vType, cValue,tValue){
  c = '"' + document.getElementById('DISPLAY'+field1.name).innerText + '"'
  d = '"' + document.getElementById('DISPLAY'+field2.name).innerText + '"'
 	if (isNaN(cValue)==true){cValue = 0}
		return CompareFieldsFull(field1,compare, field2, c, d, vType,cValue,tValue)
}
function CompareDTFields(field1, compare,field2){
	var pass=true
	if (field1.value!="")
	{	
		var d1;
		var d2;
		
		c = '"' + $('DISPLAY'+field1.name).innerText + '"';
		d = '"' + $('DISPLAY'+field2.name).innerText + '"';
		
		d1 = ConvertDate(field1.value);
		t1 = document.getElementById(field1.name + "TIME").value;
	
		d2 = ConvertDate(field2.value);
		t2 = document.getElementById(field2.name + "TIME").value;
	
		if (field1.value!='' && field2.value!=''){
			switch (compare){
				case "=": 
					if (d1!=d2 || t1!= t2){
						alert(c + ' must be the same as ' + d);
						//field1.focus();
						pass = false;
					}
					break;
				case "!=": 
					if (d1==d2 && t1==t2){
						alert(c + ' cannot be the same as ' + d);
						//field1.focus();
						pass = false;
					}
					break;
				case "<":
					if (d1>d2 ||(d1=d2 && t1>= t2)){
						alert(c + ' must be less than ' + d);
						//field1.focus();
						pass = false;
					}
					break;
				case ">":
					if (d1<d2 || (d1=d2 && t1<= t2)) {
						alert(c + ' must be greater than ' + d);
						//field1.focus();
						pass = false;
					}
					break;
				case "<=":
					if (d1>d2 || (d1=d2 && t1>t2)) {
						alert(c + ' must be less than or equal to ' + d);
						//field1.focus();
						pass = false;
					}
					break;
				case ">=":
					if (d1<d2 || (d1=d2 && t1<t2)) {
						alert(c + ' must be greater than or equal to ' + d);
						//field1.focus();
						pass = false;
					}
					break;
			}
		}
	}
	return pass
}
function getTimeDiff(field1,field2, tType){
  date1 = buildDate(field1.value,'%dd/%mm/%y')
  date2 = buildDate(field2.value,'%dd/%mm/%y')
  diff  = new Date();
  diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
  timediff = diff.getTime();
     switch (tType){
				case "week": 
            timediff = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
             break;
        case "day":
            timediff = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
              break;
        case "hour":
              //alert('test')
             timediff = Math.floor(timediff / (1000 * 60 * 60)); 
              break;
        case "month":
			//99% correct new to change logic here
            timediff = Math.floor(timediff / (1000 * 60 * 60 * 24 * 30.416)); 
          break;
        default:
          alert('time type ' + tType + ' is not supported. Use lower case');
          break;
  }
  return timediff
}


function CompareFieldsFull(field1, compare, field2, c,d, vType, cValue,tType){
	var v1,v2, pass;
	pass = true;
	if (v1!="" && v2!="" && vType=="DATE"){
		ClearExample(field1,"dd/mm/yyyy")
		ClearExample(field2,"dd/mm/yyyy")
	}	
	if (v1!="" && v2!="" && vType=="TIME"){
		ClearExample(field1,"hh:mm")
		ClearExample(field2,"hh:mm")
	}	
	v1 = field1.value
	v2 = field2.value
	cValue = cValue-0
	
// Added 27/08/04 - error on email compare from registration.asp
	if (isNaN(cValue)==true){
		cValue = 0
	}
	
	if (isNaN(v1)==false){
		v1 = v1 - 0
	}
	if (isNaN(v2)==false){
		v2 = v2 - 0
	}
	
	if (v1!="" && v2!="" && vType=="DATE"){
		v1 = ConvertDate(v1)
		v2 = ConvertDate(v2)
	}
		
	if (field1.value!='' && field2.value!=''){
	   if(cValue<=0){
		switch (compare){
			case "=": 
				if (v1!=v2){
					alert(c + ' must be the same as ' + d);
					//field1.focus();
					pass = false;
				}
				break;
			case "!=": 
				if (v1==v2){
					alert(c + ' cannot be the same as ' + d);
					//field1.focus();
					pass = false;
				}
				break;
			case "<":
				if (v1>=v2){
					alert(c + ' must be less than ' + d);
					//field1.focus();
					pass = false;
				}
				break;
			case ">":
				if (v1<=v2){
					alert(c + ' must be greater than ' + d);
					//field1.focus();
					pass = false;
				}
				break;
			case "<=":
				if (v1>v2){
					alert(c + ' must be less than or equal to ' + d);
					//field1.focus();
					pass = false;
				}
				break;
			case ">=":
				if (v1<v2){
					alert(c + ' must be greater than or equal to ' + d);
					//field1.focus();
					pass = false;
				}
				break;
    		}
    	}
  		else{
  		    if(tType == 'year'){
  		      pass = checkYearDiff(field1,field2,diff, compare)
          }
          else{
    		    var diff = getTimeDiff(field1,field2, tType)
    		    if(diff>1){tType += 's'}
    		    if (v1<v2){
    		      diff = diff*-1
    		    }
    		    //alert(diff+compare+cValue)
    		    pass = eval(diff+compare+cValue);
    		  }
  		    if(!pass){
    		    switch (compare){
        			case "=": 
        					alert(c + ' must be the same as ' + d + ' + ' + cValue + ' ' + tType);
        					break;
        			case "!=": 
        				  alert(c + ' cannot be the same as ' + d + ' + ' + cValue + ' ' + tType);
        					break;
        			case "<":
        				alert(c + ' must be less than ' + d + ' + ' + cValue +  ' ' + tType);
        				break;
        			case ">":
        					alert(c + ' must be greater than ' + d + ' + ' + cValue + ' ' + tType);
        					break;
        			case "<=":
        					alert(c + ' must be less than or equal to ' + d + ' + ' + cValue + ' ' + tType);
        				break;
        			case ">=":
        					alert(c + ' must be greater than or equal to ' + d + ' + ' + cValue + ' ' + tType);
        					break;
      		  }
    		    
    		  }
		}
	}
	return pass	;
}


function addmonth(i,field1){


	var v = ConvertDate(field1.value)
	
	var i = i - 0
	v.setMonth(v.getMonth()+ i)
//	v.setDate(v.getDate()-1)
	alert (v)
}



function  checkYearDiff(field1,field2,diff,compare){
 //alert(field1.value)
  date1 = buildDate(field1.value,'%dd/%mm/%y')
  alert('string' + date1.toGMTString())
  date1.setFullYear(date1.getFullYear()+1)
  alert('string' + date1.toGMTString())
  //alert(date1.getDay()+ '/'+ (date1.getMonth()+1) + '/' + (date1.getFullYear())
	//v1 = ConvertDate(date1.getDay()+ '/'+ (date1.getMonth()+1) + '/' + (date1.getYear()))
	v1 = ConvertDate(field1.value)
	v1 = v1 + diff*1000000
  v2 = ConvertDate(field2.value)
  alert(v1+compare+v2)
  return eval(v1+compare+v2)
}
function EnableIf(field, bol){
	field.disabled = false;
	//alert(bol)
	if(bol==true){
		document.getElementById('MESSAGE' + field.name).style.display = 'block'
		document.getElementById('MESSAGE' + field.name).innerText = '*'
	}
}
function DisableIf(field1,field2){
	if (field1.value=="" && field2.value==""){field1.disabled=true}
	
}
function RequiredIf(field1, field2, vMessage, val)
{
	if (!field1 || !field2)	//Added by Katja 14/05/2008: function crashes if a field doesn't exist
	{
		return true;
	}

	ClearExample(field1,"dd/mm/yyyy");
	ClearExample(field2,"dd/mm/yyyy");
  
	var pass = true;
	var strType =  field2.type;
	
	if (typeof(field2.type)=='undefined')
	{
		if(field2.length>0)
		{
			strType = field2[0].type
		}
	}
	else
	{
		strType = field2.type;
	}
	
	switch (strType)
	{
		case "checkbox":
			if(field2.checked)
			{
				pass = IsRequired(field1, vMessage);
			}
			break;
		case "select-one":
			if (val!="")
			{
				if (field2.selectedIndex==val)
				{
					pass = IsRequired(field1, vMessage);
				}
			}
			else 
			{	
				if(field2.selectedIndex > 0)
				{
					pass = IsRequired(field1, vMessage)
				}
			}
			break;
		default:
			if (field2.value!='')
			{
				pass = IsRequired(field1, vMessage)
			}
			break;
	}
	return pass;
}

var IsRequired = function (field, vMessage)
{
  var pass = true;
	var type
	if (vMessage==''){
		vMessage = field.parentElement.children
		vMessage = '"' + vMessage(0).innerText + ' required"'
	}

	if (typeof(field.type)=='undefined'){if(field.length>0){strType = field[0].type}}
	else{strType = field.type}
	switch (strType){
		case "checkbox":
			var total = 0;
			if (field.length>0){
				for (var i=0;i<field.length;i++){ 
					if (field[i].checked){total++;}
				}
			}
			else if (field.checked){ total = 1}
				
			if (total==0){
				pass=false;
				for (var i=0;i<field.length;i++){ 
					highlight(field[i])
				}
				
				alert(vMessage)
			}
			break;
		case "radio":
			var total = 0;
			var length = 0;
			if (field.length>0){
				for (var i=0;i<field.length;i++){ 
					if (field[i].checked){total++;}
				}
			}
			//else added by Katja 07/03/2006 - length is undefined if there is only one radio box
			else {if (field.checked){total++;}}
			if (total==0){
				pass=false;
				for (var i=0;i<field.length;i++){ 
					highlight(field[i])
				}
				alert(vMessage)
			}
			break;
		case "select-one":
			if ( field.value <=0){
				pass = false;
				highlight(field)
				alert(vMessage)
			}
			break;
		default: 
			if ( trim(field.value) == '') {
				highlight(field)
				alert(vMessage);
				if (field.type != "hidden") //if statement added by Katja 16/10/2006: was causing js error
				{
					try {field.focus();}	//If field is hidden from view (eg inside a hidden div), focus will not work
					catch(e) {}
				}
				pass = false;
			}
			break;
	}
	return pass
}
function unhighlight (field)
{
	$(field.name).removeClass('highlight_field');
}
function highlight(field)
{
	try
	{
		$(field.name).addClass('highlight_field');
	}
	catch(e)
	{
		/*Pages without mootools work the old way*/
		field.style.backgroundColor = "red";
		field.style.color="white";
	}
}
function highlightRow(field,caller)
{	
	//var old_field = $E('tr[class=selectedRow]');
	var old_field = $$('tr[class=selectedRow]');
	
	if(old_field)
	{
		var class_name = 'even';
		
		if ((old_field.getProperty('id')%2)>0)
			class_name = 'odd';
		
		old_field.setProperty('class',class_name);
	}
		
	//field = $E('tr[name='+field+']');
	field = $$('tr[name='+field+']');
	
	if (Check_SameRef(field) == true)
	{
		highlightRow_SameRef (caller);
		return;
	}
	
	if (field)
		field.setProperty('class','selectedRow');
}

function highlightRow_SameRef (caller)
{
	if (caller)
		if (caller.getParent())
			if (caller.getParent().getParent())
				caller.getParent().getParent().setProperty('class','selectedRow');
}

function Check_SameRef (field_object)
{
	var bolSameRef = false;

	//var test = $ES('tr');
	var test = $$('tr');

	if (test && field_object)
	{
		var count = 0;
		for (i=0;i<test.length;i++)
		{
			if (test[i].getProperty('name') && field_object.getProperty('name'))
			{
				if (test[i].getProperty('name') == field_object.getProperty('name'))
				{ 
					count++;
					if (count > 1)
					{
						bolSameRef = true;
						break;
					}
				}
			}
		}
	}

	return bolSameRef;
}

function Valid_Field_Msg (field,type)
{
	var valid_msg = '';
	type = type.toUpperCase();
	
	if (field.value)
	{
		if (type == "DATETIME")
			type="DATE";
		if (type == "NAME")
			type="NUMERIC";
			
		switch (type)
		{
			case "NUMERIC":
				if(!isNumeric2(field))
					valid_msg = 'Please enter a number. E.g. 0 - 9.';
				break;
			case "DECIMAL":
				if(!isDecimal(field))
					valid_msg = 'Please enter a number. E.g. 0.0 - 9.9';
				break;
			case "EMAIL":
				if(!isEmail(field))
					valid_msg = 'Please enter a valid email. E.g. john_doe@email.com';
				break;
			case "TIME":
				if(!isTime(field))
					valid_msg = 'Please enter a valid time. E.g. 12:00 (hh:mm).';
				break;
			case "DATE":
				if(!dateCheck(field.value,'%dd/%mm/%y'))
					valid_msg = 'Please enter a valid date. E.g. 01/01/1901 (dd/mm/yyyy).';
				break;				
			default:
				break;
		}
	}	
	return valid_msg;
}

function Valid_Field (field,type)
{
	var valid = true;
	type = type.toUpperCase();
	
	if (field.value)
	{
		if (type == "DATETIME")
			type="DATE";
		if (type == "NAME")
			type="NUMERIC";
			
		switch (type)
		{
			case "DATE":
				if(!dateCheck(field.value,'%dd/%mm/%y'))
					valid = false;
				break;
			case "NUMERIC":
				if(!isNumeric2(field))
					valid = false;
				break;
			case "DECIMAL":
				if(!isDecimal(field))
					valid = false;
				break;
			case "EMAIL":
				if(!isEmail(field))
					valid = false;
				break;
			case "TIME":
				if(!isTime(field))
					valid = false;
				break;
			default:
				alert('type not found')
		}
	}
	return valid;
}

function ValidateType(field, vType,DisplayName)
{
 	var pass = true;
 	
 	if (field.getAttribute('value') == 'undefined')
		if (ajaxRunning)
			return;
			
	if (trim(field.value)!=''){
		if (vType == "DATETIME"){vType="DATE"}
		if (vType == "NAME"){vType="NUMERIC"}
		switch (vType){
			case "DATE":
				if (field.value!=''){
					if(!dateCheck(field.value,'%dd/%mm/%y')) {
						highlight(field)
						field.focus();
						pass=false
					}
				}
				break;
			case "NUMERIC":
				if(!isNumeric(field,DisplayName)){pass=false}
				break;
			case "DECIMAL":
				if(!isDecimal(field,DisplayName)){pass=false}
				break;
			case "EMAIL":
				if(!isEmail_WithAlert(field,DisplayName)){pass=false}
				break;
			case "TIME":
				if(!isTime2(field,DisplayName)){pass=false}
				break; 
			default:
				alert('vtype not found')
		}
	}
	return pass
}

function isDate (value)
{
	return (!isNaN(new Date (value).getYear ())) ;
}


function SubmitForm(FormName)
{
	bolManualOnSubmit = true;

	var sfDocument = document[FormName];
		
	if(sfDocument.onsubmit())
	{
		sfDocument.onSubmit = '';
		sfDocument.submit();
	}
}

function ClearExample(field, example)
{	
	if (field.value==example)
	{
		field.value='';
	}
}

function Move(page){
  bolMoveFilter = true
	Split2();
	AA[7] = 0;
	AA[4] = page;
	goGrid(document.Form1)
}
function cls(field){ 
	//x=myForm.elements('Sch')
	if (field.value.match(/Search/gi)){field.value=''}
}
function Split2(){
  if(!bolSplit){
     AA=document.Form1.Key.value.split('^');
    // alert(A[0])
	   bolSplit = true;
	}
}
function Split()
{
  A = document.getElementById('Form1').Key.value.split('^');
}

function Q(x)
{
  bolAFFilter = true
	Split2();
	AA[5]=x;
	AA[4]=1;
	goGrid(document.Form1);
}
function cDir(sString, Dir)
{
	Split2();
	AA[0] =	sString;
	AA[1] =	Dir;
	goGrid(document.Form1);
}

function loadNew(p,t)
{
	var pageAndKey;
	
	var connector;
	if (p.indexOf('?') > 0) {connector = '&';}
	else {connector = '?';}
	
	if (bolAdd_Page_NoKey == false)
	{	
		Split();
		A[7]	= 0;
		A[11]	= t;
		pageAndKey = p + connector + 'Key=' + A.join('^') + '&list_pos=' + ListPos + CheckSelect();
	}
	else
		pageAndKey = p + connector + 'list_pos=' + ListPos + CheckSelect();
		
	if (bolAdd_Page_PopUp == false)
	{	
		hideGrid('Loading Form');
		top.location = pageAndKey;
	}
	else
	{	
		myWindow = window.open(pageAndKey, '_Add', 'top=0,toolbar=yes,scrollbars=yes,resizable=yes,height=500,width=750');
		myWindow.focus();
	}
}

function loadNew_1(t)
{
	Split();
	A[7]	= 0;
	A[11]	= t;
	hideGrid('Loading Form');
	top.location = PageName + '1.asp?Key=' + A.join('^') + '&list_pos=' + ListPos + CheckSelect();
}

function E(Id,t){
	Split()
	A[7]=Id;
	A[11]=t;
	hideGrid('Loading record')
	top.location = PageName + '1.asp?Key=' + A.join('^') + '&list_pos=' + ListPos + CheckSelect();
}

function D(Id,t)
{
	Split();
	
	if (confirm('Are you sure')==true)
	{
		if (document['Form1'].Sch)
			A[5]=A[5].replace('&','%26');
				
		A[7]  = Id;
		A[11] = t;
		
		hideGrid('Deleting')
		top.location = PageName + '.asp?A=X&Key=' + A.join('^') + '&list_pos=' + ListPos + CheckSelect();
	}
}

function CheckSelect()
{
	if (document.Form1.SELECT)
	{
		if (document.Form1.SELECT.value =='TRUE')
		{
			return	"&sel=true&" + "fetchfield=" + document.Form1.FETCHFIELD.value + "&fetchcolumn=" + document.Form1.FETCHCOLUMN.value	+ "&fetchform=" + document.Form1.FETCHFORM.value + "&fetchpage=" + document.Form1.FETCHPAGE.value;
		}
	}
		
	return "";
}

/*
	Can be found at Name.asp

function GN(sNameid,Lastname)
{
	if ( self.opener.<%=FetchForm%>.<%=FetchField%>)
	{
		self.opener.<%=FetchForm%>.<%=FetchField%>.value = sNameid;
	}
		
	if ( self.opener.<%=FetchForm%>.SelName)
	{
		self.opener.<%=FetchForm%>.SelName.value = Lastname;
	}

	if(self.opener.<%=FetchForm%>)
	{
		if (self.opener.<%=FetchForm%>.SELNAME<%=FetchField%>)
		{
			self.opener.<%=FetchForm%>.SELNAME<%=FetchField%>.value='(' + Lastname + ')';
		}
	
		if(self.opener.<%=FetchForm%>.submitTask && self.opener.<%=FetchForm%>.REFRESH<%=FetchField%>.value=='true')
		{
			self.opener.<%=FetchForm%>.submitTask.value = "REFRESH";
			self.opener.<%=FetchForm%>.submit();
		}
		else if (self.opener.<%=FetchForm%>.onsubmit)
			if (self.opener.<%=FetchForm%>.onsubmit.toString().indexOf('goGrid') != -1)	//added by Katja 07/12/2005 for refresh from clsGrid
			{
				self.opener.goGrid(self.opener.<%=FetchForm%>);
			}
	}
	
	self.close();
}
	Can be found at Name.asp
*/

function S(Id,t)
{
	if (currentDoc)
	{
		var bolRefresh	= false;
		var flag		= false;
		
		var fetchForm = document['Form1'].FETCHFORM.value;
		var fieldName = RefField + 'ID';

		if (document['Form1'].FETCHFIELD.value!="")
			fieldName	= document['Form1'].FETCHFIELD.value;
			
		var refreshField		= currentDoc.getElementById('REFRESH' + fieldName);
		var parentFieldToUpdate = currentDoc.getElementById(fieldName);
		
		if (!parentFieldToUpdate)
		{
			parentFieldToUpdate = currentDoc.getElementById(fieldName + 'Count');
			bolRefresh			= true;
		}
		
		if(parentFieldToUpdate.tagName=='INPUT')
		{	
			/*Katja 01/09/2008: Previously could not have a Fetch_Id on a Grid page*/
			if (currentDoc.getElementById('Grid'))
			{
				changeValue(fieldName, Id, window.opener);
				
				var selfield = currentDoc.getElementById('SELNAME' + fieldName);
				if (selfield)
				{
					selfield.style.display	= 'block';
					selfield.innerText		= ' (' + t.valueOf() + ')';
				}
				
				self.close();
				return;
			}
			/*Katja 01/09/2008*/
			
			parentFieldToUpdate.value = Id;
		    var selfield = currentDoc.getElementById('SELNAME' + fieldName);
		    if (selfield)
			{
				selfield.style.display	= 'block';
				selfield.innerText		= ' (' + t.valueOf() + ')';
			}
		}
		else
		{
			bolRefresh = true;
		 
			for (oc = 0; oc < parentFieldToUpdate.options.length; oc++)
			{
				if (parentFieldToUpdate.options[oc].value==Id)
				{
					flag = true;
					parentFieldToUpdate.selectedIndex = oc;
					break;
				}
			}
			
			if (flag == false)
			{
				if (fetchForm=='Form2')
					currentDoc.Form2.submitTask.value = "REFRESH";
				else if (fetchForm=='Frm')
					currentDoc.Frm.submitTask.value = "REFRESH";
				else
					currentDoc.Form1.submitTask.value = "REFRESH";
				
				parentFieldToUpdate.options[0].value = Id;
				parentFieldToUpdate.selectedIndex = 0;
			}
		}
		
		if (bolRefresh!=true)
			bolRefresh=refreshField.value; //{flag=refreshField.value} changed by Katja 29/11/2005
		
		if (bolRefresh=='true')
			bolRefresh = true;
		
		if (bolRefresh== true)
		{		
			if (fetchForm=='Form2')
			{
				currentDoc.Form2.submitTask.value = "REFRESH";
				currentDoc.Form2.submit();
			}
			else if (fetchForm=='Frm')
			{
				currentDoc.Frm.submitTask.value = "REFRESH";
				currentDoc.Frm.submit();
			}
			else
			{	
				currentDoc.Form1.submitTask.value = "REFRESH";
				currentDoc.Form1.submit();
			}
		}
		self.close();
	}
}

function createSelectList(field,ids,names)
{	
	if (names.length < 1)
	{
		names = ids;
	}
		
	ids		= returnArray(ids,'^');
	names	= returnArray(names,'^');
	
	if (field.options)
	{
		var selectedValue	= field.options[0].value;
		var bolValue_Exists = false;
		var bolZero_Option	= false;
	
		for (var z=0; z < ids.length; z++)
		{
			if (ids[z] == 0)
				bolZero_Option = true;
		}
	
		var j = 0;
	
		if (bolZero_Option==false)
		{
			j = 1;
			field.options[0] = new Option('Please select an option',0);
		}
			
		if (ids[0] > 0)
		{
			field.options[j] = new Option(field.options[0].innerText,0);
		}
			
		for (var i=0; i < ids.length; i++)
		{
			field.options[i+j] = new Option(names[i], ids[i]);
			if (selectedValue == ids[i])
			{
				bolValue_Exists		= true;
				field.selectedIndex = i+j;
			}
		}
				
		if (!bolValue_Exists && bolZero_Option == true)
			alert('The value ' + selectedValue + ' does not exist');// in ' + field.getProperty('id'));
	}
	else
	{//A Hidden CreateSelectList
	
	}
}

function createSelectList2(field,arr1,arr2)
{
	var selValue, i, bolFound, name, length,b, s, lgth;
	bolFound = false;
	b = 0;
	lgth =  field.length;
	if (field.length > 1)
	{
		for (i = 0; i < lgth; i++)
			field.options.remove(1);
		i= 0;
	}
	if (field.length != undefined)
	{
		selValue = field.options[0].value;
		
		arr1 = arr1.split('^');
		if (arr2=='')
			arr2 = arr1;
		else
			arr2 = arr2.split('^');

		if (arr2.length != arr1.length)
			alert('array length for ' + field.name + ' not equal');
		else
		{
			if (selValue == 0)
			{
				bolFound=true;
				b = 1;
			}
			if(arr1[0]==0)
			{
				bolFound=false;
				b=0;
			}		
			for (i = 0; i < arr1.length; i++)
			{
				var myNewOption = new Option(arr2[i], arr1[i]);
				
				field.options[i+b] = myNewOption;
				if (arr1[i]=='')
				{
					alert('one of the values for the ' + field.name + ' select array in empty');
					break;
				}
				if (arr1[i]==selValue)
				{
					field.selectedIndex = i;
					bolFound = true;
				}
			}
			if (bolFound==false)
				alert('Value not found for ' + field.name + ': ' + field.options[0].value);
		}
	}
}
function TrackCount(fieldObj,countField,maxChars)
{
  var diff = maxChars - fieldObj.value.length;

  // Need to check & enforce limit here also in case user pastes data
  if (diff < 0)
  {
	fieldObj.value	= fieldObj.value.substring(0,maxChars);
    alert('data pasted into field was truncated due to field size restriction of ' + maxChars + ' characters.')
    diff = maxChars - fieldObj.value.length;
  }
  countField.value = diff;
}

function LimitText(fieldObj,maxChars)
{
  var result = true;
  if (fieldObj.value.length >= maxChars)
    result = false;
  
  if (window.event)
    window.event.returnValue = result;
  return result;
}
function DisplayIf(field1,field2,compare,strValue,bol){
	if (field1 && field2)
	{
		var v1 = field1.value;
		var v2 = field2.value;
		
		if (!isNaN(v1)){v1 = v1 - 0}
		if (!isNaN(v2)){v2 = v2 - 0}
		
		//alert('working')
		
		var bolDisplay = false;
		var fParent;
		
		switch (field2.type){
			case "checkbox":
				alert('checkbox not supported at this time')
				break;
			case "radio":
				alert('radio not supported at this time')
				break;
			case "select-one":
				fieldValue = v2
				break;
			default: 
				fieldValue = v2
				break;
		}
		
		fParent = $('CONT' + field1.name);
		if (!fParent) {fParent = field1.parentElement;}
		
		if (fParent)
		{
			fParent.style.display = 'none';
		
			switch (compare){
				case "=": 
					if (fieldValue==strValue){
						fParent.style.display = 'block';
					}
					break;
				case "!=": 
					if (fieldValue!=strValue){
						fParent.style.display = 'block';
					}
					break;
				case "<":
					if (fieldValue<strValue){
						fParent.style.display = 'block';
					}
					break;
				case ">":
					if (fieldValue>strValue){
						fParent.style.display = 'block';
					}
					break;
				case "<=":
					if (fieldValue<=strValue){
						fParent.style.display = 'block';
					}
					break;
				case ">=":
					if (fieldValue>=strValue){
						fParent.style.display = 'block';
					}
					break;
			}
		}
		
		if(bol==true){
			//alert('MESSAGE' + field1.name)
			document.getElementById('MESSAGE' + field1.name).style.display = 'block'
			document.getElementById('MESSAGE' + field1.name).innerText = '*'
		}
	}
}
function testThis(a){
	alert (a)
}
function RequiredIfDisplayed(field, vMessage){
	if(field.parentElement.style.display == 'block'){
		if(!IsRequired(field, vMessage)){return false}
	}
	return true
}
function FetchValue(Com, ID, getField) {
	alert('fetching')
	document.body.style.cursor='wait';
	// Create an instance of the XML HTTP Request object
	var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );

	// Prepare the XMLHTTP object for a HTTP POST to our validation ASP page
	var sURL = "http://owl2/MerlinRenameMike_Local/Fetchvalue.asp?Com=" + Com + '&ID=' + ID + '&getField=' + getField
	oXMLHTTP.open( "POST", sURL, false );
	// Execute the request
	oXMLHTTP.send();
	alert (oXMLHTTP.responseText) 
	document.body.style.cursor='auto';
}
function hlMenu(menuitem){
	if(document.getElementById(menuitem)){
		menuitem = document.getElementById (menuitem)
		menuitem.innerHTML = menuitem.innerText
	}
	else alert("menuitem does not exist")
}
var win= null;

function NewWindow(mypage,myname,w,h,scroll,toolbar)
{
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',toolbar=' +toolbar + ',location=no,status=no,menubar=no,resizable=yes,dependent=no'
	win=window.open(mypage,myname,settings)
	if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function LoadName(Id)
{
	Split ();
	
	var home;
		home = A[6];
	
	var myWindow;
	
	myWindow = window.open('../MerlinBusiness/002NameHome.asp?Menu=MenuName&Home='+home+'&Action=sel&NameID=' + Id, '_Name')
	myWindow.focus();
}

function LoadCC(Id){
var myWindow
myWindow = window.open('../01aMarketingSetup/CommunicationContent2.asp?CommunicationContentID=' + Id, 'cc')
myWindow.focus()
}
function ConvertDate(X) { // gives YYYYMMDD
 X = X.split(/\D+/)
 X = -( (-X[2]*20-X[1])*50 - X[0] )
 return X
 }
function Hide(e)
{
	if(document.getElementById(e))
	{
		document.getElementById(e).style.display = 'none';
	}
}
function BreakItUp(field)
{
  //Set the limit for field size.
  var FormLimit = 102399

  //Get the value of the large input object.
  var TempVar = new String ();
  
	if (field)
		TempVar = field.value;
	else
		TempVar = "";
		
  //If the length of the object is greater than the limit, break it
  //into multiple objects.
  if (TempVar.length > FormLimit)
  {
    field.value = TempVar.substr(0, FormLimit)
    TempVar = TempVar.substr(FormLimit)

    while (TempVar.length > 0)
    {
      var objTEXTAREA = document.createElement("TEXTAREA")
      objTEXTAREA.name = field.name
      objTEXTAREA.value = TempVar.substr(0, FormLimit)
      field.form.appendChild(objTEXTAREA)
      
      TempVar = TempVar.substr(FormLimit)
    }
  }
}
function isTime2(field, displayName) { 
	entered = field
	with (entered) { 
		diffpos = value.indexOf(":"); 
		lastpos = value.length - 1; 

		var last_index_of = value.lastIndexOf(":"); 
		var hours = new Number(value.substring(0,diffpos)); 
		var minutes = new Number(value.substring((last_index_of+1),value.length)); 
		if (diffpos != 2 || (lastpos - diffpos) != 2 || hours > 23 || minutes > 59) { 
			highlight(field)
			alert(displayName + ' is not a valid time'); 
			return false; 
			
		} 
		else {return true;} 
	} 
}
function DefValue(X, Y, Z){
myWindow = window.open( "../05aMerlinAdminSetup/UserDefaults.asp?FormOptionId=" + X + "&WebPageId=" + Y + "&Value=" + Z, '_UserDefaults', 'top=10,left=500,toolbar=no,scrollbars=no,resizable=no,height=300,width=320')
myWindow.focus()
}

//Save rountine
function checkeydown(Form) 
{
	if (CheckIsIE())
	{
		if (window.event.ctrlKey && window.event.keyCode == 83)
		{
			event.returnValue = false; 
			Form.submitTask.value = 'Save';
			if(CheckFields()){Form.submit();}
		}
		else if (window.event.ctrlKey && window.event.keyCode == 77)
		{
			event.returnValue = false; 
			Form.submitTask.value = 'Save & New';
			if(CheckFields()){Form.submit();}
		}
		else if (window.event.ctrlKey && window.event.keyCode == 85)
		{
			event.returnValue = false; 
			Form.submitTask.value = 'Abort';
			if(CheckFields()){Form.submit();}
		}
	}
} 

//Gary 14/05/07
//Ctrl G is now 'Go'
document.onkeypress = 
	function (e)
	{	
		var KeyCode;
		var isCtrl = false;
			
		if (document.layers)
		{
			KeyCode = e.which;     //firefox
	        isCtrl	= e.ctrlKey ? true : false;
		}
		if(document.all)
	    {
	        KeyCode = window.event.keyCode;     //IE
			isCtrl	= window.event.ctrlKey ? true : false;
	    }
	    else
	    {
	        KeyCode = e.keyCode;
	        isCtrl	= e.ctrlKey ? true : false;
	    }	
		
		if(isCtrl)
			if (KeyCode == 7)
				goGrid(document['Form1']);
	};

function setTask(field)
{
	//$('submitTask').value = field.value;
	
	//NB	This function must be compatible with non-grid/non-addedit pages, ie. those without mootools.js
	if (document.getElementById('submitTask'))
	{
		document.getElementById('submitTask').value = field.value;
	}
}

function wait(){
document.getElementById("wait").innerText = document.getElementById("wait").innerText + "."
}
function showHide(elem){
if (document.getElementById(elem).style.display == 'none'){
document.getElementById(elem).style.display = 'block'}
else
	document.getElementById(elem).style.display = 'none'
}
function showHideIf(field1,elem,val){
	var bolSwitch
	bolSwitch = false
	switch (field1.type){
		case "checkbox":
			alert('checkbox not supported at this time')
			break;
		case "radio":
			alert('radio not supported at this time')
			break;
		case "select-one":
			if(field1.selectedIndex == val){bolSwitch = true}
			break;
		default: 
			if(field.value == val){bolSwitch = true}
			break;
	}
	if (bolSwitch){document.getElementById(elem).style.display = 'block'}
	else{document.getElementById(elem).style.display = 'none'}
}
function showHideElse(field1,elem,value){
		var bolSwitch
	bolSwitch = false
	switch (field1.type){
		case "checkbox":
			alert('checkbox not supported at this time')
			break;
		case "radio":
			alert('radio not supported at this time')
			break;
		case "select-one":
			if(field1.selectedIndex != val){bolSwitch = true}
			break;
		default: 
			if(field.value != val){bolSwitch = true}
			break;
	}
	if (bolSwitch){document.getElementById(elem).style.display = 'block';}
	else{document.getElementById(elem).style.display = 'none';}
}
function htmlABOVE(field_name, html)
{
	var object = $('CONT'+field_name.toUpperCase());
	
	if (!object)
	{
		object = $(field_name.toUpperCase());
	}
		
	if (object)
	{
		if (document.getElementById('SA' + field_name))	//multiple checkboxes
		{
			if (document.getElementsByName(field_name)[0].parentElement)
			{
				if (document.getElementsByName(field_name)[0].parentElement.parentElement)
				{
					object = document.getElementsByName(field_name)[0].parentElement.parentElement;
				}
				else
				{
					object = document.getElementsByName(field_name)[0].parentElement;
				}
			}
			
		}
		
		new Element('div').set('html', html).setProperties({'id':field_name+'_HTMLABOVE','class':'nav'}).injectBefore(object);
		//new Element('div').setHTML(html).setProperties({'id':field_name+'_HTMLABOVE','class':'nav'}).injectBefore(object);
	}	
}
function htmlBELOW(field_name, html)
{
	var object = $('CONT'+field_name.toUpperCase());
			
	if (!object)
	{
		object = $(field_name.toUpperCase());
	}
		
	if (object)
	{
		if (document.getElementById('SA' + field_name))	//multiple checkboxes
			object = document.getElementsByName(field_name)[0].parentElement.parentElement;
		
		if (object.getNext())
			//new Element('div').setHTML(html).setProperties({'id':field_name+'_HTMLABOVE','class':'nav'}).injectBefore(object.getNext());
			new Element('div').set('html', html).setProperties({'id':field_name+'_HTMLABOVE','class':'nav'}).injectBefore(object.getNext());
		else
			//new Element('div').setHTML(html).setProperties({'id':field_name+'_HTMLBELOW','class':'nav'}).injectAfter(object);
			new Element('div').set('html', html).setProperties({'id':field_name+'_HTMLBELOW','class':'nav'}).injectAfter(object);
	}
}

function element_BELOW (object,name,relative,position)
{
	if (object)
	{
		relative = $(relative.toUpperCase());
	
		if (relative)
		{
			if (relative.getNext())
				object.setProperties({'id':name,'class':'nav'}).injectBefore(relative.getNext());
			else
				object.setProperties({'id':name,'class':'nav'}).injectAfter(relative);
		}
	}
	else
	{
		alert('htmlInsert error');
	}
}

function insert_element (name,relative,position,html)
{
	relative = $(relative.toUpperCase());

	if (relative)
	{
		position = position.toUpperCase();
		
		if (position=="ABOVE")
		{
			//new Element('div').setHTML(html).setProperties({'id':name,'class':'nav'}).injectBefore(relative);
			new Element('div').set('html',html).setProperties({'id':name,'class':'nav'}).injectBefore(relative);
		}
		else if (position=="BELOW")
		{
			if (relative.getNext())
			{	//new Element('div').setHTML(html).setProperties({'id':name,'class':'nav'}).injectBefore(relative.getNext());
				new Element('div').set('html', html).setProperties({'id':name,'class':'nav'}).injectBefore(relative.getNext());
			}
			else
			{
				//new Element('div').setHTML(html).setProperties({'id':name,'class':'nav'}).injectAfter(relative);
				new Element('div').set('html', html).setProperties({'id':name,'class':'nav'}).injectAfter(relative);
			}
		}
		else if (position=="BEFORE")
		{
			//new Element('span').setHTML(html).setProperties({'id':name,'class':'nav'}).injectBefore(relative);
			new Element('span').set('html', html).setProperties({'id':name,'class':'nav'}).injectBefore(relative);
		}
		else if (position=="AFTER")
		{
			//new Element('span').setHTML(html).setProperties({'id':name,'class':'nav'}).injectAfter(relative);
			new Element('span').set('html', html).setProperties({'id':name,'class':'nav'}).injectAfter(relative);
		}
	}
	else
	{
		alert('htmlInsert error');
	}
}

function htmlBEFORE(field_name, html)
{
	var object = $('DISPLAY'+field_name.toUpperCase());

	if (!object)
	{
		object = $(field_name.toUpperCase());
	}
	
	if (object)
		//new Element('span').setHTML(html).setProperty('id',field_name+'_HTMLBEFORE').injectBefore(object);
		new Element('span').set('html', html).setProperty('id',field_name+'_HTMLBEFORE').injectBefore(object);
}

function htmlAFTER(field_name, html)
{
	var object = $('MESSAGE'+field_name.toUpperCase());

	if (!object)
	{
		object = $(field_name.toUpperCase());
	}
	
	if (object)
	{	//new Element('span').setHTML(html).setProperty('id',field_name+'_HTMLAFTER').injectAfter(object);
		new Element('span').set('html', html).setProperty('id',field_name+'_HTMLAFTER').injectAfter(object);
	}
}
function htmlStart(field, html){
	field = field.toUpperCase();
	var object = document.getElementById(field);
	
	if (!object)
	{
		object = $(field_name.toUpperCase());
	}	
		
	if (object)
	{//new Element('span').setHTML(html).setProperty('id',field+'_HTMLSTART').injectBefore(object);
		new Element('span').set('html', html).setProperty('id',field+'_HTMLSTART').injectBefore(object);
	}
}


// Form Field Validation Functions:
//
// isValidExpDate(formField,fieldLabel,required)
//   -- checks for date in the format MM/YY or MM/YYYY against the current date
// isValidCreditCardNumber(formField,ccType,fieldLabel,required)
//   -- checks for valid credit card format using the Luhn check and known digits about various cards
//



function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

function isValidExpDate(formField,fieldLabel,required)
{
	var result = true;
	var formValue = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
  
 	if (result && (formField.value.length>0))
 	{
 		var elems = formValue.split("/");
 		
 		result = (elems.length == 2); // should be two components
 		var expired = false;
 		
 		if (result)
 		{
 			var month = parseInt(elems[0],10);
 			var year = parseInt(elems[1],10);
 			
 			if (elems[1].length == 2)
 				year += 2000;
 			
 			var now = new Date();
 			
 			var nowMonth = now.getMonth() + 1;
 			var nowYear = now.getFullYear();
 			
 			expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));
 			
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
 		}
 		
  		if (!result)
 		{
 			alert('Please enter a date in the format MM/YY for the "' + fieldLabel +'" field.');
			formField.focus();
		}
		else if (expired)
		{
 			result = false;
 			alert('The date for "' + fieldLabel +'" has expired.');
			formField.focus();
		}
	} 
	
	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}	

		if (result)
 		{ 
 			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}



function GetRadioValue(rArray)
{
	for (var i=0;i<rArray.length;i++)
	{
		if (rArray[i].checked)
			return rArray[i].value;
	}
	
	return null;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTERCARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function validCCForm(ccTypeField,ccNumField,ccExpField)
{
	var result = isValidCreditCardNumber(ccNumField,ccTypeField.value,"Credit Card Number",true) &&
		isValidExpDate(ccExpField,"Expiration Date",true);
	return result;
}
function HideSelect(field){
//to hide a select field and show text of selected entry
val = field.options[field.selectedIndex].text
field.insertAdjacentHTML ('afterEnd',"<span style='font-weight: normal'>" + field.options[field.selectedIndex].text + "</span>")
field.style.display = 'none'
}
function deselectCheckbox(field) {
	//to deselect checkboxes in a grid where the value is negative
	if (field){
		if (field.value == undefined){
			for (var i = 0; i < field.length; i++){
			  if (field[i].value < 0){
				field[i].value = field[i].value*-1
				field[i].checked = false
				}
			}
		}	
		else {
		      if (field.value < 0){
				field.value = field.value*-1
				field.checked = false
				}
		}
	}	
}
function changeto(highlightcolor){
source=event.srcElement
if (source.tagName=="TR"||source.tagName=="TABLE")
return
while(source.tagName!="TR")
source=source.parentElement
if (source.style.backgroundColor!=highlightcolor&&source.id!="ignore")
source.style.backgroundColor=highlightcolor
}

function changeback(originalcolor){
if (event.fromElement.contains(event.toElement)||source.contains(event.toElement)||source.id=="ignore")
return
if (event.toElement!=source)
source.style.backgroundColor=originalcolor
}
// TabNext()
// WWW: http://www.mattkruse.com/
// Function to auto-tab phone field
// Arguments:
//   obj :  The input object (this)
//   event: Either 'up' or 'down' depending on the keypress event
//   len  : Max length of field - tab when input reaches this length
//   next_field: input object to get focus after this one
// -------------------------------------------------------------------
var tab_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {tab_field_length=obj.value.length;}
	else if (event == "up") {
		if (obj.value.length != tab_field_length) {
			tab_field_length=obj.value.length;
			if (tab_field_length == len) {next_field.focus();}
		}
	}
}
function checkAll(checkfield, field)
{
	//to select/deselect checkboxes in a grid
	var bolChecked = false;
	
	if (checkfield.checked)
		bolChecked = true;
		
	if (field)
	{
		if (field.value == undefined)
		{
			for (var i = 0; i < field.length; i++)
			{
			  	field[i].checked = bolChecked;
			}
		}	
		else 
		{
			field.checked	= bolChecked;
		}
	}	
}
function hasValueChecked(field){
	//to find out whether a checkbox list field has at least one value checked
	var bolChecked = false;
	if (field){
		if (field.length != undefined)
		{
			for (var i = 0; i < field.length; i++)
			{
				if (field[i].checked)
				{
			  		bolChecked = true;
			  	}
			}
		}
		else
		{
			bolChecked = field.checked;
		}
	}	
	return bolChecked;
}

function setCheckHeader(checkfield, field)
{
	var n = 0; //number checked
	
	if (field.value == undefined)
	{
		for (var i = 0; i < field.length; i++)
		{
			if(field[i].checked == true)
				n++;
		}
		
		if(n == field.length)
			checkfield.checked = true;
		else
			checkfield.checked = false;
	}
}

function setValid(myForm,item)
{
	if(item=="")
		alert('Range not set!');
	else
		myForm.Valid.selectedIndex = item;
}
function CheckIsIE() 
{ 
    if  (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER')  { 
    return true;} 
    else { return false; } 
  } 



function PrintThisPage(myiframe){ 
   if (CheckIsIE() == true) 
    { 
       myiframe.focus(); 
       myiframe.print(); 
    }      
    else 
     { 
        window.frames[myiframe.name].focus(); 
        window.frames[myiframe.name].print(); 
      } 
}
 function round(number,X) { 
 // rounds number to X decimal places, defaults to 2 X = (!X ? 2 : X);
  return Math.round(number*Math.pow(10,X))/Math.pow(10,X); 
  }
  
  function trim(strTrim){
    return rTrim(lTrim(strTrim));
}

    function lTrim(strTrim){
      while( strTrim.indexOf(' ') == 0 ){ strTrim = strTrim.substring(1) }
      return strTrim;
}

    function rTrim(strTrim){
      while( strTrim.lastIndexOf(' ') == strTrim.length-1 && strTrim.length > 0 ){ strTrim = strTrim.substring(0,strTrim.length-1) }
      return strTrim;
}
  function checkTelephoneNo(dialCode,telephone,dCodeDisplayName,telDisplayName){
    telephoneMessage = telDisplayName + ' is required if ' + dCodeDisplayName + ' has been filled in'
    dialCodeMessage = dCodeDisplayName + ' is required if ' + telDisplayName + ' has been filled in'
    if(dialCode.value!=''){
       return IsRequired(telephone,telephoneMessage)
    }
     if(telephone.value!=''){
       return IsRequired(dialCode,dialCodeMessage)
    }
    return true
  }
  
function wait1(){
	if (document.getElementById("waitGrid")){
		document.getElementById("waitGrid").innerText = document.getElementById("waitGrid").innerText + "."}
}
function hideGrid2()
{
	window.document.body.style.cursor = 'wait';
	if (document.getElementById('navbody')){
		document.getElementById('navbody').style.display='none';}
	if (document.getElementById('waitGrid')){
		document.getElementById('waitGrid').innerHTML = "Processing. Please wait....."}
	if (document.getElementById('content')){
		document.getElementById('content').style.visibility = "hidden"}
	window.setInterval('wait1()', 400)
}
function gethelp(menuItemId,webPageId,helpId)
{
	/*var i = 0;
	var indexfile;
	if (i==0){indexfile = '../help/Merlin Timeshare/'}
	else {indexfile = '../help/Merlin World/'}
	indexfile = indexfile + 'index.htm'
	myWindow = window.open(indexfile,'help' , 'top=0,toolbar=no,scrollbars=yes,resizable=yes,height=450,width=550')
	do {pausecomp(20); i++;}
	while (myWindow.frames.length<2 && i<10);
	alert('Welcome to Merlin\'s Help')
	myWindow.BODY.location.href = filename//'../Merlin Timeshare_Leisure/1145.htm'*/
	window.open( '../Internal/Help_View.asp?MenuItemId='+menuItemId+'&WebPageId='+webPageId+'&HelpId='+helpId, '_Help', 'top=0,toolbar=yes,scrollbars=yes,resizable=yes').focus();
}
function pausecomp(millis) 
{
	date = new Date();
	var curDate = null;
	do { var curDate = new Date(); } 
	while(curDate-date < millis);
}
function disableBack()
{
	/*If window has a history, open location in a new window (which will have clear history) 
	and close this window.*/
	
	if (window.history.length > 0)
	{
		var url; var myWindow; var width; var height; var windowname
		url = top.location
		
		/* Ordinarily if a window was opened manually and tries to close itself, a pop-up warns user 
			and asks if they want to allow it to close.  
			The two lines below stop this from happening.*/
		this.focus();
		self.opener = this;
		/****************************/
		
		/*Get dimensions for new window*/
		width = window.screen.availWidth;
		height = window.screen.availHeight;
		
		/*Get unique name for new window*/
		var currentTime = new Date()
		windowname = 'Merlin'+ currentTime.getTime();
		
		myWindow = window.open(url, windowname, 'left=0,top=0,width=' + width + ',height=' + height + ',toolbar=yes,location=yes,directories=yes,menubar=yes,status=yes,scrollbars=yes,resizable=yes')
		myWindow.focus();
		
		/*self.close causes securtity prompt, rather redirect to selfclose.asp*/
		//self.close();
		window.open('../selfclose.asp', '_self');
	}
}

function refreshParent ()
{
	if (self.opener)
	{
		var parentForm = self.opener.document.getElementById('Form1');
		if (parentForm)
		{
			if (parentForm['submitTask'])
				parentForm['submitTask'].value = 'REFRESH';
			parentForm.submit();
		}
		else {self.opener.location.href = self.opener.location.href;}
	}
}

function refreshParents ()
{
	//If Parent exists
	var currentWindow;
		currentWindow = self;
	
	while (currentWindow.opener)
	{
		if (currentWindow.opener.Form1)
		{
			currentWindow.opener.Form1.submit();
		}
		
		currentWindow = currentWindow.opener;
	}
}

function alertUsers (downHours, downMinutes)
{
	var dateNow	= new Date();
	
	var hours;
		hours = parseInt(downHours) + dateNow.getHours();
  
	var mins;
		mins = parseInt(downMinutes) + dateNow.getMinutes();

  if (mins>=60)		{ mins	= -(60 - mins); hours = parseInt(hours)+1; }
  if (hours>=24)	{ hours = -(24 - hours); }
  
  if (mins<=9)	{ mins	= '0' + mins; }
  if (hours<=9) { hours	= '0' + hours; }
  
  var tempMinutes;
	  tempMinutes = dateNow.getMinutes();
	  
	   if (tempMinutes<=9)	{ tempMinutes	= '0' + tempMinutes; }
	
	var msg;
		msg =	'ATTENTION\n' + 
				'\n' + 
				'Merlin will go offline at ' + hours + ':' + mins + ' for ' + downMinutes + ' Minutes for essential maintenance.\n' +
				'\n' +
				'Please save your work, log off and then Log on again after ' + downMinutes + ' minutes.\n' +
				'\n' +
				'If you require more time, please contact Support and we will advise you futher.\n' +
				'\n' +
				'Thank You\n' +
				'\n' +
				'The Merlin Team'
	
	alert (msg);
}

function takeOnName()
{
	myWindow = window.open('../01dName/NameResp.asp?WebPageId=105&Menu=FTO&list_pos=sub1011', '','top=0,toolbar=yes,scrollbars=yes,resizable=yes');
	myWindow.focus ()
}

/*function hideGrid(task)
{
	if(task ==undefined ){task="Loading"}
	
	window.document.body.style.cursor = 'wait';
	//document.getElementById('navbody').style.display='none';

	if (document.getElementById('gridcontent'))
		document.getElementById('gridcontent').innerHTML = "<span><img id='wait' src='../images/Merlin1.gif' name='wait' style='padding-left:20px;font-size: 11px;font-weight: bold;' >" + task + ". Please wait.....></span>"
	//window.setInterval('wait()', 400)
	

	//	document.getElementById('content').innerHTML = "<span id='wait' name='wait' style='padding-left:20px;font-size: 11px;font-weight: bold;' >" + task + ". Please wait.....</span>"
	//document.getElementById('content').src = "../images/Merlin1.gif" ;
}*/

function hideGrid(task)
{
	hideGridForWindow(window.document, task)
}

function hideGridForWindow(x, task)
{
	if(task ==undefined )
	{
		task="Loading";
	}
	
	if ($('GridDiv'))
	{
		$('GridDiv').set('style','display:none;');
	}
	
	var div_loading = $('div_loading');
	
	if (div_loading)
	{
		var iH = div_loading.get('html');
		if (iH.indexOf(task) == -1) 
		{
			div_loading.set('html', iH + task);
		}
		div_loading.set('style','display:inline-block;');
	}
}	

function setKey (strKey)
{
	document.Form1.Key.value = strKey;
}

function getKey (strKey)
{
	return document.Form1.Key.value;
}

function Process(bolGo_Grid)
{
	hideGrid();
	var location = PageName + '.asp?Key=' + AA.join('^') + '&list_pos=' + ListPos;
	
	//Mark as go grid
	if (bolGo_Grid==true)
	{
	alert('3');
		setTask ('Go');
		location = location + '&A=Go';
	}

	top.location = location + CheckSelect();
}

function Ajax_Check_Disabled (field)
{
	var bolDisabled = false;
	
	if ($('DISABLED'+field))
	{
		if ($('DISABLED'+field).disabled)
			bolDisabled = true;
	}
	else if ($(field+'DISABLED'))
	{
		if ($(field+'DISABLED').disabled)
			bolDisabled = true;
	}
		
	return bolDisabled;
}

function Ajax_Make_Disabled (field)
{
	$(field).setProperty('disabled','disabled');
	
	if ($('DISABLED'+field))
		$('DISABLED'+field).value = $(field).getProperty('value');
	else if ($(field+'DISABLED'))
		$(field+'DISABLED').value = $(field).getProperty('value');
}

function Update_Dependants (field)
{
	var dependants = $(field.toUpperCase() + 'DEPENDANTS');
	
	if (dependants)
	{
		if (dependants.get('value'))
		{
			var dependants_array = returnArray(dependants.get('value'),'^');
		
			for (var q=0;q<dependants_array.length;q++)
			{
				Ajax_Filter(dependants_array[q]);
			}
		}
	}
}

function Update_Dependants_Old (field)
{
	var dependants = $(field.toUpperCase() + 'DEPENDANTS');
	
	if (dependants)
	{
		if (dependants.get('value'))
		{	
			var dependants_array = returnArray(dependants.get('value'),';');
		
			for (var q=0;q<dependants_array.length;q++)
			{
				eval('"' + dependants_array[q] +';"');
			}
		}
	}
}

/*document.onkeydown = function () 
{
	var eventKeyCode = 0;
	
	if (window.event.keyCode == 8 && !window.document.activeElement.isTextEdit)
	{
		eventKeyCode		 = window.event.keyCode;
		alert('Backspace has been disabled');
		window.event.keyCode = 506;
		return false;
	}

	if (window.event.keyCode == 116)
	{
		//alert(getKey());
		eventKeyCode		 = window.event.keyCode;
		top.location		 = top.location + '&Key=' + getKey();
		window.event.keyCode = 506;
	}
}*/

/*document.onkeypress = function (evt) 
{
	var r = '';
	
	if (document.all) 
	{
		r += event.ctrlKey ? 'Ctrl-' : '';
		r += event.altKey ? 'Alt-' : '';
		r += event.shiftKey ? 'Shift-' : '';
		r += event.keyCode;
	}
	else if (document.getElementById) 
	{
		r += evt.ctrlKey ? 'Ctrl-' : '';
		r += evt.altKey ? 'Alt-' : '';
		r += evt.shiftKey ? 'Shift-' : '';
		r += evt.charCode;
	}
	else if (document.layers) 
	{
		r += evt.modifiers & Event.CONTROL_MASK ? 'Ctrl-' : '';
		r += evt.modifiers & Event.ALT_MASK ? 'Alt-' : '';
		r += evt.modifiers & Event.SHIFT_MASK ? 'Shift-' : '';
		r += evt.which;
	}
	
	alert (r);
	return false;
}*/

function Prompt (strMsg)
{
	alert (strMsg);
}

//Katja 13/04/2007
function FormatMoney(formfield){
	var wd
	wd="w"
	var tempnum=formfield.value;
	for (k=0;k<tempnum.length;k++){
		if (tempnum.charAt(k)=="."){
			wd="d"
			break
		}
	}
	if (wd=="w")
		formfield.value=tempnum+".00"
	else{
		if (tempnum.charAt(tempnum.length-2)=="."){
			formfield.value=tempnum+"0"
		}
		else{
			if (tempnum == 0){
				formfield.value = "0.00"
			}
			else{
				tempnum=Math.round(tempnum*100)/100
				formfield.value=tempnum
			}
		}
	}
}

function FormatDecimalField (fld, decPlaces, allowNegative) 
{ 
	if (fld)
	{
		var cDec = '.';		//decimal point symbol 
		var hasDecPoint = false; var val = ""; 
		var strf = ""; var neg = ""; var i = 0;
		
		str = fld.value;
		
		parseFloat ("0").toFixed (decPlaces); 
		
		if (allowNegative && str.charAt (i) == '-') { neg = '-'; i++; } 
		
		for (i; i < str.length; i++) 
		{ 
			val = str.charAt (i); 
			if (val == cDec) 
			{ 
				if (!hasDecPoint) { strf += val; hasDecPoint = true; } 
			} 
			else if (val >= '0' && val <= '9') 
				strf += val; 
		} 
		
		strf = (strf == "" ? 0 : neg + strf); 
		
		fld.value = parseFloat (strf).toFixed (decPlaces); 
	}
}
function RefreshForDependant ()
{
	if (document.getElementById("DEFAULTSINGLEDEPENDANT"))
	{	
		if (document.getElementById("DEFAULTSINGLEDEPENDANT").value)
		{	
			if (document.getElementById("DEFAULTSINGLEDEPENDANT").value==0)
			{
				document.getElementById("DEFAULTSINGLEDEPENDANT").value = 1;
				document.getElementById("submitTask").value				= "REFRESH";
				document.Form1.submit();
			}
		}
	}
}

function Hide_Block_Onload (Name,Link)
{
	var link = $(Link);
	
	if (link)
	{
		if (link.value == 1)
		{	
			$("Block"+Name).setStyle('display','block');
			
			if (link)
			{
				link.value = 1;
				$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('+','-');
			}
		}
		else
		{
			$("Block"+Name).style.display = "none";
			if ($(Link))
			{
				document.getElementById(Link).value = 0;
				document.getElementById("DISPLAY" + Link).innerHTML = document.getElementById("DISPLAY" + Link).innerHTML.replace('-','+');
			}
		}
	}
}

function Hide_Block_Onload (Name,Link,Toggle)
{	
	Link = Link.toUpperCase();
	Name = Name.toUpperCase();
	
	var link = $(Link);
		
	if (link)
	{
		if (link.value == 1)
		{
			$("Block"+Name).setStyle('display','block');
			
			if (link)
			{
				link.value = 1;
				$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('+','-');
			}
		}
		else
		{
			$("Block"+Name).style.display = "none";
			if ($(Link))
			{
				$(Link).value = 0;
				$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('-','+');
			}
		}

		if (accordion!=undefined)
		{
			accordion.hideSection(Toggle);
			accordion.toggleSection(Toggle);
		}		
	}
}

function Hide_Block_Loaded (Name,Link)
{
	var link = $(Link.toUpperCase());

	if(link.value == 0)
	{
		$("Block"+Name).style.display = 'block';
					
		if (link)
		{
			link.value = 1;
			$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('+','-');
		}
	}
	else
	{
		$("Block"+Name).style.display = "none";
		if ($(Link))
		{
			$(Link).value = 0;
			$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('-','+');
		}
	}
}

function Hide_Block_Loaded (Name,Link,Toggle)
{
	Name = Name.toUpperCase();
	Link = Link.toUpperCase();
	
	var link = $(Link);
	
	if(link.value == 0)
	{
		$("Block"+Name).setStyle('display','block');
					
		if (link)
		{
			link.value = 1;
			$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('+','-');
		}
	}
	else
	{
		$("Block"+Name).style.display = "none";
		if ($(Link))
		{
			$(Link).value = 0;
			$("DISPLAY" + Link).innerHTML = $("DISPLAY" + Link).innerHTML.replace('-','+');
		}
	}
	
	if (accordion)
	{
		accordion.hideSection(Toggle);
		accordion.toggleSection(Toggle);
	}
}

function $Get (Field)
{
	return document.getElementById(Field);
}

function CheckName_Simple(FieldPrefix)
{
	FieldPrefix = FieldPrefix.toUpperCase();
		
	var LastName	= document.getElementById(FieldPrefix + "LASTNAME").value;
	var FirstName	= document.getElementById(FieldPrefix + "FIRSTNAME").value;
		
	if (LastName.length == 0)
		alert('You must enter a Last Name to use the Check Name feature.');
	else
	{
		Split();
	
		var DupKey;
			DupKey = '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^';
			DupKey = DupKey.split('^');
			
		DupKey [8]  = FirstName.replace('&','%26');
		DupKey [9]  = LastName.replace('&','%26');
		DupKey [10] = A[10];
		DupKey [28] = 1;

		myWindow = window.open('../01dName/Name_Check.asp?Menu=NoMenu&Key=' + DupKey.join('^') + '&sel=true&NameId=0&FetchForm=Form1&FetchColumn=FULLNAME&FetchPage=Name.asp&FetchPrefix=' + FieldPrefix + '&FetchField=' + FieldPrefix + 'NAMEID&FetchField2=OCCUPIERNAMEID', '_CheckName','top=0,toolbar=yes,scrollbars=yes,resizable=yes,height=600,width=800');
		myWindow.focus();
	}
}

function CheckName(Form,FieldPrefix,UpdateField2,bolRefreshParent)
{
	if (!FieldPrefix)
	{	
		CheckName('Form1',Form,'',false);
		return;
	}
	
	FieldPrefix = FieldPrefix.toUpperCase();
	
	var LastName;
		LastName = $(FieldPrefix + "LASTNAME").value;
		
	var FirstName;
		FirstName = $(FieldPrefix + "FIRSTNAME").value;
		
	if (LastName.length == 0)
		alert('You must enter a Last Name to use the Check Name feature.');
	else
	{
		Split();
	
		var DupKey;
			DupKey = '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^';
			DupKey = DupKey.split('^');
			
		DupKey [8]  = FirstName.replace('&','%26');
		DupKey [9]  = LastName.replace('&','%26');
		DupKey [10] = A[10];
		DupKey [28] = 1;
		
		UpdateField2 = UpdateField2.toUpperCase();

		myWindow = window.open('../01dName/Name_Check.asp?Menu=NoMenu&Key='+DupKey.join('^')+'&sel=true&NameId=0&FetchForm='+Form+'&FetchColumn=FULLNAME&FetchPage=Name.asp&FetchPrefix='+FieldPrefix+'&FetchField=NAMEID&FetchField2='+UpdateField2+'&Refresh='+bolRefreshParent, '_CheckName','top=0,toolbar=yes,scrollbars=yes,resizable=yes,height=600,width=800');
		myWindow.focus();
	}
}
function LogSupportCall()
{
	NewWindow('../Internal/SupportLog1.asp?Menu=NOMENU', 'SupportLog', 1000,600,'yes','yes');
}
function EmailSupport()
{
	var url = '../Internal/SupportLogFromEmail.asp?Menu=NOMENU';
	var windowName = 'SupportEmail';
	var sourceUrl = this.location.href; var menuPath;
	
	sourceUrl = sourceUrl.replace('&', '%26');
	
	if (isDefined('oM')) {menuPath = oM.getMenuPath(self);}
	
	url = url + '&SURL=' + sourceUrl;
	
	if (menuPath)
		url = url + '&MP=' + menuPath;
	
	NewWindow(url, windowName,600,520,'yes','yes')
}
function isDefined(variable)
{
	return (typeof(window[variable]) != 'undefined');
}

var pdWinNum=0;
var pdLeft = 20;
var pdTop = 20;

function PromptDownload(FilePath, FileName, inNewWindow)
{
	var url = '../Lib/StartDownload.asp?File=' + FilePath + '&Name=' + FileName
	
	if (inNewWindow)
	{
		myWindow = window.open(url, '_Doc'+ pdWinNum,'top=' + pdTop + ',left=' + pdLeft + ',toolbar=no,scrollbars=no,resizable=no,height=20,width=20');
		myWindow.focus();	
	
		pdWinNum++;
		pdLeft+=50;
		pdTop+=50;
	}
	else
	{
		top.location = url;
	}
}

/*function $(objectName)
{
	objectName = objectName.toUpperCase();
	return document.getElementById(objectName);
}*/

function $v(objectName)
{
	objectName = objectName.toUpperCase();
	return $(objectName).value;
}
Date.prototype.add = function (sInterval, iNum){
  var dTemp = this;
  if (!sInterval || iNum == 0) return dTemp;
  switch (sInterval.toLowerCase()){
    case "ms":
      dTemp.setMilliseconds(dTemp.getMilliseconds() + iNum);
      break;
    case "s":
      dTemp.setSeconds(dTemp.getSeconds() + iNum);
      break;
    case "mi":
      dTemp.setMinutes(dTemp.getMinutes() + iNum);
      break;
    case "h":
      dTemp.setHours(dTemp.getHours() + iNum);
      break;
    case "d":
      dTemp.setDate(dTemp.getDate() + iNum);
      break;
    case "mo":
      dTemp.setMonth(dTemp.getMonth() + iNum);
      break;
    case "y":
      dTemp.setFullYear(dTemp.getFullYear() + iNum);
      break;
  }
  return dTemp;
}
function CRange(oDat)
{
	var day = '0' + oDat.getDate(); 
	day = day.substr((day.length-2),2);
	var month = '0' + (oDat.getMonth()+1);
	month = month.substr((month.length-2),2);
	return day+ '/'+ month + '/' + oDat.getFullYear();
}
function LoadAccount(GLAccountId, CompanyId)
{
	var ynow = new Date();
	ynow.add("y", 1);
	var yago = new Date();
	yago.add("d", -1);
	yago.add("y", -1);
			
	var n = CRange(ynow);
	var m = CRange(yago);
	
	LoadAccountWithDates(GLAccountId, CompanyId, m, n);
}

function LoadAccountWithDates(GLAccountId, CompanyId, FromDate, ToDate)
{
	Split();
	
	A[0]='Ref'; A[2]=50; A[4]=1; A[5]=""; A[7]=0; 
	A[8]=CompanyId; 
	A[9]=GLAccountId; 
	A[12]=1;			//Valid
	A[14]=FromDate; A[22]=ToDate;	//From Date To Date
	A[15] = '';
	A[23]=0; A[24]=0;	//From Period To Period
	A[25]=0;			//All
	
	myWindow = window.open( '../02aSalesSetUp/GLTrans.asp?Menu=NOMENU&Key=' + A.join('^'), '_GLTrans', 'top=0,toolbar=yes,scrollbars=yes,resizable=yes');
	myWindow.focus();
}

function minimize (target)
{
	$(target).tween('display', 'none');
}

function maximize (target)
{
	$(target).tween('display', 'block');
}

function popClose (target)
{
	$(target).tween('display', 'none');
}

function browserIsIE()
{
	if (navigator.userAgent.indexOf('Opera') == -1) 
	{
		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			return true;
		}
	}
	return false;
}

function setToolTip (fieldObject,text)
{
	fieldObject.setAttribute('title',text); if (fieldObject.getAttribute('className')) fieldObject.addClass('tooltip'); else fieldObject.setAttribute('class','tooltip');new Tips(fieldObject);
}

function new_window (name, location, querystring, width, height)
{
	if (width)
	{
		if (width < 1)
			width = 600;
	}
	else
		width = 600;
	
	if (height)
	{	
		if (height < 1)
			height = 400;
	}
	else
		height = 400;
		
	var top		= (screen.height - height)/2;
	var left	= (screen.width - width)/2;
	
	if (location.search("[\?]")!=-1)
		location += '&';
	else
		location += '?';
	
	var strurl	= location + querystring;
	
	window.open(strurl, name, 'top=' + top + ',left=' + left + ',toolbar=no,scrollbars=yes,resizable=yes,height=' + height + ',width=' + width).focus();
}

function appendDependancy (dependancies, appendThis)
{
	if (dependancies.charAt(dependancies.length)=='^')
		dependancies += appendThis;
	else
		dependancies += '^' + appendThis;
	
	return dependancies;
}

function updateSpan (field,value)
{
	var bolIsSpan = false;
		
	if (field.tagName.toUpperCase() == 'SPAN')	
		bolIsSpan = true;
	
	if (bolIsSpan == true)
	{
		if (browserIsIE())
			field.innerText = value; /*unescape(value).replace(/\+/g,' ');*/
		else
			field.innerHTML = value; /*unescape(value).replace(/\+/g,' ');*/
	}
}

function getSpanText (field)
{
	var bolIsSpan	= false;
	var text		= '';
			
	if (field.tagName.toUpperCase() == 'SPAN')	
		bolIsSpan = true;
	
	if (bolIsSpan == true)
	{
		if (browserIsIE())
			text = field.innerText; /*unescape(value).replace(/\+/g,' ');*/
		else
			text = field.innerText; /*unescape(value).replace(/\+/g,' ');*/
	}
	
	return text;
}

function setBookmark(formname, fieldname)
{
	formname = document.getElementById(formname);
	
	if (formname)
	{
		var bookmark = formname.Bookmark;
		var anchor	= document.getElementById('B' + fieldname.toUpperCase());
		
		if (bookmark && anchor)
		{
			bookmark.value = anchor.value;
		}
	}
}
function HTML_Encode (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   alert(div.innerHTML);
   return div.innerHTML;
};

function changeValue(fieldId, value, parent)
{
	if (parent)
		parent.eval('changeValueActual("' + fieldId + '", "' + value + '");')
}

function changeValueActual(fieldName, value)
{
	var field = $(fieldName);
	
	if (field)
	{		
		var prevValue = '';
		
		if (isSpan(field))
		{
			prevValue = field.innerHTML;
			updateSpan(field,value);
		}
		else
		{
			prevValue = field.value;
			field.value = value;
		}
		
		if (value != prevValue)
		{
			if (field.getProperty('onchange'))
			{
				var onchange = field.getProperty('onchange');
				typeof onchange == 'function' ? onchange() : eval(onchange);
			}
		}
	}
}
function isSpan(field)
{
	return (field.get('tag').toUpperCase() == 'SPAN');
}
function makeDate(fld)
{
	fld = fld.toUpperCase();
	if ($(fld))
	{
		if ($(fld).value.length == 8)
			$(fld).value = $(fld).value.substr(0,2) + '/' + $(fld).value.substr(2,2) + '/' + $(fld).value.substr(4,4);
		if ($(fld).value.length == 6)
			$(fld).value = $(fld).value.substr(0,2) + '/' + $(fld).value.substr(2,2) + '/20' + $(fld).value.substr(4,2);
	}
}
function IEFocusHack()
{
	if (CheckIsIE)
	{
		for(var i = 0; i < document.forms.length; i++)
		{
			var form = document.forms[i]; var onFocus; var onBlur; var id;
			for(var t = 0; t < form.elements.length; t++)
			{
				id = form.elements[t].id;
				
				if ($(id).getProperty('type') != 'hidden')
				{
					onFocus = $(id).getProperty('onfocus');
					form.elements[t].onfocus = function(){this.className += "focus"; eval(onFocus);}
					
					onBlur = $(id).getProperty('onblur');
					form.elements[t].onblur = function(){this.className = this.className.replace("focus", ""); eval(onBlur);}
				}
			}
		}
	}
}
function openEmail(toAdd, subj, body)
{
	var strMail = 'mailto:'
	var hasSubj = false;
	
	if (toAdd)
		if (toAdd.length > 0)
			strMail += toAdd
		
	if (subj)		
		if (subj.length > 0)
		{
			strMail += '?subject=' + subj
			hasSubj = true;
		}
		
	if (body)
		if (body.length > 0)
			if (!hasSubj)
				strMail += '?body=' + body
			else
				strMail += '&body=' + body
	
	this.location.href = strMail;
}

function ShowDivIfTicked(tickboxName, divName)
{
	if ($(tickboxName) && $(divName))
	{
		if ($(tickboxName).checked)
			$(divName).style.display = 'block';
		else
			$(divName).style.display = 'none';
	}
}

function getProperty(strProperty)
{
	this.get(strProperty);
}

function evalOnchange (field_Name)
{	
	var field = $(field_Name.toUpperCase())
	
	if (field)
	{
		var onchange = field.get('onchange');
		
		if (onchange.length > 0)
		{
			eval(onchange);
		}
	}
}

function evalAttribute (field_Name,attribute)
{	
	var field = $(field_Name);
	
	if (field)
	{
		var attribute_value = field.get(attribute);
		
		if (attribute_value.length > 0)
		{
			eval(attribute_value);
		}
	}
}

function evalOnchange_fld(field)	//For a non-mootools field
{
	var onchange = field.onchange;
 
	if (onchange)
	{
		typeof onchange == 'function' ? onchange() : eval(onchange);
	}
}

var Validate_Field = function (field,type)
	{
		var valid_msg = Valid_Field_Msg($(field),type);
		
		if(valid_msg.length > 0)
		{ 
			var msg_field = $('MESSAGE'+field);
			
			if($(field+'validation'))
			{
				$(field+'validation').set({'html':valid_msg, 'style':'display:inline;'});
				highlight($(field));
			}
			else 
			{
				msg_field.adopt(new Element('span').set({'id':field+'validation','class':'validationerror_field','html':valid_msg}));
			}
			
			msg_field.set('style','display:inline;');
			highlight($(field));
		}
		else
		{
			if($(field+'validation'))
			{
				$(field+'validation').set({'style':'display:none;','html':''});
				unhighlight($(field));
			}
		}
	}
	
var hideActions = function (showing)
	{				
		if (showing)
		{
			showing.removeClass('showing');
			showing.set('style','display:none;');
			removeBodyEvents();
		}
	}
	
var removeBodyEvents = function ()
	{
		$$('body')[0].removeEvents();
	}
	
var showActions = function (list_number)
	{
		var already_showing = $$('.showing');
		
		if (already_showing.length > 0)
		{
			hideActions(already_showing[0]);
			
			if (list_number > -1)
			{
				if (already_showing[0].get('id') != 'action_list_' + list_number)
				{
					showActionList(list_number);
				}
			}
		}
		else
		{
			showActionList(list_number);
		}
	}
	
var showActionList = function (list_number)
	{
		var id = new String('action_list_'+list_number.toString());
		var action_list = $(id);
		
		if (action_list)
		{		
			action_list.set('tween',
				{
					onComplete: function()
						{
							$$('body')[0].addEvent('click',function(){hideActions($(id));return false;});
						}
				});
		
			action_list.addClass('showing');
			action_list.tween('display','block');
			
			positionField (action_list,action_list.getParent(),'bottomLeft');
		}
	}
	
var positionField = function(position_this, relative_to, where)
	{
		if (position_this)
		{
			if (relative_to)
			{
				position_this.setPosition
					({
						relativeTo: relative_to,
						position: where
					});
			}
		}
	}
function Contract(I)
{
	var ynow = new Date();
	var n = CRange(ynow);
	
	Split()
	A[0]='Ref';A[5]=I; A[7]=I; A[8]=0; A[9]=0; A[12]=0; A[14]=0; A[26]=450; A[28]=n; A[29]=n; A[35]=''; A[36]='';
	myWindow = window.open( '../02bSalesProcesses/Contracts.asp?Menu=NOMENU&Key=' + A.join('^'), '_Contracts', 'top=0,toolbar=yes,scrollbars=yes,resizable=yes')
	myWindow.focus()
}
