var item_obj = null ;

$(document).ready(function() 
{ 
	$('#formItem').hide() ;
	$('#btnItemClear').button().bind('click',clearItem) ;
	
	$('#btnItemAdd').button().bind('click',addItem) ;

	// $('#item-tabs').tabs() ;
	$('#txtItemDesc').focus() ;
	$(window).resize(resizeItemGrid) ;
	resizeItemGrid() ;
	clearItem();
	filterItem();
}) ;

function showFormItem(){
	clearItem();
	$('#formItem').show('slow') ;
}

function closeFormItem(){
	clearItem() ;
	$('#formItem').hide('slow') ;
}	

function resizeItemGrid() {
	var h = $("#sbg-center-panel").outerHeight() - $("#sbg-item-entry").outerHeight() - 55;
	$("div#sbg-item-data").css("height", h +'px') ;		
}

function clearItem() {
	$('#txtItemId').val("Auto") ;
	$('#txtItemDesc').val("") ;
	$('#txtItemCode').val("") ;
	$('#txtItemRef').val("") ;
	// $('#item-tabs').tabs("option", "active", 0) ;
	$('#txtItemDesc').focus() ;
	$('#btnItemUpdate').prop('disabled','disabled') ;
	$('#item_err_mesg').text('') ;
	$('#item_err_desc').hide() ;
	$('#item_err_code').hide() ;
	if (item_obj != null && item_obj != undefined)
	{
		$($(item_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	item_obj = null;
}

function filterItem() {
	var data = { "type": C_LIST , "code":$('#filterCode').val(),"desc":$('#filterDesc').val(),"brand":$('#filterBrand').val()} ;
	var url = "request.pzx?c=" + itemexport_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showItemFilterList,item_obj) ;
}

function showItemFilterList(obj,resp) {
	dataJSONArray = resp.data.itemLocal;
	$('.sbg-item-table').KTDatatable('destroy');
	init_dt();

	dataJSONArrayRMS = resp.data.itemRms;
	$('.sbg-export-table').KTDatatable('destroy');
	init_dtrms();
}

function init_dt() {
	var datatable = $('.sbg-item-table').KTDatatable({
		// datasource definition
		data: {
			type: 'local',
			source: dataJSONArray,
			pageSize: 5, // display 20 records per page
			serverPaging: true,
			serverFiltering: true,
			serverSorting: true,
		},

		// layout definition
		layout: {
			scroll: true, // enable/disable datatable scroll both horizontal and vertical when needed.
			height: 'auto', // datatable's body's fixed height
			footer: false, // display/hide footer
		},

		// column sorting
		sortable: true,

		// toolbar
		toolbar: {
			// toolbar placement can be at top or bottom or both top and bottom repeated
			placement: ['bottom'],

			// toolbar items
			items: {
				// pagination
				pagination: {
					// page size select
					pageSizeSelect: [5, 10, 20, 30, 50], // display dropdown to select pagination size. -1 is used for "ALl" option
				},
			},
		},

		search: {
			input: $('#generalSearch'),
		},

		columns: [
			{
				field: "id",
				title: "ID",
				width:60,
			}, {
				field: "code",
				title: "Code",
				width:100,
			}, {
				field: "desc",
				title: "Description",
				width:200,
			}, {
				field: "brand",
				title: "Brand",
				width: 100,
			}],
	});
}

function init_dtrms() {
	var datatable = $('.sbg-export-table').KTDatatable({
		// datasource definition
		data: {
			type: 'local',
			source: dataJSONArrayRMS,
			pageSize: 5, // display 20 records per page
			serverPaging: true,
			serverFiltering: true,
			serverSorting: false,
		},

		// layout definition
		layout: {
			scroll: true, // enable/disable datatable scroll both horizontal and vertical when needed.
			height: 'auto', // datatable's body's fixed height
			footer: false, // display/hide footer
		},

		// column sorting
		sortable: true,

		// toolbar
		toolbar: {
			// toolbar placement can be at top or bottom or both top and bottom repeated
			placement: ['bottom'],

			// toolbar items
			items: {
				// pagination
				pagination: {
					// page size select
					pageSizeSelect: [5, 10, 20, 30, 50], // display dropdown to select pagination size. -1 is used for "ALl" option
				},
			},
		},

		search: {
			input: $('#generalSearch'),
		},

		columns: [
			{
				field: "action",
				title: '<label class="kt-checkbox kt-checkbox--single kt-checkbox--brand">'+
				'<input type="checkbox" id="selectAll" onclick="allChecked()" class="m-checkable">'+
				'<span></span></label>',
				width:50,
				sortable: false
			},{
				field: "code",
				title: "Code",
				width:100,
			}, {
				field: "desc",
				title: "Description",
				width:200,
			}, {
				field: "brand",
				title: "Brand",
				width: 100,
			}],

	});
}

function allChecked() {
	var oTable = $('.sbg-export-table').KTDatatable({
        stateSave: true
    });

    var allPages = oTable.cells( ).nodes( );

    $('body').on('click', '#selectAll', function () {
        if ($(this).hasClass('allChecked')) {
            $('input[type="checkbox"]', allPages).prop('checked', false);
        } else {
            $('input[type="checkbox"]', allPages).prop('checked', true);
        }
        $(this).toggleClass('allChecked');
    })
}
function addItem() {
	saveItem(C_ADD) ;
}
function saveItem(type) {
	var lines = "";
	var sep = "" ;

	KTApp.blockPage();

	$('.sbg-export-table table > tbody  > tr').each(function () {
		check   	= ($('.itemChecked',this).is(':checked') ? '1' : '0');
		var code    = $(this).find("td").eq(1).find("span:first").html();
		var desc    = $(this).find("td").eq(2).find("span:first").html();
		var ref     = $(this).find("td").eq(3).find("span:first").html();
		if(check == '1'){

            lines       = lines + sep + code+'~'+desc+'~'+ref;
            sep         = "|" ;
		}
	});

	var data = { "type": type, 
                 "data" : lines };
	var url = "request.pzx?c=" + itemexport_url + "&d=" + new Date().getTime() ;
	
	callServer(url,"json",data,onItemResponse,item_obj) ;
	
}

function onItemResponse(obj,resp) {
	if (resp.status != C_OK) {
		KTApp.unblockPage();
		swal("Error",resp.mesg) ;
		return;
	}
	if (resp.type == C_ADD) {
		KTApp.unblockPage();
		swal("Successfull!", "Your Item Successfully add to the system", "success");
	} else if (resp.type == C_DELETE) {
		swal("Successfull!", "Your Item Successfully delete to the system", "success");
	} else if (resp.type == C_UPDATE) {
		swal("Successfull!", "Your Item Successfully update to the system", "success");
	}
	$('#sbg-popup-box').html(resp.mesg) ;
	$('#sbg-popup-box').show() ;
	$('#sbg-popup-box').fadeOut(5000) ;
	clearItem() ;
	filterItem();
	closeFormItem();
}
