/* 
 * More info at: http://phpjs.org
 * 
 * This is version: 3.09
 * php.js is copyright 2010 Kevin van Zonneveld.
 * 
 * Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
 * (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
 * (http://getsprink.com), Waldo Malqui Silva, Paulo Ricardo F. Santos, Jack,
 * Jonas Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson,
 * Legaev Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn
 * Wieringa, Nate, Philippe Baumann, lmeyrick
 * (https://sourceforge.net/projects/bcmath-js/), Enrique Gonzalez,
 * Webtoolkit.info (http://www.webtoolkit.info/), Jani Hartikainen, travc, Ole
 * Vrijenhoek, Ash Searle (http://hexmen.com/blog/), Carlos R. L. Rodrigues
 * (http://www.jsfromhell.com), d3x,
 * http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
 * pilus, stag019, WebDevHobo (http://webdevhobo.blogspot.com/), Michael
 * Grier, Erkekjetter, T.Wild, Andrea Giammarchi
 * (http://webreflection.blogspot.com), marrtins, GeekFG
 * (http://geekfg.blogspot.com), Johnny Mast (http://www.phpvrouwen.nl),
 * gorthaur, Michael White, majak, Steve Hilder, Oleg Eremeev, Martin
 * (http://www.erlenwiese.de/), gettimeofday, Joris, Steven Levithan
 * (http://blog.stevenlevithan.com), Tim de Koning (http://www.kingsquare.nl),
 * KELAN, Arpad Ray (mailto:arpad@php.net), Breaking Par Consulting Inc
 * (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
 * Josh Fraser
 * (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
 * Chris, Marc Palau, Public Domain (http://www.json.org/json2.js), saulius,
 * Aman Gupta, Pellentesque Malesuada, Mailfaker (http://www.weedem.fr/), Caio
 * Ariede (http://caioariede.com), Thunder.m, Alfonso Jimenez
 * (http://www.alfonsojimenez.com), AJ, mdsjack (http://www.mdsjack.bo.it),
 * Lars Fischer, Kankrelune (http://www.webfaktory.info/), Felix Geisendoerfer
 * (http://www.debuggable.com/felix), Tyler Akins (http://rumkin.com), Mirek
 * Slugen, Robin, Karol Kowalski, Paul Smith, Sakimori, David, noname, Marco,
 * Douglas Crockford (http://javascript.crockford.com), Scott Cariss,
 * class_exists, marc andreu, Steve Clay, Francois, nobbler, David James,
 * Arno, madipta, Fox, mktime, ger, Nathan, felix, Frank Forte, Slawomir
 * Kaniecki, john (http://www.jd-tech.net), Nick Kolosov (http://sammy.ru),
 * Mateusz "loonquawl" Zalega, ReverseSyntax, nord_ua, T. Wild, Thiago Mata
 * (http://thiagomata.blog.com), Linuxworld, lmeyrick
 * (https://sourceforge.net/projects/bcmath-js/this.), Jon Hohle, Pyerre,
 * MeEtc (http://yass.meetcweb.com), Peter-Paul Koch
 * (http://www.quirksmode.org/js/beat.html), T0bsn, Soren Hansen, djmix,
 * Lincoln Ramsay, Sanjoy Roy, sankai, Denny Wardhana, 0m3r, Subhasis Deb,
 * Bayron Guevara, paulo kuong, duncan, Gilbert, Brad Touesnard, Tim Wiel,
 * Marc Jansen, Francesco, Stoyan Kyosev (http://www.svest.org/), J A R, Paul,
 * Ole Vrijenhoek (http://www.nervous.nl/), Raphael (Ao RUDLER), kenneth, Hyam
 * Singer (http://www.impact-computing.com/), LH, JB, JT, Thomas Beaucourt
 * (http://www.webapp.fr), David Randall, Bryan Elliott, date, Ozh, Eugene
 * Bulkin (http://doubleaw.com/), Der Simon
 * (http://innerdom.sourceforge.net/), echo is bad, XoraX
 * (http://www.xorax.info), Matt Bradley, Itsacon (http://www.itsacon.net/),
 * Saulo Vallory, Kristof Coomans (SCK-CEN Belgian Nucleair Research Centre),
 * Pierre-Luc Paour, Kirk Strobeck, Martin Pool, Christoph, Daniel Esteban,
 * Artur Tchernychev, Wagner B. Soares, Valentina De Rosa, strftime, Jason
 * Wong (http://carrot.org/), Brant Messenger
 * (http://www.brantmessenger.com/), Rick Waldron, Bug?, Anton Ongson, Simon
 * Willison (http://simonwillison.net), Marco van Oort, Gabriel Paderni, Blues
 * (http://tech.bluesmoon.info/), Luke Godfrey, rezna, Mick@el, Tomasz
 * Wesolowski, Eric Nagel, Pul, Bobby Drake, uestla, Alan C, Ulrich, Yves
 * Sucaet, sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick
 * Callen, ejsanders, Aidan Lister (http://aidanlister.com/), Brian Tafoya
 * (http://www.premasolutions.com/), Philippe Jausions
 * (http://pear.php.net/user/jausions), Rob, Orlando, HKM, metjay, strcasecmp,
 * strcmp, Taras Bogach, jpfle, ChaosNo1, Alexander Ermolaev
 * (http://snippets.dzone.com/user/AlexanderErmolaev), dptr1988, kilops, Le
 * Torbi, James, DxGx, Pedro Tainha (http://www.pedrotainha.com), Philipp
 * Lenssen, penutbutterjelly, FGFEmperor, baris ozdil, Greg Frazier, Alexander
 * M Beedie, Tod Gentille, gabriel paderni, Yannoo, Maximusya, Atli Þór,
 * daniel airton wermann (http://wermann.com.br), jakes, 3D-GRAF, Riddler
 * (http://www.frontierwebdev.com/), T.J. Leahy, Matteo, stensi, Billy, Jalal
 * Berrami, vlado houba, Victor, fearphage
 * (http://http/my.opera.com/fearphage/), Luis Salazar
 * (http://www.freaky-media.com/), FremyCompany, Tim de Koning, taith, Cord,
 * Manish, davook, Benjamin Lupton, Russell Walker (http://www.nbill.co.uk/),
 * Garagoth, Andrej Pavlovic, rem, Dino, Jamie Beck (http://www.terabit.ca/),
 * DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Michael,
 * Christian Doebler, setcookie, YUI Library:
 * http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Andreas,
 * Blues at http://hacks.bluesmoon.info/strftime/strftime.js, meo, Greenseed,
 * Luke Smith (http://lucassmith.name), Rival, Diogo Resende, Allan Jensen
 * (http://www.winternet.no), Howard Yeend, Kheang Hok Chin
 * (http://www.distantia.ca/), Jay Klehr, Leslie Hoare, mk.keck, Ben Bryan,
 * booeyOH, Amir Habibi (http://www.residence-mixte.com/), Cagri Ekin
 * 
 * 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.
 */ 


/**
 * BC Math Library for Javascript
 * Ported from the PHP5 bcmath extension source code,
 * which uses the libbcmath package...
 *    Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
 *    Copyright (C) 2000 Philip A. Nelson
 *     The Free Software Foundation, Inc.
 *     59 Temple Place, Suite 330
 *     Boston, MA 02111-1307 USA.
 *      e-mail:  philnelson@acm.org
 *     us-mail:  Philip A. Nelson
 *               Computer Science Department, 9062
 *               Western Washington University
 *               Bellingham, WA 98226-9062
 *
 * bcmath-js homepage:
 *
 * This code is covered under the LGPL licence, and can be used however you want :)
 * Be kind and share any decent code changes.
 */
/**
 * Binary Calculator (BC) Arbitrary Precision Mathematics Lib v0.10  (LGPL)
 * Copy of libbcmath included in PHP5 src
 *
 * Note: this is just the shared library file and does not include the php-style functions.
 *       use bcmath{-min}.js for functions like bcadd, bcsub etc.
 *
 * Feel free to use how-ever you want, just email any bug-fixes/improvements to the sourceforge project:
 *      
 *
 * Ported from the PHP5 bcmath extension source code,
 * which uses the libbcmath package...
 *    Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
 *    Copyright (C) 2000 Philip A. Nelson
 *     The Free Software Foundation, Inc.
 *     59 Temple Place, Suite 330
 *     Boston, MA 02111-1307 USA.
 *      e-mail:  philnelson@acm.org
 *     us-mail:  Philip A. Nelson
 *               Computer Science Department, 9062
 *               Western Washington University
 *               Bellingham, WA 98226-9062
 */
