/*
'=====================================================
' Project:      CustomWebControls
' Programmer:   Derek Souers
' File:         lib.js
' Description:  
' Last Updated: 08/11/10
'=====================================================
*/

var ie4 = document.all;
var ns6 = document.getElementById && !document.all;

if (ie4 !== null)
    ie4 = true;

if (ns6 !== null)
    ns6 = false;

var lastScrollPosition = 0;

//----------------------------------------------------
//DaintyDate by CustomControlFreak on 02/20/07
//Further Modifications by Derek Souers on 07/13/07

function DateControl(divDays, divHeader, instanceName, showWeekNumber, y, m, d, displayDefault, dateFormat, toggleCalendar, upImage, downImage, isNull) {

    var today = new Date();
    var SelectedDate = new Date();

    var isDateNull = isNull;

    SelectedDate.setFullYear(y, m - 1, d);

    // render the selected date or default date via ASP.NET
    var selectedDay = SelectedDate.getDate();
    var selectedMonth = SelectedDate.getMonth(); // Jan = 0 | Dec = 11
    var selectedYear = SelectedDate.getFullYear();

    var displayMonth = SelectedDate.getMonth(); // Jan = 0 | Dec = 11
    var displayYear = SelectedDate.getFullYear();

    var keepOpen = false;

    var dropDisplayYear = displayYear;

    // set the default selected date to null
    var selectedCell = null;

    this.keepCalendarOpen = function() {
        keepOpen = true;
    };

    // **drop downs**

    //Function by Peter-Paul Koch and Alex Tingle http://blog.firetree.net/2005/07/04/javascript-find-position"
    this.findPosX = function(obj) {
        var curLeft = 0;
        if (obj.offsetParent) {
            while (true) {
                curLeft += obj.offsetLeft;
                if (!obj.offsetParent) {
                    break;
                }
                obj = obj.offsetParent;
            }
        }
        else if (obj.x) {
            curLeft += obj.x;
        }
        return curLeft;
    };

    this.findPosY = function(obj) {
        var curTop = 0;
        if (obj.offsetParent) {
            while (true) {
                curTop += obj.offsetTop;
                if (!obj.offsetParent) {
                    break;
                }
                obj = obj.offsetParent;
            }
        }
        else if (obj.y) {
            curTop += obj.y;
        }
        return curTop;
    };

    this.exactMonth = function(month) {
        displayMonth = month;

        //Update the textbox
        if (autopostBack == "true")
            this.setSelectedDateToDisplayDate();

        this.renderDays();
        this.toggleMonthDrop();

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };

    this.exactYear = function(year) {
        displayYear = year;

        //Update the textbox
        if (autopostBack == "true")
            this.setSelectedDateToDisplayDate();

        this.renderDays();
        this.toggleYearDrop();

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };

    this.renderMonths = function() {
        var divMonths = document.getElementById('divMonths' + instanceName);
        var html = "<table width='100%' border=0 cellpadding=0 cellspacing=0>";


        for (var i = 0; i < 12; i++) {
            if (i == displayMonth) {
                html += "<tr><td align=center class='" + instanceName + "mOverHighlightHover' onClick='javascript:" + instanceName + "Class.exactMonth(" + i + ");'>" + months[i] + "</td></tr>";
            }
            else {
                html += "<tr><td align=center class='" + instanceName + "mOverHighlight' onmouseover=this.className='" + instanceName + "mOverHighlightHover' onmouseout=this.className='" + instanceName + "mOverHighlight'  onClick='javascript:" + instanceName + "Class.exactMonth(" + i + ");'>" + months[i] + "</td></tr>";
            }
        }

        html += "</table>";
        divMonths.innerHTML = html;
    };

    this.renderYears = function(direction) {
        var divYears = document.getElementById('divYears' + instanceName);
        var html = "<table width='100%' border=0 cellpadding=0 cellspacing=0>";
        var fromYear = dropDisplayYear - 6;
        var toYear = dropDisplayYear + 6;

        if (direction == 1) {
            fromYear--;
            toYear--;
            dropDisplayYear--;
        }
        else if (direction == -1) {
            fromYear++;
            toYear++;
            dropDisplayYear++;
        }

        html += "<tr><td align=center onmouseover='" + instanceName + "Class.renderYears(1)' style='cursor:pointer' height='10'><img src='" + upImage + "' onmouseover='" + instanceName + "Class.renderYears(1)' onmouseclick='" + instanceName + "Class.renderYears(1)'></td></tr>";

        for (var i = fromYear; i < toYear; i++) {
            if (i == displayYear) {
                html += "<tr><td align=center class='" + instanceName + "mOverHighlightHover' onClick='" + instanceName + "Class.exactYear(" + i + ")'>" + i + "</td></tr>";
            }
            else {
                html += "<tr><td align=center class='" + instanceName + "mOverHighlight' onmouseover=this.className='" + instanceName + "mOverHighlightHover' onmouseout=this.className='" + instanceName + "mOverHighlight' onClick='" + instanceName + "Class.exactYear(" + i + ")'>" + i + "</td></tr>";
            }
        }
        html += "<tr><td align=center onmouseover='" + instanceName + "Class.renderYears(-1)' style='cursor:pointer' height='10'><img src='" + downImage + "' onmouseover='" + instanceName + "Class.renderYears(-1)' onmouseclick='" + instanceName + "Class.renderYears(-1)'></td></tr>";
        html += "</table>";
        divYears.innerHTML = html;
    };

    this.renderMonths();

    this.toggleMonthDrop = function() {

        var divMonths = document.getElementById('divMonths' + instanceName);
        var divHeader = document.getElementById('divMonthSelect' + instanceName);
        divMonths.style.left = this.findPosX(divHeader) + 'px';
        divMonths.style.top = this.findPosY(divHeader) + 20 + 'px';

        if (divMonths.style.visibility == 'visible') {
            keepOpen = true;
        }

        divMonths.style.visibility = (divMonths.style.visibility == 'visible') ? 'hidden' : 'visible';

        this.renderMonths();
    };

    this.toggleYearDrop = function() {
        var divYears = document.getElementById('divYears' + instanceName);
        var divHeader = document.getElementById('divYearSelect' + instanceName);
        dropDisplayYear = displayYear;
        divYears.style.left = this.findPosX(divHeader) + 'px';
        divYears.style.top = this.findPosY(divHeader) + 20 + 'px';

        if (divYears.style.visibility == 'visible') {
            keepOpen = true;
        }

        divYears.style.visibility = (divYears.style.visibility == 'visible') ? 'hidden' : 'visible';

        this.renderYears(0);
    };


    //Select a new date
    this.selectDate = function(day) {
        //reset the cell if one has been selected
        if (selectedCell !== null) {
            selectedCell.className = instanceName + 'normalDayCell';
        }

        // assign the selected cell so it can be normalised upon new day selection
        selectedCell = document.getElementById('dayCell' + instanceName + day);
        selectedCell.className = instanceName + 'selectedDayCell';

        //set the the selection
        selectedDay = day;
        selectedMonth = displayMonth;
        selectedYear = displayYear;

        SelectedDate.setFullYear(selectedYear, selectedMonth, selectedDay);

        //only render to the textbox if the parsed date was valid
        if (!displayDefault) {
            this.setTextValue(SelectedDate);
        }

        //make sure its set for manual intervention through the calendar
        displayDefault = false;

        //Hide the calendar
        if (toggleCalendar) {
            var cal = document.getElementById('calendar' + instanceName);
            var divYears = document.getElementById('divYearSelect' + instanceName);
            var divMonths = document.getElementById('divMonthSelect' + instanceName);
            cal.style.visibility = 'hidden';
            divYears.visibility = 'hidden';
            divMonths.visibility = 'hidden';
        }
    };

    this.setNoneDate = function() {
        this.setTextValue(null);

        if (selectedCell !== null) {
            selectedCell.className = instanceName + 'normalDayCell';
        }

        this.toggleCalendarShow();

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };

    this.setTodayDate = function() {
        this.setTextValue(today);

        SelectededDay = today.getDate();
        SelectededMonth = displayMonth = today.getMonth();
        Selectededyear = displayYear = today.getFullYear();

        this.toggleCalendarShow();
        this.renderDays();
        this.selectDate(SelectededDay);

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };

    this.toggleCalendarShow = function() {

        var cal = document.getElementById('calendar' + instanceName);
        var divYears = document.getElementById('divYearSelect' + instanceName);
        var divMonths = document.getElementById('divMonthSelect' + instanceName);


        //has toggle been selected?
        if (toggleCalendar) {
            if (cal.style.visibility == 'visible') {
                cal.style.visibility = 'hidden';
                divYears.visibility = 'hidden';
                divMonths.visibility = 'hidden';
                keepOpen = false;
            } else {
                cal.style.visibility = 'visible';
                keepOpen = true;
            }
        }
    };

    this.setTextValue = function(date) {
        var txt = document.getElementById('txt' + instanceName);
        txt.value = this.format(dateFormat, date);
    };

    //the week day that the 1st falls on
    this.firstWeekDay = function(month, year) {
        var date = new Date();
        date.setFullYear(year, month, 1);

        return date.getDay();
    };

    // get the number of days in the month accounting for a leap year
    this.getDays = function(month, year) {
        // leap years only matter in February
        if (1 == month) {
            return ((0 === year % 4) && (0 !== (year % 100))) || (0 === year % 400) ? 29 : 28;
        }
        else {
            return daysInMonth[month];
        }
    };

    // sets the display to selected
    this.setSelectedDateToDisplayDate = function() {
        selectedYear = displayYear;
        selectedMonth = displayMonth;
        selectedDay = 1;

        SelectedDate.setFullYear(displayYear, displayMonth, 1);
        this.setTextValue(SelectedDate);
    }

    // The month has been reduced
    this.monthBack = function() {
        // if the month is january then set to December
        if (displayMonth === 0) {
            displayMonth = 11;
            displayYear--; // decrement the year
        }
        else {
            displayMonth--;
        }

        //Update the textbox
        if (autopostBack == "true")
            this.setSelectedDateToDisplayDate();

        //re-render the control
        this.renderDays();

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };


    // The month has been advanced
    this.monthForward = function() {
        // if the month is December then set to January
        if (displayMonth == 11) {
            displayMonth = 0;
            displayYear++; // Increment the year
        }
        else {
            displayMonth++;
        }

        //Update the textbox
        if (autopostBack == "true")
            this.setSelectedDateToDisplayDate();

        //re-render the control
        this.renderDays();

        if (autopostBack == "true")
            __doPostBack(instanceName, 'TextChanged'); //New
    };


    // render the days
    this.renderDays = function() {
        //TODO:includePastDays,includeFutureDays

        // get the number of days to render
        var numberOfDays = this.getDays(displayMonth, displayYear);
        var firstDayOfWeek = this.firstWeekDay(displayMonth, displayYear);

        // used for row control
        var leftCount = 1;
        // the html content builder to be assigned the control
        var content = "";
        // the preselected day table cell
        var preSelectedDayCell = null;
        // the preselected day
        var preSelectedDay = null;
        // the ordered week number
        var weekNumber = 1;

        //open the table
        content += '<table width="100%" cellspacing=0><tr><td>&nbsp;</td>';

        // render the remaining days for last month
        for (var j = 0; j < 7; j++) {
            content += '<td class="' + instanceName + 'dayMn">' + days[j] + '</td>';
        }

        // only render the a new row if last month has bled into this
        if (firstDayOfWeek > 0) {
            content += '<tr class="' + instanceName + 'dayMn">';
        }

        // get the last few days of last month in reverse
        var lastMonth = (displayMonth === 0) ? 11 : displayMonth - 1;

        var lastMonthDays = daysInMonth[lastMonth] - firstDayOfWeek + 1;

        var i = 0;

        //pad the days of last month
        for (i = 0; i < firstDayOfWeek; i++) {
            //onmouseover="window.status = displayMonth;return true;" onmouseout="window.status = '';return true;"
            if (i === 0) {
                if (showWeekNumber) {
                    content += '<td class="' + instanceName + 'weekNumber" >' + weekNumber++ + '</td>';
                }
                else {
                    content += '<td>&nbsp;</td>';
                }
            }
            content += '<td class="' + instanceName + 'dim">' + lastMonthDays++ + '</td>';
            leftCount++;
        }


        // loop through all the days of the display month
        for (i = 1; i <= numberOfDays; i++) {
            //Render the <TR> tag
            if (leftCount == 1) {
                content += '<tr class="' + instanceName + 'day">';

                if (showWeekNumber) {
                    content += '<td class="' + instanceName + 'weekNumber">' + weekNumber++ + '</td>';
                }
                else {
                    content += '<td>&nbsp;</td>';
                }
            }

            // add the day table cell and add the onClick javascript reference             
            content += "<td id='dayCell" + instanceName + i + "' class='" + instanceName + "normalDayCell' onClick='javascript:" + instanceName + "Class.selectDate(" + i + ");";

            if (autopostBack == "true")
                content += "__doPostBack(\"" + instanceName + "\",\"TextChanged\");"//New

            content += "'>" + i + "</td>";


            // register the selected day making sure the date isnt set to null
            if (selectedMonth == displayMonth && selectedYear == displayYear && selectedDay == i && !isDateNull) {
                preSelectedDayCell = 'dayCell' + instanceName + i;
                preSelectedDay = i;
            }

            // render the close <TR> tag
            if (leftCount == 7) {
                content += '<td>&nbsp;</td></tr>';
                leftCount = 1; //reset leftCount
            }
            else {
                leftCount++;
            }
        }

        // pad the remaining days of the month
        if (leftCount <= 7) {
            var nextMonthDays = 1;

            for (i = leftCount; i <= 7; i++) {
                // leave a space if the week number column is being displayed
                if (i == 1 && showWeekNumber) {
                    content += '<td class="' + instanceName + 'weekNumber">&nbsp;</td>';
                }
                else if (i == 1) {
                    content += '<td>&nbsp;</td>';
                }

                content += '<td class="' + instanceName + 'dim">' + nextMonthDays++ + '</td>';
                // render the close <TR> tag
                if (i == 7) {
                    content += '</tr>';
                }
            }
        }

        // close the table
        content += '</table>';

        // assemble the html to the div objects
        divDays.innerHTML = content;
        divHeader.innerHTML = "<div align=center ><table border=0 style='font-size:small;'><tr><td><div id='divMonthSelect" + instanceName + "' style='cursor:pointer;position:relative;' onClick='" + instanceName + "Class.toggleMonthDrop();'>" + months[displayMonth] + "</div></td><td><div onClick='" + instanceName + "Class.toggleYearDrop();' id='divYearSelect" + instanceName + "' style='position:relative;cursor:pointer;'>" + displayYear + "</div></td></tr></table></div>";

        // preselecct the day cell
        if (preSelectedDayCell !== null) {
            this.selectDate(preSelectedDay);

            if (!displayDefault) {
                this.setTextValue(SelectedDate);
            }
        }

        //only disable preselection on the first run
        displayDefault = false;
    };

    this.documentClick = function() {

        if (!keepOpen && toggleCalendar) {
            var cal = document.getElementById('calendar' + instanceName);
            var divYears = document.getElementById('divYears' + instanceName);
            var divMonths = document.getElementById('divMonths' + instanceName);
            cal.style.visibility = 'hidden';
            divYears.style.visibility = 'hidden';
            divMonths.style.visibility = 'hidden';
        }

        keepOpen = false;
    };


    if (document.layers) {
        window.captureEvents(Event.CLICK);
        window.onClick = this.documentClick;
    } else if (document.all && !document.getElementById) {
        document.onClick = this.documentClick;
    } else if (document.all) {
        document.attachEvent('onClick', this.documentClick);
    } else if (document.addEventListener) {
        document.addEventListener('click', this.documentClick, false);
    }

    //render this month when the page first loads
    return this;
}


