var DEVXEntry = function (data) {
	this.data = data;
    this.needClearAll = false;
    this.needFilterGrid = false;
    this.allData = new Array();
    this.currentRow = 0;
};

DEVXEntry.prototype.init = function() {
    customFilterPrefix = 'entry';
    this.searches = new Array();
    for (var i = 0; i < this.data['el_per_row']*this.data['row_per_page']; i++){
        this.searches[i] = this.addQuickSearch(i);
        this.allData[i] = {comp_name : '', comp_id : 0};
    }
    this.checkClearAll();
}

DEVXEntry.prototype.moveDown = function(count) {
    var newRow = this.currentRow + this.data['row_per_page'];
    for (var i = 0; i < this.data['el_per_row'] * count; i++){
        if (typeof(this.allData[i + this.data['el_per_row']*newRow]) == 'undefined') {
            this.allData[i + this.data['el_per_row']*newRow] = {comp_name : '', comp_id : 0};
        }
    }
    this.currentRow += count;
    this.updateFilters();
    getObj('btn_up').style.display = '';
}

DEVXEntry.prototype.moveUp = function(count) {
    if (this.currentRow == 0) {
        return;
    }
    this.currentRow -= count;
    if (this.currentRow  < 0) {
        this.currentRow = 0;
    }
    this.updateFilters();
    if (this.currentRow == 0) {
        getObj('btn_up').style.display = 'none';
    }
}

DEVXEntry.prototype.updateFilters = function() {
    for (var i = 0; i < this.data['el_per_row']*this.data['row_per_page']; i++){
        var record = this.allData[this.data['el_per_row']*this.currentRow + i];
        getObj(this.data['text_prefix'] + i).value = record.comp_name;
        var btn = getObj(this.data['btn_prefix']+i);
        if (record.comp_id != 0) {
            btn.style.display = '';
        } else {
            btn.style.display = 'none';
        }
    }
}

DEVXEntry.prototype.filterGrid = function(hdl, addorder) {
    addorder = (typeof(addorder) != 'undefined')?  addorder : true;
    if ((typeof(hdl) == 'undefined') && !this.needFilterGrid) {
        return;
    }
    var curr_hdl = (typeof(hdl) == 'undefined')? last_hdl : hdl;
    var ptype = current_grid;
    var vars = 'filters[]=user_id';
    for(var i = 0; i < this.allData.length; i++){
        if (!this.allData[i] || (this.allData[i].comp_id == 0)) {
            continue;
        }
        vars += '&user_id[]='+this.allData[i].comp_id;
    }
    var url = 'index.php?act=company&hdl='+curr_hdl+'_grid&use_entry=true';
    if (useFields && (document.getElementById('entryFilters').style.display == 'none')){
        url='index.php?act=company&hdl=field_grid&from_hdl='+curr_hdl+'_grid&use_entry=true';
        ptype = 'field';
        vars += getFields();
        document.getElementById('gridTabs').style.display = 'none';
    }else{
        document.getElementById('gridTabs').style.display = '';
    }
    document.getElementById('printType').value = ptype;
    vars += '&applyCustomFilter=true';
    loadGrid(curr_hdl, last_hdl, addorder, vars, url);
    if (Ext.get('btn_filter_grid')) {
        Ext.get('btn_filter_grid').addClass('btn_result_dis');
        Ext.get('btn_filter_grid').removeClass('btn_result');
    }
    this.needFilterGrid = false;
}

DEVXEntry.prototype.onChangeCompany = function(num, el) {
    var btn_name = this.data['btn_prefix']+num;
    var btn = getObj(btn_name);
    if (!btn) {
        return;
    }
    if (!this.searches[num].isExpanded()) {
        if (el.value != '') {
            el.value = this.allData[this.currentRow * this.data['el_per_row'] + num].comp_name;
            btn.style.display = ((el.value == '')? 'none' : '');
        } else {
            this.allData[this.currentRow * this.data['el_per_row'] + num] = {comp_id : 0, comp_name : ''};
            btn.style.display = 'none';
            //this.removeEmptyRow(num);
        }
    }
    Ext.get('btn_filter_grid').addClass('btn_result');
    Ext.get('btn_filter_grid').removeClass('btn_result_dis');
    this.needFilterGrid = true;
    this.checkClearAll();
}

