/* Merged Plone Javascript file
 * This file is dynamically assembled from separate parts.
 * Some of these parts have 3rd party licenses or copyright information attached
 * Such information is valid for that section,
 * not for the entire composite file
 * originating files are separated by ----- filename.js -----
 */

/* ----- sarissa.js ----- */
/*****************************************************************************
 *
 * Sarissa XML library version 0.9.6
 * Copyright (c) 2003 Manos Batsis, 
 * mailto: mbatsis at users full stop sourceforge full stop net
 * This software is distributed under the Kupu License. See
 * LICENSE.txt for license text. See the Sarissa homepage at
 * http://sarissa.sourceforge.net for more information.
 *
 *****************************************************************************

 * ====================================================================
 * About
 * ====================================================================
 * Sarissa cross browser XML library 
 * @version 0.9.6
 * @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
 *
 * 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+) and, last but not least, KHTML based browsers like
 * Konqueror and Safari.
 *
 */
/**
 * <p>Sarissa is a utility class. Provides static methods for DOMDocument and 
 * XMLHTTP objects, DOM Node serializatrion to XML strings and other goodies.</p>
 * @constructor
 */
function Sarissa(){};
/** @private */
Sarissa.PARSED_OK = "Document contains no parsing errors";
/**
 * Tells you whether transformNode and transformNodeToObject are available. This functionality
 * is contained in sarissa_ieemu_xslt.js and is deprecated. If you want to control XSLT transformations
 * use the XSLTProcessor
 * @deprecated
 * @type boolean
 */
Sarissa.IS_ENABLED_TRANSFORM_NODE = false;
/**
 * tells you whether XMLHttpRequest (or equivalent) is available
 * @type boolean
 */
Sarissa.IS_ENABLED_XMLHTTP = false;
/**
 * tells you whether selectNodes/selectSingleNode is available
 * @type boolean
 */
Sarissa.IS_ENABLED_SELECT_NODES = false;
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.toLowerCase().indexOf("applewebkit") != -1;
var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1;

if(!window.Node || !window.Node.ELEMENT_NODE){
    var 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};
};

