// Build 9.00.7773.9

IS_CHROME = navigator.userAgent.toLowerCase().indexOf("chrome") != -1;
IS_SAFARI = !IS_CHROME && (navigator.userAgent.toLowerCase().indexOf("safari") != -1 || navigator.userAgent.toLowerCase().indexOf("konqueror") != -1);
IS_OPERA = navigator.userAgent.toLowerCase().indexOf("opera") != -1;
IS_GECKO = !IS_SAFARI && !IS_CHROME && navigator.userAgent.toLowerCase().indexOf("gecko") != -1;
if (IS_GECKO) {
    GECKO_VERSION = parseFloat (navigator.userAgent.substr (navigator.userAgent.search ("Firefox") + 8, 3));
}
IS_MAC = navigator.userAgent.toLowerCase().indexOf("macintosh") != -1;
IS_IE = navigator.userAgent.toLowerCase().indexOf ("msie") != -1;
if (IS_IE) {
    IE_VERSION = parseFloat (navigator.userAgent.substr (navigator.userAgent.toLowerCase().search ("msie") + 4, 4));
}
IE_DOCMODE = document.documentMode;
IS_MOBILE = navigator.userAgent.toLowerCase().indexOf ("mobile") != -1;

//For now chrome is handled as firefox (Gecko)
if(IS_GECKO || IS_SAFARI || IS_OPERA || IS_CHROME) {
    // support "innerText"
    HTMLElement.prototype.__defineGetter__("innerText", function() { return this.textContent; });
    HTMLElement.prototype.__defineSetter__("innerText", function($value) { this.textContent = $value; });
    
    Event.prototype.__defineGetter__("srcElement", function() {
        return (this.target.nodeType == Node.ELEMENT_NODE) ? this.target : this.target.parentNode;
    });
    Event.prototype.__defineGetter__("toElement", function() {
        return (this.type == "mouseout") ? this.relatedTarget : (this.type == "mouseover") ? this.srcElement : null;
    });
}
if(typeof XMLDocument === "undefined" && typeof Document !== "undefined") XMLDocument = Document;

Qva = {} 

Qva.binders = {}
Qva.GetBinder = function(id, view) {
    var binder = Qva.binders[id || ""];
    if(!binder && view) {
        binder = new Qva.PageBinding(id);
        binder.View = view;
        if (Qva.Modal && !Qva.Modal.instance) new Qva.Modal();
        
        var def_binder = Qva.GetBinder();
        if(def_binder) {
            binder.Autoview   = def_binder.Autoview;
            binder.Remote     = def_binder.Remote;
            binder.JSON       = def_binder.JSON;
        }
    }
    return binder;
}
Qva.Start = function() {
    function GetDPI() {
        if(screen.deviceXDPI) return screen.deviceXDPI;
        //if(screen.logicalXDPI) return screen.logicalXDPI;
        
        var div = document.createElement("div");
        div.style.cssText = "padding: 0px; position: absolute; width: 1in; visibility: hidden;"
        document.body.appendChild(div);
        var dpi = div.offsetWidth;
        document.body.removeChild(div);
        return dpi;
    }
    Qva.DPI = GetDPI();
    function GetFactor() {
        var div = document.createElement("div");
        div.style.cssText = "border: none; padding: 0px; position: absolute; width: 1000pt; visibility: hidden;"
        document.body.appendChild(div);
        var factor = (300.0 * parseFloat(div.style.width)) / (72.0 * div.offsetWidth);
        document.body.removeChild(div);
        return factor;
    }
    Qva.Factor = GetFactor();
    
    function _Start() {
        if(Qva.Scanner && Qva.Scanner.instance) Qva.Scanner.instance.Start();
        for(var id in Qva.binders) Qva.binders[id].Start();
        if (document.addEventListener) { 
            document.addEventListener ("mouseup", function (event) { Qva.OnMouseUp(event); }, false);
            document.addEventListener ("keyup", function (event) { Qva.OnKeyUp(event); }, false);
            try {
                window.parent.addEventListener ("mouseup", function (event) { Qva.OnMouseUp(event); }, false);
                window.parent.addEventListener ("keyup", function (event) { Qva.OnKeyUp(event); }, false);
            } catch (Err) {}
        } else { 
            document.attachEvent ("onmouseup", function (event) { Qva.OnMouseUp(event); });
            document.attachEvent ("onkeyup", function (event) { Qva.OnKeyUp(event); });
        }
        document.onclick = function () { 
            var binder = null;
            if (Qva.PopupSearch != null) {
                var mgr = Qva.PopupSearch.AvqMgr;
                binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
            }
            Qva.HideContextMenu (); 
            Qva.ClosePopupSearch (); 
            Qva.ClosePopupInput (); 
            Qva.CloseMessagePopup ();
            if (binder) {
                binder.LoadBegin ();
            }
        }
    }
    
    var userid = Qva.ExtractProperty ("userid", null, true);
    var password = Qva.ExtractProperty ("password", null, true);

    if(userid === "" || password === "") {
        Qva.RemainingRetries = parseInt(Qva.ExtractProperty("retry", "3"));
        if(isNaN(Qva.RemainingRetries)) Qva.RemainingRetries = 3;
        
        var first = true;
        var fakePagebinder = {
            'LabelClick': false, 
            'Refresh': function() {
                if(!first) return;
                first = false;
                _Start();
            }
        };
        Qva.Modal.instance.Show(fakePagebinder, Qva.Modal.instance.ScriptPath + 'login.htm?userid=' + escape(userid));
    } else {
        _Start();
    }
}

Qva.AsyncPostPaintMgrQueue = [];
Qva.PopupInput = null;
Qva.ContextMenu = null;
Qva.ContextMenuMgr = null;
Qva.KeepContextMenuAlive = false;
Qva.MgrWithMouseDown = null;
Qva.MgrWithSelectStart = null;
Qva.StartoffsetX = 0;
Qva.StartoffsetY = 0;
Qva.ActiveObject = null;
Qva.SearchableObject = null;
Qva.ActiveElement = null;
Qva.PopupSearch = null;
Qva.KeepPopupSearchAlive = false;
Qva.DragRect = null;
Qva.DragStartX = 0;
Qva.DragStartY = 0;
Qva.DragRectLeft = 0;
Qva.DragRectTop = 0;
Qva.DragRectWidth = 0;
Qva.DragRectHeight = 0;
Qva.LabelClick = true;

Qva.PageBinding = function(id) {
    this.ID = id || "";
    if (Qva.binders[this.ID]) { alert("Need unique binderid"); return; }
    Qva.binders[this.ID] = this;

    this.OnUpdateBegin = null;
    this.IsUpdating = false;
    this.HasPendingLoad = false;
    this.PendingNames = [];
    this.ScrollLeftToRemember = 0;
    this.ScrollTopToRemember = 0;
    this.IsPartialLoad = false;
    this.CurrentLoadIsPartial = false;
    this.Enabled = false;
    this.First = true;
    this.Managers = new Array();
    this.Members = {}
    var loc = "" + window.location.pathname;
    if (loc.indexOf ("opendoc.htm") >= 0) {
        loc = loc.substr(0, loc.lastIndexOf("/") + 1);
    } else {
        loc = "/QvAJAXZfc/";
    }
    loc += "QvsViewClient.asp";
    try {
        this.Remote = (parent.qva && parent.qva.Remote) || loc;
    } catch (Error) {
        this.Remote = loc;
    }
    this.UsePost = true;
    this.JSON = false;
    this.Body = '';
    this.InitialSets = '';
    this.Mark = '';
    this.Stamp = '';
    this.RecursiveReadyLevel = 0;
    this.ShowMessage = Qva.DefaultShowMessage;
    this.OnSessionLost = Qva.DefaultOnSessionLost;
    this.OnUpdateComplete = Qva.NoAction;
    this.OnCreateContextMenu = Qva.DefaultOnCreateContextMenu;
    this.AllowComAgent = true;
    this.InlineStyle = true;
    this.TableLimit = 5000;
    this.Ident = null;
    this.TransientObject = '';
    this.GlobaSearchObject = '';
    this.ToggleSelect = "";
    this.ToggleSelects = null;
    this.TogglePhase = null;
    this.DelaySet = false;
    this.PendingDblClickName = '';
    this.PendingSearchName = '';
    this.PendingSearchKeyName = '';
    this.DefaultScope = 'Document';
    this.IsContained = false; //WB used for workbench/webpart objects to prevent minimize/move 
    this.CustomIcons = {}

    try {
        var impl = window.document.implementation;
        if (impl && impl.createDocument) {
            var doc = impl.createDocument("", "", null);
            if (doc.readyState == null) {
                doc.readyState = 1;
                doc.addEventListener("load", function() {
                    doc.readyState = 4;
                    if (typeof doc.onreadystatechange == "function") {
                        doc.onreadystatechange();
                    }
                }, false);
            }
            this.Doc = doc;
            this.LeftButton = 0;
        } else if (window.ActiveXObject) {
            this.Doc = new ActiveXObject("Microsoft.XMLDOM");
            this.LeftButton = 1;
        }
    } catch (e) { }
    if (this.Doc == null) throw new Error("Your browser does not support XmlDocument objects");
}

Qva.PageBinding.prototype.Start = function() {
    this.IsRemote = true;
    this.IsHosted = false;
    if (this.View == null && parent.qva != null) this.View = parent.qva.View;
    if (this.JSON) this.Session = Qva.ExtractProperty("session", this.Session);
    this.Ident = Qva.ExtractProperty("ident", this.Ident);
    this.Userid = Qva.ExtractProperty("userid", this.Userid);
    this.Xuserid = Qva.ExtractProperty("xuserid", this.Xuserid);
    this.Password = Qva.ExtractProperty("password", this.Password);
    this.Xpassword = Qva.ExtractProperty("xpassword", this.Xpassword);
    this.Bookmark = Qva.ExtractProperty("bookmark", this.Bookmark);
    this.View = Qva.ExtractProperty("application", this.View);
    this.InitialSelections = Qva.ExtractPropertyArray("select", this.InitialSelections)
    //    this.Ticket = Qva.ExtractProperty("ticket", this.Ticket);
    this.Ticket = Qva.ExtractPropertyForDocument("ticket", this.View, this.Ticket);
    this.AsyncServer = Qva.ExtractProperty("server") == "async";
    if (this.AsyncServer) this.AutoViewAppend(null, this.DefaultScope, 'asyncronous');
    this.Host = Qva.ExtractProperty("host", this.Host);
    if (Qva.Benchmark) {
        this.Benchmark = new Qva.Benchmark();
    }
    this.Url = this.Remote;
    this.Url += (this.Url.indexOf('?') == -1) ? '?mark=' : '&mark=';

    if (window.ActiveXObject && (this.Unicorn || window.location.protocol == "file:")) {
        this.TryAltAgent();
    }

    var _this = this;
    document.oncontextmenu = function(event) { return _this.OnContextMenu(event); }

    var useragent = "" + window.window.navigator.userAgent;
    var version = parseInt(useragent.substr(useragent.indexOf('MSIE') + 5, 3));
    this.AutoViewAppend(null, qva.DefaultScope, 'ie6' + (useragent.indexOf('MSIE') != -1 && version < 7));

    this.LoadBegin();
    // TODO: KeepAliveKicker ();
}

Qva.QueuePostPaintMessage = function (mgr) {
    for (var ix = 0; ix < Qva.AsyncPostPaintMgrQueue.length; ++ ix) {
        if (this.AsyncPostPaintMgrQueue [ix] == mgr) {
            return; // No need for multiple paints
        }
    }
    this.AsyncPostPaintMgrQueue.push (mgr);
    window.setTimeout (avqAsyncPostPaint, 0);
}