DEVXEntry.prototype.removeEmptyRow = function (num) {
    // remove empty row if we not on the first row
    var rownum = Math.floor(num / this.data['el_per_row']);
    if ((this.currentRow == 0) || (rownum >= this.data['row_per_page'] - 1)) {
        return;
    }
    var needRemoveRow = true;
    for (var i = 0; i < this.data['el_per_row']; i++) {
        if (this.allData[(this.currentRow + rownum) * this.data['el_per_row'] + i].comp_id != 0){
            needRemoveRow = false;
            break;
        }
    }
    if (!needRemoveRow) {
        return;
    }
    // removed element from not top row - so we need to move up all elements.
    var len = this.allData.length;
    for (var i = (this.currentRow + rownum + 1)*this.data['el_per_row']; i < len; i++){
        this.allData[i - this.data['el_per_row']] = {
            comp_id : this.allData[i].comp_id,
            comp_name : this.allData[i].comp_name
        };
    }
    // clear last row
    for (var i = len; i > len - this.data['el_per_row']; i--) {
        this.allData[i] = {comp_name : '', comp_id : 0};
    }
    this.moveUp();
}

DEVXEntry.prototype.clearCompany = function(num, el) {
    var comp_name = this.data['text_prefix']+num;
    var comp = getObj(comp_name);
    if (!comp) {
        return;
    }
    comp.value = '';
    this.allData[this.currentRow * this.data['el_per_row'] + num] = {comp_id : 0, comp_name : ''};
    Ext.get('btn_filter_grid').addClass('btn_result');
    Ext.get('btn_filter_grid').removeClass('btn_result_dis');
    this.needFilterGrid = true;
    el.style.display = 'none';
    this.checkClearAll();
    this.saveNames();
    this.filterGrid()
}

DEVXEntry.prototype.checkClearAll = function() {
    this.needClearAll = false;
    for(var i = 0; i < this.allData.length; i++) {
        if (this.allData[i] && this.allData[i].comp_id != 0) {
            this.needClearAll = true;
            break;
        }
    }
    for(var k in customFiltersData) {
        if (customFiltersData[k].used) {
            this.needClearAll = true;
            break;
        }
    }
    if (this.needClearAll) {
        Ext.get('btn_clear_all').addClass('btn_reset');
        Ext.get('btn_clear_all').removeClass('btn_reset_dis');
    } else {
        Ext.get('btn_clear_all').addClass('btn_reset_dis');
        Ext.get('btn_clear_all').removeClass('btn_reset');
    }
}

DEVXEntry.prototype.clearAll = function(el) {
    if (!this.needClearAll) {
        return;
    }
    var have_custom_filter = false;
    for (var k in customFiltersData) {
        have_custom_filter = true;
        if (document.getElementById('x-grid3-top-cell-'+k)) {
            document.getElementById('x-grid3-top-cell-'+k).innerHTML = '<div unselectable="on" class="x-grid3-td-inner ">filter</div>';
        }
    }
    customFiltersData = {};
    if (have_custom_filter) {
        Ext.get('btn_filter_grid').addClass('btn_result');
        Ext.get('btn_filter_grid').removeClass('btn_result_dis');
        updClicked = false;
    }
    this.currentRow = 0;
    this.allData = new Array();
    for(var i = 0; i < this.data['el_per_row']*this.data['row_per_page']; i++) {
        this.allData[i] = {comp_name : '', comp_id : 0};
    }
    this.updateFilters();
    getObj('btn_up').style.display = 'none';
    Ext.get(el.id).addClass('btn_reset_dis');
    Ext.get(el.id).removeClass('btn_reset');
    Ext.get('btn_filter_grid').addClass('btn_result');
    Ext.get('btn_filter_grid').removeClass('btn_result_dis');
    this.needFilterGrid = true;
    this.saveNames();
    var prefix = (typeof(customFilterPrefix) != 'undefined')? '&prefix='+customFilterPrefix : '';
    var s = this;
    loader.data['onerror'] = function(){};
    loader.processGET('index.php?act=filters&hdl=clear_custom_all'+prefix, function(http){ s.filterGrid(); }, false, false);
}