function _phpjs_shared_bc () {
    // http://kevin.vanzonneveld.net
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: _phpjs_shared_bc();
    // *     returns 1: {}
    
    var libbcmath = {
        PLUS: '+',
        MINUS: '-',
        BASE: 10,           // must be 10 (for now)
        scale: 0,           // default scale

        /**
         * Basic number structure
         */
        bc_num: function() {
            this.n_sign = null; // sign
            this.n_len = null;  /* (int) The number of digits before the decimal point. */
            this.n_scale = null; /* (int) The number of digits after the decimal point. */
            //this.n_refs = null; /* (int) The number of pointers to this number. */
            //this.n_text = null; /* ?? Linked list for available list. */
            this.n_value = null;  /* array as value, where 1.23 = [1,2,3] */
            this.toString = function() {
                var r, tmp;
                tmp=this.n_value.join('');

                // add minus sign (if applicable) then add the integer part
                r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len);

                // if decimal places, add a . and the decimal part
                if (this.n_scale > 0) {
                    r += '.' + tmp.substr(this.n_len, this.n_scale);
                }
                return r;
            };
        },

        /**
         * Base add function
         *
         //  Here is the full add routine that takes care of negative numbers.
         //  N1 is added to N2 and the result placed into RESULT.  SCALE_MIN
         //  is the minimum scale for the result.
         *
         * @param {bc_num} n1
         * @param {bc_num} n2
         * @param {int} scale_min
         * @return bc_num
         */
        bc_add: function(n1, n2, scale_min) {
            var sum, cmp_res, res_scale;

            if (n1.n_sign === n2.n_sign) {
                sum = libbcmath._bc_do_add(n1, n2, scale_min);
                sum.n_sign = n1.n_sign;
            } else {
                /* subtraction must be done. */
                cmp_res = libbcmath._bc_do_compare(n1, n2, false, false); /* Compare magnitudes. */
                switch (cmp_res) {
                    case -1:
                        /* n1 is less than n2, subtract n1 from n2. */
                        sum = libbcmath._bc_do_sub(n2, n1, scale_min);
                        sum.n_sign = n2.n_sign;
                        break;

                    case  0:
                        /* They are equal! return zero with the correct scale! */
                        res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale));
                        sum = libbcmath.bc_new_num(1, res_scale);
                        libbcmath.memset(sum.n_value, 0, 0, res_scale+1);
                        break;

                    case  1:
                        /* n2 is less than n1, subtract n2 from n1. */
                        sum = libbcmath._bc_do_sub(n1, n2, scale_min);
                        sum.n_sign = n1.n_sign;
                }
            }
            return sum;
        },

        /**
 * This is the "user callable" routine to compare numbers N1 and N2.
 * @param {bc_num} n1
 * @param {bc_num} n2
 * @return int -1, 0, 1  (n1 < n2, ==, n1 > n2)
 */
        bc_compare: function(n1, n2) {
            return libbcmath._bc_do_compare (n1, n2, true, false);
        },

        _one_mult: function(num, n_ptr, size, digit, result, r_ptr) {
            var carry, value; // int
            var nptr, rptr; // int pointers

            if (digit === 0) {
                libbcmath.memset(result, 0, 0, size);   //memset (result, 0, size);
            } else {
                if (digit == 1) {
                    libbcmath.memcpy(result, r_ptr, num, n_ptr, size); //memcpy (result, num, size);
                } else {
                    /*  Initialize */
                    nptr = n_ptr+size-1; //nptr = (unsigned char *) (num+size-1);
                    rptr = r_ptr+size-1; //rptr = (unsigned char *) (result+size-1);
                    carry = 0;

                    while (size-- > 0) {
                        value = num[nptr--] * digit + carry; //value = *nptr-- * digit + carry;
                        //result[rptr--] = libbcmath.cint(value % libbcmath.BASE); // @CHECK cint //*rptr-- = value % BASE;
                        result[rptr--] = value % libbcmath.BASE; // @CHECK cint //*rptr-- = value % BASE;
                        //carry = libbcmath.cint(value / libbcmath.BASE);   // @CHECK cint //carry = value / BASE;
                        carry = Math.floor(value / libbcmath.BASE);   // @CHECK cint //carry = value / BASE;
                    }

                    if (carry !== 0) {
                        result[rptr] = carry;
                    }
                }
            }
        },

        bc_divide: function(n1, n2, scale) {
            var quot;   // bc_num return
            var qval; // bc_num
            var num1, num2; // string
            var ptr1, ptr2, n2ptr, qptr; // int pointers
            var scale1, val; // int
            var len1, len2, scale2, qdigits, extra, count; // int
            var qdig, qguess, borrow, carry; // int
            var mval; // string
            var zero; // char
            var norm; // int
            var ptrs; // return object from one_mul

            /* Test for divide by zero. (return failure) */
            if (libbcmath.bc_is_zero(n2)) {
                return -1;
            }

            /* Test for zero divide by anything (return zero) */
            if (libbcmath.bc_is_zero(n1)) {
                return libbcmath.bc_new_num(1, scale);
            }

            /* Test for n1 equals n2 (return 1 as n1 nor n2 are zero)
    if (libbcmath.bc_compare(n1, n2, libbcmath.MAX(n1.n_scale, n2.n_scale)) === 0) {
        quot=libbcmath.bc_new_num(1, scale);
        quot.n_value[0] = 1;
        return quot;
    }
    */

            /* Test for divide by 1.  If it is we must truncate. */
            // todo: check where scale > 0 too.. can't see why not (ie bc_is_zero - add bc_is_one function)
            if (n2.n_scale === 0) {
                if (n2.n_len === 1 && n2.n_value[0] === 1) {
                    qval = libbcmath.bc_new_num(n1.n_len, scale);       //qval = bc_new_num (n1->n_len, scale);
                    qval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS);
                    libbcmath.memset(qval.n_value, n1.n_len, 0, scale); //memset (&qval->n_value[n1->n_len],0,scale);
                    libbcmath.memcpy(qval.n_value, 0, n1.n_value, 0, n1.n_len + libbcmath.MIN(n1.n_scale, scale)); //memcpy (qval->n_value, n1->n_value, n1->n_len + MIN(n1->n_scale,scale));
                // can we return here? not in c src, but can't see why-not.
                // return qval;
                }
            }

            /* Set up the divide.  Move the decimal point on n1 by n2's scale.
     Remember, zeros on the end of num2 are wasted effort for dividing. */
            scale2 = n2.n_scale;    //scale2 = n2->n_scale;
            n2ptr = n2.n_len + scale2 - 1;  //n2ptr = (unsigned char *) n2.n_value+n2.n_len+scale2-1;
            while ((scale2 > 0) && (n2.n_value[n2ptr--] === 0)) {
                scale2--;
            }

            len1 = n1.n_len + scale2;
            scale1 = n1.n_scale - scale2;
            if (scale1 < scale) {
                extra = scale - scale1;
            } else {
                extra = 0;
            }

            num1 = libbcmath.safe_emalloc(1, n1.n_len + n1.n_scale, extra + 2); //num1 = (unsigned char *) safe_emalloc (1, n1.n_len+n1.n_scale, extra+2);
            if (num1 === null) {
                libbcmath.bc_out_of_memory();
            }
            libbcmath.memset(num1, 0, 0, n1.n_len+n1.n_scale+extra+2); //memset (num1, 0, n1->n_len+n1->n_scale+extra+2);
            libbcmath.memcpy(num1, 1, n1.n_value, 0, n1.n_len+n1.n_scale); //memcpy (num1+1, n1.n_value, n1.n_len+n1.n_scale);

            len2 = n2.n_len + scale2;  // len2 = n2->n_len + scale2;
            num2 = libbcmath.safe_emalloc(1, len2, 1);//num2 = (unsigned char *) safe_emalloc (1, len2, 1);
            if (num2 === null) {
                libbcmath.bc_out_of_memory();
            }
            libbcmath.memcpy(num2, 0, n2.n_value, 0, len2);  //memcpy (num2, n2.n_value, len2);
            num2[len2] = 0;   // *(num2+len2) = 0;
            n2ptr = 0; //n2ptr = num2;

            while (num2[n2ptr] === 0) {   // while (*n2ptr == 0)
                n2ptr++;
                len2--;
            }

            /* Calculate the number of quotient digits. */
            if (len2 > len1+scale) {
                qdigits = scale+1;
                zero = true;
            } else {
                zero = false;
                if (len2>len1) {
                    qdigits = scale+1;      /* One for the zero integer part. */
                } else {
                    qdigits = len1-len2+scale+1;
                }
            }

            /* Allocate and zero the storage for the quotient. */
            qval = libbcmath.bc_new_num(qdigits-scale,scale);   //qval = bc_new_num (qdigits-scale,scale);
            libbcmath.memset(qval.n_value, 0, 0, qdigits); //memset (qval->n_value, 0, qdigits);

            /* Allocate storage for the temporary storage mval. */
            mval = libbcmath.safe_emalloc(1, len2, 1); //mval = (unsigned char *) safe_emalloc (1, len2, 1);
            if (mval === null) {
                libbcmath.bc_out_of_memory();
            }

            /* Now for the full divide algorithm. */
            if (!zero) {
                /* Normalize */
                //norm = libbcmath.cint(10 / (libbcmath.cint(n2.n_value[n2ptr]) + 1)); //norm =  10 / ((int)*n2ptr + 1);
                norm = Math.floor(10 / (n2.n_value[n2ptr] + 1)); //norm =  10 / ((int)*n2ptr + 1);
                if (norm != 1) {
                    libbcmath._one_mult(num1, 0, len1+scale1+extra+1, norm, num1, 0); //libbcmath._one_mult(num1, len1+scale1+extra+1, norm, num1);
                    libbcmath._one_mult(n2.n_value, n2ptr, len2, norm, n2.n_value, n2ptr); //libbcmath._one_mult(n2ptr, len2, norm, n2ptr);

                // @CHECK Is the pointer affected by the call? if so, maybe need to adjust points on return?

                }

                /* Initialize divide loop. */
                qdig = 0;
                if (len2 > len1) {
                    qptr = len2-len1; //qptr = (unsigned char *) qval.n_value+len2-len1;
                }  else {
                    qptr = 0; //qptr = (unsigned char *) qval.n_value;
                }

                /* Loop */
                while (qdig <= len1+scale-len2) {
                    /* Calculate the quotient digit guess. */
                    if (n2.n_value[n2ptr] == num1[qdig]) {
                        qguess = 9;
                    } else {
                        qguess = Math.floor((num1[qdig]*10 + num1[qdig+1]) / n2.n_value[n2ptr]);
                    }
                    /* Test qguess. */

                    if (n2.n_value[n2ptr+1]*qguess > (num1[qdig]*10 + num1[qdig+1] - n2.n_value[n2ptr]*qguess)*10 + num1[qdig+2]) { //if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2]) {
                        qguess--;
                        /* And again. */
                        if (n2.n_value[n2ptr+1]*qguess > (num1[qdig]*10 + num1[qdig+1] - n2.n_value[n2ptr]*qguess)*10 + num1[qdig+2]) { //if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2])
                            qguess--;
                        }
                    }

                    /* Multiply and subtract. */
                    borrow = 0;
                    if (qguess !== 0) {
                        mval[0] = 0; //*mval = 0; // @CHECK is this to fix ptr2 < 0?
                        libbcmath._one_mult(n2.n_value, n2ptr, len2, qguess, mval, 1); //_one_mult (n2ptr, len2, qguess, mval+1); // @CHECK

                        ptr1 = qdig+len2; //(unsigned char *) num1+qdig+len2;
                        ptr2 = len2; //(unsigned char *) mval+len2;

                        // @CHECK: Does a negative pointer return null?
                        //         ptr2 can be < 0 here as ptr1 = len2, thus count < len2+1 will always fail ?
                        for (count = 0; count < len2+1; count++) {
                            if (ptr2 < 0) {
                                //val = libbcmath.cint(num1[ptr1]) - 0 - borrow;    //val = (int) *ptr1 - (int) *ptr2-- - borrow;
                                val = num1[ptr1] - 0 - borrow;    //val = (int) *ptr1 - (int) *ptr2-- - borrow;
                            } else {
                                //val = libbcmath.cint(num1[ptr1]) - libbcmath.cint(mval[ptr2--]) - borrow;    //val = (int) *ptr1 - (int) *ptr2-- - borrow;
                                val = num1[ptr1] - mval[ptr2--] - borrow;    //val = (int) *ptr1 - (int) *ptr2-- - borrow;
                            }
                            if (val < 0) {
                                val += 10;
                                borrow = 1;
                            } else {
                                borrow = 0;
                            }
                            num1[ptr1--] = val;
                        }
                    }

                    /* Test for negative result. */
                    if (borrow == 1) {
                        qguess--;
                        ptr1 = qdig+len2; //(unsigned char *) num1+qdig+len2;
                        ptr2 = len2-1; //(unsigned char *) n2ptr+len2-1;
                        carry = 0;
                        for (count = 0; count < len2; count++) {
                            if (ptr2 < 0) {
                                //val = libbcmath.cint(num1[ptr1]) + 0 + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry;
                                val = num1[ptr1] + 0 + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry;
                            } else {
                                //val = libbcmath.cint(num1[ptr1]) + libbcmath.cint(n2.n_value[ptr2--]) + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry;
                                val = num1[ptr1] + n2.n_value[ptr2--] + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry;
                            }
                            if (val > 9) {
                                val -= 10;
                                carry = 1;
                            } else {
                                carry = 0;
                            }
                            num1[ptr1--] = val; //*ptr1-- = val;
                        }
                        if (carry == 1) {
                            //num1[ptr1] = libbcmath.cint((num1[ptr1] + 1) % 10);  // *ptr1 = (*ptr1 + 1) % 10; // @CHECK
                            num1[ptr1] = (num1[ptr1] + 1) % 10;  // *ptr1 = (*ptr1 + 1) % 10; // @CHECK
                        }
                    }

                    /* We now know the quotient digit. */
                    qval.n_value[qptr++] =  qguess;  //*qptr++ =  qguess;
                    qdig++;
                }
            }

            /* Clean up and return the number. */
            qval.n_sign = ( n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS );
            if (libbcmath.bc_is_zero(qval)) {
                qval.n_sign = libbcmath.PLUS;
            }
            libbcmath._bc_rm_leading_zeros(qval);

            return qval;

        //return 0;    /* Everything is OK. */
        },



        MUL_BASE_DIGITS: 80,
        MUL_SMALL_DIGITS: (this.MUL_BASE_DIGITS / 4), //#define MUL_SMALL_DIGITS mul_base_digits/4


        /* The multiply routine.  N2 times N1 is put int PROD with the scale of
   the result being MIN(N2 scale+N1 scale, MAX (SCALE, N2 scale, N1 scale)).
   */
        /**
         * @param n1 bc_num
         * @param n2 bc_num
         * @param scale [int] optional
         */
        bc_multiply: function(n1, n2, scale) {
            var pval; // bc_num
            var len1, len2; // int
            var full_scale, prod_scale; // int

            // Initialize things.
            len1 = n1.n_len + n1.n_scale;
            len2 = n2.n_len + n2.n_scale;
            full_scale = n1.n_scale + n2.n_scale;
            prod_scale = libbcmath.MIN(full_scale,libbcmath.MAX(scale,libbcmath.MAX(n1.n_scale, n2.n_scale)));

            //pval = libbcmath.bc_init_num(); // allow pass by ref
            // Do the multiply
            pval = libbcmath._bc_rec_mul (n1, len1, n2, len2, full_scale);

            // Assign to prod and clean up the number.
            pval.n_sign  = ( n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS );
            //pval.n_value = pval.n_ptr; // @FIX
            pval.n_len   = len2 + len1 + 1 - full_scale;
            pval.n_scale = prod_scale;
            libbcmath._bc_rm_leading_zeros(pval);
            if (libbcmath.bc_is_zero(pval)) {
                pval.n_sign = libbcmath.PLUS;
            }
            //bc_free_num (prod);
            return pval;
        },

        new_sub_num: function(length, scale, value) {
            var temp = new libbcmath.bc_num();
            temp.n_sign = libbcmath.PLUS;
            temp.n_len = length;
            temp.n_scale = scale;
            temp.n_value = value;
            return temp;
        },

        _bc_simp_mul: function(n1, n1len, n2, n2len, full_scale) {
            var prod;   // bc_num
            var n1ptr, n2ptr, pvptr; // char *n1ptr, *n2ptr, *pvptr;
            var n1end, n2end; //char *n1end, *n2end;        /* To the end of n1 and n2. */
            var indx, sum, prodlen; //int indx, sum, prodlen;

            prodlen = n1len+n2len+1;

            prod = libbcmath.bc_new_num(prodlen, 0);

            n1end = n1len-1; //(char *) (n1->n_value + n1len - 1);
            n2end = n2len-1; //(char *) (n2->n_value + n2len - 1);
            pvptr = prodlen-1; //(char *) ((*prod)->n_value + prodlen - 1);
            sum = 0;

            // Here is the loop...
            for (indx = 0; indx < prodlen-1; indx++) {
                n1ptr = n1end - libbcmath.MAX(0, indx-n2len+1); //(char *) (n1end - MAX(0, indx-n2len+1));
                n2ptr = n2end - libbcmath.MIN(indx, n2len-1); //(char *) (n2end - MIN(indx, n2len-1));
                while ((n1ptr >= 0) && (n2ptr <= n2end)) {
                    sum += n1.n_value[n1ptr--] * n2.n_value[n2ptr++];   //sum += *n1ptr-- * *n2ptr++;
                }
                prod.n_value[pvptr--] = Math.floor(sum % libbcmath.BASE); //*pvptr-- = sum % BASE;
                sum = Math.floor(sum / libbcmath.BASE); //sum = sum / BASE;
            }
            prod.n_value[pvptr]=sum; //*pvptr = sum;
            return prod;
        },


        /* A special adder/subtractor for the recursive divide and conquer
           multiply algorithm.  Note: if sub is called, accum must
           be larger that what is being subtracted.  Also, accum and val
           must have n_scale = 0.  (e.g. they must look like integers. *) */
        _bc_shift_addsub: function(accum, val, shift, sub) {
            var accp, valp; //signed char *accp, *valp;
            var count, carry; //int  count, carry;

            count = val.n_len;
            if (val.n_value[0] === 0) {
                count--;
            }

            //assert (accum->n_len+accum->n_scale >= shift+count);
            if (accum.n_len+accum.n_scale < shift+count) {
                throw new Error("len + scale < shift + count"); // ?? I think that's what assert does :)
            }


            // Set up pointers and others
            accp = accum.n_len + accum.n_scale - shift - 1; // (signed char *)(accum->n_value + accum->n_len + accum->n_scale - shift - 1);
            valp = val.n_len = 1; //(signed char *)(val->n_value + val->n_len - 1);
            carry = 0;
            if (sub) {
                // Subtraction, carry is really borrow.
                while (count--) {
                    accum.n_value[accp] -= val.n_value[valp--] + carry; //*accp -= *valp-- + carry;
                    if (accum.n_value[accp] < 0) {  //if (*accp < 0)
                        carry = 1;
                        accum.n_value[accp--] += libbcmath.BASE; //*accp-- += BASE;
                    } else {
                        carry = 0;
                        accp--;
                    }
                }
                while (carry) {
                    accum.n_value[accp] -= carry; //*accp -= carry;
                    if (accum.n_value[accp] < 0) { //if (*accp < 0)
                        accum.n_value[accp--] += libbcmath.BASE; //    *accp-- += BASE;
                    } else {
                        carry = 0;
                    }
                }
            } else {
                // Addition
                while (count--) {
                    accum.n_value[accp] += val.n_value[valp--] + carry; //*accp += *valp-- + carry;
                    if (accum.n_value[accp] > (libbcmath.BASE-1)) {//if (*accp > (BASE-1))
                        carry = 1;
                        accum.n_value[accp--] -= libbcmath.BASE; //*accp-- -= BASE;
                    } else {
                        carry = 0;
                        accp--;
                    }
                }
                while (carry) {
                    accum.n_value[accp] += carry; //*accp += carry;
                    if (accum.n_value[accp] > (libbcmath.BASE-1)) { //if (*accp > (BASE-1))
                        accum.n_value[accp--] -= libbcmath.BASE; //*accp-- -= BASE;
                    } else {
                        carry = 0;
                    }
                }
            }
            return true; // accum is the pass-by-reference return
        },

        /* Recursive divide and conquer multiply algorithm.
           Based on
           Let u = u0 + u1*(b^n)
           Let v = v0 + v1*(b^n)
           Then uv = (B^2n+B^n)*u1*v1 + B^n*(u1-u0)*(v0-v1) + (B^n+1)*u0*v0

           B is the base of storage, number of digits in u1,u0 close to equal.
        */
        _bc_rec_mul: function (u, ulen, v, vlen, full_scale) {
            var prod; // @return
            var u0, u1, v0, v1; //bc_num
            var u0len, v0len;   //int
            var m1, m2, m3, d1, d2; //bc_num
            var n, prodlen, m1zero; // int
            var d1len, d2len;   // int

            // Base case?
            if ( (ulen+vlen) < libbcmath.MUL_BASE_DIGITS || ulen < libbcmath.MUL_SMALL_DIGITS || vlen < libbcmath.MUL_SMALL_DIGITS ) {
                return libbcmath._bc_simp_mul(u, ulen, v, vlen,  full_scale);
            }

            // Calculate n -- the u and v split point in digits.
            n = Math.floor((libbcmath.MAX(ulen, vlen)+1) / 2);

            // Split u and v.
            if (ulen < n) {
                u1 = libbcmath.bc_init_num(); //u1 = bc_copy_num (BCG(_zero_));
                u0 = libbcmath.new_sub_num(ulen,0, u.n_value);
            } else {
                u1 = libbcmath.new_sub_num(ulen-n, 0, u.n_value);
                u0 = libbcmath.new_sub_num(n, 0, u.n_value+ulen-n);
            }
            if (vlen < n) {
                v1 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_));
                v0 = libbcmath.new_sub_num(vlen,0, v.n_value);
            } else {
                v1 = libbcmath.new_sub_num(vlen-n, 0, v.n_value);
                v0 = libbcmath.new_sub_num(n, 0, v.n_value+vlen-n);
            }
            libbcmath._bc_rm_leading_zeros(u1);
            libbcmath._bc_rm_leading_zeros(u0);
            u0len = u0.n_len;
            libbcmath._bc_rm_leading_zeros(v1);
            libbcmath._bc_rm_leading_zeros(v0);
            v0len = v0.n_len;

            m1zero = libbcmath.bc_is_zero(u1) || libbcmath.bc_is_zero(v1);

            // Calculate sub results ...

            d1 = libbcmath.bc_init_num(); // needed?
            d2 = libbcmath.bc_init_num(); // needed?
            d1 = libbcmath.bc_sub(u1, u0, 0);
            d1len = d1.n_len;

            d2 = libbcmath.bc_sub (v0, v1, 0);
            d2len = d2.n_len;

            // Do recursive multiplies and shifted adds.
            if (m1zero) {
                m1 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_));
            } else {
                //m1 = libbcmath.bc_init_num(); //allow pass-by-ref
                m1 = libbcmath._bc_rec_mul (u1, u1.n_len, v1, v1.n_len, 0);
            }
            if (libbcmath.bc_is_zero(d1) || libbcmath.bc_is_zero(d2)) {
                m2 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_));
            } else {
                //m2 = libbcmath.bc_init_num(); //allow pass-by-ref
                m2 = libbcmath._bc_rec_mul (d1, d1len, d2, d2len, 0);
            }

            if (libbcmath.bc_is_zero(u0) || libbcmath.bc_is_zero(v0)) {
                m3 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_));
            } else {
                //m3 = libbcmath.bc_init_num(); //allow pass-by-ref
                m3 = libbcmath._bc_rec_mul(u0, u0.n_len, v0, v0.n_len, 0);
            }

            // Initialize product
            prodlen = ulen+vlen+1;
            prod = libbcmath.bc_new_num(prodlen, 0);

            if (!m1zero) {
                libbcmath._bc_shift_addsub(prod, m1, 2*n, 0);
                libbcmath._bc_shift_addsub(prod, m1, n, 0);
            }
            libbcmath._bc_shift_addsub(prod, m3, n, 0);
            libbcmath._bc_shift_addsub(prod, m3, 0, 0);
            libbcmath._bc_shift_addsub(prod, m2, n, d1.n_sign != d2.n_sign);

            return prod;
        // Now clean up!
        //bc_free_num (&u1);
        //bc_free_num (&u0);
        //bc_free_num (&v1);
        //bc_free_num (&m1);
        //bc_free_num (&v0);
        //bc_free_num (&m2);
        //bc_free_num (&m3);
        //bc_free_num (&d1);
        //bc_free_num (&d2);
        },


        /**
         * 
         * @param {bc_num} n1
         * @param {bc_num} n2
         * @param {boolean} use_sign
         * @param {boolean} ignore_last
         * @return -1, 0, 1 (see bc_compare)
         */
        _bc_do_compare: function(n1, n2, use_sign, ignore_last) {
            var n1ptr, n2ptr; // int
            var count;    // int

            /* First, compare signs. */
            if (use_sign && (n1.n_sign != n2.n_sign)) {
                if (n1.n_sign == libbcmath.PLUS) {
                    return (1);    /* Positive N1 > Negative N2 */
                } else {
                    return (-1);    /* Negative N1 < Positive N1 */
                }
            }

            /* Now compare the magnitude. */
            if (n1.n_len != n2.n_len) {
                if (n1.n_len > n2.n_len) {
                    /* Magnitude of n1 > n2. */
                    if (!use_sign || (n1.n_sign == libbcmath.PLUS)) {
                        return (1);
                    } else {
                        return (-1);
                    }
                } else {
                    /* Magnitude of n1 < n2. */
                    if (!use_sign || (n1.n_sign == libbcmath.PLUS)) {
                        return (-1);
                    } else {
                        return (1);
                    }
                }
            }

            /* If we get here, they have the same number of integer digits.
       check the integer part and the equal length part of the fraction. */
            count = n1.n_len + Math.min(n1.n_scale, n2.n_scale);
            n1ptr = 0;
            n2ptr = 0;

            while ((count > 0) && (n1.n_value[n1ptr] == n2.n_value[n2ptr])) {
                n1ptr++;
                n2ptr++;
                count--;
            }

            if (ignore_last && (count == 1) && (n1.n_scale == n2.n_scale)) {
                return (0);
            }

            if (count !== 0) {
                if (n1.n_value[n1ptr] > n2.n_value[n2ptr])  {
                    /* Magnitude of n1 > n2. */
                    if (!use_sign || n1.n_sign == libbcmath.PLUS) {
                        return (1);
                    } else {
                        return (-1);
                    }
                } else {
                    /* Magnitude of n1 < n2. */
                    if (!use_sign || n1.n_sign == libbcmath.PLUS) {
                        return (-1);
                    } else {
                        return (1);
                    }
                }
            }

            /* They are equal up to the last part of the equal part of the fraction. */
            if (n1.n_scale != n2.n_scale) {
                if (n1.n_scale > n2.n_scale) {
                    for (count =(n1.n_scale - n2.n_scale); count>0; count--) {
                        if (n1.n_value[n1ptr++] !== 0) {
                            /* Magnitude of n1 > n2. */
                            if (!use_sign || n1.n_sign == libbcmath.PLUS) {
                                return (1);
                            } else {
                                return (-1);
                            }
                        }
                    }
                } else {
                    for (count = (n2.n_scale - n1.n_scale); count>0; count--) {
                        if (n2.n_value[n2ptr++] !== 0) {
                            /* Magnitude of n1 < n2. */
                            if (!use_sign || n1.n_sign == libbcmath.PLUS) {
                                return (-1);
                            } else {
                                return (1);
                            }
                        }
                    }
                }
            }

            /* They must be equal! */
            return (0);
        },



        /* Here is the full subtract routine that takes care of negative numbers.
   N2 is subtracted from N1 and the result placed in RESULT.  SCALE_MIN
   is the minimum scale for the result. */
        bc_sub: function(n1, n2, scale_min) {
            var diff; // bc_num
            var cmp_res, res_scale; //int
            if (n1.n_sign != n2.n_sign) {
                diff = libbcmath._bc_do_add (n1, n2, scale_min);
                diff.n_sign = n1.n_sign;
            } else {
                /* subtraction must be done. */
                /* Compare magnitudes. */
                cmp_res = libbcmath._bc_do_compare(n1, n2, false, false);
                switch (cmp_res) {
                    case -1:
                        /* n1 is less than n2, subtract n1 from n2. */
                        diff = libbcmath._bc_do_sub(n2, n1, scale_min);
                        diff.n_sign = (n2.n_sign == libbcmath.PLUS ? libbcmath.MINUS : libbcmath.PLUS);
                        break;
                    case  0:
                        /* They are equal! return zero! */
                        res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale));
                        diff = libbcmath.bc_new_num(1, res_scale);
                        libbcmath.memset(diff.n_value, 0, 0, res_scale+1);
                        break;
                    case  1:
                        /* n2 is less than n1, subtract n2 from n1. */
                        diff = libbcmath._bc_do_sub(n1, n2, scale_min);
                        diff.n_sign = n1.n_sign;
                        break;
                }
            }

            /* Clean up and return. */
            //bc_free_num (result);
            //*result = diff;
            return diff;
        },


        _bc_do_add: function(n1, n2, scale_min) {
            var sum;  // bc_num
            var sum_scale, sum_digits; // int
            var n1ptr, n2ptr, sumptr; // int
            var carry, n1bytes, n2bytes; // int
            var tmp; // int


            // Prepare sum.
            sum_scale   = libbcmath.MAX(n1.n_scale, n2.n_scale);
            sum_digits  = libbcmath.MAX(n1.n_len, n2.n_len) + 1;
            sum         = libbcmath.bc_new_num(sum_digits, libbcmath.MAX(sum_scale, scale_min));


            /* Not needed?
        if (scale_min > sum_scale) {
            sumptr = (char *) (sum->n_value + sum_scale + sum_digits);
            for (count = scale_min - sum_scale; count > 0; count--) {
                *sumptr++ = 0;
            }
        }
        */

            // Start with the fraction part.  Initialize the pointers.
            n1bytes = n1.n_scale;
            n2bytes = n2.n_scale;
            n1ptr = (n1.n_len + n1bytes - 1);
            n2ptr = (n2.n_len + n2bytes - 1);
            sumptr = (sum_scale + sum_digits - 1);

            // Add the fraction part.  First copy the longer fraction (ie when adding 1.2345 to 1 we know .2345 is correct already) .
            if (n1bytes != n2bytes) {
                if (n1bytes > n2bytes) {
                    // n1 has more dp then n2
                    while (n1bytes>n2bytes) {
                        sum.n_value[sumptr--] = n1.n_value[n1ptr--];
                        // *sumptr-- = *n1ptr--;
                        n1bytes--;
                    }
                } else {
                    // n2 has more dp then n1
                    while (n2bytes>n1bytes) {
                        sum.n_value[sumptr--] = n2.n_value[n2ptr--];
                        // *sumptr-- = *n2ptr--;
                        n2bytes--;
                    }
                }
            }

            // Now add the remaining fraction part and equal size integer parts.
            n1bytes += n1.n_len;
            n2bytes += n2.n_len;
            carry = 0;
            while ((n1bytes > 0) && (n2bytes > 0)) {

                // add the two numbers together
                tmp = n1.n_value[n1ptr--] + n2.n_value[n2ptr--] + carry;
                // *sumptr = *n1ptr-- + *n2ptr-- + carry;

                // check if they are >= 10 (impossible to be more then 18)
                if (tmp >= libbcmath.BASE) {
                    carry = 1;
                    tmp -= libbcmath.BASE;  // yep, subtract 10, add a carry
                } else {
                    carry = 0;
                }
                sum.n_value[sumptr] = tmp;
                sumptr--;
                n1bytes--;
                n2bytes--;
            }

            // Now add carry the [rest of the] longer integer part.
            if (n1bytes === 0) {
                // n2 is a bigger number then n1
                while (n2bytes-- > 0) {
                    tmp = n2.n_value[n2ptr--] + carry;
                    // *sumptr = *n2ptr-- + carry;

                    if (tmp >= libbcmath.BASE) {
                        carry = 1;
                        tmp -= libbcmath.BASE;
                    } else {
                        carry = 0;
                    }
                    sum.n_value[sumptr--]=tmp;
                }
            } else {
                // n1 is bigger then n2..
                while (n1bytes-- > 0) {
                    tmp = n1.n_value[n1ptr--] + carry;
                    // *sumptr = *n1ptr-- + carry;

                    if (tmp >= libbcmath.BASE) {
                        carry = 1;
                        tmp -= libbcmath.BASE;
                    } else {
                        carry = 0;
                    }
                    sum.n_value[sumptr--]=tmp;
                }
            }

            // Set final carry.
            if (carry == 1) {
                sum.n_value[sumptr] += 1;
            // *sumptr += 1;
            }

            // Adjust sum and return.
            libbcmath._bc_rm_leading_zeros (sum);
            return sum;
        },

        /**
     * Perform a subtraction
     *
     // Perform subtraction: N2 is subtracted from N1 and the value is
     //  returned.  The signs of N1 and N2 are ignored.  Also, N1 is
     //  assumed to be larger than N2.  SCALE_MIN is the minimum scale
     //  of the result.
     *
     * Basic school maths says to subtract 2 numbers..
     * 1. make them the same length, the decimal places, and the integer part
     * 2. start from the right and subtract the two numbers from each other
     * 3. if the sum of the 2 numbers < 0, carry -1 to the next set and add 10 (ie 18 > carry 1 becomes 8). thus 0.9 + 0.9 = 1.8
     *
     * @param {bc_num} n1
     * @param {bc_num} n2
     * @param {int} scale_min
     * @return bc_num
     */
        _bc_do_sub: function(n1, n2, scale_min) {
            var diff; //bc_num
            var diff_scale, diff_len; // int
            var min_scale, min_len; // int
            var n1ptr, n2ptr, diffptr; // int
            var borrow, count, val; // int

            // Allocate temporary storage.
            diff_len    = libbcmath.MAX(n1.n_len,   n2.n_len);
            diff_scale  = libbcmath.MAX(n1.n_scale, n2.n_scale);
            min_len     = libbcmath.MIN(n1.n_len,   n2.n_len);
            min_scale   = libbcmath.MIN(n1.n_scale, n2.n_scale);
            diff        = libbcmath.bc_new_num(diff_len, libbcmath.MAX(diff_scale, scale_min));

            /* Not needed?
        // Zero extra digits made by scale_min.
        if (scale_min > diff_scale) {
            diffptr = (char *) (diff->n_value + diff_len + diff_scale);
            for (count = scale_min - diff_scale; count > 0; count--) {
                *diffptr++ = 0;
            }
        }
        */

            // Initialize the subtract.
            n1ptr   = (n1.n_len + n1.n_scale -1);
            n2ptr   = (n2.n_len + n2.n_scale -1);
            diffptr = (diff_len + diff_scale -1);

            // Subtract the numbers.
            borrow = 0;

            // Take care of the longer scaled number.
            if (n1.n_scale != min_scale) {
                // n1 has the longer scale
                for (count = n1.n_scale - min_scale; count > 0; count--) {
                    diff.n_value[diffptr--] = n1.n_value[n1ptr--];
                // *diffptr-- = *n1ptr--;
                }
            } else {
                // n2 has the longer scale
                for (count = n2.n_scale - min_scale; count > 0; count--) {
                    val = 0 - n2.n_value[n2ptr--] - borrow;
                    //val = - *n2ptr-- - borrow;
                    if (val < 0) {
                        val += libbcmath.BASE;
                        borrow = 1;
                    } else {
                        borrow = 0;
                        diff.n_value[diffptr--] = val;
                    //*diffptr-- = val;
                    }
                }
            }

            // Now do the equal length scale and integer parts.
            for (count = 0; count < min_len + min_scale; count++) {
                val = n1.n_value[n1ptr--] - n2.n_value[n2ptr--] - borrow;
                //val = *n1ptr-- - *n2ptr-- - borrow;
                if (val < 0) {
                    val += libbcmath.BASE;
                    borrow = 1;
                } else {
                    borrow = 0;
                }
                diff.n_value[diffptr--] = val;
            //*diffptr-- = val;
            }

            // If n1 has more digits then n2, we now do that subtract.
            if (diff_len != min_len) {
                for (count = diff_len - min_len; count > 0; count--) {
                    val = n1.n_value[n1ptr--] - borrow;
                    // val = *n1ptr-- - borrow;
                    if (val < 0) {
                        val += libbcmath.BASE;
                        borrow = 1;
                    } else {
                        borrow = 0;
                    }
                    diff.n_value[diffptr--] = val;
                }
            }

            // Clean up and return.
            libbcmath._bc_rm_leading_zeros(diff);
            return diff;
        },

        /**
         * 
         * @param {int} length
         * @param {int} scale
         * @return bc_num
         */
        bc_new_num: function(length, scale) {
            var temp; // bc_num
            temp            = new libbcmath.bc_num();
            temp.n_sign     = libbcmath.PLUS;
            temp.n_len      = length;
            temp.n_scale    = scale;
            temp.n_value    = libbcmath.safe_emalloc(1, length+scale, 0);
            libbcmath.memset(temp.n_value, 0, 0, length+scale);
            return temp;
        },

        safe_emalloc: function(size, len, extra) {
            return Array((size * len) + extra);
        },

        /**
         * Create a new number
         */
        bc_init_num: function() {
            return new libbcmath.bc_new_num(1,0);

        },

        _bc_rm_leading_zeros: function (num) {
            /* We can move n_value to point to the first non zero digit! */
            while ((num.n_value[0] === 0) && (num.n_len > 1)) {
                num.n_value.shift();
                num.n_len--;
            }
        },

        /**
         * Convert to bc_num detecting scale
         */
        php_str2num: function(str) {
            var p;
            p = str.indexOf('.');
            if (p==-1) {
                return libbcmath.bc_str2num(str, 0);
            } else {
                return libbcmath.bc_str2num(str, (str.length-p));
            }

        },

        CH_VAL: function(c) {
            return c - '0'; //??
        },

        BCD_CHAR: function(d) {
            return d + '0'; // ??
        },

        isdigit: function(c) {
            return (isNaN(parseInt(c,10)) ? false : true);
        },

        bc_str2num: function(str_in, scale) {
            var str,num, ptr, digits, strscale, zero_int, nptr;
            // remove any non-expected characters
            /* Check for valid number and count digits. */

            str=str_in.split(''); // convert to array
            ptr = 0;    // str
            digits = 0;
            strscale = 0;
            zero_int = false;
            if ( (str[ptr] === '+') || (str[ptr] === '-'))  {
                ptr++;  /* Sign */
            }
            while (str[ptr] === '0') {
                ptr++;            /* Skip leading zeros. */
            }
            //while (libbcmath.isdigit(str[ptr])) {
            while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) {
                ptr++;
                digits++;    /* digits */
            }

            if (str[ptr] === '.') {
                ptr++;            /* decimal point */
            }
            //while (libbcmath.isdigit(str[ptr])) {
            while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) {
                ptr++;
                strscale++;    /* digits */
            }

            if ((str[ptr]) || (digits+strscale === 0)) {
                // invalid number, return 0
                return libbcmath.bc_init_num();
            //*num = bc_copy_num (BCG(_zero_));
            }

            /* Adjust numbers and allocate storage and initialize fields. */
            strscale = libbcmath.MIN(strscale, scale);
            if (digits === 0) {
                zero_int = true;
                digits = 1;
            }

            num = libbcmath.bc_new_num(digits, strscale);

            /* Build the whole number. */
            ptr = 0; // str
            if (str[ptr] === '-') {
                num.n_sign = libbcmath.MINUS;
                //(*num)->n_sign = MINUS;
                ptr++;
            } else {
                num.n_sign = libbcmath.PLUS;
                //(*num)->n_sign = PLUS;
                if (str[ptr] === '+') {
                    ptr++;
                }
            }
            while (str[ptr] === '0') {
                ptr++;            /* Skip leading zeros. */
            }

            nptr = 0; //(*num)->n_value;
            if (zero_int) {
                num.n_value[nptr++] = 0;
                digits = 0;
            }
            for (;digits > 0; digits--) {
                num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]);
            //*nptr++ = CH_VAL(*ptr++);
            }

            /* Build the fractional part. */
            if (strscale > 0) {
                ptr++;  /* skip the decimal point! */
                for (;strscale > 0; strscale--) {
                    num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]);
                }
            }

            return num;
        },

        cint: function(v) {
            if (typeof(v) == 'undefined') {
                v = 0;
            }
            var x=parseInt(v,10);
            if (isNaN(x)) {
                x = 0;
            }
            return x;
        },

        /**
         * Basic min function
         * @param {int} a
         * @param {int} b
         */
        MIN: function(a, b) {
            return ((a > b) ? b : a);
        },

        /**
         * Basic max function
         * @param {int} a
         * @param {int} b
         */
        MAX: function(a, b) {
            return ((a > b) ? a : b);
        },

        /**
         * Basic odd function
         * @param {int} a
         */
        ODD: function(a) {
            return (a & 1);
        },

        /**
         * replicate c function
         * @param {array} r     return (by reference)
         * @param {int} ptr
         * @param {string} chr    char to fill
         * @param {int} len       length to fill
         */
        memset: function(r, ptr, chr, len) {
            var i;
            for (i=0;i<len;i++) {
                r[ptr+i] = chr;
            }
        },

        /**
         * Replacement c function
         * Obviously can't work like c does, so we've added an "offset" param so you could do memcpy(dest+1, src, len) as memcpy(dest, 1, src, len)
         * Also only works on arrays
         */
        memcpy: function(dest, ptr, src, srcptr, len) {
            var i;
            for (i=0;i<len;i++) {
                dest[ptr+i]=src[srcptr+i];
            }
            return true;
        },


        /**
         * Determine if the number specified is zero or not
         * @param {bc_num} num    number to check
         * @return boolean      true when zero, false when not zero.
         */
        bc_is_zero: function(num) {
            var count; // int
            var nptr; // int

            /* Quick check. */
            //if (num == BCG(_zero_)) return TRUE;

            /* Initialize */
            count = num.n_len + num.n_scale;
            nptr = 0; //num->n_value;

            /* The check */
            while ((count > 0) && (num.n_value[nptr++] === 0)) {
                count--;
            }

            if (count !== 0) {
                return false;
            } else {
                return true;
            }
        },

        bc_out_of_memory: function() {
            throw new Error("(BC) Out of memory");
        }
    };
    return libbcmath;
}