function avqAsyncPostPaint () {
    if (Qva.AsyncPostPaintMgrQueue.length == 0) {
        alert ("AsyncPostPaintMgrQueue.length == 0");
        return;
    }
    var mgr = Qva.AsyncPostPaintMgrQueue.shift ();
    mgr.PostPaint ();
}

Qva.MgrGetName = function (elem) {
    while (elem) {
        if (elem.AvqMgr != null) return elem.AvqMgr.Name;
        elem = elem.parentNode;
    }
    return "";
}

function ctrlKeyPressed (event) {
	// ctrlKey valid for windows - IE, Firefox
	// metaKey valid for Mac - Safari, Firefox
	// keyCode 224 for stopping onKeyUp on Firefox for Mac
	// keyCode 91 for stopping onKeyUp on Safari for Mac
	return event.ctrlKey || event.metaKey || event.keyCode == 224 || event.keyCode == 91;
}
Qva.OnMouseUp = function(event) {
    if (Qva.OnMouseupEvent) Qva.OnMouseupEvent(event);
    Qva.MgrWithMouseDown = null;
    if (!event) {
        event = window.event;
    }
    if (Qva.MgrWithSelectStart != null) {
        var mgr = Qva.MgrWithSelectStart;
        Qva.MgrWithSelectStart = null;
        var X = event.clientX;
        var Y = event.clientY;
        mgr.SelectEnd(X, Y, ctrlKeyPressed(event));
    } else {
        var elem = event.target;
        if (elem == null) elem = event.srcElement;
        if (Qva.MgrGetName(Qva.PopupSearch) != Qva.MgrGetName(elem)) {
            if (Qva.PopupSearch != null) {
                var binder = Qva.ClosePopupSearch();
                if (binder.Body != '') binder.LoadBegin();
            }
        }
    }
}

Qva.OnKeyUp = function (event) {
    if (Qva.PopupInput != null) return;
    if (!Qva.LabelClick) return;
    if (! event) {
        event = window.event;
    }
    var srcelement = event.target;
    if (! srcelement) srcelement = event.srcElement;
    if (event.keyCode == 13 && srcelement.tagName == 'INPUT' && srcelement.onchange) {
        srcelement.onchange();
    }
    if (srcelement.tagName == 'INPUT' && srcelement.type == 'text') return;
    if (Qva.SearchableObject) {
        var element = document.getElementById (Qva.SearchableObject);
        if (element && element.AvqMgr) {
            var binder = element.AvqMgr.PageBinder;
            if (binder.ToggleSelect != "" && (event.keyCode == 17 || event.keyCode == 224 || event.keyCode == 91)) {
                var objectName = binder.ToggleSelect;
                if (binder.TogglePhase != null && binder.ToggleSelects.length > 0) {
                    binder.Set (objectName, 'phase', binder.TogglePhase, false);
                }
                binder.TogglePhase = null;
                for (var i = 0; i < binder.ToggleSelects.length; i++) {
                    binder.Set (objectName, 'value', binder.ToggleSelects [i], false);
                }
                binder.ToggleSelects = null;
                binder.ToggleSelect = "";
                binder.LoadBegin ();
            } else if (element.AvqMgr.Searchable) {
                if (Qva.PopupSearch == null && event.keyCode >= 32 && ! ctrlKeyPressed (event)) {
                    var key = event.keyCode;
                    if (key >= 33 && key <= 40) {
                        if (key != 37 && key != 39) {
                            var currentkey;
                            switch (key) {
                            case 33:
                                currentkey = "pgup";
                                break;
                            case 34:
                                currentkey = "pgdn";
                                break;
                            case 35:
                                currentkey = "end";
                                break;
                            case 36:
                                currentkey = "home";
                                break;
                            case 38:
                                currentkey = "up";
                                break;
                            case 40:
                                currentkey = "down";
                                break;
                            }
                            binder.Set (element.AvqMgr.PageName, 'key', currentkey, true);
                        }
                    } else if ((key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 96 && key <= 107) || key == 109 || key == 111 || key == 187 || key == 189 || key == 226) {
                        Qva.OpenPopupSearch (element);
                        var character;
                        if (key == 226) {
                            if (event.shiftKey) {
                                character = ">";
                            } else {
                                character = "<";
                            }
                        } else {
                            if (key >= 96 && key <= 105) {
                                character = key - 96;
                            } else if (key == 106) {
                                character = "*";
                            } else if (key == 107 || key == 187) {
                                character = "+";
                            } else if (key == 109 || key == 189) {
                                character = "-";
                            } else if (key == 111) {
                                character = "/";
                            } else {
                                character = String.fromCharCode (key).toLowerCase ();
                            }
                            character = '*' + character + '*';
                        }
                        Qva.PopupSearch.value = character;
                        Qva.SetCursor (Qva.PopupSearch);
                        Qva.Search (element.AvqMgr, Qva.PopupSearch, key);
                    } 
                }
            }
        }
    }
}

Qva.Search = function (mgr, elem, key) {
    Qva.KeepPopupSearchAlive = (elem == Qva.PopupSearch);
    if (mgr.SearchName != "") {
        var binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
		if (binder.Enabled) {
			binder.Set (mgr.SearchName, "search", elem.value, true);
		} else {
			binder.PendingSearchName = mgr.SearchName;
			binder.PendingSearchValue = elem.value;
		}
	}
}
Qva.CloseSearch = function (mgr, elem, accept, ctrl) {
    Qva.KeepPopupSearchAlive = false;
    var SearchName = mgr.SearchName;
    var currentsearchvalue = elem.value;
    elem.value = "";
    elem.onkeyup = null;
    if (elem == Qva.PopupSearch) mgr.SearchName = null;
    
    var binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
    if (Qva.PopupSearch.searchcol != null) {
	    if (accept) binder.Set (SearchName + ":" + Qva.PopupSearch.searchcol, "searchcolumn", currentsearchvalue, true);
    } else {
        if (binder.Enabled) {
		    if (accept) binder.Set (SearchName, "search", currentsearchvalue, false);
		    var cmd;
		    if (accept) {
		        cmd = ctrl ? "ctrlaccept" : "accept";
		    } else {
		        cmd = "abort";
		    }
            binder.Set (SearchName, "closesearch", cmd, true);
        } else {
            binder.PendingSearchKey = (accept ? "accept" : "abort");
            binder.PendingSearchKeyName = SearchName;
        }
        var transientname = binder.TransientObject;
        if (transientname == SearchName) {
            binder.CloseTransient ();
        }
    }
}

Qva.OpenPopupSearch = function (elem, param) {
    var mgr = elem.AvqMgr;
    var searchname = elem.Name;
    if (! searchname) {
        searchname = mgr.Name || mgr.PageName;
        if (! searchname) {
            searchname = mgr.ColList [0].Name.split ('.') [1];
        }
    }
    var binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
    if (binder.TransientObject != searchname) {
        binder.CloseTransient ();
    }
    if (searchname == mgr.SearchName && mgr.Search != null) return;
    mgr.SearchName = searchname;
    Qva.PopupSearch = document.createElement ('input');
    Qva.PopupSearch.param = param;
    Qva.PopupSearch.tabIndex = 1;
    Qva.PopupSearch.className = 'avqEdit';
    Qva.PopupSearch.onkeydown = AvqAction_Search_KeyDown;
    Qva.PopupSearch.onkeyup = AvqAction_Search_KeyUp;
    Qva.PopupSearch.onfocus = AvqAction_Search_Focus;

    if (elem.xx != null) {
        if (elem.yy != 0) debugger;
        Qva.PopupSearch.searchcol = elem.xx;
    }
    mgr.Search = Qva.PopupSearch;
    Qva.PopupSearch.AvqMgr = mgr;
    var positionsource = Qva.GetFrame (mgr.Element);
    if (positionsource == null) {
        var element = document.getElementById (searchname.replace (mgr.PageBinder.DefaultScope + ".", ""));
        positionsource = Qva.GetFrame (element);
        if (positionsource == null) {
            positionsource = element;
        }
    }
    var elemPageCoords = Qva.GetAbsolutePageCoords (positionsource);
    Qva.PopupSearch.style.position = "absolute";
    Qva.PopupSearch.style.left = elemPageCoords.x + "px";
    Qva.PopupSearch.style.top = elemPageCoords.y - 19 + "px";
    Qva.PopupSearch.style.width = '100pt';
    Qva.PopupSearch.style.zIndex = 666;
    Qva.PopupSearch.style.border = '1pt solid black';
    Qva.PopupSearch.style.display = '';

    document.body.insertBefore (Qva.PopupSearch, document.body.firstChild);
    Qva.PopupSearch.focus ();
    Qva.KeepPopupSearchAlive = true;
}
Qva.ClosePopupSearch = function() {
    if (Qva.PopupSearch == null) return;
    var mgr = Qva.PopupSearch.AvqMgr;
    var binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
    if (mgr.SearchName != null) {
        binder.Set(mgr.SearchName, "closesearch", "abort", false);
    }
    if (Qva.ActiveElement == Qva.PopupSearch) Qva.ActiveElement = mgr.Element;
    mgr.SearchName = null;
    mgr.Search = null;
    document.body.removeChild(Qva.PopupSearch);
    Qva.PopupSearch = null;
    return binder;
}

Qva.OpenPopupInput = function (elem, inputbox) {
    Qva.ClosePopupInput ();
    var parent = elem;
    if (! inputbox) {
        parent = elem.parentNode;
    }
    Qva.PopupInput = document.createElement ("input");
    if (IS_GECKO || IS_SAFARI || IS_OPERA || IS_CHROME) {
        var gs = document.defaultView.getComputedStyle (parent, "");
        Qva.PopupInput.style.fontFamily = gs.getPropertyValue ("font-family");
        Qva.PopupInput.style.fontSize = gs.getPropertyValue ("font-size");
    } else {
        Qva.PopupInput.style.fontFamily = parent.currentStyle.fontFamily;
        Qva.PopupInput.style.fontSize = parent.currentStyle.fontSize;
    }
    Qva.PopupInput.style.top = parent.offsetTop + "px";
    Qva.PopupInput.style.left = parent.offsetLeft + "px";
    Qva.PopupInput.style.width = parent.clientWidth + "px";
    Qva.PopupInput.style.height = parent.clientHeight + "px";
    Qva.PopupInput.style.zIndex = 666;
    Qva.PopupInput.style.position = "absolute";
    Qva.PopupInput.style.border = "none";
    Qva.PopupInput.style.padding = "0px 0px 0px 0px";
    if (inputbox) {
        Qva.PopupInput.value = elem.value;
        Qva.PopupInput.inputname = elem.inputname;
    } else {
        Qva.PopupInput.value = parent.innerText;
    }
    Qva.PopupInput.onmousedown = Qva.CancelAction;
    Qva.PopupInput.onmouseup = Qva.CancelAction;
    Qva.PopupInput.onclick = Qva.CancelAction;
    Qva.PopupInput.onkeydown = function (event) {
        if (! event) { event = window.event; }
        var key = event.keyCode;
        switch (key) {
        case 13:    // <Enter>
            var binder = Qva.GetBinder(this.binderid);
            if (!binder.Enabled) return;
            if (this.inputname) {
                binder.Set (this.inputname, "text", this.value, true);
            } else {
                binder.Set (this.targetname, "inputvalue", this.xx + ":" + this.yy + ":" + this.value, true);
            }
        case 27:    // <Escape>
            break;
        }
    }
    Qva.PopupInput.onchange = function () {
        var binder = Qva.GetBinder(this.binderid);
        if (!binder.Enabled) return;
        if (this.inputname) {
            binder.Set (this.inputname, "text", this.value, true);
        } else {
            binder.Set (this.targetname, "inputvalue", this.xx + ":" + this.yy + ":" + this.value, true);
        }
    };
    Qva.PopupInput.binderid = elem.binderid;
    Qva.PopupInput.xx = elem.xx;
    Qva.PopupInput.yy = elem.yy;
    Qva.PopupInput.targetname = elem.targetname;
    parent.offsetParent.offsetParent.appendChild (Qva.PopupInput);
    
    Qva.PopupInput.focus ();
    Qva.SetCursor (Qva.PopupInput, true);
}
Qva.ClosePopupInput = function () {
    if (Qva.PopupInput == null) return;
    Qva.PopupInput.parentNode.removeChild (Qva.PopupInput);
    Qva.PopupInput = null;
}

