var isMac = (navigator.appVersion.indexOf("Mac") != -1);
var allSupport = (document.all != null);
var layerSupport = (document.layers != null);
var elementbyidSupport = (document.getElementById != null);
var ns6 = (document.getElementById && !document.all && !navigator.userAgent.indexOf("firefox") ); // Netscape 6+

//*******************************************
// Popup Window Detection
function DetectPopupBlocker() 
{
	/* var testBlocker = window.open("popupTest.htm?page=NoPage","","width=10,height=10,left=1,top=1");
	try
		{
		// Popups not blocked.
		testBlocker.close();
		return true;
		}
	catch (e) 
		{
		// Popups blocked
		alert("Pop Up Blocker:\n\nYou appear to have a pop-up blocker preventing EnterOnLine from opening a required window.\n\nPlease enable pop-ups for this website - then try again.");
		return false;
		}
	// SDG switched off for now until issue encountered. */
	return true;
}
//**********************************************
// Open a window with a parsed object, width and height.
function OpenWindow(obj,thisWidth,thisHeight)
{
	var popUpNotBlocked = DetectPopupBlocker();
	if (popUpNotBlocked)
		{
		window.open(obj,'newWindow','width='+thisWidth+',height='+thisHeight+',scrollbars=no,resizable=yes,left=10,top=20');
		}
}

//**********************************************
// Open a sizable window with a parsed image name.
function OpenImageSizableWindow(thisWindowTitle, thisImage, thisWindowWidth, thisWindowHeight)
{		
	var popUpNotBlocked = DetectPopupBlocker();
	if (popUpNotBlocked)
		{
		newWindow=window.open('','newWindow','width='+thisWindowWidth+',height='+thisWindowHeight+',scrollbars=yes, resizable=yes, left=20,top=20');
		newWindow.document.open();
		newWindow.document.write("<html>");
		newWindow.document.write("<head>");
		newWindow.document.write("<title>"+thisWindowTitle+"</title>");
		newWindow.document.write('<LINK rel="stylesheet" type="text/css" href="stylesheet.css" title="style">');
		newWindow.document.write("<style title='PopWindow Styles' type='text/css'> ");		
		newWindow.document.write("Body { background-color: #FFFFFF; }");		
		newWindow.document.write("</style>");		
		newWindow.document.write("</head>");
		newWindow.document.write("<body topmargin='10' leftmargin='10' rightmargin='10'>");
		newWindow.document.write("<br><br><center><img src='"+thisImage+"'><center><br>");
		newWindow.document.write('<center><a href="JavaScript:window.self.close()"><img src="images/Button_Close.png" style="background:transparent" border="0"></a>&nbsp;&nbsp;<a href="JavaScript:window.print();"><img src="images/Button_Print.png" style="background:transparent" border="0"></a></center>');
		newWindow.document.write("</body>");
		newWindow.document.write("</html>");
		newWindow.document.close();
		newWindow.focus();
		}
}


//**********************************************
// Open a pop-up, non-sizeable frame type window with the provided URL, width and height of the window.
function OpenNonSizeablePopWindow(windowName,thisURL,thisWidth,thisHeight)
{
	var popUpNotBlocked = DetectPopupBlocker();
	if (popUpNotBlocked)
		{
		window.open(""+thisURL+"",""+windowName+"","width="+thisWidth+",height="+thisHeight+",left=50,top=100,status=yes,toolbar=no,scrollbars=yes");
		}
}

//**********************************************
// Open a pop-up, sizeable frame type window with the provided window name, URL, width and height of the window and scroll bars.
function OpenSizeablePopWindow(windowName,thisURL,thisWidth,thisHeight)
{
	var popUpNotBlocked = DetectPopupBlocker();
	if (popUpNotBlocked)
		{
		window.open(""+thisURL+"",""+windowName+"","width="+thisWidth+",height="+thisHeight+",left=20,top=20,status=yes, resizable=yes, toolbar=no, scrollbars=yes");
		}
}

//**********************************************
// Open a pop-up, modal window with the provided URL, width and height of the window.
function OpenPopModalWindowFrame(thisURL,thisWidth,thisHeight)
{
	// See: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/showmodaldialog.asp
	// window.showModalDialog("MYWindow.htm","Dialog Box Arguments # 1","dialogHeight: 400px; dialogWidth: 744px; dialogTop: 167px; dialogLeft: 1046px; edge: Raised; center: Yes; resizable: Yes; status: Yes;");
	// Note that if using 'center' then dialogTop/dialogLeft need to be set to an empty value
	// The Arguments parameter is for passing in any items you want to use in the window (eg. some text).
	var popUpNotBlocked = DetectPopupBlocker();
	if (popUpNotBlocked)
		{	
		var sFeatures = "dialogHeight:" + thisHeight + "px; dialogWidth:" + thisWidth + "px;";
		sFeatures = sFeatures + "dialogTop:10px; dialogLeft:10px; edge:Raised; center:No; resizable:Yes; status:Yes";
		window.showModalDialog(thisURL, "ModalWindow", sFeatures);
		}
}

