/**
 * ====================================================================
 * About
 * ====================================================================
 * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
 * The library supports Gecko based browsers like Mozilla and Firefox,
 * Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and a little of Opera
 * @version 0.9.7.6
 * @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
 * ====================================================================
 * Licence
 * ====================================================================
 * Sarissa is free software distributed under the GNU GPL version 2 (see <a href="gpl.txt">gpl.txt</a>) or higher, 
 * GNU LGPL version 2.1 (see <a href="lgpl.txt">lgpl.txt</a>) or higher and Apache Software License 2.0 or higher 
 * (see <a href="asl.txt">asl.txt</a>). This means you can choose one of the three and use that if you like. If 
 * you make modifications under the ASL, i would appreciate it if you submitted those.
 * In case your copy of Sarissa does not include the license texts, you may find
 * them online in various formats at <a href="http://www.gnu.org">http://www.gnu.org</a> and 
 * <a href="http://www.apache.org">http://www.apache.org</a>.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
 * WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * <p>Sarissa is a utility class. Provides "static" methods for DOMDocument, 
 * DOM Node serialization to XML strings and other utility goodies.</p>
 * @constructor
 */
function Sarissa(){};
Sarissa.PARSED_OK = "Document contains no parsing errors";
Sarissa.PARSED_EMPTY = "Document is empty";
Sarissa.PARSED_UNKNOWN_ERROR = "Not well-formed or other error";
var _sarissa_iNsCounter = 0;
var _SARISSA_IEPREFIX4XSLPARAM = "";
var _SARISSA_HAS_DOM_IMPLEMENTATION = document.implementation && true;
var _SARISSA_HAS_DOM_CREATE_DOCUMENT = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.createDocument;
var _SARISSA_HAS_DOM_FEATURE = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.hasFeature;
var _SARISSA_IS_MOZ = _SARISSA_HAS_DOM_CREATE_DOCUMENT && _SARISSA_HAS_DOM_FEATURE;
var _SARISSA_IS_SAFARI = (navigator.userAgent && navigator.vendor && (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1 || navigator.vendor.indexOf("Apple") != -1));
var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
if(!window.Node || !Node.ELEMENT_NODE){
    Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5,  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
};

if(typeof XMLDocument == "undefined" && typeof Document !="undefined"){ XMLDocument = Document; } 

// IE initialization
if(_SARISSA_IS_IE){
    // for XSLT parameter names, prefix needed by IE
    _SARISSA_IEPREFIX4XSLPARAM = "xsl:";
    // used to store the most recent ProgID available out of the above
    var _SARISSA_DOM_PROGID = "";
    var _SARISSA_XMLHTTP_PROGID = "";
    var _SARISSA_DOM_XMLWRITER = "";
    /**
     * Called when the Sarissa_xx.js file is parsed, to pick most recent
     * ProgIDs for IE, then gets destroyed.
     * @private
     * @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object
     * @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled
     */
    Sarissa.pickRecentProgID = function (idList){
        // found progID flag
        var bFound = false;
        for(var i=0; i < idList.length && !bFound; i++){
            try{
                var oDoc = new ActiveXObject(idList[i]);
                o2Store = idList[i];
                bFound = true;
            }catch (objException){
                // trap; try next progID
            };
        };
        if (!bFound) {
            throw "Could not retreive a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")";
        };
        idList = null;
        return o2Store;
    };
    // pick best available MSXML progIDs
    _SARISSA_DOM_PROGID = null;
    _SARISSA_THREADEDDOM_PROGID = null;
    _SARISSA_XSLTEMPLATE_PROGID = null;
    _SARISSA_XMLHTTP_PROGID = null;
    if(!window.XMLHttpRequest){
        /**
         * Emulate XMLHttpRequest
         * @constructor
         */
        XMLHttpRequest = function() {
            if(!_SARISSA_XMLHTTP_PROGID){
                _SARISSA_XMLHTTP_PROGID = Sarissa.pickRecentProgID(["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]);
            };
            return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
        };
    };
    // we dont need this anymore
    //============================================
    // Factory methods (IE)
    //============================================
    // see non-IE version
    Sarissa.getDomDocument = function(sUri, sName){
        if(!_SARISSA_DOM_PROGID){
            _SARISSA_DOM_PROGID = Sarissa.pickRecentProgID(["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]);
        };
        var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
        // if a root tag name was provided, we need to load it in the DOM object
        if (sName){
            // create an artifical namespace prefix 
            // or reuse existing prefix if applicable
            var prefix = "";
            if(sUri){
                if(sName.indexOf(":") > 1){
                    prefix = sName.substring(0, sName.indexOf(":"));
                    sName = sName.substring(sName.indexOf(":")+1); 
                }else{
                    prefix = "a" + (_sarissa_iNsCounter++);
                };
            };
            // use namespaces if a namespace URI exists
            if(sUri){
                oDoc.loadXML('<' + prefix+':'+sName + " xmlns:" + prefix + "=\"" + sUri + "\"" + " />");
            } else {
                oDoc.loadXML('<' + sName + " />");
            };
        };
        return oDoc;
    };
    // see non-IE version   
    Sarissa.getParseErrorText = function (oDoc) {
        var parseErrorText = Sarissa.PARSED_OK;
        if(oDoc.parseError.errorCode != 0){
            parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason + 
                "\nLocation: " + oDoc.parseError.url + 
                "\nLine Number " + oDoc.parseError.line + ", Column " + 
                oDoc.parseError.linepos + 
                ":\n" + oDoc.parseError.srcText +
                "\n";
            for(var i = 0;  i < oDoc.parseError.linepos;i++){
                parseErrorText += "-";
            };
            parseErrorText +=  "^\n";
        }
        else if(oDoc.documentElement == null){
            parseErrorText = Sarissa.PARSED_EMPTY;
        };
        return parseErrorText;
    };
    // see non-IE version
    Sarissa.setXpathNamespaces = function(oDoc, sNsSet) {
        oDoc.setProperty("SelectionLanguage", "XPath");
        oDoc.setProperty("SelectionNamespaces", sNsSet);
    };   
    /**
     * Basic implementation of Mozilla's XSLTProcessor for IE. 
     * Reuses the same XSLT stylesheet for multiple transforms
     * @constructor
     */
    XSLTProcessor = function(){
        if(!_SARISSA_XSLTEMPLATE_PROGID){
            _SARISSA_XSLTEMPLATE_PROGID = Sarissa.pickRecentProgID(["Msxml2.XSLTemplate.6.0", "MSXML2.XSLTemplate.3.0"]);
        };
        this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID);
        this.processor = null;
    };
    /**
     * Imports the given XSLT DOM and compiles it to a reusable transform
     * <b>Note:</b> If the stylesheet was loaded from a URL and contains xsl:import or xsl:include elements,it will be reloaded to resolve those
     * @argument xslDoc The XSLT DOMDocument to import
     */
    XSLTProcessor.prototype.importStylesheet = function(xslDoc){
        if(!_SARISSA_THREADEDDOM_PROGID){
            _SARISSA_THREADEDDOM_PROGID = Sarissa.pickRecentProgID(["MSXML2.FreeThreadedDOMDocument.6.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
        };
        xslDoc.setProperty("SelectionLanguage", "XPath");
        xslDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
        // convert stylesheet to free threaded
        var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID);
        // make included/imported stylesheets work if exist and xsl was originally loaded from url
        if(xslDoc.url && xslDoc.selectSingleNode("//xsl:*[local-name() = 'import' or local-name() = 'include']") != null){
            converted.async = false;
            if (_SARISSA_THREADEDDOM_PROGID == "MSXML2.FreeThreadedDOMDocument.6.0") { 
                converted.setProperty("AllowDocumentFunction", true); 
                converted.resolveExternals = true; 
            }
            converted.load(xslDoc.url);
        } else {
            converted.loadXML(xslDoc.xml);
        };
        converted.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
        var output = converted.selectSingleNode("//xsl:output");
        this.outputMethod = output ? output.getAttribute("method") : "html";
        this.template.stylesheet = converted;
        this.processor = this.template.createProcessor();
        // for getParameter and clearParameters
        this.paramsSet = new Array();
    };

    /**
     * Transform the given XML DOM and return the transformation result as a new DOM document
     * @argument sourceDoc The XML DOMDocument to transform
     * @return The transformation result as a DOM Document
     */
    XSLTProcessor.prototype.transformToDocument = function(sourceDoc){
        // fix for bug 1549749
        if(_SARISSA_THREADEDDOM_PROGID){
            this.processor.input=sourceDoc;
            var outDoc=new ActiveXObject(_SARISSA_DOM_PROGID);
            this.processor.output=outDoc;
            this.processor.transform();
            return outDoc;
        }
        else{
            if(!_SARISSA_DOM_XMLWRITER){
                _SARISSA_DOM_XMLWRITER = Sarissa.pickRecentProgID(["Msxml2.MXXMLWriter.6.0", "Msxml2.MXXMLWriter.3.0", "MSXML2.MXXMLWriter", "MSXML.MXXMLWriter", "Microsoft.XMLDOM"]);
            };
            this.processor.input = sourceDoc;
            var outDoc = new ActiveXObject(_SARISSA_DOM_XMLWRITER);
            this.processor.output = outDoc; 
            this.processor.transform();
            var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
            oDoc.loadXML(outDoc.output+"");
            return oDoc;
        };
    };
    
    /**
     * Transform the given XML DOM and return the transformation result as a new DOM fragment.
     * <b>Note</b>: The xsl:output method must match the nature of the owner document (XML/HTML).
     * @argument sourceDoc The XML DOMDocument to transform
     * @argument ownerDoc The owner of the result fragment
     * @return The transformation result as a DOM Document
     */
    XSLTProcessor.prototype.transformToFragment = function (sourceDoc, ownerDoc) {
        this.processor.input = sourceDoc;
        this.processor.transform();
        var s = this.processor.output;
        var f = ownerDoc.createDocumentFragment();
        if (this.outputMethod == 'text') {
            f.appendChild(ownerDoc.createTextNode(s));
        } else if (ownerDoc.body && ownerDoc.body.innerHTML) {
            var container = ownerDoc.createElement('div');
            container.innerHTML = s;
            while (container.hasChildNodes()) {
                f.appendChild(container.firstChild);
            }
        }
        else {
            var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
            if (s.substring(0, 5) == '<?xml') {
                s = s.substring(s.indexOf('?>') + 2);
            }
            var xml = ''.concat('<my>', s, '</my>');
            oDoc.loadXML(xml);
            var container = oDoc.documentElement;
            while (container.hasChildNodes()) {
                f.appendChild(container.firstChild);
            }
        }
        return f;
    };
    
    /**
     * Set global XSLT parameter of the imported stylesheet
     * @argument nsURI The parameter namespace URI
     * @argument name The parameter base name
     * @argument value The new parameter value
     */
    XSLTProcessor.prototype.setParameter = function(nsURI, name, value){
        // nsURI is optional but cannot be null 
        if(nsURI){
            this.processor.addParameter(name, value, nsURI);
        }else{
            this.processor.addParameter(name, value);
        };
        // update updated params for getParameter 
        if(!this.paramsSet[""+nsURI]){
            this.paramsSet[""+nsURI] = new Array();
        };
        this.paramsSet[""+nsURI][name] = value;
    };
    /**
     * Gets a parameter if previously set by setParameter. Returns null
     * otherwise
     * @argument name The parameter base name
     * @argument value The new parameter value
     * @return The parameter value if reviously set by setParameter, null otherwise
     */
    XSLTProcessor.prototype.getParameter = function(nsURI, name){
        nsURI = nsURI || "";
        if(this.paramsSet[nsURI] && this.paramsSet[nsURI][name]){
            return this.paramsSet[nsURI][name];
        }else{
            return null;
        };
    };
    /**
     * Clear parameters (set them to default values as defined in the stylesheet itself)
     */
    XSLTProcessor.prototype.clearParameters = function(){
        for(var nsURI in this.paramsSet){
            for(var name in this.paramsSet[nsURI]){
                if(nsURI){
                    this.processor.addParameter(name, null, nsURI);
                }else{
                    this.processor.addParameter(name, null);
                };
            };
        };
        this.paramsSet = new Array();
    };
}else{ /* end IE initialization, try to deal with real browsers now ;-) */
    if(_SARISSA_HAS_DOM_CREATE_DOCUMENT){
        /**
         * <p>Ensures the document was loaded correctly, otherwise sets the
         * parseError to -1 to indicate something went wrong. Internal use</p>
         * @private
         */
        Sarissa.__handleLoad__ = function(oDoc){
            Sarissa.__setReadyState__(oDoc, 4);
        };
        /**
        * <p>Attached by an event handler to the load event. Internal use.</p>
        * @private
        */
        _sarissa_XMLDocument_onload = function(){
            Sarissa.__handleLoad__(this);
        };
        /**
         * <p>Sets the readyState property of the given DOM Document object.
         * Internal use.</p>
         * @private
         * @argument oDoc the DOM Document object to fire the
         *          readystatechange event
         * @argument iReadyState the number to change the readystate property to
         */
        Sarissa.__setReadyState__ = function(oDoc, iReadyState){
            oDoc.readyState = iReadyState;
            oDoc.readystate = iReadyState;
            if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function")
                oDoc.onreadystatechange();
        };
        Sarissa.getDomDocument = function(sUri, sName){
            var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
            if(!oDoc.onreadystatechange){
            
                /**
                * <p>Emulate IE's onreadystatechange attribute</p>
                */
                oDoc.onreadystatechange = null;
            };
            if(!oDoc.readyState){
                /**
                * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p>
                * <ul><li>1 == LOADING,</li>
                * <li>2 == LOADED,</li>
                * <li>3 == INTERACTIVE,</li>
                * <li>4 == COMPLETED</li></ul>
                */
                oDoc.readyState = 0;
            };
            oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false);
            return oDoc;
        };
        if(window.XMLDocument){
            // do nothing
        }// TODO: check if the new document has content before trying to copynodes, check  for error handling in DOM 3 LS
        else if(_SARISSA_HAS_DOM_FEATURE && window.Document && !Document.prototype.load && document.implementation.hasFeature('LS', '3.0')){
            //Opera 9 may get the XPath branch which gives creates XMLDocument, therefore it doesn't reach here which is good
            /**
            * <p>Factory method to obtain a new DOM Document object</p>
            * @argument sUri the namespace of the root node (if any)
            * @argument sUri the local name of the root node (if any)
            * @returns a new DOM Document
            */
            Sarissa.getDomDocument = function(sUri, sName){
                var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
                return oDoc;
            };
        }
        else {
            Sarissa.getDomDocument = function(sUri, sName){
                var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null);
                // looks like safari does not create the root element for some unknown reason
                if(oDoc && (sUri || sName) && !oDoc.documentElement){
                    oDoc.appendChild(oDoc.createElementNS(sUri, sName));
                };
                return oDoc;
            };
        };
    };//if(_SARISSA_HAS_DOM_CREATE_DOCUMENT)
};
//==========================================
// Common stuff
//==========================================
if(!window.DOMParser){
    if(_SARISSA_IS_SAFARI){
        /*
         * DOMParser is a utility class, used to construct DOMDocuments from XML strings
         * @constructor
         */
        DOMParser = function() { };
        /** 
        * Construct a new DOM Document from the given XMLstring
        * @param sXml the given XML string
        * @param contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml). 
        * @return a new DOM Document from the given XML string
        */
        DOMParser.prototype.parseFromString = function(sXml, contentType){
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "data:text/xml;charset=UTF-8," + encodeURIComponent(sXml), false);
            xmlhttp.send(null);
            return xmlhttp.responseXML;
        };
    }else if(Sarissa.getDomDocument && Sarissa.getDomDocument() && Sarissa.getDomDocument(null, "bar").xml){
        DOMParser = function() { };
        DOMParser.prototype.parseFromString = function(sXml, contentType){
            var doc = Sarissa.getDomDocument();
            doc.loadXML(sXml);
            return doc;
        };
    };
};

if((typeof(document.importNode) == "undefined") && _SARISSA_IS_IE){
    try{
        /**
        * Implementation of importNode for the context window document in IE
        * @param oNode the Node to import
        * @param bChildren whether to include the children of oNode
        * @returns the imported node for further use
        */
        document.importNode = function(oNode, bChildren){
            var tmp;
            if(oNode.nodeName == "tbody" || oNode.nodeName == "tr"){
                tmp = document.createElement("table");
            }
            else if(oNode.nodeName == "td"){
                tmp = document.createElement("tr");
            }
            else if(oNode.nodeName == "option"){
                tmp = document.createElement("select");
            }
            else{
                tmp = document.createElement("div");
            };
            if(bChildren){
                tmp.innerHTML = oNode.xml ? oNode.xml : oNode.outerHTML;
            }else{
                tmp.innerHTML = oNode.xml ? oNode.cloneNode(false).xml : oNode.cloneNode(false).outerHTML;
            };
            return tmp.getElementsByTagName("*")[0];
        };
    }catch(e){ };
};
if(!Sarissa.getParseErrorText){
    /**
     * <p>Returns a human readable description of the parsing error. Usefull
     * for debugging. Tip: append the returned error string in a &lt;pre&gt;
     * element if you want to render it.</p>
     * <p>Many thanks to Christian Stocker for the initial patch.</p>
     * @argument oDoc The target DOM document
     * @returns The parsing error description of the target Document in
     *          human readable form (preformated text)
     */
    Sarissa.getParseErrorText = function (oDoc){
        var parseErrorText = Sarissa.PARSED_OK;
        if(!oDoc.documentElement){
            parseErrorText = Sarissa.PARSED_EMPTY;
        } else if(oDoc.documentElement.tagName == "parsererror"){
            parseErrorText = oDoc.documentElement.firstChild.data;
            parseErrorText += "\n" +  oDoc.documentElement.firstChild.nextSibling.firstChild.data;
        } else if(oDoc.getElementsByTagName("parsererror").length > 0){
            var parsererror = oDoc.getElementsByTagName("parsererror")[0];
            parseErrorText = Sarissa.getText(parsererror, true)+"\n";
        } else if(oDoc.parseError && oDoc.parseError.errorCode != 0){
            parseErrorText = Sarissa.PARSED_UNKNOWN_ERROR;
        };
        return parseErrorText;
    };
};
Sarissa.getText = function(oNode, deep){
    var s = "";
    var nodes = oNode.childNodes;
    for(var i=0; i < nodes.length; i++){
        var node = nodes[i];
        var nodeType = node.nodeType;
        if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){
            s += node.data;
        } else if(deep == true
                    && (nodeType == Node.ELEMENT_NODE
                        || nodeType == Node.DOCUMENT_NODE
                        || nodeType == Node.DOCUMENT_FRAGMENT_NODE)){
            s += Sarissa.getText(node, true);
        };
    };
    return s;
};
if(!window.XMLSerializer 
    && Sarissa.getDomDocument 
    && Sarissa.getDomDocument("","foo", null).xml){
    /**
     * Utility class to serialize DOM Node objects to XML strings
     * @constructor
     */
    XMLSerializer = function(){};
    /**
     * Serialize the given DOM Node to an XML string
     * @param oNode the DOM Node to serialize
     */
    XMLSerializer.prototype.serializeToString = function(oNode) {
        return oNode.xml;
    };
};

/**
 * strips tags from a markup string
 */
Sarissa.stripTags = function (s) {
    return s.replace(/<[^>]+>/g,"");
};
/**
 * <p>Deletes all child nodes of the given node</p>
 * @argument oNode the Node to empty
 */
Sarissa.clearChildNodes = function(oNode) {
    // need to check for firstChild due to opera 8 bug with hasChildNodes
    while(oNode.firstChild) {
        oNode.removeChild(oNode.firstChild);
    };
};
/**
 * <p> Copies the childNodes of nodeFrom to nodeTo</p>
 * <p> <b>Note:</b> The second object's original content is deleted before 
 * the copy operation, unless you supply a true third parameter</p>
 * @argument nodeFrom the Node to copy the childNodes from
 * @argument nodeTo the Node to copy the childNodes to
 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
 */
Sarissa.copyChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
    if((!nodeFrom) || (!nodeTo)){
        throw "Both source and destination nodes must be provided";
    };
    if(!bPreserveExisting){
        Sarissa.clearChildNodes(nodeTo);
    };
    var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
    var nodes = nodeFrom.childNodes;
    if(typeof(ownerDoc.importNode) != "undefined")  {
        for(var i=0;i < nodes.length;i++) {
            nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
        };
    } else {
        for(var i=0;i < nodes.length;i++) {
            nodeTo.appendChild(nodes[i].cloneNode(true));
        };
    };
};

/**
 * <p> Moves the childNodes of nodeFrom to nodeTo</p>
 * <p> <b>Note:</b> The second object's original content is deleted before 
 * the move operation, unless you supply a true third parameter</p>
 * @argument nodeFrom the Node to copy the childNodes from
 * @argument nodeTo the Node to copy the childNodes to
 * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is
 */ 
Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
    if((!nodeFrom) || (!nodeTo)){
        throw "Both source and destination nodes must be provided";
    };
    if(!bPreserveExisting){
        Sarissa.clearChildNodes(nodeTo);
    };
    var nodes = nodeFrom.childNodes;
    // if within the same doc, just move, else copy and delete
    if(nodeFrom.ownerDocument == nodeTo.ownerDocument){
        while(nodeFrom.firstChild){
            nodeTo.appendChild(nodeFrom.firstChild);
        };
    } else {
        var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
        if(typeof(ownerDoc.importNode) != "undefined") {
           for(var i=0;i < nodes.length;i++) {
               nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
           };
        }else{
           for(var i=0;i < nodes.length;i++) {
               nodeTo.appendChild(nodes[i].cloneNode(true));
           };
        };
        Sarissa.clearChildNodes(nodeFrom);
    };
};

/** 
 * <p>Serialize any object to an XML string. All properties are serialized using the property name
 * as the XML element name. Array elements are rendered as <code>array-item</code> elements, 
 * using their index/key as the value of the <code>key</code> attribute.</p>
 * @argument anyObject the object to serialize
 * @argument objectName a name for that object
 * @return the XML serializationj of the given object as a string
 */
Sarissa.xmlize = function(anyObject, objectName, indentSpace){
    indentSpace = indentSpace?indentSpace:'';
    var s = indentSpace  + '<' + objectName + '>';
    var isLeaf = false;
    if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String 
        || anyObject instanceof Boolean || anyObject instanceof Date){
        s += Sarissa.escape(""+anyObject);
        isLeaf = true;
    }else{
        s += "\n";
        var itemKey = '';
        var isArrayItem = anyObject instanceof Array;
        for(var name in anyObject){
            s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + "   ");
        };
        s += indentSpace;
    };
    return s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n");
};

/** 
 * Escape the given string chacters that correspond to the five predefined XML entities
 * @param sXml the string to escape
 */
Sarissa.escape = function(sXml){
    return sXml.replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&apos;");
};

/** 
 * Unescape the given string. This turns the occurences of the predefined XML 
 * entities to become the characters they represent correspond to the five predefined XML entities
 * @param sXml the string to unescape
 */
Sarissa.unescape = function(sXml){
    return sXml.replace(/&apos;/g,"'")
        .replace(/&quot;/g,"\"")
        .replace(/&gt;/g,">")
        .replace(/&lt;/g,"<")
        .replace(/&amp;/g,"&");
};
//   EOF

NIJS = {};
NIJS.Adeo = {}

var tempX = 0;
var tempY = 0;
var offsetX = 0;
var offsetY = 0;

var dragElem = null;
var resizeElem = null;
var resizeContent = null;
var frameHelper = null;
var currSelTab = 1;

var toolbarHeight;

AdeoGlobal = {};
AdeoGlobal.init = function() {
	if( document.getElementById('contentContainer'))
		document.getElementById('contentContainer').appendChild( windowContainer.Element);
	else if( windowContainer)
		document.body.appendChild( windowContainer.Element);

        if( document.getElementById( 'toolbarContainer')){
		toolbarHeight = document.getElementById( 'toolbarContainer').offsetHeight;
		document.getElementById( 'contentContainer').style.height = document.body.clientHeight - toolbarHeight;
        }else {
		document.body.style.overflow = 'auto';
        }
 };
AdeoGlobal.cloneObject = function(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new AdeoGlobal.cloneObject(what[i]);
        }
        else
            this[i] = what[i];
    }
};
AdeoGlobal.Editor = {};
AdeoGlobal.Editor.CurrentMode = 0;
AdeoGlobal.Editor.LastMouseOvered = null;
AdeoGlobal.Editor.LastMouseClicked = null;
AdeoGlobal.Editor.EditingModeCaptions = {};
AdeoGlobal.Editor.EditingModeCaptions.EN = [ 'Preview', 'Edit'],
AdeoGlobal.Editor.EditingModeCaptions.HR = [ 'Pregled', 'Promjena'];
AdeoGlobal.Editor.Mode = { PREVIEW : 0, EDIT : 1 };
AdeoGlobal.Editor.Modules = [ '', 'Page', 'Area', 'Data', 'Login', 'Menu', 'Text'];