Qva.AddRule = function (ss, name, style) {
    // Guard against security error
    try {
        if (ss.addRule) {
            ss.addRule (name, style);
        } else {
            ss.insertRule (name + " { " + style + " }", ss.cssRules.length);
        }
    } catch (e) {
    }
}

Qva.PageBinding.prototype.Refresh = function () {
    if (!this.Enabled) return;
    this.LoadBegin ();
}
Qva.PageBinding.prototype.LoadBegin = function (polling) {
    Qva.CloseMessagePopup ();
    if (this.IsUpdating) {
        this.HasPendingLoad = true;
        return;
    }
    if (this.OnUpdateBegin != null) this.OnUpdateBegin (polling);	
    
    if (!polling) this.IsUpdating = true;
    this.ScrollLeftToRemember = 0;
    this.ScrollTopToRemember = 0;
    Qva.ActiveElement = null;
    try {
        this.ScrollLeftToRemember = document.body.scrollLeft;
        this.ScrollTopToRemember = document.body.scrollTop;
        Qva.ActiveElement = document.activeElement;
        if (!polling) document.body.style.cursor = 'wait';
    } catch(e) { }

    if (!this.IsPartialLoad && !polling) {
        if (!Qva.KeepPopupSearchAlive && Qva.PopupSearch != null) {
            var mgr = Qva.PopupSearch.AvqMgr;
            var binder = mgr.PageBinder || Qva.GetBinder(mgr.binderid);
            if(binder == this) {
                Qva.ClosePopupSearch();
            }
        }
        Qva.ClosePopupInput ();
    }
    if (! Qva.KeepContextMenuAlive && !polling) {
        Qva.HideContextMenu ();
    }

    if (!polling) this.Enabled = false;
    if (!this.First) {
        for (var mix = 0; mix < this.Managers.length; ++mix) {
            var mgr = this.Managers [mix];
            if (this.IsRemote && !polling && mgr.Lock) mgr.Lock ();
            mgr.Touched = false;
        }
    }

    if (this.Benchmark != null) this.Benchmark.Load.Start();

    if (this.View == null && this.Kind == null) {
        this.Ready ();
    } else {
        if (this.AutoviewDictionary != null && !polling) {
            this.SetAutoviewAddCommands ();
        }
        this.Load (polling);
    }
}

Qva.PageBinding.prototype.DoPendingSearch = function (polling) {
    if (this.PendingSearchName == '' && this.PendingSearchKeyName == '') return false;
    if (this.PendingSearchName != '') {
        this.Set (this.PendingSearchName, "search", this.PendingSearchValue, false);
        this.PendingSearchName = '';
        this.PendingSearchValue = '';
    } 
    if (this.PendingSearchKeyName != '') {
        this.Set (this.PendingSearchKeyName, "closesearch", this.PendingSearchKey, false);
        Qva.ClosePopupSearch();
        this.PendingSearchKeyName = '';
    }
    return true;
}

Qva.PageBinding.prototype.Load = function (polling) {
    this.HasPendingLoad = false;
    
    this.CurrentLoadIsPartial = this.IsPartialLoad;
    this.IsPartialLoad = false;

    if (polling) {
        //nothing
    } else if (! this.DoPendingSearch () && this.PendingDblClickName != '') {
        this.Set (this.PendingDblClickName, "click", this.PendingDblClickName, false);
        this.PendingDblClickName = '';
    }
    var cmd = '<update mark="' + this.Mark + '" stamp="' + this.Stamp + '"';
    if (window.navigator && window.navigator.cookieEnabled) {
        cmd += ' cookie="true"';
    } else {
        cmd += ' cookie="false"';
    }
    if (this.DefaultScope != null) cmd += ' scope="' + this.DefaultScope + '"';
    if (this.JSON && this.Session != null) cmd += ' session="' + this.Session + '"';
    if (this.View != null) cmd += ' view="' + Qva.XmlEncode (this.View) + '"';
    if (this.Autoview != null && this.Autoview != "") cmd += ' autoview="' + Qva.XmlEncode (this.Autoview) + '"';
    cmd += ' ident="' + Qva.XmlEncode (this.Ident) + '"';
    if (this.Userid != null) cmd += ' userid="' + this.Userid + '"';
    if (this.Xuserid != null) cmd += ' xuserid="' + this.Xuserid + '"';
    if (this.Password != null) cmd += ' password="' + this.Password + '"';
    if (this.Xpassword != null) cmd += ' xpassword="' + this.Xpassword + '"';
    if (this.Kind != null) cmd += ' kind="' + this.Kind + '"';
    cmd += '>';
    if (polling) {
        cmd += '<poll />';
    } else {
        cmd += this.Body;
        if (!this.HasAutoviewAddCommands ()) {   // Do not add initial sets until all autoviews are done and we have space
            cmd += this.InitialSets;
            this.InitialSets = '';
        }
        this.Body = '';
    }
    cmd += '</update>';
    if (this.Trace != null && this.Trace.Request != null) this.Trace.Request.innerText = cmd;
    var pb = this;
    if (this.Agent == null) {
        var url = this.Url;
        
        if (this.Host != null) url += '&host=' + escape (this.Host);
        if (this.Ticket != null) url += '&ticket=' + escape (this.Ticket);
        if (this.View != null) url += '&view=' + escape (this.View);
        if (this.Userid != null) url += '&userid=' + escape (this.Userid);
        if (this.Xuserid != null) url += '&xuserid=' + escape (this.Xuserid);
        if (this.Password != null) url += '&password=' + escape (this.Password);
        if (this.Xpassword != null) url += '&xpassword=' + escape (this.Xpassword);
        if (this.Mark == '') {
            var platform = "browser.";
            if (IS_CHROME) {
                platform += "chrome";
            } else if (IS_GECKO) {
                platform += "gecko." + GECKO_VERSION;
            } else if (IS_SAFARI) {
                platform += "safari";
            } else if (IS_OPERA) {
                platform += "opera";
            } else if (IS_IE) {
                platform += navigator.userAgent.substr(navigator.userAgent.indexOf('MSIE'), 8);    
            } else {
                platform += "unknown";
            }
            url += '&platform=' + escape(platform);
        }
        
        if(this.JSON) {
            if (this.Session != null) url += '&session=' + escape (this.Session);
            url += '&json=' + escape (this.ID);
            url += '&cmd=' + escape (cmd);
            
            var scriptTag = document.createElement("script");
            
            // Add script object attributes
            scriptTag.setAttribute("type", "text/javascript");
            scriptTag.setAttribute("src", url);
            
            // Create the script tag
            var head = document.getElementsByTagName("head").item(0);
            if(this.ScriptTag) {
                head.replaceChild(scriptTag, this.ScriptTag)
            } else {
                head.appendChild(scriptTag);
            }
            this.ScriptTag = scriptTag;
            
        } else if (this.UsePost) {
            var xmlhttp;
            if (window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest()
            } else {
                xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    if(xmlhttp.responseXML) { // somtime null in chrome
                        pb.Doc = xmlhttp.responseXML;
                    } else if(xmlhttp.responseText) {
                        debugger;
                        pb.loadXML(xmlhttp.responseText);
                    }
                    pb.Ready ();
                }
            }

            xmlhttp.open("POST", url, true);
            try {
                xmlhttp.send(cmd);
            } catch(e) {
                alert('Communication error.');
                this.Enabled = true;
            }
        } else {
            url += '&cmd=' + escape (cmd);
            this.Doc.onreadystatechange = function () {
                if (pb.Doc.readyState == 4) {
                    pb.Ready ();
                }
            }
            if (!this.Doc.load(url)) {
                alert('Communication error (get)');
                this.Enabled = true;
            }
        }
    } else {
        var data;
        try {
            data = this.UseExecute ? this.Agent.Execute (cmd) : this.Agent.XmlUpdate (cmd);
        } catch(e) {
            data = '<result><message text="Server not responding" /></result>';
        }
        if (!this.Doc.loadXML (data)) {
            alert ('Unexpected error loading');
            this.Enabled = true;
            return;
        }
        window.setTimeout (function () { pb.Ready() }, 0);	// make local loading asynchronous as well
    }
}

Qva.PageBinding.prototype.PartialLoad = function (name, pageoffset) {
    if (isNaN (parseInt (pageoffset))) return;
    this.IsPartialLoad = true;
    this.Set (name, "pageoffset", pageoffset, true);
}

Qva.PageBinding.prototype.AddManager = function (mgr) {
    mgr.PageBinder = this;
    mgr.Touched = false;
    mgr.Dirty = false;
    if (mgr.SelectedClassName == null) {
        mgr.SelectedClassName = 'AvqSelected';
        mgr.DeselectedClassName = 'AvqDeselected';
        mgr.EnabledClassName = 'AvqEnabled';
        mgr.DisabledClassName = 'AvqDisabled';
        mgr.LockedClassName = 'AvqLocked';
        mgr.ModeIfNotEnabled = 'n';    // Use "true" non-enabled mode
    }
    this.Managers [this.Managers.length] = mgr;
    this.Append (mgr, mgr.Name, mgr.Attr);
}

Qva.PageBinding.prototype.Append = function (mgr, name, attr, noautoview) {
    if (name == null || name.substr (0,1) == ".") debugger;
    if (name == null || name == "") return;
    var list = this.Members[name];
    if (list == null) {
        list = new Array ();
        this.Members[name] = list;
    }
    for (var i = 0; i < list.length; i ++) {
        if (list [i] == mgr) break;
    }
    if (i == list.length) {
        list [list.length] = mgr;
    }
    if (this.Autoview != null && ! noautoview) {
        var nameattr = name.split ('@');
        var autoviewname = nameattr [0];
        var autoviewattr = nameattr.length > 1 ? nameattr [1] : attr;
        this.AutoViewAppend (mgr, autoviewname, autoviewattr);
    }
}

Qva.PageBinding.prototype.HasAutoviewAddCommands = function () {
    if(this.AutoviewDictionary == null) return false;
    for (var name in this.AutoviewDictionary) {
        var item = this.AutoviewDictionary [name];
        if (item.dirty) return true;
    }
    return false;
}
Qva.PageBinding.prototype.AutoViewAppend = function (mgr, name, attr) {
    if (attr == null) attr = "text";
    if (this.AutoviewDictionary == null) this.AutoviewDictionary = {}
    var item = this.AutoviewDictionary[name];
    if (item == null) {
        item = {}
        item.dirty = true;
        item.attrs = "mode";
        this.AutoviewDictionary[name] = item;
    }
    if (item.attrs.indexOf(attr) == -1) {
        item.dirty = true;
        item.attrs += ";" + attr;
    }
}
Qva.PageBinding.prototype.SetAutoviewAddCommands = function() {
    for (var name in this.AutoviewDictionary) {
        var item = this.AutoviewDictionary[name];
        if (!item.dirty) continue;
        item.dirty = false;
        this.Set(name, 'add', item.attrs, false);
        if (this.First && this.Body.length > 900 && !this.UsePost) return;     // arbitrary length to keep URL below 1K
    }
    if (this.First && this.Bookmark != null) {
        this.Set('bookmark-apply', 'docaction', this.Bookmark, false);
    }
    if (this.First && this.InitialSelections != null) {
        for (var sel = 0; sel < this.InitialSelections.length; sel++) {
            var selection = this.InitialSelections[sel].split(",").reverse ();
            var objectpart = selection.pop ().split(".");
            var dataok = true;
            if (objectpart.length == 2) {
                // data source specified for object, could be either name of document or datasource
                if (objectpart[objectpart.length - 2] != this.View && objectpart[objectpart.length - 2] != this.ID)
                    dataok = false;
            } else if (objectpart.length == 0) {
                dataok = false;
            }
            if (dataok) {
                if (objectpart[objectpart.length - 1].indexOf("\\") == -1) {
                    var name = this.DefaultScope + ".Document\\" + objectpart[objectpart.length - 1];
                } else {
                    var name = this.DefaultScope + "." + objectpart[objectpart.length - 1];
                }

                this.Set(name, "initialset", selection.join (","), false);
            }
        }
        this.InitialSelections = null;
    }
}