function abs (mixed_number)  {
    // Return the absolute value of the number  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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 addcslashes (str, charlist) {
    // Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\n', '\r', '\t' etc...)  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/addcslashes
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %  note 1: We show double backslashes in the return value example code below because a JavaScript string will not
    // %  note 1: render them as backslashes otherwise
    // *     example 1: addcslashes('foo[ ]', 'A..z'); // Escape all ASCII within capital A to lower z range, including square brackets
    // *     returns 1: "\\f\\o\\o\\[ \\]"
    // *     example 2: addcslashes("zoo['.']", 'z..A'); // Only escape z, period, and A here since not a lower-to-higher range
    // *     returns 2: "\\zoo['\\.']"
    // *     example 3: addcslashes("@a\u0000\u0010\u00A9", "\0..\37!@\177..\377") == '\\@a\\000\\020\\302\\251'); // Escape as octals those specified and less than 32 (0x20) or greater than 126 (0x7E), but not otherwise
    // *     returns 3: true
    // *     example 4: addcslashes("\u0020\u007E", "\40..\175") == '\\ ~'); // Those between 32 (0x20 or 040) and 126 (0x7E or 0176) decimal value will be backslashed if specified (not octalized)
    // *     returns 4: true
    // *     example 5: addcslashes("\r\u0007\n", '\0..\37'); // Recognize C escape sequences if specified
    // *     returns 5: "\\r\\a\\n"
    // *     example 6: addcslashes("\r\u0007\n", '\0'); // Do not recognize C escape sequences if not specified
    // *     returns 7: "\r\u0007\n"
    var target = '', chrs = [], i = 0, j = 0, c = '', next = '', rangeBegin = '', rangeEnd = '', chr = '', begin = 0, end = 0,
                octalLength = 0, postOctalPos = 0, cca = 0, escHexGrp = [], encoded = '', percentHex = /%([\dA-Fa-f]+)/g;
    var _pad = function (n, c){
        if ( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };

    for (i=0; i < charlist.length; i++) {
        c = charlist.charAt(i);
        next = charlist.charAt(i+1);
        if (c === '\\' && next && (/\d/).test(next)) { // Octal
            rangeBegin = charlist.slice(i+1).match(/^\d+/)[0];
            octalLength = rangeBegin.length;
            postOctalPos = i+octalLength+1;
            if (charlist.charAt(postOctalPos)+charlist.charAt(postOctalPos+1) === '..' ) { // Octal begins range
                begin = rangeBegin.charCodeAt(0);
                if ((/\\\d/).test(charlist.charAt(postOctalPos+2)+charlist.charAt(postOctalPos+3))) { // Range ends with octal
                    rangeEnd = charlist.slice(postOctalPos+3).match(/^\d+/)[0];
                    i += 1; // Skip range end backslash
                }
                else if (charlist.charAt(postOctalPos+2)) { // Range ends with character
                    rangeEnd = charlist.charAt(postOctalPos+2);
                }
                else {
                    throw 'Range with no end point';
                }
                end = rangeEnd.charCodeAt(0);
                if (end > begin) { // Treat as a range
                    for (j=begin; j <= end; j++) {
                        chrs.push(String.fromCharCode(j));
                    }
                }
                else { // Supposed to treat period, begin and end as individual characters only, not a range
                    chrs.push('.', rangeBegin, rangeEnd);
                }
                i += rangeEnd.length+2; // Skip dots and range end (already skipped range end backslash if present)
            }
            else { // Octal is by itself
                chr = String.fromCharCode(parseInt(rangeBegin, 8));
                chrs.push(chr);
            }
            i += octalLength; // Skip range begin
        }
        else if (next+charlist.charAt(i+2) === '..') { // Character begins range
            rangeBegin = c;
            begin = rangeBegin.charCodeAt(0);
            if ((/\\\d/).test(charlist.charAt(i+3)+charlist.charAt(i+4))) { // Range ends with octal
                rangeEnd = charlist.slice(i+4).match(/^\d+/)[0];
                i += 1; // Skip range end backslash
            }
            else if (charlist.charAt(i+3)) { // Range ends with character
                rangeEnd = charlist.charAt(i+3);
            }
            else {
                throw 'Range with no end point';
            }
            end = rangeEnd.charCodeAt(0);
            if (end > begin) { // Treat as a range
                for (j=begin; j <= end; j++) {
                    chrs.push(String.fromCharCode(j));
                }
            }
            else { // Supposed to treat period, begin and end as individual characters only, not a range
                chrs.push('.', rangeBegin, rangeEnd);
            }
            i += rangeEnd.length+2; // Skip dots and range end (already skipped range end backslash if present)
        }
        else { // Character is by itself
            chrs.push(c);
        }
    }

    for (i = 0; i < str.length; i++) {
        c = str.charAt(i);
        if (chrs.indexOf(c) !== -1) {
            target += '\\';
            cca = c.charCodeAt(0);
            if (cca < 32 || cca > 126) { // Needs special escaping
                switch (c) {
                    case '\n': target += 'n'; break;
                    case '\t': target += 't'; break;
                    case '\u000D': target += 'r'; break;
                    case '\u0007': target += 'a'; break;
                    case '\v': target += 'v'; break;
                    case '\b': target += 'b'; break;
                    case '\f': target += 'f'; break;
                    default:                        
                        //target += _pad(cca.toString(8), 3);break; // Sufficient for UTF-16

                        encoded = encodeURIComponent(c);

                        // 3-length-padded UTF-8 octets
                        if ((escHexGrp = percentHex.exec(encoded)) !== null) {
                            target += _pad(parseInt(escHexGrp[1], 16).toString(8), 3); // already added a slash above
                        }
                        while ((escHexGrp = percentHex.exec(encoded)) !== null) {
                            target += '\\'+_pad(parseInt(escHexGrp[1], 16).toString(8), 3);
                        }
                        break;
                }
            }
            else { // Perform regular backslashed escaping
                target += c;
            }
        }
        else { // Just add the character unescaped
            target += c;
        }
    }
    return target;
}

function addslashes (str) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes  
    // 
    // version: 1003.2411
    // 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
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function aggregate (obj, class_name) {
    // !No description available for aggregate. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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;
   var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };

   if (typeof class_name === 'string') { // PHP behavior
       class_name = this.window[class_name];
   }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_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];
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_info (obj) {
    // !No description available for aggregate_info. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_info
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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='';
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };

    if (!this.php_js || !this.php_js.aggregateRecords || !this.php_js.aggregateKeys || !this.php_js.aggregateClasses) {
        return false; // Is this what is returned?
    }

    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    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) {
    // !No description available for aggregate_methods. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_methods
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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;
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_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];
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_methods_by_list (obj, class_name, properties_list, exclude) {
    // !No description available for aggregate_methods_by_list. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_methods_by_list
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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;
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_name));
    
    if (!properties_list.indexOf) {
        properties_list.indexOf = indexOf;
    }

    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];
            }
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_methods_by_regexp (obj, class_name, regexp, exclude) {
    // !No description available for aggregate_methods_by_regexp. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_methods_by_regexp
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %          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,
        indexOf = function (value) {
            for (var i = 0, length=this.length; i < length; i++) {
                if (this[i] === value) {
                    return i;
                }
            }
            return -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
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_name));
    
    for (p in class_name) {
        test = exclude ? p.search(regexp) === -1 : p.search(regexp) !== -1;
        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 ? p.search(regexp) === -1 : p.search(regexp) !== -1;
        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];
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_properties (obj, class_name) {
    // !No description available for aggregate_properties. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_properties
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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,
        indexOf = function (value) {
            for (var i = 0, length=this.length; i < length; i++) {
                if (this[i] === value) {
                    return i;
                }
            }
            return -1;
        };

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_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];
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_properties_by_list (obj, class_name, properties_list, exclude) {
    // !No description available for aggregate_properties_by_list. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_properties_by_list
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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,
        indexOf = function (value) {
            for (var i = 0, length=this.length; i < length; i++) {
                if (this[i] === value) {
                    return i;
                }
            }
            return -1;
        };
        
    if (!properties_list.indexOf) {
        properties_list.indexOf = indexOf;
    }

    if (typeof class_name === 'string') { // PHP behavior
        class_name = this.window[class_name];
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    // END REDUNDANT
    this.php_js.aggregateClasses.push(getFuncName(class_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];
            }
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregate_properties_by_regexp (obj, class_name, regexp, exclude) {
    // !No description available for aggregate_properties_by_regexp. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregate_properties_by_regexp
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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,
        indexOf = function (value) {
            for (var i = 0, length=this.length; i < length; i++) {
                if (this[i] === value) {
                    return i;
                }
            }
            return -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
    this.php_js = this.php_js || {};
    this.php_js.aggregateKeys = this.php_js.aggregateKeys || [];
    this.php_js.aggregateRecords = this.php_js.aggregateRecords || []; // Needed to allow deaggregate() and aggregate_info()
    this.php_js.aggregateClasses = this.php_js.aggregateClasses || [];
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    // END REDUNDANT

    for (p in class_name) {
        test = exclude ? p.search(regexp) === -1 : p.search(regexp) !== -1;
        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 ? p.search(regexp) === -1 : p.search(regexp) !== -1;
        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];
        }
    }
    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    pos = this.php_js.aggregateKeys.indexOf(obj);
    if (pos !== -1) {
        this.php_js.aggregateRecords[pos].push(record);
        this.php_js.aggregateClasses[pos].push(getFuncName(class_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(getFuncName(class_name));
    }
}

function aggregation_info (obj) {
    // !No description available for aggregation_info. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/aggregation_info
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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 this.aggregate_info(obj);
}

function array () {
    // !No description available for array. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_combine
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: array_combine([0,1,2], ['kevin','van','zonneveld']);
    // *     returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
   
    var new_array = {}, keycount = keys && keys.length, i = 0;

    // input sanitation
    if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects
        typeof keycount !== 'number' || typeof values.length !== 'number' ||
        !keycount){ // Require arrays to have a count
        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: 1003.2411
    // 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: 1003.2411
    // 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://brett-zamir.me)
    // *     example 1: array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
    // *     returns 1: {0:'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: 1003.2411
    // 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://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_diff_key
    // +   original by: Ates Goral (http://magnetiq.com)
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_diff_uassoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_diff_ukey
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_fill_keys
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_filter
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_intersect
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_intersect_assoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_intersect_key
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_intersect_uassoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_intersect_ukey
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_keys
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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: 1003.2411
    // 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://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_merge
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_merge_recursive
    // +   original by: Subhasis Deb
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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] = this.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];
// Fix: this function must be fixed like asort(), etc., to return a (shallow) copy by default, since IE does not support!

    // 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)) { // Keep extra parentheses around latter flags check to avoid minimization leading to CDATA closer
                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: 1003.2411
    // 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 (inputArr) {
    // Pops an element off the end of the array  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Theriault
    // %        note 1: While IE (and other browsers) support iterating an object's
    // %        note 1: own properties in order, if one attempts to add back properties
    // %        note 1: in IE, they may end up in their former position due to their position
    // %        note 1: being retained. So use of this function with "associative arrays"
    // %        note 1: (objects) may lead to unexpected behavior in an IE environment if
    // %        note 1: you add back properties with the same keys that you removed
    // *     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 = '', lastKey = '';

    if (inputArr.hasOwnProperty('length')) {
        // Indexed
        if (!inputArr.length){
            // Done popping, are we?
            return null;
        }
        return inputArr.pop();
    } else {
        // Associative
        for (key in inputArr) {
            if (inputArr.hasOwnProperty(key)) {
                lastKey = key;
            }
        }
        if (lastKey) {
            var tmp = inputArr[lastKey];
            delete(inputArr[lastKey]);
            return tmp;
        } else {
            return null;
        }
    }
}

function array_product ( input ) {
    // Returns the product of the array entries  
    // 
    // version: 1003.2411
    // 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 ( inputArr ) {
    // Pushes elements onto the end of the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/array_push
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Note also that IE retains information about property position even
    // %        note 1: after being supposedly deleted, so if you delete properties and then
    // %        note 1: add back properties with the same keys (including numeric) that had
    // %        note 1: been deleted, the order will be as before; thus, this function is not
    // %        note 1: really recommended with associative arrays (objects) in IE environments
    // *     example 1: array_push(['kevin','van'], 'zonneveld');
    // *     returns 1: 3
    var i=0, pr = '', argv = arguments, argc = argv.length,
            allDigits = /^\d$/, size = 0, highestIdx = 0, len = 0;
    if (inputArr.hasOwnProperty('length')) {
        for (i=1; i < argc; i++){
            inputArr[inputArr.length] = argv[i];
        }
        return inputArr.length;
    }
    
    // Associative (object)
    for (pr in inputArr) {
        if (inputArr.hasOwnProperty(pr)) {
            ++len;
            if (pr.search(allDigits) !== -1) {
                size = parseInt(pr, 10);
                highestIdx = size > highestIdx ? size : highestIdx;
            }
        }
    }
    for (i=1; i < argc; i++){
        inputArr[++highestIdx] = argv[i];
    }
    return len + i - 1;
}

function array_rand ( input, num_req ) {
    // Return key/keys for random entry/entries in the array  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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_replace (arr) {
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: array_replace(["orange", "banana", "apple", "raspberry"], {0 : "pineapple", 4 : "cherry"}, {0:"grape"});
    // *     returns 1: {0: 'grape', 1: 'banana', 2: 'apple', 3: 'raspberry', 4: 'cherry'}

    if (arguments.length < 2) {
        throw new Error('There should be at least 2 arguments passed to array_replace()');
    }

    // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself
    var retObj = {};
    for (var prop in arr) {
        retObj[prop] = arr[prop];
    }

    for (var i = 1; i < arguments.length; i++) {
        for (var p in arguments[i]) {
            retObj[p] = arguments[i][p];
        }
    }
    return retObj;
}

function array_replace_recursive (arr) {
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: array_replace_recursive({'citrus' : ["orange"], 'berries' : ["blackberry", "raspberry"]}, {'citrus' : ['pineapple'], 'berries' : ['blueberry']});
    // *     returns 1: {citrus : ['pineapple'], berries : ['blueberry', 'raspberry']}

    if (arguments.length < 2) {
        throw new Error('There should be at least 2 arguments passed to array_replace_recursive()');
    }

    // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself
    var retObj = {};
    for (var prop in arr) {
        retObj[prop] = arr[prop];
    }

    for (var i = 1; i < arguments.length; i++) {
        for (var p in arguments[i]) {
            if (typeof retObj[p] === 'object' && retObj[p] !== null) {
                retObj[p] = this.array_replace_recursive(retObj[p], arguments[i][p]);
            }
            else {
                retObj[p] = arguments[i][p];
            }
        }
    }
    return retObj;
}

function array_reverse (array, preserve_keys) {
    // Return input as a new array with the order of the entries reversed  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_search
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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 (inputArr) {
    // Pops an element off the beginning of the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/array_shift
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Martijn Wieringa
    // %        note 1: Currently does not handle objects
    // *     example 1: array_shift(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin'
    var props = false,
        shift = undefined, pr = '', allDigits = /^\d$/, int_ct=-1,
        _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 (inputArr.length === 0) {
        return null;
    }
    if (inputArr.length > 0) {
        return inputArr.shift();
    }

    /*
    UNFINISHED FOR HANDLING OBJECTS
    for (pr in inputArr) {
        if (inputArr.hasOwnProperty(pr)) {
            props = true;
            shift = inputArr[pr];
            delete inputArr[pr];
            break;
        }
    }
    for (pr in inputArr) {
        if (inputArr.hasOwnProperty(pr)) {
            if (pr.search(allDigits) !== -1) {
                int_ct += 1;
                if (parseInt(pr, 10) === int_ct) { // Key is already numbered ok, so don't need to change key for value
                    continue;
                }
                _checkToUpIndices(inputArr, int_ct, pr);
                arr[int_ct] = arr[pr];
                delete arr[pr];
            }
        }
    }
    if (!props) {
        return null;
    }
    return shift;
    */
}

function array_slice (arr, offst, lgth, preserve_keys) {
    // Returns elements specified by offset and length  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/array_slice
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: is_int
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_splice
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Theriault
    // %        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
    // %        note 1: not reliable anyways
    // %        note 2: Note also that IE retains information about property position even
    // %        note 2: after being supposedly deleted, so use of this function may produce
    // %        note 2: unexpected results in IE if you later attempt to add back properties
    // %        note 2: with the same keys that had been deleted
    // -    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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_udiff
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_udiff_assoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_udiff_uassoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_uintersect
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_uintersect_assoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/array_uintersect_uassoc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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 (inputArr) {
    // Removes duplicate values from array  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: The second argument, sort_flags is not implemented;
    // %          note 1: also should be sorted (asort?) first according to docs
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: {0: 'Kevin', 2: 'van', 3: '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_arr2 = {}, val = '';

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty(fkey)) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };

    for (key in inputArr) {
        if (inputArr.hasOwnProperty(key)) {
            val = inputArr[key];
            if (false === __array_search(val, tmp_arr2)) {
                tmp_arr2[key] = val;
            }
        }
    }

    return tmp_arr2;
}

function array_unshift (array) {
    // Pushes elements onto the beginning of the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/array_unshift
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Martijn Wieringa
    // %        note 1: Currently does not handle objects
    // *     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: 1003.2411
    // 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: 1003.2411
    // 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' || array === null) {
        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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/arsort
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        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
    // %        note 3: This function deviates from PHP in returning a copy of the array instead
    // %        note 3: of acting by reference and returning true; this was necessary because
    // %        note 3: IE does not allow deleting and re-adding of properties without caching
    // %        note 3: of property position; you can set the ini of "phpjs.strictForIn" to true to
    // %        note 3: get the PHP behavior, but use this only if you are in an environment
    // %        note 3: such as Firefox extensions where for-in iteration order is fixed and true
    // %        note 3: property deletion is supported. Note that we intend to implement the PHP
    // %        note 3: behavior by default if IE ever does allow it; only gives shallow copy since
    // %        note 3: is by reference in PHP anyways
    // -    depends on: i18n_loc_get_default
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: data = arsort(data);
    // *     returns 1: data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}
    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: arsort(data);
    // *     results 2: data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}
    // *     returns 2: true
    var valArr=[], keyArr=[], k, i, ret, sorter, that = this, strictForIn = false, populateArr = [];

    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)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            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;
                }
            }
        }
    };

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value;
    populateArr = strictForIn ? inputArr : populateArr;


    // Get key and value arrays
    for (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            valArr.push(inputArr[k]);
            keyArr.push(k);
            if (strictForIn) {
                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++) {
        populateArr[keyArr[i]] = valArr[i];
    }

    return strictForIn ? true : populateArr;
}

