///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Grid Panel
$.ui.panel.subclass('ui.grid_panel', {

	_init: function() {var grid = this.grid = this.options.grid;}, 
	callGrid: function(method, params) {
		if (this.grid && this.options.grid_widget) {
           return $.plugin(this.grid, this.options.grid_widget, method, params);
        } else return false;
	}
});
$.ui.grid_panel.defaults.extend({});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Grid Form
$.ui.form.subclass('ui.grid_form', {

	_init: function() {var grid = this.grid = this.options.grid;}, 
	callGrid: function(method, params) {
		if (this.grid && this.options.grid_widget) {
           return $.plugin(this.grid, this.options.grid_widget, method, params);
        }else return false;
	}, 
	submitHandler: function(responce) {
		this._super(responce);
		if (responce) {
			if (responce.result && !responce.close) this.close();
			if (responce.html && responce.html.dataset)	{
				this.callGrid('submitAddFormHandler', [responce.html.dataset]);
			}
		}
	}
});
$.ui.grid_form.defaults.extend({});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Grid Advanced Search Form
$.ui.grid_form.subclass('ui.grid_advanced_search_form', {

	submitHandler: function(responce) {
		if (responce) {
			if (responce.redirect_url) return window.location = responce.redirect_url;
			if (responce.html) {
				if (responce.html.fieldset) {
					this.recreateFieldSet(responce.html.fieldset);
				}
				if (responce.html.dataset)	{
					this.callGrid('recreateDataSet', [responce.html.dataset]);
				}
			}
		}
	}
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
$.ui.component.subclass('ui.grid', {
	// Init
	_init: function() {
		var self = this, 
			options = this.options,
			grid = this.grid = self.element, 
			gridHeader = this.gridHeader = grid.find(options.headerSelector), 
			gridBody = this.gridBody = grid.find(options.bodySelector), 
			gridFooter = this.gridFooter = grid.find(options.footerSelector), 
			gridButtons = this.gridButtons = grid.find(options.buttonsSelector), 
			gridDataSet = this.gridDataSet = gridBody.find(options.dataSetSelector);
		this.create();
	}, 
	// Grid
	getBodyObject: function(selector) {return this.gridBody.find(selector);}, 
	create: function() {		
		this.createBody();
		this.createHeader();
		this.createButtons();
	}, 
	destroy: function() {
		this.destroyHeader();
		this.destroyBody();
		this.destroyButtons();
	}, 
	// Header
	createHeader: function() {}, 
	destroyHeader: function() {}, 
	// Buttons
	createButtons: function() {
		var self = this;
		this.gridButtons.find(this.options.addButtonSelector).each(function() {
			$(this).bind('click', function() {self.add();});
		});
		this.gridButtons.find(this.options.advancedSearchButtonSelector).each(function() {
			$(this).bind('click', function() {self.advancedSearch();});
		});
		this.gridButtons.find(this.options.resetButtonSelector).each(function() {
			$(this).bind('click', function() {self.reset_();});
		});
		this.gridButtons.find(this.options.refreshButtonSelector).each(function() {
			$(this).bind('click', function() {self.refresh();});
		});
	}, 
	destroyButtons: function() {
		this.gridButtons.find(this.options.addButtonSelector).each(function() {$(this).unbind('click');});
		this.gridButtons.find(this.options.advancedSearchButtonSelector).each(function() {$(this).unbind('click');});
		this.gridButtons.find(this.options.resetButtonSelector).each(function() {$(this).unbind('click');});
		this.gridButtons.find(this.options.refreshButtonSelector).each(function() {$(this).unbind('click');});
	}, 
	// Body
	createBody: function() {
		this.createViewPanel();
		this.createAdvancedSearchForm();
		this.createAddForm();
		this.createEditForm();
		this.createDataSet();
	}, 
	destroyBody: function() {
		this.destroyViewPanel();
		this.destroyAdvancedSearchForm();
		this.destroyAddForm();
		this.destroyEditForm();
		this.destroyDataSet();
	}, 
	// Advanced Search Form
	callAdvancedSearchForm: function(method, params) {
		if ($.ui.form) return $.plugin(this.getBodyObject(this.options.advancedSearchForm.widgetSelector), this.options.advancedSearchForm.widget, method, params);
		else return false;
	}, 
	destroyAdvancedSearchForm: function() {
		this.callAdvancedSearchForm('destroy');
	}, 
	createAdvancedSearchForm: function() {
		this.callAdvancedSearchForm({grid: this.grid, grid_widget: this.options.widget});
	}, 
	showAdvancedSearchForm: function() {
		this.callAdvancedSearchForm('show');
	}, 
	hideAdvancedSearchForm: function() {
		this.callAdvancedSearchForm('hide');
	}, 
	// View Panel
	callViewPanel: function(method, params) {
		if ($.ui.panel) return $.plugin(this.getBodyObject(this.options.viewPanel.widgetSelector), this.options.viewPanel.widget, method, params);
		else return false;
	}, 
	destroyViewPanel: function() {
		this.callViewPanel('destroy');
	}, 
	createViewPanel: function() {
		this.viewPanel = this.callViewPanel({grid: this.grid, grid_widget: this.options.widget});
		this.callViewPanel('hide');
	}, 
	// Add Form
	callAddForm: function(method, params) {
		return $.plugin(this.getBodyObject(this.options.addForm.widgetSelector), this.options.addForm.widget, method, params);
	}, 
	destroyAddForm: function() {
		this.callAddForm('destroy');
	}, 
	createAddForm: function() {
		this.addForm = this.callAddForm({grid: this.grid, grid_widget: this.options.widget});
		this.callAddForm('hide');
	}, 
	// Edit Form
	callEditForm: function(method, params) {
		return $.plugin(this.getBodyObject(this.options.editForm.widgetSelector), this.options.editForm.widget, method, params);
	}, 
	destroyEditForm: function() {
		this.callEditForm('destroy');
	}, 
	createEditForm: function() {
		this.editForm = this.callEditForm({grid: this.grid, grid_widget: this.options.widget});
		this.callEditForm('hide');
	}, 
	// DataSet
	getDataSetContent: function() {
		return this.gridDataSet.find(this.options.dataSetContentSelector);
	}, 
	createDataSet: function() {
		this.createColumnSet();
		this.createRecordSet();
		var self = this;
		this.gridDataSet.find(this.options.pageButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.page($(this).attr('key'));});
		});
		this.gridDataSet.find(this.options.messagerSelector).each(function() {
			var object = $(this);
			object.unbind();
			object.bind('click', function() {$(this).slideUp('slow');});
		});
		this.gridDataSet.find(this.options.pagerResetLinkSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.reset_();});
		});
	}, 
	destroyDataSet: function() {
		this.destroyRecordSet();
		this.destroyColumnSet();
		this.gridDataSet.find(this.options.pageButtonSelector).each(function() {$(this).unbind('click');});
		this.gridDataSet.find(this.options.messagerSelector).each(function() {$(this).unbind();});
	}, 
	recreateDataSet: function(content) {
		this.destroyDataSet();
		this.gridDataSet.html(content);
		this.createDataSet();
	}, 
	showDataSet: function() {this.gridDataSet.show();},
	hideDataSet: function() {this.gridDataSet.hide();}, 
	// ColumnSet
	createColumnSet: function() {
		var self = this;
		this.getDataSetContent().find(this.options.sortButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.sort($(this).attr('column'), $(this).attr('dir_'));});
		});
		this.getDataSetContent().find(this.options.helpButtonSelector).tooltip();
	}, 
	destroyColumnSet: function() {
		this.getDataSetContent().find(this.options.sortButtonSelector).each(function() {$(this).unbind('click');});
	}, 
	// RecordSet
	createRecordSet: function() {
		var self = this;
		this.getDataSetContent().find('.grid-record-action-menu').each(function() {
			$(this).find('.jd_menu').jdMenu({});
		});
		this.getDataSetContent().find(this.options.viewButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.view($(this).attr('key'));});
		});
		this.getDataSetContent().find(this.options.editButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.edit($(this).attr('key'));});
		});
		this.getDataSetContent().find(this.options.downButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.down($(this).attr('key'));});
		});
		this.getDataSetContent().find(this.options.upButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.up($(this).attr('key'));});
		});
		this.getDataSetContent().find(this.options.deleteButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.delete_($(this).attr('key'), $(this).attr('message'));});
		});
		this.getDataSetContent().find(this.options.archiveButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.archive_($(this).attr('key'), $(this).attr('message'));});
		});
		this.getDataSetContent().find(this.options.changeStatusButtonSelector).each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {               
               self.changeStatus($(this).attr('key'), $(this).attr('status_'));
            });
		});
		this.getDataSetContent().find(this.options.sortOrderDragAndDropSelector).each(function() {
			$(this).sortable({placeholder: 'ui-state-highlight'});
			$(this).disableSelection();
			$(this).sortable('option', 'axis', 'y');
			$(this).bind('sortstop', function(event, ui) {                
				var resArr = new Array();
				var i=0;
				$(this).find('.ui-state-default').each(function (){                    
					resArr[i] = $(this).attr('key');
					i=i+1;
				});                
				self.sortOrderDragAndDrop(resArr[i-1],resArr.join('.'));
            });		
		});
	}, 
	destroyRecordSet: function() {
		this.getDataSetContent().find(this.options.viewButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.editButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.downButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.upButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.deleteButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.archiveButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.changeStatusButtonSelector).each(function() {$(this).unbind('click');});
		this.getDataSetContent().find(this.options.sortOrderDragAndDropSelector).each(function() {$(this).sortable( 'destroy' )});
	}, 

	hideControls: function() {
		this.callAddForm('hide');
		this.callAdvancedSearchForm('hide');
		this.callEditForm('hide');
		this.callViewPanel('hide');
	}, 
	
	getURL: function() {return this.grid.attr('url');}, 
	getId: function() {return this.grid.attr('id');}, 
	getPageOptions: function() {return {page: this.options.page};}, 
	callPage: function(method, params) {
		var options = this.getPageOptions();
		if (options && options.page && options.page.widget && options.page.object) 
			$.plugin(options.page.object, options.page.widget, method, params);
	}, 

	cmdViewHandler: function(responce, arguments) {
		if (responce.html) {
			this.callViewPanel('recreateBody', [responce.html.body]);
			this.callViewPanel('show');
		}
	}, 
    submitAddFormHandler:function(content) {
        this.recreateDataSet(content);
    },
	cmdAddHandler: function(responce, arguments) {
		if (responce.html) {
			this.callAddForm('recreateFieldSet', [responce.html.fieldset]);
			this.callAddForm('show');
		}
	}, 

	cmdEditHandler: function(responce, arguments) {
		if (responce.html) {
			this.callEditForm('recreateFieldSet', [responce.html.fieldset]);
			this.callEditForm('show');
		}
	}, 
	cmdChangeStatusHandler: function(responce, arguments) {
		if (responce.html && responce.html.dataset){
            this.recreateDataSet(responce.html.dataset);
        }
	},
	cmdDeleteHandler: function(responce, arguments) {
		if (responce.html && responce.html.dataset){
            this.recreateDataSet(responce.html.dataset);
        }
	},
	
	cmdCustomHandler: function(responce, arguments) {}, 
	
	cmdHandler: function(responce, arguments) {
		if (responce) {
			if (responce.redirect_url) return window.location = responce.redirect_url;
		}
		if (arguments.cmd) {
			if (arguments.cmd == 'view') this.cmdViewHandler(responce, arguments);
			if (arguments.cmd == 'add') this.cmdAddHandler(responce, arguments);
			if (arguments.cmd == 'edit') this.cmdEditHandler(responce, arguments);
			if (arguments.cmd == 'delete') this.cmdDeleteHandler(responce, arguments);
			if (arguments.cmd == 'change_status') this.cmdChangeStatusHandler(responce, arguments);
			this.cmdCustomHandler(responce, arguments);
			if (responce.html && responce.html.dataset) this.recreateDataSet(responce.html.dataset);
		}
	}, 
	getUID: function() {
		var newDate = new Date;
		return newDate.getTime();
	}, 
	cmd: function(cmd, query) {
		var url = this.getURL() + '/cmd/' + cmd;
		if (query) url += '/' + query;
		$.request({url: url, scope: this, func: this.cmdHandler, container: this.grid, arguments: {cmd: cmd, query: query}});
	}, 
	sort: function(column, dir) {this.cmd('sort', 'column/' + column + '/dir/' + dir);}, 
	page: function(page, dir) {this.cmd('page', 'page/' + page);}, 
	view: function(id) {this.hideControls(); this.cmd('view', 'id/' + id);}, 
	add: function() {this.hideControls(); this.cmd('add');}, 
	edit: function(id) {this.hideControls(); this.cmd('edit', 'id/' + id);}, 
	down: function(id) {this.cmd('down', 'id/' + id);}, 
	up: function(id) {this.cmd('up', 'id/' + id);}, 
	reset_: function() {this.cmd('reset');}, 
	refresh: function() {this.cmd('refresh');}, 
	search_: function(keyword) {this.cmd('search', 'keyword/' + escape(keyword));}, 
	advancedSearch: function() {
		this.hideControls(); 
		this.callAdvancedSearchForm('show');
	}, 
	delete_: function(id, message) {
		if (confirm(message)) {
			this.cmd('delete', 'id/' + id);
		}
	},
	archive_: function(id, message) {
		if (confirm(message)) {
			this.cmd('archive', 'id/' + id);
		}
	},
	changeStatus: function(id, status) {
		this.cmd('change_status', 'id/' + id+'/status/'+status);
	}, 
	sortOrderDragAndDrop: function(id, ids_array_as_string) {this.cmd('sort_order', 'id/'+id+'/ids_array_as_string/' + ids_array_as_string);}, 
	hasParentOptions: function() {
		return (this.options.parent && this.options.parent.widget && this.options.parent.object) ? true : false;
	}, 
	getParentOptions: function() {return this.options.parent;}, 
	callParent: function(method, params) {
		if (this.hasParentOptions()) {
			$.plugin(this.getParentOptions().object, this.getParentOptions().widget, method, params);
		}
	}
});
// Page Grid
$.ui.grid.subclass('ui.page_grid', {

	hasPageOptions: function() {
		return (this.options.page && this.options.page.widget && this.options.page.object) ? true : false;
	}, 
	getPageOptions: function() {return this.options.page;}, 
	callPage: function(method, params) {
		if (this.hasPageOptions()) {
			$.plugin(this.getPageOptions().object, this.getPageOptions().widget, method, params);
		}
	}
});
$.ui.grid.defaults.extend(
	{
		widget: 'grid', 
		
		headerSelector: '.grid-header', 
		bodySelector: '.grid-body', 
		footerSelector: '.grid-footer', 
		buttonsSelector: '.grid-buttons', 
		dataSetSelector: '.grid-dataset', 

		advancedSearchButtonSelector: '.advanced-search', 
		resetButtonSelector: '.reset', 
		addButtonSelector: '.add', 
		refreshButtonSelector: '.refresh', 
		
		advancedSearchForm: {widget: 'grid_advanced_search_form', widgetSelector: '.advanced-search-form'}, 
		viewPanel: {widget: 'grid_panel', widgetSelector: '.view-panel'}, 
		addForm: {widget: 'grid_form', widgetSelector: '.add-form'}, 
		editForm: {widget: 'grid_form', widgetSelector: '.edit-form'}, 

		dataSetContentSelector: '.grid-dataset-content', 
		pageButtonSelector: '.page', 
		messagerSelector: '.messager', 
		sortButtonSelector: '.sort', 
		helpButtonSelector: '.help', 

		viewButtonSelector: '.view', 
		editButtonSelector: '.edit', 
		upButtonSelector: '.up', 
		downButtonSelector: '.down', 
		deleteButtonSelector: '.delete',
		archiveButtonSelector: '.archive',
		changeStatusButtonSelector: '.change_status',
		sortOrderDragAndDropSelector: '#sortable-grid-recordset'
	}
);