Qva.PageBinding.prototype.loadXML = function (xmltext) {
    if(this.Doc && typeof this.Doc.loadXML !== "undefined") {
        return this.Doc.loadXML (xmltext)
    } else if(typeof DOMParser !== "undefined") {
        this.Doc = new DOMParser().parseFromString(xmltext, 'text/xml');
        return this.Doc != null;
    }
    return false;
}

function SetActiveStyle (element, isactive) {
    element.IsActive = isactive;
    if (element.style.display == "none") return;
    if (element.BorderWidth != null) {
        var bordercolor = isactive && element.ActiveBorderColor ? element.ActiveBorderColor : element.BorderColor;
        var borderstyle = element.BorderWidth + "pt " + element.BorderStyle + " " + bordercolor;
        element.style.border = borderstyle;
    }
    var captionelem = getSiblingByClassname (element, "caption");
    if (captionelem != null) {
        if (captionelem.style.display == "none") return;
        var color = isactive ? captionelem.activecolor : captionelem.color;
        if (color == null) return;
        if (captionelem.innerText == "Gg") {
            if (color.getAttribute ('bkgcolor')) captionelem.style.color = color.getAttribute ('bkgcolor');
        } else {
            setStyle (color, captionelem);
        }
        setBackgroundStyle (color, captionelem);
        captionelem.style.borderBottom = "1pt " + element.BorderStyle + " " + bordercolor;

        var numberofchildren = captionelem.childNodes.length;
        for (var ichild = 0; ichild < numberofchildren; ichild++) {
            var child = captionelem.childNodes [ichild];
            if (child.nodeName != "IMG") continue;
            var url = child.src;
            url = Qva.FixUrl (url, "color", color.getAttribute ('color'));
            url = Qva.FixUrl (url, "bkgcolor", color.getAttribute ('bkgcolor'));
            child.src = url;
        }
    }
}

function SetActiveAndSearchable (newsearchable, newactive) {
    if (newsearchable) {
        Qva.SearchableObject = newsearchable;
    }
    if (Qva.ActiveObject != newactive) {
        var oldelem = window.document.getElementById (Qva.ActiveObject + "_frame");
        if (oldelem) {
            SetActiveStyle (oldelem, false);
        } 
        var elem = window.document.getElementById (newactive + "_frame");
        if (elem) {
            SetActiveStyle (elem, true);
            Qva.ActiveObject = newactive;
        } else {
            Qva.ActiveObject = "";
        }
    } 
}

Qva.PageBinding.prototype.Ready = function() {
    if (this.RecursiveReadyLevel > 0) {
        return;
    }

    try {
        document.body.style.cursor = 'auto';
    } catch (e) { debugger }

    //    if (this.Enabled) { alert ('State error'); }
    this.Enabled = true;

    var pendingPoll = false;
    var openUrlWindow = null; // window opened from server using 'open/@url'
    for (; ; ) {
        if (this.Doc == null) {
            debugger;
            return;
        }
        var root = this.Doc.documentElement;
        if (this.View != null || this.Kind != null) {
            if (root == null) {
                var error_string = "";
                var parseError = this.Doc.parseError;
                if (parseError != null) {
                    error_string += 'Line: ' + parseError.line +
                    '\r\n\r\nChar: ' + parseError.filepos +
                    '\r\n\r\nReason: ' + parseError.reason + '\r\n\r\n';
                }
                error_string += 'Failed to load:\r\n\r\nURL: ' + this.Doc.url;
                this.ShowMessage(error_string);
                return;
            }
            switch (Qva.GetMessageCode(root) || Qva.GetMessage(root)) {
                case "Error: No Authentication":
                    var url = '/QvAjaxZfc/Authentication.asp?json='
                    var scriptTag = document.createElement("script");

                    // Add script object attributes
                    scriptTag.setAttribute("type", "text/javascript");
                    scriptTag.setAttribute("src", url);

                    // Create the script tag
                    var head = document.getElementsByTagName("head").item(0);
                    if (this.ScriptTag) {
                        head.replaceChild(scriptTag, this.ScriptTag)
                    } else {
                        head.appendChild(scriptTag);
                    }
                    this.ScriptTag = scriptTag;
                    return;

                case "15":
                case "Failed to open document, you don't have access to the server.":
                    if (Qva.RemainingRetries <= 0) break;
                    var loc = Qva.FixUrl("" + window.location, 'userid', "");
                    if (this.JSON && this.Session) loc = Qva.FixUrl(loc, 'session', this.Session);
                    loc = Qva.FixUrl(loc, 'retry', Qva.RemainingRetries);
                    window.location = loc;
                    return;
            }
            if (!this.IsHosted) {
                if (root.getAttribute('unicorn') == '3') Qva.Unicorn = true;
                var session = root.getAttribute('session');
                if (this.Session == null) {
                    this.Session = session; // remember;
                } else if (this.Session != session) {
                    var message = Qva.GetMessage(root);
                    if (message == null) {
                        message = "Session timed out";
                    }
                    this.OnSessionLost(message);
                    return;
                }
            }
            var pending = root.getAttribute('pending');
            if (this.AsyncServer) {
                if (pending != null) {
                    pendingPoll = true;
                    this.PendingNames = pending.split(';');
                } else {
                    this.PendingNames = [];
                }
            } else {
                if (pending == "true") this.HasPendingLoad = true;
            }

            var currentobjects = root.getElementsByTagName('object');
            var newactive = null;
            var newsearchable = null;
            if (currentobjects.length >= 1) {
                newactive = currentobjects[0].getAttribute('activeobject');
                newsearchable = currentobjects[0].getAttribute('searchableobject');
            }
            SetActiveAndSearchable(newsearchable, newactive);

            var open_nodes = root.getElementsByTagName('open');
            if (open_nodes.length >= 1) {
                for (var iUrl = 0; iUrl < open_nodes.length; iUrl++) {
                    var open_node = open_nodes[iUrl];
                    var url = open_node.getAttribute('url');
                    if (url) {
                        var redirect = open_node.getAttribute('redirect') == "true";
                        try {
                            var OpenDoc = window.parent["OpenDoc"];
                            var doc = Qva.ExtractProperty('document', null, false, url);
                            if (doc && OpenDoc) {
                                var urlparams = null;
                                var index = url.indexOf('&');
                                if (index > 0) { urlparams = url.substr(index); }
                                url = OpenDoc(doc, urlparams, Qva.ExtractProperty, Qva.FixUrl);
                            }
                            if(url) {
                                if (redirect) {
                                    window.parent.location = url;
                                } else {
                                    openUrlWindow = window.open(url);
                                    Qva.ShowOpenUrlMsg (url);
                                }
                            }
                        } catch (e) {
                            this.ShowMessage("Can't open '" + url + "' due to error: " + e.description);
                        }
                        open_node.setAttribute("url", "");
                    }
                }
            }
            var ident = root.getAttribute('ident');
            if (ident != null) this.Ident = ident;
            var kind = root.getAttribute('kind');
            if (kind != null) this.Kind = kind;
            var mark = root.getAttribute('mark');
            var stamp = root.getAttribute('stamp');
            if (mark != null && stamp != null) {
                this.Mark = mark;
                this.Stamp = stamp;
            }

            var partial = this.CurrentLoadIsPartial;
            this.CurrentLoadIsPartial = false;

            if (this.Benchmark != null) this.Benchmark.Load.Stop();
            if (this.Benchmark != null) this.Benchmark.Paint.Start();
            this.PaintTree(root, '', partial);
            if (this.Benchmark != null) this.Benchmark.Paint.Stop();

            var MoreAutoviewsToAdd = this.First && (this.HasAutoviewAddCommands() || this.InitialSets != '');
            if (this.PendingSearchName != '' || this.PendingSearchKeyName != '' || this.PendingDblClickName != '' ||
                MoreAutoviewsToAdd || this.HasPendingLoad) {
                this.Enabled = false;
                if (MoreAutoviewsToAdd) this.SetAutoviewAddCommands();
                if (this.Benchmark != null) this.Benchmark.Load.Start();
                this.Load();
                return;
            }
            this.IsUpdating = false;
            break;
        }
    }
    this.PaintDone(true, root);

    if (this.View != null || this.Kind != null) {
        var msg = Qva.GetErrorMessage(root);
        if (msg != null) {
            if (msg.indexOf("Error Message: Object expected") != -1 || msg.indexOf("Error Message: Failed to connect") != -1)
                Qva.ErrorMessage("Could not connect to server!");
            else
                Qva.ErrorMessage(msg);
        } else {
            var msg = Qva.GetMessage(root);
            if (msg != null) {
                this.ShowMessage(msg);
            }
        }
        if (this.Trace != null && this.Trace.Response != null) this.Trace.Response.innerText = this.Doc.xml;
    }
    if (this.First && this.DeveloperMode) {
        var errmsg = this.OnceAfterLoad();
        if (errmsg != null) this.ShowMessage(errmsg);
    }
    if (this.IsHosted && this.first) window.focus();
    if (this.IsRemote) {
        try {
            if (document.selection && document.selection.type != 'None') {
                var y = document.selection.createRange();
                if (y != null) y.select();
            }
        } catch (e) { debugger }
    }
    this.First = false;
    try {
        document.body.scrollLeft = this.ScrollLeftToRemember;
        document.body.scrollTop = this.ScrollTopToRemember;
        if (document.activeElement != Qva.ActiveElement) {
            Qva.ActiveElement.focus();
        }
    } catch (e) { }

    if (Qva.PopupSearch != null) Qva.KeepPopupSearchAlive = false;

    if (openUrlWindow != null) {
        openUrlWindow.focus();
    }

    if (pendingPoll) this.LoadBegin(true);
}

Qva.OpenUrlMsg = null;
Qva.ShowOpenUrlMsg = function (url) {
    if(!Qva.OpenUrlMsg) {
        Qva.OpenUrlMsg = document.createElement("div");
        Qva.OpenUrlMsg.className = "QvUrlPopup";
        document.body.appendChild(Qva.OpenUrlMsg);
    }
    Qva.OpenUrlMsg.innerHTML = "";
    Qva.OpenUrlMsg.style.display = "";
    var span = document.createElement("span");
    span.innerText = "The requested content has been opened in another window. ";
    Qva.OpenUrlMsg.appendChild(span);
    var span = document.createElement("span");
    span.innerText = "If not, ";
    Qva.OpenUrlMsg.appendChild(span);
    var link = document.createElement("a");
    link.href = url;
    link.innerText = "press here";
    Qva.OpenUrlMsg.appendChild(link);
    var top = parseInt ((Qva.GetViewportHeight () - Qva.OpenUrlMsg.offsetHeight) / 2);
    var left = parseInt ((Qva.GetViewportWidth () - Qva.OpenUrlMsg.offsetWidth) / 2);
    Qva.OpenUrlMsg.style.top = top + "px";
    Qva.OpenUrlMsg.style.left = left + "px";
    var span = document.createElement("span");
    span.innerText = "close";
    span.onclick = Qva.CloseUrlMsgDiv;
    span.style.position = "relative";
    span.style.cursor = "pointer";
    Qva.OpenUrlMsg.appendChild(span);
    span.style.top = Qva.OpenUrlMsg.offsetHeight - span.offsetTop - span.offsetHeight - 20 + "px";
    span.style.left = Qva.OpenUrlMsg.offsetWidth - span.offsetLeft - span.offsetWidth - 30 + "px";
    window.setTimeout (function () { Qva.CloseUrlMsgDiv (); }, 10000);
}

