Ext.namespace('OTN.Helper');

/**
 * PrzeĹ‚adowuje grida.
 * @param string idGrid
 * @param object params JeĹĽeli atrybut params nie zostanie podany, wtedy
 * grid zostanie odĹ›wieĹĽony z parametrem "start". WartoĹ›Ä‡ tego parametru
 * zaleĹĽy od tego, czy podany grid posiada PagingToolbar. JeĹĽeli tak,
 * to zostanie pobrana aktualna pozycja wyĹ›wietlanej listy.
 */
OTN.Helper.reloadDS = function(idGrid, params){
    var grid = Ext.getCmp(idGrid);
    if (grid != null) {
        var ds = grid.getStore();
        if (typeof(params) == 'undefined') {
            var pager = grid.getBottomToolbar();
            var startPos = 0;
            if (typeof(pager) != 'undefined') {
                startPos = pager.cursor;
            }
            params = {
                params: {
                    start: startPos
                }
            };
        }
        ds.reload(params);
    }
}

OTN.Helper.btnSave_Click = function(btn){
    var form = btn.scope.formObj.form;
    var win = btn.scope.windowObj;
    var idGrid = btn.scope.gridId;
    var url = btn.scope.url;
    var params = btn.scope.params;
    var formParams = btn.scope.formParams;
    if (typeof(formParams) == 'undefined') {
        formParams = null;
    }
    
    if (form.isValid()) {
        form.submit({
            url: url,
            method: 'post',
            success: function(form, action){
                OTN.Helper.reloadDS(idGrid, params);
                if ((win != null) && (win != 'undefined')) {
                    win.close();
                }
            },
            failure: function(form, action){
                Ext.Msg.alert('BĹ‚Ä…d:', action.result.msg);
            },
            waitTitle: 'Przetwarzanie danych',
            waitMsg: 'Czekaj...',
            params: formParams
        });
    }
}


OTN.Helper.btnSave_Click_with_confirm = function(btn){
    var form = btn.scope.formObj.form;
    var win = btn.scope.windowObj;
    var idGrid = btn.scope.gridId;
    var url = btn.scope.url;
    var params = btn.scope.params;
    var formParams = btn.scope.formParams;
    
    if (typeof(formParams) == 'undefined') 
        formParams = null;
    
    if (form.isValid()) {
        form.submit({
            url: url,
            method: 'post',
            success: function(form, action){
                Ext.Msg.alert('Komunikat', 'Formularz został wysłany. Dziękujemy.');
                OTN.Helper.reloadDS(idGrid, params);
                if ((win != null) && (win != 'undefined')) 
                    win.close();
            },
            failure: function(form, action){
                Ext.Msg.alert('Błąd:', action.result.msg);
            },
            waitTitle: 'Przetwarzanie danych',
            waitMsg: 'Czekaj...',
            params: formParams
        });
    }
}


OTN.Helper.btnSave_Click_no_close = function(btn){
    var form = btn.scope.formObj.form;
    var win = btn.scope.windowObj;
    var idGrid = btn.scope.gridId;
    var url = btn.scope.url;
    var params = btn.scope.params;
    var formParams = btn.scope.formParams;
    if (typeof(formParams) == 'undefined') {
        formParams = null;
    }
    
    if (form.isValid()) {
        form.submit({
            url: url,
            method: 'post',
            success: function(form, action){
                OTN.Helper.reloadDS(idGrid, params);
                if ((win != null) && (win != 'undefined')) {
                    Ext.Msg.alert("Failure", "Zawodnik został dodany.");
                    
                    // czyscimy okna
                    //win.close();
                }
                form.reset();
            },
            failure: function(form, action){
                Ext.Msg.alert('Błąd:', action.result.msg);
            },
            waitTitle: 'Przetwarzanie danych',
            waitMsg: 'Czekaj...',
            params: formParams
        });
    }
    
}

OTN.Helper.btnDelete_Click = function(){
    var dg = Ext.getCmp(this.idGrid);
    var m = dg.getSelectionModel().getSelections();
    if (m.length > 0) {
        Ext.MessageBox.confirm('Message', 'Czy naprawdę chcesz usunąć zaznaczone elementy?', OTN.Helper.DeleteById, {
            idGrid: this.idGrid
        });
    }
    else {
        Ext.MessageBox.alert('Message', 'Proszę wybrać przynajmniej jeden element do usunięcia.');
    }
}

OTN.Helper.btnRefresh_Click = function(btn){
    OTN.Helper.reloadDS(this.idGrid, {
        params: {
            start: 0
        }
    });
}

