;(function($) {

//	var table;
//	var tableDiv;
//	var tableId;
//	var formElement;
//	var options;
	
	$.fn.loadTableOptions = [];
	
	$.fn.getTable = function(id) {
		var allOptions = $.fn.loadTableOptions;
		for (var i=0 ; i<allOptions.length; i++){
			if (allOptions[i].tableId == id){
				return allOptions[i].table;
			}
		}
		return null;
	};
	
	$.fn.getOptions = function(id) {
		var allOptions = $.fn.loadTableOptions;
		for (var i=0 ; i<allOptions.length; i++){
			if (allOptions[i].tableId == id){
				return allOptions[i];
			}
		}
		return null;
	};
	
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback )
	{
		if ( typeof sNewSource != 'undefined' )
		{
			oSettings.sAjaxSource = sNewSource;
		}
		this.fnClearTable( this );
		this.oApi._fnProcessingDisplay( oSettings, true );
		var that = this;
		
		$.getJSON( oSettings.sAjaxSource, null, function(json) {
			/* Got the data - add it to the table */
			for ( var i=0 ; i<json.aaData.length ; i++ )
			{
				that.oApi._fnAddData( oSettings, json.aaData[i] );
			}
			
			oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
			that.fnDraw( that );
			that.oApi._fnProcessingDisplay( oSettings, false );
			
			/* Callback user function - for event handlers etc */
			if ( typeof fnCallback == 'function' )
			{
				fnCallback( oSettings );
			}
		} );
	};
	
	$.fn.loadTable = function(customOptions) {
		
		var _options = $.fn.loadTableOptions;

		function optionsClass(customOptions) {
			
			this.aoColumns = (typeof customOptions.aoColumns == 'undefined') ? [] : customOptions.aoColumns;
			this.successMessage = (typeof customOptions.successMessage == 'undefined') ? "" : customOptions.successMessage;
			this.formTableElement = (typeof customOptions.formTableElement == 'undefined') ? null : customOptions.formTableElement;
			this.fnDrawCallback = (typeof customOptions.fnDrawCallback == 'undefined') ? null : customOptions.fnDrawCallback;
			this.sAjaxSource = (typeof customOptions.sAjaxSource == 'undefined') ? "" : customOptions.sAjaxSource;
			this.editFormElement = (typeof customOptions.editFormElement == 'undefined') ? null : customOptions.editFormElement;
			this.fileEditForm = (typeof customOptions.fileEditForm == 'undefined') ? "" : customOptions.fileEditForm;
			this.editCallback = (typeof customOptions.editCallback == 'undefined') ? null : customOptions.editCallback;
			
			this.tableDiv = null;
			this.tableId = null;
			this.table = null;
		}
		
		return this.each(function() {
			
			var options = new optionsClass(customOptions);
			
//			options.tableDiv = this.get(0);
			options.tableId = this.getAttribute("id");
			
			_options.push( options );
		
		//Ajax form plugin: http://malsup.com/jquery/form/
//		$.getScript(options.fileAjaxForm, function() {
			var optionsDelete = {
		        beforeSubmit:  resetAjaxForm,  // pre-submit callback 
		        success:       processDeleteResponse,  // post-submit callback 
		 		error: 		   processDeleteError
		        //É possível adicionar outras opções da funcão Ajax do JQuery (http://docs.jquery.com/Ajax/jQuery.ajax)
		    };
			options.formTableElement.ajaxForm(optionsDelete);

			function resetAjaxForm() {
				options.formTableElement.find(".status").html('Carregando...');
			}

			function processDeleteError(XMLHttpRequest, textStatus, errorThrown) {
				options.formTableElement.find(".status").html(textStatus+':'+XMLHttpRequest.responseText);
			}

			function processDeleteResponse(response, status) {
				//$('#restrito_equipamentos_content').load('restrito/equipamentos/equipamentos_tabela.php');
				if (response == "") {
					var anSelected = fnGetSelected(options.table);
					$.each(anSelected, function(i, val) {
						var iRow = options.table.fnGetPosition(val);
						options.table.fnDeleteRow(iRow);
					});
					options.formTableElement.find(".status").html('Registro(s) excluído(s) com sucesso!');
				}
				else {
					options.formTableElement.find(".status").html(response);
				}
			}


			/* Get the rows which are currently selected */ 
			function fnGetSelected( oTableLocal ) {
				var aReturn = new Array();
				var aTrs = oTableLocal.fnGetNodes();
				
				for ( var i=0 ; i<aTrs.length ; i++ ) {
					if ( $(aTrs[i]).hasClass('row_selected') && $(aTrs[i]).is(":visible")) {
						aReturn.push( aTrs[i] );
					}
				}
				return aReturn;
			}
			
//		});

		//Datatables plugin: http://www.datatables.net/
//		$.getScript(options.fileDataTables, function() {
			
			options.table = $('#' + options.tableId).dataTable({
					"oLanguage": {
					"sProcessing": "Carregando...",
					"sLengthMenu": "Exibir _MENU_ resultados",
					"sZeroRecords": "Nenhum resultado encontrado",
					"sInfo": "Exibindo _START_ a _END_ de _TOTAL_ resultados",
					"sInfoEmpty": "Nenhum resultado",
					"sInfoFiltered": "(filtrados de _MAX_ resultados)",
					"sInfoPostFix": "",
					"sSearch": "Procurar:",
					"sUrl": "",
					"oPaginate": {
						"sFirst":    "Primeira",
						"sPrevious": "Anterior",
						"sNext":     "Próxima",
						"sLast":     "Última"
					}
			},
			"sPaginationType": "full_numbers",
			"bAutoWidth": false,
			"fnDrawCallback": function() { 
				bindEvents();
				if (options.fnDrawCallback) {
					options.fnDrawCallback();
				}
			},
			"bLengthChange": false,
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": options.sAjaxSource,
			/*"fnServerData": function ( sSource, aoData, fnCallback ) {
				            $.ajax( {
				                "type": "POST",
				                "url": sSource,
				                "data": aoData,
				                "success": function (msg) {
					                alert(msg);
					            }
				            } );
				        }*/
			"aoColumns": options.aoColumns,
			"sDom": '<"top"ifr>t<"bottom"p><"clear">',
			"fnInitComplete": function() {
				options.formTableElement.find(".bottom").prepend("<input type='submit' id='excluir_selecionados' value='Excluir selecionados' class='button' /> <span class='status'></span>");
			}
			});
//		});
		
		function bindEvents() {
			$("#" + options.tableId + " :checkbox").change(function(event) {
				if ($(this).is(':checked')){
					$(event.target.parentNode.parentNode).addClass('row_selected');
				}
				else {
					$(event.target.parentNode.parentNode).removeClass('row_selected');
				}
			});
			$("#" + options.tableId + " tbody tr").click(function(event) {
				options.table.fnClose( this );
				if ($(event.target).is(":not(:first-child)")) {
					var id = this.childNodes[0].childNodes[0].value;
					if (id) {
						$(options.editFormElement).load(options.fileEditForm, { 'id': id }, function() {
							if (options.editCallback) {
								options.editCallback();
							}
						});
					}  
				}
			});
		}
		});
	};
	
	$.fn.formSubmit = function(generalOptions) {
		
		var formElement = this;
		
		var options = $.extend({
			successMessage: "Registro alterado com sucesso!"
		}, generalOptions, options);
		
		formElement.append("<span class='status'></span>");
		
		function resetAjaxForm() {
			formElement.find(".status").html('Carregando...');
		}

		function processAjaxFormError(XMLHttpRequest, textStatus, errorThrown) {
			formElement.find(".status").html(textStatus+':'+XMLHttpRequest.responseText);
		}

		function processAjaxFormResponse(response, status) {
			if (response == "") {
				formElement.find(".status").html(options.successMessage);
//				$('#restrito_equipamentos_content').load('restrito/equipamentos/equipamentos_tabela.php');
				$.fn.getTable(options.tableId).fnReloadAjax();
			}
			else {
				formElement.find(".status").html(response);
			}
		}

		var optionsAjaxForm = {
		    beforeSubmit:  resetAjaxForm,  // pre-submit callback 
		    success:       processAjaxFormResponse,  // post-submit callback 
		 	error: 		   processAjaxFormError
		    //É possível adicionar outras opções da funcão Ajax do JQuery (http://docs.jquery.com/Ajax/jQuery.ajax)
		};
		
		//Ajax form plugin: http://malsup.com/jquery/form/
//		$.getScript(options.fileAjaxForm, function() {
			formElement.ajaxForm(optionsAjaxForm);
//		});
	};
})(jQuery);