AdeoGlobal.Editor.Module = {};
AdeoGlobal.Editor.Module.mouseOver = function( event, target){
	if( AdeoGlobal.Editor.CurrentMode != AdeoGlobal.Editor.Mode.EDIT)
		return;
	if( !target || !target.getAttribute( 'type') || target.getAttribute( 'editable') == "false")
		return;

	adeo.element.niStopBubbling( event);
	var inEditMode = target.getAttribute( 'inEditMode');
	if( inEditMode == 'true')
		return;
	
	if( AdeoGlobal.Editor.LastMouseOvered != null)
		AdeoGlobal.Editor.Module.mouseOut( AdeoGlobal.Editor.LastMouseOvered);
    
	var backgroundColor = AdeoGlobal.Css.getElementProp( target, 'backgroundColor');
	if( !backgroundColor)	{	
		target.setAttribute( 'haveBGC', 'no'); 
		backgroundColor = AdeoGlobal.Css.getElementUltimateProp( target, 'backgroundColor');
	}else 
		target.setAttribute( 'haveBGC', 'yes'); 
		
	var rgbColor = new RGBColor( backgroundColor ? backgroundColor : 'white');
	rgbColor.emphasize();
	
	target.setAttribute( 'bgc', backgroundColor);  
	target.style.backgroundColor = rgbColor.toHex();
	AdeoGlobal.Editor.LastMouseOvered = target;

};
AdeoGlobal.Editor.Module.mouseOut = function( event, target){
	if( AdeoGlobal.Editor.CurrentMode != AdeoGlobal.Editor.Mode.EDIT)
		return;
	
	if( target){
		if( target.getAttribute( 'haveBGC') == 'no')
			target.style.backgroundColor = '';
		else
			target.style.backgroundColor = target.getAttribute( 'bgc');

		if( AdeoGlobal.Editor.LastMouseOvered == target)
			AdeoGlobal.Editor.LastMouseOvered = null;
	}
};
AdeoGlobal.Editor.Module.mouseClick = function( event, target){
	if( AdeoGlobal.Editor.CurrentMode != AdeoGlobal.Editor.Mode.EDIT)
		return;
	if( !target || !target.getAttribute( 'type') || target.getAttribute( 'editable') == "false")
		return;
	adeo.element.niStopBubbling( event);
	var inRawMode = target.getAttribute( 'inRawMode');
	if( inRawMode == 'true')
		oSel.setTextArea( target);

	var inEditMode = target.getAttribute( 'inEditMode');
	if( inEditMode == 'true')
		return;

	AdeoGlobal.Editor.Menu( target);

	target.style.backgroundColor = target.getAttribute( 'bgc');
	if( AdeoGlobal.Editor.LastMouseOvered == target)
		AdeoGlobal.Editor.LastMouseOvered = null;

	if( AdeoGlobal.Editor.LastMouseClicked == target){
		AdeoGlobal.Editor.LastMouseClicked = null;
	}else{
		AdeoGlobal.Editor.LastMouseClicked = target;
		oSel.setElem( target);
	}
};
AdeoGlobal.Editor.Module.mouseDblClick = function( event, target){
	if( AdeoGlobal.Editor.CurrentMode != AdeoGlobal.Editor.Mode.EDIT)
		return;
	if( !target || !target.getAttribute( 'type') || target.getAttribute( 'editable') == "false")
		return;

	adeo.element.niStopBubbling( event);

	AdeoGlobal.Editor.Menu();
	var elemType = parseInt( target.getAttribute( 'type'));
	if( elemType == 1006) {
		target.style.backgroundColor = target.getAttribute( 'bgc');
		if( AdeoGlobal.Editor.LastMouseOvered == target)
			AdeoGlobal.Editor.LastMouseOvered = null;
		oSel.setElem( target);
		var module = new AdeoElement( target);
		module.switchToEditMode();
		oSel.updateHeight();

		adeoTabs.selectTab( 'pageEditor', 0); 
		windowContainer.displayWindowContent( '/Text.do?idtextinfo=2&idcss=309&prefix=pageEditor', 'pageEditorcont0', '100%', null, 'adeo.init();');

	} 
};
AdeoGlobal.Editor.toogleEditingMode = function( target){
	if( !target) return;
	AdeoGlobal.Editor.CurrentMode = (AdeoGlobal.Editor.CurrentMode + 1) % 2;

	var currentLang = target.getAttribute( 'lang');
	if( !currentLang || !eval( 'AdeoGlobal.Editor.EditingModeCaptions.' + currentLang)){
		currentLang = 'EN';
		target.setAttribute( 'lang', 'EN');
	}

	eval( 'target.innerHTML = AdeoGlobal.Editor.EditingModeCaptions.' + currentLang + '[ ' + AdeoGlobal.Editor.CurrentMode + ']');
};
AdeoGlobal.Editor.Menu = {}
AdeoGlobal.Editor.Menu = function( elem){
	var rem = document.getElementById( 'editorMenu');
	if( rem){
		rem.parentNode.removeChild( rem);
	}else{
		var adeoElem = new AdeoElement();
		adeoElem.setStyle( 'width', '100px');
		adeoElem.setStyle( 'backgroundColor', 'white');
		adeoElem.setAttribute( 'id', 'editorMenu');
		adeoElem.setStyle( 'border', '1px solid #666666');
		document.body.appendChild( adeoElem.Element);
		adeoElem.displayAbsolute();
	
		var elemType = parseInt( elem.getAttribute( "type") ? elem.getAttribute( "type") : '999');
		if( elemType > 1000){
			var str = AdeoGlobal.Editor.Modules[ elemType - 1000];
			adeoElem.add( AdeoGlobal.Editor.Menu.item( str + ' module', elem, null, null, null));
			adeoElem.add( AdeoGlobal.Editor.Menu.line());
		}
		if( elemType == 1002) {	
			
		}else if( elemType == 1003){

			adeoElem.add( AdeoGlobal.Editor.Menu.item( 'insert data', elem, AdeoGlobal.Editor.DataModule.insert, null, null));
			adeoElem.add( AdeoGlobal.Editor.Menu.line());
			adeoElem.add( AdeoGlobal.Editor.Menu.item( 'view data', elem, AdeoGlobal.Editor.DataModule.view, null, null));
			adeoElem.add( AdeoGlobal.Editor.Menu.line());
			adeoElem.add( AdeoGlobal.Editor.Menu.item( 'edit data', elem, AdeoGlobal.Editor.DataModule.edit, null, null));
			adeoElem.add( AdeoGlobal.Editor.Menu.line());

		}else if( elemType == 1006) {

			adeoElem.add( AdeoGlobal.Editor.Menu.item( 'edit text', elem, AdeoGlobal.Editor.Text.edit, null, null));
			adeoElem.add( AdeoGlobal.Editor.Menu.line());

		} 
		adeoElem.add( AdeoGlobal.Editor.Menu.item( 'edit css', elem, AdeoGlobal.Editor.Css.edit, null, null));
		adeoElem.add( AdeoGlobal.Editor.Menu.line());
		adeoElem.add( AdeoGlobal.Editor.Menu.item( 'add module end', elem, AdeoGlobal.Editor.addModule.Click, AdeoGlobal.Editor.addModule.showWhere, AdeoGlobal.Editor.addModule.showWhere));
		adeoElem.add( AdeoGlobal.Editor.Menu.line());
		adeoElem.add( AdeoGlobal.Editor.Menu.item( 'remove element', elem, AdeoGlobal.Editor.removeModule.Click, null, null));
	}
};
AdeoGlobal.Editor.Menu.line = function(){
	var adeoElem = new AdeoElement();
	adeoElem.setStyle( 'borderTop', '1px solid #666666');
	adeoElem.setStyle( 'width', '100%');
	adeoElem.setStyle( 'height', '1px');
	return adeoElem;
}
AdeoGlobal.Editor.Menu.item = function( text, elem, onClick, onOver, onOut){
	var adeoElem = new AdeoElement();
	adeoElem.setStyle( 'textAlign', 'center');
	adeoElem.setStyle( 'fontSize', '11px');
	adeoElem.setStyle( 'lineHeight', '14px');
	adeoElem.setAttribute( 'type', '1000');
	if( elem) {
		adeoElem.setAttribute( 'elemid', elem.id);
		if( elem.getAttribute('type') == '1002'){
			adeoElem.setAttribute( 'ancestorWhere', elem.getAttribute('ancestorWhere'));
			adeoElem.setAttribute( 'edge', elem.getAttribute('edge'));
		}else if( elem.getAttribute('type') == '1003'){
			adeoElem.setAttribute( 'entity', elem.getAttribute('entity'));
			adeoElem.setAttribute( 'iddatainfo', elem.getAttribute('iddatainfo'));
		}
	}
	if( onClick){
		adeoElem.setStyle( 'cursor', 'pointer');
		adeoElem.setStyle( 'color', '#9BB4FF');
		adeoElem.addEventListener( 'click', onClick);
	}else{
		adeoElem.setStyle( 'color', '#666666');
	}
	if( onOver)
		adeoElem.addEventListener( 'mouseover', onOver);
	if( onOut)
		adeoElem.addEventListener( 'mouseout', onOut);

	adeoElem.setInnerHTML( text);
	return adeoElem;
};
AdeoGlobal.Editor.Text = {}
AdeoGlobal.Editor.Text.edit = function( event){
	var elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	AdeoGlobal.Editor.Module.mouseDblClick( event, document.getElementById( elem.getAttribute( 'elemid')) );
};
AdeoGlobal.Editor.Css = {};
AdeoGlobal.Editor.Css.edit = function( event, elem){	
	if( !elem)
		elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	adeoTabs.selectTabAnyway( 'pageEditor', 2); 
	windowContainer.displayWindowContent( '/Text.do?idtextinfo=4&idcss=309&prefix=pageEditor', 'pageEditorcont2', '100%', null, null, null, null);

	AdeoGlobal.Editor.Menu();
};
AdeoGlobal.Editor.addModule = {};
AdeoGlobal.Editor.addModule.showWhere = function(){
	var elem = oSel.Area.Element;
	var elemChild = elem.firstChild;
	var existed = false;
	while( elemChild){
		if( elemChild.nodeName.toUpperCase() == 'DIV' && elemChild.getAttribute( 'addModule') == 'true'){
			elem.removeChild( elemChild);
			existed = true;
			break;
		}else{
			elemChild = elemChild.nextSibling;
		}
	}
	if( !existed){
		var adeoElem = new AdeoElement();
		adeoElem.setStyle( 'cursor', 'pointer');
		adeoElem.setStyle( 'textAlign', 'center');
		adeoElem.setStyle( 'fontSize', '11px');
		adeoElem.setStyle( 'color', '#9BB4FF');
		adeoElem.setAttribute( 'addModule', 'true');
		adeoElem.setInnerHTML('you will add your module here...');
		elem.appendChild( adeoElem.Element);
	}
};
AdeoGlobal.Editor.addModule.Click = function( event, elem){
	if( !elem)
		elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	windowContainer.registerWindowContent( '/Area.do?elementid=' + elem.getAttribute('elemid') + '&ancestorWhere=' + elem.getAttribute('ancestorWhere') + '&ancestorsString=' + elem.getAttribute('ancestors'), elem.getAttribute('elemid'));
	windowContainer.openNewWindow( '/DataDetail.do?action=insert&entity=8&dataid=13&id_parent=' + elem.getAttribute('elemid') + '&parentWindow=' + elem.getAttribute('parent') + '&edge=' + elem.getAttribute('edge')); 
	return false;

	AdeoGlobal.Editor.Menu();
};
AdeoGlobal.Editor.removeModule = {};
AdeoGlobal.Editor.removeModule.Click = function( event){
	var elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	if( !elem)
		return;
	oSel.removeElement( elem);
	AdeoGlobal.Editor.Menu();
};

//Data module actions
AdeoGlobal.Editor.DataModule = {};
AdeoGlobal.Editor.DataModule.insert = function( event) {
	var elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	windowContainer.registerWindowContent('/AppElement.do?elementid=' + elem.getAttribute( 'elemid'), elem.getAttribute( 'elemid'));
	windowContainer.openWindow( '/DataDetail.do?action=insert&entity=' + elem.getAttribute( 'entity') + '&parentWindow=' + elem.getAttribute( 'elemid'));

	AdeoGlobal.Editor.Menu();
};  
AdeoGlobal.Editor.DataModule.view = function( event) {
	var elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	windowContainer.openWindow( '/DataDetail.do?action=grid&entity=' + elem.getAttribute( 'entity') + '&dataid=' + elem.getAttribute( 'iddatainfo'));

	AdeoGlobal.Editor.Menu();
};  
AdeoGlobal.Editor.DataModule.edit = function( event) {
	var elem = adeo.element.niGetElementEventTarget( this);
	adeo.element.niStopBubbling( event);

	windowContainer.registerWindowContent('/AppElement.do?elementid=' + elem.getAttribute( 'elemid'), elem.getAttribute( 'elemid'));
	windowContainer.openWindow( '/DataDetail.do?action=edit&entity=7&id=' + elem.getAttribute( 'iddatainfo') + '&parentWindow=' + elem.getAttribute( 'elemid'));

	AdeoGlobal.Editor.Menu();
};


AdeoGlobal.Event = {};
AdeoGlobal.Event.currentKeyCode = function(){}; 
AdeoGlobal.Event.mouseMove = function(e) {
	if (!e) e = window.event;
	if (!e) e = parent.event;
	if( e.pageX || e.pageY){
		tempX = e.pageX;
		tempY = e.pageY;
	}else if( e.clientX || e.clientY){
		tempX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		tempY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}  
	if(dragElem != null && dragElem instanceof AdeoWindow){
		dragElem.move();
	}  
	if(resizeElem != null && resizeElem instanceof AdeoWindow){
		resizeElem.resize( tempX - parseInt( resizeElem.getPosition()[1]), tempY - parseInt( resizeElem.getPosition()[0]));
	}  
	if( oSel)
		oSel.setIErange();
};   
AdeoGlobal.Event.onkeydownMask = function( elem, evt){
        var e = evt ? evt : window.event ? window.event : null;
        AdeoGlobal.Event.currentKeyCode = e.keyCode;
        var currentValue = elem.value;
        var mask = elem.getAttribute('mask');
        var cursorPos = AdeoGlobal.Cursor.getPosition( elem);
                
        if( AdeoGlobal.Event.currentKeyCode == 8){
		  if(mask.charAt(cursorPos - 1) == '_'){
			    var newVal = currentValue.substring(0, cursorPos - 1);
			    newVal += '_';
			    newVal += currentValue.substring( cursorPos, mask.length);
			    elem.setAttribute( 'beforeValue', newVal);
			    elem.value = newVal; 
			    if( mask.charAt(cursorPos - 2) == "_")
				AdeoGlobal.Cursor.setPosition( elem, cursorPos - 1);
			    else
				AdeoGlobal.Cursor.setPosition( elem, cursorPos - 2);
		  }
		return false;
        } else if( AdeoGlobal.Event.currentKeyCode == 46){
		  if( mask.charAt(cursorPos)=='_'){
			    var newVal = currentValue.substring(0, cursorPos);
			    newVal += '_';
			    newVal += currentValue.substring( cursorPos+1, mask.length);
			    elem.setAttribute( 'beforeValue', newVal);
			    elem.value = newVal;  
			    if( mask.charAt(cursorPos + 1) == "_")
				AdeoGlobal.Cursor.setPosition( elem, cursorPos + 1);
			    else
				AdeoGlobal.Cursor.setPosition( elem, cursorPos + 2);
		  } 
		   return false;
        }
};
AdeoGlobal.Event.onkeypressMask = function( elem, evt){
        var e = evt ? evt : window.event ? window.event : null;
        var asciiCode;
        if( BrowserDetect.browser == 'Firefox' || BrowserDetect.browser == 'Safari' )
		asciiCode = e.charCode;
        else if( BrowserDetect.browser == 'Explorer' || BrowserDetect.browser == 'Opera' )
		asciiCode = e.keyCode;
        else {
		alert( "Sorry but we don't support: " + BrowserDetect.browser);           
		return false;
        }
        
        var currentValue = elem.value;
        var mask = elem.getAttribute('mask');
        var cursorPos = AdeoGlobal.Cursor.getPosition( elem);
        
        if( cursorPos > mask.length){            
		return false;
        }
        if( asciiCode > 32 && asciiCode < 127 
	    && AdeoGlobal.Event.currentKeyCode != 8 
	    && AdeoGlobal.Event.currentKeyCode != 46){
		  if( mask.charAt(cursorPos)=='_'){
			    var newVal = currentValue.substring(0, cursorPos);
			    newVal += currentValue.substring( cursorPos+1, mask.length);
			    elem.setAttribute( 'beforeValue', newVal);
			    elem.value = newVal;  
			    AdeoGlobal.Cursor.setPosition( elem, cursorPos);        
			    return true;
		  } else if( mask.charAt(cursorPos + 1)=='_'){
			    var newVal = currentValue.substring(0, cursorPos + 1);
			    newVal += currentValue.substring( cursorPos+2, mask.length);
			    elem.setAttribute( 'beforeValue', newVal);
			    elem.value = newVal;  
			    AdeoGlobal.Cursor.setPosition( elem, cursorPos + 1);        
			    return true;
		  } else {
			    AdeoGlobal.Cursor.setPosition( elem, cursorPos + 1); 
			    return false;
		  }
        } else if( AdeoGlobal.Event.currentKeyCode == 8 
			|| AdeoGlobal.Event.currentKeyCode == 46){ 
		return false;
        } else 
		return true;
};
AdeoGlobal.Css = {};
AdeoGlobal.Css.getCssRule = function ( cssRuleName, docum) {
	var doc = docum ? docum : document;		
	if( !doc.styleSheets) return;
			
	cssRuleName = cssRuleName.toLowerCase();
	for( var i = 0; i < doc.styleSheets.length; i++) {
		if( doc.styleSheets[i].rules){
			for( var j = 0; j < doc.styleSheets[i].rules.length; j++) {
				currRuleName = doc.styleSheets[i].rules[j].selectorText.toLowerCase(); 
				if( currRuleName == cssRuleName || currRuleName == "." + cssRuleName || currRuleName.search( cssRuleName) != -1)
					return doc.styleSheets[i].rules[j];
			}
		} else {
			for( var j = 0; j < doc.styleSheets[i].cssRules.length; j++) {
				currRuleName = doc.styleSheets[i].cssRules[j].selectorText.toLowerCase(); 
				if( currRuleName == cssRuleName || currRuleName == "." + cssRuleName || currRuleName.search( cssRuleName) != -1)
					return doc.styleSheets[i].cssRules[j];
			}
		}
      }	
      return;
};
AdeoGlobal.Css.addCssRule = function(cssRuleName, docum) {
	var doc = docum ? docum : document;
	if ( !doc.styleSheets) 
		return;
	if ( AdeoGlobal.Css.getCssRule( cssRuleName)) 
		return AdeoGlobal.Css.getCssRule( cssRuleName);
	
	if (doc.styleSheets[0].addRule) {           // Browser is IE?
		doc.styleSheets[0].addRule( cssRuleName, null,0);
	} else {
		doc.styleSheets[0].insertRule( cssRuleName+' { }', 0);
	}
	return AdeoGlobal.Css.getCssRule( cssRuleName);
};
AdeoGlobal.Css.getStyleProp = function( styleName, prop, docum) {
	if( !styleName) return;	
	var css = AdeoGlobal.Css.getCssRule( styleName, docum); 
	if( css) return css.style[ prop];
	else return null;
};
AdeoGlobal.Css.setStyleProp = function( cssStyleName, cssStyleProp, propValue, docum) {
	var rule = AdeoGlobal.Css.getCssRule( cssStyleName, docum);
	if( rule)
		rule.style[cssStyleProp] = propValue;
};
AdeoGlobal.Css.getElementUltimateProp = function( elem, prop, docum) {
	if( elem.nodeName.toUpperCase() == "#DOCUMENT")
		return null;
	if( AdeoGlobal.Css.getElementProp( elem, prop, docum))
		return AdeoGlobal.Css.getElementProp( elem, prop, docum);
	else
		return AdeoGlobal.Css.getElementUltimateProp( elem.parentNode, prop, docum);
	
};
AdeoGlobal.Css.getElementProp = function( elem, prop, docum){
	if( elem.style[ prop])
		return elem.style[ prop];
	else if( elem.className && AdeoGlobal.Css.getStyleProp( elem.className, prop, docum))
		return AdeoGlobal.Css.getStyleProp( elem.className, prop, docum);
	else
		return null;
};
AdeoGlobal.Css.isInheritProp = function( prop){  
	for( var i=0; i<AdeoCssInheritProperties.length; i++)
		if( AdeoCssInheritProperties[i] == prop)
			return true;
	return false;
};
AdeoGlobal.Css.isFrameProp = function( prop){  
	for( var i=0; i<AdeoCssFrameProperties.length; i++)
		if( AdeoCssFrameProperties[i] == prop)
			return true;
	return false;
};

//cssTab1
//Font Values
    var FontCssArray = new Array("inherit", "100", "900", "bold", "bolder", "italic", "large", "larger", "lighter", "medium", "normal", "oblique", "small", "small-caps", "smaller", "x-large", "x-small", "xx-large", "xx-small" );
    var FontFamilyCssArray = new Array("Arial", "Curier", "Verdana", "Tahoma", "Impact", "Times New Roman" );
    var FontSizeCssArray = new Array("8px", "10px", "12px", "14px", "18px", "22px");
    var FontStyleCssArray = new Array("inherit", "italic", "normal", "oblique");
    var FontVariantCssArray = new Array("inherit", "normal", "small-caps");
    var FontWeightCssArray = new Array("inherit", "100", "900", "bold", "lighter", "normal");

//Text Values
    var TextIndentCssArray = new Array("inherit", "5px", "10px", "5pt", "10pt");
    var TextAlignCssArray = new Array("inherit", "auto", "left", "center", "justify", "right");
    var TextDecorationCssArray = new Array("inherit", "blink", "line-through", "none", "overline", "underline");
    var TextTransformCssArray = new Array("inherit", "capitalize", "lowercase", "none", "uppercase");

//Background Values
    var BackgroundAttachmentCssArray = new Array("inherit", "fixed", "scroll");
    var BackgroundImageCssArray = new Array("inherit", "none");
    var BackgroundPositionCssArray = new Array("inherit", "bottom", "center", "left", "right", "top", "2px", "5px", "2%", "5%", "2pt", "5pt");
    var BackgroundRepeatCssArray = new Array("inherit", "no-repeat", "repeat", "repeat-x", "repeat-y");

//Extra Values
    var ContentCssArray = new Array( "inherit", "close-quote", "no-close-quote", "no-open-quote", "open-quote"); 
    var DirectionCssArray = new Array("inherit", "ltr", "rtl");
    var LetterSpacingCssArray = new Array("inherit", "normal", "2px", "4px", "2pt", "4pt");
    var LineHeightCssArray = new Array("inherit", "normal", "15px", "20px", "15pt", "20pt");
    var WordSpacingCssArray = new Array("inherit", "normal", "3px", "6px", "3pt", "6pt");

//cssTab2
//Margin Values
    var MarginTopCssArray = new Array("inherit", "auto", "10px", "20px", "10%", "10pt");
    var MarginLeftCssArray = new Array("inherit", "auto", "10px", "20px", "10%", "10pt");
    var MarginCssArray = new Array("inherit", "auto", "10px", "20px", "10%", "10pt", "5px 7px 1px 7px", "5% 7% 1% 7%", "5pt 7pt 1pt 7pt");
    var MarginRightCssArray = new Array("inherit", "auto", "10px", "20px", "10%", "10pt");
    var MarginBottomCssArray = new Array("inherit", "auto", "10px", "20px", "10%", "10pt");

//Padding
    var PaddingTopCssArray = new Array("inherit", "10px", "20px", "10%", "10pt");
    var PaddingLeftCssArray = new Array("inherit", "10px", "20px", "10%", "10pt");
    var PaddingCssArray = new Array("inherit", "10px", "20px", "10%", "10pt", "5px 7px 1px 7px", "5% 7% 1% 7%", "5pt 7pt 1pt 7pt");
    var PaddingRightCssArray = new Array("inherit", "10px", "20px", "10%", "10pt");
    var PaddingBottomCssArray = new Array("inherit", "10px", "20px", "10%", "10pt");

//Border Style Values
    var BorderTopStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");
    var BorderLeftStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");
    var BorderStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");
    var BorderRightStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");
    var BorderBottomStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");

//Border Width Values
    var BorderTopWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");
    var BorderLeftWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");
    var BorderWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");
    var BorderRightWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");
    var BorderBottomWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");

//Border Extra Values
    var BorderCollapseCssArray = new Array("inherit", "collapse", "separate");
    var BorderSpacingCssArray = new Array("inherit", "2px", "5px", "2%", "5%", "2pt", "5pt");

//cssTab3
//Dimension Values
    var WidthCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");
    var MaxWidthCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");
    var MinWidthCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");
    var HeightCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");
    var MaxHeightCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");
    var MinHeightCssArray = new Array("inherit", "auto", "100px", "200px", "50%", "100pt");

//Display Values
    var DisplayCssArray = new Array("inherit", "block", "inline", "inline-block", "inline-table", "list-item", "none", "run-in", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group");
    var VisibilityCssArray = new Array("inherit", "collapse", "hidden", "visible");
    var FloatCssArray = new Array("inherit", "left", "none", "right");
    var ClearCssArray = new Array("inherit", "both", "left", "none", "right");
    var OverflowCssArray = new Array("inherit", "auto", "hidden", "scroll", "visible");
    var zIndexCssArray = new Array("inherit", "auto", "1", "10", "30");
   
//Position Values
    var PositionCssArray = new Array("inherit", "absolute", "fixed", "relative", "static");
    var TopCssArray = new Array("inherit", "auto", "static-position", "100px", "200px", "50%", "100pt");
    var LeftCssArray = new Array("inherit", "auto", "static-position", "100px", "200px", "50%", "100pt");
    var RightCssArray = new Array("inherit", "auto", "static-position", "100px", "200px", "50%", "100pt");
    var BottomCssArray = new Array("inherit", "auto", "static-position", "100px", "200px", "50%", "100pt");
        
//Extra Values
    var CursorCssArray = new Array("inherit", "auto", "crosshair", "default", "e-resize", "help", "move", "n-resize", "ne-resize", "nw-resize", "pointer", "progress", "s-resize", "se-resize", "sw-resize", "text", "w-resize", "wait");
    var VerticalAlignCssArray = new Array("inherit", "baseline", "bottom", "middle", "sub", "super", "text-bottom", "text-top", "top", "100px", "200px", "50%", "100pt");
    var TableLayoutCssArray = new Array("inherit", "auto", "fixed");

//cssTab4
//List Style Values
    var ListStyleImageCssArray = new Array("inherit", "none");
    var ListStylePositionCssArray = new Array("inherit", "inside", "outside");
    var ListStyleTypeCssArray = new Array("inherit", "armenian", "circle", "cjk-ideographic", "decimal", "decimal-leading-zero", "disc", "georgian", "hebrew", "hiragana", "hiragana-iroha", "katakana", "katakana-iroha", "lower-alpha", "lower-greek", "lower-latin", "lower-roman", "none", "square", "upper-alpha", "upper-latin", "upper-roman");

//Outline Values
    var OutlineStyleCssArray = new Array("inherit", "dashed", "dotted", "double", "groove", "hidden", "inset", "none", "outset", "ridge", "solid");
    var OutlineWidthCssArray = new Array("inherit", "medium", "thick", "thin", "2px", "1%");

//Page Break Values
    var PageBreakAfterCssArray = new Array("inherit", "always", "auto", "awoid", "left", "right");
    var PageBreakBeforeCssArray = new Array("inherit", "always", "auto", "awoid", "left", "right");
    var PageBreakInsideCssArray = new Array("inherit", "always", "auto", "awoid", "left", "right");

//Advanced Values
    var CaptionSideCssArray = new Array("inherit", "bottom", "left", "right", "top");
    var ClipCssArray = new Array("inherit", "auto");
    var EmptyCellsCssArray = new Array("inherit", "hide", "show");
    var MarkerOffsetCssArray = new Array("inherit", "auto");
    var MarksCssArray = new Array("inherit", "crop", "cross", "none");
    var QuotesCssArray = new Array("inherit", "none");
    var UnicodeBidiCssArray = new Array("inherit", "bidi-override", "embed", "normal");
    var WhiteSpaceCssArray = new Array("inherit", "normal", "nowrap", "pre");
    
AdeoGlobal.Ajax = {};
AdeoGlobal.Ajax.load = function( url, callbackFunc, post_data, target, parent, action, cache){
	if( cache == true && ContentContainer[ url]){
		callbackFunc.call( this, ContentContainer[ url], url, target, parent, action);
		return false;
	}
	var xmlhttp = new XMLHttpRequest();
	// if needed set header information 
	// using the setRequestHeader method
	try{
		if( post_data == null) {
			xmlhttp.open( 'GET', url, true);
		} else {
			xmlhttp.open( 'POST', url, true);
			xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('Content-length', post_data.length);
			xmlhttp.setRequestHeader('Connection', 'close');
		}
		xmlhttp.setRequestHeader( 'If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState == 4 && callbackFunc){
				ContentContainer[ url] = xmlhttp.responseText;
				callbackFunc.call( this, xmlhttp.responseText, url, target, parent, action);				
			}
		}  	  
		xmlhttp.send( post_data);
		return false;
	}catch( e){
		AdeoGlobal.Ajax.callbackFunc = callbackFunc;
		AdeoGlobal.Ajax.diffDomainLoad( url, target, parent, action);
	}
};

AdeoGlobal.Ajax.loadModuleContent = function( url, target) {
	AdeoGlobal.Ajax.load( url, AdeoGlobal.Ajax.loadModuleContentCallback, null, target); 
};
AdeoGlobal.Ajax.loadModuleContentCallback = function( loadedAjax, url, target) {
	if( document.getElementById(target))
		document.getElementById(target).innerHTML = loadedAjax;
};

AdeoGlobal.Ajax.callbackFunc;
AdeoGlobal.Ajax.helpCallback = function( loadedAjax, url, target, parent, action){
	AdeoGlobal.Ajax.callbackFunc.call( this, loadedAjax, url, target, parent, action);
}
AdeoGlobal.Ajax.diffDomainLoad = function( url, target, parent, action){
        var elem = new AdeoElement();
	elem.setAttribute( 'id', 'diffDomainLoad');
	
	var onloadIFrame =  "AdeoGlobal.Ajax.helpCallback( AdeoGlobal.Ajax.getIFrameContent( this), '" + url + "', '" + target + "', '" + parent + "', " + action + " );";

        elem.setInnerHTML( '<iframe style="display:none" src="' + url +'" id="diffDomainLoadIFrame" name="diffDomainLoadIFrame" onload="' + onloadIFrame + '"></iframe>');
        document.body.appendChild( elem.Element);
};
AdeoGlobal.Ajax.getIFrameContent = function( iframe){
	var IFrame = new AdeoElement( iframe);
	if( IFrame.id != 'diffDomainLoadIFrame')
		return;
	
	var  doc;
	if( IFrame.Element.contentDocument)
		doc = IFrame.Element.contentDocument;
	else if( IFrame.Element.contentWindow)
		doc = IFrame.Element.contentWindow.document;
	else if( IFrame.Element.document)
		doc = IFrame.Element.document;

	if( doc){
		return doc.body.innerHTML;
	}else
		return;
};