Qva.CloseUrlMsgDiv = function () {
    if(!Qva.OpenUrlMsg) {
        debugger;
    } else {
        Qva.OpenUrlMsg.style.display = "none";
    }
}

Qva.PageBinding.prototype.OnceAfterLoad = function () {
    var errors = [];
    var dix = 0;
    for (var mix = 0; mix < this.Managers.length; ++mix) {
        var mgr = this.Managers [mix];
        if (mgr.Name == '' || mgr.Name == '#edit#' || mgr.Touched) {
            if (dix != mix) this.Managers [dix] = this.Managers [mix];
            ++dix;
        } else {
            if (mgr.Name != '') {
                try { mgr.Element.style.display = 'none'; } catch (e) { debugger }
                errors [errors.length] = 'Not found: ' + mgr.Name;
            }
        }
    }
    this.Managers.length = dix;
    
    if (errors.length == 0) return null;
    var msg = 'Errors:\n' + errors.join ('\n');
    return msg;
}
Qva.PageBinding.prototype.PaintTree = function (rootnode, prefix, partial) {
    for (var node = rootnode.firstChild; node != null; node = node.nextSibling) {
        if (node.nodeName != 'value' && node.nodeName != 'action' && node.nodeName != 'group' && node.nodeName != 'list') continue;
        var name = prefix + node.getAttribute ('name');
        var list = this.Members[name];
        if (list != null) {
            var mode = 'd';
            switch (node.getAttribute ('mode')) {
            case "not-applicable":
                mode = 'n';
                break;
            case "hidden":
                mode = 'h';
                break;
            case "enabled":
                mode = 'e';
                break;
            }
            var xlen = list.length;
            for (var ixx = 0; ixx < xlen; ++ixx) {
                var mgr = list [ixx];
                var mgrmode = mode;
                if (mode != 'n' && mgr.HideIf && mgr.HideIf(node.getAttribute('value'), node.getAttribute('text'))) mgrmode = 'n'; 
                mgr.Paint (mgrmode, node, name, partial);
            }
        }
    }
    for (var group = rootnode.firstChild; group != null; group = group.nextSibling) {
        if (group.nodeName != 'value' && group.nodeName != 'object' && group.nodeName != 'group' && group.nodeName != 'list') continue;
        var grpprefix = prefix + group.getAttribute('name') + '.';
        this.PaintTree (group, grpprefix, partial);
    }
}
Qva.PageBinding.prototype.PaintDone = function (remote, root) {
    if (this.First) {
        if (!this.IsHosted) {
            try {
                if (document.cookie.indexOf ("qlikmachineid") == -1) {
                    if (window.navigator && window.navigator.cookieEnabled) {
                        var machineid = root.getAttribute ('machineid');
                        if (machineid != null) {
                            var expires = new Date();
                            expires.setFullYear(2222, 2, 2);
                            document.cookie = "qlikmachineid=" + machineid + "; expires=" + expires.toGMTString();
                        }
                    }
                }
            } catch(e) {
                debugger;
            }
        }
    }

    if (this.Benchmark != null) this.Benchmark.Unlock.Start();
    for (var mix = 0; mix < this.Managers.length; ++mix) {
        var mgr = this.Managers [mix];
        if (mgr.Dirty) {
            mgr.PostPaint ();
            mgr.Dirty = false;
        }
        if (this.AsyncServer && mgr.SetPending) {
            mgr.SetPending(this.PendingNames);
        } 
        if (this.IsRemote && !mgr.Touched && mgr.Unlock) mgr.Unlock ();
    }
    if (this.Benchmark != null) this.Benchmark.Unlock.Stop();

    if (this.Benchmark != null) this.Benchmark.UpdateComplete.Start();
    this.OnUpdateComplete ();
    if (this.Benchmark != null) this.Benchmark.UpdateComplete.Stop();

    if (this.Benchmark != null) this.Benchmark.Display();

}

Qva.PageBinding.prototype.CloseTransient = function () {
    this.DoPendingSearch ();
    this.Set (this.TransientObject, "closetransient", "ok", false);
    Qva.ClosePopupSearch();
    var transientobject = window.document.getElementById (this.TransientObject.replace (this.DefaultScope + ".", ""));
    if (transientobject) {
        transientobject.parentNode.parentNode.style.display = "none";
    }
    this.TransientObject = '';
}

Qva.PageBinding.prototype.Set = function (name, type, value, _final) {
    if (this.GlobaSearchObject != '') {
        if (this.GlobaSearchObject != name.substr (0, this.GlobaSearchObject.length) &&
            this.TransientObject != name.substr (0, this.TransientObject.length) && 
            (Qva.ContextMenuMgr == null || name != Qva.ContextMenuMgr.Name)) 
        {
            this.Set (this.GlobaSearchObject, "closesearch", "abort", true);
            this.GlobaSearchObject = '';
            this.CloseTransient ();
        }
    } else if (this.TransientObject != '') {
        if (this.TransientObject != name.substr (0, this.TransientObject.length) && 
            (this.GlobaSearchObject == "" || this.GlobaSearchObject != name.substr (0, this.GlobaSearchObject.length)) &&
            (Qva.ContextMenuMgr == null || name != Qva.ContextMenuMgr.Name)) 
        {
            if (this.TransientObject == this.ToggleSelect) {
                this.ToggleSelect = "";
                this.ToggleSelects = null;
            }
            this.CloseTransient ();
        }
    }
    name = Qva.MgrMakeName (name, this.DefaultScope);
//    this.Body += '<set name="' + name + '" ' + type + '="' + Qva.XmlEncode(value) + '"/>';
    this.Body += '<set name="' + name + '" ' + type + '="' + Qva.XmlEncode(value) + '" clientsizeWH="' + Math.round(Qva.GetViewportWidth() * Qva.Factor) + ':' + Math.round(Qva.GetViewportHeight() * Qva.Factor) + '"/>';
    if (_final) {
        if(this.LoadBegin_Timeout) clearTimeout(this.LoadBegin_Timeout);
        if(this.DelaySet) {
            var self = this;
            this.LoadBegin_Timeout = setTimeout(function() { self.LoadBegin(); }, 200);
            //setTimeout(function() { self.LoadBegin(); }, 100);
        } else {
            this.LoadBegin ();
        }
    }
}

Qva.PageBinding.prototype.SetInitial = function (name, type, value) {
    this.InitialSets += '<set name="' + name + '" ' + type + '="' + Qva.XmlEncode(value) + '"/>';
}

Qva.SelectChild = function(root, names, ix) {
    for (var node = root.firstChild; node; node = node.nextSibling) {
        switch(node.nodeName) {
        case 'object':
            if (node.getAttribute('name') != names[ix]) break;
            return (ix == 0) ? node : null;
        case 'group':
        case 'list':
            if (node.getAttribute('name') != names[ix]) break;
            return node;
        case 'value':
        case 'action':
            if (node.getAttribute('name') != names[ix]) break;
            return (ix == names.length - 1) ? node : null;
        }
    }
    return null;
}
Qva.PageBinding.prototype.Select = function(path) {
    if (path == null) return null;
    path = Qva.MgrMakeName (path, this.DefaultScope);
    var parts = path.split ('.');
    var node = this.Doc.documentElement;
    for (var ix = 0; node != null && ix < parts.length; ++ix) {
        node = Qva.SelectChild(node, parts, ix);
    }
    return node;
}

Qva.SelectNode = function(root, path) {
    if (root == null || path == null) return null;
    var parts = path.split ('.');
    var node = root;
    for (var ix = 0; node != null && ix < parts.length; ++ix) {
        node = this.SelectChild(node, parts, ix);
    }
    return node;
}

Qva.PageBinding.prototype.SetClick = function (event, name, elem) {
    if (! this.Enabled) return;
    if (this.ToggleSelect != "") return;
    Qva.MgrWithMouseDown = null;
    var clickstring = "";
    if (elem) {
        var offsetX = 0;
        var offsetY = 0;
        if (! event) {
            offsetX = window.event.offsetX;
            offsetY = window.event.offsetY;
        } else {
            var evtOffsets = Qva.GetOffsets (event);
            offsetX = evtOffsets.offsetX;
            offsetY = evtOffsets.offsetY;
        }
        clickstring += '' + offsetX + ':' + offsetY;
        var objectframeNode = Qva.GetFrame(elem);
        var graphwidth = parseInt (imagewidth (objectframeNode, elem));
        var graphheight = parseInt (imageheight (objectframeNode, elem));
        clickstring += ':' + graphwidth + ':' + graphheight;
    }
    this.Set (name, "click", clickstring, true);
}

Qva.PageBinding.prototype.SetNewSheet = function() {
    var ActiveSheetNode = this.Select (".ActiveSheet");
    if (ActiveSheetNode) {
        var newTab = ActiveSheetNode.getAttribute ("text");
        if (newTab) this.NavigateToSheet (newTab);
    }
}
Qva.PageBinding.prototype.NavigateToSheet = function(id) {
    var parameters = window.location.search;
    var url = id + ".htm";
    var loc = "" + window.location.pathname;
    if (loc.length < url.length || loc.substr(loc.length - url.length) != url) {
        if (parameters.length > 0) url += parameters;
        if (this.JSON) url = Qva.FixUrl(url, 'session', this.Session);
        url = Qva.FixUrl(url, 'userid');
        url = Qva.FixUrl(url, 'password');
        window.location = url;
    }
}

Qva.GetContainingModal = function() { return window.parent.Qva.Modal.instance; }
Qva.CloseModal = function () {
     if(window.parent.Qva.Modal)
    {
        var modal = window.parent.Qva.Modal.instance;
        if (modal != null) modal.Close();
    }
}
Qva.SetModalTitle = function (text) {
    if(window.parent.Qva.Modal)
    {
        var modal = window.parent.Qva.Modal.instance;
        if (modal != null) modal.SetTitle(text);
    }
    
}

Qva.OpenDragRect = function (X, Y) {
    X = Qva.StartoffsetX - Qva.SelectClient2OffsetX + Qva.GetScrollLeft ();
    Y = Qva.StartoffsetY - Qva.SelectClient2OffsetY + Qva.GetScrollTop ();
    if (Qva.DragRect == null) {
        Qva.DragRect = document.createElement ("div");
        Qva.DragRect.className = "QvDragRect";
        Qva.DragRect.style.position = "absolute";
        Qva.DragRect.style.left = X + "px";
        Qva.DragRect.style.top = Y + "px";
        Qva.DragRect.style.width = "0px";
        Qva.DragRect.style.height = "0px";
        Qva.DragRect.style.zIndex = 666;
        Qva.DragRect.style.display = '';

        Qva.DragRect.onmousemove = function (event) { Qva.MouseMove(event, Qva.MgrWithSelectStart); }
        
        document.body.insertBefore (Qva.DragRect, document.body.firstChild);
    } else {
        Qva.DragRect.style.left = X + "px";
        Qva.DragRect.style.top = Y + "px";
        Qva.DragRect.style.display = '';
    }
    
    Qva.DragStartX = X;
    Qva.DragStartY = Y;
    Qva.DragRectLeft = X;
    Qva.DragRectTop = Y;
    Qva.DragRectWidth = 0;
    Qva.DragRectHeight = 0;
}

