
function AUTOREF_FORM_FIELDS(form) {
    var basicForm = form.getForm();
    if(_defined(form.fields)) {
        if(_DEBUG) alert('extjs: auto-reference allready exists in target object (\'field\' exists in form)');
    } else {
        form.fields = {};
        for(var i = 0; i < basicForm.items.getCount(); i++) {
            var field = basicForm.items.itemAt(i);
            var fieldName = null;
            if(_defined(field.name)) fieldName = field.name;
            else if(_defined(field.hiddenName)) fieldName = field.hiddenName;
            else alert('extjs: unnamed field');
            if(fieldName) {
                if(_defined(form[fieldName])) alert('extjs: form auto reference allready exists in target object');
                else form[fieldName] = field;
            }
        }
    }
}

function PAGING_TOOLBAR(config) {
    return (new PagingToolbar()).genTemplate(config);
}

//---[ PagingToolbar ]----------------------------------------------------------------------------------------------------

function PagingToolbar() {

    this.construct();
}

PagingToolbar.prototype.construct = function() {

    this.position = 0;
    this.page = 1;
    this.totalRows = 0;
    this.totalPages = 0;
    this.toolbar = null;
	this.profile = '__main__';
}

PagingToolbar.prototype.genTemplate = function(config) {

	this.profiles = {
		__main__: {
			pageSize: _defined(config.pageSize) ? config.pageSize : 0,
			module: _defined(config.module) ? config.module : '',
			action: _defined(config.action) ? config.action : '',
			query: _defined(config.query) ? config.query : function(data) { return data; },
			response: _defined(config.response) ? config.response : function(data) { return data.xmldata.rows; },
			total: _defined(config.total) ? config.total : function(data) { return data.xmldata.total; }
		}
	};
	
	if(_defined(config.profiles))
		for(var i in config.profiles)
			this.profiles[i] = config.profiles[i];
	
	this.loadProfile('__main__');

	// default: on
	this.search = _undefined(config.search) || (_defined(config.search) && config.search);
	
	// default: off
	this.showTotal = _defined(config.showTotal) && config.showTotal;
	
    this.store = config.store;
    this.store.pager = this;
    this.searchFields = config.searchFields;
    this.displaySummary = _defined(config.displaySummary) ? config.displaySummary : false;

    this.filter = null;
    if(_defined(config.filter)) {
        this.filter = {};
        for(var i = 0; i < config.filter.length; i++) {
            this.filter[config.filter[i]] = true;
        }
    }

    return this._genTemplate();
}

PagingToolbar.prototype.loadProfile = function(name) {

	this.profile = name;

	// reset the profile
	for(var i in this.profiles.__main__)
		this[i] = this.profiles.__main__[i];
	
	// load the appropriate on if not __main__
	if(name != '__main__')
		for(var i in this.profiles[name])
			this[i] = this.profiles[name][i]
};