AdeoGlobal.Form = {};
AdeoGlobal.Form.onSubmit = function( form){
	for(var i = 0; i < form.elements.length; i++){ 
		switch(form.elements[i].type){ 
			case 'hidden':
				if( (frame = document.getElementById( form.elements[i].id + 'Frame')) && document.getElementById(form.elements[i].id + 'cont1') == null || document.getElementById(form.elements[i].id + 'cont1') && document.getElementById(form.elements[i].id + 'cont1').style.display == 'block'){
				form.elements[i].value = frame.contentWindow.document.body.innerHTML.replace(/^\s+|\s+$/g, '');
				}
				if( (area = document.getElementById( form.elements[i].id + 'Area')) && document.getElementById(form.elements[i].id + 'cont2') && document.getElementById(form.elements[i].id + 'cont2').style.display == 'block'){
					form.elements[i].value = area.value;
				}
		} 
	} 
};
AdeoGlobal.Form.getValues = function( form, url, target, parent, action){ 
	var jsonForm = new AdeoFormJSON();
	var str = ''; 
	for(var i = 0; i < form.elements.length; i++){ 
		switch(form.elements[i].type){ 
			case 'text': 
			case 'textarea':
			case 'hidden':
			case 'password':
			case 'select-one':
				if( form.elements[i].getAttribute( 'name')){
					//str += form.elements[i].name + '=' + encodeURIComponent( form.elements[i].value).replace( '%A0' ,'%20') + '&';
					jsonForm.setValue( form.elements[i].name, form.elements[i].value);
				}
				break; 
			case 'file':
				AdeoGlobal.Form.fileUpload( url, target, parent, action);
				return null;
		} 
	}
	//return str.substr(0,(str.length - 1)); 
	return jsonForm;
};
AdeoGlobal.Form.cancel = function( form, target, parent, action){
	if( action & 8) 
		windowContainer.refreshWindow( parent);
	if( action & 1) 
		windowContainer.closeWindow( target);
	if( action & 16) 
		windowContainer.back( target);
	return false;
};
AdeoGlobal.Form.submit = function( form, url, target, parent, action){
	if( action & 1)
		windowContainer.closeWindow(target);

	var formValues = null;
	if( form) {
		AdeoGlobal.Form.onSubmit( form);
		formValues = AdeoGlobal.Form.getValues( form, url, target, parent, action);
		if( formValues == null)
			return true;
	}
	return AdeoGlobal.Ajax.load( url, AdeoGlobal.Form.submitCallback, formValues ? formValues.getURLString() : null, target, parent, action);
};
AdeoGlobal.Form.fileUpload = function( url, target, parent, action){
        var elem = new AdeoElement();
	elem.setAttribute( 'id', 'ajaxFileUpload');
	var onloadIFrame = "AdeoGlobal.Form.submitCallback( AdeoGlobal.Form.getIFrameContent( this), '" + url + "', '" + target + "', '" + parent + "', " + action + " );";
        elem.setInnerHTML( '<iframe style="display:none" src="about:blank" id="ajaxFileUploadIFrame" name="ajaxFileUploadIFrame" onload="' + onloadIFrame + '"></iframe>');
        document.body.appendChild( elem.Element);
};
AdeoGlobal.Form.getIFrameContent = function( iframe){
	var IFrame = new AdeoElement( iframe);
	if( IFrame.id != 'ajaxFileUploadIFrame')
		return;
	
	var  doc;
	if( IFrame.Element.contentDocument)
		doc = new AdeoElement( IFrame.Element.contentDocument);
	else if( IFrame.Element.contentWindow)
		doc = new AdeoElement( IFrame.Element.contentWindow.document);
	else if( IFrame.Element.document)
		doc = new AdeoElement( IFrame.Element.document);

	if( doc)
		return doc.Element.body.innerHTML;
	else
		return;
};
AdeoGlobal.Form.submitByName = function( formName) {
	var form = document.getElementById( formName);
	var actionType = form.getAttribute('actionType');
	var dataId = form.getAttribute('dataId');
	var beanCode = form.getAttribute('beanCode');
	var rowId = form.getAttribute('rowId');
	AdeoGlobal.Form.submit( form, 'DataDetail.do?action=' + actionType + '&dataid=' + dataId + '&beanCode=' + beanCode + '&id=' + rowId, '', '');
};
AdeoGlobal.Form.submitCallback = function( loadedAjax, url, targetIN, parent, action){	
	var tmp = new AdeoElement();
	var win, response;
	
	if( action & 2) {
		tmp.setInnerHTML( loadedAjax);
	}
	if( targetIN){
		win = windowContainer.open( { cont: tmp, target: targetIN});
	}
	//var resp = document.getElementById( 'response');
	if( tmp.Element.firstChild && tmp.Element.firstChild.id == 'response'){
		eval( tmp.Element.firstChild.innerHTML);
		if( response && win)
			win.Attributes.put( 'response', response);
	}
	if( win){
		var callback = win.Attributes.get( 'submitCallback');
		if( !callback)
			callback = win.getAttribute( 'submitCallback');
		var params = win.Attributes.get( 'submitCallbackParams');
		if( !params)
			params = win.getAttribute( 'submitCallbackParams');
			
		if( callback){
			eval( 'var fja=' + callback.toString());
			if( typeof fja == 'function')
				fja.call( this, response, params);
			
			win.Attributes.put( 'submitCallback', null);
			win.setAttribute( 'submitCallback', '');
			win.Attributes.put( 'submitCallbackParams', null);
			win.setAttribute( 'submitCallbackParams', '');
		}
	}
	if( action & 8) {
		if( parent == 'browser') {
			window.location.reload();
		} else if( parent) {
			windowContainer.refreshWindow( parent);
		}
	}
	
	var frameDIV = document.getElementById( 'ajaxFileUpload');
	if( frameDIV)
		frameDIV.parentNode.removeChild( frameDIV);
};

