/*
    Common Functions (CommonFunctions.js)
    James Ritchie Carroll
    September 15, 2000
    August 20, 2002 - Updated AddTableRow to do autoinc for radio button names

    External Dependencies:
        None

    Consumer Variables:
        isIE                    - Variable is true if browser is Internet Explorer
        isIE30                  - Variable is true if browser is IE 3.0 or better
        isIE40                  - Variable is true if browser is IE 4.0 or better
        isIE50                  - Variable is true if browser is IE 5.0 or better
        isIE55                  - Variable is true if browser is IE 5.5 or better

    Consumer Functions:
        IEVersion               - Returns browser version for IE browsers; non IE browsers return 0.0
        DateDiff                - Returns the number of days between two dates
        GetJSDate               - Return date object from date string formatted as "dd/mm/yyyy"
        GetDisplayDate          - Return date string as "dd/mm/yyyy" from date object
        SelectedRadioItemValue  - Returns value of selected item a radio button set
        SelectedListItemValue   - Returns value of selected item in a select list
        SelectedListItemText    - Returns text of selected item in a select list
        SelectRadioItemValue    - Select the given radio item value
        SelectListItemValue     - Select the given list item value
        SelectListItemText      - Select the given list item text
        AddListItem             - Adds a new item to a select list
        AddUniqueListItemValue  - Adds a new item to a select list if "value" doesn't already exist
        AddUniqueListItemText   - Adds a new item to a select list if "text" doesn't already exist
        AddTableRow             - Clones the last row in a table
        PhysicalTop             - Physical top position of an element relative to the screen
        GetSubStr               - Returns desired sub string out of a delimited string
        zPadL                   - Pad number with zero to the left (less than 100)
*/

// Define common browser version constants
var ieVer = IEVersion();
var isIE = (ieVer != "0.0");
var isIE30 = (ieVer >= "3.0");
var isIE40 = (ieVer >= "4.0");
var isIE50 = (ieVer >= "5.0");
var isIE55 = (ieVer >= "5.5");

// Return the version of Internet Explorer; non IE browsers return 0.0
function IEVersion()
{
    var strAgt = navigator.userAgent.toLowerCase();
    var intIndex = strAgt.indexOf("msie");

    if (intIndex != -1)
    {
        return strAgt.substr(intIndex + 5, 3);
    }
    else
        return "0.0";
}

// Return the number of days between two dates
//      dtm1    first JavaScript date object            [required]
//      dtm2    second JavaScript date object           [required]
//
function DateDiff(dtm1, dtm2)
{
    return parseInt((Date.UTC(dtm1.getFullYear(), dtm1.getMonth(), dtm1.getDate()) -
        Date.UTC(dtm2.getFullYear(), dtm2.getMonth(), dtm2.getDate())) / 86400000);
}

// Return date object from date string formatted as "dd/mm/yyyy"
//
function GetJSDate(DateString)
{
    return new Date(DateString.substr(3, 2) + "/" + DateString.substr(0, 2) + "/" + DateString.substr(6));
}

// Return date string from date object
//
function GetDisplayDate(DateObject, Format)
{
    if (!Format) Format = "dd-mm-yyyy";

    if (Format == "mm-dd-yyyy" || Format == "mm/dd/yyyy")
        return MDYDisplayDate(DateObject);
    else
        return DMYDisplayDate(DateObject);
}

function MDYDisplayDate(DateObject)
{
    return zPadL(DateObject.getMonth() + 1) + "/" + zPadL(DateObject.getDate()) + "/" + DateObject.getFullYear();
}

function DMYDisplayDate(DateObject)
{
    return zPadL(DateObject.getDate()) + "/" + zPadL(DateObject.getMonth() + 1) + "/" + DateObject.getFullYear();
}

// Return selected value from an radio button set
//      radioBtn    object reference to radio button    [required]
//
function SelectedRadioItemValue(radioBtn)
{
    var x;

    if (radioBtn.length)
    {
        for (x = 0; x < radioBtn.length; x++)
        {
            if (radioBtn(x).checked)
                return radioBtn(x).value;
        }

        return "";
    }
    else if (radioBtn)
    {
        return radioBtn.value;
    }
    else
        return "";
}

// Return selected value from a select list
//      listBox     object reference to list box        [required]
//
function SelectedListItemValue(listBox)
{
    if (listBox)
    {
        if (listBox.selectedIndex > -1)
            return listBox.options(listBox.selectedIndex).value;
        else
            return "";
    }
    else
        return "";
}