String.prototype.zf = function(l) { return '0'.string(l - this.length) + this; };
String.prototype.string = function(l) { var s = '', i = 0; while (i++ < l) { s += this; } return s; };
Number.prototype.zf = function(l) { return this.toString().zf(l); };

// NOTE: switch statement complient with Microsoft .NET DateTime string parsing
// URL:http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx

// the date format prototype
DateControl.prototype.format = function(f, d) {
    if (!this.valueOf()) {
        return '&nbsp;';
    }
    // dont try and render null dates
    if (d !== null) {

        return f.replace(/(yyyy|mmmm|mmm|mm|m|dddd|ddd|dd|d|a\/p)/gi,
        function($1) {
            switch ($1.toLowerCase()) {
                //case 'oo':   return (d.getDate() % 10 == 1 && d.getDate() != 11 ? 'st' : (d.getDate() % 10 == 2 && d.getDate() != 12 ? 'nd' : (d.getDate() % 10 == 13 && d.getDate() != 1 ? 'rd' : 'th')));   
                case 'd': return d.getDate();                        // 1
                case 'dd': return d.getDate().zf(2);                  // 01
                case 'ddd': return fullDays[d.getDay()].substr(0, 3);  // Mon
                case 'dddd': return fullDays[d.getDay()];               // Monday
                case 'm': return (d.getMonth() + 1);                   // 1
                case 'mm': return (d.getMonth() + 1).zf(2);             // 01
                case 'mmm': return months[d.getMonth()].substr(0, 3);  // Jan
                case 'mmmm': return months[d.getMonth()];               // January
                case 'yyyy': return d.getFullYear();                    // 2000
            }
        }
      );
    }
    else { // return a blank string
        return "";
    }
};

//d -Represents the day of the month as a number from 1 through 31. 
//A single-digit day is formatted without a leading zero. 

//dd - Represents the day of the month as a number from 01 through 
//31. A single-digit day is formatted with a leading zero.

//ddd - Represents the abbreviated name of the day of the week as 
//defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames property.

//dddd - Represents the full name of the day of the week as
// defined in the current System.Globalization.DateTimeFormatInfo.DayNames property.

//M - Represents the month as a number from 1 through 12. 
//A single-digit month is formatted without a leading zero. 

//MM - Represents the month as a number from 01 through 12. 
//A single-digit month is formatted with a leading zero.

//MMM - Represents the abbreviated name of the month as defined in the current
// System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames property.

//MMMM -Represents the full name of the month as defined in the
// current System.Globalization.DateTimeFormatInfo.MonthNames property.


//----------------------------------------------------
//			*AutoCompleteDropDownList*
//----------------------------------------------------
function xOnKeyUp(key_event) {
    var lb = key_event.srcElement;

    var el = document.getElementById('div_' + lb.id);
    if (el) {
        if (key_event.keyCode == 8)//Backspace
        {
            key_event.returnValue = false;
            if (el.ToolTipText.length > 0) {
                el.ToolTipText = el.ToolTipText.substr(0, el.ToolTipText.length - 1);
            }

            el.innerText = el.ToolTipText + ' ';
            xFindItem(el.ToolTipText, lb);
        }

        if (key_event.keyCode == 27)//Escape
        {
            key_event.returnValue = false;

            el.ToolTipText = '';
            el.innerText = '';
            xFindItem(el.ToolTipText, lb);
        }

        if (key_event.keyCode == 9 || key_event.keyCode == 13)//Enter,tab
        {
            key_event.returnValue = true;
            if (lb.AutoPostBack == 'true') {
                lb.onchange();
            }
        }
    }
}

function xOnKeyPress(key_event) {
    var lb = key_event.srcElement;

    var el = document.getElementById('div_' + lb.id);
    if (el) {
        if ((key_event.keyCode != 9) && (key_event.keyCode != 13))//Enter,tab
        {
            el.ToolTipText = el.ToolTipText + String.fromCharCode(key_event.keyCode);
            el.innerText = el.ToolTipText + ' ';
            xFindItem(el.ToolTipText, lb);
        }
        key_event.returnValue = false;
    }
}