AdeoGlobal.Form.setImgId = function( resp, inputId){
	var inputElem = document.getElementById( inputId);
	if( inputElem){
		inputElem.value = resp.rows[0].id_file;
		oSel.setProp( 'backgroundImage', resp.rows[0].id_file);
	}
}
AdeoGlobal.Form.attrdepend = function(bean, dependee_attr, condition) {
    var dependee = document.getElementById(bean + ':' + dependee_attr);
    var dependeerow = document.getElementById('module:' + bean + ':' + dependee_attr);

    while (attr = condition.match(/##data\.([a-z0-9_]+)##/)) {
      var dependson = document.getElementById(bean + ':' + attr[1]);
      var dependsonrow = document.getElementById('module:' + bean + ':' + attr[1]);
      condition = condition.replace(new RegExp('##data.' + attr[1] + '##', 'g'), dependsonrow .style.display == '' && dependson .value ? dependson.value : '\'\'');
    }

    var conditionresult = false;
    eval( 'conditionresult = ' + condition);

    dependeerow.style.display = conditionresult  ? '' : 'none';
    if( dependee.onchange != undefined)
    	dependee.onchange();
};
AdeoGlobal.Date = {};
AdeoGlobal.Date.Day = {
	HR : new Array( "Ned", "Pon", "Uto", "Sri", "&#268;et", "Pet", "Sub"),
	EN : new Array( "Sun", "Mon", "Tue", "Wen", "Thu", "Fri", "Sat")
};
                         
AdeoGlobal.Date.Month = {
	HR : new Array("Sije&#269;anj", "Velja&#269;a", "Ožujak", "Travanj", "Svibanj", "Lipanj",
                               "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"),
	EN : new Array("January", "February", "March", "April", "May", "June",
                               "July", "August", "September", "October", "November", "December")
}

AdeoGlobal.Cursor = {};
AdeoGlobal.Cursor.getPosition = function( input){
      var cursorPos = 0;
      if( document.selection ){
		input.focus();
		var tmpRange = document.selection.createRange();
		tmpRange.moveStart('character', -input.value.length);
		cursorPos = tmpRange.text.length;
      }else{
		if( input.selectionStart || input.selectionStart=='0')
			cursorPos = input.selectionStart;
      }
      return cursorPos;
};    
AdeoGlobal.Cursor.setPosition = function( elem, cursorPos) {
      if (elem.setSelectionRange) {
		elem.focus();
		elem.setSelectionRange( cursorPos, cursorPos);
      }else if (elem.createTextRange) {
		var range = elem.createTextRange();
		range.collapse(true);
		range.moveEnd('character', cursorPos);
		range.moveStart('character', cursorPos);
		range.select();
      }
};
AdeoGlobal.Number = {};
AdeoGlobal.Number.isNumber = function( str){
	var Numbers = "0123456789.";	 
	for (i = 0; i < str.length; i++)
		if ( Numbers.indexOf( str.charAt(i)) == -1) 
			return false;
	return true;
}
document.onmousemove = AdeoGlobal.Event.mouseMove;
window.onload = AdeoGlobal.init
window.onresize = AdeoGlobal.init
function AdeoMap(){
    this.adeoMap = new Array();
};

function AdeoKeyValueObject( key, value){
	this.key = key;
	this.value = value;
};

AdeoMap.prototype.put = function( key, value ){
	if( key && value){
		var exists = false;
		for( var i = 0 ; i < this.adeoMap.length ; i++ ){
			if( this.areKeysEqual( this.adeoMap[i].key, key) ){
				this.adeoMap[i] = new AdeoKeyValueObject( key, value );
				exists = true;
				break;
			}
		}
		if( !exists)
			this.adeoMap[this.adeoMap.length] = new AdeoKeyValueObject( key, value );
		return this.adeoMap[this.adeoMap.length - 1];
	}else
		return null;
};
AdeoMap.prototype.putByFunction = function( key, value, equalFja ){
    if( key && value){
		var exists = false;
		for( var i = 0 ; i < this.adeoMap.length ; i++ ){
			if( equalFja( this.adeoMap[i].key, key) ){
				this.adeoMap[i] = new AdeoKeyValueObject( key, value );
				exists = true;
				break;
			}
		}
		if( !exists)
			this.adeoMap[this.adeoMap.length] = new AdeoKeyValueObject( key, value );
		return this.adeoMap[this.adeoMap.length - 1];
	}else
		return null;
};
AdeoMap.prototype.get = function( key ){
        for( var i = 0 ; i < this.adeoMap.length ; i++ )
		if( this.areKeysEqual( this.adeoMap[i].key, key) )
			return this.adeoMap[i].value;
	return null;
};
AdeoMap.prototype.getByFunction = function( key, equalFja ){
        for( var i = 0 ; i < this.adeoMap.length ; i++ )
		if( equalFja( this.adeoMap[i].key, key))
			return this.adeoMap[i].value;
	return null;
};
AdeoMap.prototype.length = function(){
    return this.adeoMap.length;
};
AdeoMap.prototype.array = function(){
    return this.adeoMap;
};
AdeoMap.prototype.areKeysEqual = function( key1, key2){
	if( (key1 instanceof Array) && (key2 instanceof Array) && key1.length){
		for( var i=0; i<key1.length; i++){
			if( key1[i] == key2[i])
				return true;
		}
		return false;
	}else if( key1 == key2){
		return true;
	}
	return false;
};

function AdeoAjax(){}
AdeoAjax.prototype.load = AdeoGlobal.Ajax.load;

AdeoAjax.prototype.loadCallback = function( loadedAjax, url, target) {
	var adeoElem = new AdeoElement( target);
	adeoElem.setInnerHTML( loadedAjax);

	try{
		if( target.getAttribute( 'jsFja')){
			if( target.getAttribute( 'params')){
				eval( target.getAttribute( 'jsFja') + '.call( this,' + target.getAttribute( 'params') + ');' );
			}else{
				eval( target.getAttribute( 'jsFja') + '.call( this)');
			}
		}else if( target.getAttribute( 'jsCallback')){
			eval( target.getAttribute( 'jsCallback'));			
		}
	}catch( e){}
};
AdeoAjax.prototype.loadUrlTo = function ( url, target) {
	this.load( url, this.loadCallback, null, target); 
};
AdeoAjax.prototype.loadUrlToAndCallback = function ( url, target, callbackFja) {
	this.load( url, callbackFja, null, target); 
};
function AdeoForm( form){
	this.form = form;
	AdeoAjax.call(this);
}

AdeoForm.prototype = new AdeoAjax();
AdeoForm.prototype.constructor = AdeoForm;

AdeoForm.prototype.setValue = function( select, inputId){
	document.getElementById(inputId).value = select.options[select.selectedIndex].value;
};

AdeoForm.prototype.getValues = function(){
	AdeoGlobal.Form.getValues( this.form);
};
AdeoForm.prototype.onSubmit = function(){
	AdeoGlobal.Form.onSubmit( this.form);
};

AdeoForm.prototype.submitCallback = AdeoGlobal.Form.submitCallback;

AdeoForm.prototype.submit = function( url, target, parent){
	var formValues = null;
	if( this.form ) {
		this.onSubmit();
		formValues = this.getValues();
		if( formValues == null)
			return true;
	}
	return AdeoAjax.prototype.load.call( this, url, this.submitCallback, formValues, target, parent);
};

function AdeoFormJSON(){
	this.names = new Array();
	this.values = new Array();
};
AdeoFormJSON.prototype.setValue = function( name, value){
	this.names[ this.names.length] = name;
	this.values[ name] = value;
};
AdeoFormJSON.prototype.getValue = function( name){
	return this.values[ name];
};
AdeoFormJSON.prototype.getURLString = function(){
	var str = '';
	for( var i=0; i<this.names.length; i++){
		if( this.names[i] && this.values[ this.names[i]])
			str += this.names[i] + '=' + encodeURIComponent( this.values[ this.names[i]]).replace( '%A0' ,'%20') + '&';
	}			
	return str.substr(0,(str.length - 1));
};
AdeoFormJSON.prototype.getObject = function(){
	var strNames = " paramNames:[";
	var strRows = " rows:[{"
	for( var i=0; i<this.names.length; i++){
		if( i == this.names.length-1){
			strNames += "'" + this.names[i] + "']";
			strRows += this.names[i] + ": '" + this.values[ this.names[i]] + "' }]";
		}else{
			strNames += "'" + this.names[i] + "',";
			strRows += this.names[i] + ": '" + this.values[ this.names[i]] + "',";
		}
	}	
	var res = null;
	eval( 'res = {' + strNames + ', ' + strRows + '}');
	return res;		
};
AdeoFormJSON.prototype.setToForm = function(myForm){	
	if(!myForm)
		return;
		
	for( var i=0; i<this.names.length; i++){
		var exists = false;
		for( var j=0; j<myForm.Element.elements.length; j++){
			if( myForm.Element.elements[j].name == this.names[i]){
				myForm.Element.elements[j].value = this.getValue(this.names[i]);
				exists = true;
				break;
			}
		}
		if(!exists){
			var postParam = new AdeoElement('textarea');
			postParam.setAttribute('name', this.names[i]);
			myForm.add(postParam);
			for( var k=0; k<myForm.Element.elements.length; k++)
				if( myForm.Element.elements[k].name == this.names[i])
					myForm.Element.elements[k].value = this.getValue(this.names[i]);
		}
	}
};
function AdeoElement( elem){	
	this.Element;
	this.Type = AdeoElementType.NONE;
	this.id;
	this.Css;
	this.newCss = false;
//	this.InlineCss;
	this.create( elem);
	this.getElement = function(){ return this.Element;};
	AdeoAjax.call(this);
	this.Attributes = new AdeoMap();
	this.cssChanged;
};

AdeoElement.prototype = new AdeoAjax();
AdeoElement.prototype.constructor = AdeoElement;
 
AdeoElement.prototype.create = function( elem){  
	if( elem){
		if( elem instanceof AdeoElement)
			this.copyElementFrom( elem);
		else if( elem.nodeName)
			this.setElement( elem);
		else if( document.getElementById( elem))
			this.setElementById( elem);
		else if( elem.search('_') == -1 && !AdeoGlobal.Number.isNumber( elem))
			this.createElementByType( elem);
		else
			this.createBlankElement();
	} else
		this.createBlankElement();
};
AdeoElement.prototype.copyElementFrom = function( elem){
	this.Element = elem.Element;
	this.Type = elem.Type;
	this.id = elem.id;
	
		if( !this.Element.className || this.Element.className == 'css'){
			this.setClass( 'ElementClass' + this.id);
			this.newCss = true;
		}else{
			this.setClass( this.Element.className);
			this.newCss = false;
		}

//	this.Css = new AdeoCss( this.Element.className);
//	this.InlineCss = new AdeoCss( null, this.Element.style);
};
AdeoElement.prototype.createElementByType = function( type) {
	this.Element = document.createElement( type);
	this.Type = eval( 'AdeoElementType.' + type.toUpperCase());
	this.id = type.toUpperCase() + '_' + Math.floor(Math.random()*100000);
	
		if( !this.Element.className || this.Element.className == 'css'){
			this.setClass( 'ElementClass' + this.id);
			this.newCss = true;
		}else{
			this.setClass( this.Element.className);
			this.newCss = false;
		}

//	this.Css = new AdeoCss( this.Element.className);
//	this.InlineCss = new AdeoCss( null, this.Element.style);
};
AdeoElement.prototype.createBlankElement = function() {
	this.createElementByType( 'div');
};
AdeoElement.prototype.setElement = function( elem) {
	if( elem && elem.nodeName){
		this.Element = elem;
		var str = elem.nodeName.toUpperCase();
		if( str.charAt( 0) == '#')
			str = str.substr( 1);
		this.Type = eval( 'AdeoElementType.' + str);
		if( !elem.id)
			this.id = str + '_' + Math.floor(Math.random()*100000);
		else
			this.id = elem.id;
		if( !this.Element.className || this.Element.className == 'css'){
			this.setClass( 'ElementClass' + this.id);
			this.newCss = true;
		}else{
			this.setClass( this.Element.className);
			this.newCss = false;
		}
//			this.Css = new AdeoCss( this.Element.className);
//		this.InlineCss = new AdeoCss( null, this.Element.style);
	}
}; 
AdeoElement.prototype.setElementById = function( target) {
	if( document.getElementById( target)) {
		this.setElement( document.getElementById( target));
	} 
};  
AdeoElement.prototype.add = function( target) {
	var targetElement = new AdeoElement( target);
	if( targetElement)
		this.Element.appendChild( targetElement.Element);
};     
AdeoElement.prototype.fillWith = function( target) {
	var targetElement = new AdeoElement( target);
	if( targetElement){
		while ( this.Element.hasChildNodes())
			this.Element.removeChild( this.Element.firstChild);
		this.Element.appendChild( targetElement.Element);
	}
};       
AdeoElement.prototype.empty = function() {
	while ( this.Element.hasChildNodes())
		this.Element.removeChild( this.Element.firstChild);
};    
AdeoElement.prototype.displayIn = function( target) {
	var targetElement = new AdeoElement( target);
	if( targetElement){
		while (targetElement.Element.hasChildNodes())
			targetElement.Element.removeChild( targetElement.Element.firstChild);
		targetElement.Element.appendChild( this.Element);
	}
};        
AdeoElement.prototype.appendTo = function( target) {
	var targetElement = new AdeoElement( target);
	if( targetElement)
		targetElement.Element.appendChild( this.Element);
};  
AdeoElement.prototype.setClass = function( cssClassName){  
	if( cssClassName){
		this.Element.className = cssClassName;  
		this.Css = new AdeoCss( cssClassName);
	}
};        
AdeoElement.prototype.getClassName = function(){  
	return this.Element.className;  
};        
AdeoElement.prototype.getNodeName = function(){  
	return this.Element.nodeName;  
};   
AdeoElement.prototype.displayParent = function(){
	if( this.Element.parentNode)
		this.Element.parentNode.style.display = 'block';		
};
AdeoElement.prototype.hideParent = function(){
	if( this.Element.parentNode)
		this.Element.parentNode.style.display = 'none';		
};
AdeoElement.prototype.getParentAdeoElement = function(){
	if( this.Element.parentNode.nodeName.toUpperCase() != 'HTML')
		return new AdeoElement( this.Element.parentNode);
	return null;
};
AdeoElement.prototype.firstChild = function(){
	this.Element.firstChild;
};
AdeoElement.prototype.nextSibling = function(){
	this.Element.nextSibling;
};
AdeoElement.prototype.setAttribute = function( attrName, value){
	if( attrName == 'id')
		this.id = value;
	this.Element.setAttribute( attrName, value);
};
AdeoElement.prototype.getAttribute = function( attrName){
	return this.Element.getAttribute( attrName);
};
AdeoElement.prototype.getRealHeight = function(){
	return this.Element.offsetHeight;
};
AdeoElement.prototype.getRealWidth = function(){
	return this.Element.offsetWidth;
};
AdeoElement.prototype.setInnerHTML = function( innerHTML){
	this.Element.innerHTML = innerHTML;
};
AdeoElement.prototype.getInnerHTML = function(){
	return this.Element.innerHTML;
};
AdeoElement.prototype.getOuterHTML = function(){
	var before = '<' + this.getNodeName() + ' class="' + this.getClassName() + '">';
	var after = '</' + this.getNodeName() + '>';
	return before + this.Element.innerHTML + after;
};
AdeoElement.prototype.elementCallback = function( loadedAjax, url, target) {
	var tg = new AdeoElement( target);
	if( !tg) return;
		
	tg.setInnerHTML( loadedAjax);
	try{
		if( tg.getAttribute( 'jsCallback')){
			eval( tg.getAttribute( 'jsCallback'));
		}
		if( tg.getAttribute( 'jsFja')){
			if( tg.getAttribute( 'params')){
				eval( tg.getAttribute( 'jsFja') + '.call( this,' + tg.getAttribute( 'params') + ');' );
			}else{
				eval( tg.getAttribute( 'jsFja'));
			}
		}
	}catch( e){}
};
AdeoElement.prototype.loadUrlSig = function( url, jsFja, adeoArgs){
	this.setAttribute( 'jsFja', jsFja);
	this.setAttribute( 'params', adeoArgs);
	this.loadUrlToAndCallback( url, this.Element, this.elementCallback);
};
AdeoElement.prototype.loadUrl = function( url){
	if( this.Type == AdeoElementType.IFRAME)
		this.Element.src = url;
	else
		this.loadUrlTo( url, this.Element);
};
AdeoElement.prototype.loadAndExecute = function( jsFja, adeoArgs, url){
	this.setAttribute( 'jsFja', jsFja);
	this.setAttribute( 'params', adeoArgs);
	if( url)
		this.loadUrlTo( url, this.Element);
	else if( this.url)
		this.loadUrlTo( this.url, this.Element);
};
AdeoElement.prototype.loadAndEval = function( jsCode, url){
	this.setAttribute( 'jsCallback', jsCode);
	if( url)
		this.loadUrlTo( url, this.Element);
	else if( this.url){
		this.loadUrlToAndCallback( this.url, this.Element, this.elementCallback);
	}
};
AdeoElement.prototype.loadAndCall = function( obj, url){
	this.setAttribute( 'jsFja', obj);
	if( url)
		this.loadUrlTo( url, this.Element);
	else if( this.url)
		this.loadUrlTo( this.url, this.Element);
};
AdeoElement.prototype.addEventListener = function ( event, func) {
    if( this.Element.addEventListener)
      this.Element.addEventListener( event, func, false);
    else if (this.Element.attachEvent)
      this.Element.attachEvent( 'on' + event, func);
};
AdeoElement.prototype.setPosition = function( top, left) {
        if( top && left) {
		this.setStyle( 'left', parseInt(left) + 'px');
		this.setStyle( 'top', parseInt(top) + 'px');
        }else if( left) {
		this.setStyle( 'left', parseInt(left) + 'px');
	}else if( top) {
            this.setStyle( 'top', parseInt(top) + 'px');
	} else {
		this.setStyle( 'left', (tempX - 50) + 'px');
		this.setStyle( 'top', (tempY + 15) + 'px');
        }
};
AdeoElement.prototype.getPosition = function() {
    var currTop = this.Element.offsetTop, currLeft = this.Element.offsetLeft;
    return [ currTop, currLeft];
};
AdeoElement.prototype.setSize = function( width, height){
	if( width)
		this.setStyle( 'width', width);
	if( height)
		this.setStyle( 'height', height);
};
AdeoElement.prototype.getSize = function() {
    var elemWidth = this.Element.offsetWidth, elemHeigth = this.Element.offsetHeight;
    return [ elemWidth, elemHeigth];
};
AdeoElement.prototype.getTypeGroup = function(){    
	if(this.Type == 1000)
		return AdeoElementTypeGroups.NO_SELECTION;
        else if(this.Type == 500)
		return AdeoElementTypeGroups.IFRAME;
        else if(this.Type > 20 && this.Type < 30)
		return AdeoElementTypeGroups.CONTROL;
        else
		return AdeoElementTypeGroups.TEXT;            
};
AdeoElement.prototype.displayAbsolute = function( left, top) {
	this.setStyle( 'position', 'absolute');
	this.setPosition( top, left);
};
AdeoElement.prototype.displayFixed = function( left, top) {
	this.setStyle( 'position', 'fixed');
	this.setPosition( top, left);
};
AdeoElement.prototype.displayInFront = function(){	
	this.setStyle( 'zIndex', ++ZIndex);
};
AdeoElement.prototype.display = function(){	
	this.setStyle( 'display', 'block');
};
AdeoElement.prototype.hide = function(){	
	this.setStyle( 'display', 'none');
};
AdeoElement.prototype.move = function(){
	this.setPosition( tempY - parseInt(this.Attributes.get( 'offsetY')), tempX - parseInt(this.Attributes.get( 'offsetX')));
};
AdeoElement.prototype.switchToRawMode = function(){
        var inRawMode = this.getAttribute('inRawMode');
	if( inRawMode == 'true')	
		return;

	var TextArea = new AdeoElement( 'textarea');
	TextArea.setAttribute( 'id', this.id + '_TextArea');
                
        var size = this.getSize();
	if( BrowserDetect.browser == 'Explorer')
		TextArea.setSize( '100%', size[1] + 6);
	else
		TextArea.setSize( '100%', size[1]);
		
        this.setAttribute('inRawMode', 'true');

	var IFrame = new AdeoElement( this.id + '_Frame');
	if( IFrame.Element.contentDocument)
		doc = new AdeoElement( IFrame.Element.contentDocument);
	else if( IFrame.Element.contentWindow)
		doc = new AdeoElement( IFrame.Element.contentWindow.document);
	else if( IFrame.Element.document)
		doc = new AdeoElement( IFrame.Element.document);

	if( doc && doc.Element.body)
		TextArea.Element.value = doc.Element.body.innerHTML;
                                
	this.fillWith( TextArea);

};
AdeoElement.prototype.switchToEditMode = function(){	
	var inEditMode = this.getAttribute('inEditMode');
        var inRawMode = this.getAttribute('inRawMode');
	if( inEditMode == 'true' && inRawMode != 'true')	
		return;
	else if( inEditMode == 'true' && inRawMode == 'true'){
		var TextArea = new AdeoElement( this.id + '_TextArea');
		this.setInnerHTML( TextArea.Element.value);
	}
	
	var IFrame = new AdeoElement( 'iframe');
	IFrame.setAttribute( 'id', this.id + '_Frame');
	IFrame.Element.name = IFrame.id;
	IFrame.Element.src = 'about:blank';
	IFrame.setAttribute( 'frameborder', '0');
	var size = this.getSize();
	if( BrowserDetect.browser == 'Explorer')
		IFrame.setSize( '100%', size[1] + 6);
	else
		IFrame.setSize( '100%', size[1]);
	
	this.setAttribute('inEditMode', 'true');	
        this.setAttribute('inRawMode', 'false');
	oSel.setElem( this);
	var tmpHTML = this.getInnerHTML();
	this.fillWith( IFrame);

	var  doc;
	if( IFrame.Element.contentDocument)
		doc = new AdeoElement( IFrame.Element.contentDocument);
	else if( IFrame.Element.contentWindow)
		doc = new AdeoElement( IFrame.Element.contentWindow.document);
	else if( IFrame.Element.document)
		doc = new AdeoElement( IFrame.Element.document);

	if( doc){
		doc.Element.open();
		
		var IFrameHTML = '<html><head> <link type="text/css" href="/1002.css" rel="stylesheet"> <style type="text/css"> .cssBody{ ' + this.getUltimateStyle().getText() + '}</style> <script type="text/javascript" language="JavaScript" src="/1002.js"> </script><script type="text/javascript" language="JavaScript"> document.onmouseup = onmouseUp; document.onkeypress = onkeyPress; function onkeyPress(){ parent.oSel.updateHeight(); } function onmouseUp(){ parent.oSel.init(' + "'" + IFrame.id + "'" + '); } </script> </head> <body class="cssBody" contentEditable onLoad="document.designMode=' + "'on'; if(BrowserDetect.browser=='Firefox'){ document.addEventListener( 'mouseup', function(){ parent.oSel.init('" + IFrame.id + "')}, false ); document.addEventListener( 'keypress', function(){ parent.oSel.updateHeight() }, false );}" + '">'
	
		doc.Element.write( IFrameHTML + tmpHTML + '</body></html>');
		doc.Element.close();	
		oSel.init( IFrame.id);
	}
};
AdeoElement.prototype.getUltimateStyle = function(){
	var ultimate = new AdeoCss( 'Ultimate' + this.id);
	ultimate.merge( this.getElementStyle());
	var elem = this.getParentAdeoElement();
	while( elem){
		ultimate.inherit( elem.getElementStyle());
		elem = elem.getParentAdeoElement();
	}
	return ultimate;
};
AdeoElement.prototype.getElementStyle = function(){
//	var elemStyle = new AdeoCss( 'Style' + this.id);
//	elemStyle.merge( this.Css)
//	elemStyle.merge( this.InlineCss);
//	return elemStyle;
	return this.Css;
};
AdeoElement.prototype.SysWebText = function(){
	var syswebtextid = this.getAttribute( 'idwebtext');
	if( syswebtextid && AdeoGlobal.Number.isNumber( syswebtextid))
		return syswebtextid;
	return null;
};
AdeoElement.prototype.setStyle = function( styleName, value, prefix){
	if( this.Css.CssName != this.Element.className){
		this.Css = new AdeoCss( this.Element.className);
	}
	this.Css.setProperty( styleName, value, prefix);
	if( this.Element.style[ styleName]){
		this.Element.style[ styleName] = value;
	}
	this.cssChanged = true;
};  
AdeoElement.prototype.getStyle = function( styleName){	
	return this.Css.getProperty( styleName);
};   
AdeoElement.prototype.getCssTableId = function(){	
	if( this.Css.CssName.match( '.css')){
		return this.Css.CssName.substr(4);
	}
};   
AdeoElement.prototype.saveCss = function(){
	if( !this.cssChanged)	
		return;

	if( this.newCss){
	//create new Css class and attach it to this element	
		var urlTo = '/DataDetail.do?action=insertwork&dataid=20&edge=' + this.getAttribute( 'edge');
		this.load( urlTo, this.saveCssCallback, this.Css.getSavePost(), this.Element);
		this.changed = false;
		this.undoSteps = new Array();
		this.redoSteps = new Array();
		this.currentUndoStep = 0;
		this.currentUndoStep = 0;
	}else{
	//apply changes to element class
		var urlTo = '/DataDetail.do?entity=1000&action=editwork&id=' + this.getCssTableId();
		this.load( urlTo, null, this.Css.getSavePost(), null, null);
		this.changed = false;
		this.undoSteps = new Array();
		this.redoSteps = new Array();
		this.currentUndoStep = 0;
		this.currentUndoStep = 0;
	}
};
AdeoElement.prototype.saveCssCallback = function( loadedAjax, url, target){
	var tg = new AdeoElement( target);
	if( !tg) return;
		
	try{
		var tmpElem = new AdeoElement();
		tmpElem.setInnerHTML( loadedAjax);
		eval( tmpElem.Element.firstChild.innerHTML);
		if( response && response.rows && response.rows[0].id){
			var createdCss = new AdeoCss( 'css' + response.rows[0].id);
			createdCss.inherit( tg.Css);
			tg.setClass( 'css' + response.rows[0].id);
			tg.newCss = false;
		}
	}catch( e){}
};
AdeoElement.prototype.saveContent = function(){	
	var postData, htmlForSave;
	var inEditMode = this.getAttribute('inEditMode');
	var inRawMode = this.getAttribute('inRawMode');
	if( inEditMode == 'true'){
		if( inRawMode == 'true'){
			var TextArea = new AdeoElement( this.id + '_TextArea');
			htmlForSave = TextArea.Element.value;
		}else{
			var IFrame = new AdeoElement( this.id + '_Frame');
			if( IFrame.Element.contentDocument)
				doc = new AdeoElement( IFrame.Element.contentDocument);
			else if( IFrame.Element.contentWindow)
				doc = new AdeoElement( IFrame.Element.contentWindow.document);
			else if( IFrame.Element.document)
				doc = new AdeoElement( IFrame.Element.document);
		
			if( doc && doc.Element.body)
				htmlForSave = doc.Element.body.innerHTML;
		}
	}	
	if( htmlForSave ){
		postData = 'value(text)=' + encodeURIComponent( htmlForSave ).replace( '%A0' ,'%20');
		this.setInnerHTML( htmlForSave);
		this.setAttribute('inEditMode', 'false');
		this.setAttribute('inRawMode', 'false');
		doc = null;
	}
	
	if( !this.SysWebText()){
		alert( "You should't be able to edit this element...");
	}else{	
		if( postData){
			var urlTo = '/DataDetail.do?entity=40&action=editwork&id=' + this.SysWebText();
			this.load( urlTo, null, postData, null, null);
		}
	}
	oSel.reset();
};

AdeoElementTypeGroups = {    
        NO_SELECTION : 0,
        TEXT : 1,
        CONTROL : 2,
	FRAME : 3
};

AdeoElementType = {  
	getType : function( elem){
		if( elem && elem.nodeName){
			if( elem instanceof AdeoElement)
				return eval( 'AdeoElementType.' + elem.Element.nodeName.toUperrCase());
			else
				return eval( 'AdeoElementType.' + elem.nodeName.toUperrCase());
		}else
			'undefined';
	},

        DIV : 0,
        P : 1,
        SPAN : 2,
        PRE : 3,
        H1 : 4,
        H2 : 5,
        H3 : 6,
        H4 : 7,
        H5 : 8,
        H6 : 9,
        LI : 10,
        OL : 11,
        UL : 12,
        
        IMG : 21,
        TABLE : 22,
	TBODY : 23,
        TR : 24,
        TD : 25,
        A : 25,
        
        B : 30,
        EM : 31,
        I : 32,
        BASEFONT : 33,
        BIG : 34,
        BLOCKQUOTE : 35,
        CENTER : 36,
        CITE : 37,
        EM : 40,
        FONT : 41,
        Q : 43,
        S : 44,
        SMALL : 45,
        STRIKE : 46,
        STRONG : 47,
        SUB : 48,
        SUP : 49,
        
        BODY : 200,  
	DOCUMENT : 201,
        
        TEXT : 300,
        TEXTAREA : 301,

	IFRAME : 500,

	FORM : 700,
	INPUT : 701,
        
        NONE : 1000        
};
function AdeoSelection(){
    this.win;
    this.Frame;
    this.Area;
    this.TextArea;

    this.Sel;
    this.range;
    this.HTML;
    this.Text;

    this.Elem;
    this.Img;
    this.Table;

    this.oldBgColor = "";
    
    this.nodeCounter = 0;
    this.nodeArray = new Array();  

	this.undoSteps = new Array();
	this.redoSteps = new Array();
	this.currentUndoStep = 0;
	this.currentRedoStep = 0;	
};   
AdeoSelection.prototype.setTextArea = function( elem){                 
	this.setElem( elem);  
	AdeoGlobal.Editor.LastMouseClicked = elem; 
                this.TextArea = this.Area;                          
                this.undoSteps[ this.currentUndoStep++] = new ElementStep( 0, this.Area);
};

AdeoSelection.prototype.rawMode = function( ){ 
                if( this.TextArea ){
	               var inEditMode = this.TextArea.getAttribute('inEditMode');
	               var inRawMode = this.TextArea.getAttribute('inRawMode');
                               if( inEditMode == 'true' && inRawMode != 'true' )
                                                    this.TextArea.switchToRawMode();
                               if( inEditMode == 'true' && inRawMode == 'true' )
                                                    this.TextArea.switchToEditMode();
               }
}

AdeoSelection.prototype.init = function( frame){ 
	if( document.getElementById( frame) && document.getElementById( frame).contentWindow){
		this.Frame = frame;
		this.win = document.getElementById( frame).contentWindow; 
		var clickedElem = document.getElementById( frame.split('_')[0]);
		this.setTextArea( clickedElem );
	}

        if( this.win){    
            this.setSelectionObject();
            if( this.Sel){
                this.setObjects();
                this.HTML = this.getSelectionHTML();
                this.Text = this.getSelectionText();
		
                this.nodeCounter = 0;
                this.nodeArray = new Array(); 
                this.setNodeArray( this.Elem.Element);
            }
        }
}; 

AdeoSelection.prototype.setElem = function( elem){
	this.Area = new AdeoElement( elem);
};

AdeoSelection.prototype.updateHeight = function(){
	if( document.getElementById( this.Frame) && this.win && this.win.document.body){
		if(BrowserDetect.browser == 'Explorer')
			document.getElementById( this.Frame).style[ 'height'] = this.win.document.body.scrollHeight + 6;
		else
			document.getElementById( this.Frame).style[ 'height'] = this.win.document.body.scrollHeight;
	}
};

AdeoSelection.prototype.setSelectionObject = function(){    
        if(BrowserDetect.browser == 'Explorer'){  
		if( this.win && this.win.document.selection){
			this.Sel = this.win.document.selection;
			this.range = this.Sel.createRange();
		}
        }else{       
            if( this.win.getSelection()){
		try{
			this.win.getSelection().getRangeAt(0);
			this.Sel = this.win.getSelection();
		}catch( e){
		}
            }
        }
};
AdeoSelection.prototype.setIErange = function(){
	if( BrowserDetect.browser != 'Explorer')
		return;
	try{
		if( this.range)
			this.range.select();
		else if( this.Sel){
			this.range = this.Sel.createRange();
			this.range.select();
		}else if( this.win){
			this.Sel = this.win.document.selection;
			this.range = this.Sel.createRange();
			this.range.select();
		}
	}catch( e){}
};
AdeoSelection.prototype.setObjects = function( elem){
	if( BrowserDetect.browser == 'Explorer'){ 
		var ieRange = this.Sel.createRange();
		if( this.Sel.type == "Control"){
			this.Elem = new AdeoElement( ieRange.item( 0 ));
		}else{
			this.Elem = new AdeoElement( ieRange.parentElement());
		}	
        }else{
		if( this.Sel.anchorNode)
			if( this.Sel.anchorNode.childNodes[ this.Sel.anchorOffset ])
				this.Elem = new AdeoElement( this.Sel.anchorNode.childNodes[ this.Sel.anchorOffset ]);
			else
				this.Elem = new AdeoElement( this.Sel.anchorNode.parentNode);      
	}   

	if( this.Elem){
		if( this.Elem.Type == AdeoElementType.IMG)
			this.Img = new AdeoImage( this.Elem);
		//this.Table = new AdeoTable( this.Elem);
	}
};   
AdeoSelection.prototype.getSelectionHTML = function(){
	if( !this.Sel)
		return;
        if( BrowserDetect.browser == 'Explorer' && this.range){
		this.range.select();
		return this.range.htmlText;
        }else{
            oRange = this.Sel.getRangeAt(0);
            var clonedSelection = oRange.cloneContents();
            var div = document.createElement('div');
            div.appendChild(clonedSelection);
            return div.innerHTML;
        }
    };
    
AdeoSelection.prototype.getSelectionText = function(){
	if( !this.Sel)
		return;
        if( BrowserDetect.browser == 'Explorer'){
		this.range.select();
		return this.range.text;
        }else{
            oRange = this.Sel.getRangeAt(0);
            var clonedSelection = oRange.cloneContents();
            var div = document.createElement('div');
            div.appendChild(clonedSelection);
            return div.textContent;
        }
    };
    
AdeoSelection.prototype.reset = function(){	
	this.window = null;
	this.Area = null;
	this.Sel = null;
	this.range = null;
	this.HTML = null;
	this.Text = null;
	this.nodePathForDisplay = null;

	this.Elem = null;
	this.Img = null;
	this.Table = null;
	this.Css = null;
          
	this.undoSteps = new Array();
	this.redoSteps = new Array();
	this.currentUndoStep = 0;
	this.currentRedoStep = 0;	

        this.nodeCounter = 0;
        this.nodeArray = new Array(); 
        //document.getElementById("NodePath").innerHTML = "";
};    
AdeoSelection.prototype.setNodeArray = function( el){
	if( !el) 
		return null;
        if( el.nodeName == "BODY")
		return null; 
        else 
		this.nodeArray[this.nodeCounter] = new AdeoElement(el);
            
        this.nodeCounter++;                
        return this.setNodeArray( el.parentNode);
};
AdeoSelection.prototype.edit = function( func, param1, param2){  
	if( this.Sel && this.win){
		if(BrowserDetect.browser == 'Explorer' && this.range){
			this.range.select();
		}  
		if( func == 'InsertHtml' && BrowserDetect.browser == 'Explorer') {
			if( !this.range)
				this.setSelectionObject( );
			this.range.pasteHTML(param2);
			this.range.select();
		}else if( (func=='Cut' || func=='Copy' || func=='Paste') && BrowserDetect.browser != 'Explorer'){
			
		}else{
			this.win.document.execCommand( func, param1, param2);
			this.updateHeight();
			if( func != 'Undo' && func != 'Redo')
				this.undoSteps[ this.currentUndoStep++] = new ElementStep( 0, this.Area);
		} 
	}else{
		reportErr('No selected Area');
	}
};

AdeoSelection.prototype.setProp = function( propName, propValue, prefix){
	this.Area.setStyle( propName, propValue, prefix);
	this.undoSteps[ this.currentUndoStep++] = new ElementStep( 1, this.Area);
	var inEditMode = this.Area.getAttribute('inEditMode');
	if( inEditMode == 'true'){
		this.updateHeight();
		if( AdeoGlobal.Css.isInheritProp( propName))	
			AdeoGlobal.Css.setStyleProp( 'cssBody', propName, propValue, this.win.document);
	}
};
AdeoSelection.prototype.containsArea = function( step, tmpArray){
	for( var i=0; i<tmpArray.length; i++){
		if( tmpArray[ i].Element == step.Element && 
		tmpArray[ i].ActionType == step.ActionType)
			return true;
	}
	return false;
};
AdeoSelection.prototype.loadCss = function( prefix){
	if( this.Area && this.Area.Css){
		this.Area.Css.setValuesTo( prefix);
	}
};

AdeoSelection.prototype.removeElement = function(){	
	this.Area.setStyle( 'display', 'none');
	this.undoSteps[ this.currentUndoStep++] = new ElementStep( 2, this.Area);
};

AdeoSelection.prototype.save = function(){
	var tmpArray = [];
	var i = 0;
        while( this.currentUndoStep >=0){  
		if( this.currentUndoStep == 0)
			return;
                this.currentUndoStep--;
		var lastStep = this.undoSteps[ this.currentUndoStep];
                
		if( !this.containsArea( lastStep, tmpArray)){
			if( lastStep.ActionType == 'CONTENT'){
				lastStep.Element.saveContent();
			}else if( lastStep.ActionType == 'CSS'){
				lastStep.Element.saveCss();
			}else if( lastStep.ActionType == 'BUILD'){
			}
			tmpArray[i++] = lastStep;
		}
        }
};  

AdeoSelection.prototype.undo = function(){
        if( this.currentUndoStep > 0){
                this.currentUndoStep--;
		var lastStep = this.undoSteps[ this.currentUndoStep];
                this.redoSteps[ this.currentRedoStep++] = lastStep;
                		
		if( lastStep.ActionType == 'CONTENT'){	
			oSel.init( lastStep.Element.id + '_Frame');
			oSel.undoText();
		}else if( lastStep.ActionType == 'CSS'){
			var lastChange = lastStep.Element.Css.undo();
			var inEditMode = this.Area.getAttribute('inEditMode');
			if( lastChange && inEditMode == 'true'){
				this.updateHeight();
				if( AdeoGlobal.Css.isInheritProp( lastChange.propName))	
					AdeoGlobal.Css.setStyleProp( 'cssBody', lastChange.propName, AdeoGlobal.Css.getElementUltimateProp( lastStep.Element.Element, lastChange.propName, document), this.win.document);
			}
		}else if( lastStep.ActionType == 'BUILD'){
			var curr = lastStep.Element.getStyle( 'display');
			lastStep.Element.setStyle( 'display', curr=='block' ? 'none' : 'block');
		}
        }
};    

AdeoSelection.prototype.undoAll = function(){
        for(var i=0 ; i<this.currentUndoStep; i++){            
		this.undo();
        }
};    
AdeoSelection.prototype.redo = function(){    
        if( this.currentRedoStep>0){
		this.currentRedoStep--;	
		var lastStep = this.redoSteps[ this.currentRedoStep];
                this.undoSteps[ this.currentUndoStep++] = lastStep;
				
		if( lastStep.ActionType == 'CONTENT'){	
			oSel.init( lastStep.Element.id + '_Frame');
			oSel.redoText();
		}else if( lastStep.ActionType == 'CSS'){			
			var lastChange = lastStep.Element.Css.redo();
			var inEditMode = this.Area.getAttribute('inEditMode');
			if( lastChange && inEditMode == 'true'){
				this.updateHeight();
				if( AdeoGlobal.Css.isInheritProp( lastChange.propName))	
					AdeoGlobal.Css.setStyleProp( 'cssBody', lastChange.propName, AdeoGlobal.Css.getElementUltimateProp( lastStep.Element.Element, lastChange.propName, document), this.win.document);
			}
		}else if( lastStep.ActionType == 'BUILD'){
			var curr = lastStep.Element.getStyle( 'display');
			lastStep.Element.setStyle( 'display', curr=='block' ? 'none' : 'block');
		}
        }
};   

ActionTypes =  [ 'CONTENT', 'CSS', 'BUILD'];
function ElementStep( atype, element){
	this.Element = element;
	this.ActionType = ActionTypes[ atype];
};

AdeoSelection.prototype.undoText = function(){
	this.edit( 'Undo', null, null);
};
AdeoSelection.prototype.redoText = function(){
	this.edit( 'Redo', null, null);
};
AdeoSelection.prototype.editColor = function(par2, par3, value){

      document.getElementById(par2 + 'Link').style.backgroundColor = value;
      document.getElementById(par2 + 'Write').value = value;
      this.edit(par2, par3, value);
};

AdeoSelection.prototype.formatBlock = function(par){
  document.getElementById('formatBlockLink').value = par;
  this.edit( 'FormatBlock', null, par);
};

AdeoSelection.prototype.formatBlock = function(par){
  document.getElementById('formatBlockLink').value = par;
  this.edit( 'FormatBlock', null, par);
};

AdeoSelection.prototype.fontName = function( par){
	document.getElementById('fontNameLink').value = par;
	if(BrowserDetect.browser == 'Opera')
		this.edit( 'InsertHtml', null, '<span style="font-family:'+ par +'">'+ this.getSelectionHTML() + '</span>');    
  else
	this.edit( 'FontName', null, par );
	keepSelection = true;
};

AdeoSelection.prototype.fontSize = function( par){
	document.getElementById('fontSizeLink').value = par;
	this.edit( 'InsertHtml', null, '<span style="font-size:'+ par +'">'+ oSel.getSelectionHTML() + '</span>');    
	keepSelection = true;
};

var recentForeColors = 0;
AdeoSelection.prototype.ForeColor = function(par){
	if(arguments.length == 1){
		recentForeColors++;
		if(recentForeColors>5)recentForeColors=1;      
			document.getElementById('recentColor' + recentForeColors + '_ForeColor').style.backgroundColor = par;
	} 
	this.editColor( 'ForeColor', null, par );
};

var recentHiliteColors = 0;
AdeoSelection.prototype.HiliteColor = function(par){
	if(arguments.length == 1){
		recentHiliteColors++;
		if(recentHiliteColors>5)recentHiliteColors=1;      
			document.getElementById('recentColor' + recentHiliteColors + '_HiliteColor').style.backgroundColor = par;
	}
    
	if(BrowserDetect.browser == 'Explorer')  
		this.edit( 'InsertHtml', null, '<span style="background-color:'+ par +'">'+ this.getSelectionHTML() + '</span>');    
	else
		this.editColor( 'HiliteColor', null, par );
};    

AdeoSelection.prototype.Link = function( par){
	this.edit('CreateLink', null, par);
};

AdeoSelection.prototype.Mail = function( par){
	this.edit('CreateLink', null, 'mailto:' + par);
};

AdeoSelection.prototype.Anchor = function( par){
	this.edit('InsertHtml', null, '<a name=' + par + '>' + this.getSelectionHTML() + '</a>');
};

var oSel = new AdeoSelection();

var fontNameArray = new Array("<span style='font-family:Arial;'>Arial</span>", "<span style='font-family:Curier;'>Curier</span>", "<span style='font-family:Verdana;'>Verdana</span>", "<span style='font-family:Tahoma;'>Tahoma</span>", "<span style='font-family:Impact;'>Impact</span>", "<span style='font-family:Times New Roman;'>Times New Roman</span>" );
var fontSizeArray = new Array("<span style='font-size:6px'>6px</span>","<span style='font-size:8px'>8px</span>", "<span style='font-size:10px'>10px</span>", "<span style='font-size:11px'>11px</span>", "<span style='font-size:12px'>12px</span>", "<span style='font-size:13px'>13px</span>", "<span style='font-size:14px'>14px</span>", "<span style='font-size:16px'>16px</span>", "<span style='font-size:22px'>22px</span>");
var formatBlockArray = new Array("<div>div</div>","<span>span</span>","<p>p</p>", "<pre>pre</pre>", "<h6>h6</h6>", "<h5>h5</h5>", "<h4>h4</h4>", "<h3>h3</h3>", "<h2>h2</h2>", "<h1>h1</h1>");
//Drop Down List of values
var time = null;
var ZIndex = 10;

function hideErr(){
  clearTimeout(time);
  if( document.getElementById('ErrorCloud'))
	document.getElementById('ErrorCloud').style.display = 'none';
}

function reportErr(el){
    hideHelp();
    showHelp(el, 'null', 'ErrorCloud');
    time = setTimeout("hideErr()", 1000);
}

function hideHelp(){
  clearTimeout(time);
  if( document.getElementById('HelpCloud'))
	document.getElementById('HelpCloud').style.display = 'none';
}

function displayHelp(IE, other, elID){
  hideErr();
  time = setTimeout("showHelp('"+ IE +"', '" + other + "', '" + "HelpCloud" + "')", 800);
}

function showHelp(IE, other, elID){
  
  if(document.getElementById(elID)) {
	document.getElementById(elID).style.display = 'block';
	document.getElementById(elID).innerHTML = '<p>'+ IE +'</p>';
	inFront(document.getElementById(elID));
	document.getElementById(elID).style.top = (tempY-parseInt(document.getElementById(elID).clientHeight)-5) + 'px';
	document.getElementById(elID).style.left = (tempX + 5) + 'px';
  }
}

function inFront(el){

    ZIndex++;
    el.style.zIndex = ZIndex;
}

var listOpened = false;
var lastList = null;
function listElemOver(el){
    el.style.backgroundColor="#ACC0FA";
};
function listElemOut(el){
    el.style.backgroundColor="";
};
function getListElem(txt, num, funct, sname, prefix){
     
    var newElem = '<a id="'+funct+'_'+num+'" onclick=" closeList();';
    
	if( sname){
		if(BrowserDetect.browser == 'Explorer')
			newElem += ' oSel.setProp( ' + "'" + sname + "'" + ', this.innerText, ' + "'" + prefix + "'" + '); " ';
		else
			newElem += ' oSel.setProp( ' + "'" + sname + "'" + ', this.textContent, ' + "'" + prefix + "'" + '); " ';
	}else{
		if(BrowserDetect.browser == 'Explorer')
			newElem += ' oSel.'+funct+'( this.innerText); " ';
		else
			newElem += ' oSel.'+funct+'( this.textContent); " ';
        }
    newElem += ' onmouseover="listElemOver(this); return false;" onmouseout="listElemOut(this); return false;" ';
    
    if(num==0)
        newElem += ' style="float:left; clear:left; width:100%; height:auto; cursor:pointer; font-size:11px;" ';
    else
        newElem += ' style="float:left; clear:left; width:100%; height:auto; cursor:pointer; font-size:11px; border-top: 1px solid rgb(114,146,240);" ';
    
    newElem += '>' + txt + '</a>';
    return newElem;
};
function closeList(){
    var list = document.getElementById('ComboList');
    list.style.display = 'none';
    listOpened = false;
};
function openList(par, elem, sname, prefix){
    
    var arr = eval( par + 'Array');
    inFront(document.getElementById('ComboList'));
    var list = document.getElementById('ComboList');
	if( prefix)
		list.style.width = (parseInt(document.getElementById(sname + '_' + prefix).offsetWidth) + 9 ) + 'px';
	else
		list.style.width = (parseInt(document.getElementById(par + 'Link').offsetWidth) + 9 ) + 'px';
        
    if(lastList == par && !listOpened){
        
        list.style.display = 'block';
        list.style.top = (tempY + 8) + 'px';
        list.style.left = (tempX - parseInt(list.style.width) + 5) + 'px';
        listOpened = true;
        return false;
        
    }else if(lastList == par && listOpened){
        
        list.style.display = 'none';
        listOpened = false;
        return false;
        
    }else if(lastList != par && listOpened){
        list.innerHTML = "";
        for(var i=0; i<arr.length; i++){
            
            list.innerHTML += getListElem(arr[i], i, par, sname, prefix);
        }
        
        lastList = par;
        list.style.display = 'block';
        list.style.top = (tempY + 8) + 'px';
        list.style.left = (tempX - parseInt(list.style.width) + 5) + 'px';
    }else if(lastList != par && !listOpened){
        list.innerHTML = "";
        for(var i=0; i<arr.length; i++){
            
            list.innerHTML += getListElem(arr[i], i, par, sname, prefix);
        }
        
        lastList = par;
        listOpened = true;
        list.style.display = 'block';
        list.style.top = (tempY + 8) + 'px';
        list.style.left = (tempX - parseInt(list.style.width) + 5) + 'px';
    }
    
}
function AdeoContainer( contName){
	this.Container = new AdeoMap();

	AdeoElement.call( this);
	if( contName)
		AdeoElement.prototype.setAttribute.call( this, 'id', contName);
}

AdeoContainer.prototype = new AdeoElement();
AdeoContainer.prototype.constructor = AdeoContainer;

AdeoContainer.prototype.putToContainer = function( key, element){
	this.Container.put( key, element);
};

AdeoContainer.prototype.getFromContainer = function( key){
	return this.Container.get( key);
};
AdeoContainer.prototype.putByFunctionToContainer = function( key, element, fja){
	this.Container.putByFunction( key, element, fja);
};

AdeoContainer.prototype.getByFunctionFromContainer = function( key, fja){
	return this.Container.getByFunction( key, fja);
};

function AdeoUrlWinNameKeyEqual( key1, key2){
	if( (key1 instanceof AdeoUrlWinNameKey) && (key2 instanceof AdeoUrlWinNameKey)){
		if( key1.url == key2.url)
			return true;
		else if( key1.windowName == key2.windowName)
			return true;
		else 
			return false;
	}
};
function AdeoUrlWinNameKey( url, windowName){
	this.url = url;
	this.windowName = windowName;
};
function AdeoCss( cssName, styleArray){
	if( cssName){
		this.CssName = '.' + cssName;
		this.Css = AdeoGlobal.Css.addCssRule( '.' + cssName);
		this.style = this.Css.style;
	}else if( styleArray){
		this.Inline = true;
		this.style = styleArray;
	}else{
		this.style = new Array();
	}
	this.recentColors = new Array();
	this.changed = false;
	this.undoSteps = new Array();
	this.redoSteps = new Array();
	this.currentUndoStep = 0;
	this.currentRedoStep = 0;	
};
AdeoCss.prototype.getText = function( ){
	return this.style.cssText;
}
AdeoCss.prototype.setValuesTo = function( prefix){
	for( var i=0; i<AdeoCssProperties.length; i++){
		if( document.getElementById( AdeoCssProperties[i] + '_' + prefix))
			this.setValueTo( document.getElementById( AdeoCssProperties[i] + '_' + prefix));
	}
};
AdeoCss.prototype.getValuesFrom = function( prefix){
	for( var i=0; i<AdeoCssProperties.length; i++){
		if( document.getElementById( AdeoCssProperties[i] + '_' + prefix))
			this.getValueFrom( document.getElementById( AdeoCssProperties[i] + '_' + prefix));
	}
};
AdeoCss.prototype.merge = function( adeoCss){
	try{
		if( adeoCss instanceof AdeoCss)
			for( var i=0; i<AdeoCssProperties.length; i++)
				if( !this.getProperty( AdeoCssProperties[i]) && 
				    adeoCss.getProperty( AdeoCssProperties[i]) &&
					adeoCss.getProperty( AdeoCssProperties[i]) != 'inherit')
						this.setProperty( AdeoCssProperties[i], adeoCss.getProperty( AdeoCssProperties[i]));
	}catch(e){
		alert( e.toString());
	}
};
AdeoCss.prototype.inherit = function( adeoCss){
	try{
		if( adeoCss instanceof AdeoCss)
			for( var i=0; i<AdeoCssInheritProperties.length; i++)
				if( !this.getProperty( AdeoCssInheritProperties[i]) && 
				    adeoCss.getProperty( AdeoCssInheritProperties[i]) &&
					adeoCss.getProperty( AdeoCssProperties[i]) != 'inherit')
						this.setProperty( AdeoCssInheritProperties[i], adeoCss.getProperty( AdeoCssInheritProperties[i]));
	}catch(e){
		alert( e.toString());
	}
};
AdeoCss.prototype.setProperty = function( prop, value, prefix){
	var sName = prop;
	if( !sName) return false;
	if( sName == 'float'){
		if(BrowserDetect.browser == 'Explorer')
			sName = 'styleFloat';
		else        
			sName = 'cssFloat'; 
	}else if( sName == 'backgroundImage'){
		value = value ? ( value.indexOf( 'url') == -1 ? 'url( ' + value + '.gif)' : value ) : '';
	}
	try{
		this.changed = true;
		this.undoSteps[this.currentUndoStep++] = new Step(prop, this.style[ sName], prefix);
		this.style[ sName] = value ? value : '';
		if( prefix && document.getElementById( prop + '_' + prefix))
			this.setValueTo( document.getElementById( prop + '_' + prefix) );
	}catch( e){
		alert( "Can't set " + sName + " to " + value);
	}
};  
AdeoCss.prototype.getProperty = function( prop){
	var sName = prop;
	if( !sName) return '';
	if( sName == 'float'){
		if(BrowserDetect.browser == 'Explorer')
			sName = 'styleFloat';
		else        
			sName = 'cssFloat'; 
	}
	return this.style[ sName];
};
AdeoCss.prototype.setValueTo = function( elem){
	var tmp = elem.id.split('_');
	if( elem){
		if( elem.nodeName.toUpperCase() == 'INPUT')
			elem.value = this.getProperty( tmp[0]);
		else{
			var clr = this.getProperty( tmp[0]);
			elem.style[ 'backgroundColor'] = clr ? clr : elem.getAttribute( 'defaultBgCl');
		}		
		if( tmp[0].toLowerCase().search('color') > 0)
			this.setRecentColor( tmp[0], this.getProperty( tmp[0]));
	}
};
AdeoCss.prototype.getValueFrom = function( elem){
	var tmp = elem.id.split('_');
	if( elem){
		if( elem.nodeName.toUpperCase() == 'INPUT')
			this.setProperty( tmp[0], elem.value);
		else{
			this.setProperty( tmp[0], elem.style[ 'backgroundColor']);
		}
	}
};
AdeoCss.prototype.setRecentColor = function( name, value){
        if( !this.recentColors[ name])
		this.recentColors[ name] = 0;
	this.recentColors[ name]++;
        if( this.recentColors[ name]>5)
		this.recentColors[ name]=1;     
	var recCol = document.getElementById( name + 'recentColor' + this.recentColors[ name]);
	if( recCol)
		recCol.style[ name] = value;
};    
AdeoCss.prototype.save = function(){
};    
AdeoCss.prototype.undo = function(){
        if(this.currentUndoStep>0){
                this.currentUndoStep--;
		var lastStep = this.undoSteps[ this.currentUndoStep];
                this.redoSteps[ this.currentRedoStep++] = new Step( lastStep.propName, this.style[ lastStep.propName], lastStep.propPrefix);
                this.setProperty( lastStep.propName, lastStep.propValue, lastStep.propPrefix);
	
		return lastStep;
        }else
		return null;
};    
AdeoCss.prototype.undoAll = function(){
        for(var i=0 ; i<this.currentUndoStep; i++){            
            this.Undo();
        }
};    
AdeoCss.prototype.redo = function(){    
        if( this.currentRedoStep>0){
		this.currentRedoStep--;	
		var lastStep = this.redoSteps[ this.currentRedoStep];
		this.setProperty( lastStep.propName, lastStep.propValue, lastStep.propPrefix);
		
		return lastStep;
        }else
		return null;
};
AdeoCss.prototype.getSavePost = function(){
	var result = '';
	for( var i=0; i<AdeoCssProperties.length; i++){
		var cssValue = this.getProperty( AdeoCssProperties[i]);
		if( AdeoCssProperties[i] == 'backgroundImage'){
			cssValue = parseInt( cssValue.substr(4)) ? parseInt( cssValue.substr(4)) : '';
		}
		eval( 'var attrName = AdeoCssSave.' + AdeoCssProperties[i] + ';');
		result += '&value(' + attrName + ')=' + encodeURIComponent( cssValue);
	}
	return result;
};

function Step(prop, oldValue, prefix){

    this.propName = prop;
    this.propValue = oldValue;
    this.propPrefix = prefix;
}

AdeoCssSave = { font:'font',color:'color',fontFamily:'font_family',fontSize:'font_size',fontStyle:'font_style',fontVariant:'font_variant',fontWeight:'font_weight',textAlign:'text_align',textIndent:'text_indent',textDecoration:'text_decoration',textTransform:'text_transform',backgroundAttachment:'back_attachment',backgroundImage:'id_back_image',backgroundPosition:'back_pos',backgroundColor:'back_color',backgroundRepeat:'back_repeat',content:'content',direction:'direction',letterSpacing:'letter_spacing',lineHeight:'line_height',wordSpacing:'word_spacing',marginTop:'margin_top',marginLeft:'margin_left',margin:'margin',marginRight:'margin_right',marginBottom:'margin_bottom',paddingTop:'padding_top',paddingLeft:'padding_left',padding:'padding',paddingRight:'padding_right',paddingBottom:'padding_bottom',borderTopStyle:'border_top_style',borderLeftStyle:'border_left_style',borderStyle:'border_style',borderRightStyle:'border_right_style',borderBottomStyle:'border_bottom_style',borderTopWidth:'border_top_width',borderLeftWidth:'border_left_width',borderWidth:'border_width',borderRightWidth:'border_right_width',borderBottomWidth:'border_bottom_width',borderTopColor:'border_top_color',borderLeftColor:'border_left_color',borderColor:'border_color',borderRightColor:'border_right_color',borderBottomColor:'border_bottom_color',borderSpacing:'border_spacing',borderCollapse:'border_collapse',width:'width',maxWidth:'max_width',minWidth:'min_width',height:'height',maxHeight:'max_height',minHeight:'min_height',display:'display',visibility:'visibility',float:'css_float',clear:'clear',overflow:'overflow',zIndex:'z_index',position:'position',top:'top',left:'left',right:'right',bottom:'bottom',cursor:'cursor',verticalAlign:'vertical_align',tableLayout:'table_layout',listStyleImage:'list_style_image',listStylePosition:'list_style_pos',listStyleType:'list_style_type',outlineStyle:'outline_style',outlineWidth:'outline_width',outlineColor:'outline_color',pageBreakAfter:'page_break_after',pageBreakBefore:'page_break_before',pageBreakInside:'page_break_inside',captionSide:'caption_side',clip:'clip',emptyCells:'empty_cells',markerOffset:'marker_offset',marks:'marks',quotes:'quotes',unicodeBidi:'unicode_bidi',whiteSpace:'white_space'};

AdeoCssProperties = [ 'font', 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontVariant', 'fontWeight', 'textAlign', 'textIndent', 'textDecoration', 'textTransform', 'backgroundAttachment', 'backgroundImage', 'backgroundPosition', 'backgroundColor', 'backgroundRepeat', 'content', 'direction', 'letterSpacing', 'lineHeight', 'wordSpacing', 'marginTop', 'marginLeft', 'margin', 'marginRight', 'marginBottom', 'paddingTop', 'paddingLeft', 'padding', 'paddingRight', 'paddingBottom', 'borderTopStyle', 'borderLeftStyle', 'borderStyle', 'borderRightStyle', 'borderBottomStyle', 'borderTopWidth', 'borderLeftWidth', 'borderWidth', 'borderRightWidth', 'borderBottomWidth', 'borderTopColor', 'borderLeftColor', 'borderColor', 'borderRightColor', 'borderBottomColor', 'borderSpacing', 'borderCollapse', 'width', 'maxWidth', 'minWidth', 'height', 'maxHeight', 'minHeight', 'display', 'visibility', 'float', 'clear', 'overflow', 'zIndex', 'position', 'top', 'left', 'right', 'bottom', 'cursor', 'verticalAlign', 'tableLayout', 'listStyleImage', 'listStylePosition', 'listStyleType', 'outlineStyle', 'outlineWidth', 'outlineColor', 'pageBreakAfter', 'pageBreakBefore', 'pageBreakInside', 'captionSide', 'clip', 'emptyCells', 'markerOffset', 'marks', 'quotes', 'unicodeBidi', 'whiteSpace'];
AdeoCssInheritProperties = [ 'font', 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontVariant', 'fontWeight', 'textAlign', 'textIndent', 'textDecoration', 'textTransform', 'backgroundColor', 'content', 'direction', 'letterSpacing', 'lineHeight', 'wordSpacing', 'verticalAlign', 'tableLayout', 'listStyleImage', 'listStylePosition', 'listStyleType', 'outlineStyle', 'outlineWidth', 'outlineColor', 'pageBreakAfter', 'pageBreakBefore', 'pageBreakInside', 'emptyCells', 'markerOffset', 'marks', 'quotes', 'unicodeBidi', 'whiteSpace'];
AdeoCssFrameProperties = [ 'width', 'height'];
function AdeoImage( elem, url){
	if( elem)
		AdeoElement.call( this, elem);
	else
		AdeoElement.call( this, 'img');

	if( url)
		this.Element.src = url;

	//this.initProperties();
};
AdeoImage.prototype = new AdeoElement();
AdeoImage.prototype.constructor = AdeoImage;

AdeoImage.prototype.setValuesTo = function( prefix){
	for( var i=0; i<AdeoImageProperties.length; i++){
		if( document.getElementById( AdeoImageProperties[i] + '_' + prefix))
			document.getElementById( AdeoImageProperties[i] + '_' + prefix).value = this.getProperty( AdeoImageProperties[i]);
	}
};
AdeoImage.prototype.getValuesFrom = function( prefix){
	for( var i=0; i<AdeoImageProperties.length; i++){
		if( document.getElementById( AdeoImageProperties[i] + prefix))
			this.setProperty( AdeoImageProperties[i], document.getElementById( AdeoImageProperties[i] + prefix).value);
	}
};
AdeoImage.prototype.setProperty = function( prop, value, prefix){
	if( eval( 'this.' + prop)){
		eval( 'this.' + prop +' = ' + value);
		if( prefix)
			this.setValueTo( document.getElementById( prop + '_' + prefix) );
        }
};    
AdeoImage.prototype.getProperty = function( prop){
	if( eval( 'this.' + prop)){
		return eval( 'this.' + prop);
        }else{
		return "";
	}
};

AdeoImageProperties = [ 'border', 'complete', 'height', 'hspace', 'lowsrc', 'name', 'src', 'vspace', 'width']

function AdeoTable( elem){
	if( elem)
		AdeoElement.call( this, elem);
	else
		AdeoElement.call( this, 'table');

	this.body = new AdeoElement( 'tbody');
	//this.body.setStyle( 'overflowY', 'auto');
	//this.body.setStyle( 'overflowX', 'hidden');
	//this.body.setStyle( 'height', '300px');
	this.add( this.body);
	this.selectedCell = null;
	this.selectedRow = null;
	this.rows = this.body.Element.rows;
	this.cells = this.body.Element.cells;
	this.update();
};
AdeoTable.prototype = new AdeoElement();
AdeoTable.prototype.constructor = AdeoTable;

AdeoTable.prototype.setRowsCols = function( rows, cols){
	if( rows && cols && parseInt( rows)>0 && parseInt( cols)>0 ){		
		for(var i=0; i<rows; i++){
			this.insertRow( 0);
		}
		for(var j=0; j<cols; j++){
			this.insertColumn( 0);
			if( this.headTR){
				var th = new AdeoElement( 'th');
				this.headTR.add( th);	
				this.setDefaultCellStyle( th.Element);
			}
		}
	}
	this.update();
};
AdeoTable.prototype.toHTML = function(){
	var table = new AdeoElement();
	table.add( this);
	return table.Element.innerHTML;
};
AdeoTable.prototype.setValuesTo = function( prefix){
	for( var i=0; i<AdeoTableProperties.length; i++){
		if( document.getElementById( AdeoTableProperties[i] + '_' + prefix))
			document.getElementById( AdeoTableProperties[i] + '_' + prefix).value = this.getProperty( AdeoTableProperties[i]);
	}
};
AdeoTable.prototype.getValuesFrom = function( prefix){
	for( var i=0; i<AdeoTableProperties.length; i++){
		if( document.getElementById( AdeoTableProperties[i] + prefix))
			this.setProperty( AdeoTableProperties[i], document.getElementById( AdeoTableProperties[i] + prefix).value);
	}
};

AdeoTableProperties = [ 'border', 'caption', 'cellPadding', 'cellSpacing', 'frame', 'id', 'rules', 'summary', 'tFoot', 'tHead', 'width', 'className', 'dir', 'lang', 'title']

AdeoTable.prototype.update = function(){
	var currrow;
	var currcell;
	for(var i=0; i<this.rows.length; i++){  
		currrow = this.rows[i];
		currrow.setAttribute('id', this.id +'_rowx' + i);
		for(var j=0; j<currrow.cells.length; j++){
			currcell = currrow.cells[j];
			currcell.setAttribute('id', this.id +'_rowx' + i + '_cellx' + j);
		}
	}
};
AdeoTable.prototype.insertRow = function( where) {
	var currRow = this.body.Element.insertRow( where);
	this.setDefaultRowStyle( currRow);
	for (var i = 0; i < currRow.cells.length; i++) {
		this.setDefaultCellStyle( currRow.insertCell(i));
	}
	this.update();  
	return currRow;
	
};
AdeoTable.prototype.insertColumn = function( where){
	for(var i=0; i<this.rows.length; i++){  
		this.setDefaultCellStyle( this.rows[i].insertCell( where));
	}
	this.update();  
};
AdeoTable.prototype.deleteRow = function( where){
	row = this.rows[ where];
	for(var i=0; i<row.cells.length; i++){
            if(row.cells[i].getAttribute('rowspan') ){
                if(row.cells[i].getAttribute('rowspan') > 1 ){
                    reportErr('First remove rowspans from selected row!');
                    return false;
                }
            }
        }    
        this.deleteRow(row.rowIndex);
	this.update(); 
};
AdeoTable.prototype.deleteColumn = function( where){        
        for(var i=0; i<this.rows.length; i++){
		if( !this.rows[i].cells[ where] || !this.rows[i].cells[ where].getAttribute( 'colspan')){            
			reportErr('First remove colspans from selected column!');
			return false;                    
		}
		this.rows[i].deleteCell( where);
        }
	this.update(); 
};
AdeoTable.prototype.setDefaultRowStyle = function( row){
	row.style.borderCollapse = 'collapse';
	row.style.border = '1px solid #000000';
};
AdeoTable.prototype.setDefaultCellStyle = function( cell){
	cell.style.borderCollapse = 'collapse';
	cell.style.border = '1px solid #000000';
	cell.innerHTML = '&nbsp;';
};

AdeoTable.prototype.insertRowBefore = function() {
	if( this.selectedRow){ 
		return this.insertRow( this.selectedRow.Element.rowIndex);
	}else{
		reportErr('No cell selected');
	}
}

AdeoTable.prototype.insertRowAfter = function( ) {
	if( this.selectedRow ){
		return this.insertRow( this.selectedRow.Element.rowIndex + 1);
	}else{
		reportErr('No cell selected');
	}
}

AdeoTable.prototype.insertColumnBefore = function( ) {
	if( this.selectedCell ){
		this.insertColumn( this.selectedCell.Element.cellIndex);
	}else{
		reportErr('No cell selected');
	}
}

AdeoTable.prototype.insertColumnAfter = function( ) {
	if( this.selectedCell ){
		this.insertColumn( this.selectedCell.Element.cellIndex + 1);
	}else{
		reportErr('No cell selected');
	}
}

AdeoTable.prototype.addRowFirst = function( ) {
	if( this.Element ){
		return this.insertRow( 0);
	}else{
		reportErr('No table selected');
	}	
}

AdeoTable.prototype.addRowEnd = function( ) {
	if( this.Element ){
		return this.insertRow( -1);
	}else{
		reportErr('No table selected');
	}
}

AdeoTable.prototype.addColumnFirst = function( ) {
	if( this.rows.length > 0 ){
		this.insertColumn( 0);
	}else{
		reportErr('No table selected');
	}
}

AdeoTable.prototype.addColumnEnd = function( ) {
	if(  this.rows.length > 0 ){
		this.insertColumn( -1);
	}else{
		reportErr('No table selected');
	}
}

AdeoTable.prototype.cellSpanify = function( num){    
	if( this.selectedCell && this.selectedRow && this.Element){
		var oldColSpan = parseInt( this.selectedCell.getAttribute('colspan'));
		var newColSpan = parseInt(num);        
		if(!newColSpan || newColSpan <= 0){
			reportErr('Not a valid Number');             
		}else if( oldColSpan < newColSpan || !oldColSpan){       
			var currRowId =  this.selectedRow.id.split('_')[1].split('x');
			var rowId = parseInt( currRowId[1]);
			var currCellId = this.selectedCell.id.split('_')[2].split('x');
			var celId = parseInt( currCellId[1]);
			var spanCounter = 1;
            
			for(var i=1; i<newColSpan; i++){
				if( this.body.cells[ this.selectedRow.id + '_cellx' + (celId+1)]){
					this.selectedRow.deleteCell( this.selectedCell.cellIndex + i);
					spanCounter++;
				}else 
					break;
			}
			this.update();
			if(spanCounter >1 && !oldColSpan)
				this.selectedCell.setAttribute('colspan', spanCounter);
			else if(spanCounter >1 && oldColSpan)
				this.selectedCell.setAttribute('colspan', spanCounter + oldColSpan-1);
		}else {        
			for(var j=0; j<oldColSpan - newColSpan; j++){
				newCell = this.selectedRow.insertCell( this.selectedCell.cellIndex + 1);
				newCell.setAttribute('rowspan', this.selectedCell.getAttribute('rowspan'));
				newCell.style.borderCollapse = 'collapse';
				newCell.style.border = '1px solid #000000';
				newCell.innerHTML = '&nbsp;';
			}      
			this.selectedCell.setAttribute('colspan', newColSpan);
			this.update();
		}
	}else{
		reportErr('No cell selected');
	}
};

AdeoTable.prototype.rowSpanify = function( num){    
	if( this.selectedCell && this.selectedRow && this.Element){
		var oldRowSpan = parseInt(selectedCell.getAttribute('rowspan'));
		var newRowSpan = parseInt(num);
		var colSpan = parseInt(selectedCell.getAttribute('colspan'));
                
		var currRowId = selectedRow.id.split('_')[1].split('x');
		var rowId = parseInt(currRowId[1]);
		var currCellId = selectedCell.id.split('_')[2].split('x');
		var celId = parseInt(currCellId[1]);
		var spanCounter = 1;
        
		if(!newRowSpan || newRowSpan <= 0){
			reportErr('Not a valid Number');             
		}else if(oldRowSpan < newRowSpan || !oldRowSpan){
			for(var i=1; i<newRowSpan; i++){
				if( this.rows[ this.id + '_rowx' + (rowId + i)]){
				    var currRow = this.body.rows[ this.id + '_rowx' + (rowId + i)];                  
					if( this.body.cells[currRow.id + '_cellx' + celId]){
						var currCell = this.cells[currRow.id + '_cellx' + celId];
						if( currCell.getAttribute('colspan') != this.selectedCell.getAttribute('colspan') ){
							var tmpCell = this.selectedCell;
							var tmpRow = this.selectedRow;
							this.selectedCell = currCell;
							this.selectedRow = currRow;
						    
							this.cellSpanify( parseInt(tmpCell.getAttribute('colspan')));
							this.selectedCell = tmpCell;
							this.selectedRow = tmpRow;
						}
						currRow.deleteCell( currCell.cellIndex);
						spanCounter++;
					}
				}else 
					break;
			}
			this.update();
			if(spanCounter >1 && !oldRowSpan)
				this.selectedCell.setAttribute('rowspan', spanCounter);
			else if(spanCounter >1 && oldRowSpan)
				this.selectedCell.setAttribute('rowspan', spanCounter + oldRowSpan -1);
                
		}else {
			for(var j=0; j<oldRowSpan - newRowSpan; j++){
				var currRow = this.rows[ this.id + '_rowx' + (rowId + j + 1)];
				newCell = currRow.insertCell( this.selectedCell.cellIndex);
				newCell.setAttribute('colspan', this.selectedCell.getAttribute('colspan'));
				newCell.style.borderCollapse = 'collapse';
				newCell.style.border = '1px solid #000000';
				newCell.innerHTML = '&nbsp;';
			}      
			this.selectedCell.setAttribute('rowspan', newRowSpan);
			this.update();
		}
	}else{
		reportErr('No cell selected');
	}
}
function AdeoCalendar( obj){
	if( obj instanceof AdeoCalendar){
		this.copy( obj);
	}else{	
		this.date = new Date();
		this.today = new Date();
	}
}
AdeoCalendar.prototype.getDateStrWithDOW = function (){
        var todayStr = AdeoGlobal.Date.Day.HR[this.currentDay()] + " " + this.currentDate() + ". ";
        todayStr += AdeoGlobal.Date.Month.HR[this.currentMonth()];
        todayStr += ", " + this.currentYear() + ".";
        return todayStr;
};
AdeoCalendar.prototype.copy = function( obj){
	if( obj instanceof AdeoCalendar){
		this.date = new Date( obj.date);
		this.today = new Date( obj.today);
	}
}
AdeoCalendar.prototype.setAll = function( strDate){
	var arr = strDate.split('.');
	this.date.setDate( arr[0]);
	this.date.setMonth( arr[1]);
	this.date.setYear( arr[2]);
};
AdeoCalendar.prototype.gotoStartMonth = function(){
	while( this.date.getDate() != 1)
		this.dayBackward();
};
AdeoCalendar.prototype.getAll = function(){
	return this.date.getDate() + '.' + (this.date.getMonth()+1) + '.' + this.date.getYear();
};
AdeoCalendar.prototype.getDate = function( ){
	return this.date.getDate();
};
AdeoCalendar.prototype.getDay = function( ){
	return this.date.getDay();
};
AdeoCalendar.prototype.getMonth = function( ){
	return this.date.getMonth();
};
AdeoCalendar.prototype.getYear = function( ){   
	return this.date.getYear();
};
AdeoCalendar.prototype.setDate = function( num){
	this.date.setDate( num);
};
AdeoCalendar.prototype.setDay = function( num){
	this.date.setDay( num);
};
AdeoCalendar.prototype.setMonth = function( num){
	this.date.setMonth( num);
};
AdeoCalendar.prototype.setYear = function( num){   
	this.date.setYear( num);
};
AdeoCalendar.prototype.todaysDate = function(){
	return this.today.getDate();
};
AdeoCalendar.prototype.todaysDay = function(){
	return this.today.getDay();
};
AdeoCalendar.prototype.todaysMonth = function(){
	return this.today.getMonth();
};
AdeoCalendar.prototype.todaysYear = function(){        
	var year = this.today.getYear();
        if(year<1900) year+=1900;
        return year;
};
AdeoCalendar.prototype.currentDate = function(){
	return this.date.getDate();
};
AdeoCalendar.prototype.currentDay = function(){
	return this.date.getDay();
};
AdeoCalendar.prototype.currentMonth = function(){
	return this.date.getMonth();
};
AdeoCalendar.prototype.currentYear = function(){        
	var year = this.date.getYear();
        if(year<1900) year+=1900;
        return year;
};
AdeoCalendar.prototype.dayForward = function( num){
	var Num = parseInt( num);
	if( Num)
		this.date.setDate( this.date.getDate() + Num);
	else
		this.date.setDate( this.date.getDate() + 1);
};    
AdeoCalendar.prototype.dayBackward = function( num){
        var Num = parseInt( num);
	if( Num)
		this.date.setDate( this.date.getDate() - Num);
	else
		this.date.setDate( this.date.getDate() - 1);
};    
AdeoCalendar.prototype.weekForward = function( num){
        var Num = parseInt( num);
	if( Num)
		this.date.setDate( this.date.getDate() + Num*7);
	else
		this.date.setDate( this.date.getDate() + 7);
};    
AdeoCalendar.prototype.weekBackward = function( num){
        var Num = parseInt( num);
	if( Num)
		this.date.setDate( this.date.getDate() - Num*7);
	else
		this.date.setDate( this.date.getDate() - 7);
};    
AdeoCalendar.prototype.monthForward = function( num){
	this.date.setDate( 1);
        var Num = parseInt( num);
	if( Num)
		this.date.setMonth( this.date.getMonth() + Num);
	else
		this.date.setMonth( this.date.getMonth() + 1);
};    
AdeoCalendar.prototype.monthBackward = function( num){
	this.date.setDate( 1);
        var Num = parseInt( num);
	if( Num)
		this.date.setMonth( this.date.getMonth() - Num);
	else
		this.date.setMonth( this.date.getMonth() - 1);
};    
AdeoCalendar.prototype.yearForward = function( num){
	this.date.setDate( 1);
        var year = this.date.getYear();
        if(year<1900) year+=1900;

        var Num = parseInt( num);
	if( Num)
		this.date.setYear( year + Num);
	else
		this.date.setYear( year + 1);
};    
AdeoCalendar.prototype.yearBackward = function( num){
	this.date.setDate( 1);
        var year = this.date.getYear();
        if(year<1900) year+=1900;
        
        var Num = parseInt( num);
	if( Num)
		this.date.setYear( year - Num);
	else
		this.date.setYear( year - 1);
};

NIJS.Adeo.Date = {};
NIJS.Adeo.Date.Calendar = {};
NIJS.Adeo.Date.Calendar.Object = AdeoCalendar;
NIJS.Adeo.Date.Calendar.isDateFormat = function( str){
	var arr = str.split('.');
	if( arr.length!=4)
		return false;
	if( !AdeoGlobal.Number.isNumber( arr[0]) || !AdeoGlobal.Number.isNumber( arr[1]) || !AdeoGlobal.Number.isNumber( arr[2]))
		return false;
	return true;
};
function AdeoTabs() {
	this.selected = new Array();
}
AdeoTabs.prototype.selectTab = function( tabsName, tabId) {
	var currentClicked = new Array();
	currentClicked .tab = new AdeoElement( tabsName + 'tab' + tabId);
	currentClicked .cont = new AdeoElement( tabsName + 'cont' + tabId);

	if( !this.selected[tabsName])
		this.setSelected( tabsName);

	if( this.selected[tabsName] && this.selected[tabsName].tab.id != currentClicked .tab.id){
		this.unmarkSelected(tabsName);
		this.selected[tabsName] = currentClicked;
		this.markSelected(tabsName);
	}
}
AdeoTabs.prototype.selectTabAnyway = function( tabsName, tabId) {
	var currentSelected = new Array();
	currentSelected.tab = new AdeoElement( tabsName + 'tab' + tabId);
	currentSelected.cont = new AdeoElement( tabsName + 'cont' + tabId);

	if( !this.selected[tabsName])
		this.setSelected( tabsName);

	this.unmarkSelected();
	this.selected[tabsName] = currentSelected;
	this.markSelected();
}
AdeoTabs.prototype.markSelected = function(tabsName){
	if( !this.selected[tabsName])
		return;
		
	var oldStyle = this.selected[tabsName].tab.getClassName();
	this.selected[tabsName].tab.setClass( oldStyle + 'Sel');
	this.selected[tabsName].cont.display();
};
AdeoTabs.prototype.unmarkSelected = function(tabsName){
	if( !this.selected[tabsName])
		return;
	
	var oldStyle = this.selected[tabsName].tab.getClassName();
	this.selected[tabsName].tab.setClass( oldStyle.substring( 0, oldStyle.length-3));
	this.selected[tabsName].cont.hide();
	this.selected[tabsName] = null;
};
AdeoTabs.prototype.setSelected = function( tabsName){
	var i = 0;
	var elem = document.getElementById( tabsName + 'tab' + 0);
	while( elem){
		var oldStyle = elem.className;
		var postfix = oldStyle.substring( oldStyle.length-3);
		if( postfix == 'Sel'){
			var currentSelected = new Array();
			currentSelected.tab = new AdeoElement( tabsName + 'tab' + i);
			currentSelected.cont = new AdeoElement( tabsName + 'cont' + i);
			this.selected[tabsName] = currentSelected;
			break;
		}
		i += 1;
		elem = document.getElementById( tabsName + 'tab' + i);		
	}
};

var adeoTabs = new AdeoTabs();

function AdeoResponse( resp){
	this.responseText = resp;
	this.type = AdeoResponseType[0];
	this.JSON = this.getJSONResult();
};
AdeoResponse.prototype.getJSONResult = function(){	
	var divResp = new AdeoElement();
	divResp.setInnerHTML( this.responseText);
	try{
		if( divResp.Element.innerHTML.indexOf( 'Dogodila se') > 0){
			alert( divResp.Element.firstChild.innerHTML);
			this.type = AdeoResponseType[3];
			return null;
		}else if( divResp.Element.firstChild && divResp.Element.firstChild.id == 'response'){
			this.type = AdeoResponseType[2];
			eval( divResp.Element.firstChild.innerHTML);
			if( response)
				return response;
		}else if( divResp.Element.innerHTML.indexOf( 'data') != -1 || divResp.Element.innerHTML.indexOf( 'area') != -1){
			this.type = AdeoResponseType[1]; 
			var response = null;
			eval( 'response = {' + divResp.Element.innerHTML + '}');
			if( response)
				return response;
		}else{
			return this.responseText;
			this.type = AdeoResponseType[0];
		}
	}catch( e){
		alert( 'Response error');
		this.type = AdeoResponseType[3];
		return null;
	}
};
AdeoResponse.prototype.getHTMLResult = function(){
	return this.responseText;	
};


function AdeoDataResponse( json){
	this.JSON = json;
};
AdeoDataResponse.prototype.applyRelations = function( attrTable){
	if( !this.JSON || !this.JSON.rows)
		return null;
	for( i in this.JSON.rows){
		for( j in attrTable.relations){
			if( this.JSON.rows[i][j] && this.JSON.rows[i][j] != "null"){
				if( adeoDB.tables[ attrTable.relations[j].tableID]){
					for( k in attrTable.relations[j].tableAttrs){
						if( attrTable.relations[j].tableAttrs[k].jsonName)
							this.JSON.rows[i][j] = adeoDB.tables[attrTable.relations[j].tableID].data.rows[this.JSON.rows[i][j]][attrTable.relations[j].tableAttrs[k].dbName];
					}
				}
			}
		}
	}
	return this.JSON;
};
AdeoDataResponse.prototype.addRelations = function( attrTable){
	if( !this.JSON || !this.JSON.rows)
		return null;
	for( i in this.JSON.rows){
		for( j in attrTable.relations){
			if( this.JSON.rows[i][j] && this.JSON.rows[i][j] != "null"){
				if( adeoDB.tables[ attrTable.relations[j].tableID]){
					for( k in attrTable.relations[j].tableAttrs){
						if( attrTable.relations[j].tableAttrs[k].jsonName)
							this.JSON.rows[i][attrTable.relations[j].tableAttrs[k].jsonName] = adeoDB.tables[attrTable.relations[j].tableID].data.rows[this.JSON.rows[i][j]][attrTable.relations[j].tableAttrs[k].dbName];
						else
							this.JSON.rows[i][attrTable.relations[j].tableAttrs[k].dbName] = adeoDB.tables[attrTable.relations[j].tableID].data.rows[this.JSON.rows[i][j]][attrTable.relations[j].tableAttrs[k].dbName];
					}
				}
			}
		}
	}
	return this.JSON;
};
AdeoDataResponse.prototype.addConstant = function( name, value){
	if( !this.JSON || !this.JSON.rows)
		return null;
	for( i in this.JSON.rows){
		this.JSON.rows[i][name] = value;
	}
	return this.JSON;
};
AdeoResponseType = [ 'HTML', 'TABLE', 'ROW', 'ERROR'];

function AdeoDBTableAttrsNameValue( oldName, newName){
	this.dbName = oldName;
	this.jsonName = newName;
};
function AdeoDBTableAttrs( idTable){
	this.tableID = idTable;
	this.tableAttrs = new Array();
};
AdeoDBTableAttrs.prototype.add = function( oldName, newName){
	this.tableAttrs[ this.tableAttrs.length] = new AdeoDBTableAttrsNameValue( oldName, newName)
};
function AdeoDBRelations(){
	this.relations = new Array();
};
AdeoDBRelations.prototype.add = function( attr, idTable, oldName, newName){
	if( !this.relations[ attr])
		this.relations[ attr] = new AdeoDBTableAttrs( idTable);
	this.relations[ attr].add( oldName, newName);
};

function AdeoDB(){
	this.tables = new Array();
};
AdeoDB.prototype.loadTable = function( idTable){
	AdeoGlobal.Ajax.load.call( this, '/DataDetail.do?entity=' + idTable + '&action=json', adeoDB.callbackTable, null, idTable);
};
AdeoDB.prototype.callbackTable = function( loadedAjax, url, idTable){
	var resp = new AdeoResponse( loadedAjax);
	adeoDB.tables[ idTable] = resp.getJSONResult();
};

var adeoDB = new AdeoDB();

function AdeoDataGrid( data, target){

	AdeoTable.call( this);
	this.name = 'AdeoDataGrid_' + this.id;
	this.target = target;
	this.params = null;
	
	if( !data)
		return;
	this.jsonData = data;
	this.displayNames = {};
	for( var i in this.jsonData.displayNames){
		this.displayNames[this.jsonData.displayNames[i]] = { name: this.jsonData.displayNames[i], caption: this.jsonData.displayNames[i], sort: SortType.NONE}
	}
};
AdeoDataGrid.prototype = new AdeoTable();
AdeoDataGrid.prototype.constructor = AdeoDataGrid;

AdeoDataGrid.prototype.init = function( dispNames){

	this.applyNames( dispNames);
		
	this.data = new Array();
	for( var i in this.jsonData.rows){
		this.data[ this.data.length] = this.jsonData.rows[i];
	}
	this.createTableFromData();
	
	for(var i in dispNames)
		if(dispNames[i].sort != SortType.NONE)
			this.sortBy(dispNames[i].name, dispNames[i].sort)
};

AdeoDataGrid.prototype.applyNames = function( dispNames){
	if( !dispNames)
		return;
	
	var tmpDN = new Array();
	
	for(var i in dispNames)
		tmpDN[tmpDN.length] = dispNames[i].colOrd;
	tmpDN.sort( this.sortIntFunction);
			
	this.displayNames = {};
	for(var i in tmpDN)
		for(var j in dispNames)
			if(dispNames[j].colOrd == tmpDN[i])
				this.displayNames[dispNames[j].name] = dispNames[j];
}

AdeoDataGrid.prototype.createTableFromData = function(){
	this.body.empty();
	this.Element.style.borderCollapse = 'collapse';
	this.setHead();
	for( var i in this.data){
		var k = 0;
		var currRow = this.body.Element.insertRow( 0);
		for( var j in this.displayNames ){
			if(this.displayNames[j].display){
				var currCell = currRow.insertCell( k++);
				this.setDefaultCellStyle( currCell);
				currCell.innerHTML = ( this.data[i][j] == 'null' || this.data[i][j] == null ? "" : this.data[i][j] );
			}
		}
	}
	this.update();	
};
AdeoDataGrid.prototype.setHead = function(){
	this.head = new AdeoElement( 'thead');
	this.headTR = new AdeoElement( 'tr');
	
	for( var i in this.displayNames ){
		if(this.displayNames[i].display){
			var th = new AdeoElement( 'th');
			th.addEventListener( 'click', AdeoGridSort);
			th.setStyle( 'cursor', 'pointer');
			th.setAttribute( 'gridName', this.name);
			th.setAttribute( 'ord', this.displayNames[i].sort);
			th.setAttribute( 'colName', this.displayNames[i].name);
			th.setAttribute( 'colOrd', this.displayNames[i].colOrd);
		
			this.setDefaultCellStyle( th.Element);
				
			var srtPic = 2647;			
			if( this.displayNames[i].sort == SortType.DESC)
				srtPic = 2645;
			else if(this.displayNames[i].sort == SortType.ASC)
				srtPic = 2646;
			
			th.Element.innerHTML = '<span>' + this.displayNames[i].caption + '</span><img width="9px" height="9px" style="margin-left:15px; margin-right:5px" src="' + srtPic + '.gif" />';
			this.headTR.add( th);	
		}
	}
	
	this.head.add( this.headTR);
	this.fillWith( this.head);
	this.add( this.body);
};
AdeoDataGrid.prototype.HTMLTable = function(){
	return this.toHTML();
};

AdeoDataGrid.prototype.sortBy = function( colName, order){
	AdeoDGConstants.colName = colName;
	AdeoDGConstants.order = order;
	this.displayNames[colName].sort = order;
	this.data.sort( this.sortFunction);
	this.createTableFromData();
};
AdeoDataGrid.prototype.sortFunction = function( a, b){
	var result = 0;
	if (AdeoDGConstants.order == SortType.DESC) {
        	eval( 'result = ( a.' + AdeoDGConstants.colName + ' > b.' + AdeoDGConstants.colName + ') ? -1 : 1');
        	return result;
    	} else if(AdeoDGConstants.order == SortType.ASC){
        	eval( 'result = ( a.' + AdeoDGConstants.colName + ' < b.' + AdeoDGConstants.colName + ') ? -1 : 1');
        	return result;
    	} else{
    		return result;
    	}
};
AdeoDataGrid.prototype.sortIntFunction = function( a, b){
	return a - b;
};
AdeoDataGrid.prototype.rename = function( newName){
	this.name = newName;       
	this.setAttribute('id', newName);
};

function AdeoGridSort(){
	var elem = adeo.element.niGetElementEventTarget( this);
	grid = GridContainer[ elem.getAttribute( 'gridName')];
	var ord = elem.getAttribute( 'ord');
	var colName = elem.getAttribute( 'colName');
	
	alert("Ovo je ord varijabla... " + ord);
	if( !ord)
		ord = 1;
	ord = (parseInt( ord) + 1) % 3;	
	alert("Ovo je ord varijabla... " + ord);
	
	elem.setAttribute( 'ord', ord);
	
	if( grid){
		grid.sortBy( colName, ord);
		windowContainer.open( grid.params);
	}
}

SortType = { DESC: 0, ASC: 1, NONE: 2}
AdeoDGConstants = { colName: 'id', order: SortType.ASC}
GridContainer = new Array();
var gridContainer = new AdeoGridContainer();
function AdeoGridContainer(){
}

AdeoGridContainer.prototype.open = function( gridParams){
	var grid = this.getGrid( gridParams);
	if( !grid)
		return false;
	gridParams.cont = grid.Element;
	var win = windowContainer.open( gridParams);
	gridParams.target = win.WinContent.id;
	grid.params = gridParams;
	grid.init( gridParams.displayNames);
	return grid;
};
AdeoGridContainer.prototype.getGrid = function( gridParams){
	var grid = null;
	if( gridParams.name && GridContainer[ gridParams.name]){
		grid = GridContainer[ gridParams.name];
	}else if( gridParams.JSON){
		grid = new AdeoDataGrid( gridParams.JSON, gridParams.target);
		if( gridParams.name)
			grid.rename( gridParams.name)
		GridContainer[ grid.name] = grid;
	}
	return grid;
};
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
function RGBColor(color_string){
        this.ok = false;
    
        // strip any leading #
        if (color_string.charAt(0) == '#') { // remove # if any
            color_string = color_string.substr(1,6);
        }
    
        color_string = color_string.replace(/ /g,'');
        color_string = color_string.toLowerCase();
    
        // before getting into regexps, try simple matches
        // and overwrite the input
        var simple_colors = {
            aliceblue: 'f0f8ff',
            antiquewhite: 'faebd7',
            aqua: '00ffff',
            aquamarine: '7fffd4',
            azure: 'f0ffff',
            beige: 'f5f5dc',
            bisque: 'ffe4c4',
            black: '000000',
            blanchedalmond: 'ffebcd',
            blue: '0000ff',
            blueviolet: '8a2be2',
            brown: 'a52a2a',
            burlywood: 'deb887',
            cadetblue: '5f9ea0',
            chartreuse: '7fff00',
            chocolate: 'd2691e',
            coral: 'ff7f50',
            cornflowerblue: '6495ed',
            cornsilk: 'fff8dc',
            crimson: 'dc143c',
            cyan: '00ffff',
            darkblue: '00008b',
            darkcyan: '008b8b',
            darkgoldenrod: 'b8860b',
            darkgray: 'a9a9a9',
            darkgreen: '006400',
            darkkhaki: 'bdb76b',
            darkmagenta: '8b008b',
            darkolivegreen: '556b2f',
            darkorange: 'ff8c00',
            darkorchid: '9932cc',
            darkred: '8b0000',
            darksalmon: 'e9967a',
            darkseagreen: '8fbc8f',
            darkslateblue: '483d8b',
            darkslategray: '2f4f4f',
            darkturquoise: '00ced1',
            darkviolet: '9400d3',
            deeppink: 'ff1493',
            deepskyblue: '00bfff',
            dimgray: '696969',
            dodgerblue: '1e90ff',
            feldspar: 'd19275',
            firebrick: 'b22222',
            floralwhite: 'fffaf0',
            forestgreen: '228b22',
            fuchsia: 'ff00ff',
            gainsboro: 'dcdcdc',
            ghostwhite: 'f8f8ff',
            gold: 'ffd700',
            goldenrod: 'daa520',
            gray: '808080',
            green: '008000',
            greenyellow: 'adff2f',
            honeydew: 'f0fff0',
            hotpink: 'ff69b4',
            indianred : 'cd5c5c',
            indigo : '4b0082',
            ivory: 'fffff0',
            khaki: 'f0e68c',
            lavender: 'e6e6fa',
            lavenderblush: 'fff0f5',
            lawngreen: '7cfc00',
            lemonchiffon: 'fffacd',
            lightblue: 'add8e6',
            lightcoral: 'f08080',
            lightcyan: 'e0ffff',
            lightgoldenrodyellow: 'fafad2',
            lightgrey: 'd3d3d3',
            lightgreen: '90ee90',
            lightpink: 'ffb6c1',
            lightsalmon: 'ffa07a',
            lightseagreen: '20b2aa',
            lightskyblue: '87cefa',
            lightslateblue: '8470ff',
            lightslategray: '778899',
            lightsteelblue: 'b0c4de',
            lightyellow: 'ffffe0',
            lime: '00ff00',
            limegreen: '32cd32',
            linen: 'faf0e6',
            magenta: 'ff00ff',
            maroon: '800000',
            mediumaquamarine: '66cdaa',
            mediumblue: '0000cd',
            mediumorchid: 'ba55d3',
            mediumpurple: '9370d8',
            mediumseagreen: '3cb371',
            mediumslateblue: '7b68ee',
            mediumspringgreen: '00fa9a',
            mediumturquoise: '48d1cc',
            mediumvioletred: 'c71585',
            midnightblue: '191970',
            mintcream: 'f5fffa',
            mistyrose: 'ffe4e1',
            moccasin: 'ffe4b5',
            navajowhite: 'ffdead',
            navy: '000080',
            oldlace: 'fdf5e6',
            olive: '808000',
            olivedrab: '6b8e23',
            orange: 'ffa500',
            orangered: 'ff4500',
            orchid: 'da70d6',
            palegoldenrod: 'eee8aa',
            palegreen: '98fb98',
            paleturquoise: 'afeeee',
            palevioletred: 'd87093',
            papayawhip: 'ffefd5',
            peachpuff: 'ffdab9',
            peru: 'cd853f',
            pink: 'ffc0cb',
            plum: 'dda0dd',
            powderblue: 'b0e0e6',
            purple: '800080',
            red: 'ff0000',
            rosybrown: 'bc8f8f',
            royalblue: '4169e1',
            saddlebrown: '8b4513',
            salmon: 'fa8072',
            sandybrown: 'f4a460',
            seagreen: '2e8b57',
            seashell: 'fff5ee',
            sienna: 'a0522d',
            silver: 'c0c0c0',
            skyblue: '87ceeb',
            slateblue: '6a5acd',
            slategray: '708090',
            snow: 'fffafa',
            springgreen: '00ff7f',
            steelblue: '4682b4',
            tan: 'd2b48c',
            teal: '008080',
            thistle: 'd8bfd8',
            tomato: 'ff6347',
            turquoise: '40e0d0',
            violet: 'ee82ee',
            violetred: 'd02090',
            wheat: 'f5deb3',
            white: 'ffffff',
            whitesmoke: 'f5f5f5',
            yellow: 'ffff00',
            yellowgreen: '9acd32'
        };
        for (var key in simple_colors) {
            if (color_string == key) {
                color_string = simple_colors[key];
            }
        }
        // emd of simple type-in colors
    
        // array of color definition objects
        var color_defs = [
            {
                re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
                example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
                process: function (bits){
                    return [
                        parseInt(bits[1]),
                        parseInt(bits[2]),
                        parseInt(bits[3])
                    ];
                }
            },
            {
                re: /^(\w{2})(\w{2})(\w{2})$/,
                example: ['#00ff00', '336699'],
                process: function (bits){
                    return [
                        parseInt(bits[1], 16),
                        parseInt(bits[2], 16),
                        parseInt(bits[3], 16)
                    ];
                }
            },
            {
                re: /^(\w{1})(\w{1})(\w{1})$/,
                example: ['#fb0', 'f0f'],
                process: function (bits){
                    return [
                        parseInt(bits[1] + bits[1], 16),
                        parseInt(bits[2] + bits[2], 16),
                        parseInt(bits[3] + bits[3], 16)
                    ];
                }
            }
        ];
    
        // search through the definitions to find a match
        for (var i = 0; i < color_defs.length; i++) {
            var re = color_defs[i].re;
            var processor = color_defs[i].process;
            var bits = re.exec(color_string);
            if (bits) {
                channels = processor(bits);
                this.r = channels[0];
                this.g = channels[1];
                this.b = channels[2];
                this.ok = true;
            }
    
        }
    
        // validate/cleanup values
        this.cleanup = function() {
          this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
          this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
          this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
        };
    
        // some getters
        this.toRGB = function () {
            return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
        };
        
        this.toHex = function () {
            var r = this.r.toString(16);
            var g = this.g.toString(16);
            var b = this.b.toString(16);
            if (r.length == 1) r = '0' + r;
            if (g.length == 1) g = '0' + g;
            if (b.length == 1) b = '0' + b;
            return '#' + r + g + b;
        };
        
        this.emphasize = function () {
          var diff = ((this.r + this.g + this.b) / 3 < 128) ? 30 : -30;
          this.r += diff; this.g += diff; this.b += diff;
          this.cleanup();
        };
    
        // help
        this.getHelpXML = function () {
    
            var examples = new Array();
            // add regexps
            for (var i = 0; i < color_defs.length; i++) {
                var example = color_defs[i].example;
                for (var j = 0; j < example.length; j++) {
                    examples[examples.length] = example[j];
                }
            }
            // add type-in colors
            for (var sc in simple_colors) {
                examples[examples.length] = sc;
            }
    
            var xml = document.createElement('ul');
            xml.setAttribute('id', 'rgbcolor-examples');
            for (var i = 0; i < examples.length; i++) {
                try {
                    var list_item = document.createElement('li');
                    var list_color = new RGBColor(examples[i]);
                    var example_div = document.createElement('div');
                    example_div.style.cssText =
                            'margin: 3px; '
                            + 'border: 1px solid black; '
                            + 'background:' + list_color.toHex() + '; '
                            + 'color:' + list_color.toHex()
                    ;
                    example_div.appendChild(document.createTextNode('test'));
                    var list_item_value = document.createTextNode(
                        ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
                    );
                    list_item.appendChild(example_div);
                    list_item.appendChild(list_item_value);
                    xml.appendChild(list_item);
    
                } catch(e){}
            }
            return xml;
    
        };    
}
    
function WindowBase( urlIn) {
        this.windowName = Math.floor(Math.random()*10000);
	this.baseURL = urlIn;	
        this.url = urlIn + '&windowName=' + this.windowName;
	AdeoElement.call( this);
	AdeoElement.prototype.setAttribute.call( this, 'id', this.windowName);
	AdeoElement.prototype.setAttribute.call( this, 'baseURL', this.baseURL);
	AdeoElement.prototype.setStyle.call( this, 'overflow', 'auto');
	AdeoElement.prototype.setInnerHTML.call( this, 'Loading...');
};

WindowBase.prototype = new AdeoElement();
WindowBase.prototype.constructor = WindowBase;

WindowBase.prototype.refresh = function(){
	if( this.url)
		AdeoElement.prototype.loadUrl.call( this, this.url);
};
WindowBase.prototype.getURL = function(){
	return this.url;
};
WindowBase.prototype.getBaseURL = function(){
	return this.baseURL;
};
WindowBase.prototype.getName = function(){
	return this.windowName;
};
WindowBase.prototype.setElementById = function(id) {
	AdeoElement.prototype.setElementById.call( this, id);
	this.windowName = id;
};
WindowBase.prototype.setWindowName = function( name){
	this.windowName = name;
}
function WindowBaseFooter( name) {

	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'overflow', 'hidden');
	AdeoElement.prototype.setStyle.call( this, 'height', '13px');
	AdeoElement.prototype.setStyle.call( this, 'borderTop', '1px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'backgroundColor', '#ECE9D8');

	this.WinResize = new WindowBaseResize( name);	
	this.add( this.WinResize);
};

WindowBaseFooter.prototype = new AdeoElement();
WindowBaseFooter.prototype.constructor = WindowBaseFooter;

function WindowBaseResize( name){

	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'float', 'right');
	AdeoElement.prototype.setStyle.call( this, 'cursor', 'se-resize');
	AdeoElement.prototype.setStyle.call( this, 'borderLeft', '2px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'width', '14px');
	AdeoElement.prototype.setStyle.call( this, 'height', '14px');
	AdeoElement.prototype.setStyle.call( this, 'backgroundImage', 'url(57.gif)');
	AdeoElement.prototype.addEventListener.call( this, 'mousedown', AdeoResizeWindow);

	this.setAttribute( 'winName', name);
}

WindowBaseResize.prototype = new AdeoElement();
WindowBaseResize.prototype.constructor = WindowBaseResize;

function AdeoResizeWindow() {
	var elem = adeo.element.niGetElementEventTarget( this);
	resizeElem = WinContainer[ elem.getAttribute( 'winName')];
};
function WindowBaseHeader( name) {

	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'overflow', 'hidden');
	AdeoElement.prototype.setStyle.call( this, 'cursor', 'pointer');
	AdeoElement.prototype.setStyle.call( this, 'width', '100%');
	AdeoElement.prototype.setStyle.call( this, 'height', '16px');
	AdeoElement.prototype.setStyle.call( this, 'fontSize', '11px');
	AdeoElement.prototype.setStyle.call( this, 'borderBottom', '2px solid rgb(137,163,241)');
	AdeoElement.prototype.setStyle.call( this, 'backgroundColor', 'rgb(163,183,244)');
	AdeoElement.prototype.addEventListener.call( this, 'mousedown', AdeoMoveWindow);

	this.setAttribute( 'winName', name);

	this.WinClose = new WindowBaseClose( name);
	this.WinMinMax = new WindowBaseMinMax( name);
	this.WinImage = new WindowBaseImage( name);
	this.WinTitle = new AdeoElement();
	// this.WinTitle.setInnerHTML( name + ' title'); 
	this.WinTitle.setStyle( 'float', 'left');
	this.WinTitle.setStyle( 'height', '17px');

        this.add( this.WinClose);    
        this.add( this.WinMinMax); 
        this.add( this.WinImage);  
        this.add( this.WinTitle); 
};

WindowBaseHeader.prototype = new AdeoElement();
WindowBaseHeader.prototype.constructor = WindowBaseHeader;

WindowBaseHeader.prototype.setImage = function( url){
	this.WinImage.setStyle( 'backgroundImage', 'url(' + url + ')');
};

function WindowBaseClose( name){
	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'float', 'right');
	AdeoElement.prototype.setStyle.call( this, 'cursor', 'pointer');
	AdeoElement.prototype.setStyle.call( this, 'width', '17px');
	AdeoElement.prototype.setStyle.call( this, 'height', '17px');
	AdeoElement.prototype.setStyle.call( this, 'backgroundImage', 'url(53.gif)');
	AdeoElement.prototype.setStyle.call( this, 'backgroundRepeat', 'no-repeat');
	AdeoElement.prototype.setStyle.call( this, 'backgroundPosition', 'top left');
	AdeoElement.prototype.addEventListener.call( this, 'click', AdeoCloseWindow);

	this.setAttribute( 'winName', name);
};

WindowBaseClose.prototype = new AdeoElement();
WindowBaseClose.prototype.constructor = WindowBaseClose;

function WindowBaseMinMax( name){
	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'float', 'right');
	AdeoElement.prototype.setStyle.call( this, 'cursor', 'pointer');
	AdeoElement.prototype.setStyle.call( this, 'width', '17px');
	AdeoElement.prototype.setStyle.call( this, 'height', '17px');
	AdeoElement.prototype.setStyle.call( this, 'marginRight', '2px');
	AdeoElement.prototype.setStyle.call( this, 'backgroundImage', 'url(54.gif)');
	AdeoElement.prototype.setStyle.call( this, 'backgroundRepeat', 'no-repeat');
	AdeoElement.prototype.setStyle.call( this, 'backgroundPosition', 'top left');
	AdeoElement.prototype.addEventListener.call( this, 'click', AdeoMinMaxWindow);

	this.setAttribute( 'winName', name);
};