//**********************************************
//Following functions used for dynamic help

function SetPosition(helpDiv,itemName)
{
	var src;
	
	if (itemName == 'description')
		{
		// Special case, as "description" exists in the Meta tags too!
		src = document.forms[0].description;
		}
	else
		{
		src = GetElement(itemName);
		}
				
	if (allSupport)
		{ // Internet Explorer, Mac...
		if (isMac)
			{
			helpDiv.style.top = GetOffset(src, "Top") - 130;
			helpDiv.style.left = GetOffset(src, "Left") - 20;
			} 
		else
			{
			if (itemName == "image0")
				{ // Top help - ie. not next to the field.
				helpDiv.style.pixelTop = GetOffset(src, "Top") - 70;
				helpDiv.style.pixelLeft = GetOffset(src, "Left") + 55;
				}
			else
				{
				if (src.type == "textarea")
					{ // Text areas place the help too low, so move it up.
					helpDiv.style.pixelTop = GetOffset(src, "Top") - 200;
					helpDiv.style.pixelLeft = GetOffset(src, "Left") - 20;
					}
				else if (itemName.indexOf("Info_") != -1)
					{ // Image help (ie. id="Info_CC1243")					
					helpDiv.style.pixelTop = GetOffset(src, "Top") - 110;
					helpDiv.style.pixelLeft = GetOffset(src, "Left") - 20;
					}					
				else
					{ // Standard field.
					helpDiv.style.pixelTop = GetOffset(src, "Top") - 130;
					helpDiv.style.pixelLeft = GetOffset(src, "Left") - 20;					
					}
				}
			}	
		}
	else if (ns6)
		{ // Netscape...		
		itemName = document.getElementById(itemName);
		helpDiv.style.top = itemName.y;
		helpDiv.style.left = itemName.x;
		} 
	else if (elementbyidSupport)
		{// Firefox...	
		if (src.type == "textarea")
			{ // Text areas place the help too low, so move it up.
			helpDiv.style.top = document.images[itemName].y - 200;
			helpDiv.style.left = document.images[itemName].x;				
			}		
		 if (itemName.indexOf("Info_") != -1)
			{
			helpDiv.style.top = document.images[itemName].y - 100;
			helpDiv.style.left = document.images[itemName].x;			
			}
		else
			{
			helpDiv.style.top = GetOffset(src, "Top") - 110;
			helpDiv.style.left = GetOffset(src, "Left") - 20;
			}
		} 
	else
		{ // Other browsers...
		if (src.type == "textarea")
			{ // Text areas place the help too low, so move it up.
			helpDiv.top = GetOffset(src, "Top") - 200;
			helpDiv.left = GetOffset(src, "Left");			
			}				
		else if (itemName.indexOf("Info_") != -1)
			{
			helpDiv.top = document.images[itemName].y - 100;
			helpDiv.left = document.images[itemName].x;
			}
		else
			{
			helpDiv.top = GetOffset(src, "Top") - 110;
			helpDiv.left = GetOffset(src, "Left") - 20;	
			}
		}			 
} 	


function SetVisibility(show) 
{
	var helpDiv = GetElement("helpTable")
	
   	if (show)
		{
    	if ((allSupport)||(elementbyidSupport))
			{
       		helpDiv.style.visibility = "visible" 
       		}
     	else
			{
       		helpDiv.visibility = "show";
       		}
		}
   else
     	if ((allSupport)||(elementbyidSupport))
			{
       		helpDiv.style.visibility = "hidden"
       		}
  		else
			{
       		helpDiv.visibility = "hidden"
       		}
}
  

function DisplayContents(itemName, msg)
{
	var helpDiv = GetElement("helpTable");
	WriteContents(helpDiv, msg, itemName);	
	SetPosition(helpDiv, itemName);	
	SetVisibility(true);
} 
	

function GetElement(itemName) 
{
	if ((allSupport)||(elementbyidSupport))
		{
		return document.getElementById(itemName);
		}
	else if (layerSupport)
		{
		return document.layers[itemName];
		}
}


