// NAMESPACES
Ext.ns('CMS');

if(!Array.prototype.forEach) {
    /*
     * Array forEach Iteration based on previous work by: Dean Edwards
     * (http://dean.edwards.name/weblog/2006/07/enum/) Gecko already
     * supports forEach for Arrays : see
     * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach
     */
    Array.prototype.forEach = function(block, scope) {
        if(typeof block != "function") {
            throw new TypeError();
        }

        var i = 0, length = this.length;

        while (i < length) {
            block.call(scope, this[i], i++, this);
        }
    };
}

// GLOBAL FUNCTIONS
forEach = function(object, block, context) {
    context = context || object;

    if (object) {
        if (typeof block != "function") {
            return false;
        }

        var resolve = Object; // default

        if (object instanceof Function) {
            // functions have a "length" property
            resolve = Function;
        } else if (object.forEach instanceof Function) {
            // the object implements a custom forEach method so use that
            return object.forEach(block, context);
        } else if (typeof object == "string") {
            // the object is a string
            resolve = String;
        } else if (typeof object.length == "number") {
            // the object is array-like
            return Array.prototype.forEach.call(object, block, context);
        }

        return resolve.forEach(object, block, context);
    }
    return true;
};

clone = function(obj, deep) {
    if(obj && typeof obj.clone == 'function') {
        return obj.clone(deep);
    }

    if(!obj) {
        return obj;
    }

    var o = {};

    forEach(obj, function(val, name, objAll) {
        o[name] = (val === objAll ? o : deep ? clone(val, true) : val);
    });

    return o;
};

forEach([Number, RegExp, Boolean], function(t) {
    t.prototype.clone = function(deep) {
        return deep ? new t(this) : this;
    };
});

Ext.applyIf(Array.prototype, {
    findBy: function(fn) {
        var result = [];

        for(var i = 0, len = this.length; i < len; i++) {
            if(fn.call(this || scope, this[i])) {
                result.push(this[i]);
            }
        }

        if(result.length !== 0) {
            return result;
        }

        return false;
    },

    slice: function(object) {
        return slice.apply(object, slice.call(arguments, 1));
    },
    map: function(fun, scope) {
        var len = this.length;

        if(typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];

        for(var i = 0; i < len; i++) {
            if(i in this) {
                res[i] = fun.call(scope || this, this[i], i, this);
            }
        }

        return res;
    },

    include : function(value, deep) {
        // use native indexOf if available
        if (!deep && typeof this.indexOf == 'function') {
            return this.indexOf(value) != -1;
        }
        var found = false;
        try {
            this.forEach(function(item, index) {
                var found = (deep ? (item.include ? item.include(value, deep) : (item === value)) : item === value);
                    if (found) {
                        throw Ext.stopIteration;
                    }
            });
        } catch (exc) {
            if (exc != Ext.stopIteration) {
                throw exc;
            }
        }
        return found;
    },
    // Using iterFn, traverse the array, push the current element
    // value onto the
    // result if the iterFn returns true
    filter : function(iterFn, scope) {
        var a = [];

        if(!iterFn) {
            iterFn = function(value) {
                return value;
            };
        }

        this.forEach(function(value, index) {
            if (iterFn.call(scope, value, index)) {
                a.push(value);
            }
        });

        return a;
    },

    compact : function(deep) { // Remove null, undefined array
                                // elements
        var a = [];
        this.forEach(function(v) {
            if(v !== null && v !== undefined) {
                a.push(deep && Ext.isArray(v) ? v.compact() : v);
            }
        }, this);
        return a;
    },

    flatten : function() { // flatten: [1,2,3,[4,5,6]] ->
                            // [1,2,3,4,5,6]
        var a = [];
        this.forEach(function(v) {
            if(Ext.isArray(v)) {
                a = a.concat(v);
            } else {
                a.push(v);
            }
        }, this);
        return a;
    },

    unique : function(sorted /* sort optimization */, exact) {
        var a = [];
        this.forEach(function(value, index) {
            if (0 === index || (sorted ? a.last() != value : !a.include(value, exact))) {
                a.push(value);
            }
        }, this);
        return a;
    },
    // search array values based on regExpression pattern returning
    // test (and optionally execute function(value,index) on test
    // before returned)
    grep : function(pattern, iterFn, scope) {
        var a = [];
        if(!iterFn) {
            iterFn = function(value) {
                return value;
            };
        }
        var fn = scope ? iterFn.createDelegate(scope) : iterFn;

        if (typeof pattern == 'string') {
            pattern = new RegExp(pattern);
        }
        this.forEach(function(value, index) {
            if (pattern.test(value)) {
                a.push(fn(value, index));
            }
        });
        return a;
    },
    first : function() {
        return this[0];
    },

    last : function() {
        return this[this.length - 1];
    },

    clear : function() {
        this.length = 0;
    },

    // return an array element selected at random
    atRandom : function(defValue) {
        var r = Math.floor(Math.random() * this.length);
        return this[r] || defValue;
    },

    clone : function(deep) {
        if (!deep) {
            return this.concat();
        }

        var length = this.length || 0, t = [];
        while (length--) {
            t[length] = clone(this[length], true);
        }
        return t;

    },

    max: function(){
        return Math.max.apply({},this);
    },

    sum: function(){
        for(var i=0,sum = 0;i<this.length;i++){
            sum += this[i];
        }
        return sum;
    },

    min: function(){
        return Math.min.apply({},this);
    }
});