WindowBaseMinMax.prototype = new AdeoElement();
WindowBaseMinMax.prototype.constructor = WindowBaseMinMax;
 
function WindowBaseImage( name){
	AdeoElement.call( this);
	AdeoElement.prototype.setStyle.call( this, 'float', 'left');
	AdeoElement.prototype.setStyle.call( this, 'cursor', 'pointer');
	AdeoElement.prototype.setStyle.call( this, 'width', '17px');
	AdeoElement.prototype.setStyle.call( this, 'height', '17px');
	AdeoElement.prototype.setStyle.call( this, 'backgroundImage', 'url(55.gif)');
	AdeoElement.prototype.setStyle.call( this, 'backgroundRepeat', 'no-repeat');
	AdeoElement.prototype.setStyle.call( this, 'backgroundPosition', 'top left');

	this.setAttribute( 'winName', name);
};

WindowBaseImage.prototype = new AdeoElement();
WindowBaseImage.prototype.constructor = WindowBaseImage;

function AdeoMoveWindow() {
	var elem = adeo.element.niGetElementEventTarget( this);
	dragElem = WinContainer[ elem.getAttribute( 'winName')];
		
	if( dragElem){
		dragElem.Attributes.put( 'offsetY', tempY - parseInt(dragElem.getStyle('top')));
		dragElem.Attributes.put( 'offsetX', tempX - parseInt(dragElem.getStyle('left')));
	}
	
};