function xFindItem(s, lb) {
    s = s.toUpperCase();

    var slen = s.length;
    var lblen = lb.length;
    var lbo = lb.options;

    if (slen === 0 && lblen > 0) {
        lb.selectedIndex = 0;
        return;
    }

    for (i = 0; i < lblen; i++) {
        if (lbo[i].text.toUpperCase().substr(0, slen) == s) {
            lb.selectedIndex = i;
            break;
        }
    }
}

function xOnFocus(elm) {
    var el = document.getElementById('div_' + elm.id);
    if (!el) {
        var xdiv = document.createElement('DIV');
        xdiv.id = 'div_' + elm.id;
        xdiv.noWrap = true;
        xdiv.style.position = 'absolute';

        xdiv.ToolTipText = '';
        xdiv.style.color = elm.ToolTipForeColor;
        xdiv.style.width = elm.ToolTipInitialWidth;
        xdiv.style.padding = elm.ToolTipPadding;
        xdiv.style.display = (elm.ToolTipHide == 'false') ? 'inline' : 'none';
        xdiv.style.backgroundColor = elm.ToolTipBackColor;
        xdiv.style.borderColor = elm.ToolTipBorderColor;
        xdiv.style.borderStyle = elm.ToolTipBorderStyle;
        xdiv.style.borderWidth = elm.ToolTipBorderWidth;
        xdiv.style.fontFamily = elm.ToolTipFontFamily;
        xdiv.style.fontSize = elm.ToolTipFontSize;
        xdiv.style.fontWeight = elm.ToolTipFontBold;
        xdiv.style.zIndex = elm.ToolTipZIndex;

        if (document.documentElement && document.documentElement.scrollTop) {
            xdiv.style.top = document.documentElement.scrollTop + elm.getBoundingClientRect().top - parseInt(elm.ToolTipOffsetTop);
        }
        else {
            xdiv.style.top = document.body.scrollTop + elm.getBoundingClientRect().top - parseInt(elm.ToolTipOffsetTop);
        }
        if (document.documentElement && document.documentElement.scrollLeft) {
            xdiv.style.left = document.documentElement.scrollLeft + elm.getBoundingClientRect().left + parseInt(elm.ToolTipOffsetLeft);
        }
        else {
            xdiv.style.left = document.body.scrollLeft + elm.getBoundingClientRect().left + parseInt(elm.ToolTipOffsetLeft);
        }

        elm.insertAdjacentElement('afterEnd', xdiv);
    }
    else {
        if (document.documentElement && document.documentElement.scrollTop) {
            el.style.top = document.documentElement.scrollTop + elm.getBoundingClientRect().top - parseInt(elm.ToolTipOffsetTop);
        }
        else {
            el.style.top = document.body.scrollTop + elm.getBoundingClientRect().top - parseInt(elm.ToolTipOffsetTop);
        }
        if (document.documentElement && document.documentElement.scrollLeft) {
            el.style.left = document.documentElement.scrollLeft + elm.getBoundingClientRect().left + parseInt(elm.ToolTipOffsetLeft);
        }
        else {
            el.style.left = document.body.scrollLeft + elm.getBoundingClientRect().left + parseInt(elm.ToolTipOffsetLeft);
        }

        if (elm.ToolTipSaveText == 'false') {
            el.innerText = '';
            el.ToolTipText = '';
        }
        el.style.display = (elm.ToolTipHide == 'false') ? 'inline' : 'none';
    }
}

function xOnBlur(elm) {
    var el = document.getElementById('div_' + elm.id);
    if (el) {
        el.style.display = 'none';
    }
}


//----------------------------------------------------
//					*DataGrid*
//----------------------------------------------------
function AddTableHeader(tableName) {
    var table = document.getElementById(tableName);
    if (table !== null) {
        var head = document.createElement("THEAD");
        head.style.display = "table-header-group";
        head.appendChild(table.rows[0]);
        table.insertBefore(head, table.childNodes[0]);
    }
}