Qva.SizeDragRect = function (X, Y) {
    X += Qva.GetScrollLeft ();
    Y += Qva.GetScrollTop ();
    Qva.DragRectLeft = X > Qva.DragStartX ? Qva.DragStartX : X;
    Qva.DragRectTop = Y > Qva.DragStartY ? Qva.DragStartY : Y;
    Qva.DragRectWidth = X > Qva.DragStartX ? X - Qva.DragStartX : Qva.DragStartX - X;
    Qva.DragRectHeight = Y > Qva.DragStartY ? Y - Qva.DragStartY : Qva.DragStartY - Y;
    Qva.DragRect.style.left = Qva.DragRectLeft + "px";
    Qva.DragRect.style.top = Qva.DragRectTop + "px";
    Qva.DragRect.style.width = Qva.DragRectWidth + "px";
    Qva.DragRect.style.height = Qva.DragRectHeight + "px";
}

Qva.CloseDragRect = function (X, Y, name, binderid, elem) {
    Qva.SizeDragRect (X, Y);
    var left = Qva.DragRectLeft + Qva.SelectClient2OffsetX - Qva.GetScrollLeft ();
    var top = Qva.DragRectTop + Qva.SelectClient2OffsetY - Qva.GetScrollTop ();
    var width = Qva.DragRectWidth;
    var height = Qva.DragRectHeight;
    var rectstring = '' + left + ':' + top + ':' + width + ':' + height;
    Qva.DragRect.style.display = 'none';
    var objectframeNode = Qva.GetFrame(elem);
    var graphwidth = parseInt (imagewidth (objectframeNode, elem));
    var graphheight = parseInt (imageheight (objectframeNode, elem));
    rectstring += ':' + graphwidth + ':' + graphheight;
    Qva.GetBinder(binderid).Set (name, "rect", rectstring, true);
}

Qva.MouseDown = function (event, mgr) {
    //if (! this.Enabled) return;
    Qva.MgrWithMouseDown = mgr;
    Qva.MgrWithSelectStart = null;
    if (! event) {
        event = window.event;
        if (mgr.Select != null) {
            event.returnValue = false;
        }
        Qva.StartoffsetX = window.event.offsetX;
        Qva.StartoffsetY = window.event.offsetY;
    } else {
        if (mgr.Select != null) {
            event.preventDefault ();
        }
        var evtOffsets = Qva.GetOffsets (event);
        Qva.StartoffsetX = evtOffsets.offsetX;
        Qva.StartoffsetY = evtOffsets.offsetY;
    }
}

Qva.MouseMove = function (event, mgr, mindelta) {
    //if (! this.Enabled) return;
    if (Qva.MgrWithMouseDown != mgr && Qva.MgrWithSelectStart != mgr) return;
    var offsetX = 0;
    var offsetY = 0;
    if (! event) {
        event = window.event;
        if (mgr.Select != null) {
            event.returnValue = false;
        }
        offsetX = event.offsetX;
        offsetY = event.offsetY;
    } else {
        if (mgr.Select != null) {
            event.preventDefault ();
        }
        var evtOffsets = Qva.GetOffsets (event);
        offsetX = evtOffsets.offsetX;
        offsetY = evtOffsets.offsetY;
    }
    var X = event.clientX;
    var Y = event.clientY;
    if (Qva.MgrWithMouseDown == mgr) {
        var deltaX = offsetX - Qva.StartoffsetX;
        var deltaY = offsetY - Qva.StartoffsetY;
        if (mindelta == null) mindelta = 4;
        if (deltaX < -mindelta || deltaX > mindelta || deltaY < -mindelta || deltaY > mindelta) {
            Qva.MgrWithMouseDown = null;
            Qva.MgrWithSelectStart = mgr;
            Qva.SelectClient2OffsetX = offsetX - X;
            Qva.SelectClient2OffsetY = offsetY - Y;
            if (Qva.MgrWithSelectStart.SelectStart != null) {
                Qva.MgrWithSelectStart.SelectStart (X, Y);
            }
        }
    }
    if (Qva.MgrWithSelectStart == mgr) {
        if (Qva.MgrWithSelectStart.Select != null) {
            Qva.MgrWithSelectStart.Select (X, Y);
        }
    }
}

Qva.MessagePopup = null;
Qva.ShowMessagePopup = function (msg, binder) {
    if(!Qva.MessagePopup) {
        Qva.MessagePopup = document.createElement("div");
        Qva.MessagePopup.className = "QvMessagePopup";
        document.body.appendChild(Qva.MessagePopup);
    } else {
        Qva.CloseMessagePopup ();
    }
    Qva.MessagePopup.style.display = "";
    var img = document.createElement("img");
    img.style.cssText = "float:right;"
    img.src = binder.BuildBinaryUrl (null, "", "CX");
    Qva.MessagePopup.appendChild(img);
    var br = document.createElement("br");
    Qva.MessagePopup.appendChild(br);
    var img = document.createElement("img");
    img.src = binder.BuildBinaryUrl (null, "", "HELPICON");
    Qva.MessagePopup.appendChild(img);
    var span = document.createElement("span");
    span.innerText = msg;
    span.style.cssText = "padding:15px 10px 10px 10px;"
    Qva.MessagePopup.appendChild(span);
    var width = Math.min (Qva.GetViewportWidth () - 100, Qva.MessagePopup.offsetWidth);
    var top = parseInt ((Qva.GetViewportHeight () - Qva.MessagePopup.offsetHeight) / 2);
    var left = parseInt ((Qva.GetViewportWidth () - width) / 2);
    Qva.MessagePopup.style.width = width + "px";
    Qva.MessagePopup.style.top = top + "px";
    Qva.MessagePopup.style.left = left + "px";
}

Qva.CloseMessagePopup = function () {
    if(Qva.MessagePopup) {
        Qva.MessagePopup.innerHTML = "";
        Qva.MessagePopup.style.display = "none";
        Qva.MessagePopup.style.width = "";
        Qva.MessagePopup.style.top = "";
        Qva.MessagePopup.style.left = "";
    }
}

Qva.PageBinding.prototype.ContextClientAction = function (event, elem) {
    if (! event) { event = window.event; }
    event.cancelBubble = true;
    if (elem.clientaction == "search") {
        Qva.OpenPopupSearch (elem, elem.param);
    } else if (elem.clientaction == "modal" && Qva.Modal.instance != null) {
        var modals = elem.param.split(':');
        Qva.Modal.instance.Show (this, Qva.Modal.instance.ScriptPath + modals[0] + '.htm?target=' + escape(elem.Name || elem.AvqMgr.Name), parseInt(modals[1]), parseInt(modals[2]));
    } else if (elem.clientaction == "inputfield") {
        Qva.OpenPopupInput (elem);
    } else if (elem.clientaction == "confirm") {
        var parts = elem.param.split(':');
        var name = (elem.Name || elem.AvqMgr.Name) + '.' + parts[0];
        var msg = parts.slice(1).join(':');
        if (window.confirm(msg)) {
            this.Set(name, 'action', '', true);
        }
    } else if (elem.clientaction == "url") {
        window.open (elem.param);
    } else if (elem.clientaction == "bundledurl") {
        var url = this.BuildBinaryUrl (null, "", elem.param)
        window.open (url);
    } else if (elem.clientaction == "popup") {
        Qva.ShowMessagePopup (elem.param, this)
    } else {
        alert ("Not supported clientside action: " + elem.clientaction); 
    }
    Qva.HideContextMenu ();
    return false;
}

Qva.PageBinding.prototype.OnContextMenu = function (event, name) {
    if (! event) event = window.event;
    if (event.shiftKey && ctrlKeyPressed (event)) return; 
    Qva.HideContextMenu ();
    var position = null;
    var fullname;
    var srcelement = event.target;
    if (! srcelement) {
        srcelement = event.srcElement;
    }
    if (srcelement.position != null) {
        fullname = srcelement.targetname ? this.DefaultScope + "." + srcelement.targetname : name;
        position = srcelement.position;
    } else if (name) {
        fullname = name;
        if (srcelement.tagName == "IMG" && srcelement.isgraph) {
            var pos = Qva.GetPageCoords(srcelement);
            position = (event.clientX - pos.x) + ':' + (event.clientY - pos.y);
        } else {
            position = "";
        }
    } else if (Qva.LabelClick) {
        fullname = this.DefaultScope + '.StandardActions';
    } else {
        return;
    }
    return this.OnCreateContextMenu (this, event, fullname, position);
}

Qva.HideContextMenu = function () {
    if (Qva.ContextMenu == null) return;
    if (Qva.ContextMenuMgr.SubMenuRow && Qva.ContextMenuMgr.SubMenuRow.SubMenu) {
        document.body.removeChild (Qva.ContextMenuMgr.SubMenuRow.SubMenu);
        Qva.ContextMenuMgr.SubMenuRow.SubMenu = null;
    }
    while (Qva.ContextMenu.rows.length > 0) {
        Qva.ContextMenu.deleteRow (Qva.ContextMenu.rows.length - 1);
    }
    Qva.ContextMenu.style.display = 'none';
}

Qva.PageBinding.prototype.TryAltAgent = function () {
    try {
        if(external && typeof (external.AvqIdent) == "string") {
            var _this = this;
            external.AvqInitServer (this.View, function() { if (_this.Enabled) _this.LoadBegin(); });
            if (this.HostedTitle == null) {
                external.AvqTitle (document.title);
            } else if (this.HostedTitle != "") {
                external.AvqTitle (this.HostedTitle);
            }
            this.IsRemote = false;
            this.IsHosted = true;
            this.Ident = external.AvqIdent;
            this.Kind = external.AvqKind;
            this.Agent = external;
        } else if (this.AllowComAgent) {
            try {
                var segm = /[\?\&]admin=/.exec (this.Remote);
                this.Agent = new ActiveXObject ("QvsRemote.Client");
            this.UseExecute = true;
                if (segm == null) {
                    this.Agent.Connect("localhost", true);
                } else {
                    this.Agent.AdminConnect("localhost");
                }
                this.IsRemote = false;
            } catch (e) {
                // will fail later
            }
        }
    } catch (e) {
        debugger
    }
}

Qva.PageBinding.prototype.BuildBinaryUrl = function (path, stamp, name, color) {
    if (!this.Unicorn && this.IsHosted) {
        if (! this.ImageFolder) {
            this.ImageFolder = path.replace (name + ".png", "");
        }
        return path;
    }
    if (name != null && stamp == null && this.CustomIcons [name]) {
        return this.CustomIcons [name];
    }
    var url = this.Url;
    url = url.replace ('mark=', 'datamode=binary');
    if (name != null) {
        url += '&name=' + escape (name);
    }
    if (this.Host != null) url += '&host=' + escape (this.Host);
    if (stamp != null) {
        url += '&stamp=' + escape (stamp);
        if (this.Ticket != null) url += '&ticket=' + escape (this.Ticket);
        if (this.View != null) url += '&view=' + escape (this.View);
        if (this.Kind != null) url += '&kind=' + this.Kind;
        if (this.Userid != null) url += '&userid=' + this.Userid;
        if (this.Xuserid != null) url += '&xuserid=' + this.Xuserid;
        if (this.Password != null) url += '&password=' + this.Password;
        if (this.Xpassword != null) url += '&xpassword=' + this.Xpassword;
    } else { // no stamp is session independent images
        url += '&public=only';
    }
    if (this.Session != null && this.JSON) url += '&session=' + escape (this.Session);
    if (color) url += '&color=' + escape (color);
    return url;
}