function asin (arg) {
    // Returns the arc sine of the number in radians  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/asort
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   input by: paulo kuong
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        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
    // %        note 3: This function deviates from PHP in returning a copy of the array instead
    // %        note 3: of acting by reference and returning true; this was necessary because
    // %        note 3: IE does not allow deleting and re-adding of properties without caching
    // %        note 3: of property position; you can set the ini of "phpjs.strictForIn" to true to
    // %        note 3: get the PHP behavior, but use this only if you are in an environment
    // %        note 3: such as Firefox extensions where for-in iteration order is fixed and true
    // %        note 3: property deletion is supported. Note that we intend to implement the PHP
    // %        note 3: behavior by default if IE ever does allow it; only gives shallow copy since
    // %        note 3: is by reference in PHP anyways
    // -    depends on: strnatcmp
    // -    depends on: i18n_loc_get_default
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: data = asort(data);
    // *     results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
    // *     returns 1: true
    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: asort(data);
    // *     results 2: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
    // *     returns 2: true
    var valArr=[], keyArr=[], k, i, ret, sorter, that = this, strictForIn = false, populateArr = [];

    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)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            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;
                }
            }
        }
    };

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value;
    populateArr = strictForIn ? inputArr : populateArr;

    // Get key and value arrays
    for (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            valArr.push(inputArr[k]);
            keyArr.push(k);
            if (strictForIn) {
                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++) {
        populateArr[keyArr[i]] = valArr[i];
    }

    return strictForIn ? true : populateArr;
}

function assert (assertion) {
    // Checks if assertion is false  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/assert
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    this.php_js.assert_values = this.php_js.assert_values || {};
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/assert_options
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: assert_options('ASSERT_CALLBACK');
    // *     returns 1: null
    
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    this.php_js.assert_values = this.php_js.assert_values || {};
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/atan2
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // 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: 1003.2411
    // 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://brett-zamir.me)
    // +   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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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'
    // *     example 2: basename('ecra.php?p=1');
    // *     returns 2: 'ecra.php?p=1'
    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 bcadd(left_operand, right_operand, scale) {
    // Returns the sum of two arbitrary precision numbers  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcadd
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcadd(1, 2);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bcadd', 1, '3', bcadd("1", "2"));
//        bcmath.test.result('bcadd', 2, '4.0000', bcadd("-1", "5", 4));
//        bcmath.test.result('bcadd', 3, '8728932003911564969352217864684.00', bcadd("1928372132132819737213", "8728932001983192837219398127471", 2));
//        bcmath.test.result('bcadd', 4, '3.357000', bcadd('1.123', '2.234', 6));

    var libbcmath = this._phpjs_shared_bc();

    var first, second, result;
    
    if (typeof(scale) == 'undefined') {
        scale = libbcmath.scale;
    }
    scale   = ((scale < 0) ? 0 : scale);

    // create objects
    first   = libbcmath.bc_init_num();
    second  = libbcmath.bc_init_num();
    result  = libbcmath.bc_init_num();

    first   = libbcmath.php_str2num(left_operand.toString());
    second  = libbcmath.php_str2num(right_operand.toString());


    result  = libbcmath.bc_add(first, second, scale);

    if (result.n_scale > scale) {
        result.n_scale = scale;
    }

    return result.toString();
}

function bccomp(left_operand, right_operand, scale) {
    // Compares two arbitrary precision numbers  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bccomp
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bccomp(1, 2);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bccomp', 1, -1, bccomp('-1','5', 4));
//        bcmath.test.result('bccomp', 2, -1, bccomp('1928372132132819737213', '8728932001983192837219398127471'));
//        bcmath.test.result('bccomp', 3,  0, bccomp('1.00000000000000000001', '1', 2));
//        bcmath.test.result('bccomp', 4,  1, bccomp('97321', '2321'));

    var libbcmath = this._phpjs_shared_bc();

    var first, second; //bc_num

    if (typeof(scale) == 'undefined') {
        scale = libbcmath.scale;
    }
    scale   = ((scale < 0) ? 0 : scale);

    first   = libbcmath.bc_init_num();
    second  = libbcmath.bc_init_num();

    first   = libbcmath.bc_str2num(left_operand.toString(), scale);     // note bc_ not php_str2num
    second  = libbcmath.bc_str2num(right_operand.toString(), scale);    // note bc_ not php_str2num

    return libbcmath.bc_compare(first, second, scale);
}

function bcdiv(left_operand, right_operand, scale) {
    // Returns the quotient of two arbitrary precision numbers (division)  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcdiv
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcdiv(1, 2);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bcdiv', 1, '0', bcdiv("1", "2"));
//        bcmath.test.result('bcdiv', 2, '0.50', bcdiv("1", "2", 2));
//        bcmath.test.result('bcdiv', 3, '-0.2000', bcdiv("-1", "5", 4));
//        bcmath.test.result('bcdiv', 4, '3333.3333', bcdiv("10000.0000", "3", 4));
//        bcmath.test.result('bcdiv', 5, '2387.8877', bcdiv("5573.33", "2.334", 4));
//        bcmath.test.result('bcdiv', 7, '1.00', bcdiv('6.00', '6.00', 2));
//        bcmath.test.result('bcdiv', 8, '1.00', bcdiv('2.00', '2.00', 2));
//        bcmath.test.result('bcdiv', 9, '59.51111111', bcdiv('66.95', '1.125', 8));
//        bcmath.test.result('bcdiv', 10, '4526580661.75', bcdiv('8728932001983192837219398127471.00', '1928372132132819737213.00', 2));
        
    var libbcmath = this._phpjs_shared_bc();

    var first, second, result;

    if (typeof(scale) == 'undefined') {
        scale = libbcmath.scale;
    }
    scale   = ((scale < 0) ? 0 : scale);

    // create objects
    first   = libbcmath.bc_init_num();
    second  = libbcmath.bc_init_num();
    result  = libbcmath.bc_init_num();

    first   = libbcmath.php_str2num(left_operand.toString());
    second  = libbcmath.php_str2num(right_operand.toString());

    result  = libbcmath.bc_divide(first, second, scale);
    if (result === -1) {
        // error
        throw new Error(11, "(BC) Division by zero");
    }
    if (result.n_scale > scale) {
        result.n_scale = scale;
    }
    return result.toString();
}

function bcmul(left_operand, right_operand, scale) {
    // Returns the multiplication of two arbitrary precision numbers  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcmul
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcmul(1, 2);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bcmul', 1, '2', bcmul("1", "2"));
//        bcmath.test.result('bcmul', 2, '-15', bcmul("-3", "5"));
//        bcmath.test.result('bcmul', 3, '12193263111263526900', bcmul("1234567890", "9876543210"));
//        bcmath.test.result('bcmul', 4, '3.75', bcmul("2.5", "1.5", 2));
//        bcmath.test.result('bcmul', 5, '13008.1522', bcmul("5573.33", "2.334", 4));

    var libbcmath = this._phpjs_shared_bc();

    var first, second, result;

    if (typeof(scale) == 'undefined') {
        scale = libbcmath.scale;
    }
    scale   = ((scale < 0) ? 0 : scale);

    // create objects
    first   = libbcmath.bc_init_num();
    second  = libbcmath.bc_init_num();
    result  = libbcmath.bc_init_num();

    first   = libbcmath.php_str2num(left_operand.toString());
    second  = libbcmath.php_str2num(right_operand.toString());

    result  = libbcmath.bc_multiply(first, second, scale);

    if (result.n_scale > scale) {
        result.n_scale = scale;
    }
    return result.toString();
}

function bcround(val, precision) {
    // !No description available for bcround. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcround
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcround(1, 2);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bcround', 1, '-2', bcround('-1.5', 0));
//        bcmath.test.result('bcround', 2, '-1.1235', bcround('-1.1234567', 4));
//        bcmath.test.result('bcround', 3, '2', bcround('1.5', 0));
//        bcmath.test.result('bcround', 4, '1.1235', bcround('1.1234567', 4));
//        bcmath.test.result('bcround', 5, '1', bcround('1.499999999', 0));
//        bcmath.test.result('bcround', 6, '2', bcround('1.5555555555555555555', 0));
//        bcmath.test.result('bcround', 7, '1.44', bcround('1.444999', 2));
//        bcmath.test.result('bcround', 8, '-1.44', bcround('-1.444999', 2));

    var libbcmath = this._phpjs_shared_bc();

    var temp, result, digit;
    var right_operand;

    // create number
    temp  = libbcmath.bc_init_num();
    temp  = libbcmath.php_str2num(val.toString());

    // check if any rounding needs
    if (precision >= temp.n_scale) {
        // nothing to round, just add the zeros.
        while (temp.n_scale < precision) {
            temp.n_value[temp.n_len+temp.n_scale]=0;
            temp.n_scale++;
        }
        return temp.toString();
    }

    // get the digit we are checking (1 after the precision)
    // loop through digits after the precision marker
    digit = temp.n_value[temp.n_len + precision];

    right_operand = libbcmath.bc_init_num();
    right_operand = libbcmath.bc_new_num(1, precision);

    if (digit >= 5) {
        //round away from zero by adding 1 (or -1) at the "precision".. ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5)
        right_operand.n_value[right_operand.n_len+right_operand.n_scale-1] = 1;
        if (temp.n_sign == libbcmath.MINUS) {
            // round down
            right_operand.n_sign = libbcmath.MINUS;
        }
        result  = libbcmath.bc_add(temp, right_operand, precision);
    } else {
        // leave-as-is.. just truncate it.
        result  = temp;
    }

    if (result.n_scale > precision) {
        result.n_scale = precision;
    }
    return result.toString();
}

function bcscale(scale) {
    // Sets default scale parameter for all bc math functions  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcscale
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)this.
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcscale(1);
    // *     returns 1: 3
//  @todo: implement these testcases
//        bcscale(0);
//
//        bcmath.test.result('bcscale', 1, false, bcscale('fail'));
//        bcmath.test.result('bcscale', 2, false, bcscale(-1));
//        bcmath.test.result('bcscale', 3, true, bcscale(5));
//        bcmath.test.result('bcscale', 4, true, bcscale(0));

    var libbcmath = this._phpjs_shared_bc();

    scale = parseInt(scale, 10);
    if (isNaN(scale)) {
        return false;
    }
    if (scale < 0) {
        return false;
    }
    libbcmath.scale = scale;
    return true;
}

function bcsub(left_operand, right_operand, scale) {
    // Returns the difference between two arbitrary precision numbers  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/bcsub
    // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
    // -    depends on: _phpjs_shared_bc
    // *     example 1: bcsub(1, 2);
    // *     returns 1: -1
//  @todo: implement these testcases
//        // set scale to zero
//        bcscale(0);
//
//        bcmath.test.result('bcsub', 1, '-1', bcsub('1','2'));
//        bcmath.test.result('bcsub', 2, '-6.0000', bcsub('-1','5', 4));
//        bcmath.test.result('bcsub', 3, '8728932000054820705086578390258.00', bcsub('8728932001983192837219398127471','1928372132132819737213', 2));
//        bcmath.test.result('bcsub', 4, '-1.111000', bcsub('1.123', '2.234', 6));
//        bcmath.test.result('bcsub', 5, '-2.20', bcsub('1.123456', '3.333333', 2)); //-2.209877 note: rounding not applicable as bcmath truncates.

    var libbcmath = this._phpjs_shared_bc();

    var first, second, result;

    if (typeof(scale) == 'undefined') {
        scale = libbcmath.scale;
    }
    scale   = ((scale < 0) ? 0 : scale);

    // create objects
    first   = libbcmath.bc_init_num();
    second  = libbcmath.bc_init_num();
    result  = libbcmath.bc_init_num();

    first   = libbcmath.php_str2num(left_operand.toString());
    second  = libbcmath.php_str2num(right_operand.toString());

    result  = libbcmath.bc_sub(first, second, scale);

    if (result.n_scale > scale) {
        result.n_scale = scale;
    }

    return result.toString();
}

function bin2hex (s){
    // Converts the binary representation of data to hex  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/call_user_func
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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(arguments, 1));
}

function call_user_func_array (cb, parameters) {
    // Call a user function which is the first parameter with the arguments contained in array  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // *     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: 1003.2411
    // 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 ( m, d, y ) {
    // Returns true(1) if it is a valid date in gregorian calendar  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/checkdate
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Pyerre
    // +   improved by: Theriault
    // *     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
    return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}

function chop ( str, charlist ) {
    // !No description available for chop. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/chr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     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, chunklen, end) {
    // Returns split line  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/chunk_split
    // +   original by: Paulo Ricardo F. Santos
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Theriault
    // *     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!*'
    
    chunklen = parseInt(chunklen, 10) || 76;
    end = end || '\r\n';

    if (chunklen < 1) {
        return false;
    }

    return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}

function class_alias (clss, alias, autoload) {
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: This function is not documented and only available in PHP source
    // *     example 1: function someFunc () {}
    // *     example 1: class_alias('someFunc', 'olFunc');
    // *     returns 1: true

    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    if (autoload && typeof this.window.__autoload === 'function') {
        this.window.__autoload(clss);
    }
    if (typeof clss === 'string') {
        clss = this.window[clss];
    }
    if (typeof clss === 'undefined') {
        throw "Class '"+getFuncName(clss)+"' not found";
        return false; // Return false until replace throw with error triggering
    }
    if (typeof clss !== 'function') {
        throw 'First argument of class_alias() must be a name of user defined class';
        return false;
    }
    if (typeof this.window[alias] === 'function') {
        throw 'Cannot redeclare class '+alias;
        return false;
    }

    this.window[alias] = clss;
    return true;
}

function class_exists (cls) {
    // Checks if the class exists  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/class_exists
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_import
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_method_add
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_method_copy
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_method_redefine
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_method_remove
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/classkit_method_rename
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/compact
    // +   original by: Waldo Malqui Silva
    // +    tweaked by: Jack
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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: 1003.2411
    // discuss at: http://phpjs.org/functions/constant
    // +   original by: Paulo Ricardo F. Santos
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     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_cyr_string (str, from, to) {
    // Convert from one Cyrillic character set to another  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/convert_cyr_string
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: Assumes and converts to Unicode strings with character
    // %          note 1: code equivalents of the same numbers as in the from or
    // %          note 1: target character set; Note that neither the input or output
    // %          note 1: should be treated as actual Unicode, since the PHP function
    // %          note 1: this is based on does not either
    // %          note 2: One could easily represent (or convert the results) of a
    // %          note 2: string form as arrays of code points instead but since JavaScript
    // %          note 2: currently has no clear binary data type, we chose to use strings
    // %          note 2: as in PHP
    // *     example 1: convert_cyr_string(String.fromCharCode(214), 'k', 'w').charCodeAt(0) === 230; // Char. 214 of KOI8-R gives equivalent number value 230 in win1251
    // *     returns 1: true
    var _cyr_win1251 = [
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
154,174,190,46,159,189,46,46,179,191,180,157,46,46,156,183,
46,46,182,166,173,46,46,158,163,152,164,155,46,46,46,167,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,184,186,32,179,191,32,32,32,32,32,180,162,32,
32,32,32,168,170,32,178,175,32,32,32,32,32,165,161,169,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206,
207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218,
],
_cyr_cp866 = [
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
35,35,35,124,124,124,124,43,43,124,124,43,43,43,43,43,
43,45,45,124,45,43,124,124,43,43,45,45,124,45,43,45,
45,45,45,43,43,43,43,43,43,43,43,35,35,124,124,35,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
179,163,180,164,183,167,190,174,32,149,158,32,152,159,148,154,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
205,186,213,241,243,201,32,245,187,212,211,200,190,32,247,198,
199,204,181,240,242,185,32,244,203,207,208,202,216,32,246,32,
238,160,161,230,164,165,228,163,229,168,169,170,171,172,173,174,
175,239,224,225,226,227,166,162,236,235,167,232,237,233,231,234,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
],
_cyr_iso88595 = [
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,179,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
32,163,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,241,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,161,32,32,32,32,32,32,32,32,32,32,32,32,
238,208,209,230,212,213,228,211,229,216,217,218,219,220,221,222,
223,239,224,225,226,227,214,210,236,235,215,232,237,233,231,234,
206,176,177,198,180,181,196,179,197,184,185,186,187,188,189,190,
191,207,192,193,194,195,182,178,204,203,183,200,205,201,199,202,
],
_cyr_mac = [
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,179,163,209,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,255,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
160,161,162,222,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,221,180,181,182,183,184,185,186,187,188,189,190,191,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,223,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
];

    var from_table = null, to_table = null, tmp, i=0, retStr = '';

    switch (from.toUpperCase()) {
        case 'W':
            from_table = _cyr_win1251;
            break;
        case 'A':
        case 'D':
            from_table = _cyr_cp866;
            break;
        case 'I':
            from_table = _cyr_iso88595;
            break;
        case 'M':
            from_table = _cyr_mac;
            break;
        case 'K':
            break;
        default:
            throw 'Unknown source charset: '+from; // warning
            break;
    }

    switch (to.toUpperCase()) {
        case 'W':
            to_table = _cyr_win1251;
            break;
        case 'A':
        case 'D':
            to_table = _cyr_cp866;
            break;
        case 'I':
            to_table = _cyr_iso88595;
            break;
        case 'M':
            to_table = _cyr_mac;
            break;
        case 'K':
            break;
        default:
            throw 'Unknown destination charset: '+ to; // fix: make a warning
    }

    if (!str) {
        return str;
    }

    for (i = 0; i < str.length; i++) {
        tmp = (from_table === null)? str.charAt(i) : String.fromCharCode(from_table[ str.charAt(i).charCodeAt(0) ]);
        retStr += (to_table === null) ? tmp : String.fromCharCode(to_table[tmp.charCodeAt(0)+256]);
    }
    return retStr;
}

function convert_uuencode (str){
    // uuencode a string  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // -    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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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 += this.count(mixed_var[key], 1);
        }
    }

    return cnt;
}

function count_chars (str, mode) {
    // Returns info about what characters are used in input  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Theriault
    // *     example 1: count_chars("Hello World!", 3);
    // *     returns 1: "!HWdelor"
    // *     example 2: count_chars("Hello World!", 1);
    // *     returns 2: {32:1,33:1,72:1,87:1,100:1,101:1,108:3,111:2,114:1}
    var result = {}, resultArr = [], i;

    str = ('' + str).split('').sort().join('').match(/(.)\1*/g);

    if ((mode & 1) == 0) {
        for (i = 0; i != 256; i++) {
             result[i] = 0;
        }
    }

    if (mode === 2 || mode === 4) {

        for (i = 0; i != str.length; i += 1) {
             delete result[str[i].charCodeAt(0)];
        }
        for (i in result) {
            result[i] = (mode === 4) ? String.fromCharCode(i) : 0;
        }

    } else if (mode === 3) {

        for (i = 0; i != str.length; i += 1) {
             result[i] = str[i].slice(0, 1);
        }

    } else {

        for (i = 0; i != str.length; i += 1) {
             result[str[i].charCodeAt(0)] = str[i].length;
        }

    }
    if (mode < 3) {
        return result;
    }

    for (i in result) {
       resultArr.push(result[i]);
    }
    return resultArr.join('');    
}

function crc32 ( str ) {
    // Calculate the crc32 polynomial of a string  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/create_function
    // +   original by: Johnny Mast (http://www.phpvrouwen.nl)
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/ctype_alnum
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: setlocale
    // *     example 1: ctype_alnum('AbC12');
    // *     returns 1: true
    if (typeof text !== 'string') {
        return false;
    }
    // BEGIN REDUNDANT
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
    // END REDUNDANT
    return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.an) !== -1;
}

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

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

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

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

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

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

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

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

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

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