function findPosX(obj) {
    var curLeft = 0;
    if (obj.offsetParent) {
        while (true) {
            curLeft += obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    }
    else if (obj.x) {
        curLeft += obj.x;
    }
    return curLeft;
}


function findPosY(obj) {
    var curTop = 0;
    if (obj.offsetParent) {
        while (true) {
            curTop += obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    }
    else if (obj.y) {
        curTop += obj.y;
    }
    return curTop;
};


//----------------------------------------------------
//					*Misc*
//----------------------------------------------------
//EditItemListCtrl
function AdjustEditControlPosition(btn, div) {
    var el_btn = document.getElementById(btn);
    var el_div = document.getElementById(div);

    var test = findPosX(el_btn);

    el_div.x = (findPosX(el_btn) + 16);
    el_div.y = (findPosY(el_btn) + 16);
}

//Generic Prompt
function ConfirmPrompt(strField) {
    if (confirm(strField + 'Are you sure?') === true) {
        return true;
    }
    return false;
}

/*--------------------------
Validate Date Field script- By JavaScriptKit.com
For this script and 100s more, visit http://www.javascriptkit.com
This notice must stay intact for usage
Modified: by Derek Souers to support MM/DD/YY style as well
---------------------------*/
function checkDate(txt, allowEmpty) {
    //Basic check for format validity for standard and shortened year formats
    var validFormat = /^\d{2}\/\d{2}\/\d{4}$/;
    var validFormat2 = /^\d{2}\/\d{2}\/\d{2}$/;

    var returnVal = false;
    if (allowEmpty === true) {
        if (txt.value === '') {
            return true;
        }
        if (txt.value == '//') {
            txt.value = '';
            return true;
        }
    }
    // Adjust Year from 2digit to 4 digit
    if (validFormat2.test(txt.value)) {
        var d = new Date();
        var yr = String(d.getFullYear()).substring(0, 2);
        var monthfield = txt.value.split('/')[0];
        var dayfield = txt.value.split('/')[1];
        var yearfield = yr + txt.value.split('/')[2];
        txt.value = monthfield + '/' + dayfield + '/' + yearfield;
    }
    if (validFormat.test(txt.value)) {
        //Detailed check for valid date ranges
        var monthfield = txt.value.split('/')[0];
        var dayfield = txt.value.split('/')[1];
        var yearfield = txt.value.split('/')[2];
        var dayobj = new Date(yearfield, monthfield - 1, dayfield);
        if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
            txt.value = "";
        }
        else {
            returnVal = true;
        }
    }
    else {
        txt.value = "";
    }
    if (returnVal === false) {
        txt.select();
    }
    return returnVal;
}

function NumericSpinValueUp(container_id, maxVal, eventName) {
    var el = document.getElementById(container_id);
    if (el.value === null) {
        return;
    }
    if (el.value === '') {
        return;
    }
    if ((parseInt(el.value) + 1) <= maxVal) {
        el.value = parseInt(el.value) + 1;
    }
}

function NumericSpinValueDown(container_id, minVal, eventName) {
    var el = document.getElementById(container_id);
    if (el.value === null) {
        return;
    }
    if (el.value === '') {
        return;
    }
    if ((parseInt(el.value) - 1) >= minVal) {
        el.value = parseInt(el.value) - 1;
    }
}


//----------------------------------------------------
//			*NumericFilterTextBoxCtrl*
//----------------------------------------------------
// [dFilter] - A Numerical Input Mask for JavaScript
// Written By Dwayne Forehand - March 27th, 2003
// Please reuse & redistribute while keeping this notice.
//
// Further Additions by Derek Souers - July 17, 2008
var dFilterStep = 0;

function dFilterStrip(dFilterTemp, dFilterMask) {
    dFilterMask = replace(dFilterMask, '#', '');
    for (dFilterStep = 0; dFilterStep < dFilterMask.length++; dFilterStep++) {
        dFilterTemp = replace(dFilterTemp, dFilterMask.substring(dFilterStep, dFilterStep + 1), '');
    }
    return dFilterTemp;
}


function dFilterMax(dFilterMask) {
    var dFilterTemp = dFilterMask;
    for (dFilterStep = 0; dFilterStep < (dFilterMask.length + 1); dFilterStep++) {
        if (dFilterMask.charAt(dFilterStep) != '#') {
            dFilterTemp = replace(dFilterTemp, dFilterMask.charAt(dFilterStep), '');
        }
    }
    return dFilterTemp.length;
}


function dFilter(key, textbox, dFilterMask) {
    var dFilterNum = dFilterStrip(textbox.value, dFilterMask);

    //Allow the user to cancel out of a textbox via Escape
    if (key == 27) {
        textbox.value = '';
        return true;
    }

    if (key == 9) {
        return true;
    }
    else if (((key == 8) && (dFilterNum.length !== 0)) || ((key == 46) && (dFilterNum.length !== 0))) {
        var oSelect = document.selection;
        var oSelectRange = oSelect.createRange();
        var oText = oSelectRange.text;

        //allow the user to delete the entire section
        if (oText.length > 0) {
            textbox.value = '';
            return;
        }

        //chop it down if its too big
        dFilterNum = dFilterNum.substring(0, dFilterNum.length - 1);
    }
    else if (((key > 47 && key < 58) || (key > 95 && key < 106)) && dFilterNum.length < dFilterMax(dFilterMask)) {
        //append the new key
        if (key >= 96 && key <= 105) {
            key = key - 48;
        }
        dFilterNum = dFilterNum + String.fromCharCode(key); //MMDDYYYY
    }

    var cursorPos = caretPos(textbox);
    if ((textbox.value.length == dFilterMask.length) && (cursorPos != textbox.value.length)) {
        //Get the current selection
        var oSelect = document.selection;
        var oSelectRange = oSelect.createRange();
        var oText = oSelectRange.text;

        //Only allow them to change one digit at a time
        if (oText.length == 1) {
            if ((key > 47 && key < 58) || (key > 95 && key < 106)) {
                if (key >= 96 && key <= 105) {
                    key = key - 48;
                }

                var temp = textbox.value;

                //Modify the character
                var result = temp.substring(0, cursorPos) + String.fromCharCode(key) + temp.substring(cursorPos + 1, temp.length);

                //Update the now updated temp string to the textbox
                textbox.value = result;

                //Update the filter selection
                dFilterNum = dFilterStrip(textbox.value, dFilterMask);

                //Update the beginning of the selection
                cursorPos = cursorPos + 1;

                //Make sure the next character is not on a delimiter, if it is, skip it!						
                if (dFilterMask.charAt(cursorPos) != '#') {
                    cursorPos = cursorPos + 1;
                }

                oSelectRange.moveStart('character', cursorPos);

                //Update the ending of the selection
                var endVal = oSelectRange.text.length - 1;
                if (endVal > 0) {
                    oSelectRange.moveEnd('character', -endVal);
                }

                //Readjust the selection
                oSelectRange.select();

                return false;
            }
        }
    }

    var dFilterFinal = '';
    for (dFilterStep = 0; dFilterStep < dFilterMask.length; dFilterStep++) {
        if (dFilterMask.charAt(dFilterStep) == '#') {
            if (dFilterNum.length !== 0) {
                dFilterFinal = dFilterFinal + dFilterNum.charAt(0);
                dFilterNum = dFilterNum.substring(1, dFilterNum.length);
            }
            else {
                dFilterFinal = dFilterFinal + '';
            }
        }
        else if (dFilterMask.charAt(dFilterStep) != '#') {
            dFilterFinal = dFilterFinal + dFilterMask.charAt(dFilterStep);
        }
    }
    textbox.value = dFilterFinal;
    return false;
}


//function by Derek
function setEditSelection(textbox, dFilterMask) {
    if (textbox.value.length === 0) {
        return true;
    }

    var cursorPos = caretPos(textbox);
    var offset = 0;

    if (textbox.value.length == cursorPos) {
        return true;
    }

    if (dFilterMask.charAt(cursorPos) != '#') {
        //The cursor is currently located on a delimiter
        if (cursorPos !== 0) {
            cursorPos = cursorPos - 1;
            offset = -1;
        }
    }

    //Get the current selection
    var oSelect = document.selection;
    var oSelectRange = oSelect.createRange();
    var oText = oSelectRange.text;

    //Select the new digit
    if (offset === 0) {
        oSelectRange.moveEnd('character', 1);
        oSelectRange.select();
    }
    else {
        oSelectRange.moveStart('character', -1);
        oSelectRange.select();
    }
    return true;
}


//function by Ivo
function caretPos(textbox) {
    if (textbox.value.length <= 0) {
        return -1;
    }

    var i = textbox.value.length + 1;
    if (textbox.createTextRange) {
        var theCaret = document.selection.createRange().duplicate();
        while (theCaret.parentElement() == textbox && theCaret.move('character', 1) == 1) {
            --i;
        }
    }
    return i - 1;
}


function replace(fullString, txt, by) {
    // Replaces text with by in string
    var strLength = fullString.length, txtLength = txt.length;
    if ((strLength === 0) || (txtLength === 0)) {
        return fullString;
    }
    var i = fullString.indexOf(txt);
    if ((!i) && (txt != fullString.substring(0, txtLength))) {
        return fullString;
    }
    if (i == -1) {
        return fullString;
    }
    var newstr = fullString.substring(0, i) + by;
    if (i + txtLength < strLength) {
        newstr += replace(fullString.substring(i + txtLength, strLength), txt, by);
    }
    return newstr;
}

//----------------------------------------------------
//			*ClientDualListCtrl*
//----------------------------------------------------
function copyToList(from, to, hid) {
    fromList = document.getElementById(from);
    toList = document.getElementById(to);
    hidBox = document.getElementById(hid);
    if (toList.options.length > 0 && toList.options[0].value == 'temp') {
        toList.options.length = 0;
    }
    var sel = false;
    for (i = 0; i < fromList.options.length; i++) {
        var current = fromList.options[i];
        if (current.selected) {
            sel = true;
            if (current.value == 'temp') {
                alert('You cannot move this item!');
                return;
            }
            txt = current.text;
            val = current.value;
            toList.options[toList.length] = new Option(txt, val);
            fromList.options[i] = null;
            i--;
        }
    }
    if (!sel) {
        alert('Please select an item first!');
    }

    var temp = '';
    for (a = 0; a < toList.options.length; a++) {
        if (temp == '') {
            temp = toList.options[a].value;
        }
        else {
            temp = temp + '-' + toList.options[a].value;
        }
    }
    hidBox.value = temp;
}


function doPostBack(eventTarget, eventArgument) {
    var theform;
    if (window.navigator.appName.toLowerCase().indexOf('microsoft') > -1) {
        theform = document.Form1;
    }
    else {
        theform = document.forms['Form1'];
    }
    theform.__EVENTTARGET.value = eventTarget.split('$').join(':');
    theform.__EVENTARGUMENT.value = eventArgument;
    theform.submit();
}

//----------------------------------------------------
//			*MenuCtrl*
//----------------------------------------------------

/***********************************************
* AnyLink Drop Down Menu- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function getposOffset(what, offsettype) {
    var totaloffset = (offsettype == 'left') ? what.offsetLeft : what.offsetTop;
    var parentEl = what.offsetParent;
    while (parentEl !== null) {
        totaloffset = (offsettype == 'left') ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
        parentEl = parentEl.offsetParent;
    }
    return totaloffset;
}


function showhide(obj, e, isvisible, ishidden, menuwidth) {
    if (ie4 || ns6) {
        dropmenuobj.style.left = dropmenuobj.style.top = '-500px';
    }

    if (menuwidth !== '') {
        dropmenuobj.widthobj = dropmenuobj.style;
        dropmenuobj.widthobj.width = menuwidth;
    }
    if (e.type == 'click' && obj.visibility == ishidden || e.type == 'mouseover') {
        obj.visibility = isvisible;
    }
    else if (e.type == 'click') {
        obj.visibility = ishidden;
    }
}


function iecompattest() {
    return (document.compatMode && document.compatMode != 'BackCompat') ? document.documentElement : document.body;
}


function clearbrowseredge(obj, whichedge) {
    var edgeoffset = 0;
    if (whichedge == 'rightedge') {
        var windowedge = ie4 && !window.opera ? iecompattest().scrollLeft + iecompattest().clientWidth - 15 : window.pageXOffset + window.innerWidth - 15;
        dropmenuobj.contentmeasure = dropmenuobj.offsetWidth;
        if (windowedge - dropmenuobj.x < dropmenuobj.contentmeasure) {
            edgeoffset = dropmenuobj.contentmeasure - obj.offsetWidth;
        }
    }
    else {
        var topedge = ie4 && !window.opera ? iecompattest().scrollTop : window.pageYOffset;
        var windowedge = ie4 && !window.opera ? iecompattest().scrollTop + iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18;
        dropmenuobj.contentmeasure = dropmenuobj.offsetHeight;
        if (windowedge - dropmenuobj.y < dropmenuobj.contentmeasure) { //move up?
            edgeoffset = dropmenuobj.contentmeasure + obj.offsetHeight;
            if ((dropmenuobj.y - topedge) < dropmenuobj.contentmeasure) { //up no good either?
                edgeoffset = dropmenuobj.y + obj.offsetHeight - topedge;
            }
        }
    }
    return edgeoffset;
}


function populatemenu(what) {
    if (ie4 || ns6) {
        dropmenuobj.innerHTML = what.join('');
    }
}


function dropdownmenu(obj, e, menucontents, menuwidth) {
    if (window.event) {
        event.cancelBubble = true;
    }
    else if (e.stopPropagation) {
        e.stopPropagation();
    }
    clearhidemenu();
    dropmenuobj = document.getElementById ? document.getElementById('dropmenudiv') : dropmenudiv;
    populatemenu(menucontents);

    if (ie4 || ns6) {
        showhide(dropmenuobj.style, e, 'visible', 'hidden', menuwidth);
        dropmenuobj.x = getposOffset(obj, 'left');
        dropmenuobj.y = getposOffset(obj, 'top');
        dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, 'rightedge') + 'px';
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, 'bottomedge') + obj.offsetHeight + 'px';
    }
    return clickreturnvalue();
}


function clickreturnvalue() {
    if (ie4 || ns6) {
        return false;
    }
    else {
        return true;
    }
}


function contains_ns6(a, b) {
    while (b.parentNode) {
        if ((b = b.parentNode) == a) {
            return true;
        }
    }
    return false;
}


function dynamichide(e) {
    if (ie4 && !dropmenuobj.contains(e.toElement)) {
        delayhidemenu();
    }
    else if (ns6 && e.currentTarget != e.relatedTarget && !contains_ns6(e.currentTarget, e.relatedTarget)) {
        delayhidemenu();
    }
}


function hidemenu(e) {
    if (typeof dropmenuobj != 'undefined') {
        if (ie4 || ns6) {
            dropmenuobj.style.visibility = 'hidden';
        }
    }
}


function delayhidemenu() {
    if (ie4 || ns6) {
        delayhide = setTimeout('hidemenu();', disappeardelay);
    }
}


function clearhidemenu() {
    if (typeof delayhide != 'undefined') {
        clearTimeout(delayhide);
    }
}


// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com
// V1.1.4: Sandeep V. Tamhankar (stamhankar@hotmail.com)
// Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) 
function emailCheck(emailStr, allowEmpty) {

    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (emailStr == '') {
        if ((allowEmpty == null) || (allowEmpty == '') || (allowEmpty == 'false') || (allowEmpty == 'False') || (allowEmpty == 'FALSE')) {
            alert('Please specify an Email address');
            return false;
        }
        else {
            return true;
        }
    }

    if (matchArray == null) {
        alert('Email address seems incorrect (check @s and .s)');
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            alert("Ths username contains invalid characters.");
            return false;
        }
    }
    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            alert("Ths domain name contains invalid characters.");
            return false;
        }
    }

    if (user.match(userPat) == null) {
        alert('The username does not seem to be valid.');
        return false;
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {

        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                alert('Destination IP address is invalid!');
                return false;
            }
        }
        return true;
    }

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            alert("The domain name does not seem to be valid.");
            return false;
        }
    }

    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
domArr[domArr.length - 1].search(knownDomsPat) == -1) {
        alert("The address must end in a well-known domain or two letter " + "country.");
        return false;
    }

    if (len < 2) {
        alert('This address is missing a hostname!');
        return false;
    }

    return true;
}


//**Color Picker**
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/* SOURCE FILE: AnchorPosition.js */
function getAnchorPosition(anchorname) { var useWindow = false; var coordinates = new Object(); var x = 0, y = 0; var use_gebi = false, use_css = false, use_layers = false; if (document.getElementById) { use_gebi = true; } else if (document.all) { use_css = true; } else if (document.layers) { use_layers = true; } if (use_gebi && document.all) { x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y = AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_gebi) { var o = document.getElementById(anchorname); x = AnchorPosition_getPageOffsetLeft(o); y = AnchorPosition_getPageOffsetTop(o); } else if (use_css) { x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y = AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_layers) { var found = 0; for (var i = 0; i < document.anchors.length; i++) { if (document.anchors[i].name == anchorname) { found = 1; break; } } if (found == 0) { coordinates.x = 0; coordinates.y = 0; return coordinates; } x = document.anchors[i].x; y = document.anchors[i].y; } else { coordinates.x = 0; coordinates.y = 0; return coordinates; } coordinates.x = x; coordinates.y = y; return coordinates; }
function getAnchorWindowPosition(anchorname) { var coordinates = getAnchorPosition(anchorname); var x = 0; var y = 0; if (document.getElementById) { if (isNaN(window.screenX)) { x = coordinates.x - document.body.scrollLeft + window.screenLeft; y = coordinates.y - document.body.scrollTop + window.screenTop; } else { x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset; y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset; } } else if (document.all) { x = coordinates.x - document.body.scrollLeft + window.screenLeft; y = coordinates.y - document.body.scrollTop + window.screenTop; } else if (document.layers) { x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset; y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset; } coordinates.x = x; coordinates.y = y; return coordinates; }
function AnchorPosition_getPageOffsetLeft(el) { var ol = el.offsetLeft; while ((el = el.offsetParent) != null) { ol += el.offsetLeft; } return ol; }
function AnchorPosition_getWindowOffsetLeft(el) { return AnchorPosition_getPageOffsetLeft(el) - document.body.scrollLeft; }
function AnchorPosition_getPageOffsetTop(el) { var ot = el.offsetTop; while ((el = el.offsetParent) != null) { ot += el.offsetTop; } return ot; }
function AnchorPosition_getWindowOffsetTop(el) { return AnchorPosition_getPageOffsetTop(el) - document.body.scrollTop; }

/* SOURCE FILE: PopupWindow.js */
function PopupWindow_getXYPosition(anchorname) { var coordinates; if (this.type == "WINDOW") { coordinates = getAnchorWindowPosition(anchorname); } else { coordinates = getAnchorPosition(anchorname); } this.x = coordinates.x; this.y = coordinates.y; }
function PopupWindow_setSize(winWidth, winHeight) { this.width = winWidth; this.height = winHeight; }
function PopupWindow_populate(winContents) { this.contents = winContents; this.populated = false; }
function PopupWindow_setUrl(url) { this.url = url; }
function PopupWindow_setWindowProperties(props) { this.windowProperties = props; }
function PopupWindow_refresh() { if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).innerHTML = this.contents; } else if (this.use_css) { document.all[this.divName].innerHTML = this.contents; } else if (this.use_layers) { var d = document.layers[this.divName]; d.document.open(); d.document.writeln(this.contents); d.document.close(); } } else { if (this.popupWindow != null && !this.popupWindow.closed) { if (this.url != "") { this.popupWindow.location.href = this.url; } else { this.popupWindow.document.open(); this.popupWindow.document.writeln(this.contents); this.popupWindow.document.close(); } this.popupWindow.focus(); } } }
function PopupWindow_showPopup(anchorname) { this.getXYPosition(anchorname); this.x += this.offsetX; this.y += this.offsetY; if (!this.populated && (this.contents != "")) { this.populated = true; this.refresh(); } if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).style.left = this.x + "px"; document.getElementById(this.divName).style.top = this.y; document.getElementById(this.divName).style.visibility = "visible"; } else if (this.use_css) { document.all[this.divName].style.left = this.x; document.all[this.divName].style.top = this.y; document.all[this.divName].style.visibility = "visible"; } else if (this.use_layers) { document.layers[this.divName].left = this.x; document.layers[this.divName].top = this.y; document.layers[this.divName].visibility = "visible"; } } else { if (this.popupWindow == null || this.popupWindow.closed) { if (this.x < 0) { this.x = 0; } if (this.y < 0) { this.y = 0; } if (screen && screen.availHeight) { if ((this.y + this.height) > screen.availHeight) { this.y = screen.availHeight - this.height; } } if (screen && screen.availWidth) { if ((this.x + this.width) > screen.availWidth) { this.x = screen.availWidth - this.width; } } var avoidAboutBlank = window.opera || (document.layers && !navigator.mimeTypes['*']) || navigator.vendor == 'KDE' || (document.childNodes && !document.all && !navigator.taintEnabled); this.popupWindow = window.open(avoidAboutBlank ? "" : "about:blank", "window_" + anchorname, this.windowProperties + ",width=" + this.width + ",height=" + this.height + ",screenX=" + this.x + ",left=" + this.x + ",screenY=" + this.y + ",top=" + this.y + ""); } this.refresh(); } }
function PopupWindow_hidePopup() { if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).style.visibility = "hidden"; } else if (this.use_css) { document.all[this.divName].style.visibility = "hidden"; } else if (this.use_layers) { document.layers[this.divName].visibility = "hidden"; } } else { if (this.popupWindow && !this.popupWindow.closed) { this.popupWindow.close(); this.popupWindow = null; } } }
function PopupWindow_isClicked(e) { if (this.divName != null) { if (this.use_layers) { var clickX = e.pageX; var clickY = e.pageY; var t = document.layers[this.divName]; if ((clickX > t.left) && (clickX < t.left + t.clip.width) && (clickY > t.top) && (clickY < t.top + t.clip.height)) { return true; } else { return false; } } else if (document.all) { var t = window.event.srcElement; while (t.parentElement != null) { if (t.id == this.divName) { return true; } t = t.parentElement; } return false; } else if (this.use_gebi && e) { var t = e.originalTarget; while (t.parentNode != null) { if (t.id == this.divName) { return true; } t = t.parentNode; } return false; } return false; } return false; }
function PopupWindow_hideIfNotClicked(e) { if (this.autoHideEnabled && !this.isClicked(e)) { this.hidePopup(); } }
function PopupWindow_autoHide() { this.autoHideEnabled = true; }
function PopupWindow_hidePopupWindows(e) { for (var i = 0; i < popupWindowObjects.length; i++) { if (popupWindowObjects[i] != null) { var p = popupWindowObjects[i]; p.hideIfNotClicked(e); } } }
function PopupWindow_attachListener() { if (document.layers) { document.captureEvents(Event.MOUSEUP); } window.popupWindowOldEventListener = document.onmouseup; if (window.popupWindowOldEventListener != null) { document.onmouseup = new Function("window.popupWindowOldEventListener();PopupWindow_hidePopupWindows();"); } else { document.onmouseup = PopupWindow_hidePopupWindows; } }
function PopupWindow() { if (!window.popupWindowIndex) { window.popupWindowIndex = 0; } if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); } if (!window.listenerAttached) { window.listenerAttached = true; PopupWindow_attachListener(); } this.index = popupWindowIndex++; popupWindowObjects[this.index] = this; this.divName = null; this.popupWindow = null; this.width = 0; this.height = 0; this.populated = false; this.visible = false; this.autoHideEnabled = false; this.contents = ""; this.url = ""; this.windowProperties = "toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no"; if (arguments.length > 0) { this.type = "DIV"; this.divName = arguments[0]; } else { this.type = "WINDOW"; } this.use_gebi = false; this.use_css = false; this.use_layers = false; if (document.getElementById) { this.use_gebi = true; } else if (document.all) { this.use_css = true; } else if (document.layers) { this.use_layers = true; } else { this.type = "WINDOW"; } this.offsetX = 0; this.offsetY = 0; this.getXYPosition = PopupWindow_getXYPosition; this.populate = PopupWindow_populate; this.setUrl = PopupWindow_setUrl; this.setWindowProperties = PopupWindow_setWindowProperties; this.refresh = PopupWindow_refresh; this.showPopup = PopupWindow_showPopup; this.hidePopup = PopupWindow_hidePopup; this.setSize = PopupWindow_setSize; this.isClicked = PopupWindow_isClicked; this.autoHide = PopupWindow_autoHide; this.hideIfNotClicked = PopupWindow_hideIfNotClicked; }


