function aim_OnBodyLoad()
{
	// Called on body load
	var oForm = document.forms[0];
	for (var i=0; i < oForm.length; i++)
	{
		if (typeof(oForm[i].getAttribute("TargetFieldName")) == "string")
		{
			LoadDropdown(oForm[i]);
		}
	}
}
function ValidateFields()
{
	var oForm = document.forms[0];
	var bError = false;
	var sValue = "", oId = null, sId = "", lastId = "", k = 0;
	for (var i=0; i < oForm.length; i++)
	{ 
		if (((oForm[i].getAttribute("IsRequired") == "yes") && IsBlank(oForm[i].value)) ||
			((oForm[i].getAttribute("IsEmail") == "yes") && !IsEmail(oForm[i].value)) ||
			((oForm[i].getAttribute("IsDate") == "yes") && !IsLocaleDate(oForm[i].value)) ||
			((oForm[i].getAttribute("IsNumber") == "yes") && isNaN(oForm[i].value)) ||
			((oForm[i].getAttribute("IsCompare") == "yes") && !IsCompare(oForm[i])) ||
			((oForm[i].getAttribute("IsRange") == "yes") && !IsRange(oForm[i])) ||
			((oForm[i].getAttribute("IsCustomValidation") == "yes") && !IsCustomValidation(oForm[i])) ||
			((oForm[i].getAttribute("IsPicker") == "yes") && ProcessSelected(oForm[i])))
		{
			MarkField(oForm[i]);
			bError = true;
		}
		/*if ((!bError) && (oForm[i].getAttribute("IsDate") == "yes"))
		{
			if (oForm[i].value != "")
			{
				oForm[i].value = oForm[i].value; // FormatLocaleDate(oForm[i].value);
			}
		}
		*/
		if ((oForm[i].getAttribute("IsValDate") == "yes") && IsValDate(oForm[i]))
		{
		    MarkField(oForm[i]);
		    return false;
		}
		if (String(oForm[i].id).indexOf("_cb") != -1)
		{
			sId = extractData(oForm[i].id,"_");
			if (sId != lastId && k > 0)
			{
				if (sValue == "")
					CleanData(oId, oForm);
				else
					sValue = "";
				k = 0;
			}
			oId = document.getElementById(oForm[i].id); 
			if(oId.checked == true)
				sValue += oForm[i].value;
			lastId = sId;
			k++;
		}
	}
	if (bError)
	{
		window.open(sFullAppPath + "Framework/ContentManagement/frmModal.aspx?form=" + encodeURIComponent(sFullAppPath + "Framework/Utils/MessageBox.aspx?type=message&token=err_FieldValidation"),"","width=400px,height=200px,left="+((screen.width -400) / 2)+ ",top="+ (screen.height - 200) / 2 + ",status=0,menubar=0,toolbar=0,scrollbars=0,resizable=0");
		return false;
	}
	if (sValue == "" && oId != null)
		CleanData(oId, oForm);
	return true;
}
function extractData(str, sExp)
{
	var iPos = str.indexOf(sExp,5);
	return str.substring(0,iPos);
}
function CleanData(oId, oForm)
{
	if (typeof(oId) == "object")
	{
		oId.value = ""; 
		oId.style.visibility = "hidden";
		oId.checked = true;
		oForm.submit();
	}
}
function MarkField(oControl)
{
	oControl.style.backgroundColor = "#FFFF99";
}
function IsBlank(sValue)
{
	for (var i = 0; i < sValue.length; i++)
	{
		var c = sValue.charAt(i);
		if (c != " " && c != "\n" && c != "\t" && c != "\r") return false;
	}
	return true;
}
function IsCompare(oElement)
{
	var sVlu = oElement.value; 
	var bRtrn = false;
	var sCmprVlu = null;
	var oMrkEl;
	if (oElement.getAttribute("IsCompareID"))
	{
		var sCmpEl = oElement.getAttribute("IsCompareID"); 
		oMrkEl = document.getElementById(sCmpEl); // in html, for FireFox, must have an "id=.." won't work with "name=.."
		sCmprVlu = oMrkEl.value;
	}
	if (sVlu == sCmprVlu)
		bRtrn = true;
	else
		MarkField(oMrkEl);
	return bRtrn;
}
function IsCustomValidation(oElement)
{
	// execute the script associated with the field
    // put result into an atribute (IsValid) since we cannot return a value when using execScript
	var bRtn = true;
	try
	{
	    var sFieldName = oElement.name;
	    var sCode = "Validate_" + sFieldName.replace(/\-/g, "_") + "()";
	    (window.eval || eval)(sCode, null);
		if ((document.getElementById(sFieldName).getAttribute("IsValid")) && (document.getElementById(sFieldName).getAttribute("IsValid") != "yes"))
			bRtn = false;
	}
	catch(e) {alert("Validation script error:\r\n" + e.name + ": " + e.message);};
	return bRtn;
}
function IsEmail(sValue)
{
	var bRetVal = false;
	if (sValue != "") 
	{
		var oRegExp = /^([\w-\']+\.?)*[\w-\']+@([\da-zA-z-]+\.)+[a-zA-z]{2,6}$/;
		bRetVal = oRegExp.test(sValue);
	}
	else
		bRetVal = true;
	return bRetVal;
}
function DatePicker(sControlName, startYear)
{
    var oControl = document.getElementById(sControlName);
    if (String(startYear) == "undefined")
		startYear = "";
	if (document.all)
	{
		var sNewDate = window.showModalDialog(sFullAppPath + "Framework/ContentManagement/frmModal.aspx?form=" + encodeURIComponent(sFullAppPath + "Framework/Utils/CalendarPopUp.aspx?startYear=" + startYear + "&textbox=" + sControlName + "&date=" + oControl.value),null,"dialogHeight:340px;dialogWidth:260px;center:yes;help:no;resizable:no;status:no;scroll:no;");
		if (sNewDate != null)
		{
			oControl.value = sNewDate; //FormatLocaleDate(sNewDate);
		}
	}
	else
	{
		var sUrl = sFullAppPath + "Framework/Utils/CalendarPopUp.aspx?startYear=" + startYear + "&textbox=" + sControlName + "&date=" + getValidatedDate(oControl.value);
		var sFeatures = "width=260px,height=340px,left="+((screen.width - 360) / 2)+ ",top="+ (screen.height - 330) / 2 + ",status=0,menubar=0,toolbar=0,scrollbars=1,resizable=1";
		var oWin = window.open(sUrl,"myDate",sFeatures);
	}
}
// new version that works with modal window.
function DatePicker1(sControlName, startYear)
{
    var oControl = document.getElementById(sControlName);
    if (String(startYear) == "undefined")
		startYear = "";
	if (document.all)
	{
		var sNewDate = window.showModalDialog(sFullAppPath + "Framework/ContentManagement/frmModal.aspx?form=" + encodeURIComponent(sFullAppPath + "Framework/Utils/CalendarPopUp.aspx?startYear=" + startYear + "&textbox=" + sControlName + "&date=" + oControl.value), null, "dialogHeight:340px;dialogWidth:260px;center:yes;help:no;resizable:no;status:no;scroll:no;");
		if (sNewDate != null)
		{
			oControl.value = sNewDate; //FormatLocaleDate(sNewDate);
		}
	}
	else
	{
		var sUrl = "Framework/Utils/CalendarPopUp.aspx?startYear=" + startYear + "&textbox=" + sControlName + "&date=" + getValidatedDate(oControl.value);
		//var sFeatures = "width=260px,height=340px,left="+((screen.width - 360) / 2)+ ",top="+ (screen.height - 330) / 2 + ",status=0,menubar=0,toolbar=0,scrollbars=1,resizable=1";
		OpenModalWindow(sUrl, false, 340, 260, "myDate");
	}
}
function getValidatedDate(dStr)
{
	var bRetVal = null;
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	var re = new RegExp(datePat);
	if (re.test(dStr))
		bRetVal = dStr;
	return bRetVal;
}
function IsRange(oElement)
{
	var sStart = "";
	var sEnd = "";
	if (oElement.getAttribute("IsRangeStartID"))
	{
		var oStartElement = document.getElementById(oElement.getAttribute("IsRangeStartID"));
		sStart = oStartElement.value; //ISODate(oStartElement.value);
	}
	sEnd = oElement.value; //ISODate(oElement.value);
	if (sStart > sEnd)
		return false;
	return true;
}

function ProcessSelected(oElem)
{
	if(oElem != null)
	{
		var oTarget = document.getElementById(oElem.getAttribute("TargetField"));
		var optionList = oElem.options;
		var data = "";
		var len = optionList.length;
		for(i=0; i<len; i++){
			data += optionList.item(i).value + ",";
		}
		oTarget.value = data;
    }
}

var platformMoz = (document.implementation && document.implementation.createDocument);
var platformIE6 = (!platformMoz && document.getElementById && window.ActiveXObject);
var docXML, docXSL, sXMLFile, sXSLTFile, oTarget, cache, processor;

// Asynchronous load of dropdown boxes (StateProv/City)
function LoadDropdown(oSource)
{
	try {
		var sTableName = oSource.getAttribute("LoadTableName");
		oTarget = document.getElementById(oSource.getAttribute("TargetFieldName"));
		var sFilterID = oSource.value;
		if (sFilterID == "")
			sFilterID = oSource.getAttribute("Selected");
		else
		{
			var iLoc = sFilterID.lastIndexOf("_");
			if (iLoc != 0)
			{
				var sFld = sFilterID.substring(0,iLoc);
				var oEl = document.getElementById(sFld);
				var oCC = document.getElementById(oSource.id+"_CurrencyCode");
				if (oCC && oEl)
				{
					oCC.value = oEl.value;
				}
			}
		}	
		if (sFilterID == null) // avoid firefox show empty error
			return;
		sXMLFile = sFullAppPath + "Framework/Utils/ReturnXMLStream.aspx?Type=combo&TableName=" + sTableName + "&FilterID=" + sFilterID;
		sXSLTFile = sFullAppPath + "Framework/Utils/Templates/ReturnOptionElements.xsl";
		
		LoadData();
	}
	catch(e) {}	
}
// Asynchronous load of nav tree for div
function LoadTree(oSource)
{
    var postfix = oSource.getAttribute("postfix");
	var sFilterID = (postfix).substr(1);
	var sParam = "&"; 
	oTarget = document.getElementById("d" + oSource.id + postfix); 
	
	if (sPageType == "alias")
	{ 	
	    sParam += "CMID=" + sFilterID;	   
	}
	else
	{
	    sParam += "MAOID=" + sFilterID;
	}
	var sParameter = oTarget.getAttribute("parameter");
	if (sParameter == 1 )
	{
	    sParam += "&IsDivTree=1";
	}
	
	sXMLFile = sFullAppPath + "Framework/Utils/ReturnXMLStream.aspx?Type=tree" + sParam;
	sXSLTFile = sFullAppPath + "Framework/Utils/Templates/ReturnTreeDiv.xsl";
	
	LoadData();
}
// Loads data on demand .. works for IE and Firefox
// platformMoz:  www.mozilla.org/projects/xslt/js-interface.html
// platformIE6:  www.perfectxml.com/articles/xml/XSLTInMSXML.asp
function LoadData() 
{
	if (platformMoz)
	{
		docXML = document.implementation.createDocument("", "", null);;
		docXSL = document.implementation.createDocument("", "", null);;
	
		docXML.async = false;
		docXSL.async = false;
		
		docXML.addEventListener("load", DoLoadXSL, false);
		docXML.load(sXMLFile);
	}
	else if (platformIE6)
	{
		//docXML = new ActiveXObject("MSXML2.DOMDocument"); 
		docXML = xmlDoc_Get();
		docXSL = new ActiveXObject("MSXML2.FreeThreadedDOMDocument"); 

		docXML.async = false;
		docXSL.async = false;

		docXML.load(sXMLFile);
		docXSL.load(sXSLTFile);

		DoTransform();
	}
}
function DoLoadXSL()
{
	docXSL.addEventListener("load", DoTransform, false);
	docXSL.load(sXSLTFile);
}
function DoTransform() 
{
	var sParameter = oTarget.getAttribute("selected");
	if ( (sParameter == null) || (sParameter == ""))
	{
		sParameter = oTarget.getAttribute("parameter")
	}
    var sWrapWidth = document.getElementById("iUserWrapWidth");
	if (platformMoz)
	{
		processor = new XSLTProcessor();
		processor.importStylesheet(docXSL);
		
		if (sWrapWidth)
		    processor.setParameter(null,"sWrapWidth", sWrapWidth.value);
 
		if ((sParameter != null) && (sParameter != ""))
		{
			processor.setParameter(null, "Parameter", sParameter);
		}

		var fragment = processor.transformToFragment(docXML, document);
/*
		while (oTarget.hasChildNodes())
		{
		    var pos = (oTarget.childNodes[0].innerHTML).indexOf("Loading ..."); 
			oTarget.removeChild(oTarget.childNodes[0]);
			if (pos != -1)
			    break;
        }
		oTarget.appendChild(fragment); 
		*/
		if (oTarget.hasChildNodes())
		{
		    oTarget.replaceChild(fragment,oTarget.childNodes[0]);
		}
		else
		    oTarget.appendChild(fragment);
	}
	else if (platformIE6)
	{
		cache = new ActiveXObject("Msxml2.XSLTemplate");
		cache.stylesheet = docXSL;

		processor = cache.createProcessor();
		processor.input = docXML;
		if ((sParameter != null) && (sParameter != ""))
		{
			processor.addParameter("Parameter", sParameter);
		}
		if (sWrapWidth)
		    processor.addParameter("sWrapWidth", sWrapWidth.value);
		processor.transform();
        var sOutput = processor.output;
        
		// Remove backwards else you get values flashing in the combo
        if (sPageType == "alias")
	    { 
             oTarget.firstChild.innerHTML = sOutput;
             return;
	    }
	    else
	    {
		    while (oTarget.hasChildNodes())
		    {
			    oTarget.removeChild(oTarget.lastChild);
            }
        }
		
		if (sOutput.substr(0,7) == "<option")
		{
			var iStart = 0, iLength = 0;
			var aOptions = sOutput.split("\r\n");
			var oElem = null;
			for (var i=0; i<aOptions.length-1; i++)
			{
				iStart = aOptions[i].indexOf(">") + 1;
				iLength = aOptions[i].lastIndexOf("<") - iStart;
				oElem = document.createElement(aOptions[i].substr(0,iStart));
				oTarget.appendChild(oElem);
				oElem.text = aOptions[i].substr(iStart,iLength);
			}
			
			oTarget.style.width = "0px";
			oTarget.style.width = "auto";
		}
		else
		{
		    oTarget.innerHTML = sOutput;
		}
	}
}
function IsLocaleTime(sTime)
{
    var bRV = true;
    if (sTime.length != 0)
    {
        try {
            var oRE = /^([0-1]?[0-9]|2[0-3])[:][0-5][0-9] ?(AM|am|PM|pm)?$/;
            bRV = oRE.test(sTime);
         }
	     catch(e) { bRV = false; }
	}
	return(bRV);
}
function IsLocaleDate(sDate)
{
    var bRV = true;
	if (sDate.length != 0)
	{
	    try { // validate a UK date dd/mm/yyyy
	        var oRE = /^(?:(?:0?[1-9]|1\d|2[0-8])(\/|-)(?:0?[1-9]|1[0-2]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:31(\/|-)(?:0?[13578]|1[02]))|(?:(?:29|30)(\/|-)(?:0?[1,3-9]|1[0-2])))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(29(\/|-)0?2)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/;
            // validate a US date mm/dd/yyyy    	        
	        //var oRE = /^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/;
            bRV = oRE.test(sDate);
         }
	     catch(e) { bRV = false; }
	}
	return(bRV);
}
function IsValDate(oDate)
{ 
    var bRV = false;
    if (oDate)
    {
        try {
            // hardcode for UK date dd/mm/yyyy format
            var sDefaultDate = (oDate.getAttribute("DefaultDate")).split("/");
            var sInputDate = (oDate.value).split("/");
            var defaultDate = sDefaultDate[2] + sDefaultDate[1] + sDefaultDate[0];
            var inputDate = sInputDate[2] + sInputDate[1] + sInputDate[0];
           
            if (inputDate < defaultDate)
            {
                alert("You entered an invalid date. Please enter a date after " + oDate.getAttribute("DefaultDate") + ".");
                bRV = true;
            }
        }
        catch(e) { bRV = true; }
    }
    return(bRV);
}
function xmlDoc_Get()
{	
	var progIDs = [ "Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "Msxml2.DOMDocument" ];
    for (var i = 0; i < progIDs.length; i++) 
    {
        try {
            var xmlDOM = new ActiveXObject(progIDs[i]);
            return xmlDOM;
        }
        catch (ex) {}
    }
    return null;
}