function AdeoCloseWindow() {
	var elem = adeo.element.niGetElementEventTarget( this);
	win = WinContainer[ elem.getAttribute( 'winName')];
	
	if( win)
		win.close();
	
};


function AdeoMinMaxWindow() {
	var elem = adeo.element.niGetElementEventTarget( this);
	win = WinContainer[ elem.getAttribute( 'winName')];
		
	if( win)
		win.maximizeORminimize();
};
function WindowMain( urlIn){
	this.WinContent = new WindowBase( urlIn);
	this.WinHeader = new WindowBaseHeader( this.getName());
	this.WinFooter = new WindowBaseFooter( this.getName());
	AdeoElement.call( this);
	AdeoElement.prototype.setAttribute.call( this, 'id', this.getName()  + 'Window');
	this.setAttribute( 'winName', this.getName());
	this.history = new Array();
	this.currentStep = 0;

//        this.iFrameHelper = new AdeoElement( 'iframe');
//        this.iFrameHelper.setAttribute( 'id', this.getName() + 'FrameHelper');        
//        this.iFrameHelper.setAttribute( 'frameborder', '0');
};

WindowMain.prototype = new AdeoElement();
WindowMain.prototype.constructor = WindowMain;

WindowMain.prototype.setWinStyle = function(){	
        /** Window style **/
	AdeoElement.prototype.setStyle.call( this, 'borderTop', '2px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderLeft', '2px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderBottom', '3px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderRight', '3px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'backgroundColor', '#EFEFEF');

	AdeoElement.prototype.addEventListener.call( this, 'mousedown', InFrontWin);
	AdeoElement.prototype.addEventListener.call( this, 'mouseup', MouseUpMoveWin);
};
WindowMain.prototype.setWindowName = function( windowName) {
	this.WinContent.windowName = windowName;
	this.setAttribute( 'winName', this.getName());
	this.setAttribute( 'id', this.getName()  + 'Window');
	this.WinHeader.setAttribute( 'id', this.getName() + 'Header');
	this.WinFooter.setAttribute( 'id', this.getName() + 'Footer');
}
WindowMain.prototype.loadAndExecute = function( jsFja, adeoArgs){
	this.WinContent.loadAndExecute( jsFja, adeoArgs);
};
WindowMain.prototype.loadAndEval = function( jsCode){
	this.WinContent.loadAndEval( jsCode);
};
WindowMain.prototype.refresh = function(){
	this.WinContent.refresh();
};
WindowMain.prototype.getURL = function(){
	return this.WinContent.getURL();
};
WindowMain.prototype.getBaseURL = function(){
	return this.WinContent.getBaseURL();
};
WindowMain.prototype.getName = function(){
	return this.WinContent.windowName;
};
WindowMain.prototype.setTitle = function( title){
	this.WinHeader.WinTitle.setInnerHTML( title); 
};
WindowMain.prototype.setHeader = function( header){
	if( header)
		this.WinHeader.copyElementFrom( new AdeoElement( header));
        this.WinHeader.setAttribute( 'id', this.getName() + 'Header');
        this.add( this.WinHeader);
};
WindowMain.prototype.setContent = function( content){ 
	if( content)
		this.WinContent.copyElementFrom( new AdeoElement( content));  
        this.add( this.WinContent);
	this.history[ this.currentStep] = this.WinContent;
	this.currentStep++;
};
WindowMain.prototype.fillContent = function( content){ 
	if( content)
		this.WinContent.copyElementFrom( new AdeoElement( content));  
        this.fillWith( this.WinContent);
	this.history[ this.currentStep] = this.WinContent;
	this.currentStep++;
};
WindowMain.prototype.back = function(){
	if( this.currentStep - 2 >= 0 && this.history[ this.currentStep - 2]){
		this.fillWith( this.history[ this.currentStep - 2]);
		this.currentStep--;
	}
};
WindowMain.prototype.forward = function(){
	if( this.currentStep >= 0 && this.history[ this.currentStep]){
		this.fillWith( this.history[ this.currentStep]);
		this.currentStep++;
	}
};
WindowMain.prototype.setFooter = function( footer){   
	if( footer)
		this.WinFooter.copyElementFrom( new AdeoElement( footer));         
        this.WinFooter.setAttribute( 'id', this.getName() + 'Footer');
        this.add( this.WinFooter);
};
WindowMain.prototype.show = function( x, y) {
	this.displayAbsolute( x, y);
//        this.iFrameHelper.displayAbsolute( x, y);
//	this.iFrameHelper.displayInFront();
	this.displayInFront();
	this.open();
};
WindowMain.prototype.open = function() {
        this.display();
//        this.iFrameHelper.display();
};        
WindowMain.prototype.close = function() {
        this.hide();
//        this.iFrameHelper.hide();
};
WindowMain.prototype.maximizeORminimize = function( ){
	if( this.WinContent.getStyle( 'display') == 'block' || this.WinContent.getStyle( 'display') == '')
		this.minimize();
	else
		this.maximize();
};
WindowMain.prototype.maximize = function( ){
	this.WinHeader.WinMinMax.setStyle( 'backgroundImage', 'url(54.gif)');
	this.WinContent.setStyle( 'display', 'block');
	this.WinFooter.setStyle( 'display', 'block');
        this.WinHeader.WinClose.setStyle( 'display', 'block');  
        
        this.setStyle( 'position', 'absolute');                        

	var w = parseInt( this.Attributes.get( 'tmpW'));
	var h = parseInt( this.Attributes.get( 'tmpH'));
	this.setSize( w, h);
};
WindowMain.prototype.minimize = function( ){
	this.WinHeader.WinMinMax.setStyle( 'backgroundImage', 'url(56.gif)');
	this.WinContent.setStyle( 'display', 'none');
	this.WinFooter.setStyle( 'display', 'none');
        this.WinHeader.WinClose.setStyle( 'display', 'none');   

        this.setStyle( 'position', 'static');
        this.setStyle( 'float', 'left');   
	this.Attributes.put( 'tmpH', this.getStyle( 'height'));
	this.Attributes.put( 'tmpW', this.getStyle( 'width'));
        this.setStyle( 'height', '17px');   
        this.setStyle( 'width', '100px');   

//	if( this.iFrameHelper){
//		if(BrowserDetect.browser == 'Explorer'){
//			this.iFrameHelper.setStyle( 'height', '19px');
//			this.iFrameHelper.setStyle( 'width', '100px');
//		}else{
//			this.iFrameHelper.setStyle( 'height', '21px');
//			this.iFrameHelper.setStyle( 'width', '104px');
//		}
//	}    
};
WindowMain.prototype.setSize = function( w, h){                
        this.setWidth( w ? w : 500);
	this.setHeight( h ? h : 400);
};
WindowMain.prototype.setWidth = function( w){
	var width = w;
	if(!w) width = 400;

	this.setStyle('width', width);
	this.Attributes.put( 'tmpW', width);
	if(BrowserDetect.browser == 'Explorer')
		this.WinContent.setStyle( 'width', width - 4);
	else
		this.WinContent.setStyle( 'width', width);
//        if( this.iFrameHelper != null){
//		if(BrowserDetect.browser == 'Explorer')
//			this.iFrameHelper.setAttribute( 'width', (width + 1)+'px');
//		    else
//			this.iFrameHelper.setAttribute( 'width', (width + 5)+'px');
//	}
};
WindowMain.prototype.setHeight = function( h){
	var height = h; 
	if(!h) height = 250;

	this.setStyle('height', height);
	this.Attributes.put( 'tmpH', height);
	this.WinContent.setStyle( 'height', height - parseInt( this.WinHeader.getStyle( 'height')) - parseInt( this.WinFooter.getStyle( 'height')) - 3);
//	if( this.iFrameHelper != null){
//		if(BrowserDetect.browser == 'Explorer')
//			this.iFrameHelper.setAttribute( 'height', (height + 1)+'px');
//		else
//			this.iFrameHelper.setAttribute( 'height', (height + 5)+'px');
//	}
};
WindowMain.prototype.resize = function( w, h){
	if( BrowserDetect.browser == 'Explorer' && toolbarHeight)
			h -= parseInt( toolbarHeight);
	if( h>50)
		this.setHeight( h);
	if( w>100)
		this.setWidth( w);
};
WindowMain.prototype.moveTo = function( top, left){
	this.setPosition( top, left);
//	if( this.iFrameHelper ){        
//		this.iFrameHelper.setPosition( top, left);
//	}
};
WindowMain.prototype.move = function(){
	this.moveTo( tempY - parseInt(this.Attributes.get( 'offsetY')), tempX - parseInt(this.Attributes.get( 'offsetX')));
};

function InFrontWin( el) {
	var elem = adeo.element.niGetElementEventTarget( this);
	win = WinContainer[ elem.getAttribute( 'winName')];
		
	if( win)
		win.maximizeORminimize();
};

function MouseUpMoveWin() {
	dragElem = null;  
        resizeElem = null;
};
function WindowContainer(){
	AdeoContainer.call( this, 'WindowContainerJS');
};

WindowContainer.prototype = new AdeoContainer();
WindowContainer.prototype.constructor = WindowContainer;

WindowContainer.prototype.open = function( winParams){
	if(winParams.WindowType == WindowType.Browser){
		return this.openBrowserWindow(winParams);
	}
	var win = this.getWindow( winParams);
	if( !win)
		return false;
	win.openWindow( winParams);
	return win;
};
WindowContainer.prototype.getWindow = function( winParams){
	var win = null;
	if( winParams.name && WinContainer[ winParams.name]){
		win = WinContainer[ winParams.name];
	}else if( winParams.target && WinContainer[ winParams.target]){	
		win = WinContainer[ winParams.target];
	}else{
		win = new AdeoWindow( winParams.target);
		if( winParams.name)
			win.rename( winParams.name)
		WinContainer[ win.windowName] = win;
		if( !winParams.target)		
			this.add( win);
	}
	return win;
}; 
WindowContainer.prototype.openBrowserWindow = function( winParams){
	var myForm = new AdeoElement('form');
	myForm.hide();
	document.body.appendChild(myForm.Element);
	myForm.Element.name = myForm.id;
	winParams.formElements.setToForm( myForm);
	myForm.Element.method = winParams.method;
	myForm.Element.target = winParams.target;
	if( winParams.features)
		window.open("about:blank", winParams.target, winParams.features);
	else
		window.open("about:blank", winParams.target);
	myForm.Element.action = winParams.action;
	myForm.Element.submit();
};
WindowContainer.prototype.openNewWindow = function( urlIN, xIN, yIN, wIN, hIN, afterAjaxLoadFunctionsIN, cssClassIN) {	
	return this.open( { type: WindowType.New, style: true, header: true, footer: true, url: urlIN, x: xIN, y: yIN, w: wIN, h: hIN, clbckFunctions: afterAjaxLoadFunctionsIN, cssClass: cssClassIN});
};  
WindowContainer.prototype.openBlankWindow = function( nameIN, xIN, yIN, wIN, hIN, cssClassIN) {
	return this.open( { type: WindowType.Blank, style: true, header: true, footer: true, name: nameIN, x: xIN, y: yIN, w: wIN, h: hIN, cssClass: cssClassIN});
};  
WindowContainer.prototype.openWindow = function( urlIN, xIN, yIN, wIN, hIN, afterAjaxLoadFunctionsIN, cssClassIN) {	
	return this.open( { type: WindowType.Window, style: true, header: true, footer: true, url: urlIN, x: xIN, y: yIN, w: wIN, h: hIN, clbckFunctions: afterAjaxLoadFunctionsIN, cssClass: cssClassIN});
};   
WindowContainer.prototype.openInlineWindow = function(  urlIN, targetIN, afterAjaxLoadFunctionsIN, cssClassIN, existingWinNameIN) {
	return this.open( { type: WindowType.Inline, url: urlIN, target: targetIN, name: existingWinNameIN, jsCode: afterAjaxLoadFunctionsIN, cssClass: cssClassIN});
};   
WindowContainer.prototype.displayWindowContent = function( urlIN, targetIN, wIN, hIN, afterAjaxLoadFunctionsIN, cssClassIN, existingWinNameIN) {
	return this.open( { type: WindowType.Inline, url: urlIN, w: wIN, h:hIN, target: targetIN, name: existingWinNameIN, jsCode: afterAjaxLoadFunctionsIN, cssClass: cssClassIN});
};   
WindowContainer.prototype.appendWindowContent = function( urlIN, targetIN, wIN, hIN, afterAjaxLoadFunctionsIN, cssClassIN) {
	return this.open( { type: WindowType.Inline, url: urlIN, w: wIN, h:hIN, target: targetIN, jsCode: afterAjaxLoadFunctionsIN, cssClass: cssClassIN});
};   
WindowContainer.prototype.registerWindowContent = function( urlIN, targetIN) {
	return this.open( {url: urlIN, target: targetIN, register: true});
};   
WindowContainer.prototype.back = function( winName){
	if( WinContainer[ winName])
		WinContainer[ winName].back();
};
WindowContainer.prototype.forward = function( winName){	
	if( WinContainer[ winName])
		WinContainer[ winName].forward();
};
WindowContainer.prototype.refreshWindow = function( winName) {
        if( WinContainer[ winName])
		WinContainer[ winName].refresh();
};
WindowContainer.prototype.closeWindow = function( winName) {	
        if( WinContainer[ winName])
		WinContainer[ winName].close();
};

ContentContainer = new Array();
WinContainer = new Array();

function WindowParams( type, url, target, name){
	this.type = type;
	this.url = url;
	this.target = target;
	this.name = name;
	this.old = false;
};
WindowParams.prototype.display = function( header, footer, style, cssClass){
	this.header = header;
	this.footer = footer;
	this.style = style;
	this.cssClass = cssClass;
};
WindowParams.prototype.posdim = function( x, y, w, h){
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
};
WindowParams.prototype.operation = function( jsCode, clbckFunc, clbckParams, register){
	this.jsCode = jsCode;
	this.clbckFunc = clbckFunc;
	this.clbckParams = clbckParams;
	this.register = register;
};
WindowParams.prototype.content = function( cont){
	this.cont = cont;
}
WindowType = { 
	Window: 0,
	New: 1,
	Blank: 2,
	Inline: 3,
	Browser: 4
};

var windowContainer = new WindowContainer();
function AdeoWindow( nameIn){       
	if( nameIn){
        	this.windowName = nameIn;
        	if( document.getElementById( nameIn))
			AdeoElement.call( this, nameIn); 
		else
			AdeoElement.call( this); 
	}else{
        	this.windowName = Math.floor(Math.random()*10000);
		AdeoElement.call( this); 
        }
        this.windowID = this.windowName  + 'Window';
	AdeoElement.prototype.setAttribute.call( this, 'id', this.windowID);
	this.setAttribute( 'winName', this.windowName);
	this.WinContent = new AdeoElement();
	this.WinContent.setAttribute( 'id', this.windowName);
	this.WinContent.setStyle( 'overflow', 'auto');
	this.WinFooter = new WindowBaseFooter( this.windowName);
	this.WinHeader = new WindowBaseHeader( this.windowName);
	this.CurrentContent;
	this.history = new Array();
	this.currentStep = 0;
        
//        this.iFrameHelper = new AdeoElement( 'iframe');
//        this.iFrameHelper.setAttribute( 'id', this.getName() + 'FrameHelper');        
//        this.iFrameHelper.setAttribute( 'frameborder', '0');
};

AdeoWindow.prototype = new AdeoElement();
AdeoWindow.prototype.constructor = AdeoWindow;


AdeoWindow.prototype.openWindow = function( winParams) {
	this.baseURL = winParams.url;	
        this.url = winParams.url + '&windowName=' + this.windowName;
        this.jsCode = winParams.jsCode;
        this.clbckFunc = winParams.clbckFunc;
        this.clbckParams = winParams.clbckParams;
        
	if( winParams.register){
        	winParams.cont = new AdeoElement();
        	winParams.cont.setInnerHTML( this.getInnerHTML());
		this.empty();
	}
		
        if( !winParams.old){
        	if( winParams.style)
		        this.setWinStyle();
        	if( winParams.header)
		        this.setHeader();
		       
		this.setContent( winParams.cont);
		
        	if( winParams.footer)
		        this.setFooter();    
	        if( winParams.cssClass)
			this.WinContent.setClass( winParams.cssClass);
	}
	if( !winParams.target){
        	this.setSize( winParams.w, winParams.h);
        	this.show( winParams.x, winParams.y);
        }
};
AdeoWindow.prototype.rename = function( newName){
        this.windowName = newName;        
        this.windowID = this.windowName  + 'Window';
	this.setAttribute('id', this.windowID);
	this.setAttribute( 'winName', this.windowName);
	this.WinContent.setAttribute( 'id', this.windowName);
	this.WinFooter.WinResize.setAttribute( 'winName', this.windowName);
	this.WinHeader.setAttribute( 'winName', this.windowName);
	this.WinHeader.WinClose.setAttribute( 'winName', this.windowName);
	this.WinHeader.WinMinMax.setAttribute( 'winName', this.windowName);
	this.WinHeader.WinImage.setAttribute( 'winName', this.windowName);
};
AdeoWindow.prototype.setWinStyle = function(){	
        /** Window style **/
	AdeoElement.prototype.setStyle.call( this, 'borderTop', '2px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderLeft', '2px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderBottom', '3px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'borderRight', '3px solid #7B9ABB');
	AdeoElement.prototype.setStyle.call( this, 'backgroundColor', '#EFEFEF');

	AdeoElement.prototype.addEventListener.call( this, 'mousedown', InFrontWin);
	AdeoElement.prototype.addEventListener.call( this, 'mouseup', MouseUpMoveWin);
};
AdeoWindow.prototype.refresh = function(){
	if( this.baseURL){
		newWinCont = new AdeoElement();
		newWinCont.Element.innerHTML = 'Loading...';
		this.WinContent.fillWith( newWinCont);
		ContentContainer[ this.baseURL] = newWinCont;
		if( this.jsCode){
			newWinCont.setAttribute( 'jsCallback', this.jsCode);
		}else if( this.clbckFunc){
			newWinCont.setAttribute( 'jsFja', this.clbckFunc);
			newWinCont.setAttribute( 'params', this.clbckParams);
		}
		AdeoAjax.prototype.loadUrlTo.call( this, this.url, newWinCont.Element);
	}
};
AdeoWindow.prototype.getURL = function(){
	return this.getURL();
};
AdeoWindow.prototype.getBaseURL = function(){
	return this.getBaseURL();
};
AdeoWindow.prototype.getName = function(){
	return this.windowName;
};
AdeoWindow.prototype.setTitle = function( title){
	this.WinHeader.WinTitle.setInnerHTML( title); 
};
AdeoWindow.prototype.setHeader = function(){	
        this.add( this.WinHeader);
};
AdeoWindow.prototype.setFooter = function(){   
        this.add( this.WinFooter);
};
AdeoWindow.prototype.setContent = function( content){ 
	var newWinCont;
	if( content)
		newWinCont = content;
	else
		newWinCont = ContentContainer[ this.baseURL]; 	
			
	if( newWinCont){
		this.WinContent.fillWith( newWinCont);
	}else if( this.baseURL){
		newWinCont = new AdeoElement();
		newWinCont.Element.innerHTML = 'Loading...';
		this.WinContent.fillWith( newWinCont);
		ContentContainer[ this.baseURL] = newWinCont;
		if( this.jsCode){
			newWinCont.setAttribute( 'jsCallback', this.jsCode);
		}else if( this.clbckFunc){
			newWinCont.setAttribute( 'jsFja', this.clbckFunc);
			newWinCont.setAttribute( 'params', this.clbckParams);
		}
		AdeoAjax.prototype.loadUrlTo.call( this, this.url, newWinCont.Element);
	}
        this.add( this.WinContent);
        this.history[ this.currentStep] = newWinCont;
	this.currentStep++;
};
AdeoWindow.prototype.back = function(){
	if( this.currentStep - 2 >= 0 && this.history[ this.currentStep - 2]){
		this.WinContent.fillWith( this.history[ this.currentStep - 2]);
		this.currentStep--;
	}
};
AdeoWindow.prototype.forward = function(){
	if( this.currentStep >= 0 && this.history[ this.currentStep]){
		this.WinContent.fillWith( this.history[ this.currentStep]);
		this.currentStep++;
	}
};
AdeoWindow.prototype.show = function( x, y) {
	this.displayAbsolute( x, y);
//      this.iFrameHelper.displayAbsolute( x, y);
//	this.iFrameHelper.displayInFront();
	this.displayInFront();
	this.open();
};
AdeoWindow.prototype.open = function() {
        this.display();
//      this.iFrameHelper.display();
};        
AdeoWindow.prototype.close = function() {
        this.hide();
//      this.iFrameHelper.hide();
};
AdeoWindow.prototype.maximizeORminimize = function( ){
	if( this.WinContent.getStyle( 'display') == 'block' || this.WinContent.getStyle( 'display') == '')
		this.minimize();
	else
		this.maximize();
};
AdeoWindow.prototype.maximize = function( ){
	this.WinHeader.WinMinMax.setStyle( 'backgroundImage', 'url(54.gif)');
	this.WinContent.setStyle( 'display', 'block');
	this.WinFooter.setStyle( 'display', 'block');
        this.WinHeader.WinClose.setStyle( 'display', 'block');  
        
        this.setStyle( 'position', 'absolute');                        

	var w = parseInt( this.Attributes.get( 'tmpW'));
	var h = parseInt( this.Attributes.get( 'tmpH'));
	this.setSize( w, h);
};
AdeoWindow.prototype.minimize = function( ){
	this.WinHeader.WinMinMax.setStyle( 'backgroundImage', 'url(56.gif)');
	this.WinContent.setStyle( 'display', 'none');
	this.WinFooter.setStyle( 'display', 'none');
        this.WinHeader.WinClose.setStyle( 'display', 'none');   

        this.setStyle( 'position', 'static');
        this.setStyle( 'float', 'left');   
	this.Attributes.put( 'tmpH', this.getStyle( 'height'));
	this.Attributes.put( 'tmpW', this.getStyle( 'width'));
        this.setStyle( 'height', '17px');   
        this.setStyle( 'width', '100px');   

//	if( this.iFrameHelper){
//		if(BrowserDetect.browser == 'Explorer'){
//			this.iFrameHelper.setStyle( 'height', '19px');
//			this.iFrameHelper.setStyle( 'width', '100px');
//		}else{
//			this.iFrameHelper.setStyle( 'height', '21px');
//			this.iFrameHelper.setStyle( 'width', '104px');
//		}
//	}    
};
AdeoWindow.prototype.setSize = function( w, h){                
        this.setWidth( w ? w : 500);
	this.setHeight( h ? h : 400);
};
AdeoWindow.prototype.setWidth = function( w){
	var width = w;
	if(!w) width = 400;

	this.setStyle('width', width);
	this.Attributes.put( 'tmpW', width);
	if(BrowserDetect.browser == 'Explorer')
		this.WinContent.setStyle( 'width', width - 4);
	else
		this.WinContent.setStyle( 'width', width);
//        if( this.iFrameHelper != null){
//		if(BrowserDetect.browser == 'Explorer')
//			this.iFrameHelper.setAttribute( 'width', (width + 1)+'px');
//		    else
//			this.iFrameHelper.setAttribute( 'width', (width + 5)+'px');
//	}
};
AdeoWindow.prototype.setHeight = function( h){
	var height = h; 
	if(!h) height = 250;

	this.setStyle('height', height);
	this.Attributes.put( 'tmpH', height);
	this.WinContent.setStyle( 'height', height - parseInt( this.WinHeader.getStyle( 'height')) - parseInt( this.WinFooter.getStyle( 'height')) - 3);
//	if( this.iFrameHelper != null){
//		if(BrowserDetect.browser == 'Explorer')
//			this.iFrameHelper.setAttribute( 'height', (height + 1)+'px');
//		else
//			this.iFrameHelper.setAttribute( 'height', (height + 5)+'px');
//	}
};
AdeoWindow.prototype.resize = function( w, h){
	if( BrowserDetect.browser == 'Explorer' && toolbarHeight)
			h -= parseInt( toolbarHeight);
	if( h>50)
		this.setHeight( h);
	if( w>100)
		this.setWidth( w);
};
AdeoWindow.prototype.moveTo = function( top, left){
	this.setPosition( top, left);
//	if( this.iFrameHelper ){        
//		this.iFrameHelper.setPosition( top, left);
//	}
};
AdeoWindow.prototype.move = function(){
	this.moveTo( tempY - parseInt(this.Attributes.get( 'offsetY')), tempX - parseInt(this.Attributes.get( 'offsetX')));
};

function InFrontWin( el) {
	var elem = adeo.element.niGetElementEventTarget( this);
	var win = WinContainer[ elem.getAttribute( 'winName')];
	if( win)
		win.displayInFront();
};

function MouseUpMoveWin() {
	dragElem = null;  
        resizeElem = null;
};
function AdeoImageEditor( prefix){
	AdeoElement.call( this);
	this.selectedImage = null;
}
AdeoImageEditor.prototype = new AdeoElement();
AdeoImageEditor.prototype.constructor = AdeoImageEditor;



AdeoImageEditor.prototype.checkSelection = function( elem){
	this.selectedImage = null;
	var tmpElem = elem;
	while( AdeoElementType.getType( tmpElem) != AdeoElementType.BODY){
		if( AdeoElementType.getType( tmpElem) == AdeoElementType.IMG){
			this.selectedImage = new AdeoElement( tmpElem);
		}
		tmpElem = tmpElem.parentNode;
	}
};
function AdeoTableEditor(){
	AdeoTable.call( this);
}
AdeoTableEditor.prototype = new AdeoTable();
AdeoTableEditor.prototype.constructor = AdeoTableEditor;

AdeoTableEditor.prototype.checkSelection = function( ){
	var tmpElem = oSel.getSelectionElement();
	while( AdeoElementType.getType( tmpElem) != AdeoElementType.BODY){
		if( AdeoElementType.getType( tmpElem) == AdeoElementType.TD){
			this.selectedCell = new AdeoElement( 'td', tmpElem.id);
		}else if( AdeoElementType.getType( tmpElem) == AdeoElementType.TR){
			this.selectedRow = new AdeoElement( 'tr', tmpElem.id);
		}else if( AdeoElementType.getType( tmpElem) == AdeoElementType.TABLE){
			this.setElement( tmpElem);
		}
		tmpElem = tmpElem.parentNode;
	}
};

AdeoTableEditor.prototype.createTable = function( prefix) {
	var rows = parseInt( document.getElementById('rows' + prefix).value);
	var cols = parseInt( document.getElementById('cols' + prefix).value);
	if(!rows){
		reportErr('Rows must be number');
	}else if(!cols){
		reportErr('Cols must be number');
	}else{
		var newTable = new AdeoTable( rows, cols);
		newTable.getValuesFrom( prefix);
		oSel.adeoEdit('InsertHtml', null, newTable.toHTML() );
	}	
}


function AdeoDatePicker( onClickDay, params){
	AdeoCalendar.call( this);

        this.datePicker = new AdeoTable();
        this.datePicker.setStyle( 'textAlign', 'center');
        this.datePicker.setStyle( 'border', '0');
	this.Name = this.datePicker.id + 'DatePicker';

	if( onClickDay)
		this.ONCLICK = onClickDay;
	else
		this.ONCLICK = NIJS.Adeo.Date.Picker.onDayClickForm;
	this.PARAMS = params;

        this.monthYearTR;
	this.daysInWeekTR;
	this.daysInMonthTR;
	this.todaysDateTR;
}

AdeoDatePicker.prototype = new AdeoCalendar();
AdeoDatePicker.prototype.constructor = AdeoDatePicker;

AdeoDatePicker.prototype.getDatePicker = function(){
	this.monthYearTR = this.datePicker.addRowEnd();
        this.monthYearTR.style.border = '0';
	this.monthYearRowRefresh();

        this.daysInWeekTR = this.datePicker.addRowEnd();
        this.daysInWeekTR.style.border = '0';
	this.printDaysInWeekCells();

        this.daysInMonthTR = this.datePicker.addRowEnd();
        this.daysInMonthTR.style.border = '0';
	this.daysInMonthRowRefresh();

        this.todaysDateTR = this.datePicker.addRowEnd();
        this.todaysDateTR.style.border = '0';
	this.todaysDateRowRefresh();

	return this.datePicker.Element;
};
AdeoDatePicker.prototype.refresh = function(){
	this.monthYearRowRefresh();
	this.printDaysInWeekCells();
	this.daysInMonthRowRefresh();
	this.todaysDateRowRefresh();
};
AdeoDatePicker.prototype.printDaysInWeekCells = function(){	
	var cell = document.createElement('td');

	if( this.daysInWeekTR){
		while( this.daysInWeekTR.firstChild)
			this.daysInWeekTR.removeChild( this.daysInWeekTR.firstChild);
		//this.daysInWeekTR.innerHTML = "";
		this.daysInWeekTR.appendChild( cell);
	}
        cell.style.borderTop = '1px solid rgb(163, 183, 244)';
        for( var j=0; j<7; j++){
		var head = new AdeoElement();
		head.setSize( '25px', '15px');
		head.setStyle( 'lineHeight', '15px');
		head.setStyle( 'fontSize', '10px');
		head.setStyle( 'float', 'left');
		head.setInnerHTML( AdeoGlobal.Date.Day.HR[ j ]);
		cell.appendChild( head.Element);
        }
};
AdeoDatePicker.prototype.monthYearRowRefresh = function(){
	var cell = document.createElement('td');
	
	if( this.monthYearTR){
		while( this.monthYearTR.firstChild)
			this.monthYearTR.removeChild( this.monthYearTR.firstChild);
		//this.monthYearTR.innerHTML = "";
		this.monthYearTR.appendChild( cell);
	}

        cell.appendChild( this.yearForPrint());
        cell.appendChild( this.monthForPrint());
};
AdeoDatePicker.prototype.daysInMonthRowRefresh = function(){
	var tmpCell = document.createElement( 'td');

	if( this.daysInMonthTR){
		while( this.daysInMonthTR.firstChild)
			this.daysInMonthTR.removeChild( this.daysInMonthTR.firstChild);
		//this.daysInMonthTR.innerHTML = "";
		this.daysInMonthTR.appendChild( tmpCell);
	}

        tmpCell.style.textAlign = 'center';
        tmpCell.style.borderTop = '1px solid rgb(163, 183, 244)';
	tmpCell.appendChild( this.daysInMonthTable());
};
AdeoDatePicker.prototype.todaysDateRowRefresh = function(){
	var todaysDate = document.createElement( 'td');
        todaysDate.style.textAlign = 'center';
        todaysDate.style.borderTop = '1px solid rgb(163, 183, 244)';
        todaysDate.innerHTML = this.getDateStrWithDOW();        
	
	if( this.todaysDateTR){
		while( this.todaysDateTR.firstChild)
			this.todaysDateTR.removeChild( this.todaysDateTR.firstChild);
		//this.todaysDateTR.innerHTML = "";
		this.todaysDateTR.appendChild( todaysDate);
	}
};
AdeoDatePicker.prototype.daysInMonthTable = function(){
        var daysInMonth = new AdeoTable();
        daysInMonth.setProperty( 'backgroundColor', 'whitesmoke');          
         
        var dateHelp = new AdeoCalendar( this);
	dateHelp.gotoStartMonth();

        while( dateHelp.getMonth() == this.getMonth()){
            var daysInWeek = daysInMonth.addRowEnd(); 
		daysInWeek.style.border = '0';
       
            for(var i=0; i<7; i++){
                var day = document.createElement('td');
		day.setAttribute( 'params', this.PARAMS);
		day.setAttribute( 'onClickDay', this.ONCLICK);
		day.setAttribute( 'myName', this.Name);
                day.setAttribute('date', dateHelp.currentDate() + '.' + dateHelp.currentMonth() + '.' + dateHelp.currentYear() );
                day.style.width = '24px';

		if( this.todaysDate() == dateHelp.currentDate() && dateHelp.currentDay() == i && dateHelp.getMonth() == this.todaysMonth())
			day.style.backgroundColor = '#aabbcc';

                if( dateHelp.currentDay() == i && dateHelp.getMonth() == this.getMonth()){
			day.innerHTML = dateHelp.currentDate();
			day.style.cursor = 'pointer';
			day.style.fontSize = '13px';
			adeo.element.niAddEventListener( day, 'click', NIJS.Adeo.Date.Picker.update);
			dateHelp.dayForward();
                }else{
			day.innerHTML = '&nbsp;';
		}
                    
                daysInWeek.appendChild( day);
            }
        }
	return daysInMonth.Element;
};  
AdeoDatePicker.prototype.monthForPrint = function(){
	var cont = new AdeoElement();

	var leftArrow = new AdeoElement();
	leftArrow.setSize( '15px', '16px'); 
	leftArrow.setStyle( 'cursor', 'pointer'); 
	leftArrow.setStyle( 'float', 'left'); 
	leftArrow.setStyle( 'backgroundImage', "url('58.gif')"); 
	leftArrow.setAttribute( 'myName', this.Name);
	leftArrow.addEventListener( 'click', NIJS.Adeo.Date.Picker.monthBackward);

	var rightArrow = new AdeoElement();
	rightArrow.setSize( '15px', '16px'); 
	rightArrow.setStyle( 'cursor', 'pointer'); 
	rightArrow.setStyle( 'float', 'left'); 
	rightArrow.setStyle( 'backgroundImage', "url('59.gif')"); 
	rightArrow.setAttribute( 'myName', this.Name);
	rightArrow.addEventListener( 'click', NIJS.Adeo.Date.Picker.monthForward);

	var month = new AdeoElement();
	month.setSize( '74px', '16px'); 
	month.setStyle( 'lineHeight', '16px'); 
	month.setStyle( 'float', 'left'); 
	month.setStyle( 'textAlign', 'center'); 	
	month.setInnerHTML( AdeoGlobal.Date.Month.HR[this.currentMonth()]);
	
	cont.add( leftArrow);
	cont.add( month);
	cont.add( rightArrow);

	return cont.Element;
};  
AdeoDatePicker.prototype.yearForPrint = function(){
	var cont = new AdeoElement();

	var leftArrow = new AdeoElement();
	leftArrow.setSize( '15px', '16px'); 
	leftArrow.setStyle( 'cursor', 'pointer'); 
	leftArrow.setStyle( 'float', 'left'); 
	leftArrow.setStyle( 'backgroundImage', "url('58.gif')"); 
	leftArrow.setAttribute( 'myName', this.Name);
	leftArrow.addEventListener( 'click', NIJS.Adeo.Date.Picker.yearBackward);

	var rightArrow = new AdeoElement();
	rightArrow.setSize( '15px', '16px'); 
	rightArrow.setStyle( 'cursor', 'pointer'); 
	rightArrow.setStyle( 'float', 'left'); 
	rightArrow.setStyle( 'backgroundImage', "url('59.gif')");
	rightArrow.setAttribute( 'myName', this.Name);
	rightArrow.addEventListener( 'click', NIJS.Adeo.Date.Picker.yearForward); 

	var year = new AdeoElement();
	year.setSize( '48px', '16px'); 
	year.setStyle( 'lineHeight', '16px'); 
	year.setStyle( 'float', 'left'); 
	year.setStyle( 'textAlign', 'center'); 	
	year.setInnerHTML( this.currentYear());
	
	cont.add( leftArrow);
	cont.add( year);
	cont.add( rightArrow);

	return cont.Element;
};  

NIJS.Adeo.Date.Picker = {};
NIJS.Adeo.Date.Picker.Object = AdeoDatePicker;
NIJS.Adeo.Date.Picker.open = function( el, onClickDay, params){	
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var dtPickName = elem.getAttribute('datePickerName');
	var oldDatePicker, newDatePicker, date;

	if( !dtPickName){
		if( !params)
			params = elem.getAttribute( 'params');

		var input = document.getElementById( params);
		if( input && input.value && NIJS.Adeo.Date.Calendar.isDateFormat( input.value))
			date = input.value;

		if( !onClickDay)
			onClickDay = elem.getAttribute( 'onClickDay');
		newDatePicker = new AdeoDatePicker( onClickDay, params);
		dtPickName = newDatePicker.Name;
		elem.setAttribute( 'datePickerName', dtPickName);
	}
	
	var winParams = new WindowParams( WindowType.Blank, null, null, dtPickName);
	winParams.display( true, false, true);
	winParams.posdim( tempX, tempY, '200px', '251px');
	if( newDatePicker){
		if( date)
			newDatePicker.setAll( date);
		winParams.content( newDatePicker.getDatePicker());		
	}
	oldDatePicker = windowContainer.open( winParams);	
	if( newDatePicker){
		oldDatePicker.Attributes.put( dtPickName, newDatePicker);
	}
};

NIJS.Adeo.Date.Picker.monthForward = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;

	var myName = elem.getAttribute( 'myName');
	if( !myName)
		return;

	var me = WinContainer[ myName];

	if( me){
		var oldMe = me.Attributes.get( myName);
		if( oldMe instanceof AdeoDatePicker){
			oldMe.monthForward();
			oldMe.refresh ();
		}
	}
};
NIJS.Adeo.Date.Picker.monthBackward = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;

	var myName = elem.getAttribute( 'myName');
	if( !myName)
		return;

	var me = WinContainer[ myName];

	if( me){
		var oldMe = me.Attributes.get( myName);
		if( oldMe instanceof AdeoDatePicker){
			oldMe.monthBackward();
			oldMe.refresh ();
		}
	}
};;
NIJS.Adeo.Date.Picker.yearForward = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;

	var myName = elem.getAttribute( 'myName');
	if( !myName)
		return;

	var me = WinContainer[ myName];

	if( me){
		var oldMe = me.Attributes.get( myName);
		if( oldMe instanceof AdeoDatePicker){
			oldMe.yearForward();
			oldMe.refresh ();
		}
	}
};
NIJS.Adeo.Date.Picker.yearBackward = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;

	var myName = elem.getAttribute( 'myName');
	if( !myName)
		return;

	var me = WinContainer[ myName];

	if( me){
		var oldMe = me.Attributes.get( myName);
		if( oldMe instanceof AdeoDatePicker){
			oldMe.yearBackward();
			oldMe.refresh ();
		}
	}
};
NIJS.Adeo.Date.Picker.update = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;

	var myName = elem.getAttribute( 'myName');
	if( !myName)
		return;
	var me = WinContainer[ myName];

	if( me){
		var oldMe = me.Attributes.get( myName);
		if( oldMe instanceof AdeoDatePicker){
			var date = elem.getAttribute( 'date');
			oldMe.setAll( date);
			oldMe.daysInMonthRowRefresh();
		}
	}

	var fja = elem.getAttribute( 'onClickDay');
	if( fja){
		eval( fja).call( this, elem);
	}
};
NIJS.Adeo.Date.Picker.onDayClickForm = function( elem){
	if( !elem)
		return;
	var params = elem.getAttribute( 'params');
	if( params){
		var input = document.getElementById( params);
		if( input){
			var date = elem.getAttribute( 'date');
			if( date){
				var arr = date.split('.');
				if( arr.length>=2){
					if( parseInt( arr[0]) >= 10)
						date = arr[0] + '.';
					else
						date = '0' + arr[0] + '.';

					var month = parseInt( arr[1]) + 1;
					if( month>=10)
						date += month + '.';
					else
						date += '0' + month + '.';

					date += arr[2] + '.';
				}
			}
			input.value = date;
		}
	}		
};
NIJS.Adeo.Date.Picker.onDayClickInsertInSelection = function( elem){
	if( !elem)
		return;
	var date = elem.getAttribute( 'date');
	if( date)
		oSel.edit( 'InsertHtml', null, date);
};
function AdeoSpecialChar( onClickDay, params){
        this.specialChar = new AdeoElement();
	this.Name = this.specialChar.id + 'SpecialChar';

	if( onClickDay)
		this.ONCLICK = onClickDay;
	else
		this.ONCLICK = NIJS.Adeo.SpecialChar.onSpecialCharClickInsertInSelection;
	this.PARAMS = params;

}
AdeoSpecialChar.prototype.getSpecialChar = function(){
	this.printSpecialChars();
	return this.specialChar.Element;
};
AdeoSpecialChar.prototype.printSpecialChars = function(){	
	if( this.specialChar){
		while( this.specialChar.Element.firstChild)
			this.specialChar.Element.removeChild( this.specialChar.Element.firstChild);
	}
        for(var i=143; i<256; i++){  
                var znak = new AdeoElement();
		znak.setInnerHTML( "&"+"#"+i+";");
		znak.setAttribute( 'charCode', "&"+"#"+i+";");
		znak.setClass( 'specialChar');
		znak.setAttribute( 'inputName', this.Name + 'Input');
		znak.addEventListener( 'click', this.ONCLICK);
		this.specialChar.add( znak);
	}
	this.printInsertSpecialChar();
};
AdeoSpecialChar.prototype.printInsertSpecialChar = function(){	
	var bottom = new AdeoElement();
	bottom.setClass( 'specialCharBottom');

	var text = new AdeoElement( 'span');
	text.setStyle( 'float', 'left');
	text.setInnerHTML( 'Character code:');

	var input = new AdeoElement( 'input');
	input.setClass( 'specialCharInput');
	input.setAttribute( 'type', 'text');
	input.setAttribute( 'value', 'char code');
	input.setAttribute( 'id', this.Name + 'Input');
	
	var okButton = new AdeoElement();
	okButton.setClass( 'okButton');
	okButton.setAttribute( 'inputName', this.Name + 'Input');
	okButton.addEventListener( 'click', NIJS.Adeo.SpecialChar.onOkButtonClickInsertInSelection);
	
	bottom.add( text);
	bottom.add( input);
	bottom.add( okButton);
	this.specialChar.add( bottom);
};