/* SOURCE FILE: ColorPicker2.js */
ColorPicker_targetInput = null;
ColorPicker_targetOutput = null;

function ColorPicker_writeDiv() { document.writeln("<div ID=\"colorPickerDiv\" style=\"position:absolute;visibility:hidden;\"> </div>"); }
function ColorPicker_show(anchorName) { this.showPopup(anchorName); }
function ColorPicker_pickColor(colorName, obj) { obj.hidePopup(); pickColor(colorName); }
function pickColor(colorName) {
    if (ColorPicker_targetInput == null) {
        alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");
        return;
    }
    ColorPicker_targetInput.value = colorName;

    if (ColorPicker_targetOutput != null) {
        ColorPicker_targetOutput.style.backgroundColor = colorName;
    }
}


function ColorPicker_select(objname) {
    var inputobj = document.getElementById(objname);
    var outputobj = document.getElementById(objname + "_color");
    var linkname = objname + "_link";

    if (inputobj.type != "text" && inputobj.type != "hidden" && inputobj.type != "textarea") {
        alert("colorpicker.select: Input object passed is not a valid form input object");
        window.ColorPicker_targetInput = null;
        window.ColorPicker_targetOutput = null;
        return;
    }

    window.ColorPicker_targetInput = inputobj;
    window.ColorPicker_targetOutput = outputobj;
    this.show(linkname);
}