function current (arr) {
    // Return the element currently pointed to by the internal array pointer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/current
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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'
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.pointers = this.php_js.pointers || [];
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };
    // END REDUNDANT
    var pointers = this.php_js.pointers;
    if (!pointers.indexOf) {
        pointers.indexOf = indexOf;
    }
    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: 1003.2411
    // 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://brett-zamir.me)
    // +   improved by: David Randall
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +  derived from: gettimeofday
    // +      input by: majak
    // +   bugfixed by: majak
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Alex
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +   improved by: Thomas Beaucourt  (http://www.webapp.fr)
    // +   improved by: JT
    // +   improved by: Theriault
    // %        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); 
    // *     example 4: (x+'').length == 10 // 2009 01 09
    // *     returns 4: true
    // *     example 5: date('W', 1104534000);
    // *     returns 5: '53'
    // *     example 6: date('B t', 1104534000);
    // *     returns 6: '999 31'
    // *     example 7: date('W', 1293750000); // 2010-12-31
    // *     returns 7: '52'
    // *     example 8: date('W', 1293836400); // 2011-01-01
    // *     returns 8: '52'
    // *     example 9: date('W Y-m-d', 1293974054); // 2011-01-02
    // *     returns 9: '52 2011-01-02'
    var that = this,
        jsdate, f, formatChr = /\\?([a-z])/gi, formatChrCb,
        // Keep this here (works, but for code commented-out
        // below for file size reasons)
        //, tal= [],
        _pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array((++c) - n.length).join("0") + n;
            } else {
                return n;
            }
        },
        txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"],
        txt_ordin = {
            1: "st",
            2: "nd",
            3: "rd",
            21: "st", 
            22: "nd",
            23: "rd",
            31: "st"
        };
    formatChrCb = function (t, s) {
        return f[t] ? f[t]() : s;
    };
    f = {
    // Day
        d: function () { // Day of month w/leading 0; 01..31
            return _pad(f.j(), 2);
        },
        D: function () { // Shorthand day name; Mon...Sun
            return f.l().slice(0, 3);
        },
        j: function () { // Day of month; 1..31
            return jsdate.getDate();
        },
        l: function () { // Full day name; Monday...Sunday
            return txt_words[f.w()] + 'day';
        },
        N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
            return f.w() || 7;
        },
        S: function () { // Ordinal suffix for day of month; st, nd, rd, th
            return txt_ordin[f.j()] || 'th';
        },
        w: function () { // Day of week; 0[Sun]..6[Sat]
            return jsdate.getDay();
        },
        z: function () { // Day of year; 0..365
            var a = new Date(f.Y(), f.n() - 1, f.j()),
                b = new Date(f.Y(), 0, 1);
            return Math.round((a - b) / 864e5) + 1;
        },

    // Week
        W: function () { // ISO-8601 week number
            var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
                b = new Date(a.getFullYear(), 0, 4);
            return 1 + Math.round((a - b) / 864e5 / 7);
        },

    // Month
        F: function () { // Full month name; January...December
            return txt_words[6 + f.n()];
        },
        m: function () { // Month w/leading 0; 01...12
            return _pad(f.n(), 2);
        },
        M: function () { // Shorthand month name; Jan...Dec
            return f.F().slice(0, 3);
        },
        n: function () { // Month; 1...12
            return jsdate.getMonth() + 1;
        },
        t: function () { // Days in month; 28...31
            return (new Date(f.Y(), f.n(), 0)).getDate();
        },

    // Year
        L: function () { // Is leap year?; 0 or 1
            var y = f.Y(), a = y & 3, b = y % 4e2, c = y % 1e2;
            return 0 + (!a && (c || !b));
        },
        o: function () { // ISO-8601 year
            var n = f.n(), W = f.W(), Y = f.Y();
            return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);
        },
        Y: function () { // Full year; e.g. 1980...2010
            return jsdate.getFullYear();
        },
        y: function () { // Last two digits of year; 00...99
            return (f.Y() + "").slice(-2);
        },

    // Time
        a: function () { // am or pm
            return jsdate.getHours() > 11 ? "pm" : "am";
        },
        A: function () { // AM or PM
            return f.a().toUpperCase();
        },
        B: function () { // Swatch Internet time; 000..999
            var H = jsdate.getUTCHours() * 36e2, // Hours
                i = jsdate.getUTCMinutes() * 60, // Minutes
                s = jsdate.getUTCSeconds(); // Seconds
            return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
        },
        g: function () { // 12-Hours; 1..12
            return f.G() % 12 || 12;
        },
        G: function () { // 24-Hours; 0..23
            return jsdate.getHours();
        },
        h: function () { // 12-Hours w/leading 0; 01..12
            return _pad(f.g(), 2);
        },
        H: function () { // 24-Hours w/leading 0; 00..23
            return _pad(f.G(), 2);
        },
        i: function () { // Minutes w/leading 0; 00..59
            return _pad(jsdate.getMinutes(), 2);
        },
        s: function () { // Seconds w/leading 0; 00..59
            return _pad(jsdate.getSeconds(), 2);
        },
        u: function () { // Microseconds; 000000-999000
            return _pad(jsdate.getMilliseconds() * 1000, 6);
        },

    // Timezone
        e: function () { // Timezone identifier; e.g. Atlantic/Azores, ...
// The following works, but requires inclusion of the very large
// timezone_abbreviations_list() function.
/*              var abbr = '', i = 0, os = 0;
            if (that.php_js && that.php_js.default_timezone) {
                return that.php_js.default_timezone;
            }
            if (!tal.length) {
                tal = that.timezone_abbreviations_list();
            }
            for (abbr in tal) {
                for (i = 0; i < tal[abbr].length; i++) {
                    os = -jsdate.getTimezoneOffset() * 60;
                    if (tal[abbr][i].offset === os) {
                        return tal[abbr][i].timezone_id;
                    }
                }
            }
*/
            return 'UTC';
        },
        I: function () { // DST observed?; 0 or 1
            // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
            // If they are not equal, then DST is observed.
            var a = new Date(f.Y(), 0), // Jan 1
                c = Date.UTC(f.Y(), 0), // Jan 1 UTC
                b = new Date(f.Y(), 6), // Jul 1
                d = Date.UTC(f.Y(), 6); // Jul 1 UTC
            return 0 + ((a - c) !== (b - d));
        },
        O: function () { // Difference to GMT in hour format; e.g. +0200
            var a = jsdate.getTimezoneOffset();
            return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4);
        },
        P: function () { // Difference to GMT w/colon; e.g. +02:00
            var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2));
        },
        T: function () { // Timezone abbreviation; e.g. EST, MDT, ...
// The following works, but requires inclusion of the very
// large timezone_abbreviations_list() function.
/*              var abbr = '', i = 0, os = 0, default = 0;
            if (!tal.length) {
                tal = that.timezone_abbreviations_list();
            }
            if (that.php_js && that.php_js.default_timezone) {
                default = that.php_js.default_timezone;
                for (abbr in tal) {
                    for (i=0; i < tal[abbr].length; i++) {
                        if (tal[abbr][i].timezone_id === default) {
                            return abbr.toUpperCase();
                        }
                    }
                }
            }
            for (abbr in tal) {
                for (i = 0; i < tal[abbr].length; i++) {
                    os = -jsdate.getTimezoneOffset() * 60;
                    if (tal[abbr][i].offset === os) {
                        return abbr.toUpperCase();
                    }
                }
            }
*/
            return 'UTC';
        },
        Z: function () { // Timezone offset in seconds (-43200...50400)
            return -jsdate.getTimezoneOffset() * 60;
        },

    // Full Date/Time
        c: function () { // ISO-8601 date.
            return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb);
        },
        r: function () { // RFC 2822
            return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
        },
        U: function () { // Seconds since UNIX epoch
            return Math.round(jsdate.getTime() / 1000);
        }
    };
    this.date = function (format, timestamp) {
        that = this;
        jsdate = (
            (typeof timestamp === 'undefined') ? new Date() : // Not provided
            (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
            new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
        );
        return format.replace(formatChr, formatChrCb);
    };
    return this.date(format, timestamp);
}

function date_default_timezone_get () {
    // !No description available for date_default_timezone_get. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/date_default_timezone_get
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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, curr_offset = -(new Date()).getTimezoneOffset()*60;

    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 === curr_offset) {
                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: 1003.2411
    // discuss at: http://phpjs.org/functions/date_default_timezone_set
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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;

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT
    // 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) {
    // Returns associative array with detailed info about given date  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/date_parse
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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}

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT

    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) {
    // !No description available for deaggregate. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/deaggregate
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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,
        indexOf = function (value) {
            for (var i = 0, length=this.length; i < length; i++) {
                if (this[i] === value) {
                    return i;
                }
            }
            return -1;
        },
        getFuncName = function (fn) {
            var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
            if (!name) {
                return '(Anonymous)';
            }
            return name[1];
        };

    if (!this.php_js || !this.php_js.aggregateRecords || !this.php_js.aggregateKeys || !this.php_js.aggregateClasses) {
        return;
    }

    if (!this.php_js.aggregateKeys.indexOf) {
        this.php_js.aggregateKeys.indexOf = indexOf;
    }
    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];
        }
        if (!this.php_js.aggregateClasses[idx].indexOf) {
            this.php_js.aggregateClasses[idx].indexOf = indexOf;
        }
        pos = this.php_js.aggregateClasses[idx].indexOf(getFuncName(class_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: 1003.2411
    // discuss at: http://phpjs.org/functions/decbin
    // +   original by: Enrique Gonzalez
    // +   bugfixed by: Onno Marsman
    // +   improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
    // +   input by: pilus
    // +   input by: nord_ua
    // *     example 1: decbin(12);
    // *     returns 1: '1100'
    // *     example 2: decbin(26);
    // *     returns 2: '11010'
    // *     example 3: decbin('26');
    // *     returns 3: '11010'
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(2);
}

function dechex (number) {
    // Returns a string containing a hexadecimal representation of the given number  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/dechex
    // +   original by: Philippe Baumann
    // +   bugfixed by: Onno Marsman
    // +   improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
    // +   input by: pilus
    // *     example 1: dechex(10);
    // *     returns 1: 'a'
    // *     example 2: dechex(47);
    // *     returns 2: '2f'
    // *     example 3: dechex(-1415723993);
    // *     returns 3: 'ab9dc427'
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(16);
}

function decoct (number) {
    // Returns a string containing an octal representation of the given number  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/decoct
    // +   original by: Enrique Gonzalez
    // +   bugfixed by: Onno Marsman
    // +   improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
    // +   input by: pilus
    // *     example 1: decoct(15);
    // *     returns 1: '17'
    // *     example 2: decoct(264); 
    // *     returns 2: '410'
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    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://brett-zamir.me)
    // *        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: 1003.2411
    // 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://brett-zamir.me)
    // %          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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/die
    // +   original by: Brett Zamir (http://brett-zamir.me)
    //  -   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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/doubleval
    // +   original by: Brett Zamir (http://brett-zamir.me)
    //  -   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: 1003.2411
    // discuss at: http://phpjs.org/functions/each
    // +   original by: Ates Goral (http://magnetiq.com) 
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // %        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
    
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.pointers = this.php_js.pointers || [];
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };
    // END REDUNDANT
    var pointers = this.php_js.pointers;
    if (!pointers.indexOf) {
        pointers.indexOf = indexOf;
    }
    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: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Eugene Bulkin (http://doubleaw.com/)
    // +   input by: JB
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: If browsers start to support DOM Level 3 Load and Save (parsing/serializing),
    // %        note 1: we wouldn't need any such long code (even most of the code below). See
    // %        note 1: link below for a cross-browser implementation in JavaScript. HTML5 might
    // %        note 1: possibly support DOMParser, but that is not presently a standard.
    // %        note 2: Although innerHTML is widely used and may become standard as of HTML5, it is also not ideal for
    // %        note 2: use with a temporary holder before appending to the DOM (as is our last resort below),
    // %        note 2: since it may not work in an XML context
    // %        note 3: Using innerHTML to directly add to the BODY is very dangerous because it will
    // %        note 3: break all pre-existing references to HTMLElements.
    // *     example 1: echo('<div><p>abc</p><p>abc</p></div>');
    // *     returns 1: undefined
    var arg = '', argc = arguments.length, argv = arguments, i = 0;
    var win = this.window;
    var d = win.document;
    var ns_xhtml = 'http://www.w3.org/1999/xhtml';
    var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; // If we're in a XUL context

    var holder;

    var stringToDOM = function (str, parent, ns, container) {
        var extraNSs = '';
        if (ns === ns_xul) {
            extraNSs = ' xmlns:html="'+ns_xhtml+'"';
        }
        var stringContainer = '<'+container+' xmlns="'+ns+'"'+extraNSs+'>'+str+'</'+container+'>';
        if (win.DOMImplementationLS &&
            win.DOMImplementationLS.createLSInput &&
            win.DOMImplementationLS.createLSParser) { // Follows the DOM 3 Load and Save standard, but not
            // implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
            // possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
            // attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
            var lsInput = DOMImplementationLS.createLSInput();
            // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
            lsInput.stringData = stringContainer;
            var lsParser = DOMImplementationLS.createLSParser(1, null); // synchronous, no schema type
            return lsParser.parse(lsInput).firstChild;
        }
        else if (win.DOMParser) {
            // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
            try {
                var fc = new DOMParser().parseFromString(stringContainer, 'text/xml');
                if (!fc || !fc.documentElement ||
                        fc.documentElement.localName !== 'parsererror' ||
                        fc.documentElement.namespaceURI !== 'http://www.mozilla.org/newlayout/xml/parsererror.xml') {
                    return fc.documentElement.firstChild;
                }
                // If there's a parsing error, we just continue on
            }
            catch(e) {
                // If there's a parsing error, we just continue on
            }
        }
        else if (win.ActiveXObject) { // We don't bother with a holder in Explorer as it doesn't support namespaces
            var axo = new ActiveXObject('MSXML2.DOMDocument');
            axo.loadXML(str);
            return axo.documentElement;
        }
        /*else if (win.XMLHttpRequest) { // Supposed to work in older Safari
            var req = new win.XMLHttpRequest;
            req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false);
            if (req.overrideMimeType) {
                req.overrideMimeType('application/xml');
            }
            req.send(null);
            return req.responseXML;
        }*/
        // Document fragment did not work with innerHTML, so we create a temporary element holder
        // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
        //if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways)
        if (d.createElementNS &&  // Browser supports the method
            d.documentElement.namespaceURI && (d.documentElement.namespaceURI !== null || // We can use if the document is using a namespace
            d.documentElement.nodeName.toLowerCase() !== 'html' || // We know it's not HTML4 or less, if the tag is not HTML (even if the root namespace is null)
            (d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace
        )) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document
            holder = d.createElementNS(ns, container);
        }
        else {
            holder = d.createElement(container); // Document fragment did not work with innerHTML
        }
        holder.innerHTML = str;
        while (holder.firstChild) {
            parent.appendChild(holder.firstChild);
        }
        return false;
        // throw 'Your browser does not support DOM parsing as required by echo()';
    };


    var ieFix = function (node) {
        if (node.nodeType === 1) {
            var newNode = d.createElement(node.nodeName);
            var i, len;
            if (node.attributes && node.attributes.length > 0) {
                for (i = 0, len = node.attributes.length; i < len; i++) {
                    newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
                }
            }
            if (node.childNodes && node.childNodes.length > 0) {
                for (i = 0, len = node.childNodes.length; i < len; i++) {
                    newNode.appendChild(ieFix(node.childNodes[i]));
                }
            }
            return newNode;
        }
        else {
            return d.createTextNode(node.nodeValue);
        }
    };

    for (i = 0; i < argc; i++ ) {
        arg = argv[i];
        if (this.php_js && this.php_js.ini && this.php_js.ini['phpjs.echo_embedded_vars']) {
            arg = arg.replace(/(.?)\{\$(.*?)\}/g, function (s, m1, m2) {
                // We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.)
                // Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
                if (m1 !== '\\') {
                    return m1+eval(m2);
                }
                else {
                    return s;
                }
            });
        }
        if (d.appendChild) {
            if (d.body) {
                if (win.navigator.appName == 'Microsoft Internet Explorer') { // We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended
                    d.body.appendChild(stringToDOM(ieFix(arg)));
                }
                else {
                    var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div').cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default)
                    if (unappendedLeft) {
                        d.body.appendChild(unappendedLeft);
                    }
                }
            } else {
                d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description')); // We will not actually append the description tag (just using for providing XUL namespace by default)
            }
        } else if (d.write) {
            d.write(arg);
        }/* else { // This could recurse if we ever add print!
            print(arg);
        }*/
    }
}

function empty (mixed_var) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // 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
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     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 ||
        typeof 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: 1003.2411
    // 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://brett-zamir.me)
    // %        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'
    
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.pointers = this.php_js.pointers || [];
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };
    // END REDUNDANT
    var pointers = this.php_js.pointers;
    if (!pointers.indexOf) {
        pointers.indexOf = indexOf;
    }
    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: 1003.2411
    // discuss at: http://phpjs.org/functions/error_get_last
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/error_reporting
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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 escapeshellarg(arg) {
    // Quote and escape an argument for use in a shell command  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/escapeshellarg
    // +   original by: Felix Geisendoerfer (http://www.debuggable.com/felix)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: escapeshellarg("kevin's birthday");
    // *     returns 1: "'kevin\'s birthday'"
    var ret = '';

    ret = arg.replace(/[^\\]'/g, function(m, i, s) {
            return m.slice(0, 1)+'\\\'';
    });

    return "'"+ret+"'";
}