DEVXEntry.prototype.addQuickSearch = function(elNum) {
    var s = this;
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'index.php?act=company&hdl=quick_search&use_page=true',
            method : 'GET'
        }),
        reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'total',
            id: 'comp_id'
        }, [
            {name: 'exchange', mapping: 'exchange'},
            {name: 'sexchange', mapping: 'sexchange'},
            {name: 'ticker', mapping: 'ticker'},
            {name: 'user_id', mapping: 'user_id'},
            {name: 'type_', mapping: 'type_'},
            {name: 'conf_status', mapping: 'conf_status'},
            {name: 'company_name', mapping: 'company_name'},
            {name: 'query', mapping: 'query'}
        ])
    });

    // Custom rendering Template
    var resultTpl;

    var search = new Ext.form.ComboBox({
        store: ds,
        minChars : 1,
        displayField:'title',
        typeAhead: false,
        loadingText: 'Searching...',
        listWidth : 400,
        queryDelay: 100,
        pageSize:10,
        hideTrigger:true,
        tpl: resultTpl,
        applyTo: this.data['text_prefix']+elNum,
        elNum : elNum,
        itemSelector: 'tr.search-item',
        onRender : function(ct, position){
            Ext.form.Field.superclass.onRender.call(this, ct, position);
            if(!this.el){
                var cfg = this.getAutoCreate();
                if(!cfg.name){
                    cfg.name = this.name || this.id;
                }
                if(this.inputType){
                    cfg.type = this.inputType;
                }
                this.el = ct.createChild(cfg, position);
            }
            if(this.readOnly){
                this.el.dom.readOnly = true;
            }
            if(this.tabIndex !== undefined){
                this.el.dom.setAttribute('tabIndex', this.tabIndex);
            }

            this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
            this.trigger = this.wrap.createChild(this.triggerConfig ||
                    {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
            if(this.hideTrigger){
                this.trigger.setDisplayed(false);
            }
            this.initTrigger();
            if(this.hiddenName){
                this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
                        id: (this.hiddenId||this.hiddenName)}, 'before', true);

                // prevent input submission
                this.el.dom.removeAttribute('name');
            }
            if(Ext.isGecko){
                this.el.dom.setAttribute('autocomplete', 'off');
            }

            if(!this.lazyInit){
                this.initList();
            }else{
                this.on('focus', this.initList, this, {single: true});
            }

            if(!this.editable){
                this.editable = true;
                this.setEditable(false);
            }
        },
        restrictHeight : function(){
            this.innerList.dom.style.height = '';
            var inner = this.innerList.dom;
            var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight;
            var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
            var ha = this.getPosition()[1]-Ext.getBody().getScroll().top;
            var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height;
            var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset;
            h = Math.min(h, space, this.maxHeight);
            pad -= 4;

            this.innerList.setHeight(h);
            this.list.beginUpdate();
            this.list.setHeight(h+pad);
            var alignX = 0;
            var alignY = 0;
            if (Ext.isGecko){
                alignX = 1;
            }else if (Ext.isIE8){
                alignY = 4;
            }else if (Ext.isIE){
                alignY = -2;
            }else if (Ext.isChrome){
                alignY = 2;
            }
            this.list.alignTo(this.wrap, this.listAlign, [alignX, alignY]);
            this.list.endUpdate();
        },
        expand : function(){
            if(this.isExpanded() || !this.hasFocus){
                return;
            }
            if (this.pageTb) {
                this.pageTb.loading.hide();
                this.pageTb.field.setHeight('');
                this.pageTb.field.setWidth('24px');
                this.pageTb.field.removeClass('x-tbar-page-number');
            }
            var alignX = 0;
            var alignY = 0;
            if (Ext.isIE8){
                alignY = 4;
            }else if (Ext.isIE){
                alignY = -2;
            }else if (Ext.isChrome){
                alignY = 2;
            }
            this.list.alignTo(this.wrap, this.listAlign, [alignX, alignY]);
            this.list.show();
            this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
            Ext.getDoc().on('mousewheel', this.collapseIf, this);
            Ext.getDoc().on('mousedown', this.collapseIf, this);
            this.fireEvent('expand', this);
        },
        onSelect: function(record){ // override default onSelect to do redirect
            for (var i = 0; i < s.allData.length; i++) {
                if (i == this.elNum + s.currentRow * s.data['el_per_row']) {
                    continue;
                }
                if (s.allData[i].comp_id == record.id) {
                    this.collapse();
                    return;
                }
            }
            s.allData[this.elNum + s.currentRow * s.data['el_per_row']] = {
                comp_id : record.id,
                comp_name : record.data.company_name
            };
            getObj(this.el.id).value = record.data.company_name;
            s.needClearAll = true;
            Ext.get('btn_clear_all').addClass('btn_reset');
            Ext.get('btn_clear_all').removeClass('btn_reset_dis');
            this.collapse();
            s.onChangeCompany(this.elNum, getObj(this.el.id));
            s.saveNames();
            s.filterGrid();
        }
    });
    search.on('beforequery', function(event){
        resultTpl = new Ext.XTemplate(
            '<table>',
            '<tpl for="."><tr class="search-item">',
                '<td style="width:30px;">{[this.highlight(values.ticker, values.query)]}</td>',
                '<td style="width:218px;">{[this.companyName(values.company_name, values.query)]}\n\
                    <tpl if="this.isImage(type_, conf_status)">\n\
                    <img src="img/stat{[this.getStatusId(values.type_, values.conf_status)]}.gif">\n\
                    </tpl></td>',
                '<td style="width:90px;padding-right:8px;text-align:right;font-size:10px;overflow:hidden;white-space:nowrap;"><div style="width:88px;overflow:hidden;white-space:nowrap;"><tpl if="this.notEmptyStr(exchange)">{exchange}<tpl if="this.notEmptyStr(sexchange)">, {sexchange}</tpl></tpl>',
                '<tpl if="this.notEmptyStr(exchange) == false"><tpl if="this.notEmptyStr(sexchange)">{sexchange}</tpl></tpl></div></td>',
            '</tr></tpl>',
            '</table>',
            {
                notEmptyStr : function (str){
                    return str > '';
                },
                companyName : function (str, query){
                    if (str.length > 35)
                        str = str.substr(0, 35) + '...';
                    return str.replace(new RegExp('('+query+')',"gi"), '<b>$1</b>');
                },
                isImage : function (type_, conf_status){
                    if (!conf_status) return false;
                    return ((type_ == 'C') || (conf_status == 'Y'));
                },
                getStatusId : function (type_, conf_status){
                    if ('C' == type_) {
                        if ('Y' == conf_status) return 3;
                        else if ('N' == conf_status) return 2;
                    } else {
                        if ('Y' == conf_status) return 1;
                    }
                    return 0;
                },
                highlight : function(str, query) {
                    return str.replace(new RegExp('^('+query+')',"gi"), '<b>$1</b>');
                }
            }
        );
        this.tpl = resultTpl;
        this.view.tpl = resultTpl;
        this.list.addClass('entry-qs');
        this.list.setStyle('z-index', '200000');
    });
    ds.on('load', function(store, records, options){
        var mult = 0;
        if (store.getTotalCount() > 10) {
            if (search.pageTb.hidden) {
                mult = 1;
            }
            search.pageTb.show();
            search.assetHeight += mult * search.footer.getHeight();
        } else {
            if (!search.pageTb.hidden) {
                mult = 1;
            }
            search.assetHeight -= mult * search.footer.getHeight();
            search.pageTb.hide();
        }
    });
    return search;
}