// Return text of selected item in a select list
//      listBox     object reference to list box        [required]
//
function SelectedListItemText(listBox)
{
    if (listBox)
    {
        if (listBox.selectedIndex > -1)
            return listBox.options(listBox.selectedIndex).text;
        else
            return "";
    }
    else
        return "";
}

// Select the given radio item value
//      radioBtn    object reference to radio button    [required]
//      itemValue   value of item to find               [required]
//
function SelectRadioItemValue(radioBtn, itemValue)
{
    var x;

    if (radioBtn.length)
    {
        for (x = 0; x < radioBtn.length; x++)
        {
            radioBtn(x).checked = (radioBtn(x).value.toLowerCase() == itemValue.toLowerCase());
        }
    }
    else if (radioBtn)
    {
         radioBtn.checked = (radioBtn.value.toLowerCase() == itemValue.toLowerCase());
    }
}

// Select the given list item value
//      listBox     object reference to list box        [required]
//      itemValue   value of item to find               [required]
//
function SelectListItemValue(listBox, itemValue)
{
    var x;

    for (x = 0; x < listBox.options.length; x++)
    {
        listBox.options(x).selected = (listBox.options(x).value.toLowerCase() == itemValue.toLowerCase());
    }
}

// Select the given list item text
//      listBox     object reference to list box        [required]
//      itemValue   value of item to find               [required]
//
function SelectListItemText(listBox, itemValue)
{
    var x;

    for (x = 0; x < listBox.options.length; x++)
    {
        listBox.options(x).selected = (listBox.options(x).text.toLowerCase() == itemValue.toLowerCase());
    }
}

// Adds an item to select list
//      listBox     object reference to list box        [required]
//      itemValue   value of item to add to list box    [required]
//      itemText    text of item to add to list box     [required]
//      selected    flag to select item being added     [optional]
//      altDocObj   alternate document object           [optional]
//
function AddListItem(listBox, itemValue, itemText, selected, altDocObj)
{
    var objOption;

    if (altDocObj)
        objOption = altDocObj.createElement("OPTION");
    else
        objOption = document.createElement("OPTION");

    objOption.text = itemText;
    objOption.value = itemValue;
    objOption.selected = selected;

    // Cross-browser compensation
    if (typeof(listBox.add) != "object")
        listBox.add = listBox.appendChild;

    listBox.add(objOption);
}

// Add item to select list, but only if the value is unique
//      listBox     object reference to list box        [required]
//      itemValue   value of item to add to list box    [required]
//      itemText    text of item to add to list box     [required]
//      selected    flag to select item being added     [optional]
//      altDocObj   alternate document object           [optional]
//
function AddUniqueListItemValue(listBox, itemValue, itemText, selected, altDocObj)
{
    var flgFound = false;
    var x;

    for (x = 0; x < listBox.options.length; x++)
    {
        if (listBox.options(x).value.toLowerCase() == itemValue.toLowerCase())
        {
            // Select list item if it is already in the list
            listBox.options(x).selected = selected;
            flgFound = true;
            break;
        }
    }

    if (!flgFound)
        AddListItem(listBox, itemValue, itemText, selected, altDocObj);
}

// Add item to select list, but only if the text is unique
//      listBox     object reference to list box        [required]
//      itemValue   value of item to add to list box    [required]
//      itemText    text of item to add to list box     [required]
//      selected    flag to select item being added     [optional]
//      altDocObj   alternate document object           [optional]
//
function AddUniqueListItemText(listBox, itemValue, itemText, selected, altDocObj)
{
    var flgFound = false;
    var x;

    for (x = 0; x < listBox.options.length; x++)
    {
        if (listBox.options(x).text.toLowerCase() == itemText.toLowerCase())
        {
            // Select list item if it is already in the list
            listBox.options(x).selected = selected;
            flgFound = true;
            break;
        }
    }

    if (!flgFound)
        AddListItem(listBox, itemValue, itemText, selected, altDocObj);
}

// Calculate the physical top position of an element relative to the screen
//      elem    object reference of element to calculate position for   [required]
//
function PhysicalTop(elem)
{
    var objElement = elem;
    var intTop = objElement.offsetTop;

    while (objElement.offsetParent.tagName != "BODY")
    {
        objElement = objElement.offsetParent;
        intTop += objElement.offsetTop;
    }

    return intTop;
}