function ColorPicker_highlightColor(c) {
    var thedoc = (arguments.length > 1) ? arguments[1] : window.document;
    var d = thedoc.getElementById("colorPickerSelectedColor");
    d.style.backgroundColor = c;
    d = thedoc.getElementById("colorPickerSelectedColorValue");
    d.innerHTML = c;
}


function ColorPicker() {
    var windowMode = false;
    if (arguments.length == 0) {
        var divname = "colorPickerDiv";
    } else if (arguments[0] == "window") {
        var divname = '';
        windowMode = true;
    } else {
        var divname = arguments[0];
    }

    if (divname != "") {
        var cp = new PopupWindow(divname);
    } else {
        var cp = new PopupWindow();
        cp.setSize(225, 250);
    }
    cp.currentValue = "#FFFFFF";
    cp.writeDiv = ColorPicker_writeDiv;
    cp.highlightColor = ColorPicker_highlightColor;
    cp.show = ColorPicker_show;
    cp.select = ColorPicker_select;
    var colors = new Array("#000000", "#000033", "#000066", "#000099", "#0000CC", "#0000FF", "#330000", "#330033", "#330066", "#330099", "#3300CC",
"#3300FF", "#660000", "#660033", "#660066", "#660099", "#6600CC", "#6600FF", "#990000", "#990033", "#990066", "#990099",
"#9900CC", "#9900FF", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#FF0000", "#FF0033", "#FF0066",
"#FF0099", "#FF00CC", "#FF00FF", "#003300", "#003333", "#003366", "#003399", "#0033CC", "#0033FF", "#333300", "#333333",
"#333366", "#333399", "#3333CC", "#3333FF", "#663300", "#663333", "#663366", "#663399", "#6633CC", "#6633FF", "#993300",
"#993333", "#993366", "#993399", "#9933CC", "#9933FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF",
"#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#006600", "#006633", "#006666", "#006699", "#0066CC",
"#0066FF", "#336600", "#336633", "#336666", "#336699", "#3366CC", "#3366FF", "#666600", "#666633", "#666666", "#666699",
"#6666CC", "#6666FF", "#996600", "#996633", "#996666", "#996699", "#9966CC", "#9966FF", "#CC6600", "#CC6633", "#CC6666",
"#CC6699", "#CC66CC", "#CC66FF", "#FF6600", "#FF6633", "#FF6666", "#FF6699", "#FF66CC", "#FF66FF", "#009900", "#009933",
"#009966", "#009999", "#0099CC", "#0099FF", "#339900", "#339933", "#339966", "#339999", "#3399CC", "#3399FF", "#669900",
"#669933", "#669966", "#669999", "#6699CC", "#6699FF", "#999900", "#999933", "#999966", "#999999", "#9999CC", "#9999FF",
"#CC9900", "#CC9933", "#CC9966", "#CC9999", "#CC99CC", "#CC99FF", "#FF9900", "#FF9933", "#FF9966", "#FF9999", "#FF99CC",
"#FF99FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#33CC00", "#33CC33", "#33CC66", "#33CC99",
"#33CCCC", "#33CCFF", "#66CC00", "#66CC33", "#66CC66", "#66CC99", "#66CCCC", "#66CCFF", "#99CC00", "#99CC33", "#99CC66",
"#99CC99", "#99CCCC", "#99CCFF", "#CCCC00", "#CCCC33", "#CCCC66", "#CCCC99", "#CCCCCC", "#CCCCFF", "#FFCC00", "#FFCC33",
"#FFCC66", "#FFCC99", "#FFCCCC", "#FFCCFF", "#00FF00", "#00FF33", "#00FF66", "#00FF99", "#00FFCC", "#00FFFF", "#33FF00",
"#33FF33", "#33FF66", "#33FF99", "#33FFCC", "#33FFFF", "#66FF00", "#66FF33", "#66FF66", "#66FF99", "#66FFCC", "#66FFFF",
"#99FF00", "#99FF33", "#99FF66", "#99FF99", "#99FFCC", "#99FFFF", "#CCFF00", "#CCFF33", "#CCFF66", "#CCFF99", "#CCFFCC",
"#CCFFFF", "#FFFF00", "#FFFF33", "#FFFF66", "#FFFF99", "#FFFFCC", "#FFFFFF");
    var total = colors.length;
    var width = 18;
    var cp_contents = "";
    var windowRef = (windowMode) ? "window.opener." : "";
    if (windowMode) {
        cp_contents += "<HTML><HEAD><TITLE>Select Color</TITLE></HEAD>";
        cp_contents += "<BODY MARGINWIDTH=0 MARGINHEIGHT=0 LEFTMARGIN=0 TOPMARGIN=0><CENTER>";
    }
    cp_contents += "<TABLE BORDER=1 CELLSPACING=1 CELLPADDING=0>";
    var use_highlight = (document.getElementById || document.all) ? true : false;
    for (var i = 0; i < total; i++) {
        if ((i % width) == 0) {
            cp_contents += "<TR>";
        }
        if (use_highlight) {
            var mo = 'onMouseOver="' + windowRef + 'ColorPicker_highlightColor(\'' + colors[i] + '\',window.document)"';
        } else {
            mo = "";
        }
        cp_contents += '<TD BGCOLOR="' + colors[i] + '"><FONT SIZE="-3"><A HREF="#" onClick="' + windowRef + 'ColorPicker_pickColor(\'' + colors[i] + '\',' + windowRef + 'window.popupWindowObjects[' + cp.index + ']);return false;" ' + mo + ' style="text-decoration:none;">&nbsp;&nbsp;&nbsp;</A></FONT></TD>';
        if (((i + 1) >= total) || (((i + 1) % width) == 0)) {
            cp_contents += "</TR>";
        }
    }
    if (document.getElementById) {
        var width1 = Math.floor(width / 2);
        var width2 = width = width1;
        cp_contents += "<TR><TD COLSPAN='" + width1 + "' BGCOLOR='#ffffff' ID='colorPickerSelectedColor'>&nbsp;</TD><TD COLSPAN='" + width2 + "' ALIGN='CENTER' ID='colorPickerSelectedColorValue'>#FFFFFF</TD></TR>";
    } cp_contents += "</TABLE>";
    if (windowMode) {
        cp_contents += "</CENTER></BODY></HTML>";
    }
    cp.populate(cp_contents + "\n");
    cp.offsetY = 25; cp.autoHide();
    return cp;
}


//**RichTextBox**
var isHTMLMode = false;


function SetDesignMode(childId) {
    var richTextFrame = childId.concat('_RichTextFrame');
    document.frames[richTextFrame].document.designMode = 'on';
}


function TextCommand(command, childId, opt) {
    if (isHTMLMode) {
        alert("Formatting happens only in Normal mode");
        return;
    }
    var richTextFrame = childId.concat('_RichTextFrame');

    document.frames[richTextFrame].focus();
    document.frames[richTextFrame].document.execCommand(command, "", opt);
    document.frames[richTextFrame].focus();

    UpdateDataToTextHtmlControls(childId);
}


function WordCount(childId) {
    var countTextBox = childId + '_txtWordCount';
    var count = window.parent.document.getElementById(countTextBox).value;
    var richTextFrame = childId.concat('_RichTextFrame');
    var textEntered = document.frames[richTextFrame].document.body.innerText;

    window.parent.document.getElementById(countTextBox).value = textEntered.length;
}


//original function by Robert Nyman - http://robertnyman.com/roblab/javascript-remove-tags.htm
function removeHTMLTags(inputText) {
    inputText = inputText.replace(/&(lt|gt);/g, function(strMatch, p1) {
        return (p1 == "lt") ? "<" : ">";
    });

    return inputText.replace(/<\/?[^>]+(>|$)/g, "");
}


function UpdateDataToTextHtmlControls(childId) {
    var htmlValue = childId.concat('_txtHtmlValue');
    var textValue = childId.concat('_txtTextValue');
    var richTextFrame = childId.concat('_RichTextFrame');

    document.getElementById(htmlValue).value = document.frames[richTextFrame].document.body.innerHTML;
    document.getElementById(textValue).value = document.frames[richTextFrame].document.body.innerText;
}


function UpdateDataFromTextHtmlControls(childId) {
    var htmlValue = childId.concat('_txtHtmlValue');
    var textValue = childId.concat('_txtTextValue');
    var richTextFrame = childId.concat('_RichTextFrame');

    var cleanString = document.getElementById(htmlValue).value;
    cleanString = removeHTMLTags(cleanString);

    if (document.frames[richTextFrame].document.body !== null) {
        document.frames[richTextFrame].document.body.innerText = cleanString;
        document.frames[richTextFrame].document.body.innerHTML = document.getElementById(htmlValue).value;
    }
}


function ChangeFontSize(childId) {
    var richTextFrame = childId.concat('_RichTextFrame');

    document.frames[richTextFrame].focus();
    document.frames[richTextFrame].document.execCommand('FontSize', 0, fontSize.options[fontSize.selectedIndex].value);
    document.frames[richTextFrame].focus();
}


function ShowSource(childId, htmlMode) {
    var richTextFrame = childId.concat('_RichTextFrame');

    if (htmlMode == isHTMLMode)
        return;

    isHTMLMode = htmlMode;

    if (isHTMLMode) {
        document.frames[richTextFrame].document.body.innerText = document.frames[richTextFrame].document.body.innerHTML;
    }
    else {
        document.frames[richTextFrame].document.body.innerHTML = document.frames[richTextFrame].document.body.innerText;
    }

    document.frames[richTextFrame].focus();
}


//Function By npguy@my-deja.com
//Finds and returns an element.
function GetElement(sTag, startObj) {
    //Copy the selected character to "start" string while start!=NULL && tagName doesn't have 'A'
    while ((startObj != null) && (startObj.tagName != sTag))
        startObj = startObj.parentElement;
    return start;
}