function exit (status) {
    // !No description available for exit. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/exit
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/expm1
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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: 1003.2411
    // discuss at: http://phpjs.org/functions/extract
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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 targetObj = this.window;
    if (this.php_js && this.php_js.ini && this.php_js.ini['phpjs.extractTargetObj'] &&
        this.php_js.ini['phpjs.extractTargetObj'].local_value) { // Allow designated object to be used instead of window
        targetObj = this.php_js.ini['phpjs.extractTargetObj'].local_value;
    }
    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 (targetObj[i] !== undefined) {
                        if (prefixed.match(validIdent) !== null) {
                            targetObj[prefixed] = arr[i];
                            ++chng;
                        }
                    }
                    else {
                        targetObj[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_SKIP' || 1:
                    if (targetObj[i] === undefined) {
                        targetObj[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_ALL' || 3:
                    if (prefixed.match(validIdent) !== null) {
                        targetObj[prefixed] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_INVALID' || 4:
                    if (i.match(validIdent) !== null) {
                        if (prefixed.match(validIdent) !== null) {
                            targetObj[prefixed] = arr[i];
                            ++chng;
                        }
                    }
                    else {
                        targetObj[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_IF_EXISTS' || 6:
                    if (targetObj[i] !== undefined) {
                        targetObj[i] = arr[i];
                        ++chng;
                    }
                    break;
                case 'EXTR_PREFIX_IF_EXISTS' || 5:
                    if (targetObj[i] !== undefined && prefixed.match(validIdent) !== null) {
                        targetObj[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:
                    targetObj[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: 1003.2411
    // discuss at: http://phpjs.org/functions/fclose
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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
    }
    catch (e) {
        return false;
    }
    return true;
}

function feof (handle) {
    // Test for end-of-file on a file pointer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/feof
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/fgetc
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/fgetcsv
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // discuss at: http://phpjs.org/functions/fgets
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fgets(handle, 1);
    // *     returns 1: '<'

    var start=0, fullline='', endlinePos = -1, content = '';

    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
    }

    content = this.php_js.resourceData[handle.id].slice(start);

    endlinePos = content.search(/\r\n?|\n/)+start+1;
    fullline = this.php_js.resourceData[handle.id].slice(start, endlinePos+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;
    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: 1003.2411
    // discuss at: http://phpjs.org/functions/fgetss
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // 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: 1003.2411
    // 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, flags, context, offset, maxLen) {
    // Read the entire file into a string
    //
    // version: 906.111
    // 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)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Raphael (Ao) RUDLER
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain without modifications.
    // %        note 2: Synchronous by default (as in PHP) so may lock up browser. Can
    // %        note 2: get async by setting a custom "phpjs.async" property to true and "notification" for an
    // %        note 2: optional callback (both as context params, with responseText, and other JS-specific
    // %        note 2: request properties available via 'this'). Note that file_get_contents() will not return the text
    // %        note 2: in such a case (use this.responseText within the callback). Or, consider using
    // %        note 2: jQuery's: $('#divId').load('http://url') instead.
    // %        note 3: The context argument is only implemented for http, and only partially (see below for
    // %        note 3: "Presently unimplemented HTTP context options"); also the arguments passed to
    // %        note 3: notification are incomplete
    // *     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, flagNames = 0, content = null, http_stream = false;
    var func = function (value) { return value.substring(1) !== ''; };

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    var ini = this.php_js.ini;
    context = context || this.php_js.default_streams_context || null;

    if (!flags) {flags = 0;}
    var OPTS = {
        FILE_USE_INCLUDE_PATH : 1,
        FILE_TEXT : 32,
        FILE_BINARY : 64
    };
    if (typeof flags === 'number') { // Allow for a single string or an array of string flags
        flagNames = flags;
    }
    else {
        flags = [].concat(flags);
        for (i=0; i < flags.length; i++) {
            if (OPTS[flags[i]]) {
                flagNames = flagNames | OPTS[flags[i]];
            }
        }
    }

    if (flagNames & OPTS.FILE_BINARY && (flagNames & OPTS.FILE_TEXT)) { // These flags shouldn't be together
        throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()';
    }

    if ((flagNames & OPTS.FILE_USE_INCLUDE_PATH) && ini.include_path &&
            ini.include_path.local_value) {
        var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\';
        url = ini.include_path.local_value+slash+url;
    }
    else if (!/^(https?|file):/.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;
    }

    if (context) {
        var http_options = context.stream_options && context.stream_options.http;
        http_stream = !!http_options;
    }

    if (!context || http_stream) {
        var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
        if (!req) {throw new Error('XMLHttpRequest not supported');}

        var method = http_stream ? http_options.method : 'GET';
        var async = !!(context && context.stream_params && context.stream_params['phpjs.async']);
        
        if (ini['phpjs.ajaxBypassCache'] && ini['phpjs.ajaxBypassCache'].local_value) {
            url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(); // Give optional means of forcing bypass of cache
        }
        
        req.open(method, url, async);
        if (async) {
            var notification = context.stream_params.notification;
            if (typeof notification === 'function') {
                // Fix: make work with req.addEventListener if available: https://developer.mozilla.org/En/Using_XMLHttpRequest
                if (0 && req.addEventListener) { // Unimplemented so don't allow to get here
                    /*
                    req.addEventListener('progress', updateProgress, false);
                    req.addEventListener('load', transferComplete, false);
                    req.addEventListener('error', transferFailed, false);
                    req.addEventListener('abort', transferCanceled, false);
                    */
                }
                else {
                    req.onreadystatechange = function (aEvt) { // aEvt has stopPropagation(), preventDefault(); see https://developer.mozilla.org/en/NsIDOMEvent

    // Other XMLHttpRequest properties: multipart, responseXML, status, statusText, upload, withCredentials
    /*
    PHP Constants:
    STREAM_NOTIFY_RESOLVE   1       A remote address required for this stream has been resolved, or the resolution failed. See severity  for an indication of which happened.
    STREAM_NOTIFY_CONNECT   2     A connection with an external resource has been established.
    STREAM_NOTIFY_AUTH_REQUIRED 3     Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
    STREAM_NOTIFY_MIME_TYPE_IS  4     The mime-type of resource has been identified, refer to message for a description of the discovered type.
    STREAM_NOTIFY_FILE_SIZE_IS  5     The size of the resource has been discovered.
    STREAM_NOTIFY_REDIRECTED    6     The external resource has redirected the stream to an alternate location. Refer to message .
    STREAM_NOTIFY_PROGRESS  7     Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
    STREAM_NOTIFY_COMPLETED 8     There is no more data available on the stream.
    STREAM_NOTIFY_FAILURE   9     A generic error occurred on the stream, consult message and message_code for details.
    STREAM_NOTIFY_AUTH_RESULT   10     Authorization has been completed (with or without success).

    STREAM_NOTIFY_SEVERITY_INFO 0     Normal, non-error related, notification.
    STREAM_NOTIFY_SEVERITY_WARN 1     Non critical error condition. Processing may continue.
    STREAM_NOTIFY_SEVERITY_ERR  2     A critical error occurred. Processing cannot continue.
    */
                        var objContext = {
                            responseText : req.responseText,
                            responseXML : req.responseXML,
                            status : req.status,
                            statusText : req.statusText,
                            readyState : req.readyState,
                            evt : aEvt
                        }; // properties are not available in PHP, but offered on notification via 'this' for convenience

                        // notification args: notification_code, severity, message, message_code, bytes_transferred, bytes_max (all int's except string 'message')
                        // Need to add message, etc.
                        var bytes_transferred;
                        switch (req.readyState) {
                            case 0: //     UNINITIALIZED     open() has not been called yet.
                                notification.call(objContext, 0, 0, '', 0, 0, 0);
                                break;
                            case 1: //     LOADING     send() has not been called yet.
                                notification.call(objContext, 0, 0, '', 0, 0, 0);
                                break;
                            case 2: //     LOADED     send() has been called, and headers and status are available.
                                notification.call(objContext, 0, 0, '', 0, 0, 0);
                                break;
                            case 3: //     INTERACTIVE     Downloading; responseText holds partial data.
                                bytes_transferred = req.responseText.length*2; // One character is two bytes
                                notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0);
                                break;
                            case 4: //     COMPLETED     The operation is complete.
                                if (req.status >= 200 && req.status < 400) {
                                    bytes_transferred = req.responseText.length*2; // One character is two bytes
                                    notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0);
                                }
                                else if (req.status === 403) { // Fix: These two are finished except for message
                                    notification.call(objContext, 10, 2, '', req.status, 0, 0);
                                }
                                else { // Errors
                                    notification.call(objContext, 9, 2, '', req.status, 0, 0);
                                }
                                break;
                            default:
                                throw 'Unrecognized ready state for file_get_contents()';
                        }
                    }
                }
            }
        }

        if (http_stream) {
            var sendHeaders = http_options.header && http_options.header.split(/\r?\n/);
            var userAgentSent = false;
            for (i=0; i < sendHeaders.length; i++) {
                var sendHeader = sendHeaders[i];
                var breakPos = sendHeader.search(/:\s*/);
                var sendHeaderName = sendHeader.substring(0, breakPos);
                req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos+1));
                if (sendHeaderName === 'User-Agent') {
                    userAgentSent = true;
                }
            }
            if (!userAgentSent) {
                var user_agent = http_options.user_agent ||
                                                                    (ini.user_agent && ini.user_agent.local_value);
                if (user_agent) {
                    req.setRequestHeader('User-Agent', user_agent);
                }
            }
            content = http_options.content || null;
            /*
            // Presently unimplemented HTTP context options
            var request_fulluri = http_options.request_fulluri || false; // When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.
            var max_redirects = http_options.max_redirects || 20; // The max number of redirects to follow. Value 1 or less means that no redirects are followed.
            var protocol_version = http_options.protocol_version || 1.0; // HTTP protocol version
            var timeout = http_options.timeout || (ini.default_socket_timeout && ini.default_socket_timeout.local_value); // Read timeout in seconds, specified by a float
            var ignore_errors = http_options.ignore_errors || false; // Fetch the content even on failure status codes.
            */
        }

        if (flagNames & OPTS.FILE_TEXT) { // Overrides how encoding is treated (regardless of what is returned from the server)
            var content_type = 'text/html';
            if (http_options && http_options['phpjs.override']) { // Fix: Could allow for non-HTTP as well
                content_type = http_options['phpjs.override']; // We use this, e.g., in gettext-related functions if character set
                                                                                                        //   overridden earlier by bind_textdomain_codeset()
            }
            else {
                var encoding = (ini['unicode.stream_encoding'] && ini['unicode.stream_encoding'].local_value) || 'UTF-8';
                if (http_options && http_options.header && (/^content-type:/im).test(http_options.header)) { // We'll assume a content-type expects its own specified encoding if present
                    content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1]; // We let any header encoding stand
                }
                if (!(/;\s*charset=/).test(content_type)) { // If no encoding
                    content_type += '; charset='+encoding;
                }
            }
            req.overrideMimeType(content_type);
        }
        // Default is FILE_BINARY, but for binary, we apparently deviate from PHP in requiring the flag, since many if not
        //     most people will also want a way to have it be auto-converted into native JavaScript text instead
        else if (flagNames & OPTS.FILE_BINARY) { // Trick at https://developer.mozilla.org/En/Using_XMLHttpRequest to get binary
            req.overrideMimeType('text/plain; charset=x-user-defined');
            // Getting an individual byte then requires:
            // responseText.charCodeAt(x) & 0xFF; // throw away high-order byte (f7) where x is 0 to responseText.length-1 (see notes in our substr())
        }

        if (http_options && http_options['phpjs.sendAsBinary']) { // For content sent in a POST or PUT request (use with file_put_contents()?)
            req.sendAsBinary(content); // In Firefox, only available FF3+
        }
        else {
            req.send(content);
        }

        tmp = req.getAllResponseHeaders();
        if (tmp) {
            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
        }

        if (offset || maxLen) {
            if (maxLen) {
                return req.responseText.substr(offset || 0, maxLen);
            }
            return req.responseText.substr(offset);
        }
        return req.responseText;
    }
    return false;
}

function filemtime (file) {
    // +   original by: Ole Vrijenhoek (http://www.nervous.nl/)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // 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 (e2){
            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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/fmod
    // +   original by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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: 1003.2411
    // discuss at: http://phpjs.org/functions/fopen
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Paul Smith
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: file_get_contents
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     returns 1: 'Resource id #1'

    var resource={}, i=0, that = this;
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    // 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.charAt(i) === 'r' && (!mode.charAt(i+1) || mode.charAt(i+1) !== '+')) {
            continue;
        }
        switch (mode.charAt(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 '+getFuncName(arguments.caller)+'()';
        }
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.resourceData = this.php_js.resourceData || {};
    this.php_js.resourceDataPointer = this.php_js.resourceDataPointer || {};
    this.php_js.resourceIdCounter = this.php_js.resourceIdCounter || 0;
    // END REDUNDANT

    // BEGIN STATIC
    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.resourceIdCounter++;
    this.php_js.resourceData[this.php_js.resourceIdCounter] = this.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 forward_static_call (cb, parameters) {
    // !No description available for forward_static_call. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/forward_static_call
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: No real relevance to late static binding here; might also use call_user_func()
    // *     example 1: forward_static_call('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(arguments, 1));
}

function forward_static_call_array (cb, parameters) {
    // !No description available for forward_static_call_array. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/forward_static_call_array
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: No real relevance to late static binding here; might also use call_user_func_array()
    // *     example 1: forward_static_call_array('isNaN', ['a']);
    // *     returns 1: true
    // *     example 2: forward_static_call_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 fpassthru (handle) {
    // Output all remaining data from a file pointer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/fpassthru
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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]);
    this.echo(chrs);
    this.php_js.resourceDataPointer[handle.id] = this.php_js.resourceData[handle.id].length; // Place pointer at end
    return chrs;
}

function fread (handle, length) {
    // Binary-safe file read  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/fread
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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 fscanf (handle, format) {
    // Implements a mostly ANSI compatible fscanf()  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/fscanf
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: fgets
    // -    depends on: sscanf
    // *     example 1: var handle = fopen('http://example.com/names_and_professions.html', 'r');
    // *     example 1: fscanf(handle, '%s\t%s\t%s\n');
    // *     returns 1: ['robert', 'slacker', 'us']

    var mixed; // Could be an array or an integer

    mixed = this.sscanf.apply(this, [fgets(handle), format].concat(Array.prototype.slice.call(arguments, 2)));

    return mixed;
}

function fseek (handle, offset, whence) {
    // Seek on a file pointer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/fseek
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: var h = fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fseek(h, 100);
    // *     returns 1: 0

    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer ||
            !handle || !handle.constructor || getFuncName(handle.constructor) !== '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: 1003.2411
    // discuss at: http://phpjs.org/functions/ftell
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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

    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer ||
            !handle || !handle.constructor || getFuncName(handle.constructor) !== '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: 1003.2411
    // discuss at: http://phpjs.org/functions/func_get_arg
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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 (e2){
            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: 1003.2411
    // discuss at: http://phpjs.org/functions/func_get_args
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/func_num_args
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_cfg_var
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_class_methods
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_class_vars
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_declared_classes
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +    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://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_defined_functions
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_defined_vars
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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_extension_funcs (module_name) {
    // Returns an array with the names of functions belonging to the named extension  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/get_extension_funcs
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: get_extension_funcs('json');
    // *     returns 1: ['json_decode', 'json_encode', 'json_last_error']

    this.php_js = this.php_js || {};
    // We put this on the global in order to avoid rebuilding and reuse this object by itself
    this.php_js.exts = this.php_js.exts || { // This only includes those extensions for which we have or are working on at least some functions
        array: ['array_change_key_case','array_chunk','array_combine','array_count_values','array_diff_assoc','array_diff_key','array_diff_uassoc','array_diff_ukey','array_diff','array_fill_keys','array_fill','array_filter','array_flip','array_intersect_assoc','array_intersect_key','array_intersect_uassoc','array_intersect_ukey','array_intersect','array_key_exists','array_keys','array_map','array_merge_recursive','array_merge','array_multisort','array_pad','array_pop','array_product','array_push','array_rand','array_reduce','array_replace_recursive','array_replace','array_reverse','array_search','array_shift','array_slice','array_splice','array_sum','array_udiff_assoc','array_udiff_uassoc','array_udiff','array_uintersect_assoc','array_uintersect_uassoc','array_uintersect','array_unique','array_unshift','array_values','array_walk_recursive','array_walk','array','arsort','asort','compact','count','current','each','end','extract','in_array','key','krsort','ksort','list','natcasesort','natsort','next','pos','prev','range','reset','rsort','shuffle','sizeof','sort','uasort','uksort','usort'],
        bc: ['bcadd','bccomp','bcdiv','bcmod','bcmul','bcpow','bcpowmod','bcscale','bcsqrt','bcsub'],
        classkit: ['classkit_import','classkit_method_add','classkit_method_copy','classkit_method_redefine','classkit_method_remove','classkit_method_rename'],
        classobj: ['call_user_method_array','call_user_method','class_alias','class_exists','get_called_class','get_class_methods','get_class_vars','get_class','get_declared_classes','get_declared_interfaces','get_object_vars','get_parent_class','interface_exists','is_a','is_subclass_of','method_exists','property_exists'],
        ctype: ['ctype_alnum','ctype_alpha','ctype_cntrl','ctype_digit','ctype_graph','ctype_lower','ctype_print','ctype_punct','ctype_space','ctype_upper','ctype_xdigit'],
        datetime: ['checkdate','date_add','date_create_from_format','date_create','date_date_set','date_default_timezone_get','date_default_timezone_set','date_diff','date_format','date_get_last_errors','date_interval_create_from_date_string','date_interval_format','date_isodate_set','date_modify','date_offset_get','date_parse_from_format','date_parse','date_sub','date_sun_info','date_sunrise','date_sunset','date_time_set','date_timestamp_get','date_timestamp_set','date_timezone_get','date_timezone_set','date','getdate','gettimeofday','gmdate','gmmktime','gmstrftime','idate','localtime','microtime','mktime','strftime','strptime','strtotime','time','timezone_abbreviations_list','timezone_identifiers_list','timezone_location_get','timezone_name_from_abbr','timezone_name_get','timezone_offset_get','timezone_open','timezone_transitions_get','timezone_version_get'],
        dir : ['chdir','chroot','dir','closedir','getcwd','opendir','readdir','rewinddir','scandir'],
        errorfunc: ['debug_backtrace','debug_print_backtrace','error_get_last','error_log','error_reporting','restore_error_handler','restore_exception_handler','set_error_handler','set_exception_handler','trigger_error','user_error'],
        exec: ['escapeshellarg','escapeshellcmd','exec','passthru','proc_close','proc_get_status','proc_nice','proc_open','proc_terminate','shell_exec','system'],
        filesystem: ['basename','chgrp','chmod','chown','clearstatcache','copy','delete','dirname','disk_free_space','disk_total_space','diskfreespace','fclose','feof','fflush','fgetc','fgetcsv','fgets','fgetss','file_exists','file_get_contents','file_put_contents','file','fileatime','filectime','filegroup','fileinode','filemtime','fileowner','fileperms','filesize','filetype','flock','fnmatch','fopen','fpassthru','fputcsv','fputs','fread','fscanf','fseek','fstat','ftell','ftruncate','fwrite','glob','is_dir','is_executable','is_file','is_link','is_readable','is_uploaded_file','is_writable','is_writeable','lchgrp','lchown','link','linkinfo','lstat','mkdir','move_uploaded_file','parse_ini_file','parse_ini_string','pathinfo','pclose','popen','readfile','readlink','realpath','rename','rewind','rmdir','set_file_buffer','stat','symlink','tempnam','tmpfile','touch','umask','unlink'],
        funchand: ['call_user_func_array','call_user_func','create_function','forward_static_call_array','forward_static_call','func_get_arg','func_get_args','func_num_args','function_exists','get_defined_functions','register_shutdown_function','register_tick_function','unregister_tick_function'],
        // Moving to http://us.php.net/manual/en/class.locale.php ?
        i18n: ['locale_get_default','locale_set_default'],
        inclued: ['inclued_get_data'],
        info: ['assert_options','assert','dl','extension_loaded','gc_collect_cycles','gc_disable','gc_enable','gc_enabled','get_cfg_var','get_current_user','get_defined_constants','get_extension_funcs','get_include_path','get_included_files','get_loaded_extensions','get_magic_quotes_gpc','get_magic_quotes_runtime','get_required_files','getenv','getlastmod','getmygid','getmyinode','getmypid','getmyuid','getopt','getrusage','ini_alter','ini_get_all','ini_get','ini_restore','ini_set','magic_quotes_runtime','main','memory_get_peak_usage','memory_get_usage','php_ini_loaded_file','php_ini_scanned_files','php_logo_guid','php_sapi_name','php_uname','phpcredits','phpinfo','phpversion','putenv','restore_include_path','set_include_path','set_magic_quotes_runtime','set_time_limit','sys_get_temp_dir','version_compare','zend_logo_guid','zend_thread_id','zend_version'],
        json: ['json_decode', 'json_encode', 'json_last_error'],
        // Note that "language" is not a real extension, but part of the PHP language which we implement as JavaScript functions
        language: ['at','clone','declare','foreach','goto','include','include_once','php_user_filter','require','require_once','stdClass',
                            'ErrorException', 'Exception','HEREDOC',
                            '$_SESSION', '__CLASS__', '__DIR__', '__FILE__','__FUNCTION__','__LINE__','__METHOD__',
                            ],
        math: ['abs','acos','acosh','asin','asinh','atan2','atan','atanh','base_convert','bindec','ceil','cos','cosh','decbin','dechex','decoct','deg2rad','exp','expm1','floor','fmod','getrandmax','hexdec','hypot','is_finite','is_infinite','is_nan','lcg_value','log10','log1p','log','max','min','mt_getrandmax','mt_rand','mt_srand','octdec','pi','pow','rad2deg','rand','round','sin','sinh','sqrt','srand','tan','tanh'],
        misc: ['connection_aborted','connection_status','connection_timeout','constant','define','defined','die','eval','exit','get_browser','__halt_compiler','highlight_file','highlight_string','ignore_user_abort','pack','php_check_syntax','php_strip_whitespace','show_source','sleep','sys_getloadavg','time_nanosleep','time_sleep_until','uniqid','unpack','usleep'],
        'net-gopher' : ['gopher_parsedir'],
        network: ['checkdnsrr','closelog','define_syslog_variables','dns_check_record','dns_get_mx','dns_get_record','fsockopen','gethostbyaddr','gethostbyname','gethostbynamel','gethostname','getmxrr','getprotobyname','getprotobynumber','getservbyname','getservbyport','header_remove','header','headers_list','headers_sent','inet_ntop','inet_pton','ip2long','long2ip','openlog','pfsockopen','setcookie','setrawcookie','socket_get_status','socket_set_blocking','socket_set_timeout','syslog'],
        objaggregation: ['aggregate_info','aggregate_methods_by_list','aggregate_methods_by_regexp','aggregate_methods','aggregate_properties_by_list','aggregate_properties_by_regexp','aggregate_properties','aggregate','aggregation_info','deaggregate'],
        outcontrol: ['flush','ob_clean','ob_end_clean','ob_end_flush','ob_flush','ob_get_clean','ob_get_contents','ob_get_flush','ob_get_length','ob_get_level','ob_get_status','ob_gzhandler','ob_implicit_flush','ob_list_handlers','ob_start','output_add_rewrite_var','output_reset_rewrite_vars'],
        overload: ['overload'],
        pcre: ['preg_filter','preg_grep','preg_last_error','preg_match_all','preg_match','preg_quote','preg_replace_callback','preg_replace','preg_split'],
        runkit: ['Runkit_Sandbox','Runkit_Sandbox_Parent','runkit_class_adopt','runkit_class_emancipate','runkit_constant_add','runkit_constant_redefine','runkit_constant_remove','runkit_function_add','runkit_function_copy','runkit_function_redefine','runkit_function_remove','runkit_function_rename','runkit_import','runkit_lint_file','runkit_lint','runkit_method_add','runkit_method_copy','runkit_method_redefine','runkit_method_remove','runkit_method_rename','runkit_return_value_used','runkit_sandbox_output_handler','runkit_superglobals'],
        session: ['session_cache_expire','session_cache_limiter','session_commit','session_decode','session_destroy','session_encode','session_get_cookie_params','session_id','session_is_registered','session_module_name','session_name','session_regenerate_id','session_register','session_save_path','session_set_cookie_params','session_set_save_handler','session_start','session_unregister','session_unset','session_write_close'],
        stream: ['set_socket_blocking','stream_bucket_append','stream_bucket_make_writeable','stream_bucket_new','stream_bucket_prepend','stream_context_create','stream_context_get_default','stream_context_get_options','stream_context_get_params','stream_context_set_default','stream_context_set_option','stream_context_set_params','stream_copy_to_stream','stream_encoding','stream_filter_append','stream_filter_prepend','stream_filter_register','stream_filter_remove','stream_get_contents','stream_get_filters','stream_get_line','stream_get_meta_data','stream_get_transports','stream_get_wrappers','stream_is_local','stream_notification_callback','stream_register_wrapper','stream_resolve_include_path','stream_select','stream_set_blocking','stream_set_timeout','stream_set_write_buffer','stream_socket_accept','stream_socket_client','stream_socket_enable_crypto','stream_socket_get_name','stream_socket_pair','stream_socket_recvfrom','stream_socket_sendto','stream_socket_server','stream_socket_shutdown','stream_supports_lock','stream_wrapper_register','stream_wrapper_restore','stream_wrapper_unregister'],
        strings: ['addcslashes','addslashes','bin2hex','chop','chr','chunk_split','convert_cyr_string','convert_uudecode','convert_uuencode','count_chars','crc32','crypt','echo','explode','fprintf','get_html_translation_table','hebrev','hebrevc','html_entity_decode','htmlentities','htmlspecialchars_decode','htmlspecialchars','implode','join','lcfirst','levenshtein','localeconv','ltrim','md5_file','md5','metaphone','money_format','nl_langinfo','nl2br','number_format','ord','parse_str','print','printf','quoted_printable_decode','quoted_printable_encode','quotemeta','rtrim','setlocale','sha1_file','sha1','similar_text','soundex','sprintf','sscanf','str_getcsv','str_ireplace','str_pad','str_repeat','str_replace','str_rot13','str_shuffle','str_split','str_word_count','strcasecmp','strchr','strcmp','strcoll','strcspn','strip_tags','stripcslashes','stripos','stripslashes','stristr','strlen','strnatcasecmp','strnatcmp','strncasecmp','strncmp','strpbrk','strpos','strrchr','strrev','strripos','strrpos','strspn','strstr','strtok','strtolower','strtoupper','strtr','substr_compare','substr_count','substr_replace','substr','trim','ucfirst','ucwords','vfprintf','vprintf','vsprintf','wordwrap'],
        tokenizer: ['token_get_all','token_name'],
        url: ['base64_decode','base64_encode','get_headers','get_meta_tags','http_build_query','parse_url','rawurldecode','rawurlencode','urldecode','urlencode'],
        'var': ['debug_zval_dump','doubleval','empty','floatval','get_defined_vars','get_resource_type','gettype','import_request_variables','intval','is_array','is_binary','is_bool','is_buffer','is_callable','is_double','is_float','is_int','is_integer','is_long','is_null','is_numeric','is_object','is_real','is_resource','is_scalar','is_string','is_unicode','isset','print_r','serialize','settype','strval','unserialize','unset','var_dump','var_export'],
        xml: ['utf8_decode','utf8_encode','xml_error_string','xml_get_current_byte_index','xml_get_current_column_number','xml_get_current_line_number','xml_get_error_code','xml_parse_into_struct','xml_parse','xml_parser_create_ns','xml_parser_create','xml_parser_free','xml_parser_get_option','xml_parser_set_option','xml_set_character_data_handler','xml_set_default_handler','xml_set_element_handler','xml_set_end_namespace_decl_handler','xml_set_external_entity_ref_handler','xml_set_notation_decl_handler','xml_set_object','xml_set_processing_instruction_handler','xml_set_start_namespace_decl_handler','xml_set_unparsed_entity_decl_handler'],
        xmlreader: ['XMLReader'], // only in class form
        xmlwriter: ['xmlwriter_end_attribute','xmlwriter_end_cdata','xmlwriter_end_comment','xmlwriter_end_document','xmlwriter_end_dtd_attlist','xmlwriter_end_dtd_element','xmlwriter_end_dtd_entity','xmlwriter_end_dtd','xmlwriter_end_element','xmlwriter_end_pi','xmlwriter_flush','xmlwriter_full_end_element','xmlwriter_open_memory','xmlwriter_open_uri','xmlwriter_output_memory','xmlwriter_set_indent_string','xmlwriter_set_indent','xmlwriter_start_attribute_ns','xmlwriter_start_attribute','xmlwriter_start_cdata','xmlwriter_start_comment','xmlwriter_start_document','xmlwriter_start_dtd_attlist','xmlwriter_start_dtd_element','xmlwriter_start_dtd_entity','xmlwriter_start_dtd','xmlwriter_start_element_ns','xmlwriter_start_element','xmlwriter_start_pi','xmlwriter_text','xmlwriter_write_attribute_ns','xmlwriter_write_attribute','xmlwriter_write_cdata','xmlwriter_write_comment','xmlwriter_write_dtd_attlist','xmlwriter_write_dtd_element','xmlwriter_write_dtd_entity','xmlwriter_write_dtd','xmlwriter_write_element_ns','xmlwriter_write_element','xmlwriter_write_pi','xmlwriter_write_raw']
    };
    return this.php_js.exts[module_name] || false;
}

function get_headers (url, format) {
    // +   original by: Paulo Ricardo F. Santos
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          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 = {}, hash_map = {}, 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;
    }

    entities['38'] = '&amp;';
    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;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function get_include_path () {
    // !No description available for get_include_path. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/get_include_path
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: get_include_path();
    // *     returns 1: '/phpjs'

    if (this.php_js && this.php_js.ini && this.php_js.ini.include_path && this.php_js.ini.include_path.local_value) {
        return this.php_js.ini.include_path.local_value;
    }
    return '';
}

function get_included_files () {
    // Returns an array with the file names that were included (includes require and once varieties)  
    // 
    // version: 1003.2411
    // 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_meta_tags (file) {
    // Extracts all meta tag content attributes from a file and returns an array
    //
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/get_meta_tags
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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.
    // -    depends on: file_get_contents
    // *     example 1: get_meta_tags('http://kevin.vanzonneveld.net/pj_test_supportfile_2.htm');
    // *     returns 1: {description: 'a php manual', author: 'name', keywords: 'php documentation', 'geo_position': '49.33;-86.59'}
    var fulltxt = '';

    if (false) {
        // Use this for testing instead of the line above:
        fulltxt = '<meta name="author" content="name">'+
        '<meta name="keywords" content="php documentation">'+
        '<meta name="DESCRIPTION" content="a php manual">'+
        '<meta name="geo.position" content="49.33;-86.59">'+
        '</head>';
    } else {
        fulltxt = this.file_get_contents(file).match(/^[\s\S]*<\/head>/i); // We have to disallow some character, so we choose a Unicode non-character
    }

    var patt = /<meta[^>]*?>/gim;
    var patt1 = /<meta\s+.*?name\s*=\s*(['"]?)(.*?)\1\s+.*?content\s*=\s*(['"]?)(.*?)\3/gim;
    var patt2 = /<meta\s+.*?content\s*=\s*(['"?])(.*?)\1\s+.*?name\s*=\s*(['"]?)(.*?)\3/gim;
    var txt, match, name, arr={};

    while ((txt = patt.exec(fulltxt)) !== null) {
        while ((match = patt1.exec(txt)) !== null) {
            name = match[2].replace(/\W/g, '_').toLowerCase();
            arr[name] = match[4];
        }
        while ((match = patt2.exec(txt)) !== null) {
            name = match[4].replace(/\W/g, '_').toLowerCase();
            arr[name] = match[2];
        }
    }
    return arr;
}

function get_object_vars (obj) {
    // Returns an array of object properties  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/get_object_vars
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_required_files
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // discuss at: http://phpjs.org/functions/get_resource_type
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: get_resource_type('a');
    // *     returns 1: false
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    if (!handle || typeof handle !== 'object' || !handle.constructor || getFuncName(handle.constructor) !== 'PHPJS_Resource') {
        return false;
    }

    return handle.get_resource_type();
}

function getdate (timestamp) {
    // Get date/time information  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/getdate
    // +   original by: Paulo Ricardo F. Santos
    // +   input by: Alex
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     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) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'object') ? new Date(timestamp) : // Javascript Date()
        new Date(timestamp*1000) // UNIX timestamp (auto-convert to int)
    );
    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) {
    // Get the value of an environment variable  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/getenv
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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 () {
    // Get time of last page modification  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/getlastmod
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 909.322
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/gettimeofday
    // + original by: Brett Zamir (http://brett-zamir.me)
    // +      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)
    // +  revised by: Theriault
    // *   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(), y = 0;

    if (return_float) {
        return t.getTime() / 1000;
    }

    y = t.getFullYear(); // Store current year.

    return {
        sec : t.getUTCSeconds(),
        usec : t.getUTCMilliseconds() * 1000,
        minuteswest : t.getTimezoneOffset(),
        // Compare Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC to see if DST is observed.
        dsttime : 0 + (((new Date(y, 0)) - Date.UTC(y, 0)) !== ((new Date(y, 6)) - Date.UTC(y, 6)))
    };
}

function gettype (mixed_var) {
    // Returns the type of the variable  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // -    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;
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    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 && getFuncName(mixed_var.constructor)) {
                name = getFuncName(mixed_var.constructor);
                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: 1003.2411
    // discuss at: http://phpjs.org/functions/gmdate
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Alex
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    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) == 'object') ? new Date(timestamp) : // Javascript Date()
        new Date(timestamp*1000) // UNIX timestamp (auto-convert to int)
    );
    timestamp = Date.parse(dt.toUTCString().slice(0, -4))/1000;
    return this.date(format, timestamp);
}

function gmmktime() {
    // Get UNIX timestamp for a GMT date  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/gmmktime
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   derived from: mktime
    // *     example 1: gmmktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201875002
    // *     example 2: gmmktime(0, 0, -1, 1, 1, 1970);
    // *     returns 2: -1
    var d = new Date(), r = arguments, i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];

    for (i = 0; i < e.length; i++) {
        if (typeof r[i] === 'undefined') {
            r[i] = d['getUTC' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        } else {
            r[i] = parseInt(r[i], 10);
            if (isNaN(r[i])) {
                return false;
            }
        }
    }
    
    // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000.
    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
    
    // Set year, month (-1 to fix JS months), and date.
    // !This must come before the call to setHours!
    d.setUTCFullYear(r[5], r[3] - 1, r[4]);
    
    // Set hours, minutes, and seconds.
    d.setUTCHours(r[0], r[1], r[2]);

    // Divide milliseconds by 1000 to return seconds and drop decimal.
    // Add 1 second if negative or it'll be off from PHP by 1 second.
    return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
}

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

function gopher_parsedir (dirent) {
    // !No description available for gopher_parsedir. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/gopher_parsedir
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // 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: 1003.2411
    // 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)
    // +      input by: Ratheous
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Nick Kolosov (http://sammy.ru)
    // +   bugfixed by: Fox
    // -    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 hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';

    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 1003.2411
    // 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)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    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 hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
    // Convert special characters to HTML entities  
    // 
    // version: 1003.2411
    // 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)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}

function htmlspecialchars_decode (string, quote_style) {
    // Convert special HTML entities back to characters  
    // 
    // version: 1003.2411
    // 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)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');

    return string;
}

function http_build_query (formdata, numeric_prefix, arg_separator) {
    // Generates a form-encoded query string from an associative array or object.  
    // 
    // version: 1003.2411
    // 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)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +    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 (val !== null && 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);
        } else {
            throw new Error('There was an error processing for http_build_query().');
        }
    };

    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: 909.322
    // 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 i18n_loc_get_default () {
    // !No description available for i18n_loc_get_default. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/i18n_loc_get_default
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: Renamed in PHP6 from locale_get_default(). Not listed yet at php.net
    // %          note 2: List of locales at http://demo.icu-project.org/icu-bin/locexp
    // %          note 3: To be usable with sort() if it is passed the SORT_LOCALE_STRING sorting flag: http://php.net/manual/en/function.sort.php
    // -    depends on: i18n_loc_set_default
    // *     example 1: i18n_loc_get_default();
    // *     returns 1: 'en_US_POSIX'

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT
    return this.php_js.i18nLocale || (i18n_loc_set_default('en_US_POSIX'), 'en_US_POSIX'); // Ensure defaults are set up
}

function i18n_loc_set_default (name) {
    // !No description available for i18n_loc_set_default. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/i18n_loc_set_default
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: Renamed in PHP6 from locale_set_default(). Not listed yet at php.net
    // %          note 2: List of locales at http://demo.icu-project.org/icu-bin/locexp (use for implementing other locales here)
    // %          note 3: To be usable with sort() if it is passed the SORT_LOCALE_STRING sorting flag: http://php.net/manual/en/function.sort.php
    // *     example 1: i18n_loc_set_default('pt_PT');
    // *     returns 1: true

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT

    this.php_js.i18nLocales = {
        en_US_POSIX : {
            sorting :
                function ( str1, str2 ) { // Fix: This one taken from strcmp, but need for other locales; we don't use localeCompare since its locale is not settable
                    return ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 );
                }
        }
    };

    this.php_js.i18nLocale = name;
    return true;
}

function idate(format, timestamp) {
    // Format a local time/date as integer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/idate
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Alex
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +  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
        (timestamp instanceof Date) ? new Date(timestamp) : // Javascript Date()
        new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
    ), a;

    switch (format) {
        case 'B':
            return Math.floor(((date.getUTCHours() * 36e2) + (date.getUTCMinutes() * 60) +
                                                date.getUTCSeconds() + 36e2) / 86.4) % 1e3;
        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'
            // Logic derived from getimeofday().
            // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
            // If they are not equal, then DST is observed.
            a = date.getFullYear();
            return 0 + (((new Date(a, 0)) - Date.UTC(a, 0)) !== ((new Date(a, 6)) - Date.UTC(a, 6)));
        case 'L':
            a = date.getFullYear();
            return (!(a & 3) && (a % 1e2 || !(a % 4e2))) ? 1 : 0;
        case 'm':
            return date.getMonth() + 1;
        case 's':
            return date.getSeconds();
        case 't':
            return (new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate();
        case 'U':
            return Math.round(date.getTime() / 1000);
        case 'w':
            return date.getDay();
        case 'W':
            a = new Date(date.getFullYear(), date.getMonth(), date.getDate() - (date.getDay() || 7) + 3);
            return 1 + Math.round((a - (new Date(a.getFullYear(), 0, 4))) / 864e5 / 7);
        case 'y':
            return parseInt((date.getFullYear() + '').slice(2), 10); // This function returns an integer, unlike date()
        case 'Y':
            return date.getFullYear();
        case 'z':
            return Math.floor((date - new Date(date.getFullYear(), 0, 1)) / 864e5);
        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: 1003.2411
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}

function import_request_variables (types, prefix) {
    // Import GET/POST/Cookie variables into the global scope  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/import_request_variables
    // +      original by: Jalal Berrami
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // + improved by: Brett Zamir (http://brett-zamir.me)
    // %          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, requestObj = this.window, getObj = false, cookieObj = false;
    prefix = prefix || '';

    var that = this;
    var _ini_get = function (ini) {
        if (that.php_js && that.php_js.ini && that.php_js.ini[ini] &&
            that.php_js.ini[ini].local_value) { // Allow designated object to be used instead of window
            return that.php_js.ini[ini].local_value;
        }
        return false;
    };

    requestObj = _ini_get('phpjs.requestVarsObj') || requestObj;
    if (/g/i.test(types)) { // GET
        getObj = _ini_get('phpjs.getVarsObj') || getObj;
        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 (!requestObj[prefix+arrName]) {
                    requestObj[prefix+arrName] = [];
                }
                requestObj[prefix+arrName].push(current[1] || null);
                if (getObj) {
                    if (!getObj[prefix+arrName]) {
                        getObj[prefix+arrName] = [];
                    }
                    getObj[prefix+arrName].push(current[1] || null);
                }
            }
            else {
                current[0] = decodeURIComponent(current[0]);
                requestObj[prefix+current[0]] = current[1] || null;
                if (getObj) {
                    getObj[prefix+current[0]] = current[1] || null;
                }
            }
        }
    }
    if (/c/i.test(types)) { // COOKIE
        cookieObj = _ini_get('phpjs.cookieVarsObj') || cookieObj;
        for (i = 0, vars = win.document.cookie.split("&"); i < vars.length;i++){
            current = vars[i].split("=");
            requestObj[prefix+current[0]] = current[1].split(";")[0] || null;
            if (cookieObj) {
                cookieObj[prefix+current[0]] = current[1].split(";")[0] || null;
            }
        }
    }
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function include (filename) {
    // !No description available for include. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // +   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] ?
            d.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'head')[0].appendChild(js) :
            d.documentElement.insertBefore(js, d.documentElement.firstChild) // in case of XUL
        ):
        d.getElementsByTagName('head')[0].appendChild(js);
    // save include state for reference by include_once
    var cur_file = {};
    cur_file[this.window.location.href] = 1;

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT
    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: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: include
    // %        note 1: Uses global: php_js to keep track of included files (though private static variable in namespaced version)
    // *     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;

    // BEGIN STATIC
    try { // We can't try to access on window, since it might not exist in some environments, and if we use "this.window"
            //    we risk adding another copy if different window objects are associated with the namespaced object
        php_js_shared; // Will be private static variable in namespaced version or global in non-namespaced
                                       //   version since we wish to share this across all instances
    }
    catch(e) {
        php_js_shared = {};
    }
    // END STATIC
    
    if (!php_js_shared.includes) {
        php_js_shared.includes = cur_file;
    }
    if (!php_js_shared.includes[filename]) {
        if (this.include(filename)){
            return true;
        }
    } else{
        return true;
    }
    return false;
}

function inet_ntop(a) {
    // Converts a packed inet address to a human readable IP address string  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/inet_ntop
    // +   original by: Theriault
    // *     example 1: inet_ntop('\x7F\x00\x00\x01');
    // *     returns 1: '127.0.0.1'
    // *     example 2: inet_ntop('\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1');
    // *     returns 2: '::1'
    
    var i = 0, m = '', c = [];
    a += '';
    if (a.length === 4) { // IPv4
        return [
            a.charCodeAt(0),
            a.charCodeAt(1),
            a.charCodeAt(2),
            a.charCodeAt(3)
        ].join('.');
    } else if (a.length === 16) { // IPv6
        for (i = 0; i < 16; i++) {
            c.push(((a.charCodeAt(i++) << 8) + a.charCodeAt(i)).toString(16));
        }
        return c.join(':').replace(/((^|:)0(?=:|$))+:?/g, function (t) {
            m = (t.length > m.length) ? t : m;
            return t;
        }).replace(m || ' ', '::');
    } else { // Invalid length
        return false;
    }
}

function inet_pton(a) {
    // Converts a human readable IP address to a packed binary string  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/inet_pton
    // +   original by: Theriault
    // *     example 1: inet_pton('::');
    // *     returns 1: '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0' (binary)
    // *     example 2: inet_pton('127.0.0.1');
    // *     returns 2: '\x7F\x00\x00\x01' (binary)
    var r, m, x, i, j, f = String.fromCharCode;
    m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/);  // IPv4
    if (m) {
        m = m[0].split('.');
        m = f(m[0]) + f(m[1]) + f(m[2]) + f(m[3]);
        // Return if 4 bytes, otherwise false.
        return m.length === 4 ? m : false;
    }
    r = /^((?:[\da-f]{1,4}(?::|)){0,8})(::)?((?:[\da-f]{1,4}(?::|)){0,8})$/;
    m = a.match(r); // IPv6
    if (m) {
        // Translate each hexadecimal value.
        for (j = 1; j < 4; j++) {
            // Indice 2 is :: and if no length, continue.
            if (j === 2 || m[j].length === 0) {
                continue;
            }
            m[j] = m[j].split(':');
            for (i = 0; i < m[j].length; i++) {
                m[j][i] = parseInt(m[j][i], 16);
                // Would be NaN if it was blank, return false.
                if (isNaN(m[j][i])) {
                    return false; // Invalid IP.
                }
                m[j][i] = f(m[j][i] >> 8) + f(m[j][i] & 0xFF);
            }
            m[j] = m[j].join('');
        }
        x = m[1].length + m[3].length;
        if (x === 16) {
            return m[1] + m[3];
        } else if (x < 16 && m[2].length > 0) {
            return m[1] + (new Array(16 - x + 1)).join('\x00') + m[3];
        }
    }
    return false; // Invalid IP.
}

function ini_alter (varname, newvalue) {
    // !No description available for ini_alter. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/ini_alter
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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: 1003.2411
    // discuss at: http://phpjs.org/functions/ini_get
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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: 1003.2411
    // discuss at: http://phpjs.org/functions/ini_get_all
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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;
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    if (extension) {
        extPattern = new RegExp('^'+extension+'\\.');
        for (key in this.php_js.ini) {
            extPattern.lastIndex = 0;
            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) {
    // Restore the value of a configuration option specified by varname  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/ini_restore
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/ini_set
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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 = '', that = this;
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    this.php_js.ini[varname] = this.php_js.ini[varname] || {};
    oldval = this.php_js.ini[varname].local_value;
    
    var _setArr = function (oldval) { // Although these are set individually, they are all accumulated
        if (typeof oldval === 'undefined') {
            that.php_js.ini[varname].local_value = [];
        }
        that.php_js.ini[varname].local_value.push(newvalue);
    };

    switch (varname) {
        case 'extension':
            if (typeof this.dl === 'function') {
                this.dl(newvalue); // This function is only experimental in php.js
            }
            _setArr(oldval, newvalue);
            break;
        default:
            this.php_js.ini[varname].local_value = newvalue;
            break;
    }
    return oldval;
}

function intval (mixed_var, base) {
    // Get the integer value of a variable using the optional base for the conversion  
    // 
    // version: 1003.2411
    // 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)
    // +   input by: Matteo
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     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
    // *     example 5: intval('1e', 16);
    // *     returns 5: 30
    var tmp;

    var type = typeof( mixed_var );

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

function ip2long(IP) {
    // Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/ip2long
    // +   original by: Waldo Malqui Silva
    // +   improved by: Victor
    // +    revised by: fearphage (http://http/my.opera.com/fearphage/)
    // +    revised by: Theriault
    // *     example 1: ip2long('192.0.34.166');
    // *     returns 1: 3221234342
    // *     example 2: ip2long('0.0xABCDEF');
    // *     returns 2: 11259375
    // *     example 3: ip2long('255.255.255.256');
    // *     returns 3: false
    var i = 0;
    // PHP allows decimal, octal, and hexadecimal IP components.
    // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
    IP = IP.match(/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i); // Verify IP format.
    if (!IP) {
        return false; // Invalid format.
    }
    // Reuse IP variable for component counter.
    IP[0] = 0;
    for (i = 1; i < 5; i += 1) {
        IP[0] += !!((IP[i] || '').length);
        IP[i] = parseInt(IP[i]) || 0;
    }
    // Continue to use IP for overflow values.
    // PHP does not allow any component to overflow.
    IP.push(256, 256, 256, 256);
    // Recalculate overflow of last component supplied to make up for missing components.
    IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
    if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
        return false;
    }
    return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
}

function is_array (mixed_var) {
    // Returns true if variable is an array  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        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 = '';
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    if (!mixed_var) {
        return false;
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    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
                                getFuncName(mixed_var.constructor) !== '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://brett-zamir.me)
    // *     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: 909.322
    // 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://brett-zamir.me)
    // *     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: 1003.2411
    // discuss at: http://phpjs.org/functions/is_callable
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        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='';
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    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 && getFuncName(obj.constructor))+'::'+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: 1003.2411
    // 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: 909.322
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/is_float
    // +   original by: Paulo Ricardo F. Santos
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // %        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
    if (typeof mixed_var !== 'number') {
        return false;
    }

    return !!(mixed_var % 1);
}

function is_infinite (val) {
    // Returns whether argument is infinite  
    // 
    // version: 909.322
    // 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: 1003.2411
    // 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)
    // +   improved by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // %        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;
    }

    return !(mixed_var % 1);
}

function is_integer (mixed_var) {
    // !No description available for is_integer. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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: 909.322
    // 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: 1003.2411
    // 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: 1003.2411
    // 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
    // +   bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     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
    // *     example 4: is_numeric([]);
    // *     returns 4: false
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function is_object (mixed_var){
    // Returns true if variable is an object  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/is_real
    // +   original by: Brett Zamir (http://brett-zamir.me)
    //  -   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: 1003.2411
    // discuss at: http://phpjs.org/functions/is_resource
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Luis Salazar (http://www.freaky-media.com/)
    // *     example 1: is_resource('a');
    // *     returns 1: false
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };
    return !(!handle || typeof handle !== 'object' || !handle.constructor || getFuncName(handle.constructor) !== 'PHPJS_Resource');
}

function is_scalar (mixed_var) {
    // Returns true if value is a scalar  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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://brett-zamir.me)
    // %        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='([\s\S])',
        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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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)
    // +      improved by: T.J. Leahy
    // +      improved by: Michael White
    // *        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 json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        try {
            return json.parse(str_json);
        } catch(err) {
            if (!(err instanceof SyntaxError)) {
                throw new Error('Unexpected error type in json_decode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null;
        } 
    }
    
    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;
    }

    this.php_js = this.php_js || {};
    this.php_js.last_error_json = 4; // usable by json_last_error()
    return null;
}

function json_encode (mixed_val) {
    // Returns the JSON representation of a value  
    // 
    // version: 1003.2411
    // 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)
    // +      improved by: Michael White
    // *        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 retVal, json = this.window.JSON;
    try {
        if (typeof json === 'object' && typeof json.stringify === 'function') {
            retVal = json.stringify(mixed_val); // Errors will not be caught here if our own equivalent to resource
                                                                            //  (an instance of PHPJS_Resource) is used
            if (retVal === undefined) {
                throw new SyntaxError('json_encode');
            }
            return retVal;
        }

        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';
                    }
                    if (value instanceof PHPJS_Resource) {
                        throw new SyntaxError('json_encode');
                    }

                    // 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;
                case 'undefined': // Fall-through
                case 'function': // Fall-through
                default:
                    throw new SyntaxError('json_encode');
            }
        };

        // Make a fake root object containing our value under the key of ''.
        // Return the result of stringifying the value.
        return str('', {
            '': value
        });
    
    } catch(err) { // Todo: ensure error handling above throws a SyntaxError in all cases where it could
                            // (i.e., when the JSON global is not available and there is an error)
        if (!(err instanceof SyntaxError)) {
            throw new Error('Unexpected error type in json_encode()');
        }
        this.php_js = this.php_js || {};
        this.php_js.last_error_json = 4; // usable by json_last_error()
        return null;
    }
}