Ext.applyIf(Date.prototype, {
    clone: function(deep){
        return deep? new Date(this.getTime()) : this ;
    }
});

Ext.applyIf(String.prototype, {
    /*
      This function adds plurilization support to every String object
        Signature:
          String.pluralize(plural) == String
        Arguments:
          plural - String (optional) - overrides normal output with said String
        Returns:
          String - singular English language nouns are returned in plural form
        Examples:
          "person".pluralize() == "people"
          "octopus".pluralize() == "octopi"
          "Hat".pluralize() == "Hats"
          "person".pluralize("guys") == "guys"
    */
    pluralize: function(plural) {
        var str=this;
        if(plural) {
            str=plural;
        } else {
            var uncountable=false;
            var x;

            for(x=0;!uncountable&&x<this._uncountable_words.length;x++) {
                uncountable=(this._uncountable_words[x]==str.toLowerCase());
            }

            if(!uncountable) {
                var matched=false;

                for(x=0;!matched&&x<this._plural_rules.length;x++) {
                    matched=str.match(this._plural_rules[x][0]);
                    if(matched) {
                        str=str.replace(this._plural_rules[x][0],this._plural_rules[x][1]);
                    }
                }
            }
        }
        return str;
    },
    /*
      This function adds singularization support to every String object
        Signature:
          String.singularize(singular) == String
        Arguments:
          singular - String (optional) - overrides normal output with said String
        Returns:
          String - plural English language nouns are returned in singular form
        Examples:
          "people".singularize() == "person"
          "octopi".singularize() == "octopus"
          "Hats".singularize() == "Hat"
          "guys".singularize("person") == "person"
    */
    singularize:    function(singular) {
        var str=this;

        if(singular) {
            str=singular;
        } else {
            var x;
            var uncountable=false;

            for(x=0;!uncountable&&x<this._uncountable_words.length;x++) {
                uncountable=(this._uncountable_words[x]==str.toLowerCase());
            }

            if(!uncountable) {
                var matched=false;

                for(x=0;!matched&&x<this._singular_rules.length;x++) {
                    matched=str.match(this._singular_rules[x][0]);
                    if(matched) {
                        str=str.replace(this._singular_rules[x][0],this._singular_rules[x][1]);
                    }
                }
            }
        }
        return str;
    },

    /*
      This is a list of nouns that use the same form for both singular and plural.
      This list should remain entirely in lower case to correctly match Strings.
      You can override this list for all Strings or just one depending on if you
      set the new values on prototype or on a given String instance.
    */
    _uncountable_words: [
        'equipment','information','rice',
        'money','species','series','fish',
        'sheep','moose','deer','news'
    ],

    /*
      These rules translate from the singular form of a noun to its plural form.
      You can override this list for all Strings or just one depending on if you
      set the new values on prototype or on a given String instance.
    */
    _plural_rules: [
        [new RegExp('(m)an$','gi'),'$1en'],
        [new RegExp('(pe)rson$','gi'),'$1ople'],
        [new RegExp('(child)$','gi'),'$1ren'],
        [new RegExp('^(ox)$','gi'),'$1en'],
        [new RegExp('(ax|test)is$','gi'),'$1es'],
        [new RegExp('(octop|vir)us$','gi'),'$1i'],
        [new RegExp('(alias|status)$','gi'),'$1es'],
        [new RegExp('(bu)s$','gi'),'$1ses'],
        [new RegExp('(buffal|tomat|potat)o$','gi'),'$1oes'],
        [new RegExp('([ti])um$','gi'),'$1a'],
        [new RegExp('sis$','gi'),'ses'],
        [new RegExp('(?:([^f])fe|([lr])f)$','gi'),'$1$2ves'],
        [new RegExp('(hive)$','gi'),'$1s'],
        [new RegExp('([^aeiouy]|qu)y$','gi'),'$1ies'],
        [new RegExp('(x|ch|ss|sh)$','gi'),'$1es'],
        [new RegExp('(matr|vert|ind)ix|ex$','gi'),'$1ices'],
        [new RegExp('([m|l])ouse$','gi'),'$1ice'],
        [new RegExp('(quiz)$','gi'),'$1zes'],
        [new RegExp('s$','gi'),'s'],
        [new RegExp('$','gi'),'s']
    ],

    /*
      These rules translate from the plural form of a noun to its singular form.
      You can override this list for all Strings or just one depending on if you
      set the new values on prototype or on a given String instance.
    */
    _singular_rules: [
        [new RegExp('(m)en$','gi'),'$1an'],
        [new RegExp('(pe)ople$','gi'),'$1rson'],
        [new RegExp('(child)ren$','gi'),'$1'],
        [new RegExp('([ti])a$','gi'), '$1um'],
        [new RegExp('((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$','gi'),'$1$2sis'],
        [new RegExp('(hive)s$','gi'), '$1'],
        [new RegExp('(tive)s$','gi'), '$1'],
        [new RegExp('(curve)s$','gi'), '$1'],
        [new RegExp('([lr])ves$','gi'), '$1f'],
        [new RegExp('([^fo])ves$','gi'), '$1fe'],
        [new RegExp('([^aeiouy]|qu)ies$','gi'), '$1y'],
        [new RegExp('(s)eries$','gi'), '$1eries'],
        [new RegExp('(m)ovies$','gi'), '$1ovie'],
        [new RegExp('(x|ch|ss|sh)es$','gi'), '$1'],
        [new RegExp('([m|l])ice$','gi'), '$1ouse'],
        [new RegExp('(bus)es$','gi'), '$1'],
        [new RegExp('(o)es$','gi'), '$1'],
        [new RegExp('(shoe)s$','gi'), '$1'],
        [new RegExp('(cris|ax|test)es$','gi'), '$1is'],
        [new RegExp('(octop|vir)i$','gi'), '$1us'],
        [new RegExp('(alias|status)es$','gi'), '$1'],
        [new RegExp('^(ox)en','gi'), '$1'],
        [new RegExp('(vert|ind)ices$','gi'), '$1ex'],
        [new RegExp('(matr)ices$','gi'), '$1ix'],
        [new RegExp('(quiz)zes$','gi'), '$1'],
        [new RegExp('s$','gi'), '']
    ],

    /*
      This function adds camelization support to every String object
        Signature:
          String.camelize(lowFirstLetter) == String
        Arguments:
          lowFirstLetter - boolean (optional) - default is to capitalize the first
            letter of the results... passing true will lowercase it
        Returns:
          String - lower case underscored words will be returned in camel case
            additionally '/' is translated to '::'
        Examples:
          "message_properties".camelize() == "MessageProperties"
          "message_properties".camelize(true) == "messageProperties"
    */
    camelize: function(lowFirstLetter) {
        var str=this.toLowerCase();
        var str_path=str.split('/');

        for(var i=0;i<str_path.length;i++) {
            var str_arr=str_path[i].split('_');
            var initX=((lowFirstLetter&&i+1==str_path.length)?(1):(0));
            for(var x=initX;x<str_arr.length;x++) {
                str_arr[x]=str_arr[x].charAt(0).toUpperCase()+str_arr[x].substring(1);
            }

            str_path[i]=str_arr.join('');
        }
        str=str_path.join('::');
        return str;
    },

    /*
      This function adds underscore support to every String object
        Signature:
          String.underscore() == String
        Arguments:
          N/A
        Returns:
          String - camel cased words are returned as lower cased and underscored
            additionally '::' is translated to '/'
        Examples:
          "MessageProperties".camelize() == "message_properties"
          "messageProperties".underscore() == "message_properties"
    */
    underscore: function() {
        var str=this;
        var str_path=str.split('::');
        var upCase=new RegExp('([ABCDEFGHIJKLMNOPQRSTUVWXYZ])','g');
        var fb=new RegExp('^_');

        for(var i=0;i<str_path.length;i++) {
            str_path[i]=str_path[i].replace(upCase,'_$1').replace(fb,'');
        }

        str=str_path.join('/').toLowerCase();
        return str;
    },

    /*
      This function adds humanize support to every String object
        Signature:
          String.humanize(lowFirstLetter) == String
        Arguments:
          lowFirstLetter - boolean (optional) - default is to capitalize the first
            letter of the results... passing true will lowercase it
        Returns:
          String - lower case underscored words will be returned in humanized form
        Examples:
          "message_properties".humanize() == "Message properties"
          "message_properties".humanize(true) == "message properties"
    */
    humanize: function(lowFirstLetter) {
        var str=this.toLowerCase();
        str=str.replace(new RegExp('_id','g'),'');
        str=str.replace(new RegExp('_','g'),' ');
        if(!lowFirstLetter){
            str=str.capitalize();
        }
        return str;
    },

    /*
      This function adds capitalization support to every String object
        Signature:
          String.capitalize() == String
        Arguments:
          N/A
        Returns:
          String - all characters will be lower case and the first will be upper
        Examples:
          "message_properties".capitalize() == "Message_properties"
          "message properties".capitalize() == "Message properties"
    */
    capitalize: function(all) {
        if(all) {
            return this.toLowerCase().replace(/\w+/g,function(s) {
                return s.charAt(0).toUpperCase() + s.substr(1);
            });
        } else {
            var str=this.toLowerCase();
            str=str.substring(0,1).toUpperCase()+str.substring(1);
            return str;
        }
    },

    /*
      This function adds dasherization support to every String object
        Signature:
          String.dasherize() == String
        Arguments:
          N/A
        Returns:
          String - replaces all spaces or underbars with dashes
        Examples:
          "message_properties".capitalize() == "message-properties"
          "Message Properties".capitalize() == "Message-Properties"
    */
    dasherize:  function() {
        var str=this;
        str=str.replace(new RegExp("[ _]",'g'),'-');
        return str;
    },

    /*
      This function adds titleize support to every String object
        Signature:
          String.titleize() == String
        Arguments:
          N/A
        Returns:
          String - capitalizes words as you would for a book title
        Examples:
          "message_properties".titleize() == "Message Properties"
          "message properties to keep".titleize() == "Message Properties to Keep"
    */
    titleize:   function() {
        var str = new String(this);
        var t=new RegExp('^'+this._non_titlecased_words.join('$|^')+'$','i');

        str=str.replace(new RegExp('_','g'),' ');

        var str_arr=str.split(' ');

        for(var x=0;x<str_arr.length;x++) {
            var d=str_arr[x].split('-');

            for(var i=0;i<d.length;i++){
                var l = d[i].toLowerCase();

                if(!l.match(t)) {
                    if(d[i] != d[i].toUpperCase()) {
                        d[i]=l.capitalize();
                    }
                }
            }

            str_arr[x]=d.join('-');
        }

        str=str_arr.join(' ');
        str=str.substring(0,1).toUpperCase()+str.substring(1);

        return str;
    },

    /*
      This is a list of words that should not be capitalized for title case.
      You can override this list for all Strings or just one depending on if you
      set the new values on prototype or on a given String instance.
    */
    _non_titlecased_words: [
        'and','or','nor','a','an','the','so','but','to','of','at','by','from',
        'into','on','onto','off','out','in','over','with','for'
    ],

    /*
      This function adds demodulize support to every String object
        Signature:
          String.demodulize() == String
        Arguments:
          N/A
        Returns:
          String - removes module names leaving only class names (Ruby style)
        Examples:
          "Message::Bus::Properties".demodulize() == "Properties"
    */
    demodulize: function() {
        var str=this;
        var str_arr=str.split('::');
        str=str_arr[str_arr.length-1];
        return str;
    },

    endsWith:  function(s) {
        return this.substring(this.length - s.length) == s;
    },

    /*
      This function adds tableize support to every String object
        Signature:
          String.tableize() == String
        Arguments:
          N/A
        Returns:
          String - renders camel cased words into their underscored plural form
        Examples:
          "MessageBusProperty".tableize() == "message_bus_properties"
    */
    tableize: function() {
        var str=this;
        str=str.underscore().pluralize();
        return str;
    },

    /*
      This function adds classification support to every String object
        Signature:
          String.classify() == String
        Arguments:
          N/A
        Returns:
          String - underscored plural nouns become the camel cased singular form
        Examples:
          "message_bus_properties".classify() == "MessageBusProperty"
    */
    classify: function() {
        var str=this;
        str=str.camelize().singularize();
        return str;
    },

    /*
      This function adds foreign key support to every String object
        Signature:
          String.foreign_key(dropIdUbar) == String
        Arguments:
          dropIdUbar - boolean (optional) - default is to seperate id with an
            underbar at the end of the class name, you can pass true to skip it
        Returns:
          String - camel cased singular class names become underscored with id
        Examples:
          "MessageBusProperty".foreign_key() == "message_bus_property_id"
          "MessageBusProperty".foreign_key(true) == "message_bus_propertyid"
    */
    foreign_key: function(dropIdUbar) {
        var str=this;
        str=str.demodulize().underscore()+((dropIdUbar)?(''):('_'))+'id';
        return str;
    },

    /*
      This function adds ordinalize support to every String object
        Signature:
          String.ordinalize() == String
        Arguments:
          N/A
        Returns:
          String - renders all found numbers their sequence like "22nd"
        Examples:
          "the 1 pitch".ordinalize() == "the 1st pitch"
    */
    ordinalize: function() {
        var str=this;
        var str_arr=str.split(' ');

        for(var x=0;x<str_arr.length;x++) {
            var i=parseInt(str_arr[x], 10);

            if(""+i!="NaN") {
                var ltd=str_arr[x].substring(str_arr[x].length-2);
                var ld=str_arr[x].substring(str_arr[x].length-1);
                var suf="th";

                if(ltd!="11"&&ltd!="12"&&ltd!="13") {
                    if(ld=="1") {
                        suf="st";
                    } else if(ld=="2") {
                        suf="nd";
                    } else if(ld=="3") {
                        suf="rd";
                    }
                }

                str_arr[x]+=suf;
            }
        }

        str=str_arr.join(' ');

        return str;
    },

    hex2rgb: function() {
        var triplet = this.toLowerCase().replace(/#/, '');
        var rgbArr  = [];

        if(triplet.length == 6) {
            rgbArr[0] = parseInt(triplet.substr(0,2), 16);
            rgbArr[1] = parseInt(triplet.substr(2,2), 16);
            rgbArr[2] = parseInt(triplet.substr(4,2), 16);
            return rgbArr;
        } else if(triplet.length == 3) {
            rgbArr[0] = parseInt((triplet.substr(0,1) + triplet.substr(0,1)), 16);
            rgbArr[1] = parseInt((triplet.substr(1,1) + triplet.substr(1,1)), 16);
            rgbArr[2] = parseInt((triplet.substr(2,2) + triplet.substr(2,2)), 16);
            return rgbArr;
        } else {
            return false;
        }
    },

    forEach : function(block, context) {
        if (typeof block != "function") {
            throw new TypeError();
        }

        Array.forEach(this.split(""), function(chr, index) {
            block.call(context || this, chr, index, this);
        }, this);
    },

    truncate: function(len) {
        var str = this;

        if(this.length > len) {
            str = str.substring(0, len-3) + '...';
        }

        return str;
    },

    trim : function() {
        return this.replace(/^\s+|\s+$/g, "");
    },

    clone : function(deep) {
        return deep ? String(this) : this;
    }
});

Ext.applyIf(Function.prototype, {
    forEach : function(object, block, context) {
        if (typeof block != "function") {
            throw new TypeError();
        }
        for (var key in object) {
            if (typeof this.prototype[key] == "undefined") {
                try {
                    block.call(context, object[key], key, object);
                } catch (e) {}
            }
        }
    },

    clone : function(deep) {
        return this;
    },

    /**
     * memoize: a general-purpose function to enable a function to use memoization
     * context: the context for the memoized function to execute within
     * Note: the function must use explicit, string-serializable parameters
     */
    memoize:    function(context) {
        var func = this;

        function memoizeArg(argPos) {
            var cache = {};

            return function() {
                if(argPos === 0) {
                    if(!(arguments[argPos] in cache)) {
                        cache[arguments[argPos]] = func.apply(context, arguments);
                    }

                    return cache[arguments[argPos]];
                } else {
                    if(!(arguments[argPos] in cache)) {
                        cache[arguments[argPos]] = memoizeArg(argPos - 1);
                    }

                    return cache[arguments[argPos]].apply(this, arguments);
                }
            };
        }

        return memoizeArg(func.length - 1);
    }
});