PagingToolbar.prototype._genTemplate = function() {

    var searchMenu = [{
        text: 'All',
        icon: 'library/client/ext-3.0.0/resources/images/default/s.gif',
        checked: true,
        hideOnClick: false
    },'-'];
    
	if(_defined(this.searchFields)) {
		for(var i = 0; i < this.searchFields.length; i++) {
			searchMenu.push({
				text: this.searchFields[i],
				icon: 'library/client/ext-3.0.0/resources/images/default/s.gif',
				checked: false,
				hideOnClick: false
			});
		}
	}

    this.toolbar = new Ext.Toolbar([{
        ref: 'firstPage',
	    icon: 'library/client/ext-3.0.0/resources/images/default/grid/page-first.gif',
	    disabled: true,
	    handler: function() {
	        this.firstPage();
	    },
	    scope: this
	},{
	    ref: 'prevPage',
	    icon: 'library/client/ext-3.0.0/resources/images/default/grid/page-prev.gif',
	    disabled: true,
	    handler: function() {
	        this.prevPage();
	    },
	    scope: this
	},'-',{
	    xtype: 'label',
	    ref: 'pageIndicator',
	    text: '1 of 1'
	    /*xtype: 'numberfield',
	    ref: 'currentPage',
	    cls: 'x-tbar-page-number',
	    style: 'margin:0px 5px 0px 5px',
	    readOnly: true,
	    value: 1
	},{
	    xtype: 'label',
	    ref: 'totalPages',
	    text: 'of 0'*/
	},'-',{
	    ref: 'nextPage',
	    icon: 'library/client/ext-3.0.0/resources/images/default/grid/page-next.gif',
	    handler: function() {
	        this.nextPage();
	    },
	    scope: this
	},{
	    ref: 'lastPage',
	    icon: 'library/client/ext-3.0.0/resources/images/default/grid/page-last.gif',
	    handler: function() {
	        this.lastPage();
	    },
	    scope: this
	},'-',{
	    icon: 'library/client/ext-3.0.0/resources/images/default/grid/refresh.gif',
	    handler: function() {
	        this.refresh();
	    },
	    scope: this
	},'-',{
	    text: 'Search',
		hidden: !this.search,
	    ref: 'searchMenu',
	    menu: searchMenu
	},{
	    xtype: 'textfield',
		hidden: !this.search,
	    ref: 'searchbox',
	    width: '100%',
	    enableKeyEvents: true,
	    listeners: {
	        keydown: function(textfield, event) {
		        if(event.getKey() == event.ENTER) this.load();
	        }.bind(this),
	        change: function(textfield, newValue, oldValue) {
	            this.load();
	        }.bind(this)
	    }
	},{
		hidden: !this.search,
	    icon: 'library/client/ext-3.0.0/resources/images/default/tabs/tab-close.gif',
	    handler: function() {
	        this.toolbar.searchbox.setValue('');
	        this.load();
	    },
	    scope: this
	},'->',{
		xtype: 'label',
		ref: 'total',
		hidden: !this.showTotal,
		text: 'Total: 0'
	},' ']);

	return this.toolbar;
}

PagingToolbar.prototype.init = function(grid) {

    this.grid = grid;
    
    if(this.filter != null) {
    
        var items = [];
        for(var i in this.filter) items.push({
            text: i,
            checked: true,
            listeners: {
                checkchange: function(menuItem, checked) {
                    this.filter[menuItem.text] = checked;
                    this.load();
                }.bind(this)
            }
        });
    
        this.grid.getTopToolbar().add(['->', {
            text: 'Filter',
            menu: items
        }]);
    }
    
    this.load();
}

PagingToolbar.prototype.getSearchParams = function() {

	var searchFields = [];
	if(_defined(this.searchFields)) {
		for(var i = 0; i < this.searchFields.length; i++)
			if(this.toolbar.searchMenu.menu.items.items[i + 2].checked)
				searchFields.push(this.searchFields[i]);
	}
	
	return {
		therm: this.toolbar.searchbox.getValue(),
		all: this.toolbar.searchMenu.menu.items.items[0].checked,
		fields: searchFields
	};
}

PagingToolbar.prototype.load = function() {

    application.startLoad();
    var doc = new JSON.Document('packet', JSON.DefaultPacket(this.module, this.action));
    var root = this.query(doc[doc.rootNode]);
	
    root.query.paging = {
        start: this.position,
        count: this.pageSize
    };

    /*var searchFields = [];
	if(_defined(this.searchFields)) {
		for(var i = 0; i < this.searchFields.length; i++)
			if(this.toolbar.searchMenu.menu.items.items[i + 2].checked)
				searchFields.push(this.searchFields[i]);
	}

	if(this.search) {
		root.query.search = {
			therm: this.toolbar.searchbox.getValue(),
			all: this.toolbar.searchMenu.menu.items.items[0].checked,
			fields: searchFields
		}
	}*/
	
	if(this.search) root.query.search = this.getSearchParams();
    
    if(this.filter != null) {
        root.query.filter = this.filter;
    }

    var req = new JSON.Request(function(response) {
        this.totalRows = this.total(response[response.rootNode]);
		if(this.showTotal) this.toolbar.total.setText('Total: ' + this.totalRows);
        this.totalPages = Math.max(1, Math.ceil(this.totalRows / this.pageSize));
        // jump backwards if the total changed and we are higher than we should
        if(this.position >= this.totalRows) {
            this.page = Math.max(1, this.totalPages);
            this.position = Math.max(0, (this.page - 1) * this.pageSize);
        }
        this.store.loadData(this.response(response[response.rootNode]));
        this.updateControls();
        application.stopLoad();
    }.bind(this));
    req.send(application.server, doc);
}