function json_last_error () {
    // !No description available for json_last_error. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/json_last_error
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: json_last_error();
    // *     returns 1: 0
    /*
    JSON_ERROR_NONE = 0
    JSON_ERROR_DEPTH = 1 // max depth limit to be removed per PHP comments in json.c (not possible in JS?)
    JSON_ERROR_STATE_MISMATCH = 2 // internal use? also not documented
    JSON_ERROR_CTRL_CHAR = 3 // [\u0000-\u0008\u000B-\u000C\u000E-\u001F] if used directly within json_decode(),
                                                                  // but JSON functions auto-escape these, so error not possible in JavaScript
    JSON_ERROR_SYNTAX = 4
    */
    return this.php_js && this.php_js.last_error_json ? this.php_js.last_error_json : 0;
}

function key (arr) {
    // Return the key of the element currently pointed to by the internal array pointer  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/key
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Riddler (http://www.frontierwebdev.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        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'
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.pointers = this.php_js.pointers || [];
    var indexOf = function (value) {
        for (var i = 0, length=this.length; i < length; i++) {
            if (this[i] === value) {
                return i;
            }
        }
        return -1;
    };
    // END REDUNDANT

    var pointers = this.php_js.pointers;
    if (!pointers.indexOf) {
        pointers.indexOf = indexOf;
    }

    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 (inputArr, sort_flags) {
    // Sort an array by key value in reverse order  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // %          note 1: The examples are correct, this is a new way
    // %        note 2: This function deviates from PHP in returning a copy of the array instead
    // %        note 2: of acting by reference and returning true; this was necessary because
    // %        note 2: IE does not allow deleting and re-adding of properties without caching
    // %        note 2: of property position; you can set the ini of "phpjs.strictForIn" to true to
    // %        note 2: get the PHP behavior, but use this only if you are in an environment
    // %        note 2: such as Firefox extensions where for-in iteration order is fixed and true
    // %        note 2: property deletion is supported. Note that we intend to implement the PHP
    // %        note 2: behavior by default if IE ever does allow it; only gives shallow copy since
    // %        note 2: is by reference in PHP anyways
    // -    depends on: i18n_loc_get_default
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: data = krsort(data);
    // *     results 1: {d: 'lemon', c: 'apple', b: 'banana', a: 'orange'}
    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'};
    // *     example 2: krsort(data);
    // *     results 2: data == {3: 'Kevin', 2: 'van', 1: 'Zonneveld'}
    // *     returns 2: true
    var tmp_arr={}, keys=[], sorter, i, k, that=this, strictForIn = false, populateArr = [];

    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)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            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 (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            keys.push(k);
        }
    }
    keys.sort(sorter);

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value;
    populateArr = strictForIn ? inputArr : populateArr;


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

    return strictForIn ? true : populateArr;
}