Qva.PageBinding.prototype.RemoveFromManagers = function (mgr) {
    var mix = -1;
    for (var ix = 0; ix < this.Managers.length; ++ ix) {
        if (this.Managers [ix] == mgr) {
            mix = ix;
            break;
        }
    }
    if (mix == -1) {
        debugger;
    } else {
        if (mix != this.Managers.length - 1) {
            var swap = this.Managers [mix];
            this.Managers [mix] = this.Managers [this.Managers.length - 1];
            this.Managers [this.Managers.length - 1] = swap;
            mix = this.Managers.length - 1;
        }
    }
    if (this.Managers [mix].Element.AvqMgr != null) {
        if (this.Managers [mix].Element.AvqMgr.Detach !== null) this.Managers [mix].Element.AvqMgr.Detach ();
        this.Managers [mix].Element.AvqMgr = null;
    }
    this.Managers [mix].Element = null;
    this.Managers.length = mix;
}
Qva.PageBinding.prototype.RemoveFromMembers = function (mgr) {
    var name = mgr.Name;
    if (name == null) debugger;
    if (name == null || name == "") return;
    var oldlist = this.Members[name];
    if (oldlist == null) {
        debugger;
        return;
    }
    var newlist = new Array ();
    for (var i = 0; i < oldlist.length; i ++) {
        if (oldlist [i] != mgr) {
            newlist [newlist.length] = oldlist [i];
        }
    }
    if (oldlist.length == newlist.length) {
        debugger;
    }
    this.Members[name] = newlist;
}

Qva.NoAction = function (event) {
    if (! event) event = window.event;
    if (! event) return;
    if (event.preventDefault) {
        event.preventDefault ();
    } else {
        event.returnValue = false;
    }
}

Qva.CancelAction = function (event) {
    if (! event) event = window.event;
    event.cancelBubble = true;
    this.pressed = true;
}

Qva.DefaultShowMessage = function (msg) { alert(msg); }
Qva.DefaultOnSessionLost = function (msg) {
//    Qva.RemainingRetries = parseInt(Qva.ExtractProperty("retry", "3"));
//    if(isNaN(Qva.RemainingRetries)) Qva.RemainingRetries = 3;
//    if (Qva.RemainingRetries < 1) {
//        document.body.innerText = msg;
//    } else {
//        document.body.innerText = msg + " Reconnecting...";
//        window.location = Qva.FixUrl(Qva.FixUrl("" + window.location, "session"), 'retry', Qva.RemainingRetries - 1);
//    }
    Qva.RetryMessage("Lost connection to server." + "<br><br>" + "Reconnecting...");
}

Qva.DefaultOnCreateContextMenu = function (binder, event, fullname, position) {
    event.cancelBubble = true;
    if (Qva.ContextMenu == null) { 
        Qva.ContextMenu = document.createElement ('table');
        Qva.ContextMenu.style.width = "140px";
        Qva.ContextMenu.style.position = "absolute";
        Qva.ContextMenu.style.zIndex = 666;
        Qva.ContextMenu.className = "contextmenu";
        var mgr = new Qva.Mgr.menu (binder, Qva.ContextMenu, binder.DefaultScope + ".Menu");
        Qva.ContextMenuMgr = mgr;
        document.body.appendChild(Qva.ContextMenu);
    } else {
        Qva.ContextMenu.style.display = "";
        while (Qva.ContextMenu.rows.length > 0) {
            Qva.ContextMenu.deleteRow ();
        }
    }
    var tr = Qva.ContextMenu.insertRow (-1);
    var td = tr.insertCell (-1);
    td.innerHTML = "<\BR>";
    var X = event.clientX + Qva.GetScrollLeft ();
    var Y = event.clientY + Qva.GetScrollTop ();
    Qva.ContextMenu.style.left = X + "px";
    Qva.ContextMenu.style.top = Y + "px";
    binder.Set (fullname, 'add', 'menu', false);
    if (position != null) binder.Set (fullname, 'position', position, false);
    try {
        Qva.ContextMenu.focus ();
    } catch (err) {} 
    Qva.KeepContextMenuAlive = true;
    binder.LoadBegin ();
    return false;
}

