

//some global conf
if (typeof editor_width == 'undefined')  editor_width = 300;
if (typeof editor_top == 'undefined')    editor_top   = 'center';


function delete_row(handler)
{
	var t = $(handler).closest('tr'); //lets get row, which has to be deleted
  var rowid = t.attr('id');
  rowid = rowid.replace('r',''); //get PK id to delete
 
  //$(handler).button( "disable" ); //disable button itself

	 $.post("/engine/ajaxRequest.php", { object: object_name,  action: 'delete', param: rowid },
   function(data){
     if (data == '1')
     {
			 $(t).fadeOut(); //(a) visual delete of row
     } else 
     {
     	$(handler).button( "enable" );
     	alert('Error during delete operation!');
     } 
   });


}


function insert_edit(handler, rid)
{

	table_name = 'tbl_' + object_name;
	if (!rid) rid = 0;
	$( "#dlg_editor" ).dialog({
		width: editor_width,
		position: ['center', editor_top],
    close: function(event, ui) { /*  $(handler).button("enable"); */ $('#dlg_editor').html('Please wait..');}, 
     open: function(event, ui) {/* $(handler).button("disable");*/ }
	});
 			

	$.post("/engine/ajaxRequest.php", { object: object_name,  action: 'draw_form', param: rid},
	function(data){
		$('#dlg_editor').html(data);
		$('#dlg_editor').append('<input id="btn_save" type="button" value="Saglabāt" />&nbsp;&nbsp;');
		$('#dlg_editor').append('<input id="btn_cancel" type="button" value="Aizvērt" />');
		$('#btn_save').button();
		$('#btn_cancel').button();
	
		
		$('#edit_form').submit(
			function(){
				if (typeof(window.validate) == 'function') { //validate function is present
					if (!validate(this)) return false;
				}
				var postdata = $(this).serialize();
				$.post("/engine/ajaxRequest.php", postdata,
				function(data) {
					if (data != '0') 
					{
						$('#' + table_name).replaceWith(data);
					  init_table();
					  $('#dlg_editor').html('Please wait..');
						$('#dlg_editor').dialog("close");
						document.location = '#top';
					}
					else
						alert('Error while inserting data');
				});
				return false;
			}
		);
		
	  $('#btn_cancel').click(function() {
	 		$('#dlg_editor').dialog("close");
		});
		 
		$('#btn_save').click(function() {
			$('#edit_form').submit();
		}); 
		


  });
  

}

function init_table()
{
	//$('.btn_edit, .btn_delete').button();

  //edit function
  $('.btn_edit').click(function() { 
  	var rid = $(this).closest('tr').attr('id');
  	rid = rid.replace('r','');
		insert_edit(this, rid);
		return false;
   });
   
  //delete function
  $('.btn_delete').click(function() { 
  	if (confirm('Vai tiešām vēlaties dzēst datus?'))
  	delete_row(this);
  	return false;
   });
  if (typeof extra_init != 'undefined') extra_init();
}
