/**
 * @author cbetancourt
 * Core utilities
 */
DJIndexes.Utils = function(){

    var config = {
        decimalPlaces: {
            standard: 2,
            divisor: 9
        }
    };
    
    function formatter(value, places){
        var nf;
        if (!nf) {
            nf = new NumberFormat(0);
            nf.setSeparators(false);
        }
        nf.setNumber(value);
        nf.setPlaces(places || config.decimalPlaces.standard);
        if (value === '') {
            return null;
        }
        else {
            return nf.toFormatted();
        }
    }
    
    return {
    
        date: function(value){
            return new Date(value).format("j-M-Y");
        },
        
        decimalFormat: function(value){
            return formatter(value);
        },
        
        changeFormat: function(value){
            var chg = formatter(value);
            var className = 'neutral';
            if (chg > 0) {
                className = 'up';
            }
            else 
                if (chg < 0) {
                    className = 'down';
                }
            var output = '<span class="' + className + '">' + chg + '</span>';
            return output;
        },
        
        changeIcon: function(value, size){
            var _size = (size === 'large') ? 'lg' : 'sm';
            var chg = formatter(value);
            var icon = '/images/blank.gif';
            if (chg > 0) {
                icon = '/images/icons/generic/tick-up-' + _size + '.gif';
            }
            else 
                if (chg < 0) {
                    icon = '/images/icons/generic/tick-down-' + _size + '.gif';
                }
            return icon;
        },
        
        divisorFormat: function(value){
            return formatter(value, config.decimalPlaces.divisor);
        },
        
        peRatioFormat: function(value){
            if (value === -999999) {
                return '<span class="neutral">NMF</span>';
            }
            else {
                return formatter(value);
            }
        },
        
        /**
         * @param string paramName
         *
         * Returns either:
         * - the value of the named param name passed; or
         * - an object literal of all params if a named param is not passed.
         */
        getQueryParams: function(paramName){
            var qp = {};
            var params = location.search.substring(1).split('&');
            for (var i = 0; i < params.length; i++) {
                var nv = params[i].split('=');
                qp[nv[0]] = nv[1];
            }
            if (paramName) {
                return qp[paramName];
            }
            return qp;
        },
        
        getCookie: function(name){
            var start = document.cookie.indexOf(name + '=');
            var len = start + name.length + 1;
            if ((!start) && (name != document.cookie.substring(0, name.length))) {
                return null
            };
            if (start == -1) {
                return null
            };
            var end = document.cookie.indexOf(';', len);
            if (end == -1) {
                end = document.cookie.length
            };
            return unescape(document.cookie.substring(len, end));
        },
        
        setCookie: function(name, value, expires, path, domain, secure){
            var cookieString = name + '=' + escape(value) +
            ((expires) ? ';expires=' + expires.toGMTString() : '') +
            ((path) ? ';path=' + path : '') +
            ((domain) ? ';domain=' + domain : '') +
            ((secure) ? ';secure' : '');
            document.cookie = cookieString;
        },
        
        Dom: function(){
            return Ext.DomHelper;
        },
        
        alert: function(config){
        
            var _message = config.message || null;
            var _type = config.type || 'info';
            var _buttons = config.buttons || Ext.Msg.OK;
            
            if (_message) {
            
                var _title = 'Info';
                var _icon = Ext.Msg.INFO;
                
                switch (_type.toLowerCase()) {
                    case 'warning':
                        _title = 'Warning';
                        _icon = Ext.Msg.WARNING;
                        break;
                    case 'question':
                        _title = 'Question';
                        _icon = Ext.Msg.QUESTION;
                        break;
                    case 'error':
                        _title = 'Error';
                        _icon = Ext.Msg.ERROR;
                        break;
                }
                
                Ext.Msg.show({
                    title: _title,
                    msg: _message,
                    buttons: _buttons,
                    icon: _icon
                });
                
            }
            
        },
        
        /**
         * Creates an invisible iframe used to download reports
         * @param {string} el - optional, defaults to 'download-frame'
         */
        createDownloadWin: function(el){
            var winId = el || 'download-frame';
            var win = Ext.getDom(winId);
            if (!win) {
                win = Ext.DomHelper.insertAfter(document.body, {
                    tag: 'iframe',
                    id: winId,
                    width: 0,
                    height: 0,
                    frameborder: 0,
                    style: 'display:none;'
                });
            }
            return win;
        },
        
        /**
         * Opens new window, of the specified size.
         * @param {string} url - required
         * @param {string} id - optional, defaults to 'popup'
         * @param {int} width - optional, defaults to 1010
         * @param {int} height - optional, defaults to 585
         */
        popUpWindow: function(url, id, width, height){
        
            var _width = width || 1010;
            var _height = height || 585;
            var _props = 'height=' + _height + ',width=' + _width + ',status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0';
            var _id = id || 'popup';
            
            window.open(url, _id, _props);
        },
        
        /**
         * Creates an object of pagination buttons and metadata
         * for use in a paginated view.
         *
         * @param Int total
         * @param Int currentPage
         */
        pagination: function(total, currentPage){
            var top = parseInt(total);
            var result = {
                meta: {
                    usePrev: (currentPage == 1) ? false : true,
                    useNext: (currentPage == top) ? false : true
                },
                data: []
            };
            var doneBeforeCurrent, doneAfterCurrent = false;
            for (var i = 1; i <= top; i++) {
                if (i == 1 || i == top || i == currentPage || i == currentPage + 1 || (currentPage == 1 && i == 3) || (currentPage == top && i == top - 3) || (i == currentPage - 1 && currentPage - 1 > 0)) {
                    var page = {
                        label: i,
                        className: (i == currentPage) ? 'active' : ''
                    }
                    result.data.push(page);
                }
                else 
                    if (i < currentPage && !doneBeforeCurrent) {
                        doneBeforeCurrent = true;
                        var page = {
                            label: '...',
                            className: 'empty'
                        }
                        result.data.push(page);
                    }
                    else 
                        if (i > currentPage && !doneAfterCurrent) {
                            doneAfterCurrent = true;
                            var page = {
                                label: '...',
                                className: 'empty'
                            }
                            result.data.push(page);
                        }
            }
            return result;
        },
        
        trim: function(str, chars){
            return this.ltrim(this.rtrim(str, chars), chars);
        },
        
        ltrim: function(str, chars){
            chars = chars || "\\s";
            return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
        },
        
        rtrim: function(str, chars){
            chars = chars || "\\s";
            return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
        },
        
        fileListHelper: function(){
            Ext.each(Ext.select('.file-list').elements, function(dropdown){
                Ext.get(dropdown).addListener('change', function(e, el){
                    var url = el.value || '';
                    if (url !== '') {
                        el.selectedIndex = 0;
                        top.location = url;
                    }
                }, this, {
                    stopEvent: true
                });
            });
        }
        
    }
}();

// JS extensions

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to){
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

if (Ext) {
    if (!Ext.isEmpty(Ext.select('.file-list').elements)) {
        DJIndexes.Utils.fileListHelper();
    }
}