NIJS.Adeo.SpecialChar = {};
NIJS.Adeo.SpecialChar.Object = AdeoSpecialChar;
NIJS.Adeo.SpecialChar.open = function( el, onClickDay, params){	
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var specialCharName = elem.getAttribute('specialCharName');
	var oldSpecialChar, newSpecialChar, date;

	if( !specialCharName){
		if( !params)
			params = elem.getAttribute( 'params');

		if( !onClickDay)
			onClickDay = elem.getAttribute( 'onClickDay');
		newSpecialChar = new AdeoSpecialChar( onClickDay, params);
		specialCharName = newSpecialChar.Name;
		elem.setAttribute( 'specialCharName', specialCharName);
	}

	oldSpecialChar = windowContainer.openBlankWindow( specialCharName, tempX, tempY, '392px', '230px');	
	if( newSpecialChar){
		oldSpecialChar.WinContent.fillWith( newSpecialChar.getSpecialChar());
		oldSpecialChar.Attributes.put( specialCharName, newSpecialChar);
	}
};
NIJS.Adeo.SpecialChar.onSpecialCharClickInsertInSelection = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var charCode = elem.getAttribute( 'charCode');
	if( charCode){
		oSel.edit( 'InsertHtml', null, charCode);

		var inputName = elem.getAttribute( 'inputName');
		if( inputName){
			var input = document.getElementById( inputName);
			if( input && input.value){
				input.value = charCode;
			}
		}
	}
};
NIJS.Adeo.SpecialChar.onOkButtonClickInsertInSelection = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var inputName = elem.getAttribute( 'inputName');
	if( inputName){
		var input = document.getElementById( inputName);
		if( input && input.value){
			oSel.edit( 'InsertHtml', null, input.value);
		}
	}
};
function AdeoColorPicker( onClickColor, params, sName, prefix){

        this.colorPicker = new AdeoTable();
        this.colorPicker.setStyle( 'textAlign', 'center');
        this.colorPicker.setStyle( 'border', '0');
	this.Name = this.colorPicker.id + 'ColorPicker';

	if( onClickColor)
		this.ONCLICK = onClickColor;
	else
		this.ONCLICK = NIJS.Adeo.Color.Picker.onColorClickSetCss;
	this.PARAMS = params;
	this.sName = sName;
	this.prefix = prefix;

	this.colorsTR;
	this.moreTR;
	this.recentTR;
}