function WriteContents(helpDiv, msg, itemName) 
{
	if (itemName == "image0")
		{
		var contents = "<table cellpadding='0' cellspacing='0' width='290' border='0'> " +
					   "<tr> " +
					   	   "<td background='images/HelpBubble_Top.png' height='26' align='center' valign='top' style='padding-top:9px'><span class='helpTableText'><strong>Help Tip...</strong></span></td></tr> " +
					   	   "<td width='222' background='images/HelpBubble_Expander.png' style='padding-left:14px;padding-right:8px'><span class='helpTableText'>"+msg+"</span></td> " +
					   "</tr> " +
					   "<tr><td align='left' valign='top' height='20'><img src='images/HelpBubble_Bottom.png'></td></tr> " +
					   "</table>";
		}
	else
		{
		var contents = "<table cellpadding='0' cellspacing='0' width='332' border='0'> " +
					   "<tr><td rowspan='3' align='left' valign='top' width='42'><img src='images/Mascot_Help.gif' align='absmiddle'></td> " +
					   	   "<td background='images/HelpBubble_Top.png' height='26' align='center' valign='top' style='padding-top:9px'><span class='helpTableText'><strong>Help Tip...</strong></span></td></tr> " +
					   	   "<td width='290' background='images/HelpBubble_Expander.png' style='padding-left:14px;padding-right:8px'><span class='helpTableText'>"+msg+"</span></td> " +
					   "</tr> " +
					   "<tr><td align='left' valign='top' height='20'><img src='images/HelpBubble_Bottom.png'></td></tr> " +
					   "</table>";		
		}		
									
    if ((allSupport)||(elementbyidSupport)) 
		{
		helpDiv.innerHTML = contents
    	}
    else
		{ 
      	helpDiv.document.open();
      	helpDiv.document.write(contents);
      	helpDiv.document.close();
    	}
}

	
function GetOffset(helpDiv, which) 
{
	var amount = helpDiv["offset" + which] ;

  	if (which == "Top")
    	amount += helpDiv.offsetHeight;
  	helpDiv = helpDiv.offsetParent;

  	while (helpDiv != null) 
		{
    	amount += helpDiv["offset" + which];
    	helpDiv = helpDiv.offsetParent;
  		}
	return amount;
}

// End of dynamic help functions
//*******************************************	

function TableRuler() 
{
// Highlight rows in tables.
  if (document.getElementById && document.createTextNode) 
  	{
    var tables=document.getElementsByTagName('table');
    for (var i=0; i < tables.length; i++)
    	{
      	if(tables[i].className == 'ruler') 
			{
        	var trs=tables[i].getElementsByTagName('tr');
        	for(var j=0; j < trs.length; j++)
        		{
          		if ((trs[j].parentNode.nodeName == 'TBODY') && (trs[j].className != 'NoRuler'))
					{
            		trs[j].onmouseover=function()
						{
						this.className='ruled';
						return false
						}
           			trs[j].onmouseout=function()
						{
						this.className='';
						return false
						}
          			}
        		}
      		}
   		}
  	}
}
 	
//*******************************************	
		
function CheckSizes()
{
// Hack as TextArea does not support maxlength
  var TextArea = document.all.tags("TextArea");
  for (var i = 0; i < TextArea.length; i++) 
  	{
       var max = TextArea[i].maxLength;
       if (max && TextArea[i].value.length > max) 
		{
         	alert(TextArea[i].name + " cannot be greater than " + max + " characters.");
         	TextArea[i].focus();
         	return false;
       	}
     	}
     return true;
   }		

//*******************************************	
// Text Counter Functions - 1st one uses a field, 2nd 1 uses innerText

function TextCounter(field,counterField,maxLimit)
{
// Check length of text area.
if (field.value.length > maxLimit) // if too long...trim it!
	{
	field.value = field.value.substring(0, maxLimit);
	}
else // otherwise, update 'characters left' counter
	{
	counterField.value = maxLimit - field.value.length;
	}
}	

function TextCounterInner(field,counterField)
{
// Check length of text area.
if (field.value.length > field.maxLength) // if too long...trim it!
	{
	field.value = field.value.substring(0, field.maxLength);
	}
else // otherwise, update 'characters left' counter
	{
	counterField.innerText = field.maxLength - field.value.length;
	}
}	