//Function By npguy@my-deja.com
function CreateLink(childId) {
    var richTextFrame = childId.concat('_RichTextFrame');

    var isA = GetElement("A", document.frames[richTextFrame].document.selection.createRange().parentElement());

    var str = prompt("Enter URL :", isA ? isA.href : "http:\/\/");

    //if str selection type is None!(If the user didn't block the string) then
    // get the string and add the <A HREF and paste it.  
    if ((str != null) && (str != "http://")) {
        if (document.frames[richTextFrame].document.selection.type == "None") {
            var sel = document.frames[richTextFrame].document.selection.createRange();
            sel.pasteHTML("<A HREF=\"" + str + "\">" + str + "</A> ");
            sel.select();
        }
        else {
            //If user had selected/blocked the string  just pass this command.
            TextCommand("CreateLink", childId, str);
        }
    }
    else {
        //If nothing entered just Focus our IFRAME.
        document.frames[richTextFrame].focus();
    }
}


function CreateImage(childId, baseImagePath) {
    if (isHTMLMode) {
        alert("Formatting happens only in Normal mode");
        return;
    }

    var richTextFrame = childId.concat('_RichTextFrame');

    var isA = GetElement("A", document.frames[richTextFrame].document.selection.createRange().parentElement());

    var str = prompt("Enter Image URL :", baseImagePath);

    if ((str != null) && (str != "")) {
        //javascript:TextCommand('insertimage',
        var sel = document.frames[richTextFrame].document.selection.createRange();
        sel.pasteHTML("<img src=\"" + str + "\">");
        sel.select();
    }
    else {
        //If nothing entered just Focus our IFRAME.
        document.frames[richTextFrame].focus();
    }
}


//**FeedbackCtrl**
function DisplayFeedbackCtrl(obj, divName) {
    var el = document.getElementById(divName);
    el.style.top = obj.style.top;
    //el.style.left = obj.style.left-200;
    el.style.display = 'block';
}

function ShowTextEditor(divCtr, txtEdit, txtOrig) {
    var edit = document.getElementById(txtEdit);
    var orig = document.getElementById(txtOrig);
    var div = document.getElementById(divCtr);

    if (div != null && edit != null && orig != null) {
        edit.value = orig.value;
        div.style.position = 'absolute';
        div.style.left = 10;
        div.style.top = 10;
        div.style.visibility = 'visible';
    }

    if (orig.style.top != null) {
        lastScrollPosition = this.findPosY(orig);
    }

    window.scrollTo(0, 0);
}


function SaveTextEditor(divCtrl, txtEdit, txtOrig) {
    var edit = document.getElementById(txtEdit);
    var orig = document.getElementById(txtOrig);
    var div = document.getElementById(divCtrl);

    if (div != null && edit != null && orig != null) {
        orig.value = edit.value;
        div.style.visibility = 'hidden';
    }

    window.scrollTo(0, lastScrollPosition);
}


function Cancel(divCtrl) {
    var div = document.getElementById(divCtrl);

    if (div != null) {
        div.style.visibility = 'hidden';
    }

    window.scrollTo(0, lastScrollPosition);
}


function CloseTextEditorDiv(divCtrl, txtEdit, txtOrig) {
    var edit = document.getElementById(txtEdit);
    var orig = document.getElementById(txtOrig);
    var div = document.getElementById(divCtrl);

    if (div != null && edit != null && orig != null) {
        if (edit.value != orig.value) {
            if (saveConfirm('Do you want to save change?')) {
                orig.value = edit.value;
            }
        }
        div.style.visibility = 'hidden';
    }

    window.scrollTo(0, lastScrollPosition);
}


function NewEntry(txtCtrl, username) {
    var edit = document.getElementById(txtCtrl);

    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();

    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();

    var date = ""; //MM/DD/YY
    var time = ""; //HH:MM

    if (month < 10)
        date = "0";

    date = date + month + "/";

    if (day < 10)
        date = date + "0";

    date = date + day + "/";

    date = date + year.toString().substring(2, 4);

    if (hours < 10)
        time = "0";

    time = time + hours;

    time = time + ":";

    if (minutes < 10)
        time = time + "0";

    time = time + minutes;

    edit.value = "\r" + username + " " + date + " " + time + ":\r" + edit.value;
}


function saveConfirm(msg) {
    return confirm(msg);
}


/**************************************************
* dom-drag.js
* 09.25.2001
* www.youngpup.net
* Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005
**************************************************
* 10.28.2001 - fixed minor bug where events
* sometimes fired off the handle, not the root.
**************************************************/
var Drag = {

    obj: null,

    init: function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper) {
        o.onmousedown = Drag.start;

        o.hmode = bSwapHorzRef ? false : true;
        o.vmode = bSwapVertRef ? false : true;

        o.root = oRoot && oRoot != null ? oRoot : o;

        if (o.hmode && isNaN(parseInt(o.root.style.left))) o.root.style.left = "0px";
        if (o.vmode && isNaN(parseInt(o.root.style.top))) o.root.style.top = "0px";
        if (!o.hmode && isNaN(parseInt(o.root.style.right))) o.root.style.right = "0px";
        if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

        o.minX = typeof minX != 'undefined' ? minX : null;
        o.minY = typeof minY != 'undefined' ? minY : null;
        o.maxX = typeof maxX != 'undefined' ? maxX : null;
        o.maxY = typeof maxY != 'undefined' ? maxY : null;

        o.xMapper = fXMapper ? fXMapper : null;
        o.yMapper = fYMapper ? fYMapper : null;

        o.root.onDragStart = new Function();
        o.root.onDragEnd = new Function();
        o.root.onDrag = new Function();
    },

    start: function(e) {
        var o = Drag.obj = this;
        e = Drag.fixE(e);
        var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right);
        o.root.onDragStart(x, y);

        o.lastMouseX = e.clientX;
        o.lastMouseY = e.clientY;

        if (o.hmode) {
            if (o.minX != null) o.minMouseX = e.clientX - x + o.minX;
            if (o.maxX != null) o.maxMouseX = o.minMouseX + o.maxX - o.minX;
        } else {
            if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
            if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
        }

        if (o.vmode) {
            if (o.minY != null) o.minMouseY = e.clientY - y + o.minY;
            if (o.maxY != null) o.maxMouseY = o.minMouseY + o.maxY - o.minY;
        } else {
            if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
            if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
        }

        document.onmousemove = Drag.drag;
        document.onmouseup = Drag.end;

        return false;
    },

    drag: function(e) {
        e = Drag.fixE(e);
        var o = Drag.obj;

        var ey = e.clientY;
        var ex = e.clientX;
        var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right);
        var nx, ny;

        if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
        if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
        if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
        if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

        nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
        ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

        if (o.xMapper)
            nx = o.xMapper(y);
        else if (o.yMapper)
            ny = o.yMapper(x);

        Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
        Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
        Drag.obj.lastMouseX = ex;
        Drag.obj.lastMouseY = ey;

        Drag.obj.root.onDrag(nx, ny);
        return false;
    },

    end: function() {
        document.onmousemove = null;
        document.onmouseup = null;
        Drag.obj.root.onDragEnd(parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
        Drag.obj = null;
    },

    fixE: function(e) {
        if (typeof e == 'undefined') e = window.event;
        if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
        if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
        return e;
    }
};


// ---------------------------
// Legal
// ---------------------------
// CastleBusyBox Control
// Castle Rock Software, LLC
// by Mark Wagner
// http://www.crsw.com
//
// Version: 1.2
//
// Copyright 2004, 2005 Castle Rock Software, LLC
// No warranty express or implied.

// ---------------------------
// General Notes
// ---------------------------
// The BusyBox javascript has been written so the BusyBox javascript
// control can be used with or without the Castle.BusyBox .NET control.

// ---------------------------
// Constructor
// ---------------------------
// BusyBox class constructor
// Arguments:
//   id - id of the IFrame tag to use.
//   varName - name of the variable this instance of the busy box is assigned to.
//   imageCount - number of image in the animation sequence.
//   imageNamePrefix - name prefix for each image.
//   imageNameSuffix - name suffix for each image.
//   imageDelay - number of milliseconds to display each image.
//   width - defines the width of the busy box (required for Netscape and Firefox)
//   height - defines the height of the busy box (required for Netscape and Firefox)
//   url - (optional) url to the page containing the custom busy box layout.
//
//   This example uses the default busy box layout defined internally (in the javascript).
//   var busyBox = new BusyBox("BusyBox1", "busyBox", 4, "gears_ani_", ".gif", 125, 147, 206)
//
//   This example uses a custom busy box layout defined in the BusyBox.htm file.
//   var busyBox = new BusyBox("BusyBox1", "busyBox", 4, "gears_ani_", ".gif", 125, 147, 206, "BusyBox.htm")
//
function BusyBox(objId, varName, imageCount, imageNamePrefix, imageNameSuffix, imageDelay, imageWidth, imageHeight, url) {
    // Initialize object
    this.id = objId;
    this.ImageCount = imageCount;
    this.CurrentImageIndex = 0;
    this.ImageWidth = 0;
    this.ImageHeight = 0;
    this.ImageNamePrefix = imageNamePrefix;
    this.ImageNameSuffix = imageNameSuffix;
    this.ImageDelay = imageDelay;
    this.DivID = "BusyBoxDiv";
    this.ImgID = "BusyBoxImg";
    this.Enabled = true;
    this.Width = imageWidth;
    this.Height = imageHeight;

    // Retain the name of the instantiated object variable so that we can animate 
    // using the setTimeout statement
    this.VarName = varName;

    // Allows us to stop the animation with clearTimeout(), should we ever want to
    this.timeout_id = null;

    // Cache (pre-load) images
    this.CacheImages();

    // Url to the page containing the busy box.
    this.BusyBoxUrl = url;

    // Get reference to the IFrame object
    this.IFrame = document.getElementById(this.id);

    // Hide the busy box
    this.Hide();

    if (this.BusyBoxUrl)
    // Load the busy box contents using a custom layout page.
        this.LoadUrl(this.BusyBoxUrl);
    else
    // Load the busy box contents using the internally defined layout.
        this.RenderContent();

    // If this browser does not support IFRAME tags then disable this control.  The
    // next version will implement the use of a DIV instead of the IFRAME tag; 
    // even though there are a couple minor issues with using DIV tags.
    if (!frames[this.id])
        this.Enabled = false;
}