function ksort (inputArr, sort_flags) {
    // Sort an array by key  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
    // %          note 1: The examples are correct, this is a new way
    // %        note 2: This function deviates from PHP in returning a copy of the array instead
    // %        note 2: of acting by reference and returning true; this was necessary because
    // %        note 2: IE does not allow deleting and re-adding of properties without caching
    // %        note 2: of property position; you can set the ini of "phpjs.strictForIn" to true to
    // %        note 2: get the PHP behavior, but use this only if you are in an environment
    // %        note 2: such as Firefox extensions where for-in iteration order is fixed and true
    // %        note 2: property deletion is supported. Note that we intend to implement the PHP
    // %        note 2: behavior by default if IE ever does allow it; only gives shallow copy since
    // %        note 2: is by reference in PHP anyways
    // -    depends on: i18n_loc_get_default
    // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: data = ksort(data);
    // *     results 1: {a: 'orange', b: 'banana', c: 'apple', d: 'lemon'}
    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'};
    // *     example 2: ksort(data);
    // *     results 2: data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'}
    // *     returns 2: true
    var tmp_arr={}, keys=[], sorter, i, k, that=this, strictForIn = false, populateArr = [];

    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)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            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 (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            keys.push(k);
        }
    }
    keys.sort(sorter);

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value;
    populateArr = strictForIn ? inputArr : populateArr;

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

    return strictForIn ? true : populateArr;
}

function lcfirst (str) {
    // !No description available for lcfirst. @php.js developers: Please update the function summary text file.
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/lcfirst
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 909.322
    // discuss at: http://phpjs.org/functions/lcg_value
    // +   original by: Onno Marsman
    return Math.random();
}

function levenshtein (s1, s2) {
      // Calculate Levenshtein distance between two strings  
    // 
    // version: 1003.2411
    // 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://brett-zamir.me)
      // + reimplemented by: Alexander M Beedie
      // *                example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
      // *                returns 1: 3
    if (s1 == s2) {
        return 0;
    }

    var s1_len = s1.length;
    var s2_len = s2.length;
    if (s1_len === 0) {
        return s2_len;
    }
    if (s2_len === 0) {
        return s1_len;
    }

    // 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 (split){
        s1 = s1.split('');
        s2 = s2.split('');
    }

    var v0 = new Array(s1_len+1);
    var v1 = new Array(s1_len+1);

    var s1_idx=0, s2_idx=0, cost=0;
    for (s1_idx=0; s1_idx<s1_len+1; s1_idx++) {
        v0[s1_idx] = s1_idx;
    }
    var char_s1='', char_s2='';
    for (s2_idx=1; s2_idx<=s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx=0; s1_idx<s1_len;s1_idx++) {
            char_s1 = s1[s1_idx];
            cost = (char_s1 == char_s2) ? 0 : 1;
            var m_min = v0[s1_idx+1] + 1;
            var b = v1[s1_idx] + 1;
            var c = v0[s1_idx] + cost;
            if (b < m_min) {
                m_min = b; }
            if (c < m_min) {
                m_min = c; }
            v1[s1_idx+1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
    }
    return v0[s1_len];
}

function localeconv () {
    // Returns numeric formatting information based on the current locale  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/localeconv
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    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 REDUNDANT
    this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place, if not already
    // END REDUNDANT

    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/localtime
    // + original by: Brett Zamir (http://brett-zamir.me)
    // +      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); // this.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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // discuss at: http://phpjs.org/functions/log1p
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          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: 1003.2411
    // 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: 1003.2411
    // 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 mail (to, subject, message, additional_headers, additional_parameters) {
    // Send an email message  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/mail
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: Currently only works if the SSJS SendMail method is available
    // %          note 1: and also depends on the ini having been set for 'sendmail_from'
    // %          note 2: 'additional_parameters' argument is not supported
    // *     example 1: mail('you@example.com', 'Hi!', "What's been going on lately?");
    // *     returns 1: true
    // *     example 2: mail("jack@example.com, barry@example.net", 'ok subj', 'my message',
    // *     example 2:           'From: jack@example.com\r\n'+'Organization : Example Corp\r\n'+
    // *     example 2:           'Content-type: text/html;charset=utf8');
    // *     returns 2: true
    var _append = function (sm, prop, value) {
        if (!sm[prop]) { // Ok?
            sm[prop] = '';
            sm[prop] += value;
        }
        else {
            sm[prop] += ','+value;
        }
    };

    if (this.window.SendMail) { // See http://research.nihonsoft.org/javascript/ServerReferenceJS12/sendmail.htm
        var sm = new this.window.SendMail();
        var from = this.php_js && this.php_js.ini && this.php_js.ini.sendmail_from && this.php_js.ini.sendmail_from.local_value;
        sm.To = to;
        sm.Subject = subject;
        sm.Body = message;
        sm.From = from;
        if (additional_headers) {
            var headers = additional_headers.trim().split(/\r?\n/);
            for (var i = 0; i < headers.length; i++) {
                var header = headers[i];
                var colonPos = header.indexOf(':');
                if (colonPos === -1) {
                    throw new Error('Malformed headers');
                }
                var prop = header.slice(0, colonPos).trim();
                var value = header.slice(colonPos+1).trim();
                switch(prop) {
                    // Todo: Add any others to this top fall-through which can allow multiple headers
                    //                via commas; will otherwise be overwritten (Errorsto, Replyto?)
                    case 'Bcc':
                        // Fall-through
                    case 'Cc':
                        // Fall-through
                    case 'To': // Apparently appendable with additional headers per PHP examples
                        _append(sm, prop, value);
                        break;
                    case 'Subject': // Overridable in additional headers?
                        break;
                    case 'Body': // Overridable in additional headers?
                        break;
                    case 'From': // Default, though can be overridden
                        /* Fall-through */
                    default: //  Errorsto, Organization, Replyto, Smtpserver
                        sm[prop] = value;
                        break;
                }
            }
        }
        if (!sm.From) {
            throw new Error('Warning: mail(): "sendmail_from" not set in php.ini');
        }
        return sm.send();
    }
    return false;
}

function max () {
    // Return the highest value in an array or a series of arguments  
    // 
    // version: 1003.2411
    // 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: 1003.2411
    // 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://brett-zamir.me)
    // +   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: 1003.2411
    // discuss at: http://phpjs.org/functions/md5_file
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   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 metaphone (word, phones){
    // +   original by: Greg Frazier
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: metaphone('Gnu');
    // *     returns 1: 'N'

    // As far as use of the String() constructor, the author recalls IE 6 giving errors otherwise
    
    var wordlength = word.length,
        x = 0, tempchar = '',
        metaword = '',
        removedbl = function (word){
            var wordlength = word.length,
            tempword = word.toLowerCase(),
            rebuilt,
            tempchar1, tempchar2,
            x;

            tempchar1 = tempword.charAt(0);
            rebuilt = tempchar1;
            for (x=1;x<wordlength;x++){
                tempchar2 = tempword.charAt(x);
                if (tempchar2 != tempchar1 || tempchar2 == 'c' || tempchar2 == 'g'){
                    rebuilt += tempchar2;
                }
                tempchar1 = tempchar2;
            }
            return rebuilt;
        },
        isVowel=function(a){
            switch (a.toLowerCase()) {
                case 'a': return true;
                case 'e': return true;
                case 'i': return true;
                case 'o': return true;
                case 'u': return true;
                default: return false;
            }
        },
        tempword = removedbl(word.toLowerCase());

    //Special wh- case
    if (tempword.charAt(0) == 'w' && tempword.charAt(1) == 'h'){
        // Remove "h" and rebuild the string
        tempword = "w" + tempword.substr(2);
    }

    for (x=0; x<wordlength; x++){
        tempchar = String(tempword).charAt(x);
        if (x === 0 && x+1 <= wordlength){
            switch (tempchar){
                case 'a': if (tempword.charAt(x+1) == 'e'){ metaword += 'e'; }else{metaword += 'a';} break;
                case 'e': metaword += 'e'; break;
                case 'i': metaword += 'i'; break;
                case 'o': metaword += 'o'; break;
                case 'u': metaword += 'u'; break;
                case 'g': if (String(tempword).charAt(x+1) == 'n'){ x += 1; tempchar = String(tempword).charAt(x);} break;
                case 'k': if (String(tempword).charAt(x+1) == 'n'){ x += 1; tempchar = String(tempword).charAt(x);} break;
                case 'p': if (String(tempword).charAt(x+1) == 'n'){ x += 1; tempchar = String(tempword).charAt(x);} break;
                case 'w': if (String(tempword).charAt(x+1) == 'r'){ x += 1; tempchar = String(tempword).charAt(x); break;} break;
            }
        }
        if (isVowel(tempchar) === false){
            switch (tempchar){
                case 'b': if (String(tempword).charAt(x-1) == 'm'){ break;}else{metaword += 'b';} break;
                case 'c': if (x+1 <= wordlength){
                            if (String(tempword).charAt(x+1) == 'h' && String(tempword).charAt(x-1) != 's'){
                                if (x === 0 && (x+2 <= wordlength) && isVowel(String(tempword).charAt(x+2))) {
                                    metaword += 'k';
                                } else {
                                    metaword += 'x';
                                }
                             }else if (String(tempword).charAt(x+1) == 'i' && String(tempword).charAt(x+2) == 'a'){ metaword += 'x';}
                            else if (String(tempword).charAt(x+1) == 'i' || String(tempword).charAt(x+1) == 'e' || String(tempword).charAt(x+1) == 'y'){
                                if (x > 0){
                                    if (String(tempword).charAt(x-1) == 's'){
                                        break;
                                    }else{
                                        metaword += 's';
                                    }
                                }else{
                                    metaword += 's';
                                }
                            }else{
                                metaword += 'k';
                            }
                          }else{
                            metaword += 'k';
                          }
                          break;
                case 'd': if (x+2 <= wordlength){
                            if (String(tempword).charAt(x+1) == 'g'){
                                if (String(tempword).charAt(x+2) == 'e' || String(tempword).charAt(x+2) == 'y' || String(tempword).charAt(x+2) == 'i'){
                                    metaword += 'j';
                                    x += 2;
                                }else{
                                    metaword += 't';
                                }
                            }else{
                                metaword += 't';
                            }
                          }else{
                                metaword += 't';
                          }
                          break;
                case 'f': metaword += 'f'; break;
                case 'g': if (x < wordlength){
                            if ((String(tempword).charAt(x+1) == 'n' && x+1 == wordlength - 1) || (String(tempword).charAt(x+1) == 'n' && String(tempword).charAt(x+2) == 's' && x+2 == wordlength - 1)){break;}
                            if (String(tempword).charAt(x+1) == 'n' && String(tempword).charAt(x+2) == 'e' && String(tempword).charAt(x+3) == 'd' && x+3 == wordlength - 1){break;}
                            if (String(tempword).charAt(x-1) == 'n' && String(tempword).charAt(x-2) == 'i' && x == wordlength - 1){break;}
                            if (String(tempword).charAt(x+1) == 'h' && x+1 <= wordlength-1 && String(tempword).charAt(x-1) == 'u' && String(tempword).charAt(x-2) == 'o'){metaword += 'f';break;}
                            if (String(tempword).charAt(x+1) == 'h' && x+2 <= wordlength){if(isVowel(String(tempword).charAt(x+2)) === false){break; /*silent*/ }else{metaword += 'k';}}
                            else if (x+1 == wordlength){if(String(tempword).charAt(x+1) == 'n'){break;}else{metaword += 'k';}}
                            else if (x+3 == wordlength){if(String(tempword).charAt(x+1) == 'n' && String(tempword).charAt(x+2) == 'e' && String(tempword).charAt(x+3) == 'd'){}else{metaword += 'k';}}
                            else if (x+1 <= wordlength){if(String(tempword).charAt(x+1) == 'i' || String(tempword).charAt(x+1) == 'e' || String(tempword).charAt(x+1) == 'y'){
                                                    if (String(tempword).charAt(x-1) != 'g'){ metaword += 'j';}
                                                    }else if (x > 0){ if (String(tempword).charAt(x-1) == 'd'){
                                                        switch (String(tempword).charAt(x+1)){
                                                            case 'e':
                                                            case 'y':
                                                            case 'i': break;
                                                            default: metaword += 'k';
                                                        }
                                                        }else{metaword += 'k';}
                                                    }else{metaword += 'k';}
                            }else{
                                metaword += 'k';
                            }
                          }else{
                                metaword += 'k';
                          }
                          break;
                case 'm': metaword += 'm'; break;
                case 'j': metaword += 'j'; break;
                case 'n': metaword += 'n'; break;
                case 'q': metaword += 'k'; break;
                case 'r': metaword += 'r'; break;
                case 'l': metaword += 'l'; break;
                case 'v': metaword += 'f'; break;
                case 'z': metaword += 's'; break;
                case 'x': if (x === 0){metaword += 's';}else{metaword += 'ks';} break;
                case 'm': metaword += 'm'; break;
                case 'k': if (x > 0){ if (String(tempword).charAt(x-1) != 'c'){metaword += 'k';}}else{metaword += 'k';} break;
                case 'p': if (x+1 <= wordlength){if(String(tempword).charAt(x+1) == 'h'){metaword += 'f';}else{metaword +='p';}}else{metaword += 'p';} break;
                case 'y': if (x+1 <= wordlength){if(isVowel(String(tempword).charAt(x+1)) === true){metaword += 'y';}}else{metaword += 'y';} break;
                case 'h': if (x === 0 || 'csptg'.indexOf(String(tempword).charAt(x-1)) === -1) {
                            if (isVowel(String(tempword).charAt(x+1)) === true){metaword += 'h';}} break;
                case 's': if (x+1 <= wordlength){if(String(tempword).charAt(x+1) == 'h'){ metaword += 'x'; }
                            else if (x+2 <= wordlength){if(String(tempword).charAt(x+1) == 'i'){if(String(tempword).charAt(x+2) == 'o' || String(tempword).charAt(x+2) == 'a'){metaword += 'x';}else{metaword += 's';}
                            }else{metaword += 's';}}else{metaword += 's';}}else{metaword += 's';} break;
                case 't': if (x+1 <= wordlength){if(String(tempword).charAt(x+1) == 'h'){ metaword += '0'; }
                            else if (x+2 <= wordlength){if(String(tempword).charAt(x+1) == 'i'){if(String(tempword).charAt(x+2) == 'o' || String(tempword).charAt(x+2) == 'a'){metaword += 'x';}else{metaword += 't';}
                            }else{metaword += 't';}}else{metaword += 't';}}else{metaword += 't';} break;
                case 'w': if (x+1 <= wordlength){if(isVowel(String(tempword).charAt(x+1)) === true){metaword += 'w';}} break;
            }
        }
    }

    phones = parseInt(phones, 10);
    if (metaword.length > phones) {
        return metaword.substr(0, phones).toUpperCase();
    }
    return metaword.toUpperCase();
}

function method_exists (obj, method) {
    // Checks if the class method exists  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/method_exists
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     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: 1003.2411
    // 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: 1003.2411
    // 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: 1003.2411
    // 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://brett-zamir.me)
    // +      input by: 3D-GRAF
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Chris
    // +    revised by: Theriault
    // %        note 1: The return values of the following examples are
    // %        note 1: received only if your system's timezone is UTC.
    // *     example 1: mktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201875002
    // *     example 2: mktime(0, 0, 0, 0, 1, 2008);
    // *     returns 2: 1196467200
    // *     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: 883612800 
    // *     example 5: mktime(0, 0, 0, 1, 1, 1998)
    // *     returns 5: 883612800 
    // *     example 6: mktime(0, 0, 0, 1, 1, 98)
    // *     returns 6: 883612800 
    // *     example 7: mktime(23, 59, 59, 13, 0, 2010)
    // *     returns 7: 1293839999
    // *     example 8: mktime(0, 0, -1, 1, 1, 1970)
    // *     returns 8: -1
    var d = new Date(), r = arguments, i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];

    for (i = 0; i < e.length; i++) {
        if (typeof r[i] === 'undefined') {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        } else {
            r[i] = parseInt(r[i], 10);
            if (isNaN(r[i])) {
                return false;
            }
        }
    }
    
    // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000.
    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
    
    // Set year, month (-1 to fix JS months), and date.
    // !This must come before the call to setHours!
    d.setFullYear(r[5], r[3] - 1, r[4]);
    
    // Set hours, minutes, and seconds.
    d.setHours(r[0], r[1], r[2]);

    // Divide milliseconds by 1000 to return seconds and drop decimal.
    // Add 1 second if negative or it'll be off from PHP by 1 second.
    return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
}

function money_format (format, number) {
    // Convert monetary value(s) to string  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/money_format
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: daniel airton wermann (http://wermann.com.br)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: setlocale
    // %          note 1: This depends on setlocale having the appropriate locale (these examples use 'en_US')
    // *     example 1: money_format('%i', 1234.56);
    // *     returns 1: 'USD 1,234.56'
    // *     example 2: money_format('%14#8.2n', 1234.5678);
    // *     returns 2: ' $     1,234.57'
    // *     example 3: money_format('%14#8.2n', -1234.5678);
    // *     returns 3: '-$     1,234.57'
    // *     example 4: money_format('%(14#8.2n', 1234.5678);
    // *     returns 4: ' $     1,234.57 '
    // *     example 5: money_format('%(14#8.2n', -1234.5678);
    // *     returns 5: '($     1,234.57)'
    // *     example 6: money_format('%=014#8.2n', 1234.5678);
    // *     returns 6: ' $000001,234.57'
    // *     example 7: money_format('%=014#8.2n', -1234.5678);
    // *     returns 7: '-$000001,234.57'
    // *     example 8: money_format('%=*14#8.2n', 1234.5678);
    // *     returns 8: ' $*****1,234.57'
    // *     example 9: money_format('%=*14#8.2n', -1234.5678);
    // *     returns 9: '-$*****1,234.57'
    // *     example 10: money_format('%=*^14#8.2n', 1234.5678);
    // *     returns 10: '  $****1234.57'
    // *     example 11: money_format('%=*^14#8.2n', -1234.5678);
    // *     returns 11: ' -$****1234.57'
    // *     example 12: money_format('%=*!14#8.2n', 1234.5678);
    // *     returns 12: ' *****1,234.57'
    // *     example 13: money_format('%=*!14#8.2n', -1234.5678);
    // *     returns 13: '-*****1,234.57'
    // *     example 14: money_format('%i', 3590);
    // *     returns 14: ' USD 3,590.00'

    // Per PHP behavior, there seems to be no extra padding for sign when there is a positive number, though my
    // understanding of the description is that there should be padding; need to revisit examples

    // Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm

    if (typeof number !== 'number') {
        return null;
    }
    var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; // 1: flags, 3: width, 5: left, 7: right, 8: conversion

    this.setlocale('LC_ALL', 0); // Ensure the locale data we need is set up
    var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY'];

    var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) {
        var value='', repl = '';
        if (conversion === '%') { // Percent does not seem to be allowed with intervening content
            return '%';
        }
        var fill = flags &