﻿/*****************************************************************************/
/* adds often used methods to the official prototype.js library
** 
** requires prototype.js
*/
var VOID_ID = -1; 

Hash.addMethods({

    /// returns the value for key or replacement if no such key exists in the hash
    getOptional : function(key, replacement)
    {
        var value = this.get(key);
        return (value == null)
            ? replacement
            : value;
    }

});

Object.extend(Array.prototype, {

    /// removes the first element from the array for which the iterator returns true. Returned value is the old index of
    /// removed element or -1 if none found
    remove : function(iterator)
    {
        var length = this.size();
        for(var i=0; i<length; i++)
        {
            if(iterator(this[i]))
            {
                this.splice(i, 1);
                return i;
            }
        }
        return -1;
    }

});

Ajax.Response.addMethods({

    /// extracts the body from a XML webservice response
    GetPayloadFromXmlResponse : function()
    {
	    //
	    // strip end of xml wrapper
	    //
	    var text = this.responseText;
	    //var re = new RegExp("^(?:<\?xml[^>]+>\n)" + "(?:<[^>]+>)" + ".+" + "(?:</[^>]>+)$", "m");
	    var reXml = /^<[?]xml[^>]+>/;
	    var reStartTag = /^<[^>]+>/m;
	    var reEndTag = /<\/[^>]+>$/m;
	    var reEmpty = /^<[^>]+\/>$/m;
    	
	    text = text.substring(reXml.exec(text)[0].length + 2); /* strip xml line */
    	
	    if(text.match(reEmpty)) return "";
	    text = text.replace(reStartTag, "");
	    text = text.replace(reEndTag, "");

        return text.unescapeHTML();
    }

});