PagingToolbar.prototype.updateControls = function() {

    //this.toolbar.currentPage.setValue(this.page);
    //this.toolbar.totalPages.setText('of ' + this.totalPages);
    this.toolbar.pageIndicator.setText(this.page + ' / ' + this.totalPages);

    if(this.page == 1) {
        this.toolbar.firstPage.disable();
        this.toolbar.prevPage.disable();
    } else {
        this.toolbar.firstPage.enable();
        this.toolbar.prevPage.enable();
    }
    
    if(this.page == this.totalPages) {
        this.toolbar.lastPage.disable();
        this.toolbar.nextPage.disable();
    } else {
        this.toolbar.lastPage.enable();
        this.toolbar.nextPage.enable();
    }
}

PagingToolbar.prototype.refresh = function() {

    this.load();
}

PagingToolbar.prototype.firstPage = function() {

    this.position = 0;
    this.page = 1;
    this.load();
}

PagingToolbar.prototype.lastPage = function() {

    this.position = (this.totalPages - 1) * this.pageSize;
    this.page = this.totalPages;
    this.load();
}

PagingToolbar.prototype.nextPage = function() {

    this.position += this.pageSize;
    if(this.position > (this.totalRows - 1)) this.position = this.totalRows - 1;
    this.page++;
    this.load();
}

PagingToolbar.prototype.prevPage = function() {

    this.position -= this.pageSize;
    if(this.position < 0) this.position = 0;
    this.page--;
    this.load();
}

//---[ GridButtonPlugin ]-------------------------------------------------------------------------------------------------

GridButtonPlugin = function(config) {
    Ext.apply(this, config);
    if(!this.id) this.id = Ext.id();
    this.renderer = this.renderer.createDelegate(this);
};

