/* 
 * More info at: http://phpjs.org
 * 
 * This is version: 2.61
 * php.js is copyright 2009 Kevin van Zonneveld.
 * 
 * Portions copyright Brett Zamir (http://brettz9.blogspot.com), Kevin van
 * Zonneveld (http://kevin.vanzonneveld.net), Onno Marsman, Michael White
 * (http://getsprink.com), Waldo Malqui Silva, Paulo Ricardo F. Santos, Jack,
 * Jonas Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Ates
 * Goral (http://magnetiq.com), Legaev Andrey, Martijn Wieringa, Nate, Enrique
 * Gonzalez, Philippe Baumann, Webtoolkit.info (http://www.webtoolkit.info/),
 * Theriault, Ash Searle (http://hexmen.com/blog/), Carlos R. L. Rodrigues
 * (http://www.jsfromhell.com), travc, Ole Vrijenhoek, Jani Hartikainen,
 * Johnny Mast (http://www.phpvrouwen.nl), d3x, Erkekjetter, stag019, Michael
 * Grier, GeekFG (http://geekfg.blogspot.com), Andrea Giammarchi
 * (http://webreflection.blogspot.com), marrtins, Alex, Steven Levithan
 * (http://blog.stevenlevithan.com), Mirek Slugen, Marc Palau, Breaking Par
 * Consulting Inc
 * (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
 * David, mdsjack (http://www.mdsjack.bo.it), KELAN, Public Domain
 * (http://www.json.org/json2.js), gettimeofday, Josh Fraser
 * (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
 * Arpad Ray (mailto:arpad@php.net), gorthaur, Thunder.m, Aman Gupta,
 * Pellentesque Malesuada, Sakimori, Alfonso Jimenez
 * (http://www.alfonsojimenez.com), Karol Kowalski, AJ, Lars Fischer, Caio
 * Ariede (http://caioariede.com), Tyler Akins (http://rumkin.com), Steve
 * Hilder, Oleg Eremeev, Douglas Crockford (http://javascript.crockford.com),
 * Steve Clay, David James, Subhasis Deb, T. Wild, Ole Vrijenhoek
 * (http://www.nervous.nl/), Hyam Singer (http://www.impact-computing.com/),
 * Lincoln Ramsay, kenneth, djmix, class_exists, mktime, sankai, Linuxworld,
 * Pyerre, Jon Hohle, madipta, Sanjoy Roy, noname, Felix Geisendoerfer
 * (http://www.debuggable.com/felix), 0m3r, Marco, Paul, J A R, Bayron
 * Guevara, john (http://www.jd-tech.net), Ozh, David Randall, Bryan Elliott,
 * MeEtc (http://yass.meetcweb.com), Brad Touesnard, Tim Wiel, Peter-Paul Koch
 * (http://www.quirksmode.org/js/beat.html), XoraX (http://www.xorax.info),
 * T0bsn, Thiago Mata (http://thiagomata.blog.com), Soren Hansen, duncan,
 * Gilbert, Marc Jansen, Francesco, echo is bad, Der Simon
 * (http://innerdom.sourceforge.net/), Eugene Bulkin (http://doubleaw.com/),
 * LH, Slawomir Kaniecki, ger, Eric Nagel, Bobby Drake, Pul, rezna, Mick@el,
 * Pierre-Luc Paour, Martin Pool, Kirk Strobeck, Luke Godfrey, Blues
 * (http://tech.bluesmoon.info/), setcookie, YUI Library:
 * http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
 * http://hacks.bluesmoon.info/strftime/strftime.js, Christian Doebler,
 * penutbutterjelly, Anton Ongson, Simon Willison (http://simonwillison.net),
 * Gabriel Paderni, Kristof Coomans (SCK-CEN Belgian Nucleair Research
 * Centre), Saulo Vallory, hitwork, Norman "zEh" Fuchs, dptr1988, sowberry,
 * Yves Sucaet, Nick Callen, ejsanders, johnrembo, Pedro Tainha
 * (http://www.pedrotainha.com), DxGx, Wagner B. Soares, Valentina De Rosa,
 * Daniel Esteban, uestla, T.Wild, Alexander Ermolaev
 * (http://snippets.dzone.com/user/AlexanderErmolaev), ChaosNo1, metjay,
 * strcasecmp, strcmp, Andreas, Garagoth, Cord, Victor, stensi, Manish, Matt
 * Bradley, Tim de Koning, taith, Robin, Jalal Berrami, date, Nathan, nobbler,
 * marc andreu, Arno, Mateusz "loonquawl" Zalega, Francois, Scott Cariss,
 * ReverseSyntax, FremyCompany, Tod Gentille, booeyOH, Cagri Ekin, Luke Smith
 * (http://lucassmith.name), Ben Bryan, Leslie Hoare, Andrej Pavlovic, Dino,
 * mk.keck, Rival, Diogo Resende, gabriel paderni, FGFEmperor, baris ozdil,
 * Yannoo, jakes, Howard Yeend, Allan Jensen (http://www.winternet.no),
 * Benjamin Lupton, Atli Þór
 * 
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * 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 KEVIN VAN ZONNEVELD 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.
 */ 


function abs( mixed_number )  {
    // Return the absolute value of the number  
    // 
    // version: 812.316
    // discuss at: http://phpjs.org/functions/abs
    // +   original by: Waldo Malqui Silva
    // +   improved by: Karol Kowalski
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *     example 1: abs(4.2);
    // *     returns 1: 4.2
    // *     example 2: abs(-4.2);
    // *     returns 2: 4.2
    // *     example 3: abs(-5);
    // *     returns 3: 5
    // *     example 4: abs('_argos');
    // *     returns 4: 0
    return Math.abs(mixed_number) || 0;
}

function acos(arg) {
    // Return the arc cosine of the number in radians  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/acos
    // +   original by: Onno Marsman
    // *     example 1: acos(0.3);
    // *     returns 1: 1.2661036727794992
    return Math.acos(arg);
}

function acosh(arg) {
    // Returns the inverse hyperbolic cosine of the number, i.e. the value whose hyperbolic cosine is number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/acosh
    // +   original by: Onno Marsman
    // *     example 1: acosh(8723321.4);
    // *     returns 1: 16.674657798418625
    return Math.log(arg + Math.sqrt(arg*arg-1));
}

function addslashes( str ) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/addslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

function aggregate (obj, class_name) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy privileged functions or instance properties, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the methods on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.method = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate(b, 'A');
	// *     returns 1: undefined

   var p = '', record={}, pos=-1;

   if (typeof class_name === 'string') { // PHP behavior
       class_name = this.window[class_name];
   }

     // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);

    for (p in class_name) {
        if (!(p in obj) && p !== 'prototype' && p[0] !== '_') { // Static (non-private) class methods and properties
            obj[p] = class_name[p];
            record[p] = class_name[p];
        }
    }
    for (p in class_name.prototype) {
        if (!(p in obj) && p[0] !== '_') { // Prototype (non-private) instance methods and prototype default properties
            obj[p] = class_name.prototype[p];
            record[p] = class_name.prototype[p];
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_info (obj) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: aggregate_info
	// *     example 1: var A = function () {};
	// *     example 1: A.prop = 5;
	// *     example 1: A.prototype.someMethod = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate(b, 'A');
	// *     example 1: aggregate_info(b);
	// *     returns 1: {'A':{methods:['someMethod'], properties:['prop']}}

    var idx=-1, p='', infoObj={}, retObj={}, i=0, name='';

    if (!this.php_js || !this.php_js.aggregateRecords || !this.php_js.aggregateKeys || !this.php_js.aggregateClasses) {
        return false; // Is this what is returned?
    }

    idx = this.php_js.aggregateKeys.indexOf(obj);
    if (idx === -1) {
        return false;
    }

    for (i=0; i < this.php_js.aggregateClasses[idx].length; i++) {
        name = this.php_js.aggregateClasses[idx][i];
        infoObj={methods:[], properties:[]};
        for (p in this.php_js.aggregateRecords[idx][i]) {
            if (typeof this.php_js.aggregateRecords[idx][i][p] === 'function') {
                infoObj.methods.push(p);
            }
            else {
                infoObj.properties.push(p);
            }
        }
        retObj[name] = infoObj;
    }
    
    return retObj;
}

function aggregate_methods (obj, class_name) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy privileged functions, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the methods on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.method = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate_methods(b, 'A');
	// *     returns 1: undefined

    var p = '', record={}, pos=-1;

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);

    for (p in class_name) {
        if (!(p in obj) && typeof class_name[p] === 'function' && p[0] !== '_') { // Static (non-private) class methods
            obj[p] = class_name[p];
            record[p] = class_name[p];
        }
    }
    for (p in class_name.prototype) {
        if (!(p in obj) && typeof class_name.prototype[p] === 'function' && p[0] !== '_') { // Prototype (non-private) instance methods
            obj[p] = class_name.prototype[p];
            record[p] = class_name.prototype[p];
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_methods_by_list (obj, class_name, properties_list, exclude) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy privileged methods, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the methods on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.method = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate_methods_by_list(b, 'A', ['method'], false);
	// *     returns 1: undefined

    var p = '', i=0, record={}, pos=-1;

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);

    if (exclude) {
        for (p in class_name) {
            if (!(p in obj) &&
                    typeof class_name[p] === 'function' &&
                        p[0] !== '_' &&
                            properties_list.indexOf(p) === -1) { // Static (non-private) class methods
                obj[p] = class_name[p];
                record[p] = class_name[p];
            }
        }
        for (p in class_name.prototype) {
            if (!(p in obj) &&
                    typeof class_name.prototype[p] === 'function' &&
                        p[0] !== '_' &&
                            properties_list.indexOf(p) === -1) { // Prototype (non-private) instance methods
                obj[p] = class_name.prototype[p];
                record[p] = class_name.prototype[p];
            }
        }
    } else {
        for (i=0; i < properties_list.length; i++) {
            p = properties_list[i];
            if (!(p in obj) &&
                    p in class_name &&
                        p[0] !== '_' &&
                            typeof class_name.prototype[p] === 'function') { // Static (non-private) class methods
                obj[p] = class_name[p];
                record[p] = class_name[p];
            } else if (!(p in obj) &&
                    p in class_name.prototype &&
                        p[0] !== '_' &&
                            typeof class_name.prototype[p] === 'function') { // Prototype (non-private) instance methods
                obj[p] = class_name.prototype[p];
                record[p] = class_name.prototype[p];
            }
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_methods_by_regexp (obj, class_name, regexp, exclude) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy privileged methods, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the methods on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.method = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate_methods_by_regexp(b, 'A', /^meth/, false);
	// *     returns 1: undefined

    var p = '', test=false, record={}, pos=-1;

    if (typeof regexp === 'string') { // If passing the regular expression as a string, note that this behavior may change in the future as we seek to implement PHP-style regexp (e.g., delimiteres and modifier flags within the string)
        regexp = eval(regexp);
    }

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);
    
    for (p in class_name) {
        test = exclude ? !regexp.test(p) : regexp.test(p);
        if (!(p in obj) &&
                typeof class_name[p] === 'function' &&
                    p[0] !== '_' &&
                        test) { // Static (non-private) class methods
            obj[p] = class_name[p];
            record[p] = class_name[p];
        }
    }
    for (p in class_name.prototype) {
        test = exclude ? !regexp.test(p) : regexp.test(p);
        if (!(p in obj) &&
                typeof class_name.prototype[p] === 'function' &&
                    p[0] !== '_' &&
                        test) { // Prototype (non-private) instance methods
            obj[p] = class_name.prototype[p];
            record[p] = class_name.prototype[p];
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_properties (obj, class_name) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy instance properties, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the properties on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.prop = 10;
	// *     example 1: var b = {};
	// *     example 1: aggregate_properties(b, 'A');
	// *     returns 1: undefined

    var p = '', record={}, pos=-1;

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);

    for (p in class_name) {
        if (!(p in obj) && typeof class_name[p] !== 'function' && p[0] !== '_') { // Static (non-private) class properties
            obj[p] = class_name[p];
            record[p] = class_name[p];
        }
    }
    for (p in class_name.prototype) {
        if (!(p in obj) && typeof class_name.prototype[p] !== 'function' && p[0] !== '_') { // Prototype (non-private) default properties
            obj[p] = class_name.prototype[p];
            record[p] = class_name.prototype[p];
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_properties_by_list (obj, class_name, properties_list, exclude) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy instance properties, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the properties on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.prop = 10;
	// *     example 1: var b = {};
	// *     example 1: aggregate_properties_by_list(b, 'A', ['prop'], false);
	// *     returns 1: undefined

    var p = '', i=0, record={}, pos=-1;

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT
    this.php_js.aggregateClasses.push(class_name.name);

    if (exclude) {
        for (p in class_name) {
            if (!(p in obj) &&
                    typeof class_name[p] !== 'function' &&
                        p[0] !== '_' &&
                            properties_list.indexOf(p) === -1) { // Static (non-private) class properties
                obj[p] = class_name[p];
                record[p] = class_name[p];
            }
        }
        for (p in class_name.prototype) {
            if (!(p in obj) &&
                    typeof class_name.prototype[p] !== 'function' &&
                        p[0] !== '_' &&
                            properties_list.indexOf(p) === -1) { // Prototype (non-private) default properties
                obj[p] = class_name.prototype[p];
                record[p] = class_name.prototype[p];
            }
        }
    } else {
        for (i=0; i < properties_list.length; i++) {
            p = properties_list[i];
            if (!(p in obj) &&
                    p in class_name &&
                        p[0] !== '_' &&
                            typeof class_name.prototype[p] !== 'function') { // Static (non-private) class properties
                obj[p] = class_name[p];
                record[p] = class_name[p];
            } else if (!(p in obj) &&
                    p in class_name.prototype &&
                        p[0] !== '_' &&
                            typeof class_name.prototype[p] !== 'function') { // Prototype (non-private) default properties
                obj[p] = class_name.prototype[p];
                record[p] = class_name.prototype[p];
            }
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregate_properties_by_regexp (obj, class_name, regexp, exclude) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: We can't copy instance properties, as those require instantiation (with potential side-effects when called)
	// %          note 1: We've chosen not to assign to or create a prototype object on the destination object even if the original object had the properties on its prototype
	// *     example 1: var A = function () {};
	// *     example 1: A.prototype.prop = 10;
	// *     example 1: var b = {};
	// *     example 1: aggregate_properties_by_regexp(b, 'A', /^pr/, false);
	// *     returns 1: undefined

    var p = '', test=false, record={}, pos=-1;

    if (typeof regexp === 'string') { // If passing the regular expression as a string, note that this behavior may change in the future as we seek to implement PHP-style regexp (e.g., delimiteres and modifier flags within the string)
        regexp = eval(regexp);
    }

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.aggregateKeys) {
        this.php_js.aggregateKeys = [];
    }
    if (!this.php_js.aggregateRecords) { // Needed to allow deaggregate() and aggregate_info()
        this.php_js.aggregateRecords = [];
    }
    if (!this.php_js.aggregateClasses) {
        this.php_js.aggregateClasses = [];
    }
    // END REDUNDANT


    for (p in class_name) {
        test = exclude ? !regexp.test(p) : regexp.test(p);
        if (!(p in obj) &&
                typeof class_name[p] !== 'function' &&
                    p[0] !== '_' &&
                        test) { // Static (non-private) class properties
            obj[p] = class_name[p];
            record[p] = class_name[p];
        }
    }
    for (p in class_name.prototype) {
        test = exclude ? !regexp.test(p) : regexp.test(p);
        if (!(p in obj) &&
                typeof class_name.prototype[p] !== 'function' &&
                    p[0] !== '_' &&
                        test) { // Prototype (non-private) default properties
            obj[p] = class_name.prototype[p];
            record[p] = class_name.prototype[p];
        }
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(class_name.name);
    } else {
        this.php_js.aggregateKeys.push(obj);
        this.php_js.aggregateRecords.push([record]);
        this.php_js.aggregateClasses[0] = [];
        this.php_js.aggregateClasses[0].push(class_name.name);
    }
}

function aggregation_info (obj) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: aggregate_info
	// *     example 1: var A = function () {};
	// *     example 1: A.prop = 5;
	// *     example 1: A.prototype.someMethod = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate(b, 'A');
	// *     example 1: aggregation_info(b);
	// *     returns 1: {'A':{methods:['someMethod'], properties:['prop']}}
    
    return aggregate_info(obj);
}

function array( ) {
    // !No description available for array. @php.js developers: Please update the function summary text file.
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array
    // +   original by: d3x
    // *     example 1: array('Kevin', 'van', 'Zonneveld');
    // *     returns 1: ['Kevin', 'van', 'Zonneveld']
    return Array.prototype.slice.call(arguments);
}

function array_change_key_case( array ) {
    // Retuns an array with all string keys lowercased [or uppercased]  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_change_key_case
    // +   original by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // *     example 1: array_change_key_case(42);
    // *     returns 1: false
    // *     example 2: array_change_key_case([ 3, 5 ]);
    // *     returns 2: {0: 3, 1: 5}
    // *     example 3: array_change_key_case({ FuBaR: 42 });
    // *     returns 3: {"fubar": 42}
    // *     example 4: array_change_key_case({ FuBaR: 42 }, 'CASE_LOWER');
    // *     returns 4: {"fubar": 42}
    // *     example 5: array_change_key_case({ FuBaR: 42 }, 'CASE_UPPER');
    // *     returns 5: {"FUBAR": 42}
    // *     example 6: array_change_key_case({ FuBaR: 42 }, 2);
    // *     returns 6: {"FUBAR": 42}
    var case_fn, tmp_ar = {}, argc = arguments.length, argv = arguments, key;

    if (array instanceof Array) {
        return array; 
    }

    if (array instanceof Object) {
        if( argc === 1 || argv[1] === 'CASE_LOWER' || argv[1] === 0 ){
            case_fn = "toLowerCase";
        } else{
            case_fn = "toUpperCase";
        }
        for (key in array) {
            tmp_ar[key[case_fn]()] = array[key];
        }
        return tmp_ar;
    }

    return false;
}

function array_chunk( input, size ) {
    // Split array into chunks  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_chunk
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // *     example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
    // *     returns 1: {0 : {0: 'Kevin', 1: 'van'} , 1 : {0: 'Zonneveld'}}
 
    for(var x, i = 0, c = -1, l = input.length, n = []; i < l; i++){
        (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
    }

    return n;
}

function array_combine( keys, values ) {
    // Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_combine
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_combine([0,1,2], ['kevin','van','zonneveld']);
    // *     returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
   
    var new_array = {}, keycount=keys.length, i;

    // input sanitation
    if( !keys || !values || keys.constructor !== Array || values.constructor !== Array ){
        return false;
    }

    // number of elements does not match
    if(keycount != values.length){
        return false;
    }

    for ( i=0; i < keycount; i++ ){
        new_array[keys[i]] = values[i];
    }

    return new_array;
}

function array_count_values( array ) {
    // Return the value as key and the frequency of that value in input as value  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_count_values
    // +   original by: Ates Goral (http://magnetiq.com)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: sankai
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_count_values([ 3, 5, 3, "foo", "bar", "foo" ]);
    // *     returns 1: {3:2, 5:1, "foo":2, "bar":1}
    // *     example 2: array_count_values({ p1: 3, p2: 5, p3: 3, p4: "foo", p5: "bar", p6: "foo" });
    // *     returns 2: {3:2, 5:1, "foo":2, "bar":1}
    // *     example 3: array_count_values([ true, 4.2, 42, "fubar" ]);
    // *     returns 3: {42:1, "fubar":1}
    var tmp_arr = {}, key = '', t = '';
    
    var __getType = function(obj) {
        // Objects are php associative arrays.
        var t = typeof obj;
        t = t.toLowerCase();
        if (t == "object") {
            t = "array";
        }
        return t;
    };

    var __countValue = function (value) {
        switch (typeof(value)) {
            case "number":
                if (Math.floor(value) != value) {
                    return;
                }
            case "string":
                if (value in this) {
                    ++this[value];
                } else {
                    this[value] = 1;
                }
        }
    };
    
    t = __getType(array);
    if (t == 'array') {
        for ( key in array ) {
            __countValue.call(tmp_arr, array[key]);
        }
    } 
    return tmp_arr;
}

function array_diff() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments.  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_diff
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sanjoy Roy
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
    // *     returns 1: ['Kevin']
    var arr1 = arguments[0], retArr = {};
    var k1 = '', i = 1, k = '', arr = {};

    arr1keys:
    for (k1 in arr1) {
        for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys; 
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_diff_assoc() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_diff_assoc
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: 0m3r
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: array_diff_assoc({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}, {0: 'Kevin', 4: 'van', 5: 'Zonneveld'});
    // *     returns 1: {1: 'van', 2: 'Zonneveld'}
    var arr1 = arguments[0], retArr = {};
    var k1 = '', i = 1, k = '', arr = {};

    arr1keys:
    for (k1 in arr1) {
        for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1] && k === k1) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_diff_key() {
    // Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved.  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_diff_key
    // +   original by: Ates Goral (http://magnetiq.com)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: array_diff_key({red: 1, green: 2, blue: 3, white: 4}, {red: 5});
    // *     returns 1: {"green":2, "blue":3, "white":4}
    // *     example 2: array_diff_key({red: 1, green: 2, blue: 3, white: 4}, {red: 5}, {red: 5});
    // *     returns 2: {"green":2, "blue":3, "white":4}
    var arr1 = arguments[0], retArr = {};
    var k1 = '', i = 1, k = '', arr = {};
 
    arr1keys:
    for (k1 in arr1) {
        for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (k === k1) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_diff_uassoc() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_diff_uassoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_diff_uassoc($array1, $array2, function(key1, key2){ return (key1 == key2 ? 0 : (key1 > key2 ? 1 : -1)); });
    // *     returns 1: {b: 'brown', c: 'blue', 0: 'red'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var arr = {}, i = 1, k1 = '', k = '';
    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        for (i=1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1] && cb(k, k1) === 0) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_diff_ukey() {
    // Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_diff_ukey
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {blue: 1, red: 2, green: 3, purple: 4}
    // *     example 1: $array2 = {green: 5, blue: 6, yellow: 7, cyan: 8}
    // *     example 1: array_diff_ukey($array1, $array2, function(key1, key2){ return (key1 == key2 ? 0 : (key1 > key2 ? 1 : -1)); });
    // *     returns 1: {red: 2, purple: 4}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var arr = {}, i = 1, k1 = '', k = '';

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        for (i=1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(k, k1) === 0) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_fill( start_index, num, mixed_val ) {
    // Create an array containing num elements starting with index start_key each initialized to val  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_fill
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // *     example 1: array_fill(5, 6, 'banana');
    // *     returns 1: { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' }
    var key, tmp_arr = {};

    if ( !isNaN( start_index ) && !isNaN( num ) ) {
        for( key = 0; key < num; key++ ) {
            tmp_arr[(key+start_index)] = mixed_val;
        }
    }

    return tmp_arr;
}

function array_fill_keys (keys, value) {
    // Create an array using the elements of the first parameter as keys each initialized to val  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_fill_keys
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: keys = {'a': 'foo', 2: 5, 3: 10, 4: 'bar'}
    // *     example 1: array_fill_keys(keys, 'banana')
    // *     returns 1: {"foo": "banana", 5: "banana", 10: "banana", "bar": "banana"}
    
    var retObj = {}, key = '';
    
    for (key in keys) {
        retObj[keys[key]] = value;
    }
    
    return retObj;
}

function array_filter (arr, func) {
    // Filters elements from the array via the callback.  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_filter
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Takes a function as an argument, not a function's name
    // *     example 1: var odd = function (num) {return (num & 1);}; 
    // *     example 1: array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd);
    // *     returns 1: {"a": 1, "c": 3, "e": 5}
    // *     example 2: var even = function (num) {return (!(num & 1));}
    // *     example 2: array_filter([6, 7, 8, 9, 10, 11, 12], even);
    // *     returns 2: {0: 6, 2: 8, 4: 10, 6: 12} 
    
    var retObj = {}, k;
    
    for (k in arr) {
        if (func(arr[k])) {
            retObj[k] = arr[k];
        }
    }
    
    return retObj;
}

function array_flip( trans ) {
    // Return array with key <-> value flipped  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_flip
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_flip( {a: 1, b: 1, c: 2} );
    // *     returns 1: {1: 'b', 2: 'c'}
    var key, tmp_ar = {};

    for( key in trans ) {
        tmp_ar[trans[key]] = key;
    }

    return tmp_ar;
}

function array_intersect() {
    // Returns the entries of arr1 that have values which are present in all the other arguments  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_intersect
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: These only output associative arrays (would need to be
    // %        note 1: all numeric and counting from zero to be numeric)
    // *     example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
    // *     example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
    // *     example 1: $array3 = ['green', 'red'];
    // *     example 1: $result = array_intersect($array1, $array2, $array3);
    // *     returns 1: {0: 'red', a: 'green'}
    var arr1 = arguments[0], retArr = {};
    var k1 = '', arr = {}, i = 0, k = '';
    
    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i=1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    if (i === arguments.length-1) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_intersect_assoc() {
    // Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_intersect_assoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: These only output associative arrays (would need to be
    // %        note 1: all numeric and counting from zero to be numeric)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'green', 0: 'yellow', 1: 'red'}
    // *     example 1: array_intersect_assoc($array1, $array2)
    // *     returns 1: {a: 'green'}
    var arr1 = arguments[0], retArr = {};
    var k1 = '', arr = {}, i = 0, k = '';

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i=1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1] && k === k1) {
                    if (i === arguments.length-1) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_intersect_key() {
    // Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data.  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_intersect_key
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: These only output associative arrays (would need to be
    // %        note 1: all numeric and counting from zero to be numeric)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'green', 0: 'yellow', 1: 'red'}
    // *     example 1: array_intersect_key($array1, $array2)
    // *     returns 1: {0: 'red', a: 'green'}
    var arr1 = arguments[0], retArr = {};
    var k1 = '', arr = {}, i = 0, k = '';

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i=1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (k === k1) {
                    if (i === arguments.length-1) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_intersect_uassoc () {
    // Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_intersect_uassoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_intersect_uassoc($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {b: 'brown'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var k1 = '', i = 1, arr = {}, k = '';

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i = 1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1] && cb(k, k1) === 0 ) {
                    if (i === arguments.length-2) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_intersect_ukey  () {
    // Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_intersect_ukey
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {blue: 1, red: 2, green: 3, purple: 4}
    // *     example 1: $array2 = {green: 5, blue: 6, yellow: 7, cyan: 8}
    // *     example 1: array_intersect_ukey ($array1, $array2, function(key1, key2){ return (key1 == key2 ? 0 : (key1 > key2 ? 1 : -1)); });
    // *     returns 1: {blue: 1, green: 3}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var k1 = '', i = 1, arr = {}, k = '';

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i = 1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(k, k1) === 0 ) {
                    if (i === arguments.length-2) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
    
}

function array_key_exists ( key, search ) {
    // Checks if the given key or index exists in the array  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_key_exists
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
    // *     example 1: array_key_exists('kevin', {'kevin': 'van Zonneveld'});
    // *     returns 1: true
    // input sanitation
    if( !search || (search.constructor !== Array && search.constructor !== Object) ){
        return false;
    }

    return key in search;
}

function array_keys( input, search_value, argStrict ) {
    // Return just the keys from the input array, optionally only for the specified search_value  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_keys
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
    // *     returns 1: {0: 'firstname', 1: 'surname'}
    
    var tmp_arr = {}, strict = !!argStrict, include = true, cnt = 0;
    var key = '';
    
    for (key in input) {
        include = true;
        if (search_value != undefined) {
            if( strict && input[key] !== search_value ){
                include = false;
            } else if( input[key] != search_value ){
                include = false;
            }
        }
        
        if (include) {
            tmp_arr[cnt] = key;
            cnt++;
        }
    }
    
    return tmp_arr;
}

function array_map( callback ) {
    // Applies the callback to the elements in given arrays.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_map
    // +   original by: Andrea Giammarchi (http://webreflection.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Takes a function as an argument, not a function's name
    // %        note 2: If the callback is a string, it can only work if the function name is in the global context
    // *     example 1: array_map( function(a){return (a * a * a)}, [1, 2, 3, 4, 5] );
    // *     returns 1: [ 1, 8, 27, 64, 125 ]
    var argc = arguments.length, argv = arguments;
    var j = argv[1].length, i = 0, k = 1, m = 0;
    var tmp = [], tmp_ar = [];

    while (i < j) {
        while (k < argc){
            tmp[m++] = argv[k++][i];
        }

        m = 0;
        k = 1;

        if( callback ){
            if (typeof callback === 'string') {
                callback = this.window[callback];
            }
            tmp_ar[i++] = callback.apply(null, tmp);
        } else{
            tmp_ar[i++] = tmp;
        }

        tmp = [];
    }

    return tmp_ar;
}

function array_merge() {
    // Merges elements from passed arrays into one array  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/array_merge
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Nate
    // -    depends on: is_int
    // %          note: Relies on is_int because !isNaN accepts floats     
    // *     example 1: arr1 = {"color": "red", 0: 2, 1: 4}
    // *     example 1: arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4}
    // *     example 1: array_merge(arr1, arr2)
    // *     returns 1: {"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4}
    // *     example 2: arr1 = []
    // *     example 2: arr2 = {1: "data"}
    // *     example 2: array_merge(arr1, arr2)
    // *     returns 2: {1: "data"}
    
    var args = Array.prototype.slice.call(arguments);
    var retObj = {}, k, j = 0, i = 0;
    var retArr;
    
    for (i=0, retArr=true; i < args.length; i++) {
        if (!(args[i] instanceof Array)) {
            retArr=false;
            break;
        }
    }
    
    if (retArr) {
        return args;
    }
    var ct = 0;
    
    for (i=0, ct=0; i < args.length; i++) {
        if (args[i] instanceof Array) {
            for (j=0; j < args[i].length; j++) {
                retObj[ct++] = args[i][j];
            }
        } else {
            for (k in args[i]) {
                if (this.is_int(k)) {
                    retObj[ct++] = args[i][k];
                } else {
                    retObj[k] = args[i][k];
                }
            }
        }
    }
    
    return retObj;
}

function array_merge_recursive (arr1, arr2){
    // Recursively merges elements from passed arrays into one array  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_merge_recursive
    // +   original by: Subhasis Deb
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: array_merge
    // *     example 1: arr1 = {'color': {'favourite': 'read'}, 0: 5}
    // *     example 1: arr2 = {0: 10, 'color': {'favorite': 'green', 0: 'blue'}}
    // *     example 1: array_merge_recursive(arr1, arr2)
    // *     returns 1: {'color': {'favorite': {0: 'red', 1: 'green'}, 0: 'blue'}, 1: 5, 1: 10}
    var idx = '';

    if ((arr1 && (arr1 instanceof Array)) && (arr2 && (arr2 instanceof Array))) {
        for (idx in arr2) {
            arr1.push(arr2[idx]);
        }
    } else if ((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))) {
        for (idx in arr2) {
            if (idx in arr1) {
                if (typeof arr1[idx] == 'object' && typeof arr2 == 'object') {
                    arr1[idx] = array_merge(arr1[idx], arr2[idx]);
                } else {
                    arr1[idx] = arr2[idx];
                }
            } else {
                arr1[idx] = arr2[idx];
            }
        }
    }
    
    return arr1;
}

function array_multisort(arr) {
    // +   original by: Theriault
    // *     example 1: array_multisort([1, 2, 1, 2, 1, 2], [1, 2, 3, 4, 5, 6]);
    // *     returns 1: true
    // *     example 2: characters = {A: 'Edward', B: 'Locke', C: 'Sabin', D: 'Terra', E: 'Edward'};
    // *     example 2: jobs = {A: 'Warrior', B: 'Thief', C: 'Monk', D: 'Mage', E: 'Knight'};
    // *     example 2: array_multisort(characters, 'SORT_DESC', 'SORT_STRING', jobs, 'SORT_ASC', 'SORT_STRING');
    // *     returns 2: true
    // *     results 2: characters == {D: 'Terra', C: 'Sabin', B: 'Locke', E: 'Edward', A: 'Edward'};
    // *     results 2: jobs == {D: 'Mage', C: 'Monk', B: 'Thief', E: 'Knight', A: 'Warrior'};
    // *     example 3: lastnames = [ 'Carter','Adams','Monroe','Tyler','Madison','Kennedy','Adams'];
    // *     example 3: firstnames = ['James', 'John' ,'James', 'John', 'James',  'John',   'John'];
    // *     example 3: president = [ 39,      6,      5,       10,     4,       35,        2    ];
    // *     example 3: array_multisort(firstnames, 'SORT_DESC', 'SORT_STRING', lastnames, 'SORT_ASC', 'SORT_STRING', president, 'SORT_NUMERIC');
    // *     returns 3: true
    // *     results 3: firstnames == ['John', 'John', 'John',   'John', 'James', 'James',  'James'];
    // *     results 3: lastnames ==  ['Adams','Adams','Kennedy','Tyler','Carter','Madison','Monroe'];
    // *     results 3: president ==  [2,      6,      35,       10,     39,       4,       5];


    // VARIABLE DESCRIPTIONS
    //
    // flags: Translation table for sort arguments. Each argument turns on certain bits in the flag byte through addition.
    //        bits:    HGFE DCBA
    //        bit A: Only turned on if SORT_NUMERIC was an argument.
    //        bit B: Only turned on if SORT_STRING was an argument.
    //        bit C: Reserved bit for SORT_ASC; not turned on.
    //        bit D: Only turned on if SORT_DESC was an argument.
    //        bit E: Turned on if either SORT_REGULAR, SORT_NUMERIC, or SORT_STRING was an argument. If already turned on, function would return FALSE like in PHP.
    //        bit F: Turned on if either SORT_ASC or SORT_DESC was an argument. If already turned on, function would return FALSE like in PHP.
    //        bit G and H: (Unused)
    //
    // sortFlag: Holds sort flag byte of every array argument.
    //
    // sortArrs: Holds the values of array arguments.
    //
    // sortKeys: Holds the keys of object arguments.
    //
    // nLastSort: Holds a copy of the current lastSort so that the lastSort is not destroyed
    //
    // nLastSort: Holds a copy of the current lastSort so that the lastSort is not destroyed
    //
    // args: Holds pointer to arguments for reassignment
    //
    // lastSort: Holds the last Javascript sort pattern to duplicate the sort for the last sortComponent.
    //
    // lastSorts: Holds the lastSort for each sortComponent to duplicate the sort of each component on each array.
    //
    // tmpArray: Holds a copy of the last sortComponent's array elements to reiterate over the array
    //
    // elIndex: Holds the index of the last sortComponent's array elements to reiterate over the array
    //
    // sortDuplicator: Function for duplicating previous sort.
    //
    // sortRegularASC: Function for sorting regular, ascending.
    //
    // sortRegularDESC: Function for sorting regular, descending.
    //
    // thingsToSort: Holds a bit that indicates which indexes in the arrays can be sorted. Updated after every array is sorted.
    var flags = {'SORT_REGULAR': 16, 'SORT_NUMERIC': 17, 'SORT_STRING': 18, 'SORT_ASC': 32, 'SORT_DESC': 40},
    sortArrs = [[]], sortFlag = [0], sortKeys = [[]], g = 0, i = 0, j = 0, k = '', l = 0, thingsToSort = [], vkey = 0, zlast = null,
    args = arguments, nLastSort = [], lastSort = [], lastSorts = [], tmpArray = [], elIndex = 0, sortDuplicator = function (a, b) {
        return nLastSort.shift();
    };
    var sortFunctions = [[function (a, b) {
        lastSort.push(a > b ? 1 : (a < b ? -1 : 0));
        return a > b ? 1 : (a < b ? -1 : 0);
    }, function (a, b) {
        lastSort.push(b > a ? 1 : (b < a ? -1 : 0));
        return b > a ? 1 : (b < a ? -1 : 0);
    }], [function (a, b) {
        lastSort.push(a - b);
        return a - b;
    }, function (a, b) {
        lastSort.push(b - a);
        return b - a;
    }], [function (a, b) {
        lastSort.push((a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0));
        return (a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0);
    }, function (a, b) {
        lastSort.push((b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0));
        return (b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0);
    }]];

    // Store first argument into sortArrs and sortKeys if an Object.
    // First Argument should be either a Javascript Array or an Object, otherwise function would return FALSE like in PHP
    if (arr instanceof Array) {
        sortArrs[0] = arr;
    }
    else if (arr instanceof Object) {
        for (i in arr) {
            if (arr.hasOwnProperty(i)) {
                sortKeys[0].push(i);
                sortArrs[0].push(arr[i]);
            }
        }
    }
    else {
        return false;
    }


    // arrMainLength: Holds the length of the first array. All other arrays must be of equal length, otherwise function would return FALSE like in PHP
    //
    // sortComponents: Holds 2 indexes per every section of the array that can be sorted. As this is the start, the whole array can be sorted.
    var arrMainLength = sortArrs[0].length, sortComponents = [0, arrMainLength];

    // Loop through all other arguments, checking lengths and sort flags of arrays and adding them to the above variables.
    for (j = 1; j < arguments.length; j++) {
        if (arguments[j] instanceof Array) {
            sortArrs[j] = arguments[j];
            sortFlag[j] = 0;
            if (arguments[j].length !== arrMainLength) {
                return false;
            }
        } else if (arguments[j] instanceof Object) {
            sortKeys[j] = [];
            sortArrs[j] = [];
            sortFlag[j] = 0;
            for (i in arguments[j]) {
                if (arguments[j].hasOwnProperty(i)) {
                    sortKeys[j].push(i);
                    sortArrs[j].push(arguments[j][i]);
                }
            }
            if (sortArrs[j].length !== arrMainLength) {
                return false;
            }
        } else if (typeof arguments[j] === 'string') {
            var lFlag = sortFlag.pop();
            if (typeof flags[arguments[j]] === 'undefined' || (((flags[arguments[j]] >>> 4) & (lFlag >>> 4)) > 0)) {
                return false;
            }
            sortFlag.push(lFlag + flags[arguments[j]]);
        } else {
            return false;
        }
    }


    for (i = 0; i !== arrMainLength; i++) {
        thingsToSort.push(true);
    }

    // Sort all the arrays....
    for (i in sortArrs) {
        if (sortArrs.hasOwnProperty(i)) {
            lastSorts = [];
            tmpArray = [];
            elIndex = 0;
            nLastSort = [];
            lastSort = [];

            // If ther are no sortComponents, then no more sorting is neeeded. Copy the array back to the argument.
            if (sortComponents.length === 0) {
                if (arguments[i] instanceof Array) {
                    args[i] = sortArrs[i];
                }
                else {
                    for (k in arguments[i]) {
                        if (arguments[i].hasOwnProperty(k)) {
                            delete arguments[i][k];
                        }
                    }
                    for (j = 0, vkey = 0; j < sortArrs[i].length; j++) {
                        vkey = sortKeys[i][j];
                        args[i][vkey] = sortArrs[i][j];
                    }
                }
                delete sortArrs[i];
                delete sortKeys[i];
                continue;
            }

            // Sort function for sorting. Either sorts asc or desc, regular/string or numeric.
            var sFunction = sortFunctions[(sortFlag[i] & 3)][((sortFlag[i] & 8) > 0) ? 1 : 0];

            // Sort current array.
            for (l = 0; l !== sortComponents.length; l += 2) {
                tmpArray = sortArrs[i].slice(sortComponents[l], sortComponents[l + 1] + 1);
                tmpArray.sort(sFunction);
                lastSorts[l] = [].concat(lastSort); // Is there a better way to copy an array in Javascript?
                elIndex = sortComponents[l];
                for (g in tmpArray) {
                    if (tmpArray.hasOwnProperty(g)) {
                        sortArrs[i][elIndex] = tmpArray[g];
                        elIndex++;
                    }
                }
            }

            // Duplicate the sorting of the current array on future arrays.
            sFunction = sortDuplicator;
            for (j in sortArrs) {
                if (sortArrs.hasOwnProperty(j)) {
                    if (sortArrs[j] === sortArrs[i]) {
                        continue;
                    }
                    for (l = 0; l !== sortComponents.length; l += 2) {
                        tmpArray = sortArrs[j].slice(sortComponents[l], sortComponents[l + 1] + 1);
                        nLastSort = [].concat(lastSorts[l]); // alert(l + ':' + nLastSort);
                        tmpArray.sort(sFunction);
                        elIndex = sortComponents[l];
                        for (g in tmpArray) {
                            if (tmpArray.hasOwnProperty(g)) {
                                sortArrs[j][elIndex] = tmpArray[g];
                                elIndex++;
                            }
                        }
                    }
                }
            }

            // Duplicate the sorting of the current array on array keys
            for (j in sortKeys) {
                if (sortKeys.hasOwnProperty(j)) {
                    for (l = 0; l !== sortComponents.length; l += 2) {
                        tmpArray = sortKeys[j].slice(sortComponents[l], sortComponents[l + 1] + 1);
                        nLastSort = [].concat(lastSorts[l]);
                        tmpArray.sort(sFunction);
                        elIndex = sortComponents[l];
                        for (g in tmpArray) {
                            if (tmpArray.hasOwnProperty(g)) {
                                sortKeys[j][elIndex] = tmpArray[g];
                                elIndex++;
                            }
                        }
                    }
                }
            }

            // Generate the next sortComponents
            zlast = null;
            sortComponents = [];
            for (j in sortArrs[i]) {
                if (sortArrs[i].hasOwnProperty(j)) {
                    if (!thingsToSort[j]) {
                        if ((sortComponents.length & 1)) {
                            sortComponents.push(j - 1);
                        }
                        zlast = null;
                        continue;
                    }
                    if (!(sortComponents.length & 1)) {
                        if (zlast !== null) {
                            if (sortArrs[i][j] === zlast) {
                                sortComponents.push(j - 1);
                            }
                            else {
                                thingsToSort[j] = false;
                            }
                        }
                        zlast = sortArrs[i][j];
                    } else {
                        if (sortArrs[i][j] !== zlast) {
                            sortComponents.push(j - 1);
                            zlast = sortArrs[i][j];
                        }
                    }
                }
            }

            if (sortComponents.length & 1) {
                sortComponents.push(j);
            }
            if (arguments[i] instanceof Array) {
                args[i] = sortArrs[i];
            }
            else {
                for (j in arguments[i]) {
                    if (arguments[i].hasOwnProperty(j)) {
                        delete arguments[i][j];
                    }
                }
                for (j = 0, vkey = 0; j < sortArrs[i].length; j++) {
                    vkey = sortKeys[i][j];
                    args[i][vkey] = sortArrs[i][j];
                }

            }
            delete sortArrs[i];
            delete sortKeys[i];
        }
    }
    return true;
}

function array_pad ( input, pad_size, pad_value ) {
    // Returns a copy of input array padded with pad_value to size pad_size  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_pad
    // +   original by: Waldo Malqui Silva
    // *     example 1: array_pad([ 7, 8, 9 ], 2, 'a');
    // *     returns 1: [ 7, 8, 9]
    // *     example 2: array_pad([ 7, 8, 9 ], 5, 'a');
    // *     returns 2: [ 7, 8, 9, 'a', 'a']
    // *     example 3: array_pad([ 7, 8, 9 ], 5, 2);
    // *     returns 3: [ 7, 8, 9, 2, 2]
    // *     example 4: array_pad([ 7, 8, 9 ], -5, 'a');
    // *     returns 4: [ 'a', 'a', 7, 8, 9 ]
    var pad = [], newArray = [], newLength, i=0;

    if ( input instanceof Array && !isNaN( pad_size ) ) {
        newLength = ( ( pad_size < 0 ) ? ( pad_size * -1 ) : pad_size );
        if ( newLength > input.length ) {
            for ( i = 0; i < ( newLength - input.length ); i++ ) { newArray [ i ] = pad_value; }
            pad = ( ( pad_size < 0 ) ? newArray.concat( input ) : input.concat( newArray ) );
        } else {
            pad = input;
        }
    }

    return pad;
}

function array_pop( array ) {
    // Pops an element off the end of the array  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_pop
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_pop([0,1,2]);
    // *     returns 1: 2
    // *     example 2: data = {firstName: 'Kevin', surName: 'van Zonneveld'};
    // *     example 2: lastElem = array_pop(data);
    // *     returns 2: 'van Zonneveld'
    // *     results 2: data == {firstName: 'Kevin'}
    var key = '', cnt = 0;

    if (array.hasOwnProperty('length')) {
        // Indexed
        if( !array.length ){
            // Done popping, are we?
            return null;
        }
        return array.pop();
    } else {
        // Associative
        for (key in array) {
            cnt++;
        }
        if (cnt) {
            delete(array[key]);
            return array[key];
        } else {
            return null;
        }
    }
}

function array_product ( input ) {
    // Returns the product of the array entries  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_product
    // +   original by: Waldo Malqui Silva
    // *     example 1: array_product([ 2, 4, 6, 8 ]);
    // *     returns 1: 384
    var Index = 0, product = 1;
    if ( input instanceof Array ) {
        while ( Index < input.length ) {
            product *= ( !isNaN( input [ Index ] ) ? input [ Index ] : 0 );
            Index++;
        }
    } else {
        product = null;
    }

    return product;
}

function array_push ( array ) {
    // Pushes elements onto the end of the array  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_push
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_push(['kevin','van'], 'zonneveld');
    // *     returns 1: 3
    var i, argv = arguments, argc = argv.length;

    for (i=1; i < argc; i++){
        array[array.length++] = argv[i];
    }

    return array.length;
}

function array_rand ( input, num_req ) {
    // Return key/keys for random entry/entries in the array  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_rand
    // +   original by: Waldo Malqui Silva
    // *     example 1: array_rand( ['Kevin'], 1 );
    // *     returns 1: 0
    var indexes = [];
    var ticks = num_req || 1;
    var checkDuplicate = function ( input, value ) {
        var exist = false, index = 0;
        while ( index < input.length ) {
            if ( input [ index ] === value ) {
                exist = true;
                break;
            }
            index++;
        }
        return exist;
    };

    if ( input instanceof Array && ticks <= input.length ) {
        while ( true ) {
            var rand = Math.floor( ( Math.random( ) * input.length ) );
            if ( indexes.length === ticks ) { break; }
            if ( !checkDuplicate( indexes, rand ) ) { indexes.push( rand ); }
        }
    } else {
        indexes = null;
    }

    return ( ( ticks == 1 ) ? indexes.join( ) : indexes );
}

function array_reduce( a_input, callback ) {
    // Iteratively reduce the array to a single value via the callback.  
    // 
    // version: 903.2116
    // discuss at: http://phpjs.org/functions/array_reduce
    // +   original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
    // %        note 1: Takes a function as an argument, not a function's name
    // *     example 1: array_reduce([1, 2, 3, 4, 5], function(v, w){v += w;return v;});
    // *     returns 1: 15
    
    var lon = a_input.length;
    var res = 0, i = 0;
    var tmp = [];

    
    for(i = 0; i < lon; i+=2 ) {
        tmp[0] = a_input[i];
        if(a_input[(i+1)]){
            tmp[1] = a_input[(i+1)];
        } else {
            tmp[1] = 0;
        }
        res+= callback.apply(null, tmp);
        tmp = [];
    }
    
    return res;
}

function array_reverse(array, preserve_keys) {
    // Return input as a new array with the order of the entries reversed  
    // 
    // version: 812.3017
    // discuss at: http://phpjs.org/functions/array_reverse
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Karol Kowalski
    // *     example 1: array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);
    // *     returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}
    var arr_len = array.length, newkey = 0, tmp_arr = {}, key = '';
    preserve_keys = !!preserve_keys;
    
    for (key in array) {
        newkey = arr_len - key - 1;
        tmp_arr[preserve_keys ? key : newkey] = array[key];
    }

    return tmp_arr;
}

function array_search( needle, haystack, argStrict ) {
    // Searches the array for a given value and returns the corresponding key if successful  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/array_search
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
    // *     returns 1: 'surname'

    var strict = !!argStrict;
    var key = '';

    for(key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
            return key;
        }
    }

    return false;
}

function array_shift( array ) {
    // Pops an element off the beginning of the array  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_shift
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Martijn Wieringa
    // *     example 1: array_shift(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin'
    if (array.length > 0) {
        return array.shift();
    }
    
    return null;
}

function array_slice(arr, offst, lgth, preserve_keys) {
    // Returns elements specified by offset and length  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/array_slice
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: is_int
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: Relies on is_int because !isNaN accepts floats 
    // *     example 1: array_slice(["a", "b", "c", "d", "e"], 2, -1);
    // *     returns 1: {0: 'c', 1: 'd'}
    // *     example 2: array_slice(["a", "b", "c", "d", "e"], 2, -1, true);
    // *     returns 2: {2: 'c', 3: 'd'}
    /*
    if ('callee' in arr && 'length' in arr) {
        arr = Array.prototype.slice.call(arr);
    }
    */
   
    var key = '';

    if (!(arr instanceof Array) || (preserve_keys && offst != 0)) { // Assoc. array as input or if required as output
        var lgt =0, newAssoc = {};
        for (key in arr) {
            //if (key !== 'length') {
            lgt += 1;
            newAssoc[key] = arr[key];
            //}
        }
        arr = newAssoc;
		
        offst = (offst < 0) ? lgt + offst : offst;
        lgth  = lgth == undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth;
		
        var assoc = {};
        var start = false, it=-1, arrlgth=0, no_pk_idx=0;
        for (key in arr) {
            ++it;
            if (arrlgth >= lgth) {
                break;
            }
            if (it == offst){
                start = true;
            }
            if (!start) {
                continue;
            }
            ++arrlgth;
            if (this.is_int(key) && !preserve_keys) {
                assoc[no_pk_idx++] = arr[key];
            } else {
                assoc[key] = arr[key];
            }
        }
        //assoc.length = arrlgth; // Make as array-like object (though length will not be dynamic)
        return assoc;
    }
    
    if (lgth === undefined) {
        return arr.slice(offst);    
    } else if (lgth >= 0) {
        return arr.slice(offst, offst + lgth);
    } else {
        return arr.slice(offst, lgth);
    }
}

function array_splice (arr, offst, lgth, replacement) {
    // Removes the elements designated by offset and length and replace them with supplied array  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/array_splice
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Order does get shifted in associative array input with numeric indices,
    // %        note 1: since PHP behavior doesn't preserve keys, but I understand order is not reliable anyways
    // -    depends on: is_int
    // *     example 1: input = {4: "red", 'abc': "green", 2: "blue", 'dud': "yellow"};
    // *     example 1: array_splice(input, 2);
    // *     returns 1: {0: "blue", 'dud': "yellow"}
    // *     results 1: input == {'abc':"green", 0:"red"}
    // *     example 2: input = ["red", "green", "blue", "yellow"];
    // *     example 2: array_splice(input, 3, 0, "purple");
    // *     returns 2: []
    // *     results 2: input == ["red", "green", "blue", "purple", "yellow"]
    // *     example 3: input = ["red", "green", "blue", "yellow"]
    // *     example 3: array_splice(input, -1, 1, ["black", "maroon"]);
    // *     returns 3: ["yellow"]
    // *     results 3: input == ["red", "green", "blue", "black", "maroon"]
    
    var checkToUpIndices = function (arr, ct, key) {
        // Deal with situation, e.g., if encounter index 4 and try to set it to 0, but 0 exists later in loop (need to
        // increment all subsequent (skipping current key, since we need its value below) until find unused)
        if (arr[ct] !== undefined) {
            var tmp = ct;
            ct += 1;
            if (ct === key) {
                ct += 1;
            }
            ct = checkToUpIndices(arr, ct, key);
            arr[ct] = arr[tmp];
            delete arr[tmp];
        }
        return ct;
    };

    if (replacement && !(typeof replacement === 'object')) {
        replacement = [replacement];
    }
    if (lgth === undefined) {
        lgth = offst >= 0 ? arr.length - offst : -offst;
    } else if (lgth < 0) {
        lgth = (offst >= 0 ? arr.length - offst : -offst)  + lgth;
    }

    if (!(arr instanceof Array)) {
        /*if (arr.length !== undefined) { // Deal with array-like objects as input
        delete arr.length;
        }*/
        var lgt = 0, ct = -1, rmvd = [], rmvdObj = {}, repl_ct=-1, int_ct=-1;
        var returnArr = true, rmvd_ct = 0, rmvd_lgth = 0, key = '';
        // rmvdObj.length = 0;
        for (key in arr) { // Can do arr.__count__ in some browsers
            lgt += 1;
        }
        offst = (offst >= 0) ? offst : lgt + offst;
        for (key in arr) {
            ct += 1;
            if (ct < offst) {
                if (this.is_int(key)) {
                    int_ct += 1;
                    if (parseInt(key, 10) === int_ct) { // Key is already numbered ok, so don't need to change key for value
                        continue;
                    }
                    checkToUpIndices(arr, int_ct, key); // Deal with situation, e.g.,
                    // if encounter index 4 and try to set it to 0, but 0 exists later in loop
                    arr[int_ct] = arr[key];
                    delete arr[key];
                }
                continue;
            }
            if (returnArr && this.is_int(key)) {
                rmvd.push(arr[key]);
                rmvdObj[rmvd_ct++] = arr[key]; // PHP starts over here too
            } else {
                rmvdObj[key] = arr[key];
                returnArr    = false;
            }
            rmvd_lgth += 1;
            // rmvdObj.length += 1;

            if (replacement && replacement[++repl_ct]) {
                arr[key] = replacement[repl_ct];
            } else {
                delete arr[key];
            }
        }
        // arr.length = lgt - rmvd_lgth + (replacement ? replacement.length : 0); // Make (back) into an array-like object
        return returnArr ? rmvd : rmvdObj;
    }

    if (replacement) {
        replacement.unshift(offst, lgth);
        return Array.prototype.splice.apply(arr, replacement);
    }
    return arr.splice(offst, lgth);
}

function array_sum( array ) {
    // Returns the sum of the array entries  
    // 
    // version: 901.617
    // discuss at: http://phpjs.org/functions/array_sum
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +   bugfixed by: Gilbert
    // *     example 1: array_sum([4, 9, 182.6]);
    // *     returns 1: 195.6
    // *     example 2: total = []; index = 0.1; for(y=0; y < 12; y++){total[y] = y + index;}
    // *     example 2: array_sum(total);
    // *     returns 2: 67.2
    var key, sum = 0;
    
    // input sanitation
    if (typeof array !== 'object') {
        return null;
    }
    
    for (key in array) {
        //tester_print_r(typeof sum);
        sum += (array[key] * 1);
    }

    return sum;
}

function array_udiff() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_udiff
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_udiff($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {c: 'blue'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var arr = '', i = 1, k1 = '', k = '';
    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        for (i=1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(arr[k], arr1[k1]) === 0) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_udiff_assoc() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Entries are compared by user supplied function.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_udiff_assoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: array_udiff_assoc({0: 'kevin', 1: 'van', 2: 'Zonneveld'}, {0: 'Kevin', 4: 'van', 5: 'Zonneveld'}, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {1: 'van', 2: 'Zonneveld'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var arr = {}, i = 1, k1 = '', k = '';
    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        for (i=1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(arr[k], arr1[k1]) === 0 && k === k1) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_udiff_uassoc () {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_udiff_uassoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_udiff_uassoc($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;}, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {0: 'red', c: 'blue'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1], cb0 = arguments[arguments.length-2];
    var k1 = '', i = 1, k = '', arr = {};

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;
    cb0 = (typeof cb0 === 'string') ? this.window[cb0] : (cb0 instanceof Array) ? this.window[cb0[0]][cb0[1]] : cb0;

    arr1keys:
    for (k1 in arr1) {
        for (i=1; i < arguments.length-2; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb0(arr[k], arr1[k1]) === 0 && cb(k, k1) === 0) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys; 
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_uintersect () {
    // Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_uintersect
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_uintersect($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {a: 'green', b: 'brown', 0: 'red'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var k1 = '', i = 1, arr = {}, k = '';

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:  
    for (k1 in arr1) {
        arrs:
        for (i = 1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(arr[k], arr1[k1]) === 0 ) {
                    if (i === arguments.length-2) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_uintersect_assoc () {
    // Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_uintersect_assoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_uintersect_assoc($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {a: 'green', b: 'brown'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1];
    var k1 = '', i = 1, arr = {}, k = '';

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i = 1; i < arguments.length-1; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb(arr[k], arr1[k1]) === 0 && k === k1) {
                    if (i === arguments.length-2) {
                        retArr[k1] = arr1[k1];
                    }
                    // If the innermost loop always leads at least once to an equal value, continue the loop until done
                    continue arrs;
                }
            }
            // If it reaches here, it wasn't found in at least one array, so try next value
            continue arr1keys;
        }
    }

    return retArr;
}

function array_uintersect_uassoc () {
    // Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/array_uintersect_uassoc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
    // *     example 1: $array2 = {a: 'GREEN', B: 'brown', 0: 'yellow', 1: 'red'}
    // *     example 1: array_uintersect_uassoc($array1, $array2, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;}, function(f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if(string1 > string2) return 1; if(string1 == string2) return 0; return -1;});
    // *     returns 1: {a: 'green', b: 'brown'}
    var arr1 = arguments[0], retArr = {}, cb = arguments[arguments.length-1], cb0 = arguments[arguments.length-2];
    var k1 = '', i = 1, k = '', arr = {};

    cb = (typeof cb === 'string') ? this.window[cb] : (cb instanceof Array) ? this.window[cb[0]][cb[1]] : cb;
    cb0 = (typeof cb0 === 'string') ? this.window[cb0] : (cb0 instanceof Array) ? this.window[cb0[0]][cb0[1]] : cb0;

    arr1keys:
    for (k1 in arr1) {
        arrs:
        for (i = 1; i < arguments.length-2; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (cb0(arr[k], arr1[k1]) === 0 && cb(k, k1) === 0) {
                    if (i === arguments.length-3) {
                        retArr[k1] = arr1[k1];
                    }
                    continue arrs; // If the innermost loop always leads at least once to an equal value, continue the loop until done
                }
            }
            continue arr1keys; // If it reaches here, it wasn't found in at least one array, so try next value
        }
    }

    return retArr;
}

function array_unique( array ) {
    // Removes duplicate values from array  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_unique
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael Grier
	// %          note 1: the second argument, sort_flags is not implemented
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {'a': 'green', 0: 'red', 1: 'blue'}
    
    var key = '', tmp_arr1 = {}, tmp_arr2 = {};
    var val = '';
    tmp_arr1 = array;
    
    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if ((haystack[fkey] + '') === (needle + '')) {
                return fkey;
            }
        }
        return false;
    };
	
    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }
        
        delete tmp_arr1[key];
    }
    
    return tmp_arr2;
}

function array_unshift( array ) {
    // Pushes elements onto the beginning of the array  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_unshift
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Martijn Wieringa
    // *     example 1: array_unshift(['van', 'Zonneveld'], 'Kevin');
    // *     returns 1: 3
    var argc = arguments.length, argv = arguments, i;
    
    for (i = 1; i < argc; i++) {
        array.unshift(argv[i]);
    }
    
    return (array.length);
}

function array_values( input ) {
    // Return just the values from the input array  
    // 
    // version: 903.2116
    // discuss at: http://phpjs.org/functions/array_values
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_values( {firstname: 'Kevin', surname: 'van Zonneveld'} );
    // *     returns 1: {0: 'Kevin', 1: 'van Zonneveld'}
    var tmp_arr = [], cnt = 0;
    var key = '';

    for ( key in input ){
        tmp_arr[cnt] = input[key];
        cnt++;
    }

    return tmp_arr;
}

function array_walk (array, funcname, userdata) {
    // Apply a user function to every member of an array  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_walk
    // +   original by: Johnny Mast (http://www.phpvrouwen.nl)
    // *     example 1: array_walk ({'a':'b'}, 'void', 'userdata');
    // *     returns 1: true
    // *     example 2: array_walk ('a', 'void', 'userdata');
    // *     returns 2: false
    
    var key; 
    
    if (typeof array != 'object') {
        return false;
    }
    
    for (key in array) {
        if (typeof(userdata) != 'undefined') {
            eval(funcname + '( array [key] , key , userdata  )' );
        } else {
            eval(funcname + '(  userdata ) ');
        }
    }
    
    return true;
}

function array_walk_recursive (array, funcname, userdata) {
    // Apply a user function recursively to every member of an array  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/array_walk_recursive
    // +   original by: Johnny Mast (http://www.phpvrouwen.nl)
    // *     example 1: array_walk_recursive ({'a': 'b', 'c': {'d': 'e'}}, 'void', 'userdata');
    // *     returns 1: true
    // *     example 2: array_walk_recursive ('a', 'void', 'userdata');
    // *     returns 2: false
    
    var key;
    
    if (typeof array != 'object'){
        return false;
    }
 
    for (key in array) {            
        if (typeof array[key] == 'object') { 
            return this.array_walk_recursive(array [key], funcname, userdata);
        }
        
        if (typeof (userdata) != 'undefined') {
            eval(funcname + '( array [key] , key , userdata  )');
        } else {
            eval(funcname + '(  userdata ) ');
        }
    }
    
    return true;
}

function arsort(inputArr, sort_flags) {
    // Sort an array in reverse order and maintain index association  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/arsort
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: SORT_STRING (as well as natsort and natcasesort) might also be
    // %        note 1: integrated into all of these functions by adapting the code at
    // %        note 1: http://sourcefrog.net/projects/natsort/natcompare.js
    // %        note 2: The examples are correct, this is a new way
    // %        note 2: Credits to: http://javascript.internet.com/math-related/bubble-sort.html
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: asort(data);
    // *     results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
    // *     returns 1: true
    var valArr=[], keyArr=[], k, i, ret, sorter, that = this;

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(b, a);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(b.localeCompare(a));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
                return 0;
            };
            break;
    }

    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {
                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret > 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k];
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;
    }

    // Repopulate the old array
    for (i = 0; i < valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];
    }

    return true;
}

function asin(arg) {
    // Returns the arc sine of the number in radians  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/asin
    // +   original by: Onno Marsman
    // *     example 1: asin(0.3);
    // *     returns 1: 0.3046926540153975
    return Math.asin(arg);
}

function asinh(arg) {
    // Returns the inverse hyperbolic sine of the number, i.e. the value whose hyperbolic sine is number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/asinh
    // +   original by: Onno Marsman
    // *     example 1: asinh(8723321.4);
    // *     returns 1: 16.67465779841863
    return Math.log(arg + Math.sqrt(arg*arg+1));
}

function asort(inputArr, sort_flags) {
    // Sort an array and maintain index association  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/asort
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: SORT_STRING (as well as natsort and natcasesort) might also be
    // %        note 1: integrated into all of these functions by adapting the code at
    // %        note 1: http://sourcefrog.net/projects/natsort/natcompare.js
    // %        note 2: The examples are correct, this is a new way
    // %        note 2: Credits to: http://javascript.internet.com/math-related/bubble-sort.html
    // -    depends on: strnatcmp
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: asort(data);
    // *     results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
    // *     returns 1: true
    var valArr=[], keyArr=[], k, i, ret, sorter, that = this;

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(a.localeCompare(b));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
                return 0;
            };
            break;
    }

    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {
                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret < 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k];
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;
    }

    // Repopulate the old array
    for (i = 0; i < valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];
    }

    return true;
}

function assert (assertion) {
    // Checks if assertion is false  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/assert
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note 1: Do not pass untrusted user input to assert() in string form (you can test it beforehand though)
    // %          note 2: Does not provide perfect arguments to the assertion callback, as far as file location or line number
    // *     example 1: assert('false === true');
    // *     returns 1: false

    var result = false, callback, retVal, err=undefined;

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.assert_values) {
        this.php_js.assert_values = {};
    }
    if (!this.php_js.ini) {
        this.php_js.ini = {};
    }
    // END REDUNDANT

    var getOption = function (value) {
        if (this.php_js.assert_values[value]) {
            return this.php_js.assert_values[value];
        }
        if (this.php_js.ini[value]) {
            return this.php_js.ini[value].local_value;
        }
        switch(value) {
            case 'assert.active':
                return 1;
            case 'assert.warning': // Don't need this now
                //return 1;
                throw 'We have not yet implemented warnings in JavaScript (assert())';
            case 'assert.bail':
                return 0;
            case 'assert.quiet_eval':
                return 0;
            case 'assert.callback':
                return null;
            default:
                throw 'There was some problem';
        }
    };

    if (!getOption('assert.active')) {
        return false; // is this correct? should callbacks still execute? Should still bail if on?
    }

    try { // Less overhead to use string when assertion checking is off, allows message of exact code to callback
        result = typeof assertion === 'string' ? eval(assertion) : assertion;
    }
    catch(e) {
        if (!getOption('assert.quiet_eval')) {
            throw e;
        }
        err = e;
        result = false;
    }
    retVal = result !== false; // return false if false, otherwise, return true
    if (retVal === false) {
        if (getOption('assert.bail')) { // Todo: Will the function bail before a callback or after?
            throw 'Assertion bailed'; // No way to bail without throwing an exception (and there are no "warnings" in JavaScript for us to throw)
        }
        callback = getOption('assert.callback');
        if (typeof callback === 'string') {
            callback = this.window[callback];
        }
        // Not perfect for file location (might also use __FILE__()) or line number
        callback(this.window.location.href, err && err.lineNumber, (typeof assertion === 'string' ? assertion : '')); // From the docs, what does this mean?: "the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)"
    }
    return retVal;
}

function assert_options (what, value) {
    // Set/get the various assert flags  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/assert_options
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: assert_options('ASSERT_CALLBACK');
    // *     returns 1: null
    
    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.assert_values) {
        this.php_js.assert_values = {};
    }
    if (!this.php_js.ini) {
        this.php_js.ini = {};
    }
    // END REDUNDANT

    var ini, dflt;
    switch(what) {
        case 'ASSERT_ACTIVE':
            ini = 'assert.active';
            dflt = 1;
            break;
        case 'ASSERT_WARNING':
            ini = 'assert.warning';
            dflt = 1;
            throw 'We have not yet implemented warnings for us to throw in JavaScript (assert_options())';
        case 'ASSERT_BAIL':
            ini = 'assert.bail';
            dflt = 0;
            break;
        case 'ASSERT_QUIET_EVAL':
            ini = 'assert.quiet_eval';
            dflt = 0;
            break;
        case 'ASSERT_CALLBACK':
            ini = 'assert.callback';
            dflt = null;
            break;
        default:
            throw 'Improper type for assert_options()';
    }
    // I presume this is to be the most recent value, instead of the default value
    var originalValue = this.php_js.assert_values[ini] || (this.php_js.ini[ini] && this.php_js.ini[ini].local_value) || dflt;

    if (value) {
        this.php_js.assert_values[ini] = value; // We use 'ini' instead of 'what' as key to be more convenient for assert() to test for current value
    }
    return originalValue;
}

function atan(arg) {
    // Returns the arc tangent of the number in radians  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/atan
    // +   original by: Onno Marsman
    // *     example 1: atan(8723321.4);
    // *     returns 1: 1.5707962121596615
    return Math.atan(arg);
}

function atan2(y, x) {
    // Returns the arc tangent of y/x, with the resulting quadrant determined by the signs of y and x  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/atan2
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: atan2(1, 1);
    // *     returns 1: 0.7853981633974483
    return Math.atan2(y, x);
}

function atanh(arg) {
    // Returns the inverse hyperbolic tangent of the number, i.e. the value whose hyperbolic tangent is number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/atanh
    // +   original by: Onno Marsman
    // *     example 1: atanh(0.3);
    // *     returns 1: 0.3095196042031118
    return 0.5 * Math.log((1+arg)/(1-arg));
}

function base64_decode( data ) {
    // Decodes string using MIME base64 algorithm  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/base64_decode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}

function base64_encode( data ) {
    // Encodes string using MIME base64 algorithm  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/base64_encode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}

function base_convert(number, frombase, tobase) {
    // Converts a number in a string from any base <= 36 to any base <= 36  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/base_convert
    // +   original by: Philippe Baumann
    // *     example 1: base_convert('A37334', 16, 2);
    // *     returns 1: '101000110111001100110100'
    return parseInt(number+'', frombase+0).toString(tobase+0);
}

function basename(path, suffix) {
    // Returns the filename component of the path  
    // 
    // version: 812.316
    // discuss at: http://phpjs.org/functions/basename
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Lincoln Ramsay
    // +   improved by: djmix
    // *     example 1: basename('/www/site/home.htm', '.htm');
    // *     returns 1: 'home'
    var b = path.replace(/^.*[\/\\]/g, '');
    
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    
    return b;
}

function bin2hex(s){
    // Converts the binary representation of data to hex  
    // 
    // version: 903.421
    // discuss at: http://phpjs.org/functions/bin2hex
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Linuxworld
    // *     example 1: bin2hex('Kev');
    // *     returns 1: '4b6576'
    // *     example 2: bin2hex(String.fromCharCode(0x00));
    // *     returns 2: '00'
    var i, f = 0, a = [];
    
    s += '';
    f = s.length;
    
    for (i = 0; i<f; i++) {
        a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
    }
    
    return a.join('');
}

function bindec (binary_string) {
    // Returns the decimal equivalent of the binary number  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/bindec
    // +   original by: Philippe Baumann
    // *     example 1: bindec('110011');
    // *     returns 1: 51
    // *     example 2: bindec('000110011');
    // *     returns 2: 51
    // *     example 3: bindec('111');
    // *     returns 3: 7
    binary_string = (binary_string+'').replace(/[^01]/gi, '');
    return parseInt(binary_string, 2);
}

function call_user_func(cb, parameters) {
    // Call a user function which is the first parameter  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/call_user_func
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: call_user_func('isNaN', 'a');
    // *     returns 1: true
    var func;
 
    if (typeof cb == 'string') {
        if (typeof this[cb] == 'function') {
            func = this[cb];
        } else {
            func = (new Function(null, 'return ' + cb))();
        }
    } else if (cb instanceof Array) {
        func = eval(cb[0]+"['"+cb[1]+"']");
    }
    
    if (typeof func != 'function') {
        throw new Error(func + ' is not a valid function');
    }

    return func.apply(null, Array.prototype.slice.call(parameters, 1));
}

function call_user_func_array(cb, parameters) {
    // Call a user function which is the first parameter with the arguments contained in array  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/call_user_func_array
    // +   original by: Thiago Mata (http://thiagomata.blog.com)
    // +   revised  by: Jon Hohle
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: call_user_func_array('isNaN', ['a']);
    // *     returns 1: true
    // *     example 2: call_user_func_array('isNaN', [1]);
    // *     returns 2: false
    var func;

    if (typeof cb == 'string') {
        if (typeof this[cb] == 'function') {
            func = this[cb];
        } else {
            func = (new Function(null, 'return ' + cb))();
        }
    } else if (cb instanceof Array) {
        func = eval(cb[0]+"['"+cb[1]+"']");
    }
    
    if (typeof func != 'function') {
        throw new Error(func + ' is not a valid function');
    }

    return func.apply(null, parameters);
}

function ceil(value) {
    // Returns the next highest integer value of the number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/ceil
    // +   original by: Onno Marsman
    // *     example 1: ceil(8723321.4);
    // *     returns 1: 8723322
    return Math.ceil(value);
}

function checkdate( month, day, year ) {
    // Returns true(1) if it is a valid date in gregorian calendar  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/checkdate
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Pyerre
    // *     example 1: checkdate(12, 31, 2000);
    // *     returns 1: true
    // *     example 2: checkdate(2, 29, 2001);
    // *     returns 2: false
    // *     example 3: checkdate(03, 31, 2008);
    // *     returns 3: true
    // *     example 4: checkdate(1, 390, 2000);
    // *     returns 4: false
    var myDate = new Date();
    myDate.setFullYear( year, (month - 1), day );

    return ((myDate.getMonth()+1) == month && day<32); 
}

function chop ( str, charlist ) {
    // !No description available for chop. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/chop
    // +   original by: Paulo Ricardo F. Santos
    // -    depends on: rtrim
    // *     example 1: rtrim('    Kevin van Zonneveld    ');
    // *     returns 1: '    Kevin van Zonneveld'
    return this.rtrim(str, charlist);
}

function chr( codePt ) {
    // Converts a codepoint number to a character  
    // 
    // version: 905.1411
    // discuss at: http://phpjs.org/functions/chr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: chr(75);
    // *     returns 1: 'K'
    // *     example 1: chr(65536) === '\uD800\uDC00';
    // *     returns 1: true
    
    if (codePt > 0xFFFF) { // Create a four-byte string (length 2) since this code point is high
                                             //   enough for the UTF-16 encoding (JavaScript internal use), to
                                             //   require representation with two surrogates (reserved non-characters
                                             //   used for building other characters; the first is "high" and the next "low")
        codePt -= 0x10000;
        return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
    }
    else {
        return String.fromCharCode(codePt);
    }
}

function chunk_split(body, argChunklen, argEnd) {
    // Returns split line  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/chunk_split
    // +   original by: Paulo Ricardo F. Santos
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: chunk_split('Hello world!', 1, '*');
    // *     returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
    // *     example 2: chunk_split('Hello world!', 10, '*');
    // *     returns 2: 'Hello worl*d!*'
    
    var result = '', chunklen = argChunklen || 76, end = argEnd || '\r\n';

    if (chunklen < 1) {
        return false;
    }

    while (body.length > chunklen) {
        result += body.substring(0, chunklen) + end;
        body = body.substring(chunklen);
    }

    return result + body + end;
}

function class_exists (cls) {
    // Checks if the class exists  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/class_exists
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function class_a() {this.meth1 = function() {return true;}};
    // *     example 1: var instance_a = new class_a();
    // *     example 1: class_exists('class_a');
    // *     returns 1: true
    var i = '';
    cls = this.window[cls]; // Note: will prevent inner classes

    if (typeof cls !== 'function') {return false;}

    for (i in cls.prototype) {
        return true;
    }
    for (i in cls) { // If static members exist, then consider a "class"
        if (i !== 'prototype') {
            return true;
        }
    }
    if (cls.toSource && cls.toSource().match(/this\./)) { 
        // Hackish and non-standard but can probably detect if setting
        // a property (we don't want to test by instantiating as that
        // may have side-effects)
        return true;
    }
    
    return false;
}

function classkit_import (file) {
    // !No description available for classkit_import. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/classkit_import
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: file_get_contents
    // %        note 1: does not return an associative array as in PHP
    // %        note 2: Implement instead with include?
    // %        note 3: CLASSKIT_AGGREGATE_OVERRIDE is mentioned as a flag at http://www.php.net/manual/en/runkit.constants.php but not in classkit docs
    // *     example 1: classkit_import('http://example.com/somefile.js');
    // *     returns 1: undefined
    
	eval(this.file_get_contents(file));
}

function classkit_method_add (classname, methodname, args, code, flags) {
    // !No description available for classkit_method_add. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/classkit_method_add
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function a(){}
    // *     example 1: classkit_method_add ('a', 'b', 'a,b', 'return a+b');
    // *     returns 1: true

    var func, argmnts = [];

	switch (flags) {
		case 'CLASSKIT_ACC_PROTECTED':
			throw 'Protected not supported';
		case 'CLASSKIT_ACC_PRIVATE':
			throw 'Private not supported';
		case 'CLASSKIT_ACC_PUBLIC':
			default:
				break;
	}

	argmnts = args.split(/,\s*/);
	
	if (typeof classname === 'string') {
		classname = this.window[classname];
	}

// Could use the following to add as a static method to the class
//	    func = Function.apply(null, argmnts.concat(code));
//            classname[methodname] = func;
	func = Function.apply(null, argmnts.concat(code));
	classname.prototype[methodname] = func;
    return true;
}

function classkit_method_copy (dClass, dMethod, sClass, sMethod) {
    // !No description available for classkit_method_copy. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/classkit_method_copy
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: classkit_method_copy('newClass', 'newMethod', 'someClass', 'someMethod');
    // *     returns 1: true
    
	/*
	function A(){}
	function C(){}
	C.d = function () {alert('inside d');}
	classkit_method_copy('A', 'b', 'C', 'd');
	A.b(); // 'inside d'
	*/
    sMethod = sMethod || dMethod;
	
	if (typeof dClass === 'string') {
		dClass = this.window[dClass];
	}
	if (typeof sClass === 'string') {
		sClass = this.window[sClass];
	}
	
	//dClass[dMethod] = sClass[sMethod]; // Copy from static to static method (as per PHP example)
	dClass.prototype[dMethod] = sClass.prototype[sMethod]; // To copy from instance to instance
    return true;
}

function classkit_method_redefine (classname, methodname, args, code, flags) {
    // !No description available for classkit_method_redefine. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/classkit_method_redefine
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: classkit_method_redefine('someClass', 'someMethod', 'a,b', 'return a+b');
    // *     returns 1: true
    
	// In JavaScript, this is identical to classkit_method_add
	
	var argmnts = [], func;

	switch (flags) {
		case 'CLASSKIT_ACC_PROTECTED':
			throw 'Protected not supported';
		case 'CLASSKIT_ACC_PRIVATE':
			throw 'Private not supported';
		case 'CLASSKIT_ACC_PUBLIC':
			default:
				break;
	}

	argmnts = args.split(/,\s*/);
	
	if (typeof classname === 'string') {
		classname = this.window[classname];
	}

// Could use the following to add as a static method to the class
//	    func = Function.apply(null, argmnts.concat(code));
//            classname[methodname] = func;
	func = Function.apply(null, argmnts.concat(code));
	classname.prototype[methodname] = func;
    return true;
}

function classkit_method_remove (classname, methodname) {
    // !No description available for classkit_method_remove. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/classkit_method_remove
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: classkit_method_remove('someClass', 'someMethod');
    // *     returns 1: true
    
    if (typeof classname === 'string') {
        classname = this.window[classname];
    }
    delete classname.prototype[methodname]; // Delete any on prototype
    // delete classname[methodname]; // Delete any as static class method
    return true;
}

function classkit_method_rename (classname, methodname, newname) {
    // !No description available for classkit_method_rename. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/classkit_method_rename
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: classkit_method_rename('someClass', 'someMethod', 'newMethod');
    // *     returns 1: true
    
	if (typeof classname === 'string') {
		classname = this.window[classname];
	}
	
	/*
	var method = classname[methodname]; // Static
	classname[newname] = method;
	delete classname[methodname];
	*/
	
	var method = classname.prototype[methodname];
	classname.prototype[newname] = method;
	delete classname.prototype[methodname];
	
	return true;
}

function compact ( ) {
    // Creates a hash containing variables and their values  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/compact
    // +   original by: Waldo Malqui Silva
    // +    tweaked by: Jack
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld';  
    // *     example 1: compact('var1', 'var2', 'var3');
    // *     returns 1: {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'}    
    
    var matrix = {}, that = this;

    var process = function ( value ) {
        var i = 0, l = value.length, key_value = '';
        for (i = 0; i < l; i++) {
            key_value = value [ i ];
            if (key_value instanceof Array) {
                process( key_value );
            } else {
                if (typeof that.window[key_value] !== 'undefined') {
                    matrix[key_value] = that.window[key_value];
                }
            }
        }
        return true;
    };
    
    process(arguments);
    return matrix;
}

function constant(name) {
    // Given the name of a constant this function will return the constant's associated value  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/constant
    // +   original by: Paulo Ricardo F. Santos
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: constant('IMAGINARY_CONSTANT1');
    // *     returns 1: null
	
	var clssPos = 0, clssCnst = null;
	if ((clssPos = name.indexOf('::')) !== -1) {
		clssCnst = name.slice(clssPos+2);
		name = name.slice(0, clssPos);
	}

    if (this.window[name] === undefined) {
        return null;
    }
	if (clssCnst) {
		return this.window[name][clssCnst];
	}
    return this.window[name];
}

function convert_uuencode(str){
    // uuencode a string  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/convert_uuencode
    // +   original by: Ole Vrijenhoek
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   reimplemented by: Ole Vrijenhoek
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: is_scalar
    // *     example 1: convert_uuencode("test\ntext text\r\n");
    // *     returns 1: '0=&5S=`IT97AT('1E>'0-"@``'
    // shortcut
    var chr = function(c) {
        return String.fromCharCode(c);
    };

    if(!str || str=="") {
        return chr(0);
    } else if(!this.is_scalar(str)) {
        return false;
    }

    var c = 0, u = 0, i = 0, a = 0;
    var encoded = "", tmp1 = "", tmp2 = "", bytes = {};

    // divide string into chunks of 45 characters
    var chunk = function() {
        bytes = str.substr(u, 45);
        for(i in bytes) {
            bytes[i] = bytes[i].charCodeAt(0);
        }
        if(bytes.length != 0) {
            return bytes.length;
        } else {
            return 0;
        }
    };

    while(chunk() !== 0) {
        c = chunk();
        u += 45;

        // New line encoded data starts with number of bytes encoded.
        encoded += chr(c+32);

        // Convert each char in bytes[] to a byte
        for(i in bytes) {
            tmp1 = bytes[i].charCodeAt(0).toString(2);
            while(tmp1.length < 8) {
                tmp1 = "0" + tmp1;
            }
            tmp2 += tmp1;
        }

        while(tmp2.length % 6) {
            tmp2 = tmp2 + "0";
        }

        for(i=0; i<=(tmp2.length/6)-1; i++) {
            tmp1 = tmp2.substr(a, 6);
            if(tmp1 == "000000") {
                encoded += chr(96);
            } else {
                encoded += chr(parseInt(tmp1, 2)+32);
            }
            a += 6;
        }
        a = 0;
        tmp2 = "";
        encoded += "\n";
    }

    // Add termination characters
    encoded += chr(96)+"\n";

    return encoded;
}

function cos(arg) {
    // Returns the cosine of the number in radians  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/cos
    // +   original by: Onno Marsman
    // *     example 1: cos(8723321.4);
    // *     returns 1: -0.18127180117607017
    return Math.cos(arg);
}

function cosh(arg) {
    // Returns the hyperbolic cosine of the number, defined as (exp(number) + exp(-number))/2  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/cosh
    // +   original by: Onno Marsman
    // *     example 1: cosh(-0.18127180117607017);
    // *     returns 1: 1.0164747716114113
    return (Math.exp(arg) + Math.exp(-arg))/2;
}

function count( mixed_var, mode ) {
    // Count the number of elements in a variable (usually an array)  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/count
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Waldo Malqui Silva
    // +      bugfixed by: Soren Hansen
    // *     example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
    // *     returns 1: 6
    // *     example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
    // *     returns 2: 6
    var key, cnt = 0;

    if (mixed_var === null){
        return 0;
    } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object){
        return 1;
    }

    if( mode === 'COUNT_RECURSIVE' ) {
        mode = 1;
    }
    if( mode != 1 ) {
        mode = 0;
    }

    for (key in mixed_var){
        cnt++;
        if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
            cnt += count(mixed_var[key], 1);
        }
    }

    return cnt;
}

function count_chars( str, mode ) {
    // Returns info about what characters are used in input  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/count_chars
    // +   original by: Ates Goral (http://magnetiq.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: count_chars("Hello World!", 1);
    // *     returns 1: "Hd e!lWor"
    var histogram = {}, tmp_arr = [];
    var key, i, code, strl = 0;
    var argc = arguments.length;
    var mode_even = 0;

    if (argc == 1) {
        mode = 0;
    }

    mode_even = (mode & 1) == 0;
    if (mode_even) {
        for (i = 1; i < 256; ++i) {
            histogram[i] = 0;
        }
    }

    str += '';

    strl = str.length;
    for (i = 0; i < strl; ++i) {
        code = str.charCodeAt(i);
        if (code in histogram) {
            ++histogram[code];
        } else {
            histogram[code] = 1;
        }
    }

    if (mode > 0) {
        for (key in histogram) {
            if (histogram[key] == 0 != mode_even) {
                delete histogram[key];
            }
        }
    }

    if (mode < 3) {
        return histogram;
    } else {
        for (key in histogram) {
            tmp_arr.push(String.fromCharCode(key));
        }
        return tmp_arr.join("");
    }
}

function crc32 ( str ) {
    // Calculate the crc32 polynomial of a string  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/crc32
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: T0bsn
    // -    depends on: utf8_encode
    // *     example 1: crc32('Kevin van Zonneveld');
    // *     returns 1: 1249991249
    str = this.utf8_encode(str);
    var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";

    var crc = 0;
    var x = 0;
    var y = 0;

    crc = crc ^ (-1);
    for( var i = 0, iTop = str.length; i < iTop; i++ ) {
        y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
        x = "0x" + table.substr( y * 9, 8 );
        crc = ( crc >>> 8 ) ^ x;
    }

    return crc ^ (-1);
}

function create_function (args, code) {
    // Creates an anonymous function, and returns its name (funny, eh?)  
    // 
    // version: 904.614
    // discuss at: http://phpjs.org/functions/create_function
    // +   original by: Johnny Mast (http://www.phpvrouwen.nl)
    // +   reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: f = create_function('a, b', "return (a + b);");
    // *     example 1: f(1, 2);
    // *     returns 1: 3
     try {
        return Function.apply(null, args.split(',').concat(code));
     }
     catch (e) {
         return false;
     }
}

function ctype_alnum (text) {
    // Checks for alphanumeric character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_alnum
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_alnum('AbC12');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.an.test(text);
}

function ctype_alpha (text) {
    // Checks for alphabetic character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_alpha
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_alpha('Az');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.al.test(text);
}

function ctype_cntrl (text) {
    // Checks for control character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_cntrl
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_cntrl('\u0020');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.ct.test(text);
}

function ctype_digit (text) {
    // Checks for numeric character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_digit
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_digit('150');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.dg.test(text);
}

function ctype_graph (text) {
    // Checks for any printable character(s) except space  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_graph
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_graph('!%');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.gr.test(text);
}

function ctype_lower (text) {
    // Checks for lowercase character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_lower
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_lower('abc');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lw.test(text);
}

function ctype_print (text) {
    // Checks for printable character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_print
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_print('AbC!#12');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pr.test(text);
}

function ctype_punct (text) {
    // Checks for any printable character which is not whitespace or an alphanumeric character  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_punct
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_punct('!?');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pu.test(text);
}

function ctype_space (text) {
    // Checks for whitespace character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_space
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_space('\t\n');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.sp.test(text);
}

function ctype_upper (text) {
    // Checks for uppercase character(s)  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_upper
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_upper('AZ');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.up.test(text);
}

function ctype_xdigit (text) {
    // Checks for character(s) representing a hexadecimal digit  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/ctype_xdigit
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: ctype_xdigit('01dF');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END STATIC
    return this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.xd.test(text);
}

function current(arr) {
    // Return the element currently pointed to by the internal array pointer  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/current
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: transport = ['foot', 'bike', 'car', 'plane'];
    // *     example 1: current(transport); 
    // *     returns 1: 'foot'
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.pointers) {
        this.php_js.pointers = [];
    }
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    var cursor = pointers[arrpos+1];
    if (arr instanceof Array) {
        return arr[cursor] || false;
    }
    var ct = 0;
    for (var k in arr) {
        if (ct === cursor) {
            return arr[k];
        }
        ct++;
    }
    return false; // Empty
}

function date ( format, timestamp ) {
    // Format a local date/time  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/date
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: MeEtc (http://yass.meetcweb.com)
    // +   improved by: Brad Touesnard
    // +   improved by: Tim Wiel
    // +   improved by: Bryan Elliott
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: David Randall
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   derived from: gettimeofday
    // %        note 1: Uses global: php_js to store the default timezone
    // *     example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400);
    // *     returns 1: '09:09:40 m is month'
    // *     example 2: date('F j, Y, g:i a', 1062462400);
    // *     returns 2: 'September 2, 2003, 2:26 am'
    // *     example 3: date('Y W o', 1062462400);
    // *     returns 3: '2003 36 2003'
    // *     example 4: x = date('Y m d', (new Date()).getTime()/1000); // 2009 01 09
    // *     example 4: (x+'').length == 10
    // *     returns 4: true
    var jsdate=(
        (typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp) // Javascript Date()
    ); // , tal=[]
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var _dst = function (t) {
        // Calculate Daylight Saving Time (derived from gettimeofday() code)
        var dst=0;
        var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
        var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
        var temp = jan1.toUTCString();
        var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        temp = june1.toUTCString();
        var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
        var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);

        if (std_time_offset === daylight_time_offset) {
            dst = 0; // daylight savings time is NOT observed
        }
        else {
            // positive is southern, negative is northern hemisphere
            var hemisphere = std_time_offset - daylight_time_offset;
            if (hemisphere >= 0) {
                std_time_offset = daylight_time_offset;
            }
            dst = 1; // daylight savings time is observed
        }
        return dst;
    };
    var ret = '';
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];

    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                var t = f.l();
                return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },

        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;

                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } 
                if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                    nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                    return date("W", Math.round(nd2.getTime()/1000));
                }
                return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
            },

        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                var t = f.F();
                return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                }
                if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                    return 31;
                }
                return 30;
            },

        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            o: function(){
                if (f.n() === 12 && f.W() === 1) {
                    return jsdate.getFullYear()+1;
                }
                if (f.n() === 1 && f.W() >= 52) {
                    return jsdate.getFullYear()-1;
                }
                return jsdate.getFullYear();
            },
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },

        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) {
                    beat -= 1000;
                }
                if (beat < 0) {
                    beat += 1000;
                }
                if ((String(beat)).length == 1) {
                    beat = "00"+beat;
                }
                if ((String(beat)).length == 2) {
                    beat = "0"+beat;
                }
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            u: function(){
                return pad(jsdate.getMilliseconds()*1000, 6);
            },

        // Timezone
            e: function () {
/*                var abbr='', i=0;
                if (this.php_js && this.php_js.default_timezone) {
                    return this.php_js.default_timezone;
                }
                if (!tal.length) {
                    tal = timezone_abbreviations_list();
                }
                for (abbr in tal) {
                    for (i=0; i < tal[abbr].length; i++) {
                        if (tal[abbr][i].offset === -jsdate.getTimezoneOffset()*60) {
                            return tal[abbr][i].timezone_id;
                        }
                    }
                }
*/
                return 'UTC';
            },
            I: function(){
                return _dst(jsdate);
            },
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               t = (jsdate.getTimezoneOffset() > 0) ? "-"+t : "+"+t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            T: function () {
/*                var abbr='', i=0;
                if (!tal.length) {
                    tal = timezone_abbreviations_list();
                }
                if (this.php_js && this.php_js.default_timezone) {
                    for (abbr in tal) {
                        for (i=0; i < tal[abbr].length; i++) {
                            if (tal[abbr][i].timezone_id === this.php_js.default_timezone) {
                                return abbr.toUpperCase();
                            }
                        }
                    }
                }
                for (abbr in tal) {
                    for (i=0; i < tal[abbr].length; i++) {
                        if (tal[abbr][i].offset === -jsdate.getTimezoneOffset()*60) {
                            return abbr.toUpperCase();
                        }
                    }
                }
*/
                return 'UTC';
            },
            Z: function(){
               return -jsdate.getTimezoneOffset()*60;
            },

        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            r: function(){
                return f.D()+', '+f.d()+' '+f.M()+' '+f.Y()+' '+f.H()+':'+f.i()+':'+f.s()+' '+f.O();
            },
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }
        return ret;
    });
}

function date_default_timezone_get () {
    // !No description available for date_default_timezone_get. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/date_default_timezone_get
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: timezone_abbreviations_list
    // %        note 1: Uses global: php_js to store the default timezone
    // *     example 1: date_default_timezone_get();
    // *     returns 1: 'unknown'
    var tal = {}, abbr = '', i = 0, today = new Date();

	if (this.php_js) {
        if (this.php_js.default_timezone) { // set by date_default_timezone_set
            return this.php_js.default_timezone;
        }
        if (this.php_js.ENV && this.php_js.ENV.TZ) { // getenv
            return this.php_js.ENV.TZ;
        }
        if (this.php_js.ini && this.php_js.ini['date.timezone']) { // e.g., if set by ini_set()
            return this.php_js.ini['date.timezone'].local_value ? this.php_js.ini['date.timezone'].local_value : this.php_js.ini['date.timezone'].global_value;
        }
    }
    // Get from system
	tal = this.timezone_abbreviations_list();
	for (abbr in tal) {
		for (i=0; i < tal[abbr].length; i++) {
			if (tal[abbr][i].offset === -today.getTimezoneOffset()*60) {
				return tal[abbr][i].timezone_id;
			}
		}
	}
	return 'UTC';
}

function date_default_timezone_set (tz) {
    // Sets the default timezone used by all date/time functions in a script  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/date_default_timezone_set
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: timezone_abbreviations_list
    // %        note 1: Uses global: php_js to store the default timezone
    // *     example 1: date_default_timezone_set('unknown');
    // *     returns 1: 'unknown'
    var tal = {}, abbr = '', i = 0;

	if (!this.php_js) {
		this.php_js={};
	}
	// PHP verifies that the timezone is valid
	tal = this.timezone_abbreviations_list();
	for (abbr in tal) {
		for (i=0; i < tal[abbr].length; i++) {
			if (tal[abbr][i].timezone_id === tz) {
				this.php_js.default_timezone = tz;
				return true;
			}
		}
	}
	return false;
}

function date_parse (date) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: strtotime
	// *     example 1: date_parse('2006-12-12 10:00:00.5');
	// *     returns 1: {year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0.5, warning_count: 0, warnings: [], error_count: 0, errors: [], is_localtime: false}

    if (!this.php_js) {
        this.php_js = {};
    }

    var warningsOffset = this.php_js.warnings ? this.php_js.warnings.length : null;
    var errorsOffset = this.php_js.errors ? this.php_js.errors.length : null;

    try {
        var ts = this.strtotime(date);
    }
    finally {
        if (!ts) {
            return false;
        }
    }

    var dt = new Date(ts*1000);

    var retObj = { // Grab any new warnings or errors added (not implemented yet in strtotime()); throwing warnings, notices, or errors could also be easily monitored by using 'watch' on this.php_js.latestWarning, etc. and/or calling any defined error handlers
        warning_count: warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset).length : 0,
        warnings: warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset) : [],
        error_count: errorsOffset !== null ? this.php_js.errors.slice(errorsOffset).length : 0,
        errors: errorsOffset !== null ? this.php_js.errors.slice(errorsOffset) : []
    };
    retObj.year = dt.getFullYear();
    retObj.month = dt.getMonth()+1;
    retObj.day = dt.getDate();
    retObj.hour = dt.getHours();
    retObj.minute = dt.getMinutes();
    retObj.second = dt.getSeconds();
    retObj.fraction = parseFloat('0.'+dt.getMilliseconds());
    retObj.is_localtime = dt.getTimezoneOffset !== 0;

    return retObj;
}

function deaggregate (obj, class_name) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// *     example 1: var A = function () {};
	// *     example 1: A.prop = 5;
	// *     example 1: A.prototype.someMethod = function () {};
	// *     example 1: var b = {};
	// *     example 1: aggregate(b, 'A');
	// *     example 1: deaggregate(b, 'A');
	// *     returns 1: undefined

    var p='', idx=-1, pos=-1, i=0;

    if (!this.php_js || !this.php_js.aggregateRecords || !this.php_js.aggregateKeys || !this.php_js.aggregateClasses) {
        return;
    }

    idx = this.php_js.aggregateKeys.indexOf(obj);
    if (idx === -1) {
        return;
    }

    if (class_name) {
        if (typeof class_name === 'string') { // PHP behavior
            class_name = this.window[class_name];
        }
        pos = this.php_js.aggregateClasses[idx].indexOf(class_name.name);
        if (pos !== -1) {
            for (p in this.php_js.aggregateRecords[idx][pos]) {
                delete obj[p];
            }
            this.php_js.aggregateClasses[idx].splice(pos, 1);
            this.php_js.aggregateRecords[idx].splice(pos, 1);
        }
    }
    else {
        for (i=0; i < this.php_js.aggregateClasses[idx].length; i++) {
            for (p in this.php_js.aggregateRecords[idx][i]) {
                delete obj[p];
            }
        }
        this.php_js.aggregateClasses.splice(idx, 1);
        this.php_js.aggregateRecords.splice(idx, 1);
    }
}

function decbin(number) {
    // Returns a string containing a binary representation of the number  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/decbin
    // +   original by: Enrique Gonzalez
    // +   bugfixed by: Onno Marsman
    // *     example 1: decbin(12);
    // *     returns 1: '1100'
    // *     example 2: decbin(26);
    // *     returns 2: '11010'
    // *     example 3: decbin('26');
    // *     returns 3: '11010'
    
    return parseInt(number, 10).toString(2);
}

function dechex(number) {
    // Returns a string containing a hexadecimal representation of the given number  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/dechex
    // +   original by: Philippe Baumann
    // +   bugfixed by: Onno Marsman
    // *     example 1: dechex(10);
    // *     returns 1: 'a'
    // *     example 2: dechex(47);
    // *     returns 2: '2f'
    
    return parseInt(number, 10).toString(16);
}

function decoct(number) {
    // Returns a string containing an octal representation of the given number  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/decoct
    // +   original by: Enrique Gonzalez
    // +   bugfixed by: Onno Marsman
    // *     example 1: decoct(15);
    // *     returns 1: '17'
    // *     example 2: decoct(264); 
    // *     returns 2: '410'
    
    return parseInt(number, 10).toString(8);
}

function define(name, value) {
    // Define a new constant
    //
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/define
    // +      original by: Paulo Ricardo F. Santos
    // +       revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // *        example 1: define('IMAGINARY_CONSTANT1', 'imaginary_value1');
    // *        results 1: IMAGINARY_CONSTANT1 == 'imaginary_value1'
    var defn, replace, script, that = this, d = this.window.document;
    var toString = function (name, value) {
        return 'const ' + name + '=' + (
            /^(null|true|false|(\+|\-)?\d+(\.\d+)?)$/.test(value = String(value)) ? value : '"' + replace(value) + '"'
            );
    };
    try {
        eval('const e=1');
        replace = function (value){
            var replace = {
                "\x08":"b",
                "\x0A":"\\n",
                "\x0B":"v",
                "\x0C":"f",
                "\x0D":"\\r",
                '"':'"',
                "\\":"\\"
            };
            return value.replace(/\x08|[\x0A-\x0D]|"|\\/g, function(value){
                return "\\"+replace[value];
			});
        };
        defn = function (name, value){
            if (d.createElementNS) {
                script = d.createElementNS('http://www.w3.org/1999/xhtml', 'script');
            } else {
                script = d.createElement('script');
            }
            script.type = 'text/javascript';
            script.appendChild(d.createTextNode(toString(name, value)));
            d.documentElement.appendChild(script);
            d.documentElement.removeChild(script);
        };
    } catch (e){
        replace = function (value) {
            var replace = {
                "\x0A":"\\n",
                "\x0D":"\\r"
            };
            return value.replace(/"/g, '""').replace(/\n|\r/g, function(value){
                return replace[value];
            });
        };
        defn = (this.execScript ?
            function (name, value){
                that.execScript(toString(name, value), 'VBScript');
            }:
            function (name, value){
                eval(toString(name, value).substring(6));
            });
    }
    defn(name, value);
}

function defined( constant_name )  {
    // Check whether a constant exists  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/defined
    // +   original by: Waldo Malqui Silva
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Because this function can (albeit only temporarily) overwrite a global variable,
	// %          note 1: it is not thread-safe (normally not a concern for JavaScript, but would be if used
	// %          note 1: in a threaded environment, e.g., DOM worker threads)
    // *     example 1: defined('IMAGINARY_CONSTANT1');
    // *     returns 1: false
    var tmp = this.window[constant_name];
    
    this.window[constant_name] = this.window[constant_name] ? 'changed'+this.window[constant_name].toString() : 'changed';
    var returnval = this.window[constant_name] === tmp;
    if (!returnval) { // Reset
        this.window[constant_name] = tmp;
    }

    return returnval;
}

function deg2rad(angle) {
    // Converts the number in degrees to the radian equivalent  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/deg2rad
    // +   original by: Enrique Gonzalez
    // *     example 1: deg2rad(45);
    // *     returns 1: 0.7853981633974483
    
    return (angle/180)*Math.PI;
}

function die( status ) {
    // !No description available for die. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/die
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    //  -   depends on: exit
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: die();
    // *     returns 1: null
    return this.exit(status);
}

function dirname(path) {
    // Returns the directory name component of the path  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/dirname
    // +   original by: Ozh
    // +   improved by: XoraX (http://www.xorax.info)
    // *     example 1: dirname('/etc/passwd');
    // *     returns 1: '/etc'
    // *     example 2: dirname('c:/Temp/x');
    // *     returns 2: 'c:/Temp'
    // *     example 3: dirname('/dir/test/');
    // *     returns 3: '/dir'
    
    return path.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '');
}

function doubleval( mixed_var ) {
    // !No description available for doubleval. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/doubleval
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    //  -   depends on: floatval
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: doubleval(186);
    // *     returns 1: 186.00
    return this.floatval(mixed_var);
}

function each(arr) {
    // Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/each
    // +   original by: Ates Goral (http://magnetiq.com) 
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: each({a: "apple", b: "balloon"});
    // *     returns 1: {0: "a", 1: "apple", key: "a", value: "apple"}
    //  Will return a 4-item object unless a class property 'returnArrayOnly'
    //  is set to true on this function if want to only receive a two-item
    //  numerically-indexed array (for the sake of array destructuring in
    //  JavaScript 1.7+ (similar to list() in PHP, but as PHP does it automatically
    //  in that context and JavaScript cannot, we needed something to allow that option)
    //  See https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment
    
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.pointers) {
        this.php_js.pointers = [];
    }
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    var cursor = pointers[arrpos+1];
    var pos = 0;

    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            if (ct === cursor) {
                pointers[arrpos+1] += 1;
                if (each.returnArrayOnly) {
                    return [k, arr[k]];
                } else {
                    return {
                        1:arr[k],
                        value:arr[k],
                        0:k,
                        key:k
                    };
                }
            }
            ct++;
        }
        return false; // Empty
    }
    if (arr.length === 0 || cursor === arr.length) {
        return false;
    }
    pos = cursor;
    pointers[arrpos+1] += 1;
    if (each.returnArrayOnly) {
        return [pos, arr[pos]];
    } else {
        return {
            1:arr[pos],
            value:arr[pos],
            0:pos,
            key:pos
        };
    }
}

function echo ( ) {
    // !No description available for echo. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/echo
    // +   original by: Philip Peterson
    // +   improved by: echo is bad
    // +   improved by: Nate
    // +    revised by: Der Simon (http://innerdom.sourceforge.net/)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Eugene Bulkin (http://doubleaw.com/)
    // %        note 1: The function still has issues with outputting certain kinds of XML, such as
    // %        note 1: attributes defined with apostrophes, or creating namespaced XML, etc.
    // %        note 1: We might at some point solve this by building on http://code.google.com/p/jssaxparser
    // %        note 1: and using that, though it would be even larger; if browsers start to support
    // %        note 1: DOM Level 3 Load and Save (parsing/serializing), we wouldn't need any
    // %        note 1: such long code (even most of the code below).
    // %        note 2: InnerHTML() is better because it works (and it's fast),
    // %        note 2: but using innerHTML on the BODY is very dangerous because
    // %        note 2: you will break all references to HTMLElements that were done before
    // *     example 1: echo('Hello', 'World');
    // *     returns 1: undefined
    
    var arg = '', argc = arguments.length, argv = arguments, i = 0;
	var d = this.window.document;
	
    var stringToDOM = function (q){
        var s = function(a){
            return a.replace(/&amp;/g,'&').replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&nbsp;/g,' ').replace(/&quot;/g,'"');
        };
        var t = function(a){
            return a.replace(/ /g,'');
        };
        var u = function(a){
            var b,c,e,f,g,h,i;
            b=d.createDocumentFragment();
            c=a.indexOf(' ');
            if (c === -1) {
                b.appendChild(d.createElement(a.toLowerCase()));
            } else {
                i = t(a.substring(0,c)).toLowerCase();
                a = a.substr(c+1);
                b.appendChild(d.createElement(i));
                while(a.length){
                    e=a.indexOf('=');
                    if(e>=0){
                        f=t(a.substring(0,e)).toLowerCase();
                        g=a.indexOf('"');
                        a=a.substr(g+1);
                        g=a.indexOf('"');
                        h=s(a.substring(0,g));
                        a=a.substr(g+2);
                        b.lastChild.setAttribute(f,h);
                    }else{
                        break;
                    }
                }
            }
            return b;
        };
        var v = function(a,b,c){
            var e,f;
            e=b;
            c=c.toLowerCase();
            f=e.indexOf('</'+c+'>');
            a=a.concat(e.substring(0,f));
            e=e.substr(f);
            while(a.indexOf('<'+c)!=-1){
                a=a.substr(a.indexOf('<'+c));
                a=a.substr(a.indexOf('>')+1);
                e=e.substr(e.indexOf('>')+1);
                f=e.indexOf('</'+c+'>');
                a=a.concat(e.substring(0,f));
                e=e.substr(f);
            }
            return b.length-e.length;
        };
        var w = function(a){
            var b,c,e,f,g,h,i,j,k,l,m,n,o,p,q;
            b=d.createDocumentFragment();
            while(a&&a.length){
                c=a.indexOf('<');
                if(c===-1){
                    a=s(a);
                    b.appendChild(d.createTextNode(a));
                    a=null;
                } else if(c){
                    q=s(a.substring(0,c));
                    b.appendChild(d.createTextNode(q));
                    a=a.substr(c);
                } else{
                    e=a.indexOf('<!--');
                    if(!e){
                        f=a.indexOf('-->');
                        g=a.substring(4,f);
                        g=s(g);
                        b.appendChild(d.createComment(g));
                        a=a.substr(f+3);
                    } else{
                        h=a.indexOf('>');
                        if(a.substring(h-1,h)==='/'){
                            i=a.indexOf('/>');
                            j=a.substring(1,i);
                            b.appendChild(u(j));
                            a=a.substr(i+2);
                        } else{
                            k=a.indexOf('>');
                            l=a.substring(1,k);
                            m=d.createDocumentFragment();
                            m.appendChild(u(l));
                            a=a.substr(k+1);
                            n=a.substring(0,a.indexOf('</'));
                            a=a.substr(a.indexOf('</'));
                            if(n.indexOf('<')!=-1){
                                o=m.lastChild.nodeName;
                                p=v(n,a,o);
                                n=n.concat(a.substring(0,p));
                                a=a.substr(p);
                            }
                            a=a.substr(a.indexOf('>')+1);
                            m.lastChild.appendChild(w(n));
                            b.appendChild(m);
                        }
                    }
                }
            }
            return b;
        };
        return w(q);
    };

    for (i = 0; i < argc; i++ ) {
        arg = argv[i];
        if (d.createDocumentFragment && d.createTextNode && d.appendChild) {
            if (d.body) {
                d.body.appendChild(stringToDOM(arg));
            } else {
                d.documentElement.appendChild(stringToDOM(arg));
            }
        } else if (d.write) {
            d.write(arg);
        } else {
            print(arg);
        }
    }
}

function empty( mixed_var ) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/empty
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    
    var key;
    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        mixed_var === undefined
    ){
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}

function end ( arr ) {
    // Advances array argument's internal pointer to the last element and return it  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/end
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Legaev Andrey
    // +    revised by: J A R
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   restored by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: end({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 1: 'Zonneveld'
    // *     example 2: end(['Kevin', 'van', 'Zonneveld']);
    // *     returns 2: 'Zonneveld'
    
    if (!this.php_js) {
		this.php_js = {};
	}
    if (!this.php_js.pointers) {
		this.php_js.pointers = [];
	}
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            ct++;
            var val = arr[k];
        }
        if (ct === 0) {
            return false; // Empty
        }
        pointers[arrpos+1] = ct - 1;
        return val;
    }
    if (arr.length === 0) {
        return false;
    }
    pointers[arrpos+1] = arr.length - 1;
    return arr[pointers[arrpos+1]];
}

function error_get_last () {
    // !No description available for error_get_last. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2716
    // discuss at: http://phpjs.org/functions/error_get_last
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: error_get_last();
    // *     returns 1: null
    // *     example 2: error_get_last();
    // *     returns 2: {type: 256, message: 'My user error', file: 'C:\WWW\index.php', line: 2}

    return this.php_js && this.php_js.last_error ? this.php_js.last_error : null; // Only set if error triggered within at() or trigger_error()
}

function error_reporting (level) {
    // Return the current error_reporting level, and if an argument was passed - change to the new level  
    // 
    // version: 905.2716
    // discuss at: http://phpjs.org/functions/error_reporting
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: ini_set
    // %        note 1: This will not set a global_value or access level for the ini item
    // %        note 2: If you wish the default value to be as in PHP, you must manually set it
    // %        note 3: This function depends on functions implementing error handling
    // %        note 4: See also our at() error suppressor function (@ operator in PHP) in experimental/language/
    // *     example 1: error_reporting(1);
    // *     returns 1: 6135
    return this.ini_set('error_reporting', level);
}

function exit( status ) {
    // !No description available for exit. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/exit
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null
    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    this.window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];
    
    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        this.window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
    }

    if (this.window.stop) {
        this.window.stop();
    }
    
    throw '';
}

function exp(arg) {
    // Returns e raised to the power of the number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/exp
    // +   original by: Onno Marsman
    // *     example 1: exp(0.3);
    // *     returns 1: 1.3498588075760032
    return Math.exp(arg);
}

function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function expm1 (x) {
    // Returns exp(number) - 1, computed in a way that accurate even when the value of number is close to zero  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/expm1
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Precision 'n' can be adjusted as desired
    // *     example 1: expm1(1e-15);
    // *     returns 1: 1.0000000000000007e-15
    var ret=0, n = 50; // degree of precision
    var factorial = function factorial (n) {
       if ((n === 0) || (n === 1)) {
           return 1;
       }
       else {
          var result = (n * factorial(n-1) );
          return result;
       }
    };
    for (var i=1; i < n; i++) {
        ret += Math.pow(x, i)/factorial(i);
    }
    return ret;
}

function extract (arr, type, prefix) {
    // Imports variables into symbol table from an array  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/extract
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Only works by extracting into global context (whether called in the global scope or
    // %        note 1: within a function); also, the EXTR_REFS flag I believe can't be made to work
    // *     example 1: size = 'large';
    // *     example 1: var_array = {'color' : 'blue', 'size' : 'medium', 'shape' : 'sphere'};
    // *     example 1: extract(var_array, 'EXTR_PREFIX_SAME', 'wddx');
    // *     example 1: color+'-'+size+'-'+shape+'-'+wddx_size;
    // *     returns 1: 'blue-large-sphere-medium'
    if (arr instanceof Array && (type !== 'EXTR_PREFIX_ALL' && type !== 'EXTR_PREFIX_INVALID')) {
        return 0;
    }
    var chng = 0;

    for (var i in arr) {
        var validIdent = /^[_a-zA-Z$][\w|$]*$/; // TODO: Refine regexp to allow JS 1.5+ Unicode identifiers
        var prefixed = prefix+'_'+i;
        try {
            switch (type) {
                case 'EXTR_PREFIX_SAME' || 2:
                    if (this[i] !== undefined) {
                        if (prefixed.match(validIdent) !== null) {
                            this[prefixed] = arr[i];
                            ++chng;
                        }
                    }
                    else {
                        this[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_SKIP' || 1:
                    if (this[i] === undefined) {
                        this[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_ALL' || 3:
                    if (prefixed.match(validIdent) !== null) {
                        this[prefixed] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_INVALID' || 4:
                    if(i.match(validIdent) !== null) {
                        if (prefixed.match(validIdent) !== null) {
                            this[prefixed] = arr[i];
                            ++chng;
                        }
                    }
                    else {
                        this[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_IF_EXISTS' || 6:
                    if (this[i] !== undefined) {
                        this[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_IF_EXISTS' || 5:
                    if (this[i] !== undefined && prefixed.match(validIdent) !== null) {
                        this[prefixed] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_REFS' || 256:
                    throw 'The EXTR_REFS type will not work in JavaScript';
                case 'EXTR_OVERWRITE' || 0:
                // Fall-through
                default:
                    this[i] = arr[i];
                    ++chng;
                    break;
            }
        }
        catch (e) { // Just won't increment for problem assignments
            
        }
    }
    return chng;
}

function fclose (handle) {
    // Close an open file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/fclose
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var handle = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fclose(handle);
    // *     returns 1: true

    if (!handle || handle.opener !== 'fopen') {
        return false;
    }
    
    try {
        delete this.php_js.resourceDataPointer[handle.id];
        delete this.php_js.resourceData[handle.id]; // Free up memory
        return true;
    }
    catch(e) {
        return false;
    }
}

function feof (handle) {
    // Test for end-of-file on a file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/feof
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var handle = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fread(handle, 1);
    // *     example 1: feof(handle);
    // *     returns 1: false

    if (!handle || !this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer) {
        return true;
    }

    return !this.php_js.resourceData[handle.id][this.php_js.resourceDataPointer[handle.id]];
    
}

function fgetc (handle) {
    // Get a character from file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/fgetc
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fgetc(handle);
    // *     returns 1: '1'

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer) {
        return false;
    }

    var start = this.php_js.resourceDataPointer[handle.id];

    if (start === undefined || !this.php_js.resourceData[handle.id][start]) {
        return false; // Resource was already closed or already reached the end of the file
    }

    var length = 1; // 2 byte-character (or surrogate)
    this.php_js.resourceDataPointer[handle.id] += length;
    var chr = this.php_js.resourceData[handle.id].substr(start, length);

    // If don't want to treat surrogate pairs as single characters, can delete from here until the last line (return chr;)
    var nextChr = this.php_js.resourceData[handle.id].substr(start+1, 1);
    var prevChr = start === 0 ? false : this.php_js.resourceData[handle.id].substr(start-1, 1);
    var code = chr.charCodeAt(0);
    if (0xD800 <= code && code <= 0xDBFF) { // High surrogate(could change last hex to 0xDB7F to treat high private surrogates as single characters)
        if (!nextChr)  {
            throw 'High surrogate without following low surrogate (fgetc)';
        }
        var next = nextChr.charCodeAt(0);
        if (0xDC00 > next || next > 0xDFFF) {
            throw 'High surrogate without following low surrogate (fgetc)';
        }
        this.php_js.resourceDataPointer[handle.id] += length; // Need to increment counter again since grabbing next item
        return chr+nextChr;
    }
    else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
        if (prevChr === false) {
            throw 'Low surrogate without preceding high surrogate (fgetc)';
        }
        var prev = prevChr.charCodeAt(0);
        if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
            throw 'Low surrogate without preceding high surrogate (fgetc)';
        }
        return prevChr+chr; // Probably shouldn't have reached here, at least if traversing by fgetc()
    }
    
    return chr;
}

function fgetcsv (handle, length, delimiter, enclosure, escape) {
    // Get line from file pointer and parse for CSV fields  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/fgetcsv
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: str_getcsv
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fgetcsv(handle, 1);
    // *     returns 1: '<'

    var start=0, fullline='';

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer || length !== undefined && !length) {
        return false;
    }

    start = this.php_js.resourceDataPointer[handle.id];

    if (start === undefined || !this.php_js.resourceData[handle.id][start]) {
        return false; // Resource was already closed or already reached the end of the file
    }

    fullline = this.php_js.resourceData[handle.id].slice(start, this.php_js.resourceData[handle.id].indexOf('\n', start)+1);
    if (fullline === '') {
        fullline = this.php_js.resourceData[handle.id].slice(start); // Get to rest of the file
    }

    length = (length === undefined || fullline.length < length) ? fullline.length : Math.floor(length/2) || 1; // two bytes per character (or surrogate), but ensure at least one

    this.php_js.resourceDataPointer[handle.id] += length; // Leaves the pointer one higher apparently than in fgets/fgetss
    return this.str_getcsv(this.php_js.resourceData[handle.id].substr(start, length), delimiter, enclosure, escape);
}

function fgets (handle, length) {
    // Get a line from file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/fgets
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fgets(handle, 1);
    // *     returns 1: '<'

    var start=0, fullline='';

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer || length !== undefined && !length) {
        return false;
    }

    start = this.php_js.resourceDataPointer[handle.id];

    if (start === undefined || !this.php_js.resourceData[handle.id][start]) {
        return false; // Resource was already closed or already reached the end of the file
    }

    fullline = this.php_js.resourceData[handle.id].slice(start, this.php_js.resourceData[handle.id].indexOf('\n', start)+1);
    if (fullline === '') {
        fullline = this.php_js.resourceData[handle.id].slice(start); // Get to rest of the file
    }

    length = (length === undefined || fullline.length < length) ? fullline.length : Math.floor(length/2) || 1; // two bytes per character (or surrogate), but ensure at least one

    this.php_js.resourceDataPointer[handle.id] += length-1;
    return this.php_js.resourceData[handle.id].substr(start, length);
}

function fgetss (handle, length, allowable_tags) {
    // Get a line from file pointer and strip HTML tags  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/fgetss
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: strip_tags
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fgetss(handle, 4096, 'a');
    // *     returns 1: ''

    var start=0, fullline='';

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer || length !== undefined && !length) {
        return false;
    }

    start = this.php_js.resourceDataPointer[handle.id];

    if (start === undefined || !this.php_js.resourceData[handle.id][start]) {
        return false; // Resource was already closed or already reached the end of the file
    }

    fullline = this.php_js.resourceData[handle.id].slice(start, this.php_js.resourceData[handle.id].indexOf('\n', start)+1);
    if (fullline === '') {
        fullline = this.php_js.resourceData[handle.id].slice(start); // Get to rest of the file
    }

    length = (length === undefined || fullline.length < length) ? fullline.length : Math.floor(length/2) || 1; // two bytes per character (or surrogate), but ensure at least one

    this.php_js.resourceDataPointer[handle.id] += length-1;
    return this.strip_tags(this.php_js.resourceData[handle.id].substr(start, length), allowable_tags);
}

function file( url ) {
    // Read entire file into an array  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/file
    // +   original by: Legaev Andrey
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
    // %        note 1: To avoid browser blocking issues's consider using jQuery's: $('#divId').load('http://url') instead.
    // *     example 1: file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: {0: '123'}
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {throw new Error('XMLHttpRequest not supported');}
       
    req.open("GET", url, false);
    req.send(null);
    
    return req.responseText.split('\n');
}

function file_exists (url) {
    // Returns true if filename exists  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/file_exists
    // +   original by: Enrique Gonzalez
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes. 
    // *     example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {throw new Error('XMLHttpRequest not supported');}
      
    // HEAD Results are usually shorter (faster) than GET
    req.open('HEAD', url, false);
    req.send(null);
    if (req.status == 200){
        return true;
    }
    
    return false;
}

function file_get_contents( url ) {
    // Read the entire file into a string  
    // 
    // version: 905.2108
    // discuss at: http://phpjs.org/functions/file_get_contents
    // +   original by: Legaev Andrey
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes. 
    // %        note 1: To avoid browser blocking issues's consider using jQuery's: $('#divId').load('http://url') instead.
    // %        note 2: flags, context, offset, maxLen arguments not implemented
    // *     example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    // Note: could also be made to optionally add to global $http_response_header as per http://php.net/manual/en/reserved.variables.httpresponseheader.php

    var tmp, headers = [], newTmp = [], k=0, i=0, href = '', pathPos = -1;
    var func = function (value) { return value.substring(1) !== ''; };
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {throw new Error('XMLHttpRequest not supported');}

    if (!/^https?:/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url())
        href = this.window.location.href;
        pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8)-1 : href.lastIndexOf('/');
        url = href.slice(0, pathPos+1)+url;
    }
    
    req.open("GET", url, false);
    req.send(null);

    tmp = req.getAllResponseHeaders();
    tmp = tmp.split('\n');
    for (k=0; k < tmp.length; k++) {
        if (func(tmp[k])) {
            newTmp.push(tmp[k]);
        }
    }
    tmp = newTmp;
    for (i=0; i < tmp.length; i++) {
        headers[i] = tmp[i];
    }
    this.$http_response_header = headers; // see http://php.net/manual/en/reserved.variables.httpresponseheader.php
    
    return req.responseText;
}

function filemtime(file) {
    // +   original by: Ole Vrijenhoek (http://www.nervous.nl/)
    // +    bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: get_headers
    // %        note 1:  Looks for Last-Modified in response header.
    // *     example 1: filemtime('http://www.un.org');
    // *     returns 1: 1241532483

    var headers = {};
    headers = this.get_headers(file, 1);
    return (headers && headers['Last-Modified'] && Date.parse(headers['Last-Modified'])/1000) || false;
}

function filesize (url) {
    // Get file size  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/filesize
    // +   original by: Enrique Gonzalez
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: T. Wild
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes. 
    // *     example 1: filesize('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '3'
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {throw new Error('XMLHttpRequest not supported');}
    
    req.open('HEAD', url, false);
    req.send(null);
    
    if (!req.getResponseHeader) {
        try {
            throw new Error('No getResponseHeader!');
        } catch(e){
            return false;
        }
    } else if (!req.getResponseHeader('Content-Length')) {
        try {
            throw new Error('No Content-Length!');
        } catch(e){
            return false;
        }
    } else {
        return req.getResponseHeader('Content-Length'); 
    }
}

function floatval(mixed_var) {
    // +   original by: Michael White (http://getsprink.com)
    // %        note 1: The native parseFloat() method of JavaScript returns NaN when it encounters a string before an int or float value.
    // *     example 1: floatval('150.03_page-section');
    // *     returns 1: 150.03
    // *     example 2: floatval('page: 3');
    // *     returns 2: 0
    // *     example 2: floatval('-50 + 8');
    // *     returns 2: -50
    return (parseFloat(mixed_var) || 0);
}

function floor(value) {
    // Returns the next lowest integer value from the number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/floor
    // +   original by: Onno Marsman
    // *     example 1: floor(8723321.4);
    // *     returns 1: 8723321
    
    return Math.floor(value);
}

function fmod(x, y) {
    // Returns the remainder of dividing x by y as a float  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/fmod
    // +   original by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: fmod(5.7, 1.3);
    // *     returns 1: 0.5
    
    var tmp, tmp2, p = 0, pY = 0, l = 0.0, l2 = 0.0;
    
    tmp = x.toExponential().match(/^.\.?(.*)e(.+)$/);
    p = parseInt(tmp[2], 10)-(tmp[1]+'').length;
    tmp = y.toExponential().match(/^.\.?(.*)e(.+)$/);
    pY = parseInt(tmp[2], 10)-(tmp[1]+'').length;
    
    if (pY > p) {
        p = pY;
    }
    
    tmp2 = (x%y);
    
    if (p < -100 || p > 20) {
        // toFixed will give an out of bound error so we fix it like this:
        l  = Math.round(Math.log(tmp2)/Math.log(10));
        l2 = Math.pow(10, l);
        
        return (tmp2 / l2).toFixed(l-p)*l2;
    } else {
        return parseFloat(tmp2.toFixed(-p));
    }
}

function fopen (filename, mode, use_include_path, context) {
    // Open a file or a URL and return a file pointer  
    // 
    // version: 905.2614
    // discuss at: http://phpjs.org/functions/fopen
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     returns 1: 'Resource id #1'

    var resource={}, i=0, that = this;

    // BEGIN file inclusion: file_get_contents
    var file_get_contents = function ( url ) {
        var req = that.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        if (!req) {
            throw new Error('XMLHttpRequest not supported');
        }
        if (!/^http/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url())
            url = that.window.location.href + '/' +url;
        }
        req.open("GET", url, false);
        req.send(null);
        return req.responseText;
    };
    // END file inclusion

    if (use_include_path === 1 || use_include_path === '1' || use_include_path === true) { 
        // Not implemented yet: Search for file in include path too
    }
    if (context) {
        // Not implemented yet, but could be useful to modify nature of HTTP request, etc.
    }

    for (i=0; i < mode.length; i++) { // Have to deal with other flags if ever allow
        if (mode[i] === 'r' && (!mode[i+1] || mode[i+1] !== '+')) {
            continue;
        }
        switch(mode[i]) {
            case 'r': // must have '+' now
            case 'w': // or 'w+'
            case 'a': // or 'a+'
            case 'x':// or 'x+'
                throw 'Writing is not implemented';
            case 'b':
            case 't':
                throw 'Windows-only modes are not supported';
            default:
                throw 'Unrecognized file mode passed to '+arguments.caller.name+'()';
        }
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.resourceData) {
        this.php_js.resourceData = {};
    }
    if (!this.php_js.resourceIdCounter) {
        this.php_js.resourceIdCounter = 0;
    }
    if (!this.php_js.resourceDataPointer) {
        this.php_js.resourceDataPointer = {};
    }

    function PHPJS_Resource (type, id, opener) { // Can reuse the following for other resources, just changing the instantiation
        // See http://php.net/manual/en/resource.php for types
        this.type = type;
        this.id = id;
        this.opener = opener;
    }
    PHPJS_Resource.prototype.toString = function () {
        return 'Resource id #'+this.id;
    };
    PHPJS_Resource.prototype.get_resource_type = function () {
        return this.type;
    };
    PHPJS_Resource.prototype.var_dump = function () {
        return 'resource('+this.id+') of type ('+this.type+')';
    };
    // END REDUNDANT

    this.php_js.resourceIdCounter++;
    this.php_js.resourceData[this.php_js.resourceIdCounter] = file_get_contents(filename);
    this.php_js.resourceDataPointer[this.php_js.resourceIdCounter] = 0;

    resource = new PHPJS_Resource('stream', this.php_js.resourceIdCounter, 'fopen');
    resource.mode = mode; // Add file-specific attributes

    return resource; // may be 'file' instead of 'stream' type on some systems
}

function fpassthru (handle) {
    // Output all remaining data from a file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/fpassthru
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fpassthru(handle);
    // *     returns 1: 3

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer || !handle || !handle.id) {
        return false;
    }

    var chrs = this.php_js.resourceData[handle.id].slice(this.php_js.resourceDataPointer[handle.id]);
    echo(chrs);
    return chrs;
}

function fread (handle, length) {
    // Binary-safe file read  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/fread
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fread(handle, 10);
    // *     returns 1: '123'

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer) {
        return false;
    }

    length = length < 8192 ? (Math.floor(length/2) || 1) : 4096; // 2 bytes per character (or surrogate) means limit of 8192 bytes = 4096 characters; ensure at least one

    var start = this.php_js.resourceDataPointer[handle.id];

    if (start === undefined) {
        return false; // Resource was already closed
    }

    if (!this.php_js.resourceData[handle.id][start]) {
        return ''; // already reached the end of the file (but pointer not closed)
    }

    this.php_js.resourceDataPointer[handle.id] += length;

    return this.php_js.resourceData[handle.id].substr(start, length); // Extra length won't be a problem here
}

function fseek (handle, offset, whence) {
    // Seek on a file pointer  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/fseek
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var h = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fseek(h, 100);
    // *     returns 1: 0

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer ||
            !handle || !handle.constructor || handle.constructor.name !== 'PHPJS_Resource') {
        return -1;
    }

    switch(whence) {
        case undefined: // fall-through
        case 'SEEK_SET':
            this.php_js.resourceDataPointer[handle.id] = offset/2+1;
            break;
        case 'SEEK_CUR':
            this.php_js.resourceDataPointer[handle.id] += offset/2+1;
            break;
        case 'SEEK_END':
            this.php_js.resourceDataPointer[handle.id] = this.php_js.resourceData[handle.id].length + offset/2 + 1;
            break;
        default:
            throw 'Unrecognized whence value for fseek()';
    }
    return 0;
}

function ftell (handle) {
    // Get file pointer's read/write position  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/ftell
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var h = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fread(h, 100);
    // *     example 1: ftell(h);
    // *     returns 1: 99

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer ||
            !handle || !handle.constructor || handle.constructor.name !== 'PHPJS_Resource') {
        return false;
    }
    return this.php_js.resourceDataPointer[handle.id]*2-1; // We're currently storing by character, so need to multiply by two; subtract one to appear like array pointer
}

function func_get_arg(num) {
    // Get the $arg_num'th argument that was passed to the function  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/func_get_arg
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: May not work in all JS implementations
    // *     example 1: function tmp_a() {return func_get_arg(1);}
    // *     example 1: tmp_a('a', 'b');
    // *     returns 1: 'a'
    if (!arguments.callee.caller) {
        try {
            throw new Error('Either you are using this in a browser which does not support the "caller" property or you are calling this from a global context');
            //return false;
        } catch(e){
            return false;
        }
    }

    if (num > arguments.callee.caller.arguments.length - 1) {
        try {
            throw new Error('Argument number is greater than the number of arguments actually passed');
            //return false;
        } catch(e){
            return false;
        }
    }

    return arguments.callee.caller.arguments[num];
}

function func_get_args() {
    // !No description available for func_get_args. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/func_get_args
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: May not work in all JS implementations
    // *     example 1: function tmp_a() {return func_get_args();}
    // *     example 1: tmp_a('a', 'b');
    // *     returns 1: ['a', 'b']
    if (!arguments.callee.caller) {
        try {
            throw new Error('Either you are using this in a browser which does not support the "caller" property or you are calling this from a global context');
            // return false;
        } catch(e){
            return false;
        }
    }

    return Array.prototype.slice.call(arguments.callee.caller.arguments);
}

function func_num_args() {
    // Get the number of arguments that were passed to the function  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/func_num_args
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: May not work in all JS implementations
    // *     example 1: function tmp_a() {return func_num_args();}
    // *     example 1: tmp_a('a', 'b');
    // *     returns 1: 2
    if (!arguments.callee.caller) {
        try {
            throw new Error('Either you are using this in a browser which does not support the "caller" property or you are calling this from a global context');
            //return false;
        } catch(e){
            return false;
        }
    }

    return arguments.callee.caller.arguments.length;
}

function function_exists( function_name ) {
    // Checks if the function exists  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/function_exists
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Steve Clay
    // +   improved by: Legaev Andrey
    // *     example 1: function_exists('isFinite');
    // *     returns 1: true
    if (typeof function_name == 'string'){
        return (typeof this.window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}

function get_cfg_var (varname) {
    // Get the value of a PHP configuration option  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/get_cfg_var
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: The ini values must be set within an ini file
    // *     example 1: get_cfg_var('date.timezone');
    // *     returns 1: 'Asia/Hong_Kong'
	if (this.php_js && this.php_js.ini && this.php_js.ini[varname].global_value !== undefined) {
		if (this.php_js.ini[varname].global_value === null) {
			return '';
		}
		return this.php_js.ini[varname].global_value;
	}
	return '';
}

function get_class(obj) {
    // Retrieves the class name  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_class
    // +   original by: Ates Goral (http://magnetiq.com)
    // +   improved by: David James
    // *     example 1: get_class(new (function MyClass() {}));
    // *     returns 1: "MyClass"
    // *     example 2: get_class({});
    // *     returns 2: "Object"
    // *     example 3: get_class([]);
    // *     returns 3: false
    // *     example 4: get_class(42);
    // *     returns 4: false
    // *     example 5: get_class(window);
    // *     returns 5: false
    // *     example 6: get_class(function MyFunction() {});
    // *     returns 6: false
    if (obj instanceof Object && !(obj instanceof Array) && 
        !(obj instanceof Function) && obj.constructor &&
        obj != this.window) {
        var arr = obj.constructor.toString().match(/function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return false;
}

function get_class_methods (name) {
    // Returns an array of method names for class or class instance.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_class_methods
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function Myclass () {this.privMethod = function(){}}
    // *     example 1: Myclass.classMethod = function () {}
    // *     example 1: Myclass.prototype.myfunc1 = function () {return(true);};
    // *     example 1: Myclass.prototype.myfunc2 = function () {return(true);}
    // *     example 1: get_class_methods('MyClass')
    // *     returns 1: {}
    var constructor, retArr={}, method = '';

    if (typeof name === 'function') {
        constructor = name;
    } else if (typeof name === 'string') {
        constructor = this.window[name];
    } else if (typeof name === 'object') {
        constructor = name;
        for (method in constructor.constructor) { // Get class methods of object's constructor
            if (typeof constructor.constructor[method] === 'function') {
                retArr[method] = constructor.constructor[method];
            }
        }
        // return retArr; // Uncomment to behave as "class" is usually defined in JavaScript convention (and see comment below)
    }
    for (method in constructor) {
        if (typeof constructor[method] === 'function') {
            retArr[method] = constructor[method];
        }
    }
     // Comment out this block to behave as "class" is usually defined in JavaScript convention (and see comment above)
    for (method in constructor.prototype) {
        if (typeof constructor.prototype[method] === 'function') {
            retArr[method] = constructor.prototype[method];
        }
    }
    
    return retArr;
}

function get_class_vars (name) {
    // Returns an array of default properties of the class.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_class_vars
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function Myclass(){privMethod = function(){};}
    // *     example 1: Myclass.classMethod = function () {}
    // *     example 1: Myclass.prototype.myfunc1 = function () {return(true);};
    // *     example 1: Myclass.prototype.myfunc2 = function () {return(true);}
    // *     example 1: get_class_vars('MyClass')
    // *     returns 1: {}
    
    var constructor, retArr={}, prop = '';
    
    if (typeof name === 'function') {
        constructor = name;
    } else if (typeof name === 'string') {
        constructor = this.window[name];
    }
    
    for (prop in constructor) {
        if (typeof constructor[prop] !== 'function' && prop !== 'prototype') {
            retArr[prop] = constructor[prop];
        }
    }
     // Comment out this block to behave as "class" is usually defined in JavaScript convention
    if (constructor.prototype) {
        for (prop in constructor.prototype) {
            if (typeof constructor.prototype[prop] !== 'function') {
                retArr[prop] = constructor.prototype[prop];
            }
        }
    }
    
    return retArr;
}

function get_declared_classes() {
    // !No description available for get_declared_classes. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_declared_classes
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +    depends on: class_exists
    // *     example 1: function A (z) {this.z=z} // Assign 'this' in constructor, making it class-like
    // *     example 1: function B () {}
    // *     example 1: B.c = function () {}; // Add a static method, making it class-like
    // *     example 1: function C () {}
    // *     example 1: C.prototype.z = function () {}; // Add to prototype, making it behave as a "class"
    // *     example 1: get_declared_classes()
    // *     returns 1: [C, B, A]

    var i = '', j = '', arr = [], already = {};

    for (i in this.window) {
        try {
            if (typeof this.window[i] === 'function') {
                if (!already[i] && this.class_exists(i)) {
                    already[i] = 1;
                    arr.push(i);
                }
            } else if (typeof this.window[i] === 'object') {
                for (j in this.window[i]) {
                    if (typeof this.window[j] === 'function' && this.window[j] && !already[j] && this.class_exists(j)) {
                        already[j] = 1;
                        arr.push(j);
                    }
                }
            }
        } catch (e) {

        }
    }

    return arr;
}

function get_defined_constants (categorize ) {
    // +    original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Could possibly substitute some others like M_PI with JavaScript's Math.PI, etc., but here
    // %        note 1: sticking to PHP, except for changing: NULL to null, NAN to NaN, and INF to Number.POSITIVE_INFINITY
    // %        note 2: TRUE, FALSE, and NULL capitalized constants (as in PHP) could work ok in some
    // %        note 2: implementations, but not all, so they are commented out
    // %        note 3: We used a PHP script to auto-convert these, so we can simply reuse it to add more below if we
    // %        note 3: implement more extensions needing constants, assuming we have a PHP set-up which
    // %        note 3: uses the extensions!
    // %        note 4: If you do ini_set('phpjs.get_defined_constants.setConstants', 'this') then call this function,
    // %        note 4: it will set the PHP constants as globals for you on the "this" object. In the namespaced version, this
    // %        note 4: means the "constants" will be attached directly to the $P object: e.g., $P.PREG_OFFSET_CAPTURE
    // %        note 4: In the non-namespaced version, this will act like the setting mentioned in note 6
    // %        note 4: If you do ini_set('phpjs.get_defined_constants.setConstants', 'thisExt') then call this function,
    // %        note 4: it will set the PHP constants for you, but will first create a namespace on your object
    // %        note 4: for each extension to which the "constants" will be added. For example, $P.pcre.PREG_OFFSET_CAPTURE
    // %        note 4: For the non-namespaced version, this will be created on window: alert(pcre.PREG_OFFSET_CAPTURE);
    // %        note 4: If you do ini_set('phpjs.get_defined_constants.setConstants', true) then call this function,
    // %        note 4: it will set the PHP constants as window globals for you, even if you are using the PHP.JS namespaced
    // %        note 4: version. For example, you can just do: alert(PREG_OFFSET_CAPTURE); . Only the constants set directly
    // %        note 4: at the level of window globals, will actually be immutable constants.
    // %        note 5: Note that our functions might not have been designed yet to handle PHP-style constants if at all, as
    // %        note 5: some of our extensions rely simply on the constant name being passed in to the function as a
    // %        note 5:  string to work as a flag
    // -    depends on: define
    // *     example 1: var cnsts = get_defined_constants();
    // *     example 1: cnsts.E_NOTICE;
    // *     returns 1: 8
    // *     example 2: var cnsts = get_defined_constants(true); // passing false will produce the same value! (in PHP as well as here)
    // *     example 2: cnsts.internal.E_NOTICE;
    // *     returns 2: 8

    var ext = '', cnst = '', constObj = {}, flatConstObj = {}, win, thisExt = false;

    constObj = {
      'internal' : {
        'E_ERROR' : 1,
        'E_RECOVERABLE_ERROR' : 4096,
        'E_WARNING' : 2,
        'E_PARSE' : 4,
        'E_NOTICE' : 8,
        'E_STRICT' : 2048,
        'E_CORE_ERROR' : 16,
        'E_CORE_WARNING' : 32,
        'E_COMPILE_ERROR' : 64,
        'E_COMPILE_WARNING' : 128,
        'E_USER_ERROR' : 256,
        'E_USER_WARNING' : 512,
        'E_USER_NOTICE' : 1024,
        'E_ALL' : 6143,
        /* // Could work ok in some implementations, but not all, so commenting out
        'TRUE' : true,
        'FALSE' : false,
        'NULL' : null,
        */
        'ZEND_THREAD_SAFE' : true,
        'PHP_VERSION' : '5.2.6',
        'PHP_OS' : 'WINNT',
        'PHP_SAPI' : 'apache2handler',
        'DEFAULT_INCLUDE_PATH' : '.;C:\\php5\\pear',
        'PEAR_INSTALL_DIR' : 'C:\\php5\\pear',
        'PEAR_EXTENSION_DIR' : 'C:\\php5',
        'PHP_EXTENSION_DIR' : 'C:\\php5',
        'PHP_PREFIX' : 'C:\\php5',
        'PHP_BINDIR' : 'C:\\php5',
        'PHP_LIBDIR' : 'C:\\php5',
        'PHP_DATADIR' : 'C:\\php5',
        'PHP_SYSCONFDIR' : 'C:\\php5',
        'PHP_LOCALSTATEDIR' : 'C:\\php5',
        'PHP_CONFIG_FILE_PATH' : 'C:\\Windows',
        'PHP_CONFIG_FILE_SCAN_DIR' : '',
        'PHP_SHLIB_SUFFIX' : 'dll',
        'PHP_EOL' : '\n',
        'PHP_INT_MAX' : 2147483647,
        'PHP_INT_SIZE' : 4,
        'PHP_OUTPUT_HANDLER_START' : 1,
        'PHP_OUTPUT_HANDLER_CONT' : 2,
        'PHP_OUTPUT_HANDLER_END' : 4,
        'UPLOAD_ERR_OK' : 0,
        'UPLOAD_ERR_INI_SIZE' : 1,
        'UPLOAD_ERR_FORM_SIZE' : 2,
        'UPLOAD_ERR_PARTIAL' : 3,
        'UPLOAD_ERR_NO_FILE' : 4,
        'UPLOAD_ERR_NO_TMP_DIR' : 6,
        'UPLOAD_ERR_CANT_WRITE' : 7,
        'UPLOAD_ERR_EXTENSION' : 8
      },
      'pcre' : {
        'PREG_PATTERN_ORDER' : 1,
        'PREG_SET_ORDER' : 2,
        'PREG_OFFSET_CAPTURE' : 256,
        'PREG_SPLIT_NO_EMPTY' : 1,
        'PREG_SPLIT_DELIM_CAPTURE' : 2,
        'PREG_SPLIT_OFFSET_CAPTURE' : 4,
        'PREG_GREP_INVERT' : 1,
        'PREG_NO_ERROR' : 0,
        'PREG_INTERNAL_ERROR' : 1,
        'PREG_BACKTRACK_LIMIT_ERROR' : 2,
        'PREG_RECURSION_LIMIT_ERROR' : 3,
        'PREG_BAD_UTF8_ERROR' : 4,
        'PCRE_VERSION' : '7.6 2008-01-28'
      },
      'session' : {
        'DATE_ATOM' : 'Y-m-d\\TH:i:sP',
        'DATE_COOKIE' : 'l, d-M-y H:i:s T',
        'DATE_ISO8601' : 'Y-m-d\\TH:i:sO',
        'DATE_RFC822' : 'D, d M y H:i:s O',
        'DATE_RFC850' : 'l, d-M-y H:i:s T',
        'DATE_RFC1036' : 'D, d M y H:i:s O',
        'DATE_RFC1123' : 'D, d M Y H:i:s O',
        'DATE_RFC2822' : 'D, d M Y H:i:s O',
        'DATE_RFC3339' : 'Y-m-d\\TH:i:sP',
        'DATE_RSS' : 'D, d M Y H:i:s O',
        'DATE_W3C' : 'Y-m-d\\TH:i:sP',
        'SUNFUNCS_RET_TIMESTAMP' : 0,
        'SUNFUNCS_RET_STRING' : 1,
        'SUNFUNCS_RET_DOUBLE' : 2
      },
      'standard' : {
        'CONNECTION_ABORTED' : 1,
        'CONNECTION_NORMAL' : 0,
        'CONNECTION_TIMEOUT' : 2,
        'INI_USER' : 1,
        'INI_PERDIR' : 2,
        'INI_SYSTEM' : 4,
        'INI_ALL' : 7,
        'PHP_URL_SCHEME' : 0,
        'PHP_URL_HOST' : 1,
        'PHP_URL_PORT' : 2,
        'PHP_URL_USER' : 3,
        'PHP_URL_PASS' : 4,
        'PHP_URL_PATH' : 5,
        'PHP_URL_QUERY' : 6,
        'PHP_URL_FRAGMENT' : 7,
        'M_E' : 2.718281828459,
        'M_LOG2E' : 1.442695040889,
        'M_LOG10E' : 0.43429448190325,
        'M_LN2' : 0.69314718055995,
        'M_LN10' : 2.302585092994,
        'M_PI' : 3.1415926535898,
        'M_PI_2' : 1.5707963267949,
        'M_PI_4' : 0.78539816339745,
        'M_1_PI' : 0.31830988618379,
        'M_2_PI' : 0.63661977236758,
        'M_SQRTPI' : 1.7724538509055,
        'M_2_SQRTPI' : 1.1283791670955,
        'M_LNPI' : 1.1447298858494,
        'M_EULER' : 0.57721566490153,
        'M_SQRT2' : 1.4142135623731,
        'M_SQRT1_2' : 0.70710678118655,
        'M_SQRT3' : 1.7320508075689,
        'INF' : Number.POSITIVE_INFINITY,
        'NAN' : 0,
        'INFO_GENERAL' : 1,
        'INFO_CREDITS' : 2,
        'INFO_CONFIGURATION' : 4,
        'INFO_MODULES' : 8,
        'INFO_ENVIRONMENT' : 16,
        'INFO_VARIABLES' : 32,
        'INFO_LICENSE' : 64,
        'INFO_ALL' : -1,
        'CREDITS_GROUP' : 1,
        'CREDITS_GENERAL' : 2,
        'CREDITS_SAPI' : 4,
        'CREDITS_MODULES' : 8,
        'CREDITS_DOCS' : 16,
        'CREDITS_FULLPAGE' : 32,
        'CREDITS_QA' : 64,
        'CREDITS_ALL' : -1,
        'HTML_SPECIALCHARS' : 0,
        'HTML_ENTITIES' : 1,
        'ENT_COMPAT' : 2,
        'ENT_QUOTES' : 3,
        'ENT_NOQUOTES' : 0,
        'STR_PAD_LEFT' : 0,
        'STR_PAD_RIGHT' : 1,
        'STR_PAD_BOTH' : 2,
        'PATHINFO_DIRNAME' : 1,
        'PATHINFO_BASENAME' : 2,
        'PATHINFO_EXTENSION' : 4,
        'PATHINFO_FILENAME' : 8,
        'CHAR_MAX' : 127,
        'LC_CTYPE' : 2,
        'LC_NUMERIC' : 4,
        'LC_TIME' : 5,
        'LC_COLLATE' : 1,
        'LC_MONETARY' : 3,
        'LC_ALL' : 0,
        'SEEK_SET' : 0,
        'SEEK_CUR' : 1,
        'SEEK_END' : 2,
        'LOCK_SH' : 1,
        'LOCK_EX' : 2,
        'LOCK_UN' : 3,
        'LOCK_NB' : 4,
        'STREAM_NOTIFY_CONNECT' : 2,
        'STREAM_NOTIFY_AUTH_REQUIRED' : 3,
        'STREAM_NOTIFY_AUTH_RESULT' : 10,
        'STREAM_NOTIFY_MIME_TYPE_IS' : 4,
        'STREAM_NOTIFY_FILE_SIZE_IS' : 5,
        'STREAM_NOTIFY_REDIRECTED' : 6,
        'STREAM_NOTIFY_PROGRESS' : 7,
        'STREAM_NOTIFY_FAILURE' : 9,
        'STREAM_NOTIFY_COMPLETED' : 8,
        'STREAM_NOTIFY_RESOLVE' : 1,
        'STREAM_NOTIFY_SEVERITY_INFO' : 0,
        'STREAM_NOTIFY_SEVERITY_WARN' : 1,
        'STREAM_NOTIFY_SEVERITY_ERR' : 2,
        'STREAM_FILTER_READ' : 1,
        'STREAM_FILTER_WRITE' : 2,
        'STREAM_FILTER_ALL' : 3,
        'STREAM_CLIENT_PERSISTENT' : 1,
        'STREAM_CLIENT_ASYNC_CONNECT' : 2,
        'STREAM_CLIENT_CONNECT' : 4,
        'STREAM_CRYPTO_METHOD_SSLv2_CLIENT' : 0,
        'STREAM_CRYPTO_METHOD_SSLv3_CLIENT' : 1,
        'STREAM_CRYPTO_METHOD_SSLv23_CLIENT' : 2,
        'STREAM_CRYPTO_METHOD_TLS_CLIENT' : 3,
        'STREAM_CRYPTO_METHOD_SSLv2_SERVER' : 4,
        'STREAM_CRYPTO_METHOD_SSLv3_SERVER' : 5,
        'STREAM_CRYPTO_METHOD_SSLv23_SERVER' : 6,
        'STREAM_CRYPTO_METHOD_TLS_SERVER' : 7,
        'STREAM_SHUT_RD' : 0,
        'STREAM_SHUT_WR' : 1,
        'STREAM_SHUT_RDWR' : 2,
        'STREAM_PF_INET' : 2,
        'STREAM_PF_INET6' : 23,
        'STREAM_PF_UNIX' : 1,
        'STREAM_IPPROTO_IP' : 0,
        'STREAM_IPPROTO_TCP' : 6,
        'STREAM_IPPROTO_UDP' : 17,
        'STREAM_IPPROTO_ICMP' : 1,
        'STREAM_IPPROTO_RAW' : 255,
        'STREAM_SOCK_STREAM' : 1,
        'STREAM_SOCK_DGRAM' : 2,
        'STREAM_SOCK_RAW' : 3,
        'STREAM_SOCK_SEQPACKET' : 5,
        'STREAM_SOCK_RDM' : 4,
        'STREAM_PEEK' : 2,
        'STREAM_OOB' : 1,
        'STREAM_SERVER_BIND' : 4,
        'STREAM_SERVER_LISTEN' : 8,
        'FILE_USE_INCLUDE_PATH' : 1,
        'FILE_IGNORE_NEW_LINES' : 2,
        'FILE_SKIP_EMPTY_LINES' : 4,
        'FILE_APPEND' : 8,
        'FILE_NO_DEFAULT_CONTEXT' : 16,
        'PSFS_PASS_ON' : 2,
        'PSFS_FEED_ME' : 1,
        'PSFS_ERR_FATAL' : 0,
        'PSFS_FLAG_NORMAL' : 0,
        'PSFS_FLAG_FLUSH_INC' : 1,
        'PSFS_FLAG_FLUSH_CLOSE' : 2,
        'CRYPT_SALT_LENGTH' : 12,
        'CRYPT_STD_DES' : 1,
        'CRYPT_EXT_DES' : 0,
        'CRYPT_MD5' : 1,
        'CRYPT_BLOWFISH' : 0,
        'DIRECTORY_SEPARATOR' : '\\',
        'PATH_SEPARATOR' : ';',
        'GLOB_BRACE' : 128,
        'GLOB_MARK' : 8,
        'GLOB_NOSORT' : 32,
        'GLOB_NOCHECK' : 16,
        'GLOB_NOESCAPE' : 4096,
        'GLOB_ERR' : 4,
        'GLOB_ONLYDIR' : 1073741824,
        'GLOB_AVAILABLE_FLAGS' : 1073746108,
        'LOG_EMERG' : 1,
        'LOG_ALERT' : 1,
        'LOG_CRIT' : 1,
        'LOG_ERR' : 4,
        'LOG_WARNING' : 5,
        'LOG_NOTICE' : 6,
        'LOG_INFO' : 6,
        'LOG_DEBUG' : 6,
        'LOG_KERN' : 0,
        'LOG_USER' : 8,
        'LOG_MAIL' : 16,
        'LOG_DAEMON' : 24,
        'LOG_AUTH' : 32,
        'LOG_SYSLOG' : 40,
        'LOG_LPR' : 48,
        'LOG_NEWS' : 56,
        'LOG_UUCP' : 64,
        'LOG_CRON' : 72,
        'LOG_AUTHPRIV' : 80,
        'LOG_PID' : 1,
        'LOG_CONS' : 2,
        'LOG_ODELAY' : 4,
        'LOG_NDELAY' : 8,
        'LOG_NOWAIT' : 16,
        'LOG_PERROR' : 32,
        'EXTR_OVERWRITE' : 0,
        'EXTR_SKIP' : 1,
        'EXTR_PREFIX_SAME' : 2,
        'EXTR_PREFIX_ALL' : 3,
        'EXTR_PREFIX_INVALID' : 4,
        'EXTR_PREFIX_IF_EXISTS' : 5,
        'EXTR_IF_EXISTS' : 6,
        'EXTR_REFS' : 256,
        'SORT_ASC' : 4,
        'SORT_DESC' : 3,
        'SORT_REGULAR' : 0,
        'SORT_NUMERIC' : 1,
        'SORT_STRING' : 2,
        'SORT_LOCALE_STRING' : 5,
        'CASE_LOWER' : 0,
        'CASE_UPPER' : 1,
        'COUNT_NORMAL' : 0,
        'COUNT_RECURSIVE' : 1,
        'ASSERT_ACTIVE' : 1,
        'ASSERT_CALLBACK' : 2,
        'ASSERT_BAIL' : 3,
        'ASSERT_WARNING' : 4,
        'ASSERT_QUIET_EVAL' : 5,
        'STREAM_USE_PATH' : 1,
        'STREAM_IGNORE_URL' : 2,
        'STREAM_ENFORCE_SAFE_MODE' : 4,
        'STREAM_REPORT_ERRORS' : 8,
        'STREAM_MUST_SEEK' : 16,
        'STREAM_URL_STAT_LINK' : 1,
        'STREAM_URL_STAT_QUIET' : 2,
        'STREAM_MKDIR_RECURSIVE' : 1,
        'STREAM_IS_URL' : 1,
        'IMAGETYPE_GIF' : 1,
        'IMAGETYPE_JPEG' : 2,
        'IMAGETYPE_PNG' : 3,
        'IMAGETYPE_SWF' : 4,
        'IMAGETYPE_PSD' : 5,
        'IMAGETYPE_BMP' : 6,
        'IMAGETYPE_TIFF_II' : 7,
        'IMAGETYPE_TIFF_MM' : 8,
        'IMAGETYPE_JPC' : 9,
        'IMAGETYPE_JP2' : 10,
        'IMAGETYPE_JPX' : 11,
        'IMAGETYPE_JB2' : 12,
        'IMAGETYPE_SWC' : 13,
        'IMAGETYPE_IFF' : 14,
        'IMAGETYPE_WBMP' : 15,
        'IMAGETYPE_JPEG2000' : 9,
        'IMAGETYPE_XBM' : 16
      }
    };

    if (this.php_js && this.php_js.ini && this.php_js.ini['phpjs.get_defined_constants.setConstants'] &&
            this.php_js.ini['phpjs.get_defined_constants.setConstants'].local_value) {
        // Allow us to set a configuration to let this function set global constants
        if (this.php_js.ini['phpjs.get_defined_constants.setConstants'].local_value === 'this') {
            win = this;
        }
        else if (this.php_js.ini['phpjs.get_defined_constants.setConstants'].local_value === 'thisExt') {
            win = this;
            thisExt = true;
        }
        else {
            win = this.window;
        }
        
        for (ext in constObj) {
            if (thisExt) { // Allows namespacing constants (e.g,. this.pcre.PREG_OFFSET_CAPTURE)
                for (cnst in constObj[ext]) {
                    if (!win[ext]) {
                        win[ext] = {};
                    }
                    // These will not be real constants!
                    win[ext][cnst] = constObj[ext][cnst];
                }
            }
            else {
                for (cnst in constObj[ext]) {
                    if (this === this.window) { // Take advantage of fact, in this case we can make real constants
                        this.define(cnst, constObj[ext][cnst]);
                    }
                    else {
                        // These will not be real constants!
                        win[cnst] = constObj[ext][cnst];
                    }
                }
            }
        }
    }

    if (typeof categorize !== 'undefined') { // PHP will return if any argument is set, even false
        return constObj;
    }

    for (ext in constObj) {
        for (cnst in constObj[ext]) {
            flatConstObj[cnst] = constObj[ext][cnst];
        }
    }
    return flatConstObj;
}

function get_defined_functions() {
    // Returns an array of all defined functions  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_defined_functions
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Test case 1: If get_defined_functions can find itself in the defined functions, it worked :)
    // *     example 1: function test_in_array(array, p_val) {for(var i = 0, l = array.length; i < l; i++) {if(array[i] == p_val) return true;} return false;}
    // *     example 1: funcs = get_defined_functions();
    // *     example 1: found = test_in_array(funcs, 'get_defined_functions');
    // *     results 1: found == true
    var i = '', arr = [], already = {};

    for (i in this.window) {
        try {
            if (typeof this.window[i] === 'function') {
                if (!already[i]) {
                    already[i] = 1;
                    arr.push(i);
                }
            }
            else if (typeof this.window[i] === 'object') {
                for (var j in this.window[i]) {
                    if (typeof this.window[j] === 'function' && this.window[j] && !already[j]) {
                        already[j] = 1;
                        arr.push(j);
                    }
                }
            }
        }
        catch (e) {

        }
    }

    return arr;
}

function get_defined_vars() {
    // Returns an associative array of names and values of all currently defined variable names (variables in the current scope)  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_defined_vars
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Test case 1: If get_defined_vars can find itself in the defined vars, it worked :)
    // *     example 1: function test_in_array(array, p_val) {for(var i = 0, l = array.length; i < l; i++) {if(array[i] == p_val) return true;} return false;}
    // *     example 1: funcs = get_defined_vars();
    // *     example 1: found = test_in_array(funcs, 'get_defined_vars');
    // *     results 1: found == true
    var i = '', arr = [], already = {};

    for (i in this.window) {
        try {
            if (typeof this.window[i] === 'function') {
                if (!already[i]) {
                    already[i] = 1;
                    arr.push(i);
                }
            }
            else if (typeof this.window[i] === 'object') {
                for (var j in this.window[i]) {
                    if (typeof this.window[j] === 'function' && this.window[j] && !already[j]) {
                        already[j] = 1;
                        arr.push(j);
                    }
                }
            }
        }
        catch (e) {

        }
    }

    return arr;
}

function get_headers(url, format) {
    // +   original by: Paulo Ricardo F. Santos
    // +    bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
    // *     example 1: get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm')[0];
    // *     returns 1: 'Date: Wed, 13 May 2009 23:53:11 GMT'
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {
        throw new Error('XMLHttpRequest not supported');
    }
    var tmp, headers, pair, i, j = 0;

    req.open('HEAD', url, false);
    req.send(null);

    if (req.readyState < 3) {
        return false;
    }

    tmp = req.getAllResponseHeaders();
    tmp = tmp.split('\n');
    tmp = this.array_filter(tmp, function (value) { return value.substring(1) !== ''; });
    headers = format ? {} : [];

    for (i in tmp) {
        if (format) {
            pair = tmp[i].split(':');
            headers[pair.splice(0, 1)] = pair.join(':').substring(1);
        } else {
            headers[j++] = tmp[i];
        }
    }
    return headers;
}

function get_html_translation_table(table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable 	  = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    // ascii decimals for better compatibility
    entities['38'] = '&amp;';
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';

    if (useTable === 'HTML_ENTITIES') {
	    entities['160'] = '&nbsp;';
	    entities['161'] = '&iexcl;';
	    entities['162'] = '&cent;';
	    entities['163'] = '&pound;';
	    entities['164'] = '&curren;';
	    entities['165'] = '&yen;';
	    entities['166'] = '&brvbar;';
	    entities['167'] = '&sect;';
	    entities['168'] = '&uml;';
	    entities['169'] = '&copy;';
	    entities['170'] = '&ordf;';
	    entities['171'] = '&laquo;';
	    entities['172'] = '&not;';
	    entities['173'] = '&shy;';
	    entities['174'] = '&reg;';
	    entities['175'] = '&macr;';
	    entities['176'] = '&deg;';
	    entities['177'] = '&plusmn;';
	    entities['178'] = '&sup2;';
	    entities['179'] = '&sup3;';
	    entities['180'] = '&acute;';
	    entities['181'] = '&micro;';
	    entities['182'] = '&para;';
	    entities['183'] = '&middot;';
	    entities['184'] = '&cedil;';
	    entities['185'] = '&sup1;';
	    entities['186'] = '&ordm;';
	    entities['187'] = '&raquo;';
	    entities['188'] = '&frac14;';
	    entities['189'] = '&frac12;';
	    entities['190'] = '&frac34;';
	    entities['191'] = '&iquest;';
	    entities['192'] = '&Agrave;';
	    entities['193'] = '&Aacute;';
	    entities['194'] = '&Acirc;';
	    entities['195'] = '&Atilde;';
	    entities['196'] = '&Auml;';
	    entities['197'] = '&Aring;';
	    entities['198'] = '&AElig;';
	    entities['199'] = '&Ccedil;';
	    entities['200'] = '&Egrave;';
	    entities['201'] = '&Eacute;';
	    entities['202'] = '&Ecirc;';
	    entities['203'] = '&Euml;';
	    entities['204'] = '&Igrave;';
	    entities['205'] = '&Iacute;';
	    entities['206'] = '&Icirc;';
	    entities['207'] = '&Iuml;';
	    entities['208'] = '&ETH;';
	    entities['209'] = '&Ntilde;';
	    entities['210'] = '&Ograve;';
	    entities['211'] = '&Oacute;';
	    entities['212'] = '&Ocirc;';
	    entities['213'] = '&Otilde;';
	    entities['214'] = '&Ouml;';
	    entities['215'] = '&times;';
	    entities['216'] = '&Oslash;';
	    entities['217'] = '&Ugrave;';
	    entities['218'] = '&Uacute;';
	    entities['219'] = '&Ucirc;';
	    entities['220'] = '&Uuml;';
	    entities['221'] = '&Yacute;';
	    entities['222'] = '&THORN;';
	    entities['223'] = '&szlig;';
	    entities['224'] = '&agrave;';
	    entities['225'] = '&aacute;';
	    entities['226'] = '&acirc;';
	    entities['227'] = '&atilde;';
	    entities['228'] = '&auml;';
	    entities['229'] = '&aring;';
	    entities['230'] = '&aelig;';
	    entities['231'] = '&ccedil;';
	    entities['232'] = '&egrave;';
	    entities['233'] = '&eacute;';
	    entities['234'] = '&ecirc;';
	    entities['235'] = '&euml;';
	    entities['236'] = '&igrave;';
	    entities['237'] = '&iacute;';
	    entities['238'] = '&icirc;';
	    entities['239'] = '&iuml;';
	    entities['240'] = '&eth;';
	    entities['241'] = '&ntilde;';
	    entities['242'] = '&ograve;';
	    entities['243'] = '&oacute;';
	    entities['244'] = '&ocirc;';
	    entities['245'] = '&otilde;';
	    entities['246'] = '&ouml;';
	    entities['247'] = '&divide;';
	    entities['248'] = '&oslash;';
	    entities['249'] = '&ugrave;';
	    entities['250'] = '&uacute;';
	    entities['251'] = '&ucirc;';
	    entities['252'] = '&uuml;';
	    entities['253'] = '&yacute;';
	    entities['254'] = '&thorn;';
	    entities['255'] = '&yuml;';
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function get_included_files() {
    // Returns an array with the file names that were included (includes require and once varieties)  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/get_included_files
    // +   original by: Michael White (http://getsprink.com)
	// %        note 1: Uses global: php_js to keep track of included files
    // *     example 1: get_included_files();
    // *     returns 1: ['http://kevin.vanzonneveld.net/pj_tester.php']
    var cur_file = {};
    cur_file[this.window.location.href] = 1;
    if(!this.php_js) {
        this.php_js = {};
    }
    if(!this.php_js.includes) {
        this.php_js.includes = cur_file;
    }

    var includes = [];
    var i = 0;
    for(var key in this.php_js.includes){
        includes[i] = key;
        i++;
    }

    return includes;
}

function get_object_vars (obj) {
    // Returns an array of object properties  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/get_object_vars
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function Myclass () {this.privMethod = function(){}}
    // *     example 1: Myclass.classMethod = function () {}
    // *     example 1: Myclass.prototype.myfunc1 = function () {return(true);};
    // *     example 1: Myclass.prototype.myfunc2 = function () {return(true);}
    // *     example 1: get_object_vars('MyClass')
    // *     returns 1: {}
    var retArr = {}, prop = '';

    for (prop in obj) {
        if (typeof obj[prop] !== 'function' && prop !== 'prototype') {
            retArr[prop] = obj[prop];
        }
    }
    for (prop in obj.prototype) {
        if (typeof obj.prototype[prop] !== 'function') {
            retArr[prop] = obj.prototype[prop];
        }
    }
    
    return retArr;
}

function get_required_files () {
    // !No description available for get_required_files. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/get_required_files
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: get_included_files
    // *     example 1: get_required_files();
    // *     returns 1: ['http://kevin.vanzonneveld.net/pj_tester.php']
    return this.get_included_files();
}

function get_resource_type (handle) {
    // Get the resource type name for a given resource  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/get_resource_type
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: get_resource_type('a');
    // *     returns 1: false

    if (!handle || typeof handle !== 'object' || !handle.constructor || handle.constructor.name !== 'PHPJS_Resource') {
        return false;
    }

    return handle.get_resource_type();
}

function getdate(timestamp) {
    // Get date/time information  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/getdate
    // +   original by: Paulo Ricardo F. Santos
    // *     example 1: getdate(1055901520);
    // *     returns 1: {'seconds': 40, 'minutes': 58, 'hours': 21, 'mday': 17, 'wday': 2, 'mon': 6, 'year': 2003, 'yday': 167, 'weekday': 'Tuesday', 'month': 'June', '0': 1055901520}
    var _w = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var _m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var d = (typeof timestamp == 'number') ? new Date(timestamp * 1000) : new Date();
    var w = d.getDay();
    var m = d.getMonth();
    var y = d.getFullYear();
    var r = {};

    r.seconds = d.getSeconds();
    r.minutes = d.getMinutes();
    r.hours = d.getHours();
    r.mday = d.getDate();
    r.wday = w;
    r.mon = m + 1;
    r.year = y;
    r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000);
    r.weekday = _w[w];
    r.month = _m[m];
    r['0'] = parseInt(d.getTime() / 1000, 10);

    return r;
}

function getenv (varname) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %        note 1: We are not using $_ENV as in PHP, you could define
    // %        note 1: "$_ENV = this.php_js.ENV;" and get/set accordingly
    // %        note 2: Returns e.g. 'en-US' when set global this.php_js.ENV is set
    // %        note 3: Uses global: php_js to store environment info
	// *     example 1: getenv('LC_ALL');
	// *     returns 1: false
    
	if (!this.php_js || !this.php_js.ENV || !this.php_js.ENV[varname]) {
		return false;
	}
    
	return this.php_js.ENV[varname];
}

function getlastmod () {
	// http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Will not work on browsers which don't support document.lastModified
    // *     example 1: getlastmod();
    // *     returns 1: 1237610043
	return new Date(this.window.document.lastModified).getTime()/1000;
}

function getrandmax()
{
    // Returns the maximum value a random number can have  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/getrandmax
    // +   original by: Onno Marsman
    // *     example 1: getrandmax();
    // *     returns 1: 2147483647
    return 2147483647;
}

function gettimeofday (return_float) {
    // Returns the current time as array  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/gettimeofday
    // + original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      derived from: Josh Fraser (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/)
    // +         parts by: Breaking Par Consulting Inc (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7)
    // *     example 1: gettimeofday();
    // *     returns 1: {sec: 12, usec: 153000, minuteswest: -480, dsttime: 0}
    // *     example 1: gettimeofday(true);
    // *     returns 1: 1238748978.49

    var t = new Date(), dst = 0;

    if (return_float) {
        return t.getTime()/1000;
    }

    // Calculate Daylight Saving Time
    var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
    var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
    var temp = jan1.toUTCString();
    var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
    temp = june1.toUTCString();
    var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
    var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
    var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);

    if (std_time_offset === daylight_time_offset) {
        dst = 0; // daylight savings time is NOT observed
    }
    else {
        // positive is southern, negative is northern hemisphere
        var hemisphere = std_time_offset - daylight_time_offset;
        if (hemisphere >= 0) {
            std_time_offset = daylight_time_offset;
        }
        dst = 1; // daylight savings time is observed
    }

    return {
        sec : t.getUTCSeconds(),
        usec : t.getUTCMilliseconds()*1000,
        minuteswest : t.getTimezoneOffset(),
        dsttime: dst
    };
}

function gettype( mixed_var ) {
    // Returns the type of the variable  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/gettype
    // +   original by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Douglas Crockford (http://javascript.crockford.com)
    // +   input by: KELAN
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: is_float
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: gettype(1);
    // *     returns 1: 'integer'
    // *     example 2: gettype(undefined);
    // *     returns 2: 'undefined'
    // *     example 3: gettype({0: 'Kevin van Zonneveld'});
    // *     returns 3: 'array'
    // *     example 4: gettype('foo');
    // *     returns 4: 'string'
    // *     example 5: gettype({0: function () {return false;}});
    // *     returns 5: 'array'
    var s = typeof mixed_var, name;
    if (s === 'object') {
        if (mixed_var !== null) { // From: http://javascript.crockford.com/remedial.html
            if (typeof mixed_var.length === 'number' &&
                    !(mixed_var.propertyIsEnumerable('length')) &&
                    typeof mixed_var.splice === 'function') {
                s = 'array';
            }
            else if (mixed_var.constructor && mixed_var.constructor.name) {
                name = mixed_var.constructor.name;
                if (name === 'Date') {
                    s = 'date'; // not in PHP
                }
                else if (name === 'RegExp') {
                    s = 'regexp'; // not in PHP
                }
                else if (name === 'PHPJS_Resource') { // Check against our own resource constructor
                    s = 'resource';
                }
            }
        } else {
            s = 'null';
        }
    }
    else if (s === 'number') {
        s = this.is_float(mixed_var) ? 'double' : 'integer';
    }
    return s;
}

function gmdate (format, timestamp) {
    // Format a GMT date/time  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/gmdate
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: date
    // *     example 1: gmdate('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400); // Return will depend on your timezone
    // *     returns 1: '07:09:40 m is month'
    var dt = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp));
    timestamp = Date.parse(dt.toUTCString().slice(0, -4))/1000;
    return this.date(format, timestamp);
}

function gmmktime() {
    // Get UNIX timestamp for a GMT date  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/gmmktime
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   derived from: mktime
    // *     example 1: gmmktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201875002

    var no=0, i = 0, ma=0, mb=0, d = new Date(), dn = new Date(), argv = arguments, argc = argv.length;

    var dateManip = {
        0: function(tt){ return d.setUTCHours(tt); },
        1: function(tt){ return d.setUTCMinutes(tt); },
        2: function(tt){ var set = d.setUTCSeconds(tt); mb = d.getUTCDate() - dn.getUTCDate(); return set;},
        3: function(tt){ var set = d.setUTCMonth(parseInt(tt, 10)-1); ma = d.getUTCFullYear() - dn.getUTCFullYear(); return set;},
        4: function(tt){ return d.setUTCDate(tt+mb);},
        5: function(tt){
            if (tt >= 0 && tt <= 69) {
                tt += 2000;
            }
            else if (tt >= 70 && tt <= 100) {
                tt += 1900;
            }
            return d.setUTCFullYear(tt+ma);
        }
        // 7th argument (for DST) is deprecated
    };

    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]*1, 10);
        if (isNaN(no)) {
            return false;
        } else {
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }
    for (i = argc; i < 6; i++) {
        switch(i) {
            case 0:
                no = dn.getUTCHours();
                break;
            case 1:
                no = dn.getUTCMinutes();
                break;
            case 2:
                no = dn.getUTCSeconds();
                break;
            case 3:
                no = dn.getUTCMonth()+1;
                break;
            case 4:
                no = dn.getUTCDate();
                break;
            case 5:
                no = dn.getUTCFullYear();
                break;
        }
        dateManip[i](no);
    }

    return Math.floor(d.getTime()/1000);
}

function gmstrftime (format, timestamp) {
    // Format a GMT/UCT time/date according to locale settings  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/gmstrftime
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: strftime
    // *     example 1: gmstrftime("%A", 1062462400);
    // *     returns 1: 'Tuesday'
    var dt = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp));
    timestamp = Date.parse(dt.toUTCString().slice(0, -4))/1000;
    return this.strftime(format, timestamp);
}

function gopher_parsedir (dirent) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// *     example 1: var entry = gopher_parsedir('0All about my gopher site.\t/allabout.txt\tgopher.example.com\t70\u000d\u000a');
	// *     example 1: entry.title;
	// *     returns 1: 'All about my gopher site.'

    /* Types
    * 0 = plain text file
    * 1 = directory menu listing
    * 2 = CSO search query
    * 3 = error message
    * 4 = BinHex encoded text file
    * 5 = binary archive file
    * 6 = UUEncoded text file
    * 7 = search engine query
    * 8 = telnet session pointer
    * 9 = binary file
    * g = Graphics file format, primarily a GIF file
    * h = HTML file
    * i = informational message
    * s = Audio file format, primarily a WAV file
    */

	var entryPattern = /^(.)(.*?)\t(.*?)\t(.*?)\t(.*?)\u000d\u000a$/;
	var entry = dirent.match(entryPattern);

    if (entry === null) {
        throw 'Could not parse the directory entry';
        // return false;
    }

    var type = entry[1];
    switch (type) {
        case 'i':
            type = 255; // GOPHER_INFO
            break;
        case '1':
            type = 1; // GOPHER_DIRECTORY
            break;
        case '0':
            type = 0; // GOPHER_DOCUMENT
            break;
        case '4':
            type = 4; // GOPHER_BINHEX
            break;
        case '5':
            type = 5; // GOPHER_DOSBINARY
            break;
        case '6':
            type = 6; // GOPHER_UUENCODED
            break;
        case '9':
            type = 9; // GOPHER_BINARY
            break;
        case 'h':
            type = 254; // GOPHER_HTTP
            break;
        default:
            return {type:-1, data: dirent}; // GOPHER_UNKNOWN
    }
	return {type:type, title:entry[2], path:entry[3], host:entry[4], port:entry[5]};
}

function hexdec(hex_string) {
    // Returns the decimal equivalent of the hexadecimal number  
    // 
    // version: 810.300
    // discuss at: http://phpjs.org/functions/hexdec
    // +   original by: Philippe Baumann
    // *     example 1: hexdec('that');
    // *     returns 1: 10
    // *     example 2: hexdec('a0');
    // *     returns 2: 160
    
    hex_string = (hex_string+'').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

function html_entity_decode( string, quote_style ) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/html_entity_decode
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/htmlentities
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function htmlspecialchars (string, quote_style) {
    // Convert special characters to HTML entities  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/htmlspecialchars
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = this.get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function htmlspecialchars_decode(string, quote_style) {
    // Convert special HTML entities back to characters  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/htmlspecialchars_decode
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = this.get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }

    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function http_build_query( formdata, numeric_prefix, arg_separator ) {
    // Generates a form-encoded query string from an associative array or object.  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/http_build_query
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: stag019
    // -    depends on: urlencode
    // *     example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;');
    // *     returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    // *     example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_');
    // *     returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk'
    var value, key, tmp = [];

    var _http_build_query_helper = function (key, val, arg_separator) {
        var k, tmp = [];
        if (val === true) {
            val = "1";
        } else if (val === false) {
            val = "0";
        }
        if (typeof(val) == "array" || typeof(val) == "object") {
            for (k in val) {
                if(val[k] !== null) {
                    tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator));
                }
            }
            return tmp.join(arg_separator);
        } else if(typeof(val) != "function") {
            return this.urlencode(key) + "=" + this.urlencode(val);
        }
    };

    if (!arg_separator) {
        arg_separator = "&";
    }
    for (key in formdata) {
        value = formdata[key];
        if (numeric_prefix && !isNaN(key)) {
            key = String(numeric_prefix) + key;
        }
        tmp.push(_http_build_query_helper(key, value, arg_separator));
    }

    return tmp.join(arg_separator);
}

function hypot(x, y) {
    // Returns sqrt(num1*num1 + num2*num2)  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/hypot
    // +   original by: Onno Marsman
    // *     example 1: hypot(3, 4);
    // *     returns 1: 5
    // *     example 2: hypot([], 'a');
    // *     returns 2: 0
    return Math.sqrt(x*x + y*y) || 0;
}

function idate (format, timestamp) {
    // Format a local time/date as integer  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/idate
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   derived from: date
    // +   derived from: gettimeofday
    // *     example 1: idate('y');
    // *     returns 1: 9

    if (format === undefined) {
        throw 'idate() expects at least 1 parameter, 0 given';
    }
    if (!format.length || format.length > 1) {
        throw 'idate format is one char';
    }

    // Fix: Need to allow date_default_timezone_set() (check for this.php_js.default_timezone and use)
    var date = ((typeof(timestamp) === 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) === 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp)); // Date() object

    var _L = function (date) {
        var y = date.getFullYear();
        return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
    };
    var _z = function (date) {
        return (date - new Date(date.getFullYear() + "/1/1")) / 864e5 >> 0;
    };

    var _dst = function (t) {
        // Calculate Daylight Saving Time (derived from gettimeofday() code)
        var dst=0;
        var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
        var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
        var temp = jan1.toUTCString();
        var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        temp = june1.toUTCString();
        var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
        var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);

        if (std_time_offset === daylight_time_offset) {
            dst = 0; // daylight savings time is NOT observed
        }
        else {
            // positive is southern, negative is northern hemisphere
            var hemisphere = std_time_offset - daylight_time_offset;
            if (hemisphere >= 0) {
                std_time_offset = daylight_time_offset;
            }
            dst = 1; // daylight savings time is observed
        }
        return dst;
    };

    switch(format) {
        case 'B':
            // peter paul koch:
            var off = (date.getTimezoneOffset() + 60)*60;
            var theSeconds = (date.getHours() * 3600) +
                             (date.getMinutes() * 60) +
                              date.getSeconds() + off;
            var beat = Math.floor(theSeconds/86.4);
            if (beat > 1000) {beat -= 1000;}
            if (beat < 0) {beat += 1000;}
            if ((String(beat)).length == 1) {beat = '00'+beat;}
            if ((String(beat)).length == 2) {beat = '0'+beat;}
            return beat;
        case 'd':
            return date.getDate();
        case 'h':
            return date.getHours() % 12 || 12;
        case 'H':
            return date.getHours();
        case 'i':
            return date.getMinutes();
        case 'I': // capital 'i'
            return _dst(date);
        case 'L':
            return _L(date);
        case 'm':
            return date.getMonth()+1;
        case 's':
            return date.getSeconds();
        case 't':
            var n;
            if( (n = date.getMonth()+1) === 2 ){
                return 28 + _L(date);
            }
            if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                return 31;
            }
            return 30;
        case 'U':
            return Math.round(date.getTime()/1000);
        case 'w':
            return date.getDay();
        case 'W':
            var a = _z(date), b = 364 + _L(date) - a;
            var nd2, nd = (new Date(date.getFullYear() + '/1/1').getDay() || 7) - 1;

            if(b <= 2 && ((date.getDay() || 7) - 1) <= 2 - b){
                return 1;
            }
            if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                nd2 = new Date(date.getFullYear() - 1 + '/12/31');
                return idate('W', Math.round(nd2.getTime()/1000));
            }
            return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
        case 'y':
            return parseInt((date.getFullYear() + '').slice(2), 10); // This function returns an integer, unlike date()
        case 'Y':
            return date.getFullYear();
        case 'z':
            return _z(date);
        case 'Z':
            return -date.getTimezoneOffset()*60;
        default:
            throw 'Unrecognized date format token';
    }
}

function implode( glue, pieces ) {
    // Joins array elements placing glue string between items and return one string  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    return ( ( pieces instanceof Array ) ? pieces.join( glue ) : pieces );
}

function import_request_variables (types, prefix) {
    // Import GET/POST/Cookie variables into the global scope  
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/import_request_variables
    // +      original by: Jalal Berrami
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // + improved by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: IMPORTANT: You must sanitize user variables passed in via URL in JavaScript as in PHP,
    // %          note 1: especially if you want to use any of these variables in an eval()-like function (not recommended)!
    // *        example 1: document.cookie = 'snack=yummy';
    // *        example 1: import_request_variables('gc', 'pr_');
    // *        results 1: pr_snack == 'yummy'
    var i = 0, current = '', url = '', vars = '', arrayBracketPos = -1, arrName='', win = this.window, targetObj = this.window;
    prefix = prefix || '';

    if (this.php_js && this.php_js.ini && this.php_js.ini['phpjs.requestVarsObj'] &&
        this.php_js.ini['phpjs.requestVarsObj'].local_value) { // Allow designated object to be used instead of window
        targetObj = this.php_js.ini['phpjs.requestVarsObj'].local_value;
    }

    if (/g/i.test(types)) { // GET
        for(i = 0, url = win.location.href, vars = url.substring(url.lastIndexOf("?") + 1, url.length).split("&"); i < vars.length; i++){
            current = vars[i].split("=");
            current[1] = decodeURIComponent(current[1]);
            arrayBracketPos = current[0].indexOf('[');
            if (arrayBracketPos !== -1) {
                arrName = current[0].substring(0, arrayBracketPos);
                arrName = decodeURIComponent(arrName);
                if (!targetObj[prefix+arrName]) {
                    targetObj[prefix+arrName] = [];
                }
                targetObj[prefix+arrName].push(current[1] || null);
            }
            else {
                current[0] = decodeURIComponent(current[0]);
                targetObj[prefix+current[0]] = current[1] || null;
            }
        }
    }
    if (/c/i.test(types)) { // COOKIE
        for(i = 0, vars = win.document.cookie.split("&"); i < vars.length;i++){
            current = vars[i].split("=");
            targetObj[prefix+current[0]] = current[1].split(";")[0] || null;
        }
    }
}

function in_array(needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 903.1614
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    var found = false, key, strict = !!argStrict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

function include( filename ) {
    // !No description available for include. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/include
    // +   original by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Legaev Andrey
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael White (http://getsprink.com)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Force Javascript execution to pause until the file is loaded. Usually causes failure if the file never loads. ( Use sparingly! )
    // %        note 2: The included file does not come available until a second script block, so typically use this in the header.
    // %        note 3: Uses global: php_js to keep track of included files
    // *     example 1: include('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: 1
    var d = this.window.document;
    var js = d.createElementNS ? d.createElementNS('http://www.w3.org/1999/xhtml', 'script') : d.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', filename);
    js.setAttribute('defer', 'defer');
    d.getElementsByTagNameNS ? d.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'head')[0].appendChild(js) : d.getElementsByTagName('head')[0].appendChild(js);

    // save include state for reference by include_once
    var cur_file = {};
    cur_file[this.window.location.href] = 1;

    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.includes) {
        this.php_js.includes = cur_file;
    }
    if (!this.php_js.includes[filename]) {
        this.php_js.includes[filename] = 1;
    } else {
        this.php_js.includes[filename]++;
    }

    return this.php_js.includes[filename];
}

function include_once( filename ) {
    // !No description available for include_once. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/include_once
    // +   original by: Legaev Andrey
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael White (http://getsprink.com)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: include
    // %        note 1: Uses global: php_js to keep track of included files
    // *     example 1: include_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: true
    var cur_file = {};
    cur_file[this.window.location.href] = 1;

    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.includes) {
        this.php_js.includes = cur_file;
    }
    if (!this.php_js.includes[filename]) {
        if(this.include(filename)){
            return true;
        }
    } else{
        return true;
    }
    return false;
}

function ini_alter (varname, newvalue) {
    // !No description available for ini_alter. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/ini_alter
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: ini_set
    // *     example 1: ini_alter('date.timezone', 'America/Chicago');
    // *     returns 1: 'Asia/Hong_Kong'
	return this.ini_set(varname, newvalue);
}

function ini_get (varname) {
    // Get a configuration option  
    // 
    // version: 904.2010
    // discuss at: http://phpjs.org/functions/ini_get
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: The ini values must be set by ini_set or manually within an ini file
    // *     example 1: ini_get('date.timezone');
    // *     returns 1: 'Asia/Hong_Kong'
	if (this.php_js && this.php_js.ini && this.php_js.ini[varname] && this.php_js.ini[varname].local_value !== undefined) {
		if (this.php_js.ini[varname].local_value === null) {
			return '';
		}
		return this.php_js.ini[varname].local_value;
	}
	return '';
}

function ini_get_all(extension, details) {
    // Get all configuration options  
    // 
    // version: 904.718
    // discuss at: http://phpjs.org/functions/ini_get_all
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: The ini values must be set by ini_set or manually within an ini file
    // %        note 1: Store each ini with PHP name and with the values global_value, local_value, and access; be sure to set the same value at the beginning for global and local value
    // %        note 1: If you define an ini file, which sets this.php_js.ini values (window.php_js.ini if you are using the non-namespaced version), be sure to also set php_js.ini_loaded_file 
    // %        note 1: equal to its path, for the sake of php_ini_loaded_file() and also set php_js.ini_scanned_files (a comma-separated string of a set of paths, all in the 
    // %        note 1: same directory) for the sake of php_ini_scanned_files().
    // *     example 1: ini_get_all('date', false);
    // *     returns 1: {'date.default_latitude':"31.7667", 'date.default_longitude':"35.2333", 'date.sunrise_zenith':"90.583333", 'date.sunset_zenith':"90.583333", date.timezone:""}
	
	var key='', ini={}, noDetails={}, extPattern;
	if (!this.php_js) {
		this.php_js = {};
	}
	if (!this.php_js.ini) {
		this.php_js.ini = {};
	}
	
	if (extension) {
		extPattern = new RegExp('^'+extension+'\\.');
		for (key in this.php_js.ini) {
			if (extPattern.test(key)) {
				ini[key] = this.php_js.ini[key];
			}
		}
	}
	else {
		for (key in this.php_js.ini) {
			ini[key] = this.php_js.ini[key];
		}
	}
	
	if (details !== false) { // default is true
		return ini; // {global_value: '', local_value: '', access: ''};
	}
	
	for (key in ini) {
		noDetails[key] = ini[key].local_value;
	}
	return noDetails;
}

function ini_restore (varname) {
	// http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: ini_restore('date.timezone');
    // *     returns 1: 'America/Chicago'
	if (this.php_js && this.php_js.ini && this.php_js.ini[varname]) {
		this.php_js.ini[varname].local_value = this.php_js.ini[varname].global_value;
	}
}

function ini_set (varname, newvalue) {
    // Set a configuration option, returns false on error and the old value of the configuration option on success  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/ini_set
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: This will not set a global_value or access level for the ini item
    // *     example 1: ini_set('date.timezone', 'America/Chicago');
    // *     returns 1: 'Asia/Hong_Kong'
	var oldval = '';
	if (!this.php_js) {
		this.php_js = {};
	}
	if (!this.php_js.ini) {
		this.php_js.ini = {};
	}
	if (!this.php_js.ini[varname]) {
		this.php_js.ini[varname] = {};
	}
	oldval = this.php_js.ini[varname].local_value;
	this.php_js.ini[varname].local_value = newvalue;
	return oldval;
}

function intval( mixed_var, base ) {
    // Get the integer value of a variable using the optional base for the conversion  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/intval
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    var tmp;

    var type = typeof( mixed_var );

    if(type == 'boolean'){
        if (mixed_var == true) {
            return 1;
        } else {
            return 0;
        }
    } else if(type == 'string'){
        tmp = parseInt(mixed_var * 1, 10);
        if(isNaN(tmp) || !isFinite(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if(type == 'number' && isFinite(mixed_var) ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

function ip2long ( ip_address ) {
    // Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address  
    // 
    // version: 901.714
    // discuss at: http://phpjs.org/functions/ip2long
    // +   original by: Waldo Malqui Silva
    // +   improved by: Victor
    // *     example 1: ip2long( '192.0.34.166' );
    // *     returns 1: 3221234342
    
    var output = false;
    var parts = [];
    if (ip_address.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
        parts  = ip_address.split('.');
        output = ( parts[0] * 16777216 +
        ( parts[1] * 65536 ) +
        ( parts[2] * 256 ) +
        ( parts[3] * 1 ) );
    }
     
    return output;
}

function is_array( mixed_var ) {
    // Returns true if variable is an array  
    // 
    // version: 905.1411
    // discuss at: http://phpjs.org/functions/is_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true  in this function (except for objects which inherit properties, being thus used as objects),
    // %        note 1: unless you do ini_set('phpjs.objectsAsArrays', true), in which case only genuine JavaScript arrays
    // %        note 1: will return true
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 3: true
    // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
    // *     returns 4: false
    var key = '';

    if (!mixed_var) {
        return false;
    }

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.ini) {
        this.php_js.ini = {};
    }
    // END REDUNDANT

    if (typeof mixed_var === 'object') {

        if (this.php_js.ini['phpjs.objectsAsArrays'] &&  // Strict checking for being a JavaScript array (only check this way if call ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays)
            (
            (this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase &&
                    this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase() === 'off') ||
                parseInt(this.php_js.ini['phpjs.objectsAsArrays'].local_value, 10) === 0)
            ) {
            return mixed_var.hasOwnProperty('length') && // Not non-enumerable because of being on parent class
                            !mixed_var.propertyIsEnumerable('length') && // Since is own property, if not enumerable, it must be a built-in function
                                mixed_var.constructor.name !== 'String'; // exclude String()
        }

        if (mixed_var.hasOwnProperty) {
            for (key in mixed_var) {
                // Checks whether the object has the specified property
                // if not, we figure it's not an object in the sense of a php-associative-array.
                if (false === mixed_var.hasOwnProperty(key)) {
                    return false;
                }
            }
        }

        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        return true;
    }

    return false;
}

function is_binary (vr) {
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: is_binary('This could be binary as far as JavaScript knows...');
    // *     returns 1: true
    return typeof vr === 'string'; // If it is a string of any kind, it could be binary
}

function is_bool(mixed_var)
{
    // Returns true if variable is a boolean  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/is_bool
    // +   original by: Onno Marsman
    // *     example 1: is_bool(false);
    // *     returns 1: true
    // *     example 2: is_bool(0);
    // *     returns 2: false
    return (typeof mixed_var == 'boolean');
}

function is_buffer (vr) {
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: is_buffer('This could be binary or a regular string as far as JavaScript knows...');
    // *     returns 1: true
    return typeof vr === 'string';
}

function is_callable (v, syntax_only, callable_name) {
    // Returns true if var is callable.  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/is_callable
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: The variable callable_name cannot work as a string variable passed by reference as in PHP (since JavaScript does not support passing strings by reference), but instead will take the name of a global variable and set that instead
    // %        note 2: When used on an object, depends on a constructor property being kept on the object prototype
    // *     example 1: is_callable('is_callable');
    // *     returns 1: true
    // *     example 2: is_callable('bogusFunction', true);
    // *     returns 2:true // gives true because does not do strict checking
    // *     example 3: function SomeClass () {}
    // *     example 3: SomeClass.prototype.someMethod = function(){};
    // *     example 3: var testObj = new SomeClass();
    // *     example 3: is_callable([testObj, 'someMethod'], true, 'myVar');
    // *     example 3: alert(myVar); // 'SomeClass::someMethod'
    var name='', obj={}, method='';
    if (typeof v === 'string') {
        obj = this.window;
        method = v;
        name = v;
    }
    else if (v instanceof Array && v.length === 2 && typeof v[0] === 'object' && typeof v[1] === 'string') {
        obj = v[0];
        method = v[1];
        name = (obj.constructor && obj.constructor.name)+'::'+method;
    }
    else {
        return false;
    }
    if (syntax_only || typeof obj[method] === 'function') {
        if (callable_name) {
            this.window[callable_name] = name;
        }
        return true;
    }
    return false;
}

function is_double( mixed_var ) {
    // !No description available for is_double. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/is_double
    // +   original by: Paulo Ricardo F. Santos
    //  -   depends on: is_float
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_double(186.31);
    // *     returns 1: true
    return this.is_float(mixed_var);
}

function is_finite(val) {
    // Returns whether argument is finite  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/is_finite
    // +   original by: Onno Marsman
    // *     example 1: is_finite(Infinity);
    // *     returns 1: false
    // *     example 2: is_finite(-Infinity);
    // *     returns 2: false
    // *     example 3: is_finite(0);
    // *     returns 3: true
    var warningType = '';

    if (val===Infinity || val===-Infinity) {
        return false;
    }

    //Some warnings for maximum PHP compatibility
    if (typeof val=='object') {
        warningType = (val instanceof Array ? 'array' : 'object');
    } else if (typeof val=='string' && !val.match(/^[\+\-]?\d/)) {
        //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does.
        warningType = 'string';
    }
    if (warningType) {
        throw new Error('Warning: is_finite() expects parameter 1 to be double, '+warningType+' given');
    }

    return true;
}

function is_float( mixed_var ) {
    // Returns true if variable is float point  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/is_float
    // +   original by: Paulo Ricardo F. Santos
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_float(186.31);
    // *     returns 1: true
    return parseFloat(mixed_var * 1) != parseInt(mixed_var * 1, 10);
}

function is_infinite(val) {
    // Returns whether argument is infinite  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/is_infinite
    // +   original by: Onno Marsman
    // *     example 1: is_infinite(Infinity);
    // *     returns 1: true
    // *     example 2: is_infinite(-Infinity);
    // *     returns 2: true
    // *     example 3: is_infinite(0);
    // *     returns 3: false
    var warningType = '';

    if (val===Infinity || val===-Infinity) {
        return true;
    }

    //Some warnings for maximum PHP compatibility
    if (typeof val=='object') {
        warningType = (val instanceof Array ? 'array' : 'object');
    } else if (typeof val=='string' && !val.match(/^[\+\-]?\d/)) {
        //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does.
        warningType = 'string';
    }
    if (warningType) {
        throw new Error('Warning: is_infinite() expects parameter 1 to be double, '+warningType+' given');
    }

    return false;
}

function is_int( mixed_var ) {
    // !No description available for is_int. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/is_int
    // +   original by: Alex
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Matt Bradley
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_int(23)
    // *     returns 1: true
    // *     example 2: is_int('23')
    // *     returns 2: false
    // *     example 3: is_int(23.5)
    // *     returns 3: false
    // *     example 4: is_int(true)
    // *     returns 4: false
    if (typeof mixed_var !== 'number') {
        return false;
    }

    if (parseFloat(mixed_var) != parseInt(mixed_var, 10)) {
        return false;
    }
    
    return true;
}

function is_integer( mixed_var ) {
    // !No description available for is_integer. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/is_integer
    // +   original by: Paulo Ricardo F. Santos
    //  -   depends on: is_int
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_integer(186.31);
    // *     returns 1: false
    // *     example 2: is_integer(12);
    // *     returns 2: true
    return this.is_int(mixed_var);
}

function is_long( mixed_var ) {
    // Returns true if variable is a long (integer)  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/is_long
    // +   original by: Paulo Ricardo F. Santos
    //  -   depends on: is_float
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_long(186.31);
    // *     returns 1: true
    return this.is_float(mixed_var);
}

function is_nan(val) {
    // Returns whether argument is not a number  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/is_nan
    // +   original by: Onno Marsman
    // +      input by: Robin
    // *     example 1: is_nan(NaN);
    // *     returns 1: true
    // *     example 2: is_nan(0);
    // *     returns 2: false
    var warningType = '';

    if (typeof val=='number' && isNaN(val)) {
        return true;
    }

    //Some errors for maximum PHP compatibility
    if (typeof val=='object') {
        warningType = (val instanceof Array ? 'array' : 'object');
    } else if (typeof val=='string' && !val.match(/^[\+\-]?\d/)) {
        //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does.
        warningType = 'string';
    }
    if (warningType) {
        throw new Error('Warning: is_nan() expects parameter 1 to be double, '+warningType+' given');
    }

    return false;
}

function is_null( mixed_var ){
    // Returns true if variable is null  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_null
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: is_null('23');
    // *     returns 1: false
    // *     example 2: is_null(null);
    // *     returns 2: true
    return ( mixed_var === null );
}

function is_numeric( mixed_var ) {
    // Returns true if value is a number or a numeric string  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/is_numeric
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    if (mixed_var === '') {
        return false;
    }

    return !isNaN(mixed_var * 1);
}

function is_object( mixed_var ){
    // Returns true if variable is an object  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_object
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function is_real( mixed_var ) {
    // !No description available for is_real. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/is_real
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    //  -   depends on: is_float
    // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
    // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
    // *     example 1: is_double(186.31);
    // *     returns 1: true
    return this.is_float(mixed_var);
}

function is_resource (handle) {
    // Returns true if variable is a resource  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/is_resource
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: is_resource('a');
    // *     returns 1: false

    if (!handle || typeof handle !== 'object' || !handle.constructor || handle.constructor.name !== 'PHPJS_Resource') {
        return false;
    }

    return true;
}

function is_scalar( mixed_var ) {
    // Returns true if value is a scalar  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/is_scalar
    // +   original by: Paulo Ricardo F. Santos
    // *     example 1: is_scalar(186.31);
    // *     returns 1: true
    // *     example 2: is_scalar({0: 'Kevin van Zonneveld'});
    // *     returns 2: false
    return (/boolean|number|string/).test(typeof mixed_var);
}

function is_string( mixed_var ){
    // Returns true if variable is a Unicode or binary string  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_string
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: is_string('23');
    // *     returns 1: true
    // *     example 2: is_string(23.5);
    // *     returns 2: false
    return (typeof( mixed_var ) == 'string');
}

function is_unicode (vr) {
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Almost all strings in JavaScript should be Unicode
    // *     example 1: is_unicode('We the peoples of the United Nations...!');
    // *     returns 1: true

    if (typeof vr !== 'string') {
        return false;
    }

    // If surrogates occur outside of high-low pairs, then this is not Unicode
    var arr=[],
        any='([^])',
        highSurrogate='[\uD800-\uDBFF]',
        lowSurrogate='[\uDC00-\uDFFF]',
        highSurrogateBeforeAny = new RegExp(highSurrogate+any, 'g'),
        lowSurrogateAfterAny = new RegExp(any+lowSurrogate, 'g'),
        singleLowSurrogate = new RegExp('^'+lowSurrogate+'$'),
        singleHighSurrogate = new RegExp('^'+highSurrogate+'$');

    while ((arr = highSurrogateBeforeAny.exec(vr)) !== null) {
        if (!arr[1] || !arr[1].match(singleLowSurrogate)) { // If high not followed by low surrogate
            return false;
        }
    }
    while ((arr = lowSurrogateAfterAny.exec(vr)) !== null) {
        if (!arr[1] || !arr[1].match(singleHighSurrogate)) { // If low not preceded by high surrogate
            return false;
        }
    }
    return true;
}

function isset(  ) {
    // !No description available for isset. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/isset
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    
    var a=arguments, l=a.length, i=0;
    
    if (l===0) {
        throw new Error('Empty isset'); 
    }
    
    while (i!==l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}

function join( glue, pieces ) {
    // An alias for implode  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/join
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: implode
    // *     example 1: join(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    return this.implode( glue, pieces );
}

function json_decode(str_json) {
    // Decodes the JSON representation into a PHP value  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/json_decode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *     returns 1: ['e', {pluribus: 'unum'}]
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if (/^[\],:{}\s]*$/.
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        j = eval('(' + text + ')');

        return j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.
    throw new SyntaxError('json_decode');
}

function json_encode(mixed_val) {
    // Returns the JSON representation of a value  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/json_encode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: json_encode(['e', {pluribus: 'unum'}]);
    // *     returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */
    
    var value = mixed_val;

    var quote = function (string) {
        var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        escapable.lastIndex = 0;
        return escapable.test(string) ?
        '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
            '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
    };

    var str = function(key, holder) {
        var gap = '';
        var indent = '    ';
        var i = 0;          // The loop counter.
        var k = '';          // The member key.
        var v = '';          // The member value.
        var length = 0;
        var mind = gap;
        var partial = [];
        var value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.
        if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        
        // What happens next depends on the value's type.
        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':
                // JSON numbers must be finite. Encode non-finite numbers as null.
                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

            case 'object':
                // If the type is 'object', we might be dealing with an object or an array or
                // null.
                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.
                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.
                gap += indent;
                partial = [];

                // Is the value an array?
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.
                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                    partial.join(',\n' + gap) + '\n' +
                    mind + ']' :
                    '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // Iterate through all of the keys in the object.
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.
                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    };

    // Make a fake root object containing our value under the key of ''.
    // Return the result of stringifying the value.
    return str('', {
        '': value
    });
}

function key(arr) {
    // Return the key of the element currently pointed to by the internal array pointer  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/key
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: array = {fruit1: 'apple', 'fruit2': 'orange'}
    // *     example 1: key(array);
    // *     returns 1: 'fruit1'
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.pointers) {
        this.php_js.pointers = [];
    }
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var cursor = pointers[pointers.indexOf(arr)+1];
    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            if (ct === cursor) {
                return k;
            }
            ct++;
        }
        return false; // Empty
    }
    if (arr.length === 0) {
        return false;
    }
    return cursor;
}

function krsort(array, sort_flags) {
    // Sort an array by key value in reverse order  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/krsort
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note: The examples are correct, this is a new way
    // *     example 1: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'};
    // *     example 1: krsort(data);
    // *     results 1: data == {3: 'Kevin', 2: 'van', 1: 'Zonneveld'}
    // *     returns 1: true
    var tmp_arr={}, keys=[], sorter, i, key, that=this;

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(b, a);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(b.localeCompare(a));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(b - a);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a < b) {
                    return 1;
				}
                if (a > b) {
                    return -1;
				}
                return 0;
            };
            break;
    }

    // Make a list of key names
    for (key in array) {
        keys.push(key);
    }

    keys.sort(sorter);

    // Rebuild array with sorted key names
    for (i = 0; i < keys.length; i++) {
        key = keys[i];
        tmp_arr[key] = array[key];
        delete array[key];
    }
    for (i in tmp_arr) {
        array[i] = tmp_arr[i];
    }

    return true;
}

function ksort(array, sort_flags) {
    // Sort an array by key  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/ksort
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note: The examples are correct, this is a new way
    // *     example 1: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'};
    // *     example 1: ksort(data);
    // *     results 1: data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'}
    // *     returns 1: true
    var tmp_arr={}, keys=[], sorter, i, key, that=this;

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(a.localeCompare(b));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
                return 0;
            };
            break;
    }

    // Make a list of key names
    for (key in array) {
        keys.push(key);
    }

    keys.sort(sorter);

    // Rebuild array with sorted key names
    for (i = 0; i < keys.length; i++) {
        key = keys[i];
        tmp_arr[key] = array[key];
        delete array[key];
    }
    for (i in tmp_arr) {
        array[i] = tmp_arr[i];
    }

    return true;
}

function lcfirst( str ) {
    // !No description available for lcfirst. @php.js developers: Please update the function summary text file.
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/lcfirst
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: lcfirst('Kevin Van Zonneveld');
    // *     returns 1: 'kevin Van Zonneveld'
    str += '';
    var f = str.charAt(0).toLowerCase();
    return f + str.substr(1);
}

function lcg_value() {
    // !No description available for lcg_value. @php.js developers: Please update the function summary text file.
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/lcg_value
    // +   original by: Onno Marsman
    return Math.random();
}

function levenshtein (a, b){
    // Calculate Levenshtein distance between two strings  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/levenshtein
    // +      original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      bugfixed by: Onno Marsman
    // +       revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // *        example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
    // *        returns 1: 3
    
    var min=Math.min, len1=0, len2=0, I=0, i=0, d=[], c='', j=0, J=0;

    // BEGIN STATIC
    var split = false;
    try{
        split=!('0')[0];
    } catch(e){
        split=true; // Earlier IE may not support access by string index
    }
    // END STATIC
    
    if (a == b) {
        return 0;
    }
    if (!a.length || !b.length) {
        return b.length || a.length;
    }
    if (split){
        a = a.split('');b = b.split('');
    }
    len1 = a.length + 1;
    len2 = b.length + 1;
    d = [[0]];
    while (++i < len2) {
        d[0][i] = i;
    }
    i = 0;
    while (++i < len1) {
        J = j = 0;
        c = a[I];
        d[i] = [i];
        while (++j < len2) {
            d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
            ++J;
        }
        ++I;
    }
    
    return d[len1 - 1][len2 - 1];
}

function localeconv () {
    // Returns numeric formatting information based on the current locale  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/localeconv
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: setlocale
    // *     example 1: localeconv();
    // *     returns 1: {decimal_point: '.', thousands_sep: ',', positive_sign: '', negative_sign: '-', int_frac_digits: 2, frac_digits: 2, p_cs_precedes: 1, p_sep_by_space: 0, n_cs_precedes: 1, n_sep_by_space: 0, p_sign_posn: 3, n_sign_posn: 0, grouping: 3, int_curr_symbol: 'USD', currency_symbol: '$', mon_decimal_point: '.', mon_thousands_sep: ',', mon_grouping: 3}

    var arr = {}, prop='';

    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place, if not already
    // END STATIC

    // Make copies
    for (prop in this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC].LC_NUMERIC) {
        arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC].LC_NUMERIC[prop];
    }
    for (prop in this.php_js.locales[this.php_js.localeCategories.LC_MONETARY].LC_MONETARY) {
        arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY].LC_MONETARY[prop];
    }
    
    return arr;
}

function localtime (timestamp, is_assoc) {
    // Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array  
    // 
    // version: 904.718
    // discuss at: http://phpjs.org/functions/localtime
    // + original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      derived from: Josh Fraser (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/)
    // +         parts by: Breaking Par Consulting Inc (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7)
    // *     example 1: localtime();
    // *     returns 1: [50,28,0,14,2,109,6,73,0]
    if (timestamp === undefined) {
        timestamp = Math.round(new Date().getTime()/1000); // time()
    } else if (timestamp instanceof Date) {
        timestamp = timestamp/1000; // Let it work with JavaScript data objects without the need for conversion
    }
    var t = new Date(timestamp*1000);

    // Calculate day of year
    var jan1 = new Date(t.getFullYear(), 0, 1);
    var yday = Math.ceil((t - jan1) / 86400000)-1;

    // Calculate Daylight Saving Time
    jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
    var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
    var temp = jan1.toUTCString();
    var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
    temp = june1.toUTCString();
    var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
    var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
    var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
    var dst;
    if (std_time_offset === daylight_time_offset) {
        dst = 0; // daylight savings time is NOT observed
    } else {
        // positive is southern, negative is northern hemisphere
        var hemisphere = std_time_offset - daylight_time_offset;
        if (hemisphere >= 0) {
            std_time_offset = daylight_time_offset;
        }
        dst = 1; // daylight savings time is observed
    }

    if (is_assoc) {
        return {
            'tm_sec': t.getSeconds(), // seconds
            'tm_min': t.getMinutes(), // minutes
            'tm_hour': t.getHours(),// hour
            'tm_mday': t.getDate(),// day of the month Months are from 0 (Jan) to 11 (Dec) and days of the week are from 0 (Sun) to 6 (Sat).
            'tm_mon': t.getMonth(),// month of the year, starting with 0 for January
            'tm_year': t.getFullYear()-1900,// Years since 1900
            'tm_wday': t.getDay(),// Day of the week
            'tm_yday': yday,// Day of the year
            'tm_isdst': dst// Is daylight savings time in effect
        };
    }
    return [t.getSeconds(), t.getMinutes(), t.getHours(), t.getDate(), t.getMonth(), t.getFullYear()-1900, t.getDay(), yday, dst];
}

function log(arg, base) {
    // Returns the natural logarithm of the number, or the base log if base is specified  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/log
    // +   original by: Onno Marsman
    // *     example 1: log(8723321.4, 7);
    // *     returns 1: 8.212871815082147
    if (base === undefined) {
        return Math.log(arg);
    } else {
        return Math.log(arg)/Math.log(base);
    }
}

function log10(arg) {
    // Returns the base-10 logarithm of the number  
    // 
    // version: 812.316
    // discuss at: http://phpjs.org/functions/log10
    // +   original by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Tod Gentille
    // *     example 1: log10(10);
    // *     returns 1: 1
    // *     example 2: log10(1);
    // *     returns 2: 0
    return Math.log(arg)/Math.LN10;
}

function log1p (x) {
    // Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/log1p
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Precision 'n' can be adjusted as desired
    // *     example 1: log1p(1e-15);
    // *     returns 1: 9.999999999999995e-16

    var ret=0, n = 50; // degree of precision
    if (x <= -1) {
        return '-INF'; // JavaScript style would be to return Number.NEGATIVE_INFINITY
    }
    if (x < 0 || x > 1) {
        return Math.log(1+x);
    }
    for (var i=1; i < n; i++) {
        if ((i % 2) === 0) {
            ret -= Math.pow(x, i)/i;
        }
        else {
            ret += Math.pow(x, i)/i;
        }
    }
    return ret;
}

function long2ip ( proper_address ) {
    // Converts an (IPv4) Internet network address into a string in Internet standard dotted format  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/long2ip
    // +   original by: Waldo Malqui Silva
    // *     example 1: long2ip( 3221234342 );
    // *     returns 1: '192.0.34.166'
    
    var output = false;
    
    if ( !isNaN( proper_address ) && ( proper_address >= 0 || proper_address <= 4294967295 ) ) {
		output = Math.floor(proper_address / Math.pow( 256, 3 ) ) + '.' +
			Math.floor( ( proper_address % Math.pow( 256, 3 ) ) / Math.pow( 256, 2 ) ) + '.' +
			Math.floor( ( ( proper_address % Math.pow( 256, 3 ) )  % Math.pow( 256, 2 ) ) / Math.pow( 256, 1 ) ) + '.' +
			Math.floor( ( ( ( proper_address % Math.pow( 256, 3 ) ) % Math.pow( 256, 2 ) ) % Math.pow( 256, 1 ) ) / Math.pow( 256, 0 ) );
    }
    
    return output;
}

function ltrim ( str, charlist ) {
    // Strips whitespace from the beginning of a string  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/ltrim
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: ltrim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld    '
    charlist = !charlist ? ' \\s\u00A0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str+'').replace(re, '');
}

function max() {
    // Return the highest value in an array or a series of arguments  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/max
    // +   original by: Onno Marsman
    // +    revised by: Onno Marsman
    // +    tweaked by: Jack
    // %          note: Long code cause we're aiming for maximum PHP compatibility
    // *     example 1: max(1, 3, 5, 6, 7);
    // *     returns 1: 7
    // *     example 2: max([2, 4, 5]);
    // *     returns 2: 5
    // *     example 3: max(0, 'hello');
    // *     returns 3: 0
    // *     example 4: max('hello', 0);
    // *     returns 4: 'hello'
    // *     example 5: max(-1, 'hello');
    // *     returns 5: 'hello'
    // *     example 6: max([2, 4, 8], [2, 5, 7]);
    // *     returns 6: [2, 5, 7]
    var ar, retVal, i = 0, n = 0;
    var argv = arguments, argc = argv.length;

    var _obj2Array = function(obj) {
        if (obj instanceof Array) {
            return obj;
        } else {
            var ar = [];
            for (var i in obj) {
                ar.push(obj[i]);
            }
            return ar;
        }
    }; //function _obj2Array
    
    var _compare = function(current, next) {
        var i = 0, n = 0, tmp = 0;
        var nl = 0, cl = 0;
        
        if (current === next) {
            return 0;
        } else if (typeof current == 'object') {
            if (typeof next == 'object') {
               current = _obj2Array(current);
               next    = _obj2Array(next);
               cl      = current.length;
               nl      = next.length;
               if (nl > cl) {
                   return 1;
               } else if (nl < cl) {
                   return -1;
               } else {
                   for (i = 0, n = cl; i<n; ++i) {
                       tmp = _compare(current[i], next[i]);
                       if (tmp == 1) {
                           return 1;
                       } else if (tmp == -1) {
                           return -1;
                       }
                   }
                   return 0;
               }
            } else {
               return -1;
            }
        } else if (typeof next == 'object') {
            return 1;
        } else if (isNaN(next) && !isNaN(current)) {
            if (current == 0) {
               return 0;
            } else {
               return (current<0 ? 1 : -1);
            }
        } else if (isNaN(current) && !isNaN(next)) {
            if (next==0) {
               return 0;
            } else {
               return (next>0 ? 1 : -1);
            }
        } else {
            if (next==current) {
               return 0;
            } else {
               return (next>current ? 1 : -1);
            }
        }
    }; //function _compare
    
    if (argc === 0) {
        throw new Error('At least one value should be passed to max()');
    } else if (argc === 1) {
        if (typeof argv[0] === 'object') {
            ar = _obj2Array(argv[0]);
        } else {
            throw new Error('Wrong parameter count for max()');
        }
        if (ar.length === 0) {
            throw new Error('Array must contain at least one element for max()');
        }
    } else {
        ar = argv;
    }
    
    retVal = ar[0];
    for (i=1, n=ar.length; i<n; ++i) {
        if (_compare(retVal, ar[i])==1) {
            retVal = ar[i];
        }
    }
    
    return retVal;
}

function md5 ( str ) {
    // Calculate the md5 hash of a string  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/md5
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: md5('Kevin van Zonneveld');
    // *     returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'
    var xl;

    var rotateLeft = function(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    };

    var addUnsigned = function(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    };

    var _F = function(x,y,z) { return (x & y) | ((~x) & z); };
    var _G = function(x,y,z) { return (x & z) | (y & (~z)); };
    var _H = function(x,y,z) { return (x ^ y ^ z); };
    var _I = function(x,y,z) { return (y ^ (x | (~z))); };

    var _FF = function(a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _GG = function(a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _HH = function(a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _II = function(a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var convertToWordArray = function(str) {
        var lWordCount;
        var lMessageLength = str.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=new Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    var wordToHex = function(lValue) {
        var wordToHexValue="",wordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            wordToHexValue_temp = "0" + lByte.toString(16);
            wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
        }
        return wordToHexValue;
    };

    var x=[],
        k,AA,BB,CC,DD,a,b,c,d,
        S11=7, S12=12, S13=17, S14=22,
        S21=5, S22=9 , S23=14, S24=20,
        S31=4, S32=11, S33=16, S34=23,
        S41=6, S42=10, S43=15, S44=21;

    str = this.utf8_encode(str);
    x = convertToWordArray(str);
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
    
    xl = x.length;
    for (k=0;k<xl;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=_FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=_FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=_FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=_FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=_FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=_FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=_FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=_FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=_FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=_FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=_FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=_FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=_FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=_FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=_FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=_FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=_GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=_GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=_GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=_GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=_GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=_GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=_GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=_GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=_GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=_GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=_GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=_GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=_GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=_GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=_GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=_GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=_HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=_HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=_HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=_HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=_HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=_HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=_HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=_HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=_HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=_HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=_HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=_HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=_HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=_HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=_HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=_HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=_II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=_II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=_II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=_II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=_II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=_II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=_II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=_II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=_II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=_II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=_II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=_II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=_II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=_II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=_II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=_II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=addUnsigned(a,AA);
        b=addUnsigned(b,BB);
        c=addUnsigned(c,CC);
        d=addUnsigned(d,DD);
    }

    var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);

    return temp.toLowerCase();
}

function md5_file ( str_filename ) {
    // Calculate the md5 hash of given filename  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/md5_file
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: file_get_contents
    // -    depends on: md5
    // *     example 1: md5_file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '202cb962ac59075b964b07152d234b70'
    var buf = '';

    buf = this.file_get_contents(str_filename);
    
    if (!buf) {
        return false;
    }
    
    return this.md5(buf);
}

function method_exists (obj, method) {
    // Checks if the class method exists  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/method_exists
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function class_a() {this.meth1 = function() {return true;}};
    // *     example 1: var instance_a = new class_a();
    // *     example 1: method_exists(instance_a, 'meth1');
    // *     returns 1: true
    // *     example 2: function class_a() {this.meth1 = function() {return true;}};
    // *     example 2: var instance_a = new class_a();
    // *     example 2: method_exists(instance_a, 'meth2');
    // *     returns 2: false
    if (typeof obj === 'string') {
        return this.window[obj] && typeof this.window[obj][method] === 'function';
    }

    return typeof obj[method] === 'function';
}

function microtime(get_as_float) {
    // Returns either a string or a float containing the current time in seconds and microseconds  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/microtime
    // +   original by: Paulo Ricardo F. Santos
    // *     example 1: timeStamp = microtime(true);
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function min() {
    // Return the lowest value in an array or a series of arguments  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/min
    // +   original by: Onno Marsman
    // +    revised by: Onno Marsman
    // +    tweaked by: Jack
    // %          note: Long code cause we're aiming for maximum PHP compatibility
    // *     example 1: min(1, 3, 5, 6, 7);
    // *     returns 1: 1
    // *     example 2: min([2, 4, 5]);
    // *     returns 2: 2
    // *     example 3: min(0, 'hello');
    // *     returns 3: 0
    // *     example 4: min('hello', 0);
    // *     returns 4: 'hello'
    // *     example 5: min(-1, 'hello');
    // *     returns 5: -1
    // *     example 6: min([2, 4, 8], [2, 5, 7]);
    // *     returns 6: [2, 4, 8]
    
    var ar, retVal, i = 0, n = 0;
    var argv = arguments, argc = argv.length;

    var _obj2Array = function(obj) {
        if (obj instanceof Array) {
            return obj;
        } else {
            var ar = [];
            for (var i in obj) {
                ar.push(obj[i]);
            }
            return ar;
        }
    }; //function _obj2Array
    
    var _compare = function(current, next) {
        var i = 0, n = 0, tmp = 0;
        var nl = 0, cl = 0;
        
        if (current === next) {
            return 0;
        } else if (typeof current == 'object') {
            if (typeof next == 'object') {
               current = _obj2Array(current);
               next    = _obj2Array(next);
               cl      = current.length;
               nl      = next.length;
               if (nl > cl) {
                   return 1;
               } else if (nl < cl) {
                   return -1;
               } else {
                   for (i = 0, n = cl; i<n; ++i) {
                       tmp = _compare(current[i], next[i]);
                       if (tmp == 1) {
                           return 1;
                       } else if (tmp == -1) {
                           return -1;
                       }
                   }
                   return 0;
               }
            } else {
               return -1;
            }
        } else if (typeof next == 'object') {
            return 1;
        } else if (isNaN(next) && !isNaN(current)) {
            if (current == 0) {
               return 0;
            } else {
               return (current<0 ? 1 : -1);
            }
        } else if (isNaN(current) && !isNaN(next)) {
            if (next==0) {
               return 0;
            } else {
               return (next>0 ? 1 : -1);
            }
        } else {
            if (next==current) {
               return 0;
            } else {
               return (next>current ? 1 : -1);
            }
        }
    }; //function _compare
    
    if (argc === 0) {
        throw new Error('At least one value should be passed to min()');
    } else if (argc === 1) {
        if (typeof argv[0] === 'object') {
            ar = _obj2Array(argv[0]);
        } else {
            throw new Error('Wrong parameter count for min()');
        }
        if (ar.length === 0) {
            throw new Error('Array must contain at least one element for min()');
        }
    } else {
        ar = argv;
    }
    
    retVal = ar[0];
    for (i=1, n=ar.length; i<n; ++i) {
        if (_compare(retVal, ar[i])==-1) {
            retVal = ar[i];
        }
    }
    
    return retVal;
}

function mktime() {
    // Get UNIX timestamp for a date  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/mktime
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: baris ozdil
    // +      input by: gabriel paderni
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FGFEmperor
    // +      input by: Yannoo
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: jakes
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Marc Palau
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: mktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201871402
    // *     example 2: mktime(0, 0, 0, 0, 1, 2008);
    // *     returns 2: 1196463600
    // *     example 3: make = mktime();
    // *     example 3: td = new Date();
    // *     example 3: real = Math.floor(td.getTime()/1000);
    // *     example 3: diff = (real - make);
    // *     results 3: diff < 5
    // *     example 4: mktime(0, 0, 0, 13, 1, 1997)
    // *     returns 4: 883609200
    // *     example 5: mktime(0, 0, 0, 1, 1, 1998)
    // *     returns 5: 883609200
    // *     example 6: mktime(0, 0, 0, 1, 1, 98)
    // *     returns 6: 883609200
    var no=0, i = 0, ma=0, mb=0, d = new Date(), dn = new Date(), argv = arguments, argc = argv.length;

    var dateManip = {
        0: function(tt){ return d.setHours(tt); },
        1: function(tt){ return d.setMinutes(tt); },
        2: function(tt){ var set = d.setSeconds(tt); mb = d.getDate() - dn.getDate(); return set;},
        3: function(tt){ var set = d.setMonth(parseInt(tt, 10)-1); ma = d.getFullYear() - dn.getFullYear(); return set;},
        4: function(tt){ return d.setDate(tt+mb);},
        5: function(tt){
            if (tt >= 0 && tt <= 69) {
                tt += 2000;
            }
            else if (tt >= 70 && tt <= 100) {
                tt += 1900;
            }
            return d.setFullYear(tt+ma);
        }
        // 7th argument (for DST) is deprecated
    };

    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]*1, 10);
        if (isNaN(no)) {
            return false;
        } else {
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }
    for (i = argc; i < 6; i++) {
        switch(i) {
            case 0:
                no = dn.getHours();
                break;
            case 1:
                no = dn.getMinutes();
                break;
            case 2:
                no = dn.getSeconds();
                break;
            case 3:
                no = dn.getMonth()+1;
                break;
            case 4:
                no = dn.getDate();
                break;
            case 5:
                no = dn.getFullYear();
                break;
        }
        dateManip[i](no);
    }

    return Math.floor(d.getTime()/1000);
}

function mt_getrandmax()
{
    // Returns the maximum value a random number from Mersenne Twister can have  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/mt_getrandmax
    // +   original by: Onno Marsman
    // *     example 1: mt_getrandmax();
    // *     returns 1: 2147483647
    return 2147483647;
}

function mt_rand( min, max ) {
    // Returns a random number from Mersenne Twister  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/mt_rand
    // +   original by: Onno Marsman
    // *     example 1: mt_rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function natcasesort(inputArr) {
    // Sort an array using case-insensitive natural sort  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/natcasesort
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: strnatcasecmp
    // *     example 1: $array1 = {0:'IMG0.png', 1:'img12.png', 2:'img10.png', 3:'img2.png', 4:'img1.png', 5:'IMG3.png'};
    // *     example 1: natcasesort($array1);
    // *     returns 1: {0: 'IMG0.png', 4: 'img1.png', 3: 'img2.png', 5: 'IMG3.png', 2: 'img10.png', 1: 'img12.png'}
    var valArr=[], keyArr=[], k, i, ret, that = this;

    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {
                ret = that.strnatcasecmp(inputArr[j+1], inputArr[j]);
                if (ret < 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k];
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;
    }

    // Repopulate the old array
    for (i = 0; i < valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];
    }

    return true;
}

function natsort(inputArr) {
    // Sort an array using natural sort  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/natsort
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: strnatcmp
    // *     example 1: $array1 = {a:"img12.png", b:"img10.png", c:"img2.png", d:"img1.png"};
    // *     example 1: natcasesort($array1);
    // *     returns 1: {d: 'img1.png', c: 'img2.png', b: 'img10.png', a: 'img12.png'}
    var valArr=[], keyArr=[], k, i, ret, that = this;

    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {
                ret = that.strnatcmp(inputArr[j+1], inputArr[j]);
                if (ret < 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }
    };

    // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k];
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;
    }

    // Repopulate the old array
    for (i = 0; i < valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];
    }

    return true;
}

function next (arr) {
    // Move array argument's internal pointer to the next element and return it  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/next
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: transport = ['foot', 'bike', 'car', 'plane'];
    // *     example 1: next(transport);
    // *     example 1: next(transport);
    // *     returns 1: 'car'
    if (!this.php_js) {this.php_js = {};}
    if (!this.php_js.pointers) {this.php_js.pointers = [];}
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    var cursor = pointers[arrpos+1];
    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            if (ct === cursor+1) {
                pointers[arrpos+1] += 1;
                return arr[k];
            }
            ct++;
        }
        return false; // End
    }
    if (arr.length === 0 || cursor === (arr.length-1)) {
        return false;
    }
    pointers[arrpos+1] += 1;
    return arr[pointers[arrpos+1]];
}

function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/nl2br
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
    var breakTag = '';

    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }

    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

function nl_langinfo (item) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: setlocale
	// *     example 1: nl_langinfo('DAY_1');
	// *     returns 1: 'Sunday'
	
	this.setlocale('LC_ALL', 0); // Ensure locale data is available
    
	var loc = this.php_js.locales[this.php_js.localeCategories.LC_TIME];
	if (item.indexOf('ABDAY_') === 0) {
		return loc.LC_TIME.a[parseInt(item.replace(/^ABDAY_/, ''), 10)-1];
	}
	else if (item.indexOf('DAY_') === 0) {
		return loc.LC_TIME.A[parseInt(item.replace(/^DAY_/, ''), 10)-1];
	}
	else if (item.indexOf('ABMON_') === 0) {
		return loc.LC_TIME.b[parseInt(item.replace(/^ABMON_/, ''), 10)-1];
	}
	else if (item.indexOf('MON_') === 0) {
		return loc.LC_TIME.B[parseInt(item.replace(/^MON_/, ''), 10)-1];
	}
	else {
		switch(item) {
			// More LC_TIME
			case 'AM_STR':
				return loc.LC_TIME.p[0];
			case 'PM_STR':
				return loc.LC_TIME.p[1];
			case 'D_T_FMT':
				return loc.LC_TIME.c;
			case 'D_FMT':
				return loc.LC_TIME.x;
			case 'T_FMT':
				return loc.LC_TIME.X;
			case 'T_FMT_AMPM':
				return loc.LC_TIME.r;
			case 'ERA': // all fall-throughs
			case 'ERA_YEAR':
			case 'ERA_D_T_FMT':
			case 'ERA_D_FMT':
			case 'ERA_T_FMT':
				return loc.LC_TIME[item];
		}
		loc = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY];
        if (item === 'CRNCYSTR') {
            item = 'CURRENCY_SYMBOL'; // alias
        }
		switch(item) {
			case 'INT_CURR_SYMBOL': // all fall-throughs
			case 'CURRENCY_SYMBOL':
			case 'MON_DECIMAL_POINT':
			case 'MON_THOUSANDS_SEP':
			case 'POSITIVE_SIGN':
			case 'NEGATIVE_SIGN':
			case 'INT_FRAC_DIGITS':
			case 'FRAC_DIGITS':
			case 'P_CS_PRECEDES':
			case 'P_SEP_BY_SPACE':
			case 'N_CS_PRECEDES':
			case 'N_SEP_BY_SPACE':
			case 'P_SIGN_POSN':
			case 'N_SIGN_POSN':
				return loc.LC_MONETARY[item.toLowerCase()];
			case 'MON_GROUPING': // Same as above, or return something different since this returns an array?
				return loc.LC_MONETARY[item.toLowerCase()];
		}
		loc = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC];
		switch(item) {
			case 'RADIXCHAR': // Fall-through
			case 'DECIMAL_POINT':
				return loc.LC_NUMERIC[item.toLowerCase()];
			case 'THOUSEP': // Fall-through
			case 'THOUSANDS_SEP':
				return loc.LC_NUMERIC[item.toLowerCase()];
			case 'GROUPING': // Same as above, or return something different since this returns an array?
				return loc.LC_NUMERIC[item.toLowerCase()];
		}
		loc = this.php_js.locales[this.php_js.localeCategories.LC_MESSAGES];
		switch(item) {
			case 'YESEXPR': // all fall-throughs
			case 'NOEXPR':
			case 'YESSTR':
			case 'NOSTR':
				return loc.LC_MESSAGES[item];
		}
		loc = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE];
		if (item === 'CODESET') {
            return loc.LC_CTYPE[item];
		}
		return false;
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // Formats a number with grouped thousands  
    // 
    // version: 902.1517
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;

    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = Math.abs(n).toFixed(prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');

        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    return s;
}

function octdec (oct_string) {
    // Returns the decimal equivalent of an octal string  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/octdec
    // +   original by: Philippe Baumann
    // *     example 1: octdec('77');
    // *     returns 1: 63
    oct_string = (oct_string+'').replace(/[^0-7]/gi, '');
    return parseInt(oct_string, 8);
}

function ord( string ) {
    // Returns the codepoint value of a character  
    // 
    // version: 905.1411
    // discuss at: http://phpjs.org/functions/ord
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: ord('K');
    // *     returns 1: 75
    // *     example 2: ord('\uD800\uDC00'); // surrogate pair to create a single Unicode character
    // *     returns 2: 65536
    var str = string + '';
    
    var code = str.charCodeAt(0);
    if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
        var hi = code;
        if (str.length === 1) {
            return code; // This is just a high surrogate with no following low surrogate, so we return its value;
                                    // we could also throw an error as it is not a complete character, but someone may want to know
        }
        var low = str.charCodeAt(1);
        if (!low) {
            
        }
        return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
    }
    if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
        return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
                                // we could also throw an error as it is not a complete character, but someone may want to know
    }
    return code;
}

function parse_str(str, array){
    // Parses GET/POST/COOKIE data and sets global variables  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/parse_str
    // +   original by: Cagri Ekin
    // +   improved by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   reimplemented by: stag019
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: stag019
	// -    depends on: urldecode
    // %        note 1: When no argument is specified, will put variables in global scope.
    // *     example 1: var arr = {};
    // *     example 1: parse_str('first=foo&second=bar', arr);
    // *     results 1: arr == { first: 'foo', second: 'bar' }
    // *     example 2: var arr = {};
    // *     example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
    // *     results 2: arr == { str_a: "Jack and Jill didn't see the well." }
	var glue1 = '=', glue2 = '&', array2 = String(str).split(glue2),
	i, j, chr, tmp, key, value, bracket, keys, evalStr,
	fixStr = function(str)
	{
		return urldecode(str).replace(/([\\"'])/g, '\\$1').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
	};

	if(!array)
	{
		array = this.window;
	}

	for(i = 0; i < array2.length; i++)
	{
		tmp = array2[i].split(glue1);
		if(tmp.length < 2)
		{
			tmp = [tmp, ''];
		}
		key   = fixStr(tmp[0]);
		value = fixStr(tmp[1]);
		while(key.charAt(0) === ' ')
		{
			key = key.substr(1);
		}
        if(key.indexOf('\0') !== -1)
        {
            key = key.substr(0, key.indexOf('\0'));
        }
		if(key && key.charAt(0) !== '[')
		{
			keys    = [];
			bracket = 0;
			for(j = 0; j < key.length; j++)
			{
				if(key.charAt(j) === '[' && !bracket)
				{
					bracket = j + 1;
				}
				else if(key.charAt(j) === ']')
				{
					if(bracket)
					{
						if(!keys.length)
						{
							keys.push(key.substr(0, bracket - 1));
						}
						keys.push(key.substr(bracket, j - bracket));
						bracket = 0;
						if(key.charAt(j + 1) !== '[')
						{
							break;
						}
					}
				}
			}
			if(!keys.length)
			{
				keys = [key];
			}
			for(j = 0; j < keys[0].length; j++)
			{
				chr = keys[0].charAt(j);
				if(chr === ' ' || chr === '.' || chr === '[')
				{
					keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
				}
				if(chr === '[')
				{
					break;
				}
			}
			evalStr = 'array';
			for(j = 0; j < keys.length; j++)
			{
				key = keys[j];
				if((key !== '' && key !== ' ') || j === 0)
				{
					key = "'" + key + "'";
				}
				else
				{
					key = eval(evalStr + '.push([]);') - 1;
				}
				evalStr += '[' + key + ']';
				if(j !== keys.length - 1 && eval('typeof ' + evalStr) === 'undefined')
				{
					eval(evalStr + ' = [];');
				}
			}
			evalStr += " = '" + value + "';\n";
			eval(evalStr);
		}
	}
}

function parse_url (str, component) {
    // Parse a URL and return its components  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/parse_url
    // +      original by: Steven Levithan (http://blog.stevenlevithan.com)
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: blog post at http://blog.stevenlevithan.com/archives/parseuri
    // %          note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: Does not replace invaild characters with '_' as in PHP, nor does it return false with
    // %          note: a seriously malformed URL.
    // %          note: Besides function name, is the same as parseUri besides the commented out portion
    // %          note: and the additional section following, as well as our allowing an extra slash after
    // %          note: the scheme/protocol (to allow file:/// as in PHP)
    // *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
    // *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    var  o   = {
        strictMode: false,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-protocol to catch file:/// (should restrict this)
        }
    };
    
    var m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;
    while (i--) {uri[o.key[i]] = m[i] || "";}
    // Uncomment the following to use the original more detailed (non-PHP) script
    /*
        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
        });
        return uri;
    */

    switch (component) {
        case 'PHP_URL_SCHEME':
            return uri.protocol;
        case 'PHP_URL_HOST':
            return uri.host;
        case 'PHP_URL_PORT':
            return uri.port;
        case 'PHP_URL_USER':
            return uri.user;
        case 'PHP_URL_PASS':
            return uri.password;
        case 'PHP_URL_PATH':
            return uri.path;
        case 'PHP_URL_QUERY':
            return uri.query;
        case 'PHP_URL_FRAGMENT':
            return uri.anchor;
        default:
            var retArr = {};
            if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
            if (uri.host !== '') {retArr.host=uri.host;}
            if (uri.port !== '') {retArr.port=uri.port;}
            if (uri.user !== '') {retArr.user=uri.user;}
            if (uri.password !== '') {retArr.pass=uri.password;}
            if (uri.path !== '') {retArr.path=uri.path;}
            if (uri.query !== '') {retArr.query=uri.query;}
            if (uri.anchor !== '') {retArr.fragment=uri.anchor;}
            return retArr;
    }
}

function pathinfo (path, options) {
    // Returns information about a certain string  
    // 
    // version: 905.2614
    // discuss at: http://phpjs.org/functions/pathinfo
    // +   original by: Nate
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Inspired by actual PHP source: php5-5.2.6/ext/standard/string.c line #1559
    // %        note 1: The way the bitwise arguments are handled allows for greater flexibility
    // %        note 1: & compatability. We might even standardize this code and use a similar approach for
    // %        note 1: other bitwise PHP functions
    // %        note 2: PHP.JS tries very hard to stay away from a core.js file with global dependencies, because we like
    // %        note 2: that you can just take a couple of functions and be on your way.
    // %        note 2: But by way we implemented this function, if you want you can still declare the PATHINFO_*
    // %        note 2: yourself, and then you can use: pathinfo('/www/index.html', PATHINFO_BASENAME | PATHINFO_EXTENSION);
    // %        note 2: which makes it fully compliant with PHP syntax.
    // -    depends on: dirname
    // -    depends on: basename
    // *     example 1: pathinfo('/www/htdocs/index.html', 1);
    // *     returns 1: '/www/htdocs'
    // *     example 2: pathinfo('/www/htdocs/index.html', 'PATHINFO_BASENAME');
    // *     returns 2: 'index.html'
    // *     example 3: pathinfo('/www/htdocs/index.html', 'PATHINFO_EXTENSION');
    // *     returns 3: 'html'
    // *     example 4: pathinfo('/www/htdocs/index.html', 'PATHINFO_FILENAME');
    // *     returns 4: 'index'
    // *     example 5: pathinfo('/www/htdocs/index.html', 2 | 4);
    // *     returns 5: {basename: 'index.html', extension: 'html'}
    // *     example 6: pathinfo('/www/htdocs/index.html', 'PATHINFO_ALL');
    // *     returns 6: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
    // *     example 7: pathinfo('/www/htdocs/index.html');
    // *     returns 7: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
    // Working vars
    var opt = '', optName='', tmp_arr = {}, cnt = 0, i=0, opts=0;
    var have_basename = false, have_extension = false, have_filename = false;

    // Input defaulting & sanitation
    if (!path) {return false;}
    if (!options) {options = 'PATHINFO_ALL';}

    // Initialize binary arguments. Both the string & integer (constant) input is
    // allowed
    var OPTS = {
        'PATHINFO_DIRNAME': 1,
        'PATHINFO_BASENAME': 2,
        'PATHINFO_EXTENSION': 4,
        'PATHINFO_FILENAME': 8,
        'PATHINFO_ALL': 0
    };
    // PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate)
    for (optName in OPTS) {
        OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName];
    }
    if (typeof options === 'number') {
        opts = options;
    }
    else { // Allow for a single string or an array of string flags
        options = [].concat(options);
        for (i=0; i < options.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[options[i]]) {
                opts = opts | OPTS[options[i]];
            }
        }
    }

    // Internal Functions
    var __getExt = function(path) {
        var str  = path+'';
        var dotP = str.lastIndexOf('.')+1;
        return str.substr(dotP);
    };


    // Gather path infos
    if (opts & OPTS.PATHINFO_DIRNAME) {
        tmp_arr.dirname = this.dirname(path);
    }

    if (opts & OPTS.PATHINFO_BASENAME) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        tmp_arr.basename = have_basename;
    }

    if (opts & OPTS.PATHINFO_EXTENSION) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        if (false === have_extension) {
            have_extension = __getExt(have_basename);
        }
        tmp_arr.extension = have_extension;
    }

    if (opts & OPTS.PATHINFO_FILENAME) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        if (false === have_extension) {
            have_extension = __getExt(have_basename);
        }
        if (false === have_filename) {
            have_filename  = have_basename.substr(0, (have_basename.length - have_extension.length)-1);
        }

        tmp_arr.filename = have_filename;
    }


    // If array contains only 1 element: return string
    cnt = 0;
    for (opt in tmp_arr){
        cnt++;
    }
    if (cnt == 1) {
        return tmp_arr[opt];
    }

    // Return full-blown array
    return tmp_arr;
}

function pclose (handle) {
    // Close a file pointer opened by popen()  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/pclose
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var handle = popen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: pclose(handle);
    // *     returns 1: true

    if (!handle || handle.opener !== 'popen') {
        return false;
    }

    try {
        delete this.php_js.resourceDataPointer[handle.id];
        delete this.php_js.resourceData[handle.id]; // Free up memory
        return true;
    }
    catch(e) {
        return false;
    }
}

function php_ini_loaded_file () {
    // Return the actual loaded ini filename  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/php_ini_loaded_file
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: This string representing the path of the main ini file must be manually set by the script to this.php_js.ini_loaded_file
    // *     example 1: php_ini_loaded_file();
    // *     returns 1: 'myini.js'
	if (!this.php_js || !this.php_js.ini_loaded_file) {
		return false;
	}
	return this.php_js.ini_loaded_file;
}

function php_ini_scanned_files () {
    // Return comma-separated string of .ini files parsed from the additional ini dir  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/php_ini_scanned_files
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: This comma-separated string of files contained in one directory must be manually set by the script to this.php_js.ini_scanned_files
    // *     example 1: php_ini_scanned_files();
    // *     returns 1: 'myini.js,myini2.js'
	if (!this.php_js || !this.php_js.ini_scanned_files) {
		return false;
	}
	return this.php_js.ini_scanned_files;
}

function php_strip_whitespace (file) {
    // Return source with stripped comments and whitespace  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/php_strip_whitespace
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
    // %        note 1: To avoid browser blocking issues's consider using jQuery's: $('#divId').load('http://url') instead.
    // -    depends on: file_get_contents
    // *     example 1: php_strip_whitespace('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    try {
        var str = this.file_get_contents(file);
    } catch (e) {
        return '';
    }
    // Strip comments (both styles), reduce non-newline whitespace to one, reduce multiple
    // newlines (preceded by any whitespace) to a newline, remove WS at beginning of line,
    // and at end of line
    return str.replace(/\/\/.*?\n/g, '').replace(/\/\*[^]*?\*\//g, '').replace(/[ \f\r\t\v\u00A0\u2028\u2029]+/g, ' ').replace(/\s*\n+/g, '\n').replace(/^\s+/gm, '').replace(/\s*$/gm, '');
}

function phpversion () {
    // Return the current PHP version  
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/phpversion
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: We are using this to get the JavaScript version (since this is JavaScript and we can't get the PHP version anyways)
    // %        note 2: The return value will depend on your client's JavaScript version
    // %        note 3: Uses global: php_js to store environment info
    // *     example 1: phpversion();
    // *     returns 1: '1.8'

	var xhtml=true, s={}, firstScript={}, d = this.window.document,
            c = 'createElement', cn = 'createElementNS', xn = 'http://www.w3.org/1999/xhtml',
            g = 'getElementsByTagName', gn = 'getElementsByTagNameNS';

	if (!this.php_js) {
		this.php_js = {};
	}

	var getVersion = function (app) {
        var att='', minVers=0, versionString='', temp_jsversion=undefined;
		if (this.php_js.jsversion !== undefined) {
			return this.php_js.jsversion;
		}
		while (this.php_js.jsversion === temp_jsversion && minVers < 10) {
			temp_jsversion = '1.'+minVers;
			if (gn) {
				firstScript = d[gn](xn, 'script')[0];
			}
			if (!firstScript) {
				firstScript = d[g]('script')[0];
				xhtml = false;
			}
			if (d[cn] && xhtml) {
				s = d[cn](xn, 'script');
			}
			else {
				s = d[c]('script');
			}

			if (app) { // Check with standard attribute (but not cross-browser standardized value?) as per Mozilla
				att = 'type';
				versionString='application/javascript;version=1.';
			}
			else {
				att = 'language'; // non-standard
				versionString='JavaScript1.';
			}

			s.setAttribute(att, versionString+minVers);
			s.appendChild(d.createTextNode("this.php_js.jsversion="+"'1."+minVers+"'"));
			firstScript.parentNode.insertBefore(s, firstScript);
            s.parentNode.removeChild(s);
			minVers++;
		}
		return this.php_js.jsversion;
	};
	getVersion(true);
	getVersion(false);

	return this.php_js.jsversion;
}

function pi() {
    // Returns an approximation of pi  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/pi
    // +   original by: Onno Marsman
    // *     example 1: pi(8723321.4);
    // *     returns 1: 3.141592653589793
    return Math.PI;
}

function popen (filename, mode, use_include_path, context) {
    // Execute a command and open either a read or a write pipe to it  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/popen
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: popen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     returns 1: 'Resource id #1'

    var resource={}, i=0, that = this;

    // BEGIN file inclusion: file_get_contents
    var file_get_contents = function ( url ) {
        var req = that.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        if (!req) {
		    throw new Error('XMLHttpRequest not supported');
		}
        if (!/^http/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url())
            url = that.window.location.href + '/' +url;
        }
        req.open("GET", url, false);
        req.send(null);
        return req.responseText;
    };
    // END file inclusion

    if (use_include_path === 1 || use_include_path === '1' || use_include_path === true) {
        // Not implemented yet: Search for file in include path too
    }
    if (context) {
        // Not implemented yet, but could be useful to modify nature of HTTP request, etc.
    }

    for (i=0; i < mode.length; i++) { // Have to deal with other flags if ever allow
        switch(mode[i]) {
            case 'r':
                if (!mode[i+1] || mode[i+1] !== '+') {
                    break;
                }
            case 'w': // or 'w+'
            case 'a': // or 'a+'
            case 'x':// or 'x+'
                throw 'Writing is not implemented';
            case 'b':
            case 't':
                throw 'Windows-only modes are not supported';
            default:
                throw 'Unrecognized file mode passed to '+arguments.caller.name+'()';
        }
    }

    // BEGIN STATIC
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.resourceData) {
        this.php_js.resourceData = {};
    }
    if (!this.php_js.resourceIdCounter) {
        this.php_js.resourceIdCounter = 0;
    }
    if (!this.php_js.resourceDataPointer) {
        this.php_js.resourceDataPointer = {};
    }
    this.php_js.resourceIdCounter++;

    function PHPJS_Resource (type, id, opener) { // Can reuse the following for other resources, just changing the instantiation
        // See http://php.net/manual/en/resource.php for types
        this.type = type;
        this.id = id;
        this.opener = opener;
    }
    PHPJS_Resource.prototype.toString = function () {
        return 'Resource id #'+this.id;
    };
    PHPJS_Resource.prototype.get_resource_type = function () {
        return this.type;
    };
    PHPJS_Resource.prototype.var_dump = function () {
        return 'resource('+this.id+') of type ('+this.type+')';
    };
    // END STATIC

    this.php_js.resourceData[this.php_js.resourceIdCounter] = file_get_contents(filename);
    this.php_js.resourceDataPointer[this.php_js.resourceIdCounter] = 0;

    resource = new PHPJS_Resource('stream', this.php_js.resourceIdCounter, 'popen');
    resource.mode = mode; // Add file-specific attributes

    return resource; // may be 'file' instead of 'stream' type on some systems
}

function pos(arr) {
    // !No description available for pos. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/pos
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // -    depends on: current
    // *     example 1: transport = ['foot', 'bike', 'car', 'plane'];
    // *     example 1: pos(transport);
    // *     returns 1: 'foot'
    
    return this.current(arr);
}

function pow(base, exp) {
    // Returns base raised to the power of exponent. Returns integer result when possible  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/pow
    // +   original by: Onno Marsman
    // *     example 1: pow(8723321.4, 7);
    // *     returns 1: 3.843909168077899e+48
    return Math.pow(base, exp);
}

function preg_grep (pattern, input, flags) {
    // Searches array and returns entries which match regex  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/preg_grep
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: If pass pattern as string, must escape backslashes, even for single quotes
    // %          note 2: The regular expression itself must be expressed JavaScript style
    // %          note 3: It is not recommended to submit the pattern as a string, as we may implement
    // %          note 3:   parsing of PHP-style expressions (flags, etc.) in the future
    // *     example 1: var arr = [1, 4, 4.5, 3, 'a', 4.4];
    // *     example 1: preg_grep("/^(\\d+)?\\.\\d+$/", arr);
    // *     returns 1: {2: 4.5, 5: 4.4}

    var p='', retObj = {};
    var invert = flags === 'PREG_GREP_INVERT' ? true : false;

    if (typeof pattern === 'string') {
        pattern = eval(pattern);
    }

    if (invert) {
        for (p in input) {
            if (!pattern.test(input[p])) {
                retObj[p] = input[p];
            }
        }
    } else {
        for (p in input) {
            if (pattern.test(input[p])) {
                retObj[p] = input[p];
            }
        }
    }

    return retObj;
}

function preg_quote( str ) {
    // Quote regular expression characters plus an optional character  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/preg_quote
    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, "\\$1");
}

function prev (arr) {
    // Move array argument's internal pointer to the previous element and return it  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/prev
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: transport = ['foot', 'bike', 'car', 'plane'];
    // *     example 1: prev(transport);
    // *     returns 1: false
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.pointers) {
        this.php_js.pointers = [];
    }
    var pointers = this.php_js.pointers;
    var arrpos = pointers.indexOf(arr);
    var cursor = pointers[arrpos+1];
    if (pointers.indexOf(arr) === -1 || cursor === 0) {
        return false;
    }
    if (!(arr instanceof Array)) {
        var ct = 0;
        for (var k in arr) {
            if (ct === cursor-1) {
                pointers[arrpos+1] -= 1;
                return arr[k];
            }
            ct++;
        }
    // Shouldn't reach here
    }
    if (arr.length === 0) {
        return false;
    }
    pointers[arrpos+1] -= 1;
    return arr[pointers[arrpos+1]];
}

function print_r( array, return_val ) {
    // Prints out or returns information about the specified variable  
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/print_r
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +      improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: echo
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4, d = this.window.document;

    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) {
            str += pad_char;
        }
        return str;
    };

    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }

        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";

        if (typeof obj === 'object' && obj !== null && obj.constructor && obj.constructor.name !== 'PHPJS_Resource') {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj === null || obj === undefined) {
            str = '';
        } else { // for our "resource" class
            str = obj.toString();
        }

        return str;
    };

    output = formatArray(array, 0, pad_val, pad_char);

    if (return_val !== true) {
        if (d.body) {
            this.echo(output);
        }
        else {
            try {
                d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
                this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
            }
            catch(e) {
                this.echo(output); // Outputting as plain text may work in some plain XML
            }
        }
        return true;
    } else {
        return output;
    }
}

function printf( ) {
    // Output a formatted string  
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/printf
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Michael White (http://getsprink.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: sprintf
    // *     example 1: printf("%01.2f", 123.1);
    // *     returns 1: 6
    var body, elmt, d = this.window.document;
    var ret = '';
    
    var HTMLNS = 'http://www.w3.org/1999/xhtml';
    body = d.getElementsByTagNameNS ?
      (d.getElementsByTagNameNS(HTMLNS, 'body')[0] ?
        d.getElementsByTagNameNS(HTMLNS, 'body')[0] :
        d.documentElement.lastChild) :
      d.getElementsByTagName('body')[0];

    if (!body) {
        return false;
    }
    
    ret = this.sprintf.apply(this, arguments);

    elmt = d.createTextNode(ret);
    body.appendChild(elmt);
    
    return ret.length;
}

function property_exists (cls, prop) {
    // Checks if the object or class has a property  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/property_exists
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function class_a() {this.prop1 = 'one'};
    // *     example 1: var instance_a = new class_a();
    // *     example 1: property_exists(instance_a, 'prop1');
    // *     returns 1: true
    // *     example 2: function class_a() {this.prop1 = 'one'};
    // *     example 2: var instance_a = new class_a();
    // *     example 2: property_exists(instance_a, 'prop2');
    // *     returns 2: false
    cls = (typeof cls === 'string') ? this.window[cls] : cls;
    
    if (typeof cls === 'function' && cls.toSource &&
        cls.toSource().match(new RegExp('this\\.'+prop+'\\s'))
    ) {
        // Hackish and non-standard but can probably detect if setting
        // the property (we don't want to test by instantiating as that
        // may have side-effects)
        return true;
    }

    return (cls[prop] !== undefined && typeof cls[prop] !== 'function') ||
        (cls.prototype !== undefined && cls.prototype[prop] !== undefined && typeof cls.prototype[prop] !== 'function') ||
        (cls.constructor && cls.constructor[prop] !== undefined && typeof cls.constructor[prop] !== 'function');
}

function putenv (setting) {
    // Set the value of an environment variable  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/putenv
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: We are not using $_ENV as in PHP, you could define
    // %        note 1: "$_ENV = this.php_js.ENV;" and get/set accordingly
    // %        note 2: Uses global: php_js to store environment info
    // *     example 1: putenv('LC_ALL=en-US');
    // *     results 1: true
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.ENV) {
        this.php_js.ENV = {};
    }
    var pos = setting.indexOf('=');
    this.php_js.ENV[setting.slice(0,pos)] = setting.slice(pos+1);
    return true;
}

function quoted_printable_decode(str) {
	// http://kevin.vanzonneveld.net
	// +   original by: Ole Vrijenhoek
	// +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // +   reimplemented by: Theriault
	// +   improved by: Brett Zamir (http://brettz9.blogspot.com)
	// +   bugfixed by: Theriault
    // *     example 1: quoted_printable_decode('a=3Db=3Dc');
    // *     returns 1: 'a=b=c'
    // *     example 2: quoted_printable_decode('abc  =20\r\n123  =20\r\n');
    // *     returns 2: 'abc   \r\n123   \r\n'
    // *     example 3: quoted_printable_decode('012345678901234567890123456789012345678901234567890123456789012345678901234=\r\n56789');
    // *     returns 3: '01234567890123456789012345678901234567890123456789012345678901234567890123456789'
    // *    example 4: quoted_printable_decode("Lorem ipsum dolor sit amet=23, consectetur adipisicing elit");
    // *    returns 4: Lorem ipsum dolor sit amet#, consectetur adipisicing elit

    // Removes softline breaks
    var RFC2045Decode1 = /=\r\n/gm,
    // Decodes all equal signs followed by two hex digits
    RFC2045Decode2IN = /=([0-9A-F]{2})/gim, // the RFC states against decoding lower case encodings, but following apparent PHP behavior
    // RFC2045Decode2IN = /=([0-9A-F]{2})/gm,

    RFC2045Decode2OUT = function (sMatch, sHex) {
        return String.fromCharCode(parseInt(sHex, 16));
    };
    return str.replace(RFC2045Decode1, '').replace(RFC2045Decode2IN, RFC2045Decode2OUT);
}

function quoted_printable_encode(str) {
    // +   original by: Theriault
	// +   improved by: Brett Zamir (http://brettz9.blogspot.com)
	// +   improved by: Theriault
    // *     example 1: quoted_printable_encode('a=b=c');
    // *     returns 1: 'a=3Db=3Dc'
    // *     example 2: quoted_printable_encode('abc   \r\n123   \r\n');
    // *     returns 2: 'abc  =20\r\n123  =20\r\n'
    // *     example 3: quoted_printable_encode('0123456789012345678901234567890123456789012345678901234567890123456789012345');
    // *     returns 3: '012345678901234567890123456789012345678901234567890123456789012345678901234=\r\n5'

    // RFC 2045: 6.7.2: Octets with decimal values of 33 through 60 (bang to less-than) inclusive, and 62 through 126 (greater-than to tilde), inclusive, MAY be represented as the US-ASCII characters
    // PHP does not encode any of the above; as does this function.
    // RFC 2045: 6.7.3: Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line
    // PHP does not encode spaces (octet 32) except before a CRLF sequence as stated above. PHP always encodes tabs (octet 9). This function replicates PHP.
    // RFC 2045: 6.7.4: A line break in a text body, represented as a CRLF sequence in the text canonical form, must be represented by a (RFC 822) line break
    // PHP does not encode a CRLF sequence, as does this function.
    // RFC 2045: 6.7.5: The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks must be used.
    // PHP breaks lines greater than 76 characters; as does this function.
    var hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'],
    RFC2045Encode1IN = / \r\n|\r\n|[^!-<>-~ ]/gm,
    RFC2045Encode1OUT = function (sMatch) {
        // Encode space before CRLF sequence to prevent spaces from being stripped
        // Keep hard line breaks intact; CRLF sequences
        if (sMatch.length > 1) {
            return sMatch.replace(' ', '=20');
        }
        // Encode matching character
        var chr = sMatch.charCodeAt(0);
        return '=' + hexChars[((chr >>> 4) & 15)] + hexChars[(chr & 15)];
    },
    // Split lines to 75 characters; the reason it's 75 and not 76 is because softline breaks are preceeded by an equal sign; which would be the 76th character.
    // However, if the last line/string was exactly 76 characters, then a softline would not be needed. PHP currently softbreaks anyway; so this function replicates PHP.
    RFC2045Encode2IN = /.{1,72}(?!\r\n)[^=]{0,3}/g,
    RFC2045Encode2OUT = function (sMatch) {
        if (sMatch.substr(sMatch.length - 2) === '\r\n') {
            return sMatch;
        }
        return sMatch + '=\r\n';
    };
    str = str.replace(RFC2045Encode1IN, RFC2045Encode1OUT).replace(RFC2045Encode2IN, RFC2045Encode2OUT);
    // Strip last softline break
    return str.substr(0, str.length - 3);
}

function quotemeta(str) {
    // Quotes meta characters  
    // 
    // version: 812.316
    // discuss at: http://phpjs.org/functions/quotemeta
    // +   original by: Paulo Ricardo F. Santos
    // *     example 1: quotemeta(". + * ? ^ ( $ )");
    // *     returns 1: '\. \+ \* \? \^ \( \$ \)'
    return (str+'').replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1');
}

function rad2deg(angle) {
    // Converts the radian number to the equivalent number in degrees  
    // 
    // version: 810.117
    // discuss at: http://phpjs.org/functions/rad2deg
    // +   original by: Enrique Gonzalez
    // *     example 1: rad2deg(3.141592653589793);
    // *     returns 1: 180
    
    return (angle/Math.PI) * 180;
}

function rand( min, max ) {
    // Returns a random number  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/rand
    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
	// %          note 1: See the commented out code below for a version which will work with our experimental (though probably unnecessary) srand() function)
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
    
    /*
    // See note above for an explanation of the following alternative code
    
	// +   reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: srand
	// %          note 1: This is a very possibly imperfect adaptation from the PHP source code
	var rand_seed, ctx, PHP_RAND_MAX=2147483647; // 0x7fffffff

	if (!this.php_js || this.php_js.rand_seed === undefined) {
		this.srand();
	}
	rand_seed = this.php_js.rand_seed;

	var argc = arguments.length;
    if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }

	var do_rand = function (ctx) {
		return ((ctx * 1103515245 + 12345) % (PHP_RAND_MAX + 1));
	};

	var php_rand = function (ctxArg) { // php_rand_r
		this.php_js.rand_seed = do_rand(ctxArg);
		return parseInt(this.php_js.rand_seed, 10);
	};

	var number = php_rand(rand_seed);

	if (argc === 2) {
		number = min + parseInt(parseFloat(parseFloat(max) - min + 1.0) * (number/(PHP_RAND_MAX + 1.0)), 10);
    }
	return number;
    */
}

function range ( low, high, step ) {
    // Create an array containing the range of integers or characters from low to high (inclusive)  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/range
    // +   original by: Waldo Malqui Silva
    // *     example 1: range ( 0, 12 );
    // *     returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    // *     example 2: range( 0, 100, 10 );
    // *     returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    // *     example 3: range( 'a', 'i' );
    // *     returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    // *     example 4: range( 'c', 'a' );
    // *     returns 4: ['c', 'b', 'a']
    var matrix = [];
    var inival, endval, plus;
    var walker = step || 1;
    var chars  = false;

    if ( !isNaN( low ) && !isNaN( high ) ) {
        inival = low;
        endval = high;
    } else if ( isNaN( low ) && isNaN( high ) ) {
        chars = true;
        inival = low.charCodeAt( 0 );
        endval = high.charCodeAt( 0 );
    } else {
        inival = ( isNaN( low ) ? 0 : low );
        endval = ( isNaN( high ) ? 0 : high );
    }

    plus = ( ( inival > endval ) ? false : true );
    if ( plus ) {
        while ( inival <= endval ) {
            matrix.push( ( ( chars ) ? String.fromCharCode( inival ) : inival ) );
            inival += walker;
        }
    } else {
        while ( inival >= endval ) {
            matrix.push( ( ( chars ) ? String.fromCharCode( inival ) : inival ) );
            inival -= walker;
        }
    }

    return matrix;
}

function rawurldecode( str ) {
    // Decodes URL-encodes string  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/rawurldecode
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: rawurldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin+van+Zonneveld!'
    // *     example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    // *     example 4: rawurldecode('-22%97bc%2Fbc');
    // *     returns 4: '-22—bc/bc'
    var histogram = {}, ret = str.toString(), unicodeStr='', hexEscStr='';

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';


    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }

    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = ret.replace(/%([a-fA-F][0-9a-fA-F])/g, function (all, hex) {return String.fromCharCode('0x'+hex);}); // These Latin-B have the same values in Unicode, so we can convert them like this
    ret = decodeURIComponent(ret);

    return ret;
}

function rawurlencode( str ) {
    // URL-encodes string  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/rawurlencode
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin%20van%20Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var histogram = {}, unicodeStr='', hexEscStr='';
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A'; 
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';


    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr];
        ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
}

function readfile (filename, use_include_path, context) {
    // Output a file or a URL  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/readfile
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: echo
    // *     example 1: readfile('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'

    var read_data = this.file_get_contents(filename, use_include_path, context); // bitwise-or use_include_path?
    this.echo(read_data);
    return read_data;
}

function realpath(path) {
    // Return the resolved path  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/realpath
    // +   original by: mk.keck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Returned path is an url like e.g. 'http://yourhost.tld/path/'
    // *     example 1: realpath('../.././_supporters/pj_test_supportfile_1.htm');
    // *     returns 1: 'file:/home/kevin/workspace/_supporters/pj_test_supportfile_1.htm'
    
    var p = 0, arr = [];
    /* Save the root, if not given */
    var r = this.window.location.href;
    /* Avoid input failures */
    path = (path + '').replace('\\', '/');
    /* Check if there's a port in path (like 'http://') */
    if (path.indexOf('://') !== -1) {
        p = 1;
    }
    /* Ok, there's not a port in path, so let's take the root */
    if (!p) {
        path = r.substring(0, r.lastIndexOf('/') + 1) + path;
    }
    /* Explode the given path into it's parts */
    arr = path.split('/');
    /* The path is an array now */
    path = [];
    /* Foreach part make a check */
    for (var k in arr) {
        /* This is'nt really interesting */
        if (arr[k] == '.') {
            continue;
        }
        /* This reduces the realpath */
        if (arr[k] == '..') {
            /* But only if there more than 3 parts in the path-array.
             * The first three parts are for the uri */
            if (path.length > 3) {
                path.pop();
            }
        }
        /* This adds parts to the realpath */
        else {
            /* But only if the part is not empty or the uri
             * (the first three parts ar needed) was not
             * saved */
            if ((path.length < 2) || (arr[k] !== '')) {
                path.push(arr[k]);
            }
        }
    }
    /* Returns the absloute path as a string */
    return path.join('/');
}

function register_shutdown_function (cb) {
    // Register a user-level function to be called on request termination  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/register_shutdown_function
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: register_shutdown_function(function(first, middle, last) {alert('Goodbye '+first+' '+middle+' '+last+'!');}, 'Kevin', 'van', 'Zonneveld');
    // *     returns 1: 'Goodbye Kevin van Zonneveld!'
    var args=[];

    args = Array.prototype.slice.call(arguments, 1);
    this.window.addEventListener('unload', function () {
        cb.apply(null, args);
    }, false);
}

function require( filename ) {
    // !No description available for require. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/require
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Force Javascript execution to pause until the file is loaded. Usually causes failure if the file never loads. ( Use sparingly! )
    // %        note 2: Uses global: php_js to keep track of included files
    // -    depends on: file_get_contents
    // *     example 1: require('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: 2
    var d = this.window.document;
    var js_code = this.file_get_contents(filename);
    var script_block = d.createElementNS ? d.createElementNS('http://www.w3.org/1999/xhtml', 'script') : d.createElement('script');
    script_block.type = 'text/javascript';
    var client_pc = navigator.userAgent.toLowerCase();
    if((client_pc.indexOf("msie") != -1) && (client_pc.indexOf("opera") == -1)) {
        script_block.text = js_code;
    } else {
        script_block.appendChild(d.createTextNode(js_code));
    }
    
    if (typeof(script_block) != "undefined") {
        d.getElementsByTagNameNS ? d.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'head')[0].appendChild(script_block) : d.getElementsByTagName('head')[0].appendChild(script_block);

        // save include state for reference by include_once and require_once()
        var cur_file = {};
        cur_file[this.window.location.href] = 1;

        if (!this.php_js) {
            this.php_js = {};
        }
        if (!this.php_js.includes) {
            this.php_js.includes = cur_file;
        }

        if (!this.php_js.includes[filename]) {
            this.php_js.includes[filename] = 1;
            return 1;
        } else {
            return ++this.php_js.includes[filename];
        }
    }
    return 0;
}

function require_once(filename) {
    // !No description available for require_once. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/require_once
    // +   original by: Michael White (http://getsprink.com)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Uses global: php_js to keep track of included files
    // -    depends on: require
    // *     example 1: require_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: true
    var cur_file = {};
    cur_file[this.window.location.href] = 1;

    // save include state for reference by include_once and require_once()
    if (!this.php_js) {
	    this.php_js = {};
	}
    if (!this.php_js.includes) {
	    this.php_js.includes = cur_file;
	}
    if (!this.php_js.includes[filename]) {
        if (this.require(filename)) {
            return true;
        }
    } else {
        return true;
    }
    return false;
}

function reset ( arr ) {
    // Set array argument's internal pointer to the first element and return it  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/reset
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Legaev Andrey
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Uses global: php_js to store the array pointer
    // *     example 1: reset({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 1: 'Kevin' 
    
    if (!this.php_js) {
        this.php_js = {};
    }
    if (!this.php_js.pointers) {
        this.php_js.pointers = [];
    }
    var pointers = this.php_js.pointers;
    if (pointers.indexOf(arr) === -1) {
        pointers.push(arr, 0);
    }
    var arrpos = pointers.indexOf(arr);
    if (!(arr instanceof Array)) {
        for (var k in arr) {
            if (pointers.indexOf(arr) === -1) {
                pointers.push(arr, 0);
            } else {
                pointers[arrpos+1] = 0;
            }
            return arr[k];
        }
        return false; // Empty
    }
    if (arr.length === 0) {
        return false;
    }
    pointers[arrpos+1] = 0;
    return arr[pointers[arrpos+1]];
}

function restore_exception_handler () {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: restore_exception_handler();
	// *     returns 1: true
    
    // Fix: Docs suggest can revert to built-in function; where/how is it set? in ini somewhere?

    if (!this.php_js || !this.php_js.previous_exception_handler) {
        return true; // function always returns true
    }

    this.php_js.exception_handler = this.php_js.previous_exception_handler;

    return true;
}

function rewind (handle) {
    // Rewind the position of a file pointer  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/rewind
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: var h = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fread(h, 100);
    // *     example 1: rewind(h);
    // *     returns 1: true

    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer ||
            !handle || !handle.constructor || handle.constructor.name !== 'PHPJS_Resource') {
        return false;
    }
    this.php_js.resourceDataPointer[handle.id] = 0;
    return true;
}

function round ( val, precision, mode ) {
    // Returns the number rounded to specified precision  
    // 
    // version: 904.2314
    // discuss at: http://phpjs.org/functions/round
    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // *     example 1: round(1241757, -3);
    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // Need to support mode flags: PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD
 
    return parseFloat(parseFloat(val).toFixed(precision));
}

function rsort (inputArr, sort_flags) {
    // Sort an array in reverse order  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/rsort
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: SORT_STRING (as well as natsort and natcasesort) might also be
    // %        note 1: integrated into all of these functions by adapting the code at
    // %        note 1: http://sourcefrog.net/projects/natsort/natcompare.js
    // *     example 1: rsort(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: rsort(fruits);
    // *     returns 2: true
    // *     results 2: fruits == {0: 'orange', 1: 'lemon', 2: 'banana', 3: 'apple'}
    var valArr = [], k = '', i = 0, sorter = false, that=this;
    
    for (k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k];
    }

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
             sorter = function (a, b) {
                return that.strnatcmp(b, a);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(b.localeCompare(a));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(b - a);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a < b) {
                    return 1;
				}
                if (a > b) {
                    return -1;
				}
                return 0;
            };
            break;
    }
    valArr.sort(sorter);

    for (i = 0; i < valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }
    return true;
}

function rtrim ( str, charlist ) {
    // Removes trailing whitespace  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/rtrim
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: rtrim('    Kevin van Zonneveld    ');
    // *     returns 1: '    Kevin van Zonneveld'
    charlist = !charlist ? ' \\s\u00A0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');
    return (str+'').replace(re, '');
}

function runkit_class_adopt (classname, parentname) {
    // !No description available for runkit_class_adopt. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/runkit_class_adopt
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only obtain and set classes from the global context
    // *     example 1: function A () {}
    // *     example 1: A.prototype.methodA = function () {};
    // *     example 1: function B () {}
    // *     example 1: runkit_class_adopt('B', 'A');
    // *     returns 1: true

    if (typeof this.window[classname] !== 'function' || typeof this.window[parentname] !== 'function') {
        return false;
    }

    // Classical style of inheritance
    this.window[classname].prototype = new this.window[parentname](); // Has side effects by calling the constructor!

/*
    // Prototypal completely by reference
    this.window[classname].prototype = parentname.prototype; // By mutual reference!
*/

/*
    // Mixin (deep copy, not by reference)
    var _copy = function (child, parent) {
        var p = '';
        for (p in parent) {
            if (typeof parent[p] === 'object') {
                child[p] = _copy(child[p], parent[p]);
            }
            else {
                child[p] = parent[p];
            }
        }
    };
    _copy(this.window[classname].prototype, this.window[parentname].prototype);
*/

    // Put original constructor property back
    this.window[classname].constructor = this.window[classname];
    return true;
}

function runkit_class_emancipate (classname) {
    // !No description available for runkit_class_emancipate. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_class_emancipate
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only obtain classes from the global context
	// %          note 2: We have to delete all items on the prototype
    // *     example 1: function A () {}
    // *     example 1: A.prototype.methodA = function () {};
    // *     example 1: function B () {}
    // *     example 1: runkit_class_adopt('B', 'A');
    // *     example 1: runkit_class_emancipate('B');
    // *     returns 1: true

    if (typeof this.window[classname] !== 'function') {
        return false;
    }

    for (var p in this.window[classname].prototype) {
        delete this.window[classname].prototype[p];
    }
    return true;
}

function runkit_function_add (funcname, arglist, code) {
    // !No description available for runkit_function_add. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_function_add
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only be added to the global context; use create_function() for an anonymous function
    // *     example 1: runkit_function_add('add', 'a, b', "return (a + b);");
    // *     returns 1: true

    if (this.window[funcname] !== undefined) { // Presumably disallows adding where exists, since there is also redefine function
        return false;
    }
    
    try {
        this.window[funcname] = Function.apply(null, arglist.split(',').concat(code));
        return true;
    }
    catch (e) {
        return false;
    }
}

function runkit_function_copy (funcname, targetname) {
    // !No description available for runkit_function_copy. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_function_copy
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only be copied to and from the global context
    // *     example 1: function plus (a, b) { return (a + b); }
    // *     example 1: runkit_function_copy('plus', 'add');
    // *     returns 1: true

    if (typeof this.window[funcname] !== 'function' || this.window[targetname] !== undefined) { //  (presumably disallow overwriting existing variables)
        return false;
    }
    this.window[targetname] = this.window[funcname];
    return true;
}

function runkit_function_redefine (funcname, arglist, code) {
    // !No description available for runkit_function_redefine. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_function_redefine
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only be added to the global context; use create_function() for an anonymous function
    // *     example 1: function add (a, b, c) {return a+b+c;}
    // *     example 1: runkit_function_redefine('add', 'a, b', "return (a + b);");
    // *     returns 1: true

    if (this.window[funcname] === undefined) { // Requires existing function?
        return false;
    }

    try {
        this.window[funcname] = Function.apply(null, arglist.split(',').concat(code));
        return true;
    }
    catch (e) {
        return false;
    }
}

function runkit_function_remove (funcname) {
    // !No description available for runkit_function_remove. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_function_remove
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only remove from the global context
    // *     example 1: function add (a, b, c) {return a+b+c;}
    // *     example 1: runkit_function_remove('add');
    // *     returns 1: true

    if (this.window[funcname] === undefined) { // Requires existing function?
        return false;
    }

    try {
        this.window[funcname] = undefined;
        return true;
    }
    catch (e) {
        return false;
    }
}

function runkit_function_rename (funcname, newname) {
    // !No description available for runkit_function_rename. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_function_rename
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: Function can only be copied to and from the global context
    // *     example 1: function plus (a, b) { return (a + b); }
    // *     example 1: runkit_function_rename('plus', 'add');
    // *     returns 1: true

    if (typeof this.window[newname] !== 'function' || this.window[funcname] !== undefined) { //  (presumably disallow overwriting existing variables)
        return false;
    }
    this.window[newname] = this.window[funcname];
    this.window[funcname] = undefined;
    return true;
}

function runkit_import (file, flags) {
    // !No description available for runkit_import. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/runkit_import
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // -    depends on: file_get_contents
    // %        note 1: does not return an associative array as in PHP and will evaluate all variables, not only those in a function or class
    // %        note 2: Implement instead with include?
    // *     example 1: runkit_import('http://example.com/somefile.js');
    // *     returns 1: undefined

    if (flags) {
        // RUNKIT_IMPORT_FUNCTIONS, RUNKIT_IMPORT_CLASS_METHODS, RUNKIT_IMPORT_CLASS_CONSTS,
        // RUNKIT_IMPORT_CLASS_PROPS, RUNKIT_IMPORT_CLASSES, RUNKIT_IMPORT_OVERRIDE
        // CLASSKIT_AGGREGATE_OVERRIDE ?
        throw 'Flags not supported for runkit_import';
    }

	eval(this.file_get_contents(file));
}

function runkit_method_add (classname, methodname, args, code, flags) {
    // !No description available for runkit_method_add. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_method_add
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: function a(){}
    // *     example 1: runkit_method_add ('a', 'b', 'a,b', 'return a+b');
    // *     returns 1: true

    var func, argmnts = [];

	switch (flags) {
		case 'RUNKIT_ACC_PROTECTED':
			throw 'Protected not supported';
		case 'RUNKIT_ACC_PRIVATE':
			throw 'Private not supported';
		case 'RUNKIT_ACC_PUBLIC':
			default:
				break;
	}

	argmnts = args.split(/,\s*/);

	if (typeof classname === 'string') {
		classname = this.window[classname];
	}

// Could use the following to add as a static method to the class
//	    func = Function.apply(null, argmnts.concat(code));
//            classname[methodname] = func;
	func = Function.apply(null, argmnts.concat(code));
	classname.prototype[methodname] = func;
    return true;
}

function runkit_method_copy (dClass, dMethod, sClass, sMethod) {
    // !No description available for runkit_method_copy. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_method_copy
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: runkit_method_copy('newClass', 'newMethod', 'someClass', 'someMethod');
    // *     returns 1: true

	/*
	function A(){}
	function C(){}
	C.d = function () {alert('inside d');}
	runkit_method_copy('A', 'b', 'C', 'd');
	A.b(); // 'inside d'
	*/
    sMethod = sMethod || dMethod;

	if (typeof dClass === 'string') {
		dClass = this.window[dClass];
	}
	if (typeof sClass === 'string') {
		sClass = this.window[sClass];
	}

	//dClass[dMethod] = sClass[sMethod]; // Copy from static to static method (as per PHP example)
	dClass.prototype[dMethod] = sClass.prototype[sMethod]; // To copy from instance to instance
    return true;
}

function runkit_method_redefine (classname, methodname, args, code, flags) {
    // !No description available for runkit_method_redefine. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_method_redefine
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: runkit_method_redefine('someClass', 'someMethod', 'a,b', 'return a+b');
    // *     returns 1: true

	// In JavaScript, this is identical to runkit_method_add

	var argmnts = [], func;

	switch (flags) {
		case 'RUNKIT_ACC_PROTECTED':
			throw 'Protected not supported';
		case 'RUNKIT_ACC_PRIVATE':
			throw 'Private not supported';
		case 'RUNKIT_ACC_PUBLIC':
			default:
				break;
	}

	argmnts = args.split(/,\s*/);

	if (typeof classname === 'string') {
		classname = this.window[classname];
	}

    if (classname.name !== 'PHP_JS' ||  // By default, don't allow overriding of PHP functions
        (this.php_js && this.php_js.ini && this.php_js.ini['runkit.internal_override'] &&
        (this.php_js.ini['runkit.internal_override'].local_value === true ||
            this.php_js.ini['runkit.internal_override'].local_value === 1 ||
            this.php_js.ini['runkit.internal_override'].local_value === '1' ||
            this.php_js.ini['runkit.internal_override'].local_value === 'true'
            )
        )) {
        // Could use the following to add as a static method to the class
        //	    func = Function.apply(null, argmnts.concat(code));
        //            classname[methodname] = func;
        func = Function.apply(null, argmnts.concat(code));
        classname.prototype[methodname] = func;
        return true;
    }
    return false;
}

function runkit_method_remove (classname, methodname) {
    // !No description available for runkit_method_remove. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_method_remove
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: runkit_method_remove('someClass', 'someMethod');
    // *     returns 1: true

    if (typeof classname === 'string') {
        classname = this.window[classname];
    }
    if (classname.name !== 'PHP_JS' ||  // By default, don't allow overriding of PHP functions
        (this.php_js && this.php_js.ini && this.php_js.ini['runkit.internal_override'] &&
        (this.php_js.ini['runkit.internal_override'].local_value === true ||
            this.php_js.ini['runkit.internal_override'].local_value === 1 ||
            this.php_js.ini['runkit.internal_override'].local_value === '1' ||
            this.php_js.ini['runkit.internal_override'].local_value === 'true'
            )
        )) {
        delete classname.prototype[methodname]; // Delete any on prototype
        return true;
    }
	// delete classname[methodname]; // Delete any as static class method
    return false;
}

function runkit_method_rename (classname, methodname, newname) {
    // !No description available for runkit_method_rename. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_method_rename
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: runkit_method_rename('someClass', 'someMethod', 'newMethod');
    // *     returns 1: true

	if (typeof classname === 'string') {
		classname = this.window[classname];
	}

	/*
	var method = classname[methodname]; // Static
	classname[newname] = method;
	delete classname[methodname];
	*/

    if (classname.name !== 'PHP_JS' ||  // By default, don't allow overriding of PHP functions
        (this.php_js && this.php_js.ini && this.php_js.ini['runkit.internal_override'] &&
        (this.php_js.ini['runkit.internal_override'].local_value === true ||
            this.php_js.ini['runkit.internal_override'].local_value === 1 ||
            this.php_js.ini['runkit.internal_override'].local_value === '1' ||
            this.php_js.ini['runkit.internal_override'].local_value === 'true'
            )
        )) {
        var method = classname.prototype[methodname];
        classname.prototype[newname] = method;
        delete classname.prototype[methodname];
        return true;
    }
    return false;
}

function runkit_superglobals () {
    // !No description available for runkit_superglobals. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/runkit_superglobals
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// %          note 1: You must manually define the superglobals to be able to use them.
	// %          note 2: Another alternative (though you can't reflect on them with this function) is to use import_request_variables()
    // *     example 1: runkit_superglobals();
    // *     returns 1: []

    var superglobal = {}, p='', arr=[];
    var superglobals = ['$_GET', '$_POST', '$_REQUEST', '$_COOKIE', '$_SESSION', '$_SERVER', '$_ENV', '$_FILES'];
    for (var i=0; i < superglobals.length; i++) {
        superglobal = this.window[superglobals[i]];
        for (p in superglobal) {
            arr.push(superglobal[p]);
        }
    }
    return arr;
}

function serialize( mixed_value ) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") {
	    val += ";";
	}
    return val;
}

function set_exception_handler (callback) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: set_exception_handler(function (exceptionObj) {alert(exceptionObj.getMessage());});
	// *     returns 1: null

    var that = this, oldHandlerName = '';
    if (typeof callback === 'string') {
        callback = this.window[callback];
    }
    if (!this.php_js) {this.php_js = {};}
    // For return
    oldHandlerName = this.php_js.exception_handler ? this.php_js.exception_handler.name : null;

    if (this.php_js.exception_handler) { // Fix: Any potential built-in ones (e.g., via ini) to fall back on, as the PHP manual suggests?
        this.php_js.previous_exception_handler = this.php_js.exception_handler; // usable by restore_exception_handler()
    }

    // Set callback
    this.php_js.exception_handler = callback;

    // Make available a global Exception class (see _experimental/language)
    if (!this.window.Exception) {
        this.window.Exception = function (message, code) {
            // These four are supposed to be protected (extendable, but not public)
            this.message = message || '';
            this.code = code || 0; // user defined exception code
            // Fix: Just putting something here for the next two (not PHP-style)... Can over-ride if extending, however;
            //    in Mozilla, error objects (e.g., if you're in a catch block), have these properties which might be used to
            //    add to the object after instantiation (or during instantiation if extending the exception): fileName,
            //    lineNumber, stack
            //  Note that for the trace, however, in Mozilla the stack property is a string, and getTrace() needs the items
            //    parsed as an array; this might be doable by setting the exception object's trace property to
            //    "e.stack.replace(/\n$/, '').split('\n');" if 'e' is a JavaScript exception
            this.file = this.window.href.location; // source filename of exception
            this.line = 0; // source line of exception
            this.string = 'Exception'; // private string; Internal Exception name
            this.name = 'Exception';  // To fit the JavaScript Error interface, user could also add a custom name property.
            that.php_js.exception_handler(this);
        };
        this.window.Exception.prototype = {
            constructor: this.window.Exception,
            // FINAL (not supposed to extend the following 6 methods)
            getMessage : function () { // message of exception
                return this.message;
            },
            getCode : function () { // code of exception
                return this.code;
            },
            getFile : function () { // source filename
                return this.file;
            },
            getLine : function () { // source line
                return this.line;
            },
            getTrace : function () { // an array of the backtrace()
                // Todo: add trace for Mozilla, etc.
                var ret = '';
                for (var i=0; i < this.trace.length; i++) {
                    ret += '\n#'+i+' '+this.trace[i];
                }
                return ret.slice(1);
                // return this.trace; // should be an array (especially so that getTraceAsString() works properly)
            },
            getTraceAsString : function () { // formatted string of trace
                // Todo: add trace for Mozilla, etc.
                return this.trace.toString();
            },
            // Overrideable
            __toString : function () { // formatted string for display
                // PHP-style
                return "exception '"+this.string+"' with message '"+this.getMessage()+"' in "+
                                this.getFile()+":"+this.getLine()+"\nStack trace:\n"+this.getTraceAsString();
                // return this.name+': '+this.message; // this works also, but in JavaScript-style
            },
            // For JavaScript interface/behavior:
            toString : function () {
                return this.__toString(); // We implement on toString() to implement JavaScript Error interface
            },
            // PRIVATE FINAL METHODS
            __clone : function () {
                throw 'Fatal exception: exceptions are not clonable';
            }
        };
    }
    
    return oldHandlerName;
}

function set_time_limit(seconds) {
    // Sets the maximum time a script can run  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/set_time_limit
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: set_time_limit(4);
    // *     returns 1: undefined
    if (!this.php_js) {
        this.php_js = {};
    }

    this.window.setTimeout(function () {
        if (!this.php_js.timeoutStatus) {
            this.php_js.timeoutStatus = true;
        }
        throw 'Maximum execution time exceeded';
    }, seconds*1000);
}

function setcookie(name, value, expires, path, domain, secure) {
    // Send a cookie  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/setcookie
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Andreas
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: setrawcookie
    // *     example 1: setcookie('author_name', 'Kevin van Zonneveld');
    // *     returns 1: true
    return this.setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure);
}

function setlocale (category, locale) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// +   derived from: Blues at http://hacks.bluesmoon.info/strftime/strftime.js
	// +   derived from: YUI Library: http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html
	// -    depends on: getenv
	// %          note 1: Is extensible, but currently only implements locales en,
    // %          note 1: en_US, en_GB, en_AU, fr, and fr_CA for LC_TIME only; C for LC_CTYPE; C and en for LC_MONETARY/LC_NUMERIC
    // %          note 2: Uses global: php_js to store locale info
	// *     example 1: setlocale('LC_ALL', 'en_US');
	// *     returns 1: 'en_US'
	var categ='', cats = [], i = 0, d = this.window.document;

	// BEGIN REDUNDANT
	if (!this.php_js) {this.php_js = {};}
	var phpjs = this.php_js;
	// END REDUNDANT

	// BEGIN STATIC
	var _copy = function _copy (orig) {
		var newObj = {};
		for (var i in orig) {
            if (typeof orig[i] === 'object') {
                newObj[i] = _copy(orig[i]);
            }
            else {
                newObj[i] = orig[i];
            }
		}
		return newObj;
	};

	if (!phpjs.locales) {
		// Can add to the locales
		phpjs.locales = {};

		phpjs.locales.en = {
            'LC_COLLATE' : '', // Need to add something here for strcoll (and modify it too), perhaps a sorter function
            'LC_CTYPE' : { // Need to change any of these for English as opposed to C?
                an: /^[A-Za-z\d]+$/g,
                al: /^[A-Za-z]+$/g,
                ct: /^[\u0000-\u001F\u007F]+$/g,
                dg: /^[\d]+$/g,
                gr: /^[\u0021-\u007E]+$/g,
                lw: /^[a-z]+$/g,
                pr: /^[\u0020-\u007E]+$/g,
                pu: /^[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]+$/g,
                sp: /^[\f\n\r\t\v ]+$/g,
                up: /^[A-Z]+$/g,
                xd: /^[A-Fa-f\d]+$/g,
                CODESET : 'UTF-8',
                 // Used by sql_regcase
                lower : 'abcdefghijklmnopqrstuvwxyz',
                upper : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
            },
            'LC_TIME' : { // Comments include nl_langinfo() constant equivalents and any changes from Blues' implementation
                a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // ABDAY_
                A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // DAY_
                b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // ABMON_
                B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], // MON_
                c: '%a %d %b %Y %r %Z', // D_T_FMT // changed %T to %r per results
                p: ['AM', 'PM'], // AM_STR/PM_STR
                P: ['am', 'pm'], // Not available in nl_langinfo()
                r: '%I:%M:%S %p', // T_FMT_AMPM (Fixed for all locales)
                x: '%m/%d/%Y', // D_FMT // switched order of %m and %d; changed %y to %Y (C uses %y)
                X: '%r', // T_FMT // changed from %T to %r  (%T is default for C, not English US)
                // Following are from nl_langinfo() or http://www.cptec.inpe.br/sx4/sx4man2/g1ab02e/strftime.4.html
                alt_digits : '', // e.g., ordinal
                ERA : '',
                ERA_YEAR : '',
                ERA_D_T_FMT : '',
                ERA_D_FMT : '',
                ERA_T_FMT : ''
            },
             // Assuming distinction between numeric and monetary is thus:
             // See below for C locale
            'LC_MONETARY' : { // Based on Windows "english" (English_United States.1252) locale
                int_curr_symbol : 'USD',
                currency_symbol : '$',
                mon_decimal_point : '.',
                mon_thousands_sep : ',',
                mon_grouping : [3],
                positive_sign : '',
                negative_sign : '-',
                int_frac_digits : 2, // Fractional digits only for money defaults?
                frac_digits : 2,
                p_cs_precedes : 1,
                p_sep_by_space : 0,
                n_cs_precedes : 1,
                n_sep_by_space : 0,
                p_sign_posn : 3,
                n_sign_posn : 0
            },
            'LC_NUMERIC' : { // Based on Windows "english" (English_United States.1252) locale
                decimal_point : '.',
                thousands_sep : ',',
                grouping : [3]
            },
            'LC_MESSAGES' : {
                YESEXPR : '^[yY].*',
                NOEXPR : '^[nN].*',
                YESSTR : '',
                NOSTR : ''
            }
        };
		phpjs.locales.en_US = _copy(phpjs.locales.en);
		phpjs.locales.en_US.LC_TIME.c = '%a %d %b %Y %r %Z';
        phpjs.locales.en_US.LC_TIME.x = '%D';
        phpjs.locales.en_US.LC_TIME.X = '%r';

		phpjs.locales.en_GB = _copy(phpjs.locales.en);
		phpjs.locales.en_GB.LC_TIME.r =  '%l:%M:%S %P %Z';

		phpjs.locales.en_AU = _copy(phpjs.locales.en_GB);
        phpjs.locales.C = _copy(phpjs.locales.en); // Assume C locale is like English (?) (We need C locale for LC_CTYPE)
        phpjs.locales.C.LC_CTYPE.CODESET = 'ANSI_X3.4-1968';
        phpjs.locales.C.LC_MONETARY = {
            int_curr_symbol : '',
            currency_symbol : '',
            mon_decimal_point : '',
            mon_thousands_sep : '',
            mon_grouping : [],
            p_cs_precedes : 127,
            p_sep_by_space : 127,
            n_cs_precedes : 127,
            n_sep_by_space : 127,
            p_sign_posn : 127,
            n_sign_posn : 127,
            positive_sign : '',
            negative_sign : '',
            int_frac_digits : 127,
            frac_digits : 127
        };
        phpjs.locales.C.LC_NUMERIC = {
            decimal_point : '.',
            thousands_sep : '',
            grouping : []
        };
        phpjs.locales.C.LC_TIME.c = '%a %b %e %H:%M:%S %Y'; // D_T_FMT
        phpjs.locales.C.LC_TIME.x = '%m/%d/%y'; // D_FMT
        phpjs.locales.C.LC_TIME.X = '%H:%M:%S'; // T_FMT
        phpjs.locales.C.LC_MESSAGES.YESEXPR = '^[yY]';
        phpjs.locales.C.LC_MESSAGES.NOEXPR = '^[nN]';

		phpjs.locales.fr =_copy(phpjs.locales.en);
		phpjs.locales.fr.LC_TIME.a = ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'];
        phpjs.locales.fr.LC_TIME.A = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'];
        phpjs.locales.fr.LC_TIME.b = ['jan', 'fÃ©v', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoÃ»', 'sep', 'oct', 'nov', 'dÃ©c'];
        phpjs.locales.fr.LC_TIME.B = ['janvier', 'fÃ©vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aoÃ»t', 'septembre', 'octobre', 'novembre', 'dÃ©cembre'];
        phpjs.locales.fr.LC_TIME.c = '%a %d %b %Y %T %Z';
        phpjs.locales.fr.LC_TIME.p = ['', ''];
        phpjs.locales.fr.LC_TIME.P = ['', ''];
        phpjs.locales.fr.LC_TIME.x = '%d.%m.%Y';
        phpjs.locales.fr.LC_TIME.X = '%T';

		phpjs.locales.fr_CA = _copy(phpjs.locales.fr);
		phpjs.locales.fr_CA.LC_TIME.x = '%Y-%m-%d';

	}
	if (!phpjs.locale) {
		phpjs.locale = 'en_US';
		var NS_XHTML = 'http://www.w3.org/1999/xhtml';
		var NS_XML = 'http://www.w3.org/XML/1998/namespace';
		if (d.getElementsByTagNameNS &&
				d.getElementsByTagNameNS(NS_XHTML, 'html')[0]) {
			if (d.getElementsByTagNameNS(NS_XHTML, 'html')[0].getAttributeNS &&
					d.getElementsByTagNameNS(NS_XHTML, 'html')[0].getAttributeNS(NS_XML, 'lang')) {
				phpjs.locale = d.getElementsByTagName(NS_XHTML, 'html')[0].getAttributeNS(NS_XML, 'lang');
			} else if(d.getElementsByTagNameNS(NS_XHTML, 'html')[0].lang) { // XHTML 1.0 only
				phpjs.locale = d.getElementsByTagNameNS(NS_XHTML, 'html')[0].lang;
			}
		} else if(d.getElementsByTagName('html')[0] && d.getElementsByTagName('html')[0].lang) {
			phpjs.locale = d.getElementsByTagName('html')[0].lang;
		}
	}
    phpjs.locale = phpjs.locale.replace('-', '_'); // PHP-style

	// Fix locale if declared locale hasn't been defined
	if(!(phpjs.locale in phpjs.locales)) {
		if(phpjs.locale.replace(/_[a-zA-Z]+$/, '') in phpjs.locales) {
			phpjs.locale = phpjs.locale.replace(/_[a-zA-Z]+$/, '');
		}
	}

	if (!phpjs.localeCategories) {
		phpjs.localeCategories = {
			'LC_COLLATE': phpjs.locale, // for string comparison, see strcoll()
			'LC_CTYPE': phpjs.locale,// for character classification and conversion, for example strtoupper()
			'LC_MONETARY': phpjs.locale,// for localeconv()
			'LC_NUMERIC': phpjs.locale,// for decimal separator (See also localeconv())
			'LC_TIME': phpjs.locale,// for date and time formatting with strftime()
			'LC_MESSAGES':phpjs.locale// for system responses (available if PHP was compiled with libintl)
		};
	}
	// END STATIC

	if (locale === null || locale === '') {
		locale = this.getenv(category) || this.getenv('LANG');
	} else if (locale instanceof Array) {
		for (i=0; i < locale.length; i++) {
			if (!(locale[i] in this.php_js.locales)) {
				if (i === locale.length-1) {
					return false; // none found
				}
				continue;
			}
			locale = locale[i];
			break;
		}
	}

	// Just get the locale
	if (locale === '0' || locale === 0) {
		if (category === 'LC_ALL') {
			for (categ in this.php_js.localeCategories) {
				cats.push(categ+'='+this.php_js.localeCategories[categ]);
			}
			return cats.join(';');
		}
		return this.php_js.localeCategories[category];
	}

	if (!(locale in this.php_js.locales)) {
		return false; // Locale not found
	}

	// Set and get locale
	if (category === 'LC_ALL') {
		for (categ in this.php_js.localeCategories) {
			this.php_js.localeCategories[categ] = locale;
		}
	} else {
		this.php_js.localeCategories[category] = locale;
	}
	return locale;
}

function setrawcookie(name, value, expires, path, domain, secure) {
    // Send a cookie with no url encoding of the value  
    // 
    // version: 905.2214
    // discuss at: http://phpjs.org/functions/setrawcookie
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   derived from: setcookie
    // *     example 1: setcookie('author_name', 'Kevin van Zonneveld');
    // *     returns 1: true
    if (expires instanceof Date) {
        expires = expires.toGMTString();
    } else if(typeof(expires) == 'number') {
        expires = (new Date(+(new Date()) + expires * 1e3)).toGMTString();
    }

    var r = [name + "=" + value], s={}, i='';
    s = {expires: expires, path: path, domain: domain};
    for(i in s){
        s[i] && r.push(i + "=" + s[i]);
    }
    
    return secure && r.push("secure"), this.window.document.cookie = r.join(";"), true;
}

function settype (vr, type) {
   // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Credits to Crockford also
    // %        note 2: only works on global variables, and "vr" must be passed in as a string
    // *     example 1: foo = '5bar';
    // *     example 1: settype(foo, 'integer');
    // *     results 1: foo == 5
    // *     returns 1: true
    // *     example 2: foo = true;
    // *     example 2: settype(foo, 'string');
    // *     results 2: foo == '1'
    // *     returns 2: true
    var is_array = function (arr) {
        return typeof arr === 'object' && typeof arr.length === 'number' &&
                    !(arr.propertyIsEnumerable('length')) &&
                    typeof arr.splice === 'function';
    };
    var v, mtch, i, obj;
    v = this[vr] ? this[vr] : vr;
    
    try {
        switch(type) {
            case 'boolean':
                if (is_array(v) && v.length === 0) {this[vr]=false;}
                else if (v === '0') {this[vr]=false;}
                else if (typeof v === 'object' && !is_array(v)) {
                    var lgth = false;
                    for (i in v) {
                        lgth = true;
                    }
                    this[vr]=lgth;
                }
                else {this[vr] = !!v;}
                break;
            case 'integer':
                if (typeof v === 'number') {this[vr]=parseInt(v, 10);}
                else if (typeof v === 'string') {
                    mtch = v.match(/^([+\-]?)(\d+)/);
                    if (!mtch) {this[vr]=0;}
                    else {this[vr]=parseInt(v, 10);}
                }
                else if (v === true) {this[vr]=1;}
                else if (v === false || v === null) {this[vr]=0;}
                else if (is_array(v) && v.length === 0) {this[vr]=0;}
                else if (typeof v === 'object') {this[vr]=1;}

                break;
            case 'float':
                if (typeof v === 'string') {
                    mtch = v.match(/^([+\-]?)(\d+(\.\d+)?|\.\d+)([eE][+\-]?\d+)?/);
                    if (!mtch) {this[vr]=0;}
                    else {this[vr]=parseFloat(v, 10);}
                }
                else if (v === true) {this[vr]=1;}
                else if (v === false || v === null) {this[vr]=0;}
                else if (is_array(v) && v.length === 0) {this[vr]=0;}
                else if (typeof v === 'object') {this[vr]=1;}
                break;
            case 'string':
                if (v === null || v === false) {this[vr]='';}
                else if (is_array(v)) {this[vr]='Array';}
                else if (typeof v === 'object') {this[vr]='Object';}
                else if (v === true) {this[vr]='1';}
                else {this[vr] += '';} // numbers (and functions?)
                break;
            case 'array':
                if (v === null) {this[vr] = [];}
                else if (typeof v !== 'object') {this[vr] = [v];}
                break;
            case 'object':
                if (v === null) {this[vr]={};}
                else if (is_array(v)) {
                    for (i = 0, obj={}; i < v.length; i++) {
                        obj[i] = v;
                    }
                    this[vr] = obj;
                }
                else if (typeof v !== 'object') {this[vr]={scalar:v};}
                break;
            case 'null':
                delete this[vr];
                break;
        }
        return true;
    } catch (e) {
        return false;
    }
}

function sha1 ( str ) {
    // Calculate the sha1 hash of a string  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/sha1
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: sha1('Kevin van Zonneveld');
    // *     returns 1: '54916d2e62f65b3afa6e192e6a601cdbe5cb5897'
    var rotate_left = function(n,s) {
        var t4 = ( n<<s ) | (n>>>(32-s));
        return t4;
    };

    /*var lsb_hex = function(val) { // Not in use; needed?
        var str="";
        var i;
        var vh;
        var vl;

        for( i=0; i<=6; i+=2 ) {
            vh = (val>>>(i*4+4))&0x0f;
            vl = (val>>>(i*4))&0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };*/

    var cvt_hex = function(val) {
        var str="";
        var i;
        var v;

        for( i=7; i>=0; i-- ) {
            v = (val>>>(i*4))&0x0f;
            str += v.toString(16);
        }
        return str;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    str = this.utf8_encode(str);
    var str_len = str.length;

    var word_array = [];
    for( i=0; i<str_len-3; i+=4 ) {
        j = str.charCodeAt(i)<<24 | str.charCodeAt(i+1)<<16 |
        str.charCodeAt(i+2)<<8 | str.charCodeAt(i+3);
        word_array.push( j );
    }

    switch( str_len % 4 ) {
        case 0:
            i = 0x080000000;
        break;
        case 1:
            i = str.charCodeAt(str_len-1)<<24 | 0x0800000;
        break;
        case 2:
            i = str.charCodeAt(str_len-2)<<24 | str.charCodeAt(str_len-1)<<16 | 0x08000;
        break;
        case 3:
            i = str.charCodeAt(str_len-3)<<24 | str.charCodeAt(str_len-2)<<16 | str.charCodeAt(str_len-1)<<8    | 0x80;
        break;
    }

    word_array.push( i );

    while( (word_array.length % 16) != 14 ) {word_array.push( 0 );}

    word_array.push( str_len>>>29 );
    word_array.push( (str_len<<3)&0x0ffffffff );

    for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
        for( i=0; i<16; i++ ) {W[i] = word_array[blockstart+i];}
        for( i=16; i<=79; i++ ) {W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);}


        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for( i= 0; i<=19; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=20; i<=39; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=40; i<=59; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=60; i<=79; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;
    }

    temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
    return temp.toLowerCase();
}

function sha1_file ( str_filename ) {
    // Calculate the sha1 hash of given filename  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/sha1_file
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: file_get_contents
    // -    depends on: sha1
    // *     example 1: sha1_file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '40bd001563085fc35165329ea1ff5c5ecbdbbeef'
    var buf = this.file_get_contents(str_filename);
    return this.sha1(buf);
}

function shuffle( inputArr ) {
    // Randomly shuffle the contents of an array  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/shuffle
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: shuffle({5:'a', 2:'3', 3:'c', 4:5, 'q':5});
    // *     returns 1: true
    var valArr = [];
    var k = '', i = 0;

    for (k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k];
    }
    valArr.sort(function() {return 0.5 - Math.random();});

    for (i = 0; i < valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }
    
    return true;
}

function sin(arg) {
    // Returns the sine of the number in radians  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/sin
    // +   original by: Onno Marsman
    // *     example 1: sin(8723321.4);
    // *     returns 1: -0.9834330348825909
    return Math.sin(arg);
}

function sinh(arg) {
    // Returns the hyperbolic sine of the number, defined as (exp(number) - exp(-number))/2  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/sinh
    // +   original by: Onno Marsman
    // *     example 1: sinh(-0.9834330348825909);
    // *     returns 1: -1.1497971402636502
    return (Math.exp(arg) - Math.exp(-arg))/2;
}

function sizeof ( mixed_var, mode ) {
    // !No description available for sizeof. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/sizeof
    // +   original by: Philip Peterson
    // -    depends on: count
    // *     example 1: sizeof([[0,0],[0,-4]], 'COUNT_RECURSIVE');
    // *     returns 1: 6
    // *     example 2: sizeof({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
    // *     returns 2: 6
 
    return this.count( mixed_var, mode );
}

function sleep(seconds) {
    // Delay for a given number of seconds  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/sleep
    // +   original by: Christian Doebler
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note: For study purposes. Current implementation could lock up the user's browser. 
    // %          note: Consider using setTimeout() instead.
    // *     example 1: sleep(1);
    // *     returns 1: 0
    
    var start = new Date().getTime();
    while (new Date() < start + seconds*1000) {}
    return 0;
}

function sort (inputArr, sort_flags) {
    // Sort an array  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/sort
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: SORT_STRING (as well as natsort and natcasesort) might also be
    // %        note 1: integrated into all of these functions by adapting the code at
    // %        note 1: http://sourcefrog.net/projects/natsort/natcompare.js
    // *     example 1: sort(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: sort(fruits);
    // *     returns 2: true
    // *     results 2: fruits == {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'orange'}
    var valArr = [], keyArr=[];
    var k = '', i = 0, sorter = false, that = this;
    
    for (k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k];
    }

    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(a.localeCompare(b));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
                return 0;
            };
            break;
    }
    valArr.sort(sorter);

    for (i = 0; i < valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }
    return true;
}

function soundex(str) {
    // Calculate the soundex key of a string  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/soundex
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: soundex('Kevin');
    // *     returns 1: 'K150'
    // *     example 2: soundex('Ellery');
    // *     returns 2: 'E460'
    // *     example 3: soundex('Euler');
    // *     returns 3: 'E460'
    var s = '';
    var i, j, l, p = isNaN(p) ? 4 : p > 10 ? 10 : p < 4 ? 4 : p;
    var m = {
        BFPV: 1,
        CGJKQSXZ: 2,
        DT: 3,
        L: 4,
        MN: 5, 
        R: 6
    };
    var r = (s = (str+'').toUpperCase().replace(/[^A-Z]/g, "").split("")).splice(0, 1);
    var sl = 0;

    sl = s.length;
    for (i = -1, l = sl; ++i < l;) {
        for (j in m) {
            if (j.indexOf(s[i]) + 1 && r[r.length-1] != m[j] && r.push(m[j])) {
                break;
            }
        }
    }

    return r.length > p && (r.length = p), r.join("") + (new Array(p - r.length + 1)).join("0");
}

function split( delimiter, string ) {
    // Split string into array by regular expression  
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/split
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: explode
    // *     example 1: split(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    return this.explode( delimiter, string );
}

function sprintf( ) {
    // Return a formatted string  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/sprintf
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];

    // pad()
    var pad = function(str, len, chr, leftJustify) {
        if (!chr) {chr = ' ';}
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };

    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };

    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };

    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };

    // doFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        var number;
        var prefix;
        var method;
        var textTransform;
        var value;

        if (substring == '%%') {return '%';}

        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) {
            switch (flags.charAt(j)) {
                case ' ': positivePrefix = ' '; break;
                case '+': positivePrefix = '+'; break;
                case '-': leftJustify = true; break;
                case "'": customPadChar = flags.charAt(j+1); break;
                case '0': zeroPad = true; break;
                case '#': prefixBaseX = true; break;
            }
        }

        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }

        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }

        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }

        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }

        // grab value using valueIndex if required?
        value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd':
                number = parseInt(+value, 10);
                prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                number = +value;
                prefix = number < 0 ? '-' : positivePrefix;
                method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            default: return substring;
        }
    };

    return format.replace(regex, doFormat);
}

function sql_regcase (str) {
	// http://kevin.vanzonneveld.net
	// +   original by: Brett Zamir (http://brettz9.blogspot.com)
	// -    depends on: setlocale
	// *     example 1: sql_regcase('Foo - bar.');
	// *     returns 1: '[Ff][Oo][Oo] - [Bb][Aa][Rr].'

    this.setlocale('LC_ALL', 0);
    var i=0, upper = '', lower='', pos=0, retStr='';

    upper = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.upper;
    lower = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lower;

    for (i=0; i < str.length; i++) {
        if (((pos = upper.indexOf(str.charAt(i))) !== -1) || ((pos = lower.indexOf(str.charAt(i))) !== -1)) {
            retStr += '['+upper[pos]+lower[pos]+']';
        }
        else {
            retStr += str.charAt(i);
        }
    }
    return retStr;
}

function sqrt(arg) {
    // Returns the square root of the number  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/sqrt
    // +   original by: Onno Marsman
    // *     example 1: sqrt(8723321.4);
    // *     returns 1: 2953.5269424875746
    
    return Math.sqrt(arg);
}

function str_getcsv ( input, delimiter, enclosure, escape ) {
    // Parse a CSV string into an array  
    // 
    // version: 904.610
    // discuss at: http://phpjs.org/functions/str_getcsv
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: str_getcsv('"abc", "def", "ghi"');
    // *     returns 1: ['abc', 'def', 'ghi']
    var output = [];
    var backwards = function (str) { // We need to go backwards to simulate negative look-behind (don't split on 
                                                              //an escaped enclosure even if followed by the delimiter and another enclosure mark)
        return str.split('').reverse().join('');
    };
    var pq = function (str) { // preg_quote()
        return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
    };

    delimiter = delimiter || ',';
    enclosure = enclosure || '"';
    escape = escape || '\\';

    input = input.replace(new RegExp('^\\s*'+pq(enclosure)), '').replace(new RegExp(pq(enclosure)+'\\s*$'), '');

    // PHP behavior may differ by including whitespace even outside of the enclosure
    input = backwards(input).split(new RegExp(pq(enclosure)+'\\s*'+pq(delimiter)+'\\s*'+pq(enclosure)+'(?!'+pq(escape)+')', 'g')).reverse();

    for (var i = 0; i < input.length; i++) {
        output.push(backwards(input[i]).replace(new RegExp(pq(escape)+pq(enclosure), 'g'), enclosure));
    }

    return output;
}

function str_ireplace ( search, replace, subject ) {
    // Replaces all occurrences of search in haystack with replace / case-insensitive  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/str_ireplace
    // +   original by: Martijn Wieringa
    // +      input by: penutbutterjelly
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Jack
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: str_ireplace('l', 'l', 'HeLLo');
    // *     returns 1: 'Hello'
    var i, k = '';
    var searchl = 0;
    var reg;

    search += '';
    searchl = search.length;
    if (!(replace instanceof Array)) {
        replace = new Array(replace);
        if (search instanceof Array) {
            // If search is an array and replace is a string,
            // then this replacement string is used for every value of search
            while (searchl > replace.length) {
                replace[replace.length] = replace[0];
            }
        }
    }

    if (!(search instanceof Array)) {
        search = new Array(search);
    }
    while (search.length>replace.length) {
        // If replace has fewer values than search,
        // then an empty string is used for the rest of replacement values
        replace[replace.length] = '';
    }

    if (subject instanceof Array) {
        // If subject is an array, then the search and replace is performed
        // with every entry of subject , and the return value is an array as well.
        for (k in subject) {
            subject[k] = str_ireplace(search, replace, subject[k]);
        }
        return subject;
    }

    searchl = search.length;
    for (i = 0; i < searchl; i++) {
        reg = new RegExp(search[i], 'gi');
        subject = subject.replace(reg, replace[i]);
    }

    return subject;
}

function str_pad( input, pad_length, pad_string, pad_type ) {
    // Returns input string padded on the left or right to specified length with pad_string  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/str_pad
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'
    var half = '', pad_to_go;

    var str_pad_repeater = function(s, len) {
        var collect = '', i;

        while(collect.length < len) {collect += s;}
        collect = collect.substr(0,len);

        return collect;
    };

    input += '';

    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }

    return input;
}

function str_repeat ( input, multiplier ) {
    // Returns the input string repeat mult times  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/str_repeat
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *     example 1: str_repeat('-=', 10);
    // *     returns 1: '-=-=-=-=-=-=-=-=-=-='
    
    
    return new Array(multiplier+1).join(input); 
}

function str_replace(search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 905.1721
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Oleg Eremeev
	// %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function str_rot13( str ) {
    // Perform the rot13 transform on a string  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/str_rot13
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   bugfixed by: Onno Marsman
    // *     example 1: str_rot13('Kevin van Zonneveld');
    // *     returns 1: 'Xriva ina Mbaariryq'
    // *     example 2: str_rot13('Xriva ina Mbaariryq');
    // *     returns 2: 'Kevin van Zonneveld'
    return (str+'').replace(/[A-Za-z]/g, function (c) {
        return String.fromCharCode((((c = c.charCodeAt(0)) & 223) - 52) % 26 + (c & 32) + 65);
    });
}

function str_shuffle (str) {
    // Shuffles string. One permutation of all possible is created  
    // 
    // version: 905.2614
    // discuss at: http://phpjs.org/functions/str_shuffle
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: shuffled = str_shuffle("abcdef");
    // *     results 1: shuffled.length == 6
    
    if (str == undefined) {
        throw 'Wrong parameter count for str_shuffle()';
    }
    
    var getRandomInt = function (max) {
        return Math.floor(Math.random() * (max + 1));
    };
    var newStr = '', rand = 0;
    
    while (str.length) {
        rand = getRandomInt(str.length-1);
        newStr += str.charAt(rand);
        str = str.substring(0, rand)+str.substr(rand+1);
    }
    
    return newStr;
}

function str_split ( f_string, f_split_length){
    // Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long.  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/str_split
    // +     original by: Martijn Wieringa
    // +     improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +     bugfixed by: Onno Marsman
    // *         example 1: str_split('Hello Friend', 3);
    // *         returns 1: ['Hel', 'lo ', 'Fri', 'end']
    f_string += '';

    if (f_split_length == undefined) {
        f_split_length = 1;
    }
    if(f_split_length > 0){
        var result = [];
        while(f_string.length > f_split_length) {
            result[result.length] = f_string.substring(0, f_split_length);
            f_string = f_string.substring(f_split_length);
        }
        result[result.length] = f_string;
        return result;
    }
    return false;
}

function str_word_count(str, format, charlist) {
    // Counts the number of words inside a string. If format of 1 is specified,     then the function will return an array containing all the words     found inside the string. If format of 2 is specified, then the function     will return an associated array where the position of the word is the key     and the word itself is the value.      For the purpose of this function, 'word' is defined as a locale dependent     string containing alphabetic characters, which also may contain, but not start     with "'" and "-" characters.  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/str_word_count
    // +   original by: Ole Vrijenhoek
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %          note 1: Original author stated that "charlist parameter works correct but the last word in the given string will not be counted", but seems to work
    // *     example 1: str_word_count('Hello fri3nd, youre   looking          good today!', 1, 'àáãç3');
    // *     returns 1: ['Hello', 'fri3nd', 'youre', 'looking', 'good', 'today']
    // A word is valid when it contains a-z A-Z ' -
    // Ole Vrijenhoek
    var l = str.length; var tmpStr = "";
    var i = 0;
    var c = '';
    var wArr = [], wC = 0;
    var assArr = {}, aC = 0, reg = "";
    
    if (charlist) {
        for(i = 0; i<=charlist.length - 1; i++) {
            if (i != charlist.length - 1) {
                reg = reg + charlist.charCodeAt(i) + "|";
            } else {
                reg = reg + charlist.charCodeAt(i);
            }
        }
        reg = new RegExp(reg);
    }

    for (i = 0; i <= l-1; i++) {
        c = str.charCodeAt(i);
        if ((c<91&&c>64)||(c<123&&c>96)||c == 45||c == 39||(reg && reg.test(c))) {
            if(tmpStr == "" && format == 2) {
                aC = i;
            }
            tmpStr = tmpStr + String.fromCharCode(c);
        } else {
            if(tmpStr != "") {
                if (format != 2) {
                    wArr[wArr.length] = tmpStr;
                } else {
                    assArr[aC] = tmpStr;
                }
                tmpStr = "";
                wC++;
            }
        }
    }
    
    if (!format) {
        return wC;
    } else if (format == 1) {
        return wArr;
    } else if (format == 2) {
        return assArr;
    }
    throw 'You have supplied an incorrect format';
}

function strcasecmp (f_string1, f_string2){
    // Binary safe case-insensitive string comparison  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/strcasecmp
    // +     original by: Martijn Wieringa
    // +     bugfixed by: Onno Marsman
    // *         example 1: strcasecmp('Hello', 'hello');
    // *         returns 1: 0
    var string1 = (f_string1+'').toLowerCase();
    var string2 = (f_string2+'').toLowerCase();

    if(string1 > string2) {
      return 1;
    }
    else if(string1 == string2) {
      return 0;
    }

    return -1;
}

function strchr ( haystack, needle, bool ) {
    // An alias for strstr  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/strchr
    // +   original by: Philip Peterson
    // -    depends on: strstr
    // *     example 1: strchr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: strchr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
 
    return this.strstr( haystack, needle, bool );
}

function strcmp ( str1, str2 ) {
    // Binary safe string comparison  
    // 
    // version: 812.316
    // discuss at: http://phpjs.org/functions/strcmp
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1
    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}

function strcoll (str1, str2) {
    // Compares two strings using the current locale  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/strcoll
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: strcoll('a', 'b');
    // *     returns 1: -1
	
	// We might modify this to work with setlocale() locales instead of JS's own (and same with sort(), etc.)
    return str1.localeCompare(str2);
}

function strcspn (str, mask, start, length) {
    // Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars)  
    // 
    // version: 905.2614
    // discuss at: http://phpjs.org/functions/strcspn
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: strcspn('abcdefg123', '1234567890');
    // *     returns 1: 7
    // *     example 2: strcspn('123abc', '1234567890');
    // *     returns 2: 3
    start = start ? start : 0;
    var count = (length && ((start + length) < str.length)) ? start + length : str.length;
    strct:
    for (var i=start, lgth=0; i < count; i++) {
        for (var j=0; j < mask.length; j++) {
            if (str.charAt(i).indexOf(mask[j]) !== -1) {
                continue strct;
            }
        }
        ++lgth;
    }
    
    return lgth;
}

function strftime (fmt, timestamp) {
    // Format a local time/date according to locale settings  
    // 
    // version: 905.1002
    // discuss at: http://phpjs.org/functions/strftime
    // +      original by: Blues (http://tech.bluesmoon.info/)
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // -       depends on: setlocale
    // %        note 1: Uses global: php_js to store locale info
    // *        example 1: strftime("%A", 1062462400); // Return value will depend on date and locale
    // *        returns 1: 'Tuesday'
    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    var phpjs = this.php_js;
    // END REDUNDANT

    // BEGIN STATIC
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    var _xPad = function (x, pad, r) {
        if (typeof r === 'undefined') {
            r=10;
        }
        for( ; parseInt(x, 10)<r && r>1; r/=10) {
            x = pad.toString() + x;
        }
        return x.toString();
    };

    var locale = phpjs.localeCategories.LC_TIME;
    var locales = phpjs.locales;

    var _formats = {
        a: function(d) {
            return locales[locale].LC_TIME.a[d.getDay()];
        },
        A: function(d) {
            return locales[locale].LC_TIME.A[d.getDay()];
        },
        b: function(d) {
            return locales[locale].LC_TIME.b[d.getMonth()];
        },
        B: function(d) {
            return locales[locale].LC_TIME.B[d.getMonth()];
        },
        C: function(d) {
            return _xPad(parseInt(d.getFullYear()/100, 10), 0);
        },
        d: ['getDate', '0'],
        e: ['getDate', ' '],
        g: function(d) {
            return _xPad(parseInt(this.G(d)/100, 10), 0);
        },
        G: function(d) {
            var y = d.getFullYear();
            var V = parseInt(_formats.V(d), 10);
            var W = parseInt(_formats.W(d), 10);

            if(W > V) {
                y++;
            }
            else if(W===0 && V>=52) {
                y--;
            }

            return y;
        },
        H: ['getHours', '0'],
        I: function(d) {
            var I=d.getHours()%12; return _xPad(I===0?12:I, 0);
        },
        j: function(d) {
            var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT');
            ms += d.getTimezoneOffset()*60000;
            var doy = parseInt(ms/60000/60/24, 10)+1;
            return _xPad(doy, 0, 100);
        },
        l: function (d) {
            var l=d.getHours()%12; return _xPad(l===0?12:l, ' ');
        },
        m: function(d) {
            return _xPad(d.getMonth()+1, 0);
        },
        M: ['getMinutes', '0'],
        p: function(d) {
            return locales[locale].LC_TIME.p[d.getHours() >= 12 ? 1 : 0 ];
        },
        P: function(d) {
            return locales[locale].LC_TIME.P[d.getHours() >= 12 ? 1 : 0 ];
        },
        s: function(d) {
            return Date.parse(d)/1000;
        },
        S: ['getSeconds', '0'],
        u: function(d) {
            var dow = d.getDay(); return ( (dow===0) ? 7 : dow );
        },
        U: function(d) {
            var doy = parseInt(_formats.j(d), 10);
            var rdow = 6-d.getDay();
            var woy = parseInt((doy+rdow)/7, 10);
            return _xPad(woy, 0);
        },
        V: function(d) {
            var woy = parseInt(_formats.W(d), 10);
            var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
            // First week is 01 and not 00 as in the case of %U and %W,
            // so we add 1 to the final result except if day 1 of the year
            // is a Monday (then %W returns 01).
            // We also need to subtract 1 if the day 1 of the year is
            // Friday-Sunday, so the resulting equation becomes:
            var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
            if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4) {
                idow = 1;
            }
            else if(idow === 0) {
                idow = _formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
            }
            return _xPad(idow, 0);
        },
        w: 'getDay',
        W: function(d) {
            var doy = parseInt(_formats.j(d), 10);
            var rdow = 7-_formats.u(d);
            var woy = parseInt((doy+rdow)/7, 10);
            return _xPad(woy, 0, 10);
        },
        y: function(d) {
            return _xPad(d.getFullYear()%100, 0);
        },
        Y: 'getFullYear',
        z: function(d) {
            var o = d.getTimezoneOffset();
            var H = _xPad(parseInt(Math.abs(o/60), 10), 0);
            var M = _xPad(o%60, 0);
            return (o>0?'-':'+') + H + M;
        },
        Z: function(d) {
            return d.toString().replace(/^.*\(([^)]+)\)$/, '$1');
        },
        '%': function(d) {
            return '%';
        }
    };
    // END STATIC


    var _date = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp)); // Date() object

    var _aggregates = {
        c: 'locale',
        D: '%m/%d/%y',
        F: '%y-%m-%d',
        h: '%b',
        n: '\n',
        r: 'locale',
        R: '%H:%M',
        t: '\t',
        T: '%H:%M:%S',
        x: 'locale',
        X: 'locale',
        z: _formats.z(_date),
        Z: _formats.Z(_date)
    };


    // First replace aggregates
    while (fmt.match(/%[cDFhnrRtTxXzZ]/)) {
        fmt = fmt.replace(/%([cDFhnrRtTxXzZ])/g, function(m0, m1)
        {
            var f = _aggregates[m1];
            return (f === 'locale' ? locales[locale].LC_TIME[m1] : f);
        });
    }

    // Now replace formats - we need a closure so that the date object gets passed through
    var str = fmt.replace(/%([aAbBCdegGHIjlmMpPsSuUVwWyY%])/g, function(m0, m1) {
        var f = _formats[m1];
        if (typeof f === 'string') {
            return _date[f]();
        } else if (typeof f === 'function') {
            return f(_date);
        } else if (typeof f === 'object' && typeof (f[0]) === 'string') {
            return _xPad(_date[f[0]](), f[1]);
        } else { // Shouldn't reach here
            return m1;
        }
    });
    return str;
}

function strip_tags(str, allowed_tags) {
    // Strips HTML and PHP tags from a string  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/strip_tags
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';

    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
	
    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}

function stripos ( f_haystack, f_needle, f_offset ){
    // Finds position of first occurrence of a string within another, case insensitive  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/stripos
    // +     original by: Martijn Wieringa
    // +      revised by: Onno Marsman
    // *         example 1: stripos('ABC', 'a');
    // *         returns 1: 0
    var haystack = (f_haystack+'').toLowerCase();
    var needle = (f_needle+'').toLowerCase();
    var index = 0;
 
    if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
        return index;
    }
    return false;
}

function stripslashes( str ) {
    // Strips backslashes from a string  
    // 
    // version: 812.1714
    // discuss at: http://phpjs.org/functions/stripslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}

function stristr( haystack, needle, bool ) {
    // Finds first occurrence of a string within another, case insensitive  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/stristr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfxied by: Onno Marsman
    // *     example 1: stristr('Kevin van Zonneveld', 'Van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);
    // *     returns 2: 'Kevin '
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

function strlen (string) {
    // Get string length  
    // 
    // version: 905.2614
    // discuss at: http://phpjs.org/functions/strlen
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // +      input by: Kirk Strobeck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +    revised by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: May look like overkill, but in order to be truly faithful to handling all Unicode
    // %        note 1: characters and to this function in PHP which does not count the number of bytes
    // %        note 1: but counts the number of characters, something like this is really necessary.
    // *     example 1: strlen('Kevin van Zonneveld');
    // *     returns 1: 19
    // *     example 2: strlen('A\ud87e\udc04Z');
    // *     returns 2: 3
    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate(could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

function strnatcasecmp(str1, str2) {
    // Returns the result of case-insensitive string comparison using 'natural' algorithm  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/strnatcasecmp
    // +      original by: Martin Pool
    // + reimplemented by: Pierre-Luc Paour
    // + reimplemented by: Kristof Coomans (SCK-CEN (Belgian Nucleair Research Centre))
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // +      bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strnatcasecmp(10, 1);
    // *     returns 1: 1
    // *     example 1: strnatcasecmp('1', '10');
    // *     returns 1: -1
    var a = (str1+'').toLowerCase();
    var b = (str2+'').toLowerCase();

    var isWhitespaceChar = function(a) {
        return a.charCodeAt(0) <= 32;
    };

    var isDigitChar = function (a) {
        var charCode = a.charCodeAt(0);
        return ( charCode >= 48  && charCode <= 57 );
    };

    var compareRight = function(a,b) {
        var bias = 0;
        var ia = 0;
        var ib = 0;

        var ca;
        var cb;

        // The longest run of digits wins.  That aside, the greatest
        // value wins, but we can't know that it will until we've scanned
        // both numbers to know that they have the same magnitude, so we
        // remember it in BIAS.
        for (;; ia++, ib++) {
            ca = a.charAt(ia);
            cb = b.charAt(ib);

            if (!isDigitChar(ca) &&
                !isDigitChar(cb)) {
                return bias;
            } else if (!isDigitChar(ca)) {
                return -1;
            } else if (!isDigitChar(cb)) {
                return +1;
            } else if (ca < cb) {
                if (bias == 0) {
                    bias = -1;
                }
            } else if (ca > cb) {
                if (bias == 0) {
                    bias = +1;
                }
            } else if (ca == 0 && cb == 0) {
                return bias;
            }
        }
    };

    var ia = 0, ib = 0;
    var nza = 0, nzb = 0;
    var ca, cb;
    var result;

    while (true) {
        // only count the number of zeroes leading the last number compared
        nza = nzb = 0;

        ca = a.charAt(ia);
        cb = b.charAt(ib);

        // skip over leading spaces or zeros
        while ( isWhitespaceChar( ca ) || ca =='0' ) {
            if (ca == '0') {
                nza++;
            } else {
                // only count consecutive zeroes
                nza = 0;
            }

            ca = a.charAt(++ia);
        }

        while ( isWhitespaceChar( cb ) || cb == '0') {
            if (cb == '0') {
                nzb++;
            } else {
                // only count consecutive zeroes
                nzb = 0;
            }

            cb = b.charAt(++ib);
        }

        // process run of digits
        if (isDigitChar(ca) && isDigitChar(cb)) {
            if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0) {
                return result;
            }
        }

        if (ca == 0 && cb == 0) {
            // The strings compare the same.  Perhaps the caller
            // will want to call strcmp to break the tie.
            return nza - nzb;
        }

        if (ca < cb) {
            return -1;
        } else if (ca > cb) {
            return +1;
        }

        ++ia; ++ib;
    }
}

function strnatcmp ( f_string1, f_string2, f_version ) {
    // Returns the result of string comparison using 'natural' algorithm  
    // 
    // version: 905.2617
    // discuss at: http://phpjs.org/functions/strnatcmp
    // +   original by: Martijn Wieringa
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // -    depends on: strcmp
    // %          note: Added f_version argument against code guidelines, because it's so neat
    // *     example 1: strnatcmp('Price 12.9', 'Price 12.15');
    // *     returns 1: 1
    // *     example 2: strnatcmp('Price 12.09', 'Price 12.15');
    // *     returns 2: -1
    // *     example 3: strnatcmp('Price 12.90', 'Price 12.15');
    // *     returns 3: 1
    // *     example 4: strnatcmp('Version 12.9', 'Version 12.15', true);
    // *     returns 4: -6
    // *     example 5: strnatcmp('Version 12.15', 'Version 12.9', true);
    // *     returns 5: 6
    var i = 0;

    if (f_version == undefined) {
        f_version = false;
    }

    var __strnatcmp_split = function( f_string ) {
        var result = [];
        var buffer = '';
        var chr = '';
        var i = 0, f_stringl = 0;

        var text = true;

        f_stringl = f_string.length;
        for (i = 0; i < f_stringl; i++) {
            chr = f_string.substring(i, i + 1);
            if (chr.match(/[0-9]/)) {
                if (text) {
                    if(buffer.length > 0){
                        result[result.length] = buffer;
                        buffer = '';
                    }

                    text = false;
                }
                buffer += chr;
            } else if ((text == false) && (chr == '.') && (i < (f_string.length - 1)) && (f_string.substring(i + 1, i + 2).match(/[0-9]/))) {
                result[result.length] = buffer;
                buffer = '';
            } else {
                if (text == false) {
                    if (buffer.length > 0) {
                        result[result.length] = parseInt(buffer, 10);
                        buffer = '';
                    }
                    text = true;
                }
                buffer += chr;
            }
        }

        if (buffer.length > 0) {
            if (text) {
                result[result.length] = buffer;
            } else {
                result[result.length] = parseInt(buffer, 10);
            }
        }

        return result;
    };

    var array1 = __strnatcmp_split(f_string1+'');
    var array2 = __strnatcmp_split(f_string2+'');

    var len = array1.length;
    var text = true;

    var result = -1;
    var r = 0;

    if (len > array2.length) {
        len = array2.length;
        result = 1;
    }

    for (i = 0; i < len; i++) {
        if (isNaN(array1[i])) {
            if (isNaN(array2[i])) {
                text = true;

                if ((r = this.strcmp(array1[i], array2[i])) != 0) {
                    return r;
                }
            } else if (text){
                return 1;
            } else {
                return -1;
            }
        } else if (isNaN(array2[i])) {
            if(text) {
                return -1;
            } else{
                return 1;
            }
        } else {
            if(text || f_version){
                if ((r = (array1[i] - array2[i])) != 0) {
                    return r;
                }
            } else {
                if ((r = this.strcmp(array1[i].toString(), array2[i].toString())) != 0) {
                    return r;
                }
            }

            text = false;
        }
    }

    return result;
}

function strncasecmp (argStr1, argStr2, len) {
    // Binary safe string comparison  
    // 
    // version: 903.1614
    // discuss at: http://phpjs.org/functions/strncasecmp
    // +   original by: Saulo Vallory
    // +      input by: Nate
    // +   bugfixed by: Onno Marsman
    // %          note: Returns < 0 if str1 is less than str2 ; > 0 if str1 is greater than str2 , and 0 if they are equal.
    // *     example 1: strncasecmp('Price 12.9', 'Price 12.15', 2);
    // *     returns 1: 0
    // *     example 2: strncasecmp('Price 12.09', 'Price 12.15', 10);
    // *     returns 2: -1
    // *     example 3: strncasecmp('Price 12.90', 'Price 12.15', 30);
    // *     returns 3: 8
    // *     example 4: strncasecmp('Version 12.9', 'Version 12.15', 20);
    // *     returns 4: 8
    // *     example 5: strncasecmp('Version 12.15', 'Version 12.9', 20);
    // *     returns 5: -8
    var diff, i = 0;
    var str1 = (argStr1+'').toLowerCase().substr(0,len);
    var str2 = (argStr2+'').toLowerCase().substr(0,len);

    if(str1.length !== str2.length) {
        if(str1.length < str2.length) {
            len = str1.length;
            if(str2.substr(0, str1.length) == str1) {
                return str1.length - str2.length; // return the difference of chars
            }
        } else {
            len = str2.length;
            // str1 is longer than str2
            if(str1.substr(0, str2.length) == str2) {
                return str1.length - str2.length; // return the difference of chars
            }
        }
    } else {
        // Avoids trying to get a char that does not exist
        len = str1.length;
    }

    for(diff = 0, i=0; i < len; i++) {
        diff = str1.charCodeAt(i) - str2.charCodeAt(i);
        if(diff !== 0) {
            return diff;
        }
    }

    return 0;
}

function strncmp ( str1, str2, lgth ) {
    // Binary safe string comparison  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/strncmp
    // +      original by: Waldo Malqui Silva
    // +         input by: Steve Hilder
    // +      improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +       revised by: gorthaur
    // + reimplemented by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: strncmp('aaa', 'aab', 2);
    // *     returns 1: 0
    // *     example 2: strncmp('aaa', 'aab', 3 );
    // *     returns 2: -1
    var s1 = (str1+'').substr(0, lgth);
    var s2 = (str2+'').substr(0, lgth);
    
    return ( ( s1 == s2 ) ? 0 : ( ( s1 > s2 ) ? 1 : -1 ) );
}

function strpbrk( haystack, char_list ) {
    // Search a string for any of a set of characters  
    // 
    // version: 903.1614
    // discuss at: http://phpjs.org/functions/strpbrk
    // +   original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strpbrk('This is a Simple text.', 'is');
    // *     returns 1: 'is is a Simple text.'
    haystack += '';
    char_list += '';
    var lon = haystack.length;
    var lon_search = char_list.length;
    var ret = false;
    var stack = '';
    var i = 0, j = 0;

    if (lon >= lon_search) {
        if (lon == lon_search) {
            if (haystack == char_list){
                ret = haystack;
            }
        } else {
            j = 0;
            i = 0;
            while (i < lon_search && j < lon && !ret) {
                if (char_list[i] == haystack[j]) {
                    i++;
                    if (i == lon_search) {
                        ret = true;
                    }
                }
                j++;
            }
            if (ret) {
                for(i = (j-lon_search); i < lon; i++){
                    stack += haystack[i];
                }
            }
            if (stack != '') {
                ret = stack;
            }
        }
    }
    
    return ret;
}

function strpos( haystack, needle, offset){
    // Finds position of first occurrence of a string within another  
    // 
    // version: 905.1314
    // discuss at: http://phpjs.org/functions/strpos
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function strrchr (haystack, needle) {
    // Finds the last occurrence of a character in a string within another  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/strrchr
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: strrchr("Line 1\nLine 2\nLine 3", 10).substr(1)
    // *     returns 1: 'Line 3'
    var pos = 0;

    if (typeof needle !== 'string') {
        needle = String.fromCharCode(parseInt(needle