DEVXEntry.prototype.compareGrid = function() {
    document.getElementById('entryMainDiv').style.display = 'none';
    document.getElementById('entryFilters').style.display = 'none';
    document.getElementById('compareButton').style.display = 'none';
    if (document.getElementById('companyMenu')) document.getElementById('companyMenu').style.display = 'none';
    document.getElementById('allCompare').style.display = '';
    document.getElementById('compareDepth').style.display = '';
    this.needFilterGrid = true;
    this.filterGrid();
}

DEVXEntry.prototype.removeCompare = function() {
    document.getElementById('entryMainDiv').style.display = '';
    document.getElementById('entryFilters').style.display = '';
    document.getElementById('compareButton').style.display = '';
    if (document.getElementById('companyMenu')) document.getElementById('companyMenu').style.display = '';
    document.getElementById('allCompare').style.display = 'none';
    document.getElementById('compareDepth').style.display = 'none';
    this.needFilterGrid = true;
    this.filterGrid();
}

DEVXEntry.prototype.saveNames = function() {
    var url = 'index.php?act=filters&hdl=save_entry';
    for (var i = 0; i < this.allData.length; i++) {
        if (this.allData[i].comp_id == 0) {
            continue;
        }
        url += '&user_id[]='+this.allData[i].comp_id;
    }
    loader.data['onerror'] = function(){};
    loader.processGET(url, function(http){ return false;}, false, false);
}

var entry = new DEVXEntry({
    'text_prefix' : 'comp_text_',
    'btn_prefix' : 'comp_clear_',
    'el_per_row' : 4,
    'row_per_page' : 2
});