GridButtonPlugin.prototype = {

    init : function(grid) {

        this.grid = grid;
        this.grid.on('render', function() {
            this.grid.getView().mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t) {
        if(this.grid.getView().findCellIndex(t) == 0) {
        
            e.stopEvent();

            if(t.className && t.className.indexOf('rowaction-delete-row') != -1) {
            
                this.grid.stopEditing();
                var index = this.grid.getView().findRowIndex(t);
                var record = this.grid.getStore().getAt(index);
            
                var proceed = _defined(this.beforeclick) ? this.beforeclick(record, index) != false : true;
                if(proceed) this.deleteRow(index);
            }
        }
    },
    
    deleteRow: function(index) {
        
        var record = this.grid.getStore().getAt(index);
        if(_defined(this.click)) this.click(record);
 
        var row = this.grid.getView().getRow(index);
        var rowEl = new Ext.Element(row);
        rowEl.syncFx();
        rowEl.slideOut('t', {
            easing: 'easeOut',
            duration: .2,
            remove: false,
            useDisplay: false,
            callback: function() {
                var data = this.grid.store.getAt(index).data;
                this.grid.store.removeAt(index);
            }.bind(this)
        });
    },

    renderer : function(value, metadata, record, rowIndex, colIndex, store) {
        metadata.css += ' rowaction-delete-row-ext-' + this.id;
        return '<div class="rowaction-delete-row">&#160;</div>';
    }
};

//---[ PRINT_BUTTON ]-----------------------------------------------------------------------------------------------------

function PRINT_BUTTON(config) {

    var default_config = {
       module: 'core_print',
       action: 'printList',
       callback: null,
       font_size: 9,
       font_style: 'arial',
       font_color: '000000',
       orientation: 'portrait',
       page_size: 'LETTER',
       background_color: 'FFFFFF',
       title: '',
       show_page_numbers: true,
       disabled: false,
       display_summary: false
    };

    for(var i in default_config)
        if(_undefined(config[i]))
            config[i] = default_config[i];

    return {
    
        text: 'Export grid',
        tooltip:'Export this grid on a Pdf or Excel file',
        xtype: 'tbbutton',
        icon:'images/icons/page_white_go.png',
        disabled: config.disabled,
        menu : {
            items: [{
                itemId: 'font_size',
                text: 'Font size',
                icon:'images/icons/font_add.png',
                menu: {        // <-- submenu by nested config object
                    items: [
                        {
                            itemId: 'size_6',
                            text: '6 pts',
                            checked: (config.font_size == 6),
                            group: 'size'
                        }, {
                            itemId: 'size_7',
                            text: '7 pts',
                            checked: (config.font_size == 7),
                            group: 'size'
                        }, {
                            itemId: 'size_8',
                            text: '8 pts',
                            checked: (config.font_size == 8),
                            group: 'size'
                        }, {
                            itemId: 'size_9',
                            text: '9 pts',
                            checked: (config.font_size == 9),
                            group: 'size'
                        }, {
                            itemId: 'size_10',
                            text: '10 pts',
                            checked: (config.font_size == 10),
                            group: 'size'
                        }, {
                            itemId: 'size_11',
                            text: '11 pts',
                            checked: (config.font_size == 11),
                            group: 'size'
                        }, {
                            itemId: 'size_12',
                            text: '12 pts',
                            checked: (config.font_size == 12),
                            group: 'size'
                        }, {
                            itemId: 'size_13',
                            text: '13 pts',
                            checked: (config.font_size == 13),
                            group: 'size'
                        }, {
                            itemId: 'size_14',
                            text: '14 pts',
                            checked: (config.font_size == 14),
                            group: 'size'
                        }
                    ]
                }
            }, {
                itemId: 'font_style',
                text: 'Font style',
                icon:'images/icons/font.png',
                menu: {        // <-- submenu by nested config object
                    items: [{
                            itemId: 'font_style_helvetica',
                            text: '<div style="font-family:helvetica">Helvetica</div>',
                            checked: (config.font_style == 'Helvetica'),
                            group: 'font_style'
                        }, {
                            itemId: 'font_style_arial',
                            text: '<div style="font-family:arial">Arial</div>',
                            checked: (config.font_style == 'arial'),
                            group: 'font_style'
                        }, {
                            itemId: 'font_style_timesnewroman',
                            text: '<div style="font-family:\'Times New Roman\', Times, serifarial">Time New Roman</div>',
                            checked: (config.font_style == 'Times-Roman'),
                            group: 'font_style'
                        }, {
                            itemId: 'font_style_courier',
                            text: '<div style="font-family: Courier, monospace;">Courier</div>',
                            checked: (config.font_style == 'Courier'),
                            group: 'font_style'
                        }
                    ]
                }
            }, {
                itemId: 'font_color',
                text: 'Font color',
                icon:'images/icons/color_swatch.png',
                menu: {        // <-- submenu by nested config object
                    items: [{
                        xtype: 'colorpalette',
                        itemId: 'font_color_color',
                        value: config.font_color
                    }]
                }
            },'-', {
                itemId: 'orientation',
                text: 'Orientation',
                icon:'images/icons/arrow_turn_right.png',
                menu: {        // <-- submenu by nested config object
                    items: [{
                            itemId: 'orientation_portrait',
                            text: 'Portrait',
                            checked: (config.orientation == 'portrait'),
                            group: 'orientation'
                        }, {
                            itemId: 'orientation_landscape',
                            text: 'Landscape',
                            checked: (config.orientation == 'landscape'),
                            group: 'orientation'
                        }
                    ]
                }
            }, {
                itemId: 'page_size',
                text: 'Page size',
                icon:'images/icons/page.png',
                menu: {        // <-- submenu by nested config object
                    items: [{
                            itemId: 'page_size_letter',
                            text: 'Letter',
                            checked: (config.page_size == 'LETTER'),
                            group: 'page_size'
                        }, {
                            itemId: 'page_size_legal',
                            text: 'Legal',
                            checked: (config.page_size == 'LEGAL'),
                            group: 'page_size'
                        }
                    ]
                }
            },'-', {
                itemId: 'background_color',
                disabled: true,
                text: 'Background color',
                icon:'images/icons/color_swatch.png',
                menu: {        // <-- submenu by nested config object
                    items: [{
                        xtype: 'colorpalette',
                        itemId: 'background_color_color',
                        value: config.background_color
                    }]
                }
            },'-', {
                xtype: 'textfield',
                itemId: 'title',
                value: config.title,
                emptyText: 'Custom title...'
                
            }, {
                itemId: 'show_page_numbers',
                text: 'Page numbers',
                checked: config.show_page_numbers
                
            },{
                itemId: 'display_summary',
                text: 'Display summaries',
                checked: config.display_summary
            },'-',{
                text: 'Export as PDF',
                icon:'images/icons/page_white_acrobat.png',
                handler: function(button) {     
                	application.startLoad();
                
                    // collect print params
                    
                    var values = {
                        font_size: {
                            size_6: 6,
                            size_7: 7,
                            size_8: 8,
                            size_9: 9,
                            size_10: 10,
                            size_11: 11,
                            size_12: 12,
                            size_13: 13,
                            size_14: 14
                        },
                        orientation: {
                            orientation_portrait: 'portrait',
                            orientation_landscape: 'landscape'
                        },
                        font_style: {
                            font_style_helvetica: 'Helvetica',
                            font_style_arial: 'arial',
                            font_style_timesnewroman: 'Times-Roman',
                            font_style_courier: 'Courier'
                        },
                        page_size: {
                            page_size_letter: 'LETTER',
                            page_size_legal: 'LEGAL'
                        }
                    }
                    
                    var components = {
                        font_size: button.parentMenu.getComponent('font_size'),
                        orientation: button.parentMenu.getComponent('orientation'),
                        font_style: button.parentMenu.getComponent('font_style'),
                        page_size: button.parentMenu.getComponent('page_size')
                    };
                    
                    var params = {};
                    
                    for(var comp in components) {
                        for(var v in values[comp]) {
                            if(components[comp].menu.getComponent(v).checked) {
                                params[comp] = values[comp][v];
                                break;
                            }
                        }
                    }
                    
                    params.font_color = button.parentMenu.getComponent('font_color').menu.getComponent('font_color_color').value;
                    params.background_color = button.parentMenu.getComponent('background_color').menu.getComponent('background_color_color').value;
                    params.title = button.parentMenu.getComponent('title').getValue();
                    params.show_page_numbers = button.parentMenu.getComponent('show_page_numbers').checked;
                    params.display_summary = button.parentMenu.getComponent('display_summary').checked;
                    
                    // print it

			        var grid = config.wnd.components[config.gridId]
                    var gridData = _defined(config.dataHandler) ? config.dataHandler(grid) : gatherGridVisibleData(grid, _defined(config.dataSource));

                    var doc = new JSON.Document('packet', JSON.DefaultPacket(config.module, config.action));
                    doc.packet.xmldata = {
                        params: params,
                        type: 'pdf',
                        columns: gridData.columns,
                        data: gridData.data
                    };
					
					if(_defined(config.dataSource)) {
					
						var args = typeof(config.dataSource.args) == 'function' ? config.dataSource.args() : config.dataSource.args;
						doc.packet.xmldata.dataSource = {
							module: config.dataSource.module,
							method: config.dataSource.method,
							args: args
						};
					}
                    
                    var req = new JSON.Request(function(response) {
                        application.stopLoad();
                        if(config.callback) config.callback(response);
                    }.bind(this));
                    req.send(application.server, doc);

                }
            },{
                text: 'Export as Excel',
                icon:'images/icons/page_white_excel.png',
                handler: function(button) {
                	application.startLoad();
                
                    // collect print params
                    
                    var values = {
                        font_size: {
                            size_6: 6,
                            size_7: 7,
                            size_8: 8,
                            size_9: 9,
                            size_10: 10,
                            size_11: 11,
                            size_12: 12,
                            size_13: 13,
                            size_14: 14
                        },
                        orientation: {
                            orientation_portrait: 'portrait',
                            orientation_landscape: 'landscape'
                        },
                        font_style: {
                            font_style_helvetica: 'Helvetica',
                            font_style_arial: 'arial',
                            font_style_timesnewroman: 'Times-Roman',
                            font_style_courier: 'Courier'
                        },
                        page_size: {
                            page_size_letter: 'LETTER',
                            page_size_legal: 'LEGAL'
                        }
                    }
                    
                    var components = {
                        font_size: button.parentMenu.getComponent('font_size'),
                        orientation: button.parentMenu.getComponent('orientation'),
                        font_style: button.parentMenu.getComponent('font_style'),
                        page_size: button.parentMenu.getComponent('page_size')
                    };
                    
                    var params = {};
                    
                    for(var comp in components) {
                        for(var v in values[comp]) {
                            if(components[comp].menu.getComponent(v).checked) {
                                params[comp] = values[comp][v];
                                break;
                            }
                        }
                    }
                    
                    params.font_color = button.parentMenu.getComponent('font_color').menu.getComponent('font_color_color').value;
                    params.background_color = button.parentMenu.getComponent('background_color').menu.getComponent('background_color_color').value;
                    params.title = button.parentMenu.getComponent('title').getValue();
                    params.show_page_numbers = button.parentMenu.getComponent('show_page_numbers').checked;
                    params.display_summary = button.parentMenu.getComponent('display_summary').checked;
                    
                    // print it

			        var grid = config.wnd.components[config.gridId]
                    var gridData = _defined(config.dataHandler) ? config.dataHandler(grid) : gatherGridVisibleData(grid, _defined(config.dataSource));

                    var doc = new JSON.Document('packet', JSON.DefaultPacket(config.module, config.action));
                    doc.packet.xmldata = {
                        params: params,
                        type: 'excel',
                        columns: gridData.columns,
                        data: gridData.data
                    };

					if(_defined(config.dataSource)) {
					
						var args = typeof(config.dataSource.args) == 'function' ? config.dataSource.args() : config.dataSource.args;
						doc.packet.xmldata.dataSource = {
							module: config.dataSource.module,
							method: config.dataSource.method,
							args: args
						};
					}
                    
                    var req = new JSON.Request(function(response) {
                        application.stopLoad();
                        if(config.callback) config.callback(response);
                    }.bind(this));
                    req.send(application.server, doc);

                }
                
            }]
        },
    };
}

function gatherGridVisibleData(grid, remotePrint) {

    var store = grid.getStore();
	
	var dataIndexes = [];
    var columns = {};
	var converts = {};
    for(var i = 0; i < grid.getColumnModel().getColumnCount(); i++) {
        var column = grid.getColumnModel().getColumnById(grid.getColumnModel().getColumnId(i));
        if(
			// don't print if there's no header
				_defined(column.header)
			// don't print if there's no dataIndex
			&&	_defined(column.dataIndex)
			// don't print if the column is hidden
			&&	!grid.getColumnModel().isHidden(i)
			// don't print if column.corePrint{ hidden: true }
			&&	(
						!_defined(column.corePrint)
					||	!_defined(column.corePrint.hidden)
					||	!column.corePrint.hidden
				)
		) {
			dataIndexes.push(column.dataIndex);
			
			var colConfig = {
				name: column.header,
				coreType: 'default',
				width: grid.getColumnModel().getColumnWidth(i)
			};
			
			// keep it backward compatible
			if(_defined(column.coreType)) colConfig.coreType = column.coreType;
			
			// new config model
			if(_defined(column.corePrint)) {
			
				var cp = column.corePrint;
				
				if(_defined(cp.header)) colConfig.name = cp.header;
				
				if(_defined(cp.type)) {
				
					colConfig.coreType = cp.type;
				
					if(cp.type == 'date') {
					
						var dateFormat = 'Y-m-d';
						if(_defined(cp.format)) dateFormat = cp.format;
						colConfig.format = dateFormat;						
					}
				}
				
				if(_defined(cp.convert)) {
				
					colConfig.convert = cp.convert;
					
					switch(cp.convert) {
					
					// look-up table
					case 'lut':		colConfig.lut = cp.lut;
									break;
					
					// date
					case 'date':	colConfig.dateFormat = cp.dateFormat;
									break;
					}
				};
			}
		
			columns[column.dataIndex] = colConfig;
		}
    }

	
	var data = [];
	if(!remotePrint) {
		for(var i = 0; i < store.getCount(); i++) {
			var rec_data = store.getAt(i).data;
			var row = {};
			for(var j = 0; j < dataIndexes.length; j++) {
			
				var dataIndex = dataIndexes[j];
				var value = rec_data[dataIndex];
				
				if(columns[dataIndex].coreType == 'date') value = parseInt(value.valueOf() / 1000);
				
				if(_defined(columns[dataIndex].convert)) {
				
					if(columns[dataIndex].convert == 'date') value = parseInt(value.valueOf() / 1000);
				}
				
				row[dataIndex] = value;
			}
			data.push(row);
		}
	}

    return {columns: columns, data: data};
}