AdeoColorPicker.prototype.getColorPicker = function(){
        this.colorsTR = this.colorPicker.addRowEnd();
        this.colorsTR.style.border = '0';
	this.printColorCellsRefresh();

        this.moreTR = this.colorPicker.addRowEnd();
        this.moreTR.style.border = '0';
	this.printMoreCells();

        this.recentTR = this.colorPicker.addRowEnd();
        this.recentTR.style.border = '0';
	this.printRecentCells();

	return this.colorPicker.Element;
};
AdeoColorPicker.prototype.refresh = function(){
	this.printColorCells();
	this.printMoreCells();
	this.printRecentCells();
};
AdeoColorPicker.prototype.printRecentCells = function(){	
	var cell = document.createElement('td');
};
AdeoColorPicker.prototype.printMoreCells = function(){

};
AdeoColorPicker.prototype.printColorCellsRefresh = function(){
	var tmpCell = document.createElement( 'td');

	if( this.colorsTR){
		while( this.colorsTR.firstChild)
			this.colorsTR.removeChild( this.colorsTR.firstChild);
		//this.daysInMonthTR.innerHTML = "";
		this.colorsTR.appendChild( tmpCell);
	}

        tmpCell.style.textAlign = 'center';
        tmpCell.style.borderTop = '1px solid rgb(163, 183, 244)';
	tmpCell.appendChild( this.printColorCells());
};
AdeoColorPicker.prototype.printColorCells = function(){
        var colors = new AdeoTable();   
	             
	for(var i=0; i<hex_colors.length; i++){
		if( i%18 == 0){
			var colorsRow = colors.addRowEnd(); 
			colorsRow.style.border = '0';	
		}
		var cell = document.createElement('td');
		cell.setAttribute( 'params', this.PARAMS);
		cell.setAttribute( 'sName', this.sName);
		cell.setAttribute( 'prefix', this.prefix);
		cell.setAttribute( 'onClickDay', this.ONCLICK);
		cell.setAttribute( 'myName', this.Name);
		cell.style.border = '1px solid black';
		adeo.element.niAddEventListener( cell, 'click', this.ONCLICK);
		cell.style.backgroundColor = '#' + hex_colors[i];
		cell.style.lineHeight = '8px';
		cell.style.width = '6px';
		cell.style.cursor = 'crosshair';
		cell.innerHTML = '&nbsp;';
				    
		colorsRow.appendChild( cell);
	}
	return colors.Element;
};  

NIJS.Adeo.Color = {}
NIJS.Adeo.Color.Picker = {};
NIJS.Adeo.Color.Picker.Object = AdeoColorPicker;
NIJS.Adeo.Color.Picker.open = function( el, onClickColor, params, sName, prefix){	
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var colorPickerName = elem.getAttribute('colorPickerName');
	var oldColorPicker, newColorPicker;

	if( !colorPickerName){
		if( !params)
			params = elem.getAttribute( 'params');
		if( !onClickColor)
			onClickColor = elem.getAttribute( 'onClickColor');

		newColorPicker = new AdeoColorPicker( onClickColor, params, sName, prefix);
		colorPickerName = newColorPicker.Name;
		elem.setAttribute( 'colorPickerName', colorPickerName);
	}

	oldColorPicker = windowContainer.openBlankWindow( colorPickerName, tempX, tempY, '240px', '225px');	
	if( newColorPicker){
		oldColorPicker.WinContent.fillWith( newColorPicker.getColorPicker());
		oldColorPicker.Attributes.put( colorPickerName, newColorPicker);
	}
};
NIJS.Adeo.Color.Picker.onColorClickSetCss = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var bgColor = elem.style.backgroundColor;
	var sName = elem.getAttribute( 'sName');
	var prefix = elem.getAttribute( 'prefix');
	oSel.setProp( sName, bgColor, prefix);
};
NIJS.Adeo.Color.Picker.onColorClickEditColor = function( el){
	var elem = adeo.element.niGetEventTarget( el);
	if( !elem)
		return;
	var bgColor = elem.style.backgroundColor;
	var sName = elem.getAttribute( 'sName');
	var prefix = elem.getAttribute( 'prefix');
	if( document.getElementById(sName + 'Link'))
	document.getElementById(sName + 'Link').style.backgroundColor = bgColor;
	oSel.edit( sName, null, bgColor );
};

var hex_colors = new Array('330000', '333300', '336600', '339900', '33CC00', '33FF00', '66FF00', '66CC00', '669900', '666600', '663300', '660000', 'FF0000', 'FF3300', 'FF6600', 'FF9900', 'FFCC00', 'FFFF00', '330033', '333333', '336633', '339933', '33CC33', '33FF33', '66FF33', '66CC33', '669933', '666633', '663333', '660033', 'FF0033', 'FF3333', 'FF6633', 'FF9933', 'FFCC33', 'FFFF33', '330066', '333366', '336666', '339966', '33CC66', '33FF66', '66FF66', '66CC66', '669966', '666666', '663366', '660066', 'FF0066', 'FF3366', 'FF6666', 'FF9966', 'FFCC66', 'FFFF66', '330099', '333399', '336699', '339999', '33CC99', '33FF99', '66FF99', '66CC99', '669999', '666699', '663399', '660099', 'FF0099', 'FF3399', 'FF6699', 'FF9999', 'FFCC99', 'FFFF99', '3300CC', '3333CC', '3366CC', '3399CC', '33CCCC', '33FFCC', '66FFCC', '66CCCC', '6699CC', '6666CC', '6633CC', '6600CC', 'FF00CC', 'FF33CC', 'FF66CC', 'FF99CC', 'FFCCCC', 'FFFFCC', '3300FF', '3333FF', '3366FF', '3399FF', '33CCFF', '33FFFF', '66FFFF', '66CCFF', '6699FF', '6666FF', '6633FF', '6600FF', 'FF00FF', 'FF33FF', 'FF66FF', 'FF99FF', 'FFCCFF', 'FFFFFF', '0000FF', '0033FF', '0066FF', '0099FF', '00CCFF', '00FFFF', '99FFFF', '99CCFF', '9999FF', '9966FF', '9933FF', '9900FF', 'CC00FF', 'CC33FF', 'CC66FF', 'CC99FF', 'CCCCFF', 'CCFFFF', '0000CC', '0033CC', '0066CC', '0099CC', '00CCCC', '00FFCC', '99FFCC', '99CCCC', '9999CC', '9966CC', '9933CC', '9900CC', 'CC00CC', 'CC33CC', 'CC66CC', 'CC99CC', 'CCCCCC', 'CCFFCC', '000099', '003399', '006699', '009999', '00CC99', '00FF99', '99FF99', '99CC99', '999999', '996699', '993399', '990099', 'CC0099', 'CC3399', 'CC6699', 'CC9999', 'CCCC99', 'CCFF99', '000066', '003366', '006666', '009966', '00CC66', '00FF66', '99FF66', '99CC66', '999966', '996666', '993366', '990066', 'CC0066', 'CC3366', 'CC6666', 'CC9966', 'CCCC66', 'CCFF66', '000033', '003333', '006633', '009933', '00CC33', '00FF33', '99FF33', '99CC33', '999933', '996633', '993333', '990033', 'CC0033', 'CC3333', 'CC6633', 'CC9933', 'CCCC33', 'CCFF33', '000000', '003300', '006600', '009900', '00CC00', '00FF00', '99FF00', '99CC00', '999900', '996600', '993300', '990000', 'CC0000', 'CC3300', 'CC6600', 'CC9900', 'CCCC00', 'CCFF00', '000000', '111111', '222222', '333333', '444444', '555555', '666666', '777777', '888888', '999999', 'AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDBBB', 'DDDDDD', 'EEECCC', 'EEEEEE', 'FFFFFF'  );
function removeDiv( divId){
  var div = document.getElementById( divId)
  document.getElementById( divId).parentNode.removeChild( div);
}

var width = 0;
var height = 0;
var desno = 0;

function onClickA(id){  
  var elem_a = document.getElementById(id + '_a');
  var tmp = elem_a.className;
  elem_a.className = elem_a.getAttribute('change');
  elem_a.setAttribute('change', tmp);
}
function onClickB(id){
  window.location.href = "Page.do?page=" + id;
}
function mouseOverC(id){
  var elem_c = document.getElementById(id + '_c');
  if(elem_c)
    elem_c.style.display = 'block';
}
function mouseOutC(id){
  var elem_c = document.getElementById(id + '_c');
  if(elem_c)
    elem_c.style.display = 'none';
}
function hoverChange(id){
  var tmp;
  var elem_a = document.getElementById(id + '_a');
  var changeA = elem_a.getAttribute( 'change');
  if( changeA != 'css'){
    tmp = elem_a.className;
    elem_a.className = changeA;
    elem_a.setAttribute('change', tmp);
  }
  var elem_b = document.getElementById(id + '_b');
  var changeB = elem_b.getAttribute( 'change');  
  if( changeB != 'css'){
    tmp = elem_b.className;
    elem_b.className = changeB;
    elem_b.setAttribute('change', tmp);
  }
}

function openPopup( url)
{      
  if( tempX < (width/2) || tempX < 600)
    popupLeft = tempX;
  else
    popupLeft = width - 650;

  if( tempY < (height/2) || tempY < 550)
    popupTop = tempY; 
  else
    popupTop = height - 600;

  window.open( url, 'w' + Math.floor(Math.random()*10000), 'left=' + popupLeft + ',top=' + popupTop + ',height=550,width=600,scrollbars=yes,resizable=yes,status=1'); return false
} 

function openPopupWH( url, left, top, width, height)
{      
  window.open( url, 'w' + Math.floor(Math.random()*10000), 'left=' + left + ',top=' + top + ',height=' + height + ',width=' + width + ',scrollbars=yes,resizable=yes,status=1'); return false
} 

function refreshParentCSS( cssElemId)
{
  if( window.opener != null){
    href = window.opener.document.getElementById( cssElemId).getAttribute('href');
    if( href.search('=') != -1)
      href = href.substring( 0, href.search('='));
    else
      href = href + '?d=';
    href = href + Math.floor(Math.random()*10000);
    window.opener.document.getElementById( cssElemId).setAttribute('href', href);
  }
}

adeo = {};
adeo.init = AdeoGlobal.init;
adeo.element = {
  niAddEventListener: function( elem, event, func) {
    if( elem.addEventListener)
      elem.addEventListener( event, func, false);
    else if (elem.attachEvent)
      elem.attachEvent( 'on' + event, func);
  },
        
  niGetElementPosition: function( elem, addSuffix) {
    var currTop = elem.offsetTop, currLeft = elem.offsetLeft;
    while( elem.offsetParent && (elem = elem.offsetParent))
      currTop += elem.offsetTop, currLeft += elem.offsetLeft;
    if( addSuffix)
      currTop += 'px', currLeft += 'px';
    return [ currTop, currLeft];
  },
        
  niGetElementDimensions: function( elem, addSuffix) {
    var elemWidth = elem.offsetWidth, elemHeigth = elem.offsetHeight;
    if( addSuffix)
      elemWidth += 'px', elemHeigth += 'px';
    return [ elemWidth, elemHeigth];
  },
        
  niGetEventTarget: function( evt) {
	evt = (evt) ? evt : ((window.event) ? window.event : window.Event)
	if (evt)
		return evt.target ? evt.target : evt.srcElement ? evt.srcElement : evt;
	else 
		return null;
  },

  niGetElementEventTarget: function( elem, evt) {	
	evt = (evt) ? evt : ((window.event) ? window.event : "")
	if (evt)
		return evt.target ? evt.target : evt.srcElement;
	else 
		return elem;
  },
        
  niStopBubbling: function( event) {
    if( !event) event = window.event;
      event.cancelBubble = true;
    if( event.stopPropagation) event.stopPropagation();
  }    
}

