(function(window)
{
    var document = window.document
    var masada = function(selector)
    {

        return new _masada(selector, arguments);
    }
    var $ = masada;
    var SetStyle = function(style)
    {
        if (typeof style == "number") return style + 'px';
        return style;
    }
    var _masada = function(selector, arguments)
    {
        var sel;
        if (arguments.length == 0)
        {
            this.element = null;
        }
        else if (selector === window.document)
        {
            this.element = selector;
        }
        else if (typeof (selector) == 'object')
        {
            this.element = selector;
        }
        else if (typeof (selector) == 'string')
        {
            if (selector.substr(0, 1) == '^')
            {
                this.element = document.createElement(selector.substr(1));
            }
            else
            {
                this.element = document.getElementById(selector);
            }
            if (this.element == null)
            {
                alert('Error, selector: ' + selector + ' is null');
            }
        }
        return this;
    }

    _masada.prototype = $.f =
    {
        ready: function(handler)
        {
            var Ready = false;
            var OnReady = function()
            {
                if (!Ready)
                {
                    var ajax = masada().ajax();
                    ajax.init(handler);
                    Ready = true;
                }
            }
            if (document.readyState === "complete") { OnReady(); return; }
            var Handler = handler;
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", OnReady, null);
            else if (/KHTML|WebKit/i.test(navigator.userAgent)) // Safari
            { // per John Resig
                var _timer = setInterval(function()
                {
                    if (/loaded|complete/.test(document.readyState))
                    {
                        clearInterval(_timer);
                        delete _timer;
                        OnReady();
                    }
                }, 10);
            }
            else document.attachEvent("onreadystatechange", OnReady)
        },

        appendTo: function(parent)
        {
            if (this.element.parentNode != null)
            {
                alert('Error in appendTo, node is already DOM element');
                return;
            }
            parent.appendChild(this.element);
            return this;
        },

        append: function(element)
        {
            this.element.appendChild(element);
            return this;
        },

        html: function(value)
        {
            if (arguments.length)
            {
                this.element.innerHTML = value;
            }
            else
            {
                return this.element.innerHTML;
            }
            return;
        },

        bindTo: function(parent)
        {
            if (this.element.parentNode != null)
            {
                alert('Error in bindTo, node is already DOM element');
                return;
            }
            parent.appendChild(this.element);
            return this;
        },

        extend: function(id)
        {
            var args = [];
            for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
            _masada.prototype[id].apply(this, args)
            return this;
        },

        hide: function()
        {
            this.element.style.display = 'none';
            return this;
        },

        show: function()
        {
            this.element.style.display = 'block';
            return this;
        },

        scrollLeft: function(text)
        {
            return this.element.scrollLeft;
        },

        scrollTop: function(text)
        {
            return this.element.scrollTop;
        },

        width: function()
        {
            return this.element.offsetWidth;
        },

        height: function()
        {
            return this.element.offsetHeight;
        },

        addEvent: function(type, handler)
        {
            if (this.element.addEventListener)
                this.element.addEventListener(type, handler, false);
            else if (this.element.attachEvent)
                this.element.attachEvent("on" + type, handler);
        },

        mousemove: function(handler)
        {
            this.addEvent('mousemove', handler);
            return this;
        },

        mouseover: function(handler)
        {
            this.addEvent('mouseover', handler);
            return this;
        },

        mouseout: function(handler)
        {
            this.addEvent('mouseout', handler);
            return this;
        },

        css: function(style, value)
        {
            this.element.style[style] = value;
            return this;
        },

        clock: function()
        {
            var This = this;
            var update = function()
            {
                This.element.innerHTML = new Date().toLocaleString();
            }
            update();
            setInterval(update, 1000);
            return this;
        },

        parseJSON: function(s)
        {
            if (JSON.parse) return JSON.parse(s);
            else return eval('(' + s + ')');
        },

        browser: function()
        {
            this.type = null;
            var agent = navigator.userAgent;
            if (agent.indexOf("MSIE") != -1) this.type = 'IE';
            else if (agent.indexOf("Firefox") != -1) this.type = 'FF';
            else if (agent.indexOf("Navigator") != -1) this.type = 'NV';
            else if (agent.indexOf("Opera") != -1) this.type = 'OP';
            else this.type = 'UK';
            return this;
        },

        insertScript: function(Id, Text)
        {
            if (document.getElementById(Id)) return;
            var script = document.createElement("script");
            //script.setAttribute('id', Id);
            script.setAttribute('type', 'text/javascript');

            if (script.canHaveChildren)
            {
                script.appendChild(document.createTextNode(Text));
            }
            else
            {
                script.text = Text;
            }
            document.body.appendChild(script);
        },

        datePicker: function(initDate)
        {
            var This = this;
            var OnComplete = null;
            var isDisable = false;
            var Mode = 'Calendar';
            var TextField = null;
            var Container = null;
            var DayCells = new Array(32);
            var ColumnWidth = 30;
            var WkDayLblHeight = 20;
            var DateCellHeight = 100;
            var CurrentDate = '';
            var CellTextAlign = 'center';
            var CellVerticalAlign = 'middle';

            if (arguments.length > 0) CurrentDate = initDate;

            var SetStyle = function(control, fontSize, fontWeight, color, backgroundColor)
            {
                control.style.fontFamily = FontFamily;
                control.style.fontSize = fontSize;
                if (fontWeight.length != 0) control.style.fontWeigh = fontWeight;
                control.style.color = color;
                control.style.backgroundColor = backgroundColor;
            }

            var MonthLabel = ['January', 'February', 'March', 'April', 'May', 'June',
                'July', 'August', 'September', 'October', 'November', 'December'];
            var DayLabel = null;
            var FontFamily = 'Tahoma, Arial, Helvetica, sans-serif';



            var pickerDiv = $$("div");
            pickerDiv.style.position = 'absolute';
            pickerDiv.style.zIndex = 10000;
            pickerDiv.style.display = 'none';
            pickerDiv.style.borderStyle = 'solid';
            pickerDiv.style.borderWidth = '1px';

            var CalTbl = pickerDiv.appendChild($$('table'));
            SetStyle(CalTbl, '12px', '', '#505050', '#dddddd');
            CalTbl.cols = '7';
            CalTbl.style.textAlign = 'center';
            CalTbl.style.border = '1px solid #ababab';


            DayLabel = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
            ColumnWidth = 10;
            WkDayLblHeight = 10;
            WkDayLblFontWeight = 'normal';
            DateCellHeight = 10;
            CellTextAlign = 'center';
            CellVerticalAlign = 'middle';

            var CalBody = CalTbl.appendChild($$('tbody'));
            document.body.appendChild(pickerDiv);


            this.bindTo = function(parent)
            {
                parent.value = Value;
                parent.appendChild(Container);
                return This;
            }

            var DisplayCalendar = function()
            {
                if (isDisable) return;
                if (pickerDiv.style.display == 'none')
                {
                    if (Container)
                    {
                        var Loc = GetPosition();
                        pickerDiv.style.left = Loc[0];
                        pickerDiv.style.top = Loc[1];
                    }
                    CurrentDate = TextField.value;
                    var theDate = null;
                    if (checkDate(CurrentDate))
                    {
                        CurrentDate = TextField.value.replace(/-/g, '/');
                        CurrentDate = CurrentDate.replace(/-/g, '.');
                        theDate = new Date(CurrentDate);
                    }
                    else
                        theDate = new Date();

                    BuildCalendar(theDate.getFullYear(), theDate.getMonth());
                    var day = theDate.getDate();
                    DayCells[day].onmouseout = function()
                    {
                        this.style.backgroundColor = '#777777';
                        this.style.borderColor = '#777777';
                        this.style.cursor = 'pointer';
                        this.style.color = 'white';
                    }
                    DayCells[day].onmouseout();
                    pickerDiv.style.display = '';
                }
                else
                {
                    if (Container)
                    {
                        if (CurrentDate.length > 0) TextField.value = CurrentDate;
                    }
                    pickerDiv.style.display = 'none';
                    DeleteCalendar();
                }
            }

            var Value = function(value)
            {
                if (arguments.length == 1)
                {
                    CurrentDate = value;
                    TextField.value = value;
                    return This;
                    //if (This.OnChange != 'undefined' && This.OnChange) This.OnChange(CurrentDate);
                }
                else return CurrentDate;
            }

            var GetPosition = function()
            {
                var x = y = 0;
                var obj = Container;
                var Browser = $().browser.type;
                while (obj.offsetParent != null)
                {
                    x += obj.offsetLeft;
                    y += obj.offsetTop;
                    obj = obj.offsetParent;
                }
                if (Browser == 'IE' && Container.parentNode.style.position == '')
                {
                    x += 10;
                    y += 12;
                }
                y += Container.offsetHeight;
                return [x + 'px', y + 'px'];
            }

            var DeleteCalendar = function()
            {
                while (CalBody.hasChildNodes())
                {
                    CalBody.removeChild(CalBody.firstChild);
                }
            }

            var CalendarHeader = function(date)
            {
                var HdrTbl = new Table();
                HdrTbl.style.width = '100%';
                var Row = HdrTbl.AddRow();
                Row.style.backgroundColor = '#dddddd';
                Row.style.border = 'none';

                var LftArw = Row.AddCell();
                LftArw.style.width = '10px';
                LftArw.appendChild(getButton(date, -1, "&lt;"));

                var TitleDiv = $$('div');
                TitleDiv.style.fontSize = '11px';
                TitleDiv.style.fontWeight = 'bold';
                TitleDiv.style.color = 'black';
                TitleDiv.innerHTML = MonthLabel[date.getMonth()] + " " + date.getFullYear();
                var TitleCell = Row.AddCell().appendChild(TitleDiv);

                var RgtArw = Row.AddCell();
                RgtArw.style.width = '10px';
                RgtArw.appendChild(getButton(date, 1, "&gt;"));

                this.BindTo = function(parent)
                {
                    parent.appendChild(HdrTbl);
                    return this;
                }
            }

            var CalendarFooter = function()
            {
                var HdrTbl = new Table();
                HdrTbl.style.width = '100%';
                var Row = HdrTbl.AddRow();
                Row.style.border = 'none';
                var Footer = Row.AddCell();
                SetStyle(Footer, '10px', 'bold', 'black', '#dddddd');

                Footer.innerHTML = 'Today: ' + ExtractDate(new Date());

                this.BindTo = function(parent)
                {
                    parent.appendChild(HdrTbl);
                    return this;
                }
            }

            var BuildCalendar = function(year, month)
            {
                var CalDay = new Date(year, month, 1);

                var HdrCell = CalBody.appendChild($$('tr')).appendChild($$('td'));
                HdrCell.colSpan = '7';
                new CalendarHeader(CalDay).BindTo(HdrCell);

                var WeekRow = CalBody.appendChild($$('tr'));
                var DayCell = null;
                for (i = 0; i < 7; i++)
                {
                    var Cell = WeekRow.appendChild($$('td'));
                    Cell.style.backgroundColor = '#204070';
                    Cell.style.width = ColumnWidth + 'px';
                    Cell.style.height = WkDayLblHeight + 'px';
                    Cell.style.fontWeight = WkDayLblFontWeight;
                    Cell.style.color = 'white';
                    Cell.innerHTML = DayLabel[i];
                }

                WeekRow = CalBody.appendChild($$('tr'));
                WeekRow.style.backgroundColor = 'White';
                WeekRow.style.borderStyle = 'none';
                WeekRow.style.borderWidth = '0px';

                for (var i = 0; i < CalDay.getDay(); i++) // leading blanks
                {
                    DayCell = WeekRow.appendChild($$('td'));
                    DayCell.style.width = ColumnWidth + 'px';
                    DayCell.style.height = DateCellHeight + 'px';
                    DayCell.innerHTML = '&nbsp';
                }
                do
                {
                    var DayOfMonth = CalDay.getDate();
                    DayCells[DayOfMonth] = DayCell = WeekRow.appendChild($$('td'));
                    DayCell.style.width = ColumnWidth + 'px';
                    DayCell.style.height = DateCellHeight + 'px';
                    DayCell.style.border = '1px solid';
                    DayCell.DateString = ExtractDate(CalDay);
                    DayCell.innerHTML = DayOfMonth.toString();
                    DayCell.style.textAlign = CellTextAlign;
                    DayCell.style.verticalAlign = CellVerticalAlign;

                    DayCell.onmouseover = function()
                    {
                        this.style.backgroundColor = '#ffff00';
                        this.style.borderColor = '#888888';
                        this.style.color = 'red';
                    }

                    DayCell.onclick = function()
                    {
                        CurrentDate = this.DateString;
                        DisplayCalendar();
                        if (This.OnChange != 'undefined' && This.OnChange) This.OnChange(CurrentDate);
                    }
                    DayCell.onmouseout = function()
                    {
                        this.style.backgroundColor = '#fcfcfc';
                        this.style.borderColor = '#fcfcfc';
                        this.style.cursor = 'pointer';
                        this.style.color = 'black';
                    }
                    DayCell.onmouseout();
                    if (CalDay.getDay() == 6)
                    {
                        WeekRow = CalBody.appendChild($$('tr'));
                    }
                    CalDay.setDate(CalDay.getDate() + 1);
                }
                while (CalDay.getDate() > 1)

                if (CalDay.getDay() > 0) // trailing blanks
                {
                    for (i = 6; i > CalDay.getDay(); i--)
                    {
                        DayCell = WeekRow.appendChild($$('td'));
                        DayCell.style.width = ColumnWidth + 'px';
                        DayCell.style.height = DateCellHeight + 'px';
                        DayCell.innerHTML = '&nbsp';
                    }
                }

                var FtrCell = CalBody.appendChild($$('tr')).appendChild($$('td'));
                FtrCell.colSpan = '7';
                new CalendarFooter().BindTo(FtrCell);
            }

            var disabled = function(state)
            {
                TextField.disabled = state;
                isDisable = state;
            }

            var getButton = function(date, adjust, label)
            {
                var Month = (date.getMonth() + adjust) % 12;
                var Year = date.getFullYear() + parseInt((date.getMonth() + adjust) / 12);
                if (Month < 0)
                {
                    Month += 12;
                    Year += -1;
                }
                var btn = $$('button');
                SetStyle(btn, '10px', 'bold', 'gray', '#d8e8ff');
                btn.style.padding = '0px';
                btn.onclick = function() { DeleteCalendar(); BuildCalendar(Year, Month); }
                btn.innerHTML = label;
                return btn;
            }

            var ExtractDate = function(theDate)
            {
                var sMonth = (theDate.getMonth() + 1).toString();
                if (sMonth.length == 1) sMonth = '0' + sMonth;
                var sDay = theDate.getDate().toString();
                if (sDay.length == 1) sDay = '0' + sDay;
                return sMonth + '/' + sDay + '/' + theDate.getFullYear();
            }

            var checkDate = function(date)
            {
                var delim1 = date.indexOf('/');
                var delim2 = date.lastIndexOf('/');
                if (delim1 != -1 && delim2 != -1)
                {
                    var month = parseInt(date.substring(0, delim1));
                    var day = parseInt(date.substring((delim1 + 1), delim2));
                    var year = parseInt(date.substring(delim2 + 1));
                    if (year > 49 && year < 100) year += 1900;
                    else if (year >= 0 && year < 50) year += 2000;
                    if (!(isNaN(month) || isNaN(day) || isNaN(year)))
                        return ExtractDate(new Date(year, month - 1, day));
                }
                return false;
            }
            Container = this.element;
            Container.style.borderStyle = 'inset';
            Container.style.backgroundColor = 'white';
            Container.style.borderWidth = '2px';
            Container.style.width = '90px';

            var tbl = Container.appendChild($$("table"));
            tbl.style.borderColor = '#204070';
            tbl.style.borderWidth = '0px';
            tbl.style.width = '100%';
            tbl.style.height = '100%';
            tbl.style.borderCollapse = 'collapse';

            var PickerTbody = tbl.appendChild($$("tbody"));
            var NewRow = $$("tr");

            var left = $$("td");
            left.style.width = '100%';
            TextField = $$("input");
            TextField.type = 'text';
            TextField.style.width = '68px';
            TextField.style.borderStyle = 'none';
            TextField.borderCollapse = 'collapse';
            TextField.style.fontSize = '10pt';
            TextField.style.height = '14px';
            TextField.style.lineHeight = '14px';
            TextField.value = CurrentDate;
            left.appendChild(TextField);
            NewRow.appendChild(left);

            var right = $$("td");
            right.style.padding = 0;
            right.style.margin = 0;
            var Image = $$('img');
            Image.src = 'Masada/Images/SelectArrow.gif';
            Image.onclick = DisplayCalendar;
            Image.style.height = '18px';
            right.appendChild(Image);
            NewRow.appendChild(right);

            PickerTbody.appendChild(NewRow);

            this.Value = Value;
            this.disabled = disabled;
            var Table = function()
            {
                var This = this;
                var Table = $$('table');
                var Body = Table.appendChild($$('tbody'));

                var AddCell = function(row, width)
                {
                    var cell = row.appendChild($$('td'));
                    if (arguments.length > 1) { alert(width); cell.style.width = width; }
                    return cell;
                }

                Table.AddRow = function()
                {
                    var Row = Body.appendChild($$('tr'));
                    Row.AddCell = function(width)
                    {
                        var cell = this.appendChild($$('td'));
                        if (arguments.length == 1) { cell.style.width = width; }
                        return cell;
                    }
                    return Row;
                }
                return Table;
            }
            return this;
        },

        textbox: function(label)
        {
            var Tbx = $$('input');
            Tbx.type = 'text';
            if (arguments.length > 1) Tbx.style.width = arguments[1] + 'px';
            if (arguments.length > 2) Tbx.style.height = arguments[2] + 'px';

            this.Style = function(name, value)
            {
                Tbx.style[name] = value;
                return This;
            }
            this.Element = Tbx;
            return this;
        },

        button: function(label)
        {
            var Btn = $$('input');
            Btn.type = 'button';
            Btn.value = label;
            if (arguments.length > 1) Btn.style.width = arguments[1] + 'px';
            if (arguments.length > 2) Btn.style.height = arguments[2] + 'px';

            this.Style = function(name, value)
            {
                Lbl.style[name] = value;
                return This;
            }
            this.Element = Btn;
            return this;
        },

        label: function(label, width, height)
        {
            var This = this;
            var Lbl = $$('Label');
            Lbl.innerHTML = label;
            if (arguments.length > 1) Lbl.style.width = arguments[1] + 'px';
            if (arguments.length > 2) Lbl.style.height = arguments[2] + 'px';

            this.Style = function(name, value)
            {
                Lbl.style[name] = value;
                return This;
            }
            this.Element = Lbl;
            return this;
        },
        ddl: function()
        {
            var Ddl = this.element;
            var TextName = null;
            var ValueName = null;
            var Handler = null;
            var Arg = 0;

            this.callback = function(handler)
            {
                Handler = handler;
                return this;
            }

            this.add = function(text, value)
            {
                var o = $$('option');
                o.text = text;
                if (arguments.length > 1) o.value = value;
                Ddl.options.add(o);
                return this;
            }

            this.clear = function()
            {
                Ddl.options.length = 0;
                return this;
            }

            this.load = function(query)
            {
                var TextName = arguments[1];
                var ValueName = TextName;
                if (arguments.length > 2) ValueName = TextName;
                var ListData = new RecordSet();
                var OnComplete = function(rtn)
                {
                    for (var i = 0; i < rtn.RowCount; i++)
                    {
                        this.add(rtn.GetValue(i, TextName), rtn.GetValue(i, ValueName));
                    }
                }
                ListData.Load(query, OnComplete);
                if (Handler != null) Handler(This);
                return this;
            }

            this.value = function(value)
            {
                var Options = Ddl.options;
                if (arguments.length)
                {
                    for (var i = 0; i < Options.length; i++)
                    {
                        var Option = Options[i];
                        var Value = Option.value.trim();
                        if (Value.length == 0) Value = Option.text.trim();
                        if (Value == value)
                        {
                            Ddl.selectedIndex = i;
                            return;
                        }
                    }
                }
                else
                {
                    if (Ddl.selectedIndex > -1)
                    {
                        return Ddl[Ddl.selectedIndex].value;
                    }
                    return '';
                }
            }

            this.index = function(idx)
            {
                Ddl.selectedIndex = idx;
                return this;
            }

            this.style = function(name, value)
            {
                Lbl.style[name] = value;
                return this;
            }
            return this;
        },

        panel: function(id)
        {
            var This = this;
            var Id = this.PanelId = id;
            if (!this.element) this.element = $$('div')
            var Container = this.Element = this.element;

            var config = { height: 0, header: { height: 0 }, body: { height: 0 }, footer: { height: 0} };
            config.id = Id;

            var Header = this.header = Container.appendChild($$('div'));
            var Body = this.body = Container.appendChild($$('div'));
            var Footer = this.footer = Container.appendChild($$('div'));

            this.Resources = {}
            this.IsLoaded = false;
            this.IsDirty = null;
            this.DirtyCount = 0;
            var BorderWidth = 0;

            var Type = 0;
            var Label = "";

            var Flags = {}
            Flags.ReadOnly = 1;
            Flags.WriteOnly = 2;
            Flags.ReadWrite = 4;
            Flags.UseInner = 8;
            Flags.Label = 16;

            this.BindTo = function(parent) { parent.appendChild(Container); return This; }

            this.Add = function(path, name, callback)
            {
                var OnLoadComplete = function(rtn)
                {
                    This.Resources[path] = rtn;
                    var container = Build(rtn, name);
                    if (callback) callback(container);
                }
                $().GetAsciiResource(path, OnLoadComplete);
                return This;
            }

            this.config = function(cfg)
            {
                try
                {
                    if (arguments.length != 1 || typeof (config) != 'object') throw new Error("configuration missing or not an object");
                    deepCopy(cfg, config)

                    if (config.height) Height = config.height;
                    if (config.width) This.element.style.width = config.width + 'px';
                    if (config.bgColor) Body.style.backgroundColor = config.bgColor;
                    if (config.borderWidth) BorderWidth = config.borderWidth;
                    if (config.header.height) Header.style.height = config.header.height + 'px';
                    if (config.body.bgColor) Body.style.backgroundColor = config.body.bgColor;
                    if (config.body.borderColor) Body.style.borderColor = config.header.borderColor;
                    if (config.body.borderStyle) Body.style.borderStyle = config.body.borderStyle;
                    if (config.body.borderWidth) Body.style.borderWidth = config.body.borderWidth;
                    if (config.footer.height) Footer.style.height = config.footer.height + 'px';

                    var bodyHeight = config.height - config.header.height - config.footer.height;
                    if (bodyHeight > 0)
                        Body.style.height = bodyHeight + 'px';
                    else
                        throw new Error("insufficient panel height");
                }
                catch (e)
                {
                    throw new Error("(panel.config) - Panel:'" + Id + "', " + e.description);
                }
                finally
                {
                    return This;
                }
            }

            var isEmpty = function(ob)
            {
                for (var i in ob) { return false; }
                return true;
            }

            var deepCopy = function(p, c)
            {
                var c = c || {};
                for (var i in p)
                {
                    if (typeof p[i] === 'object')
                    {
                        if (typeof (c[i]) == 'undefined') c[i] = (p[i].constructor === Array) ? [] : {};
                        deepCopy(p[i], c[i]);
                    }
                    else c[i] = p[i];
                }
                return c;
            }

            this.render = function(label)
            {
                var callback = function(rtn)
                {
                    var obj = JSON.parse(rtn);
                    obj.id = id;
                    if (obj.status != "OK")
                    {
                        alert('Error rendering panel: ' + id);
                        return;
                    }
                    if (config.height > 0 && config.width > 0)
                    {
                        if (config.header.height > 0)
                        {
                            This.InsertHeader(config.header.height);
                            Header.style.background = "url(masada/resource.aspx?graphic=" + validate(obj.headerId) + ") no-repeat";
                        }
                        if (config.footer.height > 0)
                        {
                            This.InsertFooter(config.footer.height);
                            Footer.style.background = "url(masada/resource.aspx?graphic=" + validate(obj.footerId) + ") no-repeat";
                        }
                    }
                }
                $().renderPanel(JSON.stringify(config), callback);
                return This;
            }

            this.InsertHeader = function(height)
            {
                Header.style.height = height + 'px';
                Header.style.overflow = 'hidden';
                This.InsertElement(Header);
            }

            this.InsertFooter = function(height)
            {
                Footer.id = 'Footer';
                Footer.style.height = height + 'px';
                Footer.style.backgroundColor = 'orange';
                This.InsertElement(Footer);
                return Footer;
            }

            var Control = function() { }
            Control.prototype.Flags = Flags;
            Control.prototype.Value = function(value)
            {
                if (arguments.length > 0)
                {
                    switch (this.Element.type)
                    {
                        case 'button':
                            {
                            }
                        case 'checkbox':
                        case 'file':
                        case 'hidden':
                        case 'image':
                        case 'password':
                        case 'radio':
                        case 'reset':
                            break;
                        case 'select-one':
                        case 'select-multiple':
                            {
                                var Ctrl = this.Element;
                                //if (value.length > 0) SetDdlOption(this.Element,value);
                                if (!(value == null || typeof (value) == 'undefined'))
                                {
                                    for (var i = 0; i < Ctrl.options.length; i++)
                                    {
                                        if (Ctrl.options[i].value == value)
                                        {
                                            Ctrl.selectedIndex = i;
                                            if (this.OnUpdate != 'undefined' && this.OnUpdate) this.OnUpdate();
                                            return;
                                        }
                                    }
                                    var option = document.createElement("OPTION");
                                    option.text = value;
                                    option.value = value;
                                    if (value.length > 0)
                                    {
                                        //option.text += '(not in list)';
                                        Ctrl.options.add(option);
                                        Ctrl.selectedIndex = i;
                                    }
                                    else
                                    {
                                        Ctrl.options.add(option, 0);
                                        Ctrl.selectedIndex = 0;
                                    }
                                }
                                break;
                            }
                        case 'submit':
                            break;
                        case 'text':
                        case 'textarea':
                            this.Element.value = value;
                            break;
                        default:
                            {   // span
                            }
                    }
                    if (this.OnUpdate != 'undefined' && this.OnUpdate) this.OnUpdate();
                }
                else
                {
                    switch (this.Element.type)
                    {
                        case 'button':
                            {
                            }
                        case 'checkbox':
                        case 'file':
                        case 'hidden':
                        case 'image':
                        case 'password':
                        case 'radio':
                        case 'reset':
                            break;
                        case 'select-one':
                        case 'select-multiple':
                            var Ctrl = this.Element;
                            if (Ctrl.selectedIndex < 0) return "";
                            if (this.IoFlags == this.Flags.UseInner)
                                return Ctrl[Ctrl.selectedIndex].innerHTML;
                            else
                                return Ctrl[Ctrl.selectedIndex].value;
                            break;
                        case 'submit':
                            break;
                        case 'text':
                        case 'textarea':
                            return this.Element.value;
                        default:
                            {   // span
                                return this.Element.innerHTML;
                            }
                    }
                }
            }

            this.InsertElement = function(element)
            {
                var Id = element.id;
                if (Id && Id != 'undefined')
                {
                    var Ctrl = new Control();
                    Ctrl.IsDirty = false;
                    if (element.type && element.type == 'text/javascript') { alert(element.type); return; }
                    if (element.className)
                    {
                        var ClassName = element.className;
                        if (ClassName.substr(0, 4) == 'link')
                        {
                            var Class = element.className.split(':');
                            if (Class[1] == 'disabled') return;
                            element.style.color = 'blue';
                            element.onclick = function()
                            {
                                if (This.EventHandler) (This.EventHandler(Class[1]));
                                $m().LogEvent(Id, This.PanelId, Class[1], null);
                            }

                            element.onmouseover = function()
                            {
                                var Style = this.style;
                                Style.cursor = 'hand';
                                Style.textDecoration = 'underline';
                            }

                            element.onmouseout = function()
                            {
                                var Style = this.style;
                                Style.cursor = 'pointer';
                                Style.textDecoration = 'none';
                            }
                        }
                    }

                    Ctrl.Element = element;
                    Ctrl.IoFlag = Ctrl.Flags.ReadWrite;
                    //if (This[Id]) alert('(HtmlPanel.InsertElement) Object already exists');
                    This[Id] = Ctrl;
                    // element.removeAttribute(element.id);
                }
            }

            this.Clone = function()
            {
                return $().panel(This.PanelId).load();
            }

            this.Clear = function()
            {
                var ioType = 3;
                for (var p in This)
                {
                    if (This.hasOwnProperty(p))
                    {
                        var Obj = This[p];
                        if (Obj == null || typeof (Obj) != 'object' || Obj.IoFlag == null) { continue; }
                        if (Obj.IoFlag != 0)
                        {
                            Obj.Value('');
                        }
                    }
                }
                return This;
            }

            this.ExtractXmlData = function(rows)
            {
                var Fields = rows.selectSingleNode("Row[@RowNbr='" + '0' + "']/Fields");
                var Values = Fields.selectNodes("Field");
                for (var i = 0; i < Values.length; i++)
                {
                    var ChildNode = Values[i].firstChild;
                    if (ChildNode)
                    {
                        var Id = Values[i].attributes.getNamedItem("Id").firstChild.nodeValue;
                        if (typeof (This[Id]) == 'undefined') continue;
                        var Value = ChildNode.nodeValue;
                        var Obj = This[Id];
                        if (Obj) { Obj.Value(Value); }
                    }
                }
                return This;
            }

            this.ExtractFormData = function(rows)
            {
                This.DirtyCount = 0;
                This.DirtyFlag = false;

                var Fields = rows.selectSingleNode("Row[@RowNbr='" + '0' + "']/Fields");
                var Values = Fields.selectNodes("Field");
                for (var i = 0; i < Values.length; i++)
                {
                    var ValueNode = Values[i];
                    var ChildNode = ValueNode.firstChild;
                    if (ChildNode == null) ChildNode = ValueNode.appendChild(rows.ownerDocument.createTextNode(""));
                    var Id = ValueNode.attributes.getNamedItem("Id").firstChild.nodeValue;
                    var Obj = This[Id];
                    if (Obj)
                    {
                        var Value = Obj.Value();
                        if (ChildNode.nodeValue != Value)
                        {
                            This.IsDirty = true;
                            This.DirtyCount++;
                            ValueNode.setAttribute('IsDirty', 'True');
                            ValueNode.firstChild.nodeValue = Value;
                        }
                    }
                }
                return This;
            }

            this.List = function()
            {
                var List = [];
                for (var property in This)
                {
                    var Obj = This[property];
                    if (Obj && typeof (Obj.SourceName) == 'string')
                    {
                        //alert(Obj.SourceName);
                        List.push(Obj);
                    }
                }
                return List;
            }

            this.Disabled = function(state)
            {
                for (var property in This)
                {
                    if (property.substr(0, 8) == 'function') continue;
                    var obj = This[property];
                    var Id = obj.id;
                    if (Id && Id.length > 0)
                    {
                        obj.disabled = state;
                    }
                }
            }

            var Build = function(html, name)
            {
                var body = Body.appendChild($$('div'));
                body.id = name;
                body.style.display = 'none';
                This.InsertElement(body);
                body.innerHTML = html;

                var Scripts = body.getElementsByTagName('script');
                for (var i = 0; i < Scripts.length; i++)
                {
                    var Panel = Scripts[i];
                    Panel.parentNode.removeChild(Panel);
                    $().insertScript(Panel.id, Panel.innerHTML);
                }

                var descend = function(node)
                {
                    //if (node.nodeType == 3) return;    // node.TEXT_NODE
                    if (node.hasChildNodes())
                    {
                        var Elements = node.childNodes;
                        for (var i = 0; i < Elements.length; i++)
                        {
                            This.InsertElement(Elements[i]);
                            descend(Elements[i]);
                        }
                    }
                }

                descend(body);
                try
                {
                    eval(name + '.call(This);');
                }
                catch (e)
                {
                    // no method 
                    if (name == 'Festival_2010') alert('Failed calling construction of ' + name + '\r\n' + e.message);

                }
                body.style.display = 'block';
                return body;
            }

            this.load = function()
            {
                var Callback = null;
                if (arguments.length == 1) Callback = arguments[0];
                This.IsLoaded = true;
                var Id = This.PanelId;

                var OnLoadComplete = function(rtn)
                {
                    This.Resources[Id] = rtn;
                    Build(rtn, Id)
                    if (This.Init) This.Init(rtn);

                    if (Callback) Callback(This);
                }

                if (typeof (This.Resources[Id]) == 'undefined')
                {
                    $().GetAsciiResource(Id, OnLoadComplete);
                }
                else
                {
                    Build(This.Resources[Id], Id)
                    if (Callback) Callback(This);
                }
                return This;
            }

            this.Remove = function(container)
            {
                if (container)
                {
                    while (container.hasChildNodes())
                    {
                        container.removeChild(container.firstChild);
                    }
                    container.parentNode.removeChild(container);
                }
                return This;
            }
            return this;
        },
        ContentManager: function()
        {
            var This = this;
            var Resources = {};

            var Handlers = {};

            this.Register = function(id, method)
            {
                Handlers[id] = method;
            }

            this.MessageInQue = function(msg)
            {
                This.Message(msg)
            }

            this.AddManager = function(w, h)
            {
                var Mgr = new Manager(w, h);
                Mgr.AddPanel = function(id)
                {
                    resource = {}
                    resource.IsLoaded = false;
                    resource.ContentMgr = Mgr;
                    Resources[id] = resource;
                    var Instance = resource.Instance = $().panel(id);
                    resource.ContentMgr.Insert(Instance);
                    This[id] = Instance;
                    Instance.Manager = This;
                    Instance.PanelMgr = Mgr;
                    return Instance;
                }
                return Mgr;
            }

            this.Message = function(id)
            {
                if (Handlers[id])
                {
                    Handlers[id]();
                    return;
                }
                var Resource = Resources[id];
                if (!Resource)
                {
                    alert('(ContentManager)Resource: ' + id + ' not found');
                    return;
                }
                var Instance = Resource.Instance;
                var Epilog = function()
                {
                    var LastPanel = Resource.ContentMgr.CurrentPanel2(Instance);
                    if (LastPanel && LastPanel.Hide) LastPanel.Hide();
                    if (Instance && Instance.Show) Instance.Show();
                }
                if (!Instance.IsLoaded)
                {
                    var OnLoadComplete = function()
                    {
                        Epilog();
                    }
                    Instance.load(OnLoadComplete);
                }
                else
                    Epilog();
            }

            var Manager = function(width, height)
            {
                var ThisManager = this;
                this.Message = This.Message;
                this.Width = width;
                this.Height = height;
                var Width = width + 'px';
                var Height = height + 'px';
                var Left = '0px';
                var Top = '0px';

                var CurrentDiv = null;
                var count = 0;
                var Divs = [];
                Divs.length = 0;

                var Properties = function()
                {
                    this.Name = null;
                    this.IsDisabled = false;
                    this.Overflow = 'hidden';
                    this.Visible = function(state) { }
                    this.Clear = function() { ClearDiv(this); }
                }

                var Container = this.Element = $$('Div');

                this.BindTo = function(parent) { parent.appendChild(Container); return ThisManager; }

                Container.style.cssText = "";
                Container.style.width = Width;
                Container.style.height = Height;
                Container.style.top = Top;
                Container.style.left = Left;
                Container.style.textAlign = 'left';
                Container.style.position = 'relative';
                Container.style.overflow = 'hidden';
                Container.style.margin = '0px';
                Container.style.padding = '0px';
                //Container.style.zIndex = 1000;

                var InsertNew = function(id, overflow)
                {
                    var div = $$('Div');
                    div.id = id;
                    div.Properties = new Properties();
                    if (arguments.length == 2) div.Properties.Overflow = overflow;
                    if (Divs.length == 0)
                    {
                        CurrentDiv = div;
                    }
                    InitializeDiv(div);
                    Divs.push(div);
                    Container.appendChild(div);
                    return div;
                }

                var Insert = function(panel)
                {
                    var div = panel.Element;
                    div.Properties = new Properties();
                    if (Divs.length == 0)
                    {
                        CurrentDiv = div;
                    }
                    InitializeDiv(div);
                    Divs.push(div);
                    Container.appendChild(div);
                    return panel;
                }

                var Clear = function()
                {
                    DeleteChildren(Container);
                }

                var Find = function(id)
                {
                    for (var i = 0; i < Divs.length; i++)
                    {
                        if (Divs[i].id == id) return Divs[i];
                    }
                    return null;
                }

                var InitializeDiv = function(div)
                {
                    div.style.position = 'absolute';
                    div.style.overflow = div.Properties.Overflow;
                    div.style.display = 'none';
                    div.style.left = 0;
                    div.style.top = 0;
                }

                var CurrentPanel = function(div)
                {
                    if (arguments.length == 0 && CurrentDiv) return CurrentDiv;
                    if (div.Properties.IsDisabled) return;
                    div.style.display = 'block';

                    if (CurrentDiv && div != CurrentDiv)
                    {
                        CurrentDiv.style.display = 'none';
                        CurrentDiv = div;
                    }
                }
                var LastPanel = null;
                var CurrentPanel2 = function(panel)
                {
                    var SavePanel = LastPanel;
                    LastPanel = panel;
                    var div = panel.Element;
                    //if (arguments.length == 0 && CurrentDiv) return CurrentDiv;
                    //if (div.Properties.IsDisabled) return;
                    div.style.display = 'block';

                    if (CurrentDiv && div != CurrentDiv)
                    {
                        CurrentDiv.style.display = 'none';
                        CurrentDiv = div;
                    }
                    return SavePanel;
                }

                Container.style.visibility = 'visible';

                this.Find = Find;
                this.Insert = Insert;
                this.InsertNew = InsertNew;
                this.CurrentPanel = CurrentPanel;
                this.CurrentPanel2 = CurrentPanel2;
            }
            return this;
        },
        popup: function(target)
        {
            var container = this;
            var Margin = 10;
            this.element = document.createElement('div');
            this.css('position', 'absolute');
            this.css('zIndex', '50000');
            this.css('padding', '3px');
            this.css('backgroundColor', '#777');
            this.css('color', 'black');
            this.css('fontSize', '10pt');
            this.hide();

            this.target = function(_target)
            {
                var target = $(_target);
                var getMousePosition = function(e)
                {
                    var pos = { x: 0, y: 0 };
                    if (!e) var e = window.event;
                    if (e.pageX || e.pageY)
                    {
                        pos.x = e.pageX;
                        pos.y = e.pageY;
                    }
                    else if (e.clientX || e.clientY)
                    {
                        pos.x = e.clientX + document.body.scrollLeft
			                + document.documentElement.scrollLeft;
                        pos.y = e.clientY + document.body.scrollTop
			                + document.documentElement.scrollTop;
                    }
                    return pos;
                }
                target.mousemove(function(e)
                {
                    var pos = getMousePosition(e);
                    x = pos.x + 10;
                    y = pos.y + 10;
                    // var Pos = AdjustPos(x, y);
                    container.css('left', x + 'px');
                    container.css('top', y + 'px');
                });
                target.mouseover(function(e) { container.show(); });
                target.mouseout(function(e) { container.hide(); });
                return this;
            }

            this.message = function(msg)
            {
                this.html(msg);
                return this;
            }
            return this;
        },

        ajax: function()
        {
            var self = this;
            var url = 'masada/ajax.aspx';
            var Namespace = null;

            if (arguments.length > 0)
            {
                url = '/' + arguments[0];
            }
            var Callback = null;

            var PostData = '';

            var Call = function(name, args)
            {
                var xmlHttp;
                if (window.ActiveXObject) xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
                else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function()
                {
                    if (xmlHttp.readyState == 4)
                    {
                        if (xmlHttp.status == 200 || xmlHttp.status == 0)
                        {
                            if (Callback) Callback(xmlHttp.responseText);
                            Callback = null;
                        }
                        else
                        {
                            alert("Ajax error calling interface: " + url + "\n" +
                            "Method: " + name + "\n" +
                            "Reason: " + xmlHttp.status);
                        }
                    }
                }
                PostData = 'module=Tip';
                PostData += '&method=' + name;


                var Length = args.length - 1;
                for (var i = 0; i < Length; i++)
                {
                    PostData += '&arg' + i.toString() + '=' + args[i];
                }
                Callback = args[Length];
                xmlHttp.open('POST', url, false);
                xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xmlHttp.send(PostData);
            }

            this.Add = function(method)
            {
                var target = _masada.prototype;
                if (Namespace != 'masada') target = window[Namespace];
                target[method] = function()
                {
                    Call(method, arguments);
                }
            }

            this.init = function(callback)
            {
                var testback = function(rtn)
                {
                    var obj = $.f.parseJSON(rtn);
                    if (obj.Status == 'Error')
                    {
                        alert('Error, : ' + obj.Message);
                        return;
                    }
                    Namespace = obj.ns;
                    if (typeof (Namespace) != 'undefined')
                    {
                        if (typeof (window[Namespace]) == 'undefined')
                            window[Namespace] = {}
                    }
                    else
                    {
                        alert('Error, namespace not specified');
                        return;
                    }

                    for (method in obj)
                    {
                        if (method == 'ns') continue;
                        if (method.substr(0, 2) == 'm_')
                        {
                            self.Add(method.substr(2));
                        }
                        else
                        {
                            var theplacee = window[Namespace];
                            theplacee[method] = obj[method];
                        }
                    }
                    callback();
                }
                Call('discovery', [testback]);
                return this;
            }
            return this;
        },

        verticalMenu: function(menuNode, styleNode, onMenuClick)
        {
            var This = this;
            var OnMenuClick = onMenuClick;
            var MenuNode = arguments[0];


            var MenuStyle = new $.f.style(styleNode.childNodes[0]);
            var SubMenuStyle = new $.f.style(styleNode.childNodes[1]);
            var MouseOverStyle = new $.f.style(styleNode.childNodes[2]);
            var MouseOutStyle = new $.f.style(styleNode.childNodes[3]);
            var ShowStyle = new $.f.style(styleNode.childNodes[4]);
            var HideStyle = new $.f.style(styleNode.childNodes[5]);


            var RowHeight = menuNode.getAttribute('Height');
            var ItemNodes = menuNode.childNodes

            var Container;
            if (this.element) Container = this.element;
            else Container = $$('div');

            var ShowHide = function(obj)
            {
                var div = obj.Div;
                if (div.style.display == 'block')
                    div.style.display = 'none';
                else
                    div.style.display = 'block';
            }

            var OnClick = function(obj)
            {
                OnMenuClick(obj.name);
            }

            var MenuItem = function(container, name, label, style, onClick)
            {
                var Item = document.createElement('a');
                Item.onmouseover = function() { MouseOverStyle.SetStyle(this); }
                Item.onmouseout = function() { MouseOutStyle.SetStyle(this); }
                Item.onclick = function() { onClick(this); }
                Item.name = name;
                style.SetStyle(Item);
                Item.innerHTML = label;
                container.appendChild(Item);
                var div = document.createElement('div');
                div.style.display = 'none'
                div.style.borderBottom = 'solid 1px';
                div.style.borderTop = 'solid 1px';
                div.id = name;
                Item.Div = div;
                container.appendChild(div);

                this.Add = function(name, label)
                {
                    return new MenuItem(div, name, label, SubMenuStyle, OnClick);
                }
            }

            this.Add = function(name, label, noClick)
            {
                var ClickEvent = OnClick;
                if (arguments.length == 3 && noClick) ClickEvent = ShowHide;
                return new MenuItem(Container, name, label, MenuStyle, ClickEvent);
            }
            return this;
        },

        simpleMenu: function()
        {
            var This = this;
            var Container;
            var Select = null;
            if (this.element) Container = this.element;
            else Container = this.element = $$('span');
            var ElementType = 'span';
            this.ElementType = function(t) { ElementType = t; return This; }

            var Color = 'black';
            this.Color = function(c) { Color = c; return This; }

            var SelectColor = 'white';
            this.SelectColor = function(c) { SelectColor = c; return This; }

            var OverColor = 'yellow';
            this.OverColor = function(c) { OverColor = c; return This; }

            var BackgroundColor = '';
            this.BackgroundColor = function(bc) { BackgroundColor = bc; return This; }

            var Width = 0;
            this.Width = function(w) { Width = w; return This; }

            var Margin = '3px 5px';
            this.Margin = function(m) { Margin = m; return This; }

            var RadioMode = true;
            this.RadioMode = function(state) { RadioMode = state; return This; }

            this.Display = function(enable)
            {
                if (enable)
                    Container.style.display = 'block';
                else
                    Container.style.display = 'none';
                return This;
            }

            var OnSelect = function()
            {
                if (!RadioMode) return;
                this.style.color = SelectColor;
                this.style.cursor = 'default';
                this.style.textDecoration = 'none';
                if (Select) Select.style.color = Color;
                Select = this;
            }


            this.Add = function(label, value)
            {
                var Item = This[value] = Container.appendChild($$(ElementType));
                Item.innerHTML = label;
                Item.style.margin = Margin;
                Item.style.backgroundColor = BackgroundColor;
                Item.style.textAlign = 'center';
                Item.style.color = Color;
                if (Width > 0) Item.style.width = Width + 'px';
                Item.style.cursor = 'default';
                Item.style.textDecoration = 'none';
                if (!RadioMode)
                {
                    Item.style.color = SelectColor;
                    Item.style.cursor = 'default';
                    Item.style.textDecoration = 'none';
                }
                Item.onmouseover = function()
                {
                    if (this == Select)
                    {
                        this.style.cursor = 'default';
                        return;
                    }
                    var Style = this.style;
                    Style.cursor = 'hand';
                    Style.color = OverColor;
                    Style.textDecoration = 'underline';
                }
                Item.onmouseout = function()
                {
                    var Style = this.style;
                    Style.cursor = 'default';
                    if (this == Select) return;
                    if (RadioMode)
                        Style.color = Color;
                    else
                        Style.color = SelectColor;
                    Style.textDecoration = 'none';
                }
                Item.onclick = function()
                {
                    OnSelect.call(this);
                    This.OnClick(this);
                }
                Item.Set = function()
                {
                    OnSelect.call(this);
                }
                OnSelect.call(Item);
                return Item;
            }
            return this;
        },

        tabPanel: function(PanelNode)
        {
            var This = this;
            this.Parent = null;

            if (this.element) Container = this.element;
            else Container = this.element = $$('div');
            var height = parseInt(PanelNode.getAttribute('Height'));
            var width = parseInt(PanelNode.getAttribute('Width'));
            var BackgroundColor = PanelNode.getAttribute('Background');

            var Width = width + 'px';
            var Height = height + 'px';

            var CurrentTab = null;
            var count = 0;

            var Tab = function()
            {
                var ThisTab = this;
                this.Id = null;
                this.IsDisabled = false;
                this.Width = '75px';
                this.Height = '24px';
                this.SelectImage = null;
                this.UnSelectImage = null;
                this.DisabledImage = null;
                this.CurrentImage = null;
                this.Header = null;
                this.OnSelect = null;
                this.Visible = function(state) { }
                this.Focus = function()
                {
                    ThisTab.Disabled(false);
                    SelectTab(ThisTab);
                    return This;
                }
                this.Disabled = function(state)
                {
                    ThisTab.IsDisabled = state;
                    if (state)
                    {
                        ThisTab.Header.style.background = "url(resource.aspx?guid=" + ThisTab.DisabledImage + ")";
                    }
                    else
                    {
                        ThisTab.Header.style.background = "url(resource.aspx?guid=" + ThisTab.UnSelectImage + ")";
                    }

                    return This;
                }
            }

            Container.style.cssText = "";
            Container.style.width = Width;
            Container.style.height = Height;
            Container.style.overflow = 'hidden';
            Container.style.margin = '0px';
            Container.style.padding = '0px';
            Container.style.color = 'black';
            Container.style.font = 'normal 9pt arial';

            var tbl = Container.appendChild($$("table"));
            tbl.cellPadding = '0px';
            tbl.cellSpacing = '0px';
            var TabBody = tbl.appendChild($$("tbody"));
            var TabRow = TabBody.appendChild($$("tr"));

            var TabDiv = $$('Div');
            Container.appendChild(TabDiv);
            TabDiv.style.position = 'relative';
            TabDiv.style.padding = '0px';
            TabDiv.style.color = 'black';
            TabDiv.style.font = 'normal 9pt arial';
            //TabDiv.style.zIndex = 400;
            TabDiv.style.height = Height;
            TabDiv.style.backgroundColor = BackgroundColor;


            var InsertDiv = function(Tab)
            {
                Tab.Element = $$('Div');
                TabDiv.appendChild(Tab.Element);
                ResetDiv(Tab.Element);
                Tab.Disabled(true);
                return Tab;
            }

            var ResetDiv = function(div)
            {
                div.style.cssText = "";
                div.style.display = 'none';
                div.style.zIndex = 1;
                div.style.left = 0;
                div.style.top = 0;
                //div.style.width = Width;
                div.style.height = Height;
                div.style.position = 'absolute';
                div.style.overflow = 'auto';
                return This;
            }

            var SelectTab = function(Hdr)
            {
                var NewTab = This[Hdr.Id];
                if (NewTab.IsDisabled) return;
                if (CurrentTab != null)
                {
                    if (CurrentTab.Id == NewTab.Id) return;
                    CurrentTab.Header.style.background = "url(resource.aspx?guid=" + CurrentTab.UnSelectImage + ")";
                    CurrentTab.Element.style.display = 'none';
                }
                NewTab.Header.style.background = "url(resource.aspx?guid=" + NewTab.SelectImage + ")";
                NewTab.Element.style.display = 'block';
                This.CurrentTab = CurrentTab = NewTab;
                if (NewTab.OnSelect) { NewTab.OnSelect(); }
                if (This.EventHandler) This.EventHandler('SelectTab', NewTab);
                //Masada.WebServices.LogEvent(This.Parent.Id, 'Tab', NewTab.Id);
                return This;
            }
            var TabsNode = PanelNode.selectSingleNode("Tabs");
            var TabNodes = TabsNode.selectNodes("Tab");
            for (var i = 0; i < TabNodes.length; i++)
            {
                var Id = TabNodes[i].attributes.getNamedItem('Id').value;
                var TabWidth = TabNodes[i].attributes.getNamedItem('Width').value;
                var TabHeight = TabNodes[i].attributes.getNamedItem('Height').value;
                var ImagesNodes = TabNodes[i].selectNodes("Image");

                var NewTab = new Tab();
                NewTab.Id = Id;
                NewTab.SelectImage = ImagesNodes[0].attributes.getNamedItem('Guid').value;
                NewTab.UnSelectImage = ImagesNodes[1].attributes.getNamedItem('Guid').value;
                NewTab.DisabledImage = ImagesNodes[2].attributes.getNamedItem('Guid').value;

                var Header = NewTab.Header = TabRow.appendChild($$("td"));
                Header.id = Id;
                Header.style.background = "url(resource.aspx?guid=" + NewTab.DisabledImage + ")";
                Header.style.width = TabWidth + 'px';
                Header.style.height = TabHeight + 'px';
                Header.onclick = function()
                {
                    SelectTab(This[this.id]);
                }
                Header.onmouseover = function()
                {
                    this.style.cursor = 'hand';
                }
                Header.onmouseout = function()
                {
                    this.style.cursor = 'pointer';
                }
                var space = TabRow.appendChild($$("td"));
                space.style.width = '4';
                This[Id] = NewTab;
                InsertDiv(NewTab);
            }

            var BindTo = function(parent, container)
            {
                this.Parent = parent;
                container.appendChild(Container);
                Container.style.backgroundColor = container.style.backgroundColor;
                return This;
            }

            this.BindTo = BindTo;
            this.Tab = Tab;
            return this;
        },


        dataAdapter: function(ajaxMethod)
        {
            this.Select = function(callback)
            {
                ajaxMethod('Select', callback);
                return This;
            }
            this.Insert = function(callback)
            {
                ajaxMethod('Insert', callback);
                return This;
            }
            this.Delete = function(callback)
            {
                ajaxMethod('Delete', callback); // needs expansion
                return This;
            }
            this.Update = function(recordSet, callback)
            {
                ajaxMethod('Update', $().serializeXML(recordSet), callback);
                return This;
            }
            return this;
        },

        recordSet: function(dataAdapter)
        {
            var This = this;
            var d = document;
            var RecordKey = "Id";
            var ReturnDoc = null;
            var RecordDoc = null;
            var EventHandler = null;
            var Fields = null;
            var Rows = null;
            var HeaderNode = null;
            this.DataAdapter = dataAdapter;
            this.Closed = false;
            this.Status = null;
            this.StatusText = null;
            this.RowCount = 0;
            this.QueryValue = 0;
            this.Root = null;

            var Callback = function(rtn)
            {
                var ReturnDoc = $().xmlDom(rtn);
                var root = This.Root = ReturnDoc.documentElement;
                HeaderNode = root.selectSingleNode("Header");
                var StatusNode = HeaderNode.selectSingleNode("ReturnStatus");
                This.Status = StatusNode.attributes.getNamedItem("Condition").firstChild.nodeValue;
                This.StatusText = StatusNode.firstChild.nodeValue;
                if (This.Status == 'Error')
                {
                    alert(This.StatusText);
                    return;
                }

                var Node = HeaderNode.selectSingleNode("RowCount");
                if (Node != null) This.RowCount = parseInt(Node.firstChild.nodeValue);
                switch (This.Status)
                {
                    case 'New':
                        RecordDoc = ReturnDoc;
                        Rows = root.selectSingleNode("Rows");
                        Fields = Rows.selectSingleNode("Row[@RowNbr='" + '0' + "']/Fields");
                        ClearDirtyFlag();
                        if (RecordKey != 'Id') HeaderNode.selectSingleNode("RecordKey").firstChild.nodeValue = RecordKey;
                        SetValue(RecordKey, '0');
                        break;
                    case 'Open':
                        if (This.RowCount == 0) break;
                        RecordDoc = ReturnDoc;
                        Rows = root.selectSingleNode("Rows");
                        Fields = Rows.selectSingleNode("Row[@RowNbr='" + '0' + "']/Fields");
                        if (RecordKey != 'Id') HeaderNode.selectSingleNode("RecordKey").firstChild.nodeValue = RecordKey;
                        ClearDirtyFlag();
                        break;
                    case 'Insert':
                        SetValue(RecordKey, This.StatusText);
                        break;
                    case 'Update':
                        ClearDirtyFlag();
                        break;
                    case 'AdRequest':
                        RecordDoc = ReturnDoc;
                        Rows = RecordDoc.documentElement.selectSingleNode("Rows");
                        break;
                    case 'NonQuery':
                        This.QueryValue = parseInt(HeaderNode.selectSingleNode("QueryValue").firstChild.nodeValue);
                        break;
                }
                if (EventHandler != null) EventHandler(This);
            }

            var Errorback = function(err)
            {
                alert("(RecordSet():error during ajax call");
            }

            this.Insert = function(eventHandler)
            {
                if (arguments.length > 0)
                    EventHandler = eventHandler;
                else
                    EventHandler = null;

                This.Closed = false;
                This.DataAdapter.Insert(Callback);
            }

            this.Load = function(eventHandler)
            {
                if (arguments.length > 0)
                    EventHandler = eventHandler;
                else
                    EventHandler = null;

                This.Closed = false;
                This.DataAdapter.Select(Callback);
            }

            this.Store = function(eventHandler)
            {
                if (arguments.length == 1)
                    EventHandler = eventHandler;
                else
                    EventHandler = null;
                This.DataAdapter.Update(RecordDoc, Callback);
            }

            this.Close = function()
            {
                This.Closed = true;
                This.Store();
            }

            var ClearDirtyFlag = function()
            {
                var nodes = Fields.selectNodes("Field");
                for (var i = 0; i < nodes.length; i++)
                    nodes[i].attributes.getNamedItem('IsDirty').value = "False";
            }

            var SetAllDirtyFlags = function(value)
            {
                var Value = 'False';
                if (value) Value = 'True';
                var nodes = Fields.selectNodes("Field");
                for (var i = 0; i < nodes.length; i++)
                    nodes[i].attributes.getNamedItem('IsDirty').value = Value;
            }

            var DirtyCount = function()
            {
                var count = 0;
                var nodes = Fields.selectNodes("Field");
                for (var i = 0; i < nodes.length; i++)
                    if (nodes[i].attributes.getNamedItem('IsDirty').value == "True") count++;
                return count;
            }

            var SetValue = function(Name, Value)
            {
                var FieldNode = Fields.selectSingleNode("Field[@Id='" + Name + "']");
                if (FieldNode.text != Value)
                {
                    FieldNode.text = Value;
                    FieldNode.attributes.getNamedItem('IsDirty').value = "True";
                }


                //            var FieldNode = Fields.selectSingleNode("Field[@Id='" + Name + "']");
                //             alert(FieldNode.xml);
                //           if (FieldNode.firstChild.nodeValue != Value)
                //            {
                //                FieldNode.firstChild.nodeValue = Value;
                //                FieldNode.attributes.getNamedItem('IsDirty').value = "True";
                //            }
            }

            var GetValue = function(arg1, arg2)
            {
                var RowNbr = '0';
                var Name = null;
                if (arguments.length == 1)
                {
                    Name = arg1;
                }
                else
                {
                    RowNbr = arg1;
                    Name = arg2;
                }

                if (This.RowCount < parseInt(RowNbr))
                {
                    alert("rowcount error");
                    return;
                }

                Fields = Rows.selectSingleNode("Row[@RowNbr='" + RowNbr + "']/Fields");
                if (typeof Name == 'number')
                {
                    Field = Fields.childNodes[arg2];
                }
                else
                {

                    var Field = Fields.selectSingleNode("Field[@Id='" + Name + "']");
                    if (Field == null)
                    {
                        alert('Unable to locate Field: ' + Name + ' in RecordSet');
                        return;
                    }
                }

                var ChildNode = Field.firstChild;
                if (ChildNode) return ChildNode.nodeValue;
                return '';
            }

            var AddRow = function()
            {
                var Rows = RecordDoc.documentElement.selectSingleNode("Rows");
                Rows.setAttribute("Count", '1');
                var Row = RecordDoc.createNode(1, 'Row', '');
                Rows.appendChild(Row);
                Row.setAttribute('RowNbr', '0');
                Fields = RecordDoc.createNode(1, "Fields", "");
                Row.appendChild(Fields);

                var SchemaFields = RecordDoc.documentElement.selectNodes("Schema/Fields/Field");
                for (var i = 0; i < SchemaFields.length; i++)
                {
                    var Field = RecordDoc.createNode(1, 'Field', '');
                    Field.setAttribute('Id', SchemaFields[i].attributes.getNamedItem('Id').value);
                    Field.setAttribute('IsDirty', 'False');
                    Fields.appendChild(Field);
                }
            }

            var AddCol = function()
            {
                var SchemaFields = RecordDoc.documentElement.selectNodes("Schema/Fields/Field");
            }


            this.RecordDoc = RecordDoc;
            this.AddRow = AddRow;
            this.AddCol = AddCol;
            this.DirtyCount = DirtyCount;
            this.SetValue = SetValue;
            this.GetValue = GetValue;
            this.SetAllDirtyFlags = SetAllDirtyFlags;
            return this;
        },

        grid: function()
        {
            var This = this;
            this.ObjectName = 'SelectGrid';
            var d = document;
            var WhereRow = null;
            var _SortClause = null;
            var EventHandler = null;
            var Columns = [];
            var PanelDiv = null;
            var GridBody = null;
            var WaitImage = null;
            this.Height = null;
            var GridWidth = 0;

            This.Recordset = null;
            var DataSource = null;

            this.BindData = function(dataSource) { DataSource = dataSource; return This; }
            var Container;
            var Select = null;
            if (this.element) Container = this.element;
            else Container = this.element = $$('div');
            this.Grid = $$('div');
            this.Grid.rules = 'all';
            this.Grid.style.overflow = 'auto';

            var Column = function()
            {
                this.ControlType = null;
                this.DataType = null;
                this.Title = null;
                this.Width = null;
                this.TextAlign = null;
                this.FieldName = null;
                this.OnClick = null;
                this.OnMouseOver = null;
                this.OnMouseOut = null;
                this.BackgroundColor = null;
            }

            this.Column = function(controlType, width, textAlign, fieldName)
            {
                if (controlType != 'Tbx' &&
                controlType != 'Lbl' &&
                controlType != 'Btn' &&
                controlType != 'Ddl')
                {
                    alert('Error(SelectGrid), unrecognized control type: ' + controlType);
                    return;
                }

                var Col = new Column();
                Col.ControlType = controlType;
                Col.Width = width + 3;
                Col.TextAlign = textAlign;
                Col.FieldName = fieldName;
                Columns.push(Col);
                //Style.AddRule(Col.ClassName,CellStyle);
                return Col;
            }

            var SortClause = function(clause)
            {
                _SortClause = clause;
            }


            var Init = function()
            {
                This.Recordset = $().recordSet(DataSource);

                GridWidth = 5;
                for (var i = 0; i < Columns.length; i++)
                {
                    GridWidth += (Columns[i].Width + 2);
                }
                GridWidth += 5;
                WaitImage = $$('img');
                WaitImage.style.visibility = 'hidden';
                This.element.appendChild(WaitImage);
                //            WaitImage.src = "/Images/wait.gif";
                //            WaitImage.src = "/Images/ajax-loader2.gif";
                WaitImage.style.position = 'absolute';
                if (This.Height) WaitImage.style.top = This.Height / 2 + 'px';
                WaitImage.style.left = GridWidth / 2 + 'px';
                if (This.Height) This.Grid.style.height = This.Height + 'px';
                This.Grid.style.width = GridWidth + 'px';
                This.element.appendChild(This.Grid);

                var GridTbl = $$('table');
                GridTbl.rules = 'all';
                GridTbl.style.borderCollapse = 'collapse';
                This.Grid.appendChild(GridTbl);
                GridBody = GridTbl.appendChild($$('tbody'));
                GridBody.This = This;
            }

            var Callback = function(rtn)
            {
                for (var rowNbr = 0; rowNbr < rtn.RowCount; rowNbr++)
                {
                    var row = GridBody.appendChild($$('tr'));
                    row.Nbr = rowNbr;
                    for (var colNbr = 0; colNbr < Columns.length; colNbr++)
                    {
                        var Col = Columns[colNbr];
                        var cell = row.appendChild($$('td'));
                        cell.width = Col.Width;
                        if (Col.ControlType == 'Btn')
                        {
                            var btn = $$("input");
                            btn.type = "button";
                            if (Col.Name)
                                btn.name = Col.Name;
                            else
                                btn.name = 'SelectBtn';
                            btn.style.width = '100%';  //Col.Width;
                            btn.style.height = '18px';
                            btn.style.font = 'bold 8pt Arial';
                            btn.style.verticalAlign = 'top';
                            btn.value = rtn.GetValue(rowNbr, Col.FieldName);
                            if (Col.OnClick != null) btn.onclick = Col.OnClick;
                            cell.appendChild(btn);
                        }
                        else if (Col.ControlType == 'Tbx')
                        {
                            var div = $$("div");
                            div.style.whiteSpace = "nowrap";
                            div.style.overflow = 'hidden';
                            div.style.width = Col.Width;
                            div.style.height = '18px';
                            div.style.padding = '0px';
                            div.style.textAlign = Col.TextAlign;
                            cell.appendChild(div);
                            div.innerHTML = rtn.GetValue(rowNbr, Col.FieldName);
                        }
                        else if (Col.ControlType == 'Txt')
                        {
                            var div = $$("div");
                            div.style.whiteSpace = "nowrap";
                            div.style.overflow = 'hidden';
                            div.style.width = Col.Width;
                            div.style.height = '18px';
                            div.style.padding = '0px';
                            div.style.textAlign = Col.TextAlign;
                            cell.appendChild(div);
                            var Value = rtn.GetValue(rowNbr, Col.FieldName);
                            //if (Col.DataType == 'Date') div.innerHTML = ExtractDate(Value);
                            //else
                            div.innerHTML = Value;
                            if (Col.OnClick) div.onclick = Col.OnClick;
                            if (Col.OnMouseOver) div.onmouseover = Col.OnMouseOver;
                            if (Col.OnMouseOut) div.onmouseout = Col.OnMouseOut;
                            if (Col.BackgroundColor) div.style.backgroundColor = Col.BackgroundColor;
                        }
                    }
                }
                if (EventHandler != null) EventHandler(This);
                WaitImage.style.visibility = 'hidden';
            }

            this.LoadGrid = function()
            {
                if (arguments.length == 1)
                    EventHandler = arguments[0];
                else
                    EventHandler = null;

                WaitImage.style.visibility = 'visible';
                while (GridBody.hasChildNodes())
                {
                    GridBody.removeChild(GridBody.firstChild);
                }
                This.Recordset.Load(Callback);
            }

            function StyleSheet(name)
            {
                var StyleElement = $$("style");
                StyleElement.id = name;
                d.documentElement.firstChild.appendChild(StyleElement);
                var Sheet = StyleElement.styleSheet;
                this.AddRule = function(className, style)
                {
                    Sheet.addRule("." + className, style);
                }
                this.AddClass = function(className, style)
                {
                    Sheet.addRule(className, style);
                }
                this.RemoveStyle = function()
                {
                    //if (StyleElement) Style.parentNode.removeChild(Style);
                }
            }

            var Style = new StyleSheet("OurSheet");
            this.GetGridDiv = function()
            {
                return This.element;
            }

            this.SortClause = SortClause;
            this.Init = Init;
            return this;
        },

        xmlDom: function(Xml)
        {
            var xmlDoc = null;

            var OuterXML = function(node)
            { //  with Opera
                if (node.ownerDocument && node.ownerDocument.implementation &&
                    document.implementation.createLSSerializer &&
                    (serializer = node.ownerDocument.implementation.createLSSerializer()))
                {
                    return serializer.writeToString(node);
                }
            }

            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("MSXML2.DOMDocument");
                xmlDoc.async = "false";
                xmlDoc.loadXML(Xml);
            }
            catch (e)
            {
                try //Firefox, Mozilla, Opera, etc.
                {
                    var parser = new DOMParser();
                    xmlDoc = parser.parseFromString(Xml, "text/xml");
                }
                catch (e) { alert(e.message); return null; }
            }

            this.OuterXML = OuterXML;
            this.DocumentElement = xmlDoc.documentElement;
            return xmlDoc;
        },

        serializeXML: function(node)
        {
            if (typeof XMLSerializer != "undefined") return (new XMLSerializer()).serializeToString(node);
            else if (node.xml) return node.xml;
            else throw "Unable to serialize";
            return this;
        },

        style: function(s)
        {
            var This = this;
            var Properties = s.childNodes;
            for (var i = 0; i < Properties.length; i++)
            {
                var Property = Properties[i].attributes[0];
                this[Property.nodeName] = Property.value;
            }

            var SetStyle = function(cell)
            {
                for (var property in This)
                {
                    if (property.substr(0, 8) == 'function') continue;
                    cell.style[property] = This[property];
                }
            }
            this.SetStyle = SetStyle;
            return this;
        },

        horizontalMenu: function(xml)
        {
            var This = this;
            var MenuDoc = null;
            var OnClickFunction = null;
            var OnClickHandler = function(id) { OnClickFunction(id); }
            var MenuXml = xml;

            this.RegisterHandler = function(Handler)
            {
                OnClickFunction = Handler;
                return This;
            }

            function Resize() { This.PositionSubMenus(); }

            function attachEvent()
            {
                if (window.addEventListener)
                {
                    window.addEventListener('resize', Resize, false);
                }
                else if (window.attachEvent)
                {
                    window.attachEvent("onresize", Resize);
                }
                else if (document.body.onresize)
                {
                    document.body.onresize = Resize;
                }
            }
            attachEvent();


            //document.body.addEventListener('resize', function() { alert('reloading'); }, false);        
            //window.onresize = function() {This.PositionSubMenus();}    
            var MenuTbl = $().table();
            var Row = null;

            var InsertDiv = function(cell, width)
            {
                var div = $$("div");
                if (width) div.style.width = width + 'px';
                div.style.whiteSpace = "nowrap";
                div.style.overflow = 'hidden';
                div.style.padding = 0;
                div.style.paddingLeft = '6px';
                div.style.paddingRight = '6px';
                cell.appendChild(div);
                return div;
            }

            var MenuArray = new Array();
            this.BindTo = function(parent)
            {
                MenuTbl.BindTo(parent);
                MenuTbl.Visible(true);
                if (MenuXml != null)
                {
                    var Cell = null;
                    MenuDoc = $().xmlDom(MenuXml);
                    var root = MenuDoc.documentElement;
                    var MenuHeight = root.getAttribute('Height');
                    Row = MenuTbl.AddRow(MenuHeight)
                    var Items = root.childNodes;
                    var Styles = root.lastChild;

                    var AllDefaultStyle = new $.f.style(Styles.childNodes[0]);
                    var MenuDefaultStyle = new $.f.style(Styles.childNodes[1]);
                    var MenuHoverOverStyle = new $.f.style(Styles.childNodes[2]);
                    var MenuMouseOutStyle = new $.f.style(Styles.childNodes[3]);
                    var VerticalMenu = function(menu, styles)
                    {
                        var This = this;
                        this.ClearOnMouseOut = true;
                        var AllDefaultStyle = new $.f.style(styles.childNodes[0]);
                        var SubMenuDefaultStyle = new $.f.style(styles.childNodes[4]);
                        var SubMenuHoverOverStyle = new $.f.style(styles.childNodes[5]);
                        var SubMenuMouseOutStyle = new $.f.style(styles.childNodes[6]);

                        var RowHeight = menu.getAttribute('Height');
                        var ItemNodes = menu.childNodes
                        var MenuTbl = $().table();
                        this.ControlItem = null;
                        d = document;
                        var CellArray = new Array();
                        var OnClickHandler = null;
                        this.RegisterHandler = function(Handler)
                        {
                            OnClickHandler = Handler;
                        }
                        var BindTo = function(parent)
                        {
                            MenuTbl.BindTo(parent);
                            for (var i = 0; i < ItemNodes.length; i++)
                            {
                                var Item = ItemNodes[i];
                                var Text = Item.getAttribute('Text');
                                var Width = Item.getAttribute('Width');
                                var ItemCell = CellArray[i] = AddItem(Width);
                                var Value = Item.getAttribute('Value');
                                if (Value) ItemCell.Value = Value;
                                var CellObj = ItemCell.Element;
                                CellObj.id = i;
                                AllDefaultStyle.SetStyle(CellObj);
                                SubMenuDefaultStyle.SetStyle(CellObj);
                                var div = InsertDiv(CellObj, Width);
                                div.innerHTML = Text;
                                CellObj.onmouseover = function()
                                {
                                    SubMenuHoverOverStyle.SetStyle(this);
                                    Visible(true);
                                }

                                CellObj.onclick = function()
                                {
                                    var sm = CellArray[this.id];
                                    if (sm && OnClickHandler) OnClickHandler(sm.Value);
                                }

                                CellObj.onmouseout = function()
                                {
                                    SubMenuMouseOutStyle.SetStyle(this);
                                    if (This.ClearOnMouseOut) Visible(false);
                                }
                            }
                            return This;
                        }

                        var AddItem = function(width)
                        {
                            var Row = MenuTbl.AddRow(RowHeight);
                            return Row.AddCell(width);
                        }

                        var Visible = function(state)
                        {
                            MenuTbl.Visible(state);
                        }

                        var Position = function(mode, left, top)
                        {
                            MenuTbl.Position(mode, left, top);
                        }

                        this.Visible = Visible;
                        this.Position = Position;
                        this.BindTo = BindTo;
                        this.AddItem = AddItem;
                    }

                    for (var i = 0; i < Items.length; i++)
                    {
                        var Item = Items[i];
                        if (Item.nodeName == 'Styles') continue;
                        var Text = Item.getAttribute('Text');
                        var Width = Item.getAttribute('Width');
                        var Value = Item.getAttribute('Value');
                        var Image = Item.getAttribute('Image');
                        if (!Width) { alert('problem'); return; }

                        MenuArray[i] = Cell = This.AddItem(Width);
                        var CellObj = Cell.Element;
                        AllDefaultStyle.SetStyle(CellObj);
                        MenuDefaultStyle.SetStyle(CellObj);

                        CellObj.id = i;
                        var Div = InsertDiv(CellObj, Width);
                        if (Text) Div.innerHTML = Text;

                        if (Item.nodeName == 'Spacer')
                        {
                            if (Image) CellObj.style.background = "url('masada/resource.aspx?image=" + validate(Image) + "') no-repeat";
                            continue;
                        }
                        if (Value)
                        {
                            Cell.Value = Value;
                            CellObj.onclick = function()
                            {
                                var sm = MenuArray[this.id];
                                if (sm && OnClickHandler) OnClickHandler(sm.Value);
                            }
                        }

                        CellObj.onmouseover = function()
                        {
                            var Cell = MenuArray[this.id];
                            var SubMenu = Cell.Reference;
                            if (SubMenu) SubMenu.Visible(true);
                            MenuHoverOverStyle.SetStyle(this);
                        }

                        CellObj.onmouseout = function()
                        {
                            var Cell = MenuArray[this.id];
                            var SubMenu = Cell.Reference;
                            if (SubMenu) SubMenu.Visible(false);
                            MenuMouseOutStyle.SetStyle(this);
                        }
                        if (Item.firstChild)
                        {
                            var SubItems = Item.firstChild.childNodes;
                            var NbrSubItems = SubItems.length;
                            if (NbrSubItems > 0)
                            {
                                var SubMenu = new VerticalMenu(Item.firstChild, Styles);
                                SubMenu.RegisterHandler(OnClickHandler);
                                Cell.Reference = SubMenu;
                                SubMenu.BindTo(document.body);
                            }
                            else
                                SubMenu = null;
                        }
                    }
                }
                This.PositionSubMenus();
                This.PositionSubMenus(); // both statements required
                return This;
            }

            This.PositionSubMenus = function()
            {
                if (!MenuArray) return;
                for (var i = 0; i < MenuArray.length; i++)
                {
                    var Cell = MenuArray[i];
                    var SubMenu = Cell.Reference;
                    if (SubMenu)
                    {
                        var Position = Cell.GetPosition();
                        SubMenu.Position('absolute', Position[0], Position[1]);
                    }
                }
            }

            this.AddItem = function(width)
            {
                return Row.AddCell(width);
            }

            var Visible = function(state)
            {
                MenuTbl.Visible(state);
            }
            this.Visible = Visible;
            return this;
        },

        table: function(width)
        {
            var d = document;
            var ThisTable = this;
            var Tbl = this.Element = $$('table');
            if (arguments == 1) Tbl.width = width;
            Tbl.cellSpacing = '0';
            Tbl.cellPadding = '0';
            Tbl.border = '0';
            var DomTable = Tbl.appendChild($$('tbody'));
            DomTable.style.display = 'none';

            var Visible = function(state)
            {
                if (state) DomTable.style.display = 'block';
                else DomTable.style.display = 'none';
                return ThisTable;
            }
            var Position = function(mode, left, top)
            {
                Tbl.style.position = mode;
                Tbl.style.left = left + 'px';
                Tbl.style.top = top + 'px';
            }

            var BindTo = function(parent)
            {
                parent.appendChild(Tbl)
                return ThisTable;
            }

            var Row = function()
            {
                var ThisRow = this;
                this.Table = ThisTable;
                this.DomRow = DomTable.appendChild($$('tr'));
                var Cell = function(width, addDiv)
                {
                    var ThisCell = this;
                    this.Row = ThisRow;
                    var td = $$('td');
                    ThisRow.DomRow.appendChild(td);
                    if (width) td.style.width = width;
                    if (addDiv)
                    {
                        this.Element = $$('div');
                        td.appendChild(this.Element);
                        this.Element.style.height = ThisRow.DomRow.style.height;
                    }
                    else
                        this.Element = td;

                    var GetPosition = function()
                    {
                        return GetElementPosition(ThisCell.Element);
                    }
                    this.GetPosition = GetPosition;
                }

                var AddCell = function(width, addDiv)
                {
                    var Width = null;
                    var AddDiv = false;
                    if (arguments.length > 0) Width = SetStyle(width);
                    if (arguments.length > 1) AddDiv = addDiv;
                    var cell = new Cell(Width, AddDiv);
                    cell.Element.style.height = ThisRow.DomRow.style.height;
                    return cell;
                }
                this.AddCell = AddCell;
            }

            var AddRow = function(height)
            {
                var row = new Row();
                if (arguments.length > 0) row.DomRow.style.height = SetStyle(height);
                return row;
            }
            this.BindTo = BindTo;
            this.AddRow = AddRow;
            this.Position = Position;
            this.Visible = Visible;
            return this;
        },


        imagePlayer: function(width, height)
        {
            var self = this;
            var Container;
            if (this.element) Container = this.element;
            else Container = this.element = $$('div');
            Container.style.overflow = 'hidden';
            Container.style.margin = '0';
            Container.style.border = '0';
            var SlideInterval = null;

            var Width = 0;
            var Height = 0;
            var Href = 'Disabled';

            if (arguments.length > 1)
            {
                Width = width;
                Height = height;
                if (arguments.length == 3 && arguments[2]) Href = 'Enabled';
            }
            else
            {
                var PlayerNode = arguments[0];
                Height = parseInt(PlayerNode.getAttribute('Height'));
                Width = parseInt(PlayerNode.getAttribute('Width'));
                Href = PlayerNode.getAttribute('Href');
                SetPlayList(PlayerNode);
            }

            var ImageDiv = Container.appendChild($$('div'));
            ImageDiv.style.overflow = 'hidden';
            ImageDiv.style.borderBottom = '0px';

            var MarqueeTbx = null;
            this.showMarquee = function()
            {
                MarqueeTbx = Container.appendChild($$('div'));
                MarqueeTbx.style.backgroundColor = 'white';
                MarqueeTbx.style.overflow = "hidden";
                MarqueeTbx.style.height = '30px';
                MarqueeTbx.style.color = 'black';
                MarqueeTbx.style.fontSize = '8pt';
                MarqueeTbx.style.paddingLeft = '6px';
                MarqueeTbx.style.fontFamily = 'Arial';
                return self;
            }

            var ImageElement = function()
            {
                this.ImageName = null;
                this.Title = null;
                this.Image = null;
                this.Id = null;
            }

            var ImagePanel = function()
            {
                var Frames = [];
                Frames.length = 0;
                var ImageNbr = 0;
                var ViewMs = 7000;

                var ImageAnchor = $$('div');
                ImageAnchor.style.position = 'relative';
                var textOverlay = ImageAnchor.appendChild($$('div'));
                var DisplayImage = new Image();
                DisplayImage.width = Width;
                DisplayImage.height = Height;
                DisplayImage.style.margin = '0px';
                DisplayImage.style.backgroundColor = '#aaaaaa';
                ImageAnchor.appendChild(DisplayImage);
                textOverlay.style.position = 'absolute';
                textOverlay.style.width = Width + 'px';
                textOverlay.style.height = Height + 'px';
                textOverlay.style.zIndex = '500000';


                if (Href && Href == 'Enabled')
                {
                    ImageAnchor.onmouseover = function() { this.style.cursor = 'hand'; }
                    ImageAnchor.onmouseout = function() { this.style.cursor = 'pointer'; }
                }
                this.Reset = function(resource, title)
                {
                    ImageNbr = 0;
                    Frames.length = 0;
                }

                this.Add = function(resourceId, viewSeconds, title)
                {
                    var NewFrame = new ImageElement();
                    NewFrame.Image = new Image(Width, Height);
                    NewFrame.ViewSeconds = viewSeconds;
                    if (arguments.length > 2 && title.length > 0) NewFrame.Title = title;
                    NewFrame.Image.src = '/masada/resource.aspx?image=' + validate(resourceId);
                    NewFrame.Id = resourceId;
                    Frames.push(NewFrame);
                    return NewFrame;
                }

                this.Run = function()
                {
                    if (Frames.length < 1) return;
                    ImageNbr = 0;
                    //SlideInterval = setInterval(Next, ViewMs);
                    Show();
                    return self;
                }

                this.Start = function()
                {
                    if (Frames.length < 1) return;
                    Next();
                    //SlideInterval = setInterval(Next, ViewMs);
                }

                this.Stop = function()
                {
                    clearInterval(SlideInterval);
                }

                var Next = this.Next = function()
                {
                    if (Frames.length < 1) return;
                    ImageNbr++;
                    if (ImageNbr >= Frames.length) ImageNbr = 0;
                    Show();
                }

                this.Previous = function()
                {
                    if (Frames.length < 1) return;
                    ImageNbr--;
                    if (ImageNbr < 0) ImageNbr = Frames.length - 1;
                    Show();
                }

                var OpacityTimer = null;
                var Show = function()
                {
                    // DisplayImage.style.filter = 'alpha(opacity=0)';
                    clearInterval(SlideInterval);
                    var Frame = Frames[ImageNbr];
                    ViewMs = Frame.ViewSeconds * 1000;
                    if (Frame.Title)
                    {
                        DisplayImage.alt = Frame.Title;
                        if (MarqueeTbx) MarqueeTbx.innerHTML = Frame.Title;
                    }
                    if (Frame.overlay)
                    {
                        textOverlay.style.display = 'block';
                        if (Frame.overlay) textOverlay.innerHTML = Frame.overlay.Element.innerHTML;
                    }
                    else
                        textOverlay.style.display = 'none';

                    DisplayImage.src = Frame.Image.src;

                    var DoIt = function(frame)
                    {
                        $().LogEvent('Logos', 'WebLink', frame.Id, null);
                        window.open(frame.link);

                    }
                    if (Frame.link) ImageAnchor.onclick = function() { DoIt(Frame) };
                    if (Frame.ViewSeconds > 0) SlideInterval = setInterval(Next, ViewMs);
                    //OpacityTimer = setInterval(Shadow, 35)
                }
                var Counter = 0;
                var Shadow = function()
                {
                    Counter += 20;
                    if (Counter > 100)
                    {
                        clearInterval(OpacityTimer);
                        Counter = 0;
                        return;
                    }
                    DisplayImage.style.filter = 'alpha(opacity=' + Counter + ')';
                    //DisplayImage.style.opacity = '.05';
                    //DisplayImage.style.-moz-opacity = '.65';
                    MarqueeTbx.value = Counter;
                }

                this.BindTo = function(parent)
                {
                    parent.appendChild(ImageAnchor);
                }
            }

            var CurrentImage = new ImagePanel();
            CurrentImage.BindTo(ImageDiv);

            var SetPlayList = function(config)
            {
                images = config.frames;
                CurrentImage.Reset();
                for (var i = 0; i < images.length; i++)
                {
                    var item = images[i];
                    var id = '';
                    if (item.id) id = item.id;
                    var viewTime = 7;
                    if (item.viewTime) viewTime = item.viewTime;
                    var Frame = CurrentImage.Add(id, viewTime)
                    if (item.text) Frame.Title = item.text;
                    if (item.link) Frame.link = item.link;
                    if (item.overlay) Frame.overlay = item.overlay;
                }
                return self;
            }


            this.showControls = function()
            {
                var HdrDiv = Container.appendChild($$('div'));
                HdrDiv.style.width = '120px';
                HdrDiv.style.padding = '1px 60px 0';

                var HdrTbl = new Table();
                HdrTbl.BindTo(HdrDiv);
                HdrTbl.Visible(true);
                var HdrRow = HdrTbl.AddRow()


                var BackBtn = HdrRow.AddCell().Element.appendChild($().button('<', 22, 22).element);
                BackBtn.style.cursor = 'hand';
                BackBtn.onclick = function()
                {
                    RunBtn.value = 'Start';
                    clearInterval(SlideInterval);
                    CurrentImage.Previous();
                }

                var RunBtn = HdrRow.AddCell().Element.appendChild($().button('Stop', 45, 22).element);
                RunBtn.style.cursor = 'hand';
                RunBtn.onclick = function()
                {
                    if (this.value == 'Start')
                    {
                        this.value = 'Stop';
                        CurrentImage.Start();
                    }
                    else
                    {
                        this.value = 'Start';
                        CurrentImage.Stop();
                    }
                }

                var FwdBtn = HdrRow.AddCell().Element.appendChild($().button('>', 22, 22).element);
                FwdBtn.style.cursor = 'hand';
                FwdBtn.onclick = function()
                {
                    RunBtn.value = 'Start';
                    clearInterval(SlideInterval);
                    CurrentImage.Next();
                }
                return self;
            }

            this.run = function()
            {
                CurrentImage.Run();
                return self;
            }

            this.setPlayList = SetPlayList;

            CurrentImage.Run();
            return this;
        },

        clearFields: function()
        {
            var start = this.element;
            InputList = start.getElementsByTagName('textarea');
            for (i = 0; i < InputList.length; i++)
            {
                InputList[i].value = "";
            }

            InputList = document.getElementsByTagName('input');
            for (i = 0; i < InputList.length; i++)
            {
                switch (InputList[i].type)
                {
                    case 'radio':
                    case 'checkbox':
                        InputList[i].checked = false;
                        break;
                    case 'text':
                        InputList[i].value = "";
                        break;
                }
            }
            return this;
        },

        mediaPlayer: function(width, height)
        {
            var Container = this.Element = $$('div');
            Container.style.width = width + 'px';
            Container.style.height = height + 'px';
            var Player = null;

            this.SetMovie = function(resourceId)
            {
                var LogPlayerEvent = function(theEvent)
                {
                    //Masada.WebServices.LogEvent('MediaPlayer', theEvent, resourceId);
                }
                Player = new flowplayer(Container, "Libs/Flowplayer/flowplayer-3.2.5.swf",
                {
                    clip:
                    {
                        autoPlay: false,
                        autoBuffering: false,
                        fadeInSpeed: 6000,
                        fadeOutSpeed: 6000
                    },
                    playlist:
                    [
                        { url: 'resource.aspx?image=' + resourceId }

                    ]
                });

                //Player.onLoad(function() { alert('Start'); } );
                Player.onStart(function() { LogPlayerEvent('Start'); });
                Player.onPause(function() { LogPlayerEvent('Pause'); });
                Player.onSeek(function() { LogPlayerEvent('Seek'); });
                Player.onResume(function() { LogPlayerEvent('Resume'); });
                Player.onStop(function() { LogPlayerEvent('Stop'); });
                Player.onFinish(function() { LogPlayerEvent('Finish'); });
            }

            this.Stop = function()
            {
                if (Player == null) return;
                Player.stop();
            }

            this.Play = function()
            {
                if (Player == null) return;
                Player.play();
            }

            this.BindTo = function(parent) { parent.appendChild(Container); }
            return this;
        }
    }

    var validate = function(obj)
    {
        if (typeof (obj) == 'undefined')
        {
            alert('object is undefined');
            return 'error';
        }
        return obj;
    }

    var ex = masada.regEx = {}
    ex.SSN = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    ex.zip = /^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/;
    ex.email = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
    ex.follar = /^\$?\d+(\.(\d{2}))?$/;
    ex.vreditCard = /^((4\d{3})|(5[1-5]\d{2}))(-?|\040?)(\d{4}(-?|\040?)){3}|^(3[4,7]\d{2})(-?|\040?)\d{6}(-?|\040?)\d{5}/; //AMEX, VISA, MasterCard
    ex.dignedFloat = /^[-+]?[0-9]*\\.?[0-9]+$/;
    ex.positiveInteger = /^[1-9]+[0-9]*$/;

    window.$$ = function() { return document.createElement(arguments[0]); }
    window.masada = window.$m = masada;
})(window);


if (!window.ActiveXObject)
{
    Element.prototype.selectNodes = function(sXPath)
    {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
        var aNodes = new Array();
        if (oResult != null)
        {
            var oElement = oResult.iterateNext();
            while(oElement)
            {
                aNodes.push(oElement);
                oElement = oResult.iterateNext();
            }
        }
        return aNodes;
    }

    Element.prototype.selectSingleNode = function(sXPath)
    {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        if (oResult != null)
            return oResult.singleNodeValue;
        else
            return null;
    }
}