Qva.XmlEncode = function (value) {
    var val = '' + value;
    val = val.replace (/&/g, '&amp;');
    val = val.replace (/</g, '&lt;');
    val = val.replace (/>/g, '&gt;');
    val = val.replace (/"/g, '&quot;');
    return val;
}
Qva.GetMessage = function(root) {
    var msg_nodes = root.getElementsByTagName ('message');
    if (msg_nodes.length >= 1) {
        var msg = msg_nodes[0].getAttribute ('text');
        if (msg && msg != '') return msg;
    }
    return null;
}
Qva.GetMessageCode = function(root) {
    var msg_nodes = root.getElementsByTagName ('message');
    if (msg_nodes.length >= 1) {
        var msg = msg_nodes[0].getAttribute ('code');
        if (msg && msg != '') return msg;
    }
    return null;
}

Qva.GetErrorMessage = function(root) {
    var error_nodes = root.getElementsByTagName ('Error');
    if (error_nodes.length >= 1) {
        var msg_nodes = root.getElementsByTagName ('message');
        if (msg_nodes.length >= 1) {
            var msg = msg_nodes[0].getAttribute ('text');
            if (msg && msg != '') return msg;
        }
    }
    return null;
}

Qva.GetViewportHeight = function () {
    if (window.innerHeight!=window.undefined) return window.innerHeight;
    if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
    if (document.body) return document.body.clientHeight; 
}
Qva.GetViewportWidth = function () {
    if (window.innerWidth!=window.undefined) return window.innerWidth; 
    if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
    if (document.body) return document.body.clientWidth; 
}
Qva.GetScrollTop = function () {
    if (self.pageYOffset) return self.pageYOffset; // all except Explorer
    if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Explorer 6 Strict
    return document.body.scrollTop; // all other Explorers
}

Qva.GetScrollLeft = function () {
    if (self.pageXOffset) return self.pageXOffset; // all except Explorer
    if (document.documentElement && document.documentElement.scrollLeft) return document.documentElement.scrollLeft; // Explorer 6 Strict
    return document.body.scrollLeft; // all other Explorers
}

Qva.MgrSplit = function (mgr, name, namePrefix) {
    if (name == null) return false;
    var segm = name.split ('@');
    switch (segm.length) {
    case 1:
        mgr.Attr = 'text';
        break;
    case 2:
        mgr.Attr = segm [1];
        break;
    case 3:
        mgr.Attr = (segm [1] != '') ? segm [1] : 'text';
        mgr.Dec = parseInt (segm [2]);
        break;
    default:
        return false;
    }
    mgr.Name = Qva.MgrMakeName (segm [0], namePrefix);
    return true;
}
Qva.MgrMakeName = function (name, namePrefix) {
    if (name == null) debugger;
    if (name.substr (0,1) == '.') {
        if (namePrefix == null) debugger; 
        return namePrefix + name;
    } else {
        return name;
    }
}

Qva.MgrGetDisplayFromMode = function (mgr, mode) {
    if (mgr.Element.disabled && mgr.ModeIfNotEnabled == 'h') {
        return 'none';
    } else if (mode == 'd' || mode == 'e' || mgr.ModeIfNotEnabled == 'd') {
        return '';
    } else {
        return 'none';
    }
}

Qva.Trunc = function (txt, ndec) {
    var dot = txt.indexOf ('.');
    if (dot < 0) return txt;
    var adec = txt.length - dot - 1;
    if (adec <= ndec) return txt;
    var f = parseFloat (txt);
    if (isNaN (f)) return txt;
    var fact = Math.pow (10, ndec);
    f = Math.round (f * fact) / fact;
    return f.toString ();
}

Qva.LockDisabled = function () {
    if (this.LockedElem == null) {
        this.LockedElem = this.Element.disabled;
        this.Element.disabled = true;
    }
}
Qva.UnlockDisabled = function () { 
    this.Element.disabled = this.LockedElem; 
    this.LockedElem = null;
}
Qva.LockReadOnly = function () {
    if (this.ReadOnlyElem == null) {
        this.ReadOnlyElem = this.Element.readOnly;
        this.Element.readOnly = true;
    }
}
Qva.UnlockReadOnly = function () { 
    this.Element.readOnly = this.ReadOnlyElem; 
    this.ReadOnlyElem = null;
}

Qva.FixUrl = function (url, parameter, value) {
    var re = new RegExp ("[\?\&]" + parameter + "=[^\&]*", "i");
    url = url.replace(re, "");
    if(value != null) url += '&' + parameter + '=' + escape(value);
    if(url.indexOf ('?') == -1) url = url.replace(/&/, "?");
    return url;
}
Qva.ExtractProperty = function (name, defprop, allowEmpty, url) {
    var re_empty = new RegExp ("[\?\&]" + name + "=", "i");
    if(allowEmpty) {
        var re = new RegExp ("[\?\&]" + name + "=([^\&]*)", "i");
    } else {
        var re = new RegExp ("[\?\&]" + name + "=([^\&]+)", "i");
    }
    var segm = re.exec (url || window.location);
    try {
        if (segm == null && !re_empty.test (url || window.location)) segm = re.exec (top.location);
    } catch (e) {
    }
    return segm != null ? unescape (segm [1]) : defprop;
}
Qva.ExtractPropertyArray = function(name, defprop, allowEmpty, url) {
    var re_empty = new RegExp ("[\?\&]" + name + "=", "i");
    if (allowEmpty) {
        var re = new RegExp("[\?\&]" + name + "=([^\&]*)", "gi");
    } else {
        var re = new RegExp("[\?\&]" + name + "=([^\&]+)", "gi");
    }
    var selections = [];
    var usedurl = "";
    try {
        if (re_empty.test(url))
            usedurl = url;
        else if (re_empty.test(window.location))
            usedurl = window.location;
        else if (re_empty.test(top.location))
            usedurl = top.location;
    } catch (e) { }
    if (usedurl != "") {
        // reset lastIndex
        re.lastIndex = 0;
        do {
            var segm = re.exec(usedurl);
            if (segm != null)
                selections.push(unescape(segm[1]));
        } while (segm != null);
    }
    if (selections.length > 0)
        return selections;
    else
        return defprop;
}
Qva.ExtractPropertyForDocument = function(name, document, defprop, allowEmpty, url) {
    var ticket = null;
    var singelTicket = null;
    var properties = Qva.ExtractPropertyArray(name, defprop, allowEmpty, url);
    if (properties) {
        for (var row = 0; row < properties.length; row++) {
            var items = properties[row].split(":");
            if (items.length == 2) {
                if (items[0].toLowerCase() == document.toLowerCase())
                    ticket = items[1];
            }
            else
                singelTicket = properties[row];
        }
    }
    if (ticket == null && singelTicket != null)
        return singelTicket;
    else
        return ticket;
}
Qva.GetAbsolutePageCoords = function (element) {
    var coords = {x : 0, y : 0};
    while (element) {
        coords.x += element.offsetLeft;
        coords.y += element.offsetTop;
        element = element.offsetParent;
    }
    return coords;
}

Qva.GetPageCoords = function (element) {
    var coords = {x : 0, y : 0};
    while (element) {
        coords.x += element.offsetLeft;
        if (element.tagName == "DIV") coords.x -= element.scrollLeft
        coords.y += element.offsetTop;
        if (element.tagName == "DIV") coords.y -= element.scrollTop
        element = element.offsetParent;
    }
    coords.x -= Qva.GetScrollLeft ();
    coords.y -= Qva.GetScrollTop ();
    return coords;
}

Qva.GetOffsets = function (event, target) {
//    if(!target) target = event.target;
    if(!target) target = event.target  || event.srcElement;

    if (typeof target.offsetLeft == 'undefined') {
        target = target.parentNode;
    }
    var pageCoords = Qva.GetAbsolutePageCoords (target);
    var eventCoords = { 
        x: Qva.GetScrollLeft() + event.clientX,
        y: Qva.GetScrollTop()  + event.clientY
    };
    var offsets = {
        offsetX: eventCoords.x - pageCoords.x,
        offsetY: eventCoords.y - pageCoords.y
    };
    return offsets;
}

Qva.SetCursor = function (elem, input) {
    var cursorpos = 0;
    if (elem.value.length > 0) {
        cursorpos = elem.value.charAt (0) == "*" ? elem.value.length - 1 : elem.value.length;
    }
    if (window.document.selection) { // the deep ie caret position magic
        var sel = window.document.selection.createRange ();
        sel.moveStart ('character', -elem.value.length);
        sel.moveEnd ('character', -elem.value.length);
        if (input) {
            sel.moveStart ('character', 0);
            sel.moveEnd ('character', elem.value.length);
        } else {
            sel.moveStart ('character', cursorpos);
        }
        sel.select ();
    } else if (elem.selectionStart) { // mozilla
        if (input) {
            elem.selectionStart = 0;
            elem.selectionEnd = elem.value.length;
        } else {
            elem.selectionStart = Math.max (1, cursorpos);
            elem.selectionEnd = Math.max (1, cursorpos);
        }
    }
}

Qva.CancelBubble = function (event) {
    if (!event) {
        window.event.cancelBubble = true;
    } else {
        event.stopPropagation();
    }
}

function dosearch (elem) { Qva.OpenPopupSearch (elem); }


function AvqAction_Search_KeyDown(event) {
    if (! event) { event = window.event; }
    var mgr = this.AvqMgr;
    var key = event.keyCode;
    switch (key) {
    case 13:    // <Enter>
        Qva.CloseSearch (mgr, this, true, ctrlKeyPressed (event));
        break;
    case 27:    // <Escape>'
        var _this = this;
        window.setTimeout (function () { Qva.CloseSearch (mgr, _this, false); }, 0);
        break;
    }
}
function AvqAction_Search_KeyUp(event) {
    if (!event) { event = window.event; }
    var key = event.keyCode;
    switch (key) {
    case 13:    // <Enter>
    case 27:    // <Escape>
        break;
    default:
        if (this.searchcol == null) {
            Qva.Search(this.AvqMgr, this, key);
        }
        break;
    }
}

function AvqAction_Search_Focus () {
    if (this.value == "") {
        this.value = this.param != null ? this.param : "**";
        Qva.SetCursor (this);
    }
}

function getSiblingByClassname (objectframeNode, classname) {
    for (var i = 0; i < objectframeNode.childNodes.length; i++) {
        var child = objectframeNode.childNodes [i];
        if (child.className != classname) continue;
        if (child.tagName != "DIV") continue;
        if (child.style.display == 'none') break;
        return child;
    }
    return null;
}

function imageheight (objectframeNode, element) {
	var graphheight = element.style.height;
	if (graphheight == 'auto' || element.autosize) {
	    if (graphheight == 'auto') element.autosize = true;
	    graphheight = getMaxClientHeight (objectframeNode);
        if (objectframeNode != element.parentNode) {
            graphheight = getContentMaxHeight (element.parentNode);
	    }
        if (graphheight < 0) {
	        graphheight = getClientHeight (element.parentNode);
        }
		element.style.height = graphheight + "px";
	    return graphheight;
	} else {
	    return element.offsetHeight;
	}
}

function imagewidth (objectframeNode, element) {
	var graphwidth = element.style.width;
	if (graphwidth == 'auto' || element.autosize) {
	    if (graphwidth == 'auto') element.autosize = true;
		graphwidth = getClientWidth (element.parentNode);
		element.style.width = graphwidth + "px";
	    return graphwidth;
	} else {
	    return element.offsetWidth;
	}
}

function getContentMaxHeight (element) {
    var objectframeNode = element.parentNode;
    var newparentheigh = getMaxClientHeight (objectframeNode);
    var numberofchildren = objectframeNode.childNodes.length;
    for (var ichild = 0; ichild < numberofchildren; ichild++) {
        var child = objectframeNode.childNodes [ichild];
        if (child == element) continue;
        if (child.nodeName != "DIV") continue;
        if (child.style.display == 'none') continue;
        if (child.className == "MoveZone") continue;
        if (child.className == "ResizeFrame") continue;
        newparentheigh -= child.offsetHeight;
    }
    if (newparentheigh > 0) return newparentheigh;
    newparentheigh = parseInt (element.style.height);
    if (isNaN (newparentheigh)) return 0;
    return newparentheigh;
}

function getClientWidth (elem) {
    if (IS_GECKO || IS_SAFARI || IS_OPERA || IS_CHROME) {
        var clientWidth = elem.offsetWidth;
        var gs = document.defaultView.getComputedStyle (elem, "");
        var pad = parseInt (gs.getPropertyValue ("padding-left")) + parseInt (gs.getPropertyValue("padding-right"));
        var bor = parseInt (gs.getPropertyValue ("border-left-width")) + parseInt (gs.getPropertyValue("border-right-width"));
        clientWidth -= pad;
        clientWidth -= bor;
        return clientWidth;
    } else {
        return elem.clientWidth;
    }
}

function getClientHeight (elem) {
    if (IS_GECKO || IS_SAFARI || IS_OPERA || IS_CHROME) {
        var clientHeight = elem.offsetHeight;
        var gs = document.defaultView.getComputedStyle (elem, "");
        var pad = parseInt (gs.getPropertyValue ("padding-top")) + parseInt (gs.getPropertyValue("padding-bottom"));
        var bor = parseInt (gs.getPropertyValue ("border-top-width")) + parseInt (gs.getPropertyValue("border-bottom-width"));
        clientHeight -= pad;
        clientHeight -= bor;
        return clientHeight;
    } else {
        return elem.clientHeight;
    }
}

function setFrameHeight (elem, deltaframeY) {
    if (! elem.maxclientheight) {
        if (! elem.style.height) return;
        var maxclientheight = getClientHeight (elem);
        elem.maxclientheight = maxclientheight;
    }
    var height = elem.maxclientheight - deltaframeY;
//    if (height != elem.offsetHeight) {
    if (height != getClientHeight (elem)) {
        elem.style.height = height + "px";
        if (elem.firstChild.ResizeType) Qva.Mgr.CreateAndUpdateResizeHandles(elem);
    }
}

function getMaxClientHeight (elem) {
    if (elem.maxclientheight) {
        return elem.maxclientheight;
    } else {
        return getClientHeight (elem);
    }
}

function setFrameWidth (elem, deltaframeX) {
    if (! elem.maxclientwidth) {
        if (! elem.style.width) return;
        var maxclientwidth = getClientWidth (elem);
        elem.maxclientwidth = maxclientwidth;
    }
    var width = elem.maxclientwidth - deltaframeX;
    if (width != getClientWidth (elem)) {
        elem.style.width = width + "px";
        if (elem.firstChild.ResizeType) Qva.Mgr.CreateAndUpdateResizeHandles(elem);
    }
}

function getMaxClientWidth (elem) {
    if (elem.maxclientwidth) {
        return elem.maxclientwidth;
    } else {
        return getClientWidth (elem);
    }
}

function setContentWidth (objectframeNode, newwidth) {
    if (newwidth == null) newwidth = getClientWidth (objectframeNode);
    var numberofchildren = objectframeNode.childNodes.length;
    var anychanges = false;
    for (var ichild = 0; ichild < numberofchildren; ichild++) {
        var child = objectframeNode.childNodes [ichild];
        if (child.nodeName != "DIV") continue;
        if (child.style.display == 'none') continue;
        if (child.ResizeType) continue;
        var currentwidth = parseInt (child.style.width);
        if (currentwidth != newwidth) {
            child.style.width = newwidth + "px";
            anychanges = true;
        }
    }
    return anychanges; 
}

Qva.Hover = null;
Qva.PageBinding.prototype.GetHoverDiv = function () {
    if(!Qva.Hover) {
        Qva.Hover = document.createElement("div");
        Qva.Hover.className = "QvHover";
        Qva.Hover.style.zIndex = 666;
        Qva.Hover.style.display = "none";
        Qva.Hover.style.position = "absolute";
        Qva.Hover.style.backgroundColor = "#FFFFCC";
        Qva.Hover.style.border = "solid 1px black";
        Qva.Hover.style.padding = "1px 3px 2px 3px";
        document.body.appendChild(Qva.Hover);
        new Qva.Mgr.hover (this, Qva.Hover, this.DefaultScope + ".Hover");
    }
    return Qva.Hover;
}

Qva.GetFrame = function (elem) {
    function EndsWidth(str, end) {
        return str && str.length >= end.length && str.substr(str.length - end.length) == end;
    }
    while(elem && !EndsWidth(elem.id, "_frame")) {
        elem = elem.parentNode;
    }
    return elem;
}
Qva.RetryMessage = function(msg) {
    var msgdiv = document.createElement("DIV");
    msgdiv.className = "HTMLMessage";
    var textdiv = document.createElement("DIV");
    textdiv.style.width = "75%";
    textdiv.style.height = "100%";
    textdiv.innerHTML = msg;
    msgdiv.appendChild(textdiv);
    var img = document.getElementById("WorkingGif");
    if (img) {
        img.style.display="block";
        img.style.position="absolute";
        img.style.left = "85%";
        img.style.top = "40%";
        msgdiv.appendChild(img);
    }
    var cancelbtn = document.createElement("BUTTON");
    cancelbtn.innerText = "Cancel";
    cancelbtn.style.display="block";
    cancelbtn.style.position="absolute";
    cancelbtn.style.left = "75%";
    cancelbtn.style.top = "75%";
    var to = setTimeout( function() {
        //window.location = Qva.FixUrl("" + window.location, "session");
        //window.location = Qva.FixUrl(Qva.FixUrl("" + window.location, "session"), "ticket");
        //window.parent.location = Qva.FixUrl("" + window.parent.location, "session");
        
        var l = window.parent.location + "";
        var i = l.lastIndexOf("#")
        if(i != -1) l = l.substr(0, i);
        window.parent.location = Qva.FixUrl(l, "session");
    },5000);
    cancelbtn.onclick = function() {
        clearTimeout(to); 
        textdiv.innerHTML += "<br><br>Action canceled by user";
        if (img) img.style.display = "none";
        cancelbtn.style.display = "none";
    }
    msgdiv.appendChild(cancelbtn);
    
    document.body.appendChild(msgdiv);
}
Qva.ErrorMessage = function(msg) {
    var msgdiv = document.createElement("DIV");
    msgdiv.className = "HTMLMessage";
    var textdiv = document.createElement("DIV");
    textdiv.style.width = "100%";
    textdiv.style.height = "100%";
    textdiv.innerHTML = msg;
    textdiv.style.overflow = "auto";
    msgdiv.appendChild(textdiv);
    document.body.appendChild(msgdiv);
}
Qva.addEvent = function(el, evname, func) {
    el["on" + evname] = func;
//    if (el.attachEvent) { // IE
//        el.attachEvent("on" + evname, func);
//    } else if (el.addEventListener) { // Gecko / W3C
//        el.addEventListener(evname, func, false);
//    } else {
//        el["on" + evname] = func;
//    }
}
Qva.removeEvent = function(el, evname, func) {
    el["on" + evname] = null;
//    if (el.detachEvent) { // IE
//        el.detachEvent("on" + evname, func);
//    } else if (el.removeEventListener) { // Gecko / W3C
//        el.removeEventListener(evname, func, true);
//    } else {
//        el["on" + evname] = null;
//    }
};
Qva.cancelSelectEvent_md = function(event) {
    if (! Qva.MouseDown) return;
    
    event = event || window.event;
    var target   = event.target || event.srcElement;
    if (Qva.DragDrop.curDrag || (target.nodeName!="INPUT" && target.nodeName!="SELECT")) 
        Qva.cancelSelectEvent = true;
    //prevents text selections in Firefox
    if (Qva.cancelSelectEvent && event.preventDefault) event.preventDefault();

}
Qva.cancelSelectEvent_mm = function(event) {
    if (Qva.cancelSelectEvent) return false;
}

Qva.LoadScript = function(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