// --------------------------------
// Instance Methods
// --------------------------------

// GetIFrameDocument:
// Returns a reference to the document object in the IFrame.
BusyBox.prototype.GetIFrameDocument = function() {
    var doc;

    if (this.IFrame.contentDocument)
    // For NS6
        doc = this.IFrame.contentDocument;
    else if (this.IFrame.contentWindow)
    // For IE5.5 and IE6
        doc = this.IFrame.contentWindow.document;
    else if (this.IFrame.document)
    // For IE5
        doc = this.IFrame.document;
    else
    // TODO: Confirm this should be the default
        doc = this.IFrame.document;

    return doc;
}

// LoadUrl:
// Changing the src attribute for an IFrame tag causes each new page to be 
// added to the browsers history object.  This causes undesired results for 
// the user when they click the back button.  Instead, we can use the 
// document.location.replace() method to correctly load our busy box 
// page into our IFrame.
//
// Arguments:
//		url - url to the busy box page.
BusyBox.prototype.LoadUrl = function(url) {
    // Get a reference to the document object in the IFrame
    var IFrameDoc = this.GetIFrameDocument();

    // Load the url using the replace method.  This will prevent the browsers 
    // history object from being updated with the new busybox url; thus allowing 
    // the back button to function as desired for the user.
    IFrameDoc.location.replace(url);
}

// RenderContent:
// This method is used when the default busy box layout is used; not a custom 
// layout.  This method is called when the url argument for the constructor is null.
BusyBox.prototype.RenderContent = function() {
    // Get the IFrame document object
    var doc = this.GetIFrameDocument();

    var cssStyle = " style='BORDER: navy 3px solid; POSITION: absolute;' ";

    doc.open();
    doc.writeln("<body ondragstart='return false;' style='Margin: 0px; Background-Color: white'>");
    doc.writeln("   <div id='" + this.DivID + "' align=center " + cssStyle + ">");
    doc.writeln("      <img id='" + this.ImgID + "' src=''>");
    doc.writeln("      <br><h3>Processing...</h3>");
    doc.writeln("   </div>");
    doc.writeln("</body>");
    doc.close();
}

// Resize:
// Resizes the busy box IFrame by setting its width and height attributes
// to the size of its contents.
BusyBox.prototype.Resize = function() {
    // Resize the busy box IFrame.
    if (BusyBox.IsBrowserIE()) {
        // Set the width by looking at its contents
        var div = frames[this.id].document.getElementById(this.DivID);
        this.IFrame.style.width = div.offsetWidth;
        this.IFrame.style.height = div.offsetHeight;
    }
    else {
        // Set the width to the value specified.
        this.IFrame.style.width = this.Width + 'px';
        this.IFrame.style.height = this.Height + 'px';
    }
}

// Center:
// Centers the busy box IFrame on the page regardless of the browsers
// scroll position.  This ensures the busy box is presented to the user
// in a visible location in the window.
BusyBox.prototype.Center = function() {
    if (!this.IFrame)
        return;

    // Center the BusyBox in the window regardless of the scroll positions
    var objLeft = (document.body.clientWidth - this.IFrame.offsetWidth) / 2;
    var objTop = (document.body.clientHeight - this.IFrame.offsetHeight) / 2;
    objLeft = objLeft + document.body.scrollLeft;
    objTop = objTop + document.body.scrollTop;

    // Position object
    this.IFrame.style.position = "absolute";
    this.IFrame.style.top = objTop + 'px';
    this.IFrame.style.left = objLeft + 'px';
}

// CacheImages:
// Pre-loads the images from the server and stores a reference to each
// image.  This allows the images to be presented to the user quickly
// for smooth image animation.
BusyBox.prototype.CacheImages = function() {
    // Instantiate the array to store the image references
    this.Images = new Array(this.ImageCount);

    // Load all the images to cache into the aniframes array
    for (var i = 0; i < this.ImageCount; i++) {
        this.Images[i] = new Image();
        this.Images[i].src = this.ImageNamePrefix + i + this.ImageNameSuffix;
    }
}

// IsAnimating:
// Returns a boolean value representing the state of the animation.
BusyBox.prototype.IsAnimating = function() {
    if (this.timeout_id == null)
        return false;
    else
        return true;
}

// IsVisible:
// Returns a boolean value representing the visibility state for the busy box.
BusyBox.prototype.IsVisible = function() {
    var ifrm = document.getElementById(this.id);

    if (ifrm.style.visibility == "visible" && ifrm.style.width > 0)
        return true;
    else
        return false;
}

// Animate:
// Performs the animation process.  This is accomplished by showing the "current" 
// image in the animation sequence process; and then submitting a timed statement
// to execute in x number of milliseconds.
BusyBox.prototype.Animate = function() {
    // Assign the current image sequence to display
    if (frames[this.id])
    // browser supports frames
        frames[this.id].document.getElementById(this.ImgID).src = this.Images[this.CurrentImageIndex].src;
    else
    // browser does not support frames
        document.getElementById(this.ImgID).src = this.Images[this.CurrentImageIndex].src;

    // Auto re-center and re-size the busy box.  This will force the busy box to 
    // always appear in the center of the window even if the user scrolls.
    this.Resize();
    this.Center();

    // Increment the current image index
    this.CurrentImageIndex = (this.CurrentImageIndex + 1) % this.ImageCount;

    // Display the next image in (imageDelay value) milliseconds (i.e. 125)
    this.timeout_id = setTimeout(this.VarName + ".Animate();", this.ImageDelay);
}

// StartAnimation:
// Starts the animation process.
BusyBox.prototype.StartAnimate = function() {
    if (this.IsAnimating())
        return;

    this.Animate();
}

// StopAnimation:
// Stops the animation process.
BusyBox.prototype.StopAnimate = function() {
    clearTimeout(this.timeout_id);
    this.timeout_id = null;
}

// Hide:
// Hides the busy box making it invisible to the user.
BusyBox.prototype.Hide = function() {
    this.StopAnimate();

    // Hide the busy box.
    this.IFrame.style.visibility = "hidden";
    this.IFrame.style.width = '0px';
    this.IFrame.style.height = '0px';
}

// Show:
// This function displays the busy box to the user.  This function centers the 
// busy dialog box, makes it visible, and starts the animation.  This function 
// will typically be called by the body event.
//
// Example:
//		<body onbeforeunload="busyBox.Show();" >
BusyBox.prototype.Show = function() {
    if (!this.Enabled)
        return;

    if (this.IsAnimating() || this.IsVisible())
        return;

    this.Resize();
    this.Center();

    // Set the busy box to be visible and make sure it is on top of all other controls.	
    this.IFrame.style.visibility = "visible";
    this.IFrame.style.zIndex = "999999";

    // Start the animation
    this.StartAnimate();
}

// --------------------------------
// Class Methods
// --------------------------------

// IsBrowserIE:
// Returns true if the executing browser it a Microsoft Internet Explorer browser.
BusyBox.IsBrowserIE = function() {
    try
	{ return (window.navigator.userAgent.indexOf("MSIE ") > 0); }
    catch (x)
	{ return false; }
}

// IsBrowserNS:
// Returns true if the executing browser it a Netscape browser.
BusyBox.IsBrowserNS = function() {
    try
	{ return (window.navigator.userAgent.indexOf("Netscape") > 0); }
    catch (x)
	{ return false; }
}

// IsBrowserFirefox:
// Returns true if the executing browser it a Firefox browser.
BusyBox.IsBrowserFirefox = function() {
    try
	{ return (window.navigator.userAgent.indexOf("Firefox") > 0); }
    catch (x)
	{ return false; }
}

function SetWaterMark(txt, evt) {
    if (txt.value.length == 0 && evt.type == "blur") {
        txt.style.color = "gray";
        txt.value = txt.title;
    }

    if (txt.value == txt.title && evt.type == "focus") {
        txt.style.color = "black";
        txt.value = "";
    }
}


function UpdateConstantContactLink(txtBoxName, lnkName, initialVal, ccid) {
    if ((document.getElementById(txtBoxName).value.length == 0) || (document.getElementById(txtBoxName).value == initialVal)) {
        document.getElementById(lnkName).target = '';
        return false;
    }

    var ccUrl = "http://ui.constantcontact.com/d.jsp?m=" + ccid + "&p=oi&ea=" + document.getElementById(txtBoxName).value;
    document.getElementById(lnkName).href = ccUrl;
}


function UpdateConstantContactRemovalLink(lnkName, email, ccid) {
    if (email.length == 0) {
        email = prompt("We are sorry to see you go, please enter your email address to remove yourself from the list.", "")

        if (email == null)
            return;
    }

    if (email.length > 0) {
        var ccUrl = "http://ui.constantcontact.com/d.jsp?m=" + ccid + "&p=un&ea=" + email;
        document.getElementById(lnkName).href = ccUrl;
    }
}


// This script and many more are available free online at -->
// The JavaScript Source!! http://javascript.internet.com -->
// V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
// Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
function ChangeFileName(source, destination) {
    obj1 = document.getElementById(source);
    obj2 = document.getElementById(destination);
    var temp = obj1.value;
    if (temp.length == 0)
        return;
    obj2.value = temp.substring(temp.lastIndexOf('\\') + 1);
}


function ToggleCheckAll(ctr) {
    obj = document.getElementById(ctr);

    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = obj.checked;
        }
    }
}


function ToggleCheckAllByObject(obj) {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = obj.checked;
        }
    }
}


function CheckAll(ctr) {
    obj = document.getElementById(ctr);

    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = true;
        }
    }
}


function CheckAllByObject(obj) {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = true;
        }
    }
}


function UnCheckAll(ctr) {
    obj = document.getElementById(ctr);

    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = false;
        }
    }
}


function UnCheckAllByObject(obj) {
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            elm.checked = false;
        }
    }
}


function ConfirmDelete() {
    return confirm('Are you sure you want to delete the file(s) from the server?');
}