// 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 = "";
    /**
     * Called when the Sarissa_xx.js file is parsed, to pick most recent
     * ProgIDs for IE, then gets destroyed.
     * @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
     */
    pickRecentProgID = function (idList, enabledList){
        // 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;
                for(var j=0;j<enabledList.length;j++)
                    if(i <= enabledList[j][1])
                        Sarissa["IS_ENABLED_"+enabledList[j][0]] = 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 = pickRecentProgID(["Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"], [["SELECT_NODES", 2],["TRANSFORM_NODE", 2]]);
    _SARISSA_XMLHTTP_PROGID = pickRecentProgID(["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"], [["XMLHTTP", 4]]);
    _SARISSA_THREADEDDOM_PROGID = pickRecentProgID(["Msxml2.FreeThreadedDOMDocument.5.0", "MSXML2.FreeThreadedDOMDocument.4.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
    _SARISSA_XSLTEMPLATE_PROGID = pickRecentProgID(["Msxml2.XSLTemplate.5.0", "Msxml2.XSLTemplate.4.0", "MSXML2.XSLTemplate.3.0"], [["XSLTPROC", 2]]);
    // we dont need this anymore
    pickRecentProgID = null;
    //============================================
    // Factory methods (IE)
    //============================================
    // see non-IE version
    Sarissa.getDomDocument = function(sUri, sName){
        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){
            // if needed, create an artifical namespace prefix the way Moz
            // does
            if (sUri){
                oDoc.loadXML("<a" + _sarissa_iNsCounter + ":" + sName + " xmlns:a" + _sarissa_iNsCounter + "=\"" + sUri + "\" />");
                // don't use the same prefix again
                ++_sarissa_iNsCounter;
            }
            else
                oDoc.loadXML("<" + sName + "/>");
        };
        return oDoc;
    };
    // see non-IE version   
    Sarissa.getParseErrorText = function (oDoc) {
        var parseErrorText = Sarissa.PARSED_OK;
        if(oDoc.parseError != 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";
        };
        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(){
        this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID);
        this.processor = null;
    };
    /**
     * Impoprts the given XSLT DOM and compiles it to a reusable transform
     * @argument xslDoc The XSLT DOMDocument to import
     */
    XSLTProcessor.prototype.importStylesheet = function(xslDoc){
        // convert stylesheet to free threaded
        var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID); 
        converted.loadXML(xslDoc.xml);
        this.template.stylesheet = converted;
        this.processor = this.template.createProcessor();
        // (re)set default param values
        this.paramsSet = new Array();
    };
    /**
     * Transform the given XML DOM
     * @argument sourceDoc The XML DOMDocument to transform
     * @return The transformation result as a DOM Document
     */
    XSLTProcessor.prototype.transformToDocument = function(sourceDoc){
        this.processor.input = sourceDoc;
        var outDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
        this.processor.output = outDoc; 
        this.processor.transform();
        return outDoc;
    };
    /**
     * Not sure if this works in IE. Maybe this will allow non-well-formed
     * transformation results (i.e. with no single root element)
     * @argument sourceDoc The XML DOMDocument to transform
     * @return The transformation result as a DOM Fragment
     */
    XSLTProcessor.prototype.transformToFragment = function(sourceDoc, ownerDocument){
        return this.transformToDocument(sourceDoc);
    };
    /**
     * 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){
        if(this.paramsSet[""+nsURI] && this.paramsSet[""+nsURI][name])
            return this.paramsSet[""+nsURI][name];
        else
            return null;
    };
}
else{ /* end IE initialization, try to deal with real browsers now ;-) */
   if(_SARISSA_HAS_DOM_CREATE_DOCUMENT){
        if(window.XMLDocument){
            /**
            * <p>Emulate IE's onreadystatechange attribute</p>
            */
            XMLDocument.prototype.onreadystatechange = null;
            /**
            * <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>
            */
            XMLDocument.prototype.readyState = 0;
            /**
            * <p>Emulate IE's parseError attribute</p>
            */
            XMLDocument.prototype.parseError = 0;

            // NOTE: setting async to false will only work with documents
            // called over HTTP (meaning a server), not the local file system,
            // unless you are using Moz 1.4+.
            // BTW the try>catch block is for 1.4; I haven't found a way to check if
            // the property is implemented without
            // causing an error and I dont want to use user agent stuff for that...
            var _SARISSA_SYNC_NON_IMPLEMENTED = false;
            try{
                /**
                * <p>Emulates IE's async property for Moz versions prior to 1.4.
                * It controls whether loading of remote XML files works
                * synchronously or asynchronously.</p>
                */
                XMLDocument.prototype.async = true;
                _SARISSA_SYNC_NON_IMPLEMENTED = true;
            }catch(e){/* trap */};
            /**
            * <p>Keeps a handle to the original load() method. Internal use and only
            * if Mozilla version is lower than 1.4</p>
            * @private
            */
            XMLDocument.prototype._sarissa_load = XMLDocument.prototype.load;

            /**
            * <p>Overrides the original load method to provide synchronous loading for
            * Mozilla versions prior to 1.4, using an XMLHttpRequest object (if
            * async is set to false)</p>
            * @returns the DOM Object as it was before the load() call (may be  empty)
            */
            XMLDocument.prototype.load = function(sURI) {
                var oDoc = document.implementation.createDocument("", "", null);
                Sarissa.copyChildNodes(this, oDoc);
                this.parseError = 0;
                Sarissa.__setReadyState__(this, 1);
                try {
                    if(this.async == false && _SARISSA_SYNC_NON_IMPLEMENTED) {
                        var tmp = new XMLHttpRequest();
                        tmp.open("GET", sURI, false);
                        tmp.send(null);
                        Sarissa.__setReadyState__(this, 2);
                        Sarissa.copyChildNodes(tmp.responseXML, this);
                        Sarissa.__setReadyState__(this, 3);
                    }
                    else {
                        this._sarissa_load(sURI);
                    };
                }
                catch (objException) {
                    this.parseError = -1;
                }
                finally {
                    if(this.async == false){
                        Sarissa.__handleLoad__(this);
                    };
                };
                return oDoc;
            };
        };//if(window.XMLDocument)

        /**
         * <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){
            if (!oDoc.documentElement || oDoc.documentElement.tagName == "parsererror")
                oDoc.parseError = -1;
            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;
            if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function")
                oDoc.onreadystatechange();
        };
        /**
        * <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:"", sName?sName:"", null);
            oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false);
            return oDoc;
        };        
    };//if(_SARISSA_HAS_DOM_CREATE_DOCUMENT)
};
//==========================================
// Common stuff
//==========================================
if(!window.DOMParser){
    /** 
    * 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 doc = Sarissa.getDomDocument();
        doc.loadXML(sXml);
        return doc;
    };
    
};

if(window.XMLHttpRequest){
    Sarissa.IS_ENABLED_XMLHTTP = true;
}
else if(_SARISSA_IS_IE){
    /**
     * Emulate XMLHttpRequest
     * @constructor
     */
    XMLHttpRequest = function() {
        return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
    };
    Sarissa.IS_ENABLED_XMLHTTP = true;
};

if(!window.document.importNode && _SARISSA_IS_IE){
    try{
        /**
        * Implements importNode for the current window document in IE using innerHTML.
        * Testing showed that DOM was multiple times slower than innerHTML for this,
        * sorry folks. If you encounter trouble (who knows what IE does behind innerHTML)
        * please gimme a call.
        * @param oNode the Node to import
        * @param bChildren whether to include the children of oNode
        * @returns the imported node for further use
        */
        window.document.importNode = function(oNode, bChildren){
            var importNode = document.createElement("div");
            if(bChildren)
                importNode.innerHTML = Sarissa.serialize(oNode);
            else
                importNode.innerHTML = Sarissa.serialize(oNode.cloneNode(false));
            return importNode.firstChild;
        };
        }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.parseError != 0){
            /*moz*/
            if(oDoc.documentElement.tagName == "parsererror"){
                parseErrorText = oDoc.documentElement.firstChild.data;
                parseErrorText += "\n" +  oDoc.documentElement.firstChild.nextSibling.firstChild.data;
            }/*konq*/
            else if(oDoc.documentElement.tagName == "html"){
                parseErrorText = Sarissa.getText(oDoc.documentElement.getElementsByTagName("h1")[0], false) + "\n";
                parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("body")[0], false) + "\n";
                parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("pre")[0], false);
            };
        };
        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){
    /**
     * <p>Factory method to obtain the serialization of a DOM Node</p>
     * @returns the serialized Node as an XML string
     */
    Sarissa.serialize = function(oDoc){
        return (new XMLSerializer()).serializeToString(oDoc);
    };
}else{
    if((Sarissa.getDomDocument("","foo", null)).xml){
        // see non-IE version
        Sarissa.serialize = function(oDoc) {
            // TODO: check for HTML document and return innerHTML instead
            return oDoc.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) {
    while(oNode.hasChildNodes()){
        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(!bPreserveExisting){
        Sarissa.clearChildNodes(nodeTo);
    };
    var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
    var nodes = nodeFrom.childNodes;
    if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
        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 false
 */
Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
    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){
        nodeTo.appendChild(nodes[i]);
    }else{
        var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
         if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
            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


/* ----- vcXMLRPC.js ----- */
//
//    Copyright (C) 2000, 2001, 2002  Virtual Cowboys info@virtualcowboys.nl
//		
//		Author: Ruben Daniels <ruben@virtualcowboys.nl>
//		Version: 0.91
//		Date: 29-08-2001
//		Site: www.vcdn.org/Public/XMLRPC/
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program; if not, write to the Free Software
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Object.prototype.toXMLRPC = function(){
	var wo = this.valueOf();
	
	if(wo.toXMLRPC == this.toXMLRPC){
		retstr = "<struct>";
		
		for(prop in this){
			if(typeof wo[prop] != "function"){
				retstr += "<member><name>" + prop + "</name><value>" + XMLRPC.getXML(wo[prop]) + "</value></member>";
			}
		}
		retstr += "</struct>";
		
		return retstr;
	}
	else{
		return wo.toXMLRPC();
	}
}

String.prototype.toXMLRPC = function(){
	//<![CDATA[***your text here***]]>
	return "<string><![CDATA[" + this.replace(/\]\]/g, "] ]") + "]]></string>";//.replace(/</g, "&lt;").replace(/&/g, "&amp;")
}

Number.prototype.toXMLRPC = function(){
	if(this == parseInt(this)){
		return "<int>" + this + "</int>";
	}
	else if(this == parseFloat(this)){
		return "<double>" + this + "</double>";
	}
	else{
		return false.toXMLRPC();
	}
}

Boolean.prototype.toXMLRPC = function(){
	if(this) return "<boolean>1</boolean>";
	else return "<boolean>0</boolean>";
}

Date.prototype.toXMLRPC = function(){
	//Could build in possibilities to express dates 
	//in weeks or other iso8601 possibillities
	//hmmmm ????
	//19980717T14:08:55
	return "<dateTime.iso8601>" + doYear(this.getUTCYear()) + doZero(this.getMonth()) + doZero(this.getUTCDate()) + "T" + doZero(this.getHours()) + ":" + doZero(this.getMinutes()) + ":" + doZero(this.getSeconds()) + "</dateTime.iso8601>";
	
	function doZero(nr) {
		nr = String("0" + nr);
		return nr.substr(nr.length-2, 2);
	}
	
	function doYear(year) {
		if(year > 9999 || year < 0) 
			XMLRPC.handleError(new Error("Unsupported year: " + year));
			
		year = String("0000" + year)
		return year.substr(year.length-4, 4);
	}
}

Array.prototype.toXMLRPC = function(){
	var retstr = "<array><data>";
	for(var i=0;i<this.length;i++){
		retstr += "<value>" + XMLRPC.getXML(this[i]) + "</value>";
	}
	return retstr + "</data></array>";
}

function VirtualService(servername, oRPC){
	this.version = '0.91';
	this.URL = servername;
	this.multicall = false;
	this.autoroute = true;
	this.onerror = null;
	
	this.rpc = oRPC;
	this.receive = {};
	
	this.purge = function(receive){
		return this.rpc.purge(this, receive);
	}
	
	this.revert = function(){
		this.rpc.revert(this);
	}
	
	this.add = function(name, alias, receive){
		this.rpc.validateMethodName();if(this.rpc.stop){this.rpc.stop = false;return false}
		if(receive) this.receive[name] = receive;
		this[(alias || name)] = new Function('var args = new Array(), i;for(i=0;i<arguments.length;i++){args.push(arguments[i]);};return this.call("' + name + '", args);');
		return true;
	}
	
	//internal function for sending data
	this.call = function(name, args){
		var info = this.rpc.send(this.URL, name, args, this.receive[name], this.multicall, this.autoroute);
		
		if(info){
			if(!this.multicall) this.autoroute = info[0];
			return info[1];
		}
		else{
			if(this.onerror) this.onerror(XMLRPC.lastError);
			return false;
		}
	}
}


XMLRPC = {
	routeServer : "",
	autoroute : false,
	multicall : false,

	services : {},
	stack : {},
	queue : new Array(),
	timers : new Array(),
	timeout : 30000,
	
	ontimeout : null,
	
	getService : function(serviceName){
		//serviceNames cannot contain / or .
		if(/[\/\.]/.test(serviceName)){
			return new VirtualService(serviceName, this);
		}
		else if(this.services[serviceName]){
			return this.services[serviceName];
		}
		else{
			try{
				var ct = eval(serviceName);
				this.services[serviceName] = new ct(this);
			}
			catch(e){
				return false;
			}
		}
	},
	
	purge : function(modConst, receive){
		if(this.stack[modConst.URL].length){
			var info = this.send(modConst.URL, "system.multicall", [this.stack[modConst.URL]], receive, false, modConst.autoroute);
			modConst.autoroute = info[0];
			this.revert(modConst);
			
			if(info){
				modConst.autoroute = info[0];
				return info[1];
			}
			else{
				if(modConst.onerror) modConst.onerror(this.lastError);
				return false;
			}
		}
	},
	
	revert : function(modConst){
		this.stack[modConst.URL] = new Array();
	},
	
	call : function(){
		//[optional info || receive, servername,] functionname, args......
		var args = new Array(), i, a = arguments;
		var servername, methodname, receive, service, info, autoroute, multicall;
		
		if(typeof a[0] == "object"){
			receive = a[0][0];
			servername = a[0][1].URL;
			methodname = a[1];
			multicall = (a[0][1].supportsMulticall && a[0][1].multicall);
			autoroute = a[0][1].autoroute;
			service = a[0][1];
		}
		else if(typeof a[0] == "function"){
			i = 3;
			receive = a[0];
			servername = a[1];
			methodname = a[2];
		}
		else{
			i = 2;
			servername = a[0];
			methodname = a[1];
		}
			
		for(i=i;i<a.length;i++){
			args.push(a[i]);
		}
		
		info = this.send(servername, methodname, args, receive, multicall, autoroute);
		if(info){
			(service || this).autoroute = info[0];
			return info[1];
		}
		else{
			if(service && service.onerror) service.onerror(this.lastError);
			return false;
		}
		
	},
	
	/***
	* Perform typematching on 'vDunno' and return a boolean value corresponding
	* to the result of the evaluation-match of the mask-value stated in the 2nd argument.
	* The 2nd argument is optional (none will be treated as a 0-mask) or a sum of
	* several masks as follows:
	* type/s    ->  mask/s
	* --------------------
	* undefined ->  0/1 [default]
	* number    ->  2
	* boolean   ->  4
	* string    ->  8
	* function  -> 16
	* object    -> 32
	* --------------------
	* Examples:
	* Want [String] only: (eqv. (typeof(vDunno) == 'string') )
	*  Soya.Common.typematch(unknown, 8)
	* Anything else than 'undefined' acceptable:
	*  Soya.Common.typematch(unknown)
	* Want [Number], [Boolean] or [Function]:
	*  Soya.Common.typematch(unknown, 2 + 4 + 16)
	* Want [Number] only:
	*  Soya.Common.typematch(unknown, 2)
	**/
	typematch : function (vDunno, nCase){
		var nMask;
		switch(typeof(vDunno)){
			case 'number'  : nMask = 2;  break;
			case 'boolean' : nMask = 4;  break;
			case 'string'  : nMask = 8;  break;
			case 'function': nMask = 16; break;
			case 'object'  : nMask = 32; break;
			default	     : nMask = 1;  break;
		}
		return Boolean(nMask & (nCase || 62));
	},
	
	getNode : function(data, tree){
		var nc = 0;//nodeCount
		//node = 1
		if(data != null){
			for(i=0;i<data.childNodes.length;i++){
				if(data.childNodes[i].nodeType == 1){
					if(nc == tree[0]){
						data = data.childNodes[i];
						if(tree.length > 1){
							tree.shift();
							data = this.getNode(data, tree);
						}
						return data;
					}
					nc++
				}
			}
		}
		
		return false;
	},
	
	toObject : function(data){
		var ret, i;
		switch(data.tagName){
			case "string":
				return (data.firstChild) ? new String(data.firstChild.nodeValue) : "";
				break;
			case "int":
			case "i4":
			case "double":
				return (data.firstChild) ? new Number(data.firstChild.nodeValue) : 0;
				break;
			case "dateTime.iso8601":
				/*
				Have to read the spec to be able to completely 
				parse all the possibilities in iso8601
				07-17-1998 14:08:55
				19980717T14:08:55
				*/
				
				var sn = (isIE) ? "-" : "/";
				
				if(/^(\d{4})(\d{2})(\d{2})T(\d{2}):(\d{2}):(\d{2})/.test(data.firstChild.nodeValue)){;//data.text)){
	      		return new Date(RegExp.$2 + sn + RegExp.$3 + sn + 
	      							RegExp.$1 + " " + RegExp.$4 + ":" + 
	      							RegExp.$5 + ":" + RegExp.$6);
	      	}
	    		else{
	    			return new Date();
	    		}

				break;
			case "array":
				data = this.getNode(data, [0]);
				
				if(data && data.tagName == "data"){
					ret = new Array();
					
					var i = 0;
					while(child = this.getNode(data, [i++])){
      				ret.push(this.toObject(child));
					}
					
					return ret;
				}
				else{
					this.handleError(new Error("Malformed XMLRPC Message1"));
					return false;
				}
				break;
			case "struct":
				ret = {};
					
				var i = 0;
				while(child = this.getNode(data, [i++])){
					if(child.tagName == "member"){
						ret[this.getNode(child, [0]).firstChild.nodeValue] = this.toObject(this.getNode(child, [1]));
					}
					else{
						this.handleError(new Error("Malformed XMLRPC Message2"));
						return false;
					}
				}
				
				return ret;
				break;
			case "boolean":
				return Boolean(isNaN(parseInt(data.firstChild.nodeValue)) ? (data.firstChild.nodeValue == "true") : parseInt(data.firstChild.nodeValue))

				break;
			case "base64":
				return this.decodeBase64(data.firstChild.nodeValue);
				break;
			case "value":
				child = this.getNode(data, [0]);
				return (!child) ? ((data.firstChild) ? new String(data.firstChild.nodeValue) : "") : this.toObject(child);

				break;
			default:
				this.handleError(new Error("Malformed XMLRPC Message: " + data.tagName));
				return false;
				break;
		}
	},
	
	/*** Decode Base64 ******
	* Original Idea & Code by thomas@saltstorm.net
	* from Soya.Encode.Base64 [http://soya.saltstorm.net]
	**/
	decodeBase64 : function(sEncoded){
		// Input must be dividable with 4.
		if(!sEncoded || (sEncoded.length % 4) > 0)
		  return sEncoded;
	
		/* Use NN's built-in base64 decoder if available.
		   This procedure is horribly slow running under NN4,
		   so the NN built-in equivalent comes in very handy. :) */
	
		else if(typeof(atob) != 'undefined')
		  return atob(sEncoded);
	
	  	var nBits, i, sDecoded = '';
	  	var base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		sEncoded = sEncoded.replace(/\W|=/g, '');
	
		for(i=0; i < sEncoded.length; i += 4){
			nBits =
				(base64.indexOf(sEncoded.charAt(i))   & 0xff) << 18 |
				(base64.indexOf(sEncoded.charAt(i+1)) & 0xff) << 12 |
				(base64.indexOf(sEncoded.charAt(i+2)) & 0xff) <<  6 |
				base64.indexOf(sEncoded.charAt(i+3)) & 0xff;
			sDecoded += String.fromCharCode(
				(nBits & 0xff0000) >> 16, (nBits & 0xff00) >> 8, nBits & 0xff);
		}
	
		// not sure if the following statement behaves as supposed under
		// all circumstances, but tests up til now says it does.
	
		return sDecoded.substring(0, sDecoded.length -
		 ((sEncoded.charCodeAt(i - 2) == 61) ? 2 :
		  (sEncoded.charCodeAt(i - 1) == 61 ? 1 : 0)));
	},
	
	getObject : function(type, message){
		if(type == "HTTP"){
			if(isIE)
				obj = new ActiveXObject("microsoft.XMLHTTP"); 
			else if(isNS)
				obj = new XMLHttpRequest();
		}
		else if(type == "XMLDOM"){
			if(isIE){
				obj = new ActiveXObject("microsoft.XMLDOM"); 
				obj.loadXML(message)
			}else if(isNS){
				obj = new DOMParser();
				obj = obj.parseFromString(message, "text/xml");
			}
			
		}
		else{
			this.handleError(new Error("Unknown Object"));
		}

		return obj;
	},
	
	validateMethodName : function(name){
		/*do Checking:
		
		The string may only contain identifier characters, 
		upper and lower-case A-Z, the numeric characters, 0-9, 
		underscore, dot, colon and slash. 
		
		*/
		if(/^[A-Za-z0-9\._\/:]+$/.test(name))
			return true
		else
			this.handleError(new Error("Incorrect method name"));
	},
	
	getXML : function(obj){
		if(typeof obj == "function"){
			this.handleError(new Error("Cannot Parse functions"));
		}else if(obj == null || obj == undefined || (typeof obj == "number" && !isFinite(obj)))
			return false.toXMLRPC();
		else
			return obj.toXMLRPC();
	},
	
	handleError : function(e){
		if(!this.onerror || !this.onerror(e)){
			//alert("An error has occured: " + e.message);
			throw e;
		}
		this.stop = true;
		this.lastError = e;
	},
	
	cancel : function(id){
		//You can only cancel a request when it was executed async (I think)
		if(!this.queue[id]) return false;
		
		this.queue[id][0].abort();
		return true;
	},
	
	send : function(serverAddress, functionName, args, receive, multicall, autoroute){
		var id, http;
		//default is sync
		this.validateMethodName();
		if(this.stop){this.stop = false; return false;}
		
		//setting up multicall
		multicall = (multicall != null) ? multicall : this.multicall;
		
		if(multicall){
			if(!this.stack[serverAddress]) this.stack[serverAddress] = new Array();
			this.stack[serverAddress].push({methodName : functionName, params : args});
			return true;
		}
		
		//creating http object
		var http = this.getObject("HTTP");
		
		//setting some things for async/sync transfers
		if(!receive || isNS){;
			async = false;
		}
		else{
			async = true;
			/* The timer functionality is implemented instead of
				the onreadystatechange event because somehow
				the calling of this event crashed IE5.x
			*/
			id = this.queue.push([http, receive, null, new Date()])-1;
			
			this.queue[id][2] = new Function("var id='" + id + "';var dt = new Date(new Date().getTime() - XMLRPC.queue[id][3].getTime());diff = parseInt(dt.getSeconds()*1000 + dt.getMilliseconds());if(diff > XMLRPC.timeout){if(XMLRPC.ontimeout) XMLRPC.ontimeout(); clearInterval(XMLRPC.timers[id]);XMLRPC.cancel(id);return};if(XMLRPC.queue[id][0].readyState == 4){XMLRPC.queue[id][0].onreadystatechange = function(){};XMLRPC.receive(id);clearInterval(XMLRPC.timers[id])}");
			this.timers[id] = setInterval("XMLRPC.queue[" + id + "][2]()", 20);
		}
		
		//setting up the routing
		autoroute = (autoroute || this.autoroute);
		
		//'active' is only set when direct sending the message has failed
		var srv = (autoroute == "active") ? this.routeServer : serverAddress;
		
		try{
			http.open('POST', srv, async);
			http.setRequestHeader("User-Agent", "vcXMLRPC v0.91 (" + navigator.userAgent + ")");
			http.setRequestHeader("Host", srv.replace(/^https?:\/{2}([:\[\]\-\w\.]+)\/?.*/, '$1'));
			http.setRequestHeader("Content-type", "text/xml");
			if(autoroute == "active"){
				http.setRequestHeader("X-Proxy-Request", serverAddress);
				http.setRequestHeader("X-Compress-Response", "gzip");
			}
		}
		catch(e){
			if(autoroute == true){
				//Access has been denied, Routing call.
				autoroute = "active";
				if(id){
					delete this.queue[id];
					clearInterval(this.timers[id]);
				}
				return this.send(serverAddress, functionName, args, receive, multicall, autoroute);
			}
			
			//Routing didn't work either..Throwing error
			this.handleError(new Error("Could not sent XMLRPC Message (Reason: Access Denied on client)"));
			if(this.stop){this.stop = false;return false}
		}
		
		//Construct the message
		var message = '<?xml version="1.0"?><methodCall><methodName>' + functionName + '</methodName><params>';
   	for(i=0;i<args.length;i++){
   		message += '<param><value>' + this.getXML(args[i]) + '</value></param>';
		}
		message += '</params></methodCall>';
		
		var xmldom = this.getObject('XMLDOM', message);
		if(self.DEBUG) alert(message);
		
		try{
			//send message
			http.send(xmldom);
		}
		catch(e){
			//Most likely the message timed out(what happend to your internet connection?)
			this.handleError(new Error("XMLRPC Message not Sent(Reason: " + e.message + ")"));
			if(this.stop){this.stop = false;return false}
		}
		
		if(!async && receive)
			return [autoroute, receive(this.processResult(http))];
		else if(receive)
			return [autoroute, id];
		else
			return [autoroute, this.processResult(http)];
	},
	
	receive : function(id){
		//Function for handling async transfers..
		if(this.queue[id]){
			var data = this.processResult(this.queue[id][0]);
			this.queue[id][1](data);
			delete this.queue[id];
		}
		else{
			this.handleError(new Error("Error while processing queue"));
		}
	},
	
	processResult : function(http){
		if(self.DEBUG) alert(http.responseText);
		if(http.status == 200){
			//getIncoming message
		   dom = http.responseXML;

		   if(dom){
		   	var rpcErr, main;

		   	//Check for XMLRPC Errors
		   	rpcErr = dom.getElementsByTagName("fault");
		   	if(rpcErr.length > 0){
		   		rpcErr = this.toObject(rpcErr[0].firstChild);
		   		this.handleError(new Error(rpcErr.faultCode, rpcErr.faultString));
		   		return false
		   	}

		   	//handle method result
		   	main = dom.getElementsByTagName("param");
		      if(main.length == 0) this.handleError(new Error("Malformed XMLRPC Message"));
				data = this.toObject(this.getNode(main[0], [0]));

				//handle receiving
				if(this.onreceive) this.onreceive(data);
				return data;
		   }
		   else{
		  		this.handleError(new Error("Malformed XMLRPC Message"));
			}
		}
		else{
			this.handleError(new Error("HTTP Exception: (" + http.status + ") " + http.statusText + "\n\n" + http.responseText));
		}
	}
}

//Smell something
ver = navigator.appVersion;
app = navigator.appName;
isNS = Boolean(navigator.productSub)
//moz_can_do_http = (parseInt(navigator.productSub) >= 20010308)

isIE = (ver.indexOf("MSIE 5") != -1 || ver.indexOf("MSIE 6") != -1) ? 1 : 0;
isIE55 = (ver.indexOf("MSIE 5.5") != -1) ? 1 : 0;

isOTHER = (!isNS && !isIE) ? 1 : 0;