//*******************************************	
// Define a list of acceptable characters for use in the CheckValidCharacters function.
var loginCharList = new RegExp(/[^a-zA-Z0-9@\_\ \-\'\.]/);
var passwordCharList = new RegExp(/[^a-zA-Z0-9\!\-\@\$\_\.]/);
var emailCharList = new RegExp(/[^a-zA-Z0-9@\_\-\'\&\.]/);
var webCharList = new RegExp(/[^a-zA-Z0-9@\_\-\%\?\+\'\.\:\/]/);
var phoneCharList = new RegExp(/[^0-9\-\+\ \()]/);
var mobileCharList = new RegExp(/[^0-9\+\ ]/);
var addressCharList = new RegExp(/[^a-zA-Z0-9\#()\,\/\-\.\'\ \r\n]/);
var identifierCharList = new RegExp(/[^a-zA-Z0-9\-]/);
var nameCharList = new RegExp(/[^a-zA-Z0-9\-\ \']/);
var specialCharList = new RegExp(/[^a-zA-Z0-9!@&()\-\:\.\,\#\'\"\xb4\%\+\?\$\ \[\]\/]/);
var adminCharList = new RegExp(/[^a-zA-Z0-9!@&()\-\:\.\,\#\'\%\"\xb4\ \[\]\/]/);
var fileCharList = new RegExp(/[^a-zA-Z0-9()\-\:\.\,\_\\\'\"\ \[\]\/]/);
var alphaCharList =  new RegExp(/[^a-zA-Z]/);
var numericCharList = new RegExp(/[^0-9.]/);
var alphaNumericCharList =  new RegExp(/[^a-zA-Z0-9]/);
var descriptionCharList = new RegExp(/[^a-zA-Z0-9\!@$%&*()\_\+\-\:\./?,;\x60\xb4\"\'\<\>\ \r\n]/);
var dobCharList = new RegExp(/[^0-9\/]/);
var bankAccountNumberList = new RegExp(/[^0-9\-\ ]/);
var reportTagCharList = new RegExp(/[^a-zA-Z0-9\_]/);

function CheckValidCharacters(thisField, fieldDisplayName, thisCharList)
{
	// Firstly remove any excess white space (eg. "My  Name is   Simon  ")
	RemoveXSWhiteSpace(thisField);

	// Then loop over the field and remove any bad characters.
 	for (index = 0; index <= thisField.value.length; index++)
		{
		thisField.value = thisField.value.replace(thisCharList,'');
		}
		
	// Cheats way - but run through it a 2nd time, as haven't thought of a better way to ensure all 
	// invalid chars are removed and the length of the field value is still appropriate after removal.
 	for (index = 0; index <= thisField.value.length; index++)
		{
		thisField.value = thisField.value.replace(thisCharList,'');
		}				
	
//Check the acceptable character list.
//if (thisField.value.match(thisCharList))
//	{
//	alert("Invalid Characters for Field Type:\n\nYou appear to have used some invalid characters in the ''" +thisFieldName+ "'' field.\n\nPlease remove any non-standard characters (eg. `~^<>;{ }) or try re-typing them.");
//	thisField.focus();
//	return false;
//	}
//else
//	{
//	return true;
//	}
}

//*******************************************	

function CheckValidValueCharacters(thisValue, thisFieldName, thisCharList)
{
RemoveXSValueWhiteSpace(thisValue);

//Check the acceptable character list.
if (thisValue.match(thisCharList))
	{
	alert("Invalid Characters for Field Type:\n\nInvalid characters in the ''" +thisFieldName+ "'' field.\n\nPlease remove any non-standard characters (eg. `~^<>;{ }) or try re-typing them.");
	//thisField.focus();
	return false;
	}
else
	{
	return true;
	}
}

//*******************************************	

function RemoveXSWhiteSpace(item)
{ //Remove excess white space (ie. trailing/leading)
  var tmp = "";
  var itemLength = item.value.length;
  var itemLengthMinus1 = item.value.length - 1;
  for (index = 0; index < itemLength; index++)
  {
    if (item.value.charAt(index) != ' ')
    {
      tmp += item.value.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.value.charAt(index+1) != ' ' && index != itemLengthMinus1)
        {
          tmp += item.value.charAt(index);
        }
      }
    }
  }
  item.value = tmp;
}

//*******************************************	

function RemoveXSValueWhiteSpace(item)
{ //Remove excess white space (ie. trailing/leading)
  var tmp = "";
  var itemLength = item.length;
  var itemLengthMinus1 = item.length - 1;
  for (index = 0; index < itemLength; index++)
  {
    if (item.charAt(index) != ' ')
    {
      tmp += item.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.charAt(index+1) != ' ' && index != itemLengthMinus1)
        {
          tmp += item.charAt(index);
        }
      }
    }
  }
  item = tmp;
}

//*******************************************	
// Check for a valid email address.
function IsEmailAddr(email)
{  
	if ((email == null) || (email.length == 0))  // Return false if no email address.
		{
		return false;
		}
	else
		{
		var goodEmail = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
		var badEmail = new RegExp(/[\.]+[\.]/);  //ie. two .. in a row.
		
		if (badEmail.test(email))
			return false;
			
		else if (goodEmail.test(email))
			return true;
		}
}
//*******************************************	

// Check selected date for validity (eg. 29/02/2006 is not valid, unless a leap year).
// Requires form name and each fields prefix (eg. birthDate, birthMonth, birthYear - where "birth" is the prefix).
// If "fieldPrefix" has no value, then it is assumed that "fieldValue" is to be used instead (eg. for "DOB" field "dd/mm/yyyy")
function CheckValidDate(formName, fieldPrefix, fieldValue)
{
	var checkstr = "0123456789";
	var separator = "/";

	if (fieldPrefix == '')
		{ // Then this is a single field being validated (eg. DOB)
		var dateArray = fieldValue.split("/");
		if (dateArray.length < 3)
			{ // Then no separator split (ie. "/") found, so invalid date.
			return false;	
			}
		else
			{
			var day = dateArray[0];
			var month = dateArray[1];
			var year = dateArray[2];
			if (year.length < 4)
				{ // Require 4 digit year
				return false;
				}
			}
		}
	else
		{ // Else this is a series of fields making up the date value to be validated.
		var day = eval("document." + formName + "." + fieldPrefix + "Day.value");
		var month = eval("document." + formName + "." + fieldPrefix + "Month.value");
		var year = eval("document." + formName + "." + fieldPrefix + "Year.value");
		}
		
	var leap = 0;
	var err = 0;
	var i;

   	err = 0;
   	/* year is wrong if year = 0 */
  	if (year == 0) { err = 20; }
	
   	/* Validation of month*/
   	if ((month < 1) || (month > 12)) { err = 21; }
   
   	/* Validation of day*/
   	if (day < 1) { err = 22; }   
   	/* Validation leap-year / february / day */
   	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) { leap = 1; }
   	if ((month == 2) && (leap == 1) && (day > 29)) { err = 23; }
   	if ((month == 2) && (leap != 1) && (day > 28)) { err = 24; }
   	/* Validation of other months */
   	if ((day > 31) && ((month == "1") || (month == "3") || (month == "5") || (month == "7") || (month == "8") || (month == "10") || (month == "12"))) 
		{ err = 25; }
   	if ((day > 30) && ((month == "4") || (month == "6") || (month == "9") || (month == "11"))) 
   		{ err = 26; }
   	/* if 0 is entered, no field selected */
   	if ((day == 0) && (month == 0) && (year == 0)) 
		{ err = 13; day = ""; month = ""; year = ""; separator = ""; }
   	/* if no error, write the completed date to Input-Field (e.g. 13/12/2001) */
   	if (err == 0) 
		{ return true; }  // All ok, date valid.
   	/* Error-message if err != 0 */
   	else 
		{ return false; }  // Something's invalid in the date.
}

//*******************************************

// Function to enable a control to already be active, which typically MSIE makes you click the object to activate it.
function CreateControl(spanID, objectID, clsid, width, height)
{
	var objectItem = document.getElementById(spanID);
  	
	objectItem.innerHTML = "<object id=" + objectID + " classid=" + clsid + " width=" + width + " height=" + height + "> ";
}

//*******************************************

function ChangeTabs(tabGroup,activeTab,numberOfTabs)
{
	// Establish which tabs to switch on/off ... firstly turning all active off...
	for (var i=1; i <= numberOfTabs; i++)
		{
		document.all[tabGroup + "Page" + i].style.visibility = "hidden";
		document.all[tabGroup + "Page" + i].style.display = "none";
		document.all[tabGroup + "Button" + i].src = "images/TabButton" + i + "_off.png";
		}
		
	// Then just turn the active one on...
	document.all[tabGroup + "Page" + activeTab].style.visibility = "visible";
	document.all[tabGroup + "Page" + activeTab].style.display = "block";
	// And set the activeTab form varialbe and change the respective tab button to the on version.
	document.all.selectedTab.value = activeTab;
	document.all[tabGroup + "Button" + activeTab].src = "images/TabButton" + activeTab + "_on.png";
}