OTN.Helper.DeleteById = function(btn){
    var dg = Ext.getCmp(this.idGrid);
    if (btn == 'yes') {
        var m = dg.getSelectionModel().getSelections();
        var jsonData = '[';
        for (var i = 0, len = m.length; i < len; i++) {
            var ss = "\"" + m[i].get('id') + "\"";
            if (i == 0) 
                jsonData = jsonData + ss;
            else 
                jsonData = jsonData + "," + ss;
        }
        jsonData = jsonData + "]";
        OTN.Helper.reloadDS(this.idGrid, {
            params: {
                delData: jsonData,
                start: 0
            }
        });
    }
}

OTN.Helper.ButtonColumn = function(config){
    config.sortable = false;
    
    this.addEvents({
        'click': true
    });
    
    OTN.Helper.ButtonColumn.superclass.constructor.call(this);
    
    Ext.apply(this, config, {
    
        init: function(grid){
            this.grid = grid;
            this.grid.on('render', function(){
                var view = this.grid.getView();
                view.mainBody.on('mousedown', this.onMouseDown, this);
            }, this);
        },
        
        onMouseDown: function(e, t){
            if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
                e.stopEvent();
                var index = this.grid.getView().findRowIndex(t);
                var record = this.grid.store.getAt(index);
                this.fireEvent('click', this, e, record, index);
            }
        },
        
        renderer: function(v, p, record){
            var result = '<div class="x-grid3-cc-' + this.id +
            ' grid-button-column ' +
            this.buttonClass +
            " " +
            ((record.data.data_sport == 0 && this.buttonClass == 'result_s') ? " result_s_deactive" : "") +
            ((record.data.data_theatre == 0 && this.buttonClass == 'result_t') ? " result_t_deactive" : "") +
            ((record.data.data_church == 0 && this.buttonClass == 'result_c') ? " result_c_deactive" : "") +
            ((record.data.data_mmo == 0 && this.buttonClass == 'result_mmo') ? " result_mmo_deactive" : "") +
            ((record.data.data_katyn == 0 && this.buttonClass == 'result_katyn') ? " result_katyn_deactive" : "") +
            '" ' +
            'title="' +
            this.tooltip +
            '"' +
            '>' +
            '&#160;</div>';
            return result;
        }
    });
    
    if (!this.id) {
        this.id = Ext.id();
    }
    
    if (typeof(this.tooltip) == 'undefined') {
        this.tooltip = '';
    }
    
    if (typeof(this.buttonType) == 'undefined') {
        this.buttonType = 'edit';
    }
    
    switch (this.buttonType) {
        case 'remove':
            this.buttonClass = 'remove';
            break;
        case 'add':
            this.buttonClass = 'add';
            break;
        case 'zoom':
            this.buttonClass = 'zoom';
            break;
        case 'copy':
            this.buttonClass = 'copy';
            break;
        case 'icon-grid':
            this.buttonClass = 'icon-grid';
            break;
        default:
            this.buttonClass = 'bogus';
            break;
    }
    
    this.renderer = this.renderer.createDelegate(this);
};

Ext.extend(OTN.Helper.ButtonColumn, Ext.util.Observable)

/**
 * @param int width
 * @param int height
 * @param string closeAction
 * @param bool modal
 * 
 * @return Ext.Window
 */
OTN.Helper.CreateWindow = function(title, width, height, closeAction, modal) {
	if ((title == null) || (title == 'undefined')) {
		title = '';
	}
	if ((width == null) || (width == 'undefined') || (width < 0)) {
		width = 640;
	}
	
	if ((height == null) || (height == 'undefined') || (height < 0)) {
		height = 480;
	}
	
	if ((closeAction == null) || (closeAction == 'undefined')) {
		closeAction = 'close';
	}
	
	if ((modal == null) || (modal == 'undefined')) {
		modal = true;
	}
	
	var helper = new OTN.Helper.WinLoader({});
	var win = new Ext.Window({
		title:				title,
		layout:				'fit',
		width:				width,
		height:				height,
		closeAction:	closeAction,
		plain:				true,
		modal:				modal,
		plugins:			[helper]
	});
	return win;
}

OTN.Helper.WinLoader = function (config) {
	Ext.apply(this, config, {
		init: function(win) {
	    this.win = win;
	    this.waitWindow.show();
	    win.on('show', this.hide, this);
	    win.on('destroy', this.hide, this);
	  },
	  hide: function() {
	  	this.waitWindow.hide();
	  }
	});
	
	if(!this.id){
		this.id = Ext.id();
	}
	
	if (typeof(this.waitMsg) == 'undefined') {
  	this.waitMsg = 'Czekaj...';
  }
  
  var waitMsg = '<table width="100%" height="100%" border="0"><tbody><tr><td align="center" valign="middle">'
  	+ this.waitMsg
  	+ '</td></tr></tbody></table>';
  
  this.waitWindow = new Ext.Window({
		closable: false,
		modal: true,
		resizable: false,
		plain: true,
		width: 200,
		height: 100,
		html: waitMsg
	});
};