// Get desired sub string out of a delimited string
//      str         delimited string    [required]
//      itemNum     sub string index    [required]
//      delimiter   item delimiter      [required]
//
function GetSubStr(str, itemNum, delimiter)
{
    var intStart;
    var intStop;

    if (str.indexOf(delimiter) > -1)
    {
        intStart = (itemNum > 1 ? GetDelimiterPos(str, itemNum - 1, delimiter) + 1 : 0);
        intStop = GetDelimiterPos(str, itemNum, delimiter);
        if (intStop < 0) intStop = str.length + 1;

        return str.substring(intStart, intStop);
    }
    else
    {
        if (itemNum == 1)
            return str;
        else
            return "";
    }
}

// Get position of desired delimiter out of a delimited string
//      str         delimited string    [required]
//      itemNum     sub string index    [required]
//      delimiter   item delimiter      [required]
//
function GetDelimiterPos(str, itemNum, delimiter)
{
    var intDelim = 1;
    var intPos;

    intPos = str.indexOf(delimiter)

    while (intPos > -1 && intDelim != itemNum)
    {
        intPos = str.indexOf(delimiter, intPos + 1);
        intDelim++;
    }

    return intPos;
}

// Pad number with zero to the left (less than 100)
//      nVal        value to be padded  [required]
//
function zPadL(nVal)
{
    var strVal = nVal.toString();

    if (strVal.length < 2)
        return "0" + strVal;
    else
        return strVal;
}

// Clones the last row in a table
//      TableName   Table identifier    [required]
//
function AddTableRow(TableName)
{
    var objTable = eval("document.all." + TableName);
    var objLastRow = objTable.rows(objTable.rows.length - 1);
    var objNewRow = objTable.insertRow();
    var objLastCell;
    var objNewCell;
    var objFocus;
    var objRetFocus;
    var strInnerHTML;
    var intIncSPos;
    var intIncEPos;
    var intIncVal;
    var x;

    for (x = 0; x < objLastRow.cells.length; x++)
    {
        objLastCell = objLastRow.cells(x);
        objNewCell = objNewRow.insertCell();

        // Get inner HTML of previous cell
        strInnerHTML = objLastCell.innerHTML;

		// Find autoinc start marker
		intIncSPos = strInnerHTML.indexOf("_INC_");

		while (intIncSPos > -1)
		{
			// Find autoinc stop marker
			intIncEPos = strInnerHTML.indexOf("_X", intIncSPos + 5);

			if (intIncEPos > -1)
			{
				// Increment value to create uniquely named radio button set per row
				intIncVal = parseInt(strInnerHTML.substring(intIncSPos + 5, intIncEPos)) + 1;
				strInnerHTML = strInnerHTML.substring(0, intIncSPos + 5) + intIncVal + strInnerHTML.substr(intIncEPos);
			}

			// Find next autoinc start marker
			intIncSPos = strInnerHTML.indexOf("_INC_", intIncSPos + 5);
		}

        // Clone cell attributes from previous row
        objNewCell.align = objLastCell.align;
        objNewCell.bgcolor = objLastCell.bgcolor;
        objNewCell.colspan = objLastCell.colspan;
        objNewCell.height = objLastCell.height;
        objNewCell.innerHTML = strInnerHTML;
        objNewCell.nowrap = objLastCell.nowrap;
        objNewCell.rowspan = objLastCell.rowspan;
        objNewCell.width = objLastCell.width;

		// Clear data fields in table cell
		objRetFocus = ClearFields(objNewCell);
		if (!objFocus) objFocus = objRetFocus;
    }

    if (objFocus) objFocus.focus();
}

function ClearFields(objRoot)
{
    var objNode;
    var objFocus;
    var objRetFocus;
    var x;
    var y;

	for (x = 0; x < objRoot.childNodes.length; x++)
	{
		objNode = objRoot.childNodes(x);

		if (objNode.tagName == "INPUT" || objNode.tagName == "SELECT" || objNode.tagName == "TEXTAREA")
		{
			if (!objFocus && objNode.type != "hidden") objFocus = objNode;

			// Clear out any data and/or selections to show blank data fields
			switch (objNode.tagName)
			{
				case "INPUT":
					switch (objNode.type)
					{
						case "checkbox":
						case "radio":
							objNode.checked = false;
							break;
						default:
							objNode.value = "";
							break;
					}
					break;
				case "SELECT":
					for (y = 0; y < objNode.options.length; y++)
						objNode.options(y).selected = false;
					break;
				case "TEXTAREA":
					objNode.value = "";
					break;
			}
		}
		else if(objNode.childNodes.length)
		{
			// Clear fields in object's children
			objRetFocus = ClearFields(objNode);
			if (!objFocus) objFocus = objRetFocus;
		}
	}

	return objFocus;
}