//START:
// override these in your code to change the default behavior and style 


//dla poprawnego wyszukiwania
var ajax_url = "index.php?module=EcmStockDocInsideIns&action=javahelper&to_pdf=1";
module_function = 'EcmInvetorys';
number_show = true;
unit_show = true;
extraproductinfo_show = true;
searchedProducts = [];
group_ks_search = "3";
var wartosci_przed_autocomplete;

$["ui"]["autocomplete"].prototype["_renderItem"] = function (ul, item) {
	return $("<li></li>").data("item.autocomplete", item).append(
			$("<a></a>").html(item.label)).appendTo(ul);
};

$(document).ready(function() {
	window.onbeforeunload = confirmExit;
	getCategoriesList();
	$('#searchProductsInput').keyup(function() {
		searchProducts();
	});
	InitializePositionList();
	$("#add_from_stock").on('click',add_from_stock);
	var ecminventory_id = $("input[name='record']").val();
	var init_data = '';
	if(ecminventory_id ==''){
    $("#stock").on('change',function(){
		var potwierdzenie = confirm('Zmiana magazynu spowoduje usunięcie wszystkich pozycji z listy, kontynuować?');
		if(potwierdzenie){
			$('#position_list').appendGrid('load',[]);
			$('#position_list').appendGrid('appendRow',1);
			$("#stock_id").val($("#stock").val());
		}else{
			$("#stock").val($("#stock_id").val());
		}
    });
  }else{
    $("#stock").prop('disabled',true);
  }
	// Pobieranie danych
});

function addProducts(){
	var lista_zaznaczonych = $("#searchResultDiv").find(":checked");
	// przerabiam zjebane id checkboxow na nadające się do bazy po stronie klienta,a co ma się serwer męczyć
	id_list = new Array();
	$.each(lista_zaznaczonych, function (pos,checkbox){
		id_list.push($(checkbox).prop('id').replace('prod_',''));
	});
	
	$.ajax({
		type: "POST",
		url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
		dataType: "json",
		async: true,
		data: {
			job: "getProductListById",
			id_list: id_list,
			stock_id: $("#stock").val(),
		},
		success: function (data) {
			// sprawdzanie czy jest juz w tabeli
			var dane_w_tabeli = $('#position_list').appendGrid('getAllValue');
			var lista_id = {};
			$.each(dane_w_tabeli,function (k, v){
				if(v['ecmproduct_id'] == ''){
					return; 
				}
				lista_id[v['ecmproduct_id']] = true;
			});
			var dane_do_tabeli = new Array();
			var dane_juz_w_tabeli = new Array();
			$.each(data,function (k,v){
				if(lista_id[v['ecmproduct_id']]){
					dane_juz_w_tabeli.push(v);
					return;
				}
				data[k]['name'] = correct_name_code_htmlentieties(v['name']);
				data[k]['code'] = correct_name_code_htmlentieties(v['code']);
				dane_do_tabeli.push(data[k]);
			});
			
			if(dane_juz_w_tabeli.length>0){
				var allert_message = 'Następujące produkty są już na liście:';
				$.each(dane_juz_w_tabeli, function (key, val){
					console.log(val);
					allert_message +='\n' + key  + '. ' + val['code'] + ' ' + val['name'];
				});
				alert(allert_message);
			}
			
			
			
			$('#position_list').appendGrid('appendRow',dane_do_tabeli);
			//zamieniam indeks typu 0,1,2 na id porduktu by latwiej wyszukiwac
			var tmp = {};
			$.each(dane_do_tabeli,function (k,v){
				tmp[v['ecmproduct_id']] = v;
			});
			var data_table = $('#position_list').appendGrid('getAllValue', false);
			// iteruje po tabelce by poprawić precyzje bo niestety kolejnosc zdarzen nie jest taka jaka bym chcial
			$.each(data_table,function (indeks_row, row_values){
				if(tmp[row_values['ecmproduct_id']]!== undefined){
					var id = $('#position_list').appendGrid('getUniqueIndex', indeks_row);
					var precyzja = tmp[row_values['ecmproduct_id']]['dd_unit_precision'];
					var stan = tmp[row_values['ecmproduct_id']]['stock_state'];
					
					var ilosc = UnformatNumber($('#position_list_quantity_'+id).val());
					if($('#searchInputQty').val()!=''){
						ilosc = UnformatNumber($('#searchInputQty').val());
					}
					$('#position_list_stock_state_'+id).val(FormatNumber(stan,precyzja));
					$('#position_list_quantity_'+id).val(FormatNumber(ilosc,precyzja));
					var roznica = ilosc-stan;
					$('#position_list_difference_'+id).val(FormatNumber(roznica,precyzja));
					if(ilosc > stan){
						$('#position_list_difference_'+id).css('color','green');
					}
					if(ilosc < stan){
						$('#position_list_difference_'+id).css('color','red');
					}
					if(ilosc == stan){
						$('#position_list_difference_'+id).css('color','black');
					}
				}
			});
			$("#searchResultDiv").html('');
		}
	});
}

function correct_name_code_htmlentieties(string_input){
	var return_string = string_input.replace(/&#039;/g,'\'');
	return_string = return_string.replace(/&quot;/g,'"');
	return_string = return_string.replace(/\/u/g,'');
	return return_string;
}

function toggle_show_options_add_from_stock(){
	
}

function add_from_stock(){
	if($("#stock").val()==''){
		alert('Proszę wybrać magazyn!');
		return;
	}
	
	$.ajax({
		type: "POST",
		url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
		dataType: "json",
		async: true,
		data: {
			job: "add_from_stock",
			stock_id: $("#stock").val(),
			add_options: $("#add_options").val(),
			rewrite_state:  $("#rewrite_state").prop('checked'),
		},
		success: function (data) {
			// sprawdzanie czy jest juz w tabeli
			var dane_w_tabeli = $('#position_list').appendGrid('getAllValue');
			var lista_id = {};
			$.each(dane_w_tabeli,function (k, v){
				if(v['ecmproduct_id'] == ''){
					return; 
				}
				lista_id[v['ecmproduct_id']] = true;
			});
			var dane_do_tabeli = new Array();
			$.each(data,function (k,v){
				if(lista_id[v['ecmproduct_id']]){
					return;
				}
				data[k]['name'] = correct_name_code_htmlentieties(v['name']);
				data[k]['code'] = correct_name_code_htmlentieties(v['code']);
				dane_do_tabeli.push(data[k]);
			});
			$('#position_list').appendGrid('appendRow',dane_do_tabeli);
			//zamieniam indeks typu 0,1,2 na id porduktu by latwiej wyszukiwac
			var tmp = {};
			$.each(dane_do_tabeli,function (k,v){
				tmp[v['ecmproduct_id']] = v;
			});
			var data_table = $('#position_list').appendGrid('getAllValue', false);
			// iteruje po tabelce by poprawić precyzje bo niestety kolejnosc zdarzen nie jest taka jaka bym chcial
			$.each(data_table,function (indeks_row, row_values){
				if(tmp[row_values['ecmproduct_id']]!== undefined){
					var id = $('#position_list').appendGrid('getUniqueIndex', indeks_row);
					var precyzja = tmp[row_values['ecmproduct_id']]['dd_unit_precision'];
					var stan = tmp[row_values['ecmproduct_id']]['stock_state'];
					var ilosc =  tmp[row_values['ecmproduct_id']]['quantity'];
					
					$('#position_list_stock_state_'+id).val(FormatNumber(stan,precyzja));
					$('#position_list_quantity_'+id).val(FormatNumber(ilosc,precyzja));
					var roznica = ilosc-stan;
					$('#position_list_difference_'+id).val(FormatNumber(roznica,precyzja));
					if(ilosc > stan){
						$('#position_list_difference_'+id).css('color','green');
					}
					if(ilosc < stan){
						$('#position_list_difference_'+id).css('color','red');
					}
					if(ilosc == stan){
						$('#position_list_difference_'+id).css('color','black');
					}
					
				}
			});
			$('#position_list').appendGrid('removeEmptyRows');
		}
	});
}

function InitializePositionList(id) {
	var ecminventory_id = $("input[name='record']").val();
	var init_data = '';
	if(ecminventory_id !=''){
		$.ajax({
			type: "POST",
			url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
			dataType: "json",
			async: false,
			data: {
				job: "getPositionList",
				ecminventory_id: ecminventory_id,
			},
			success: function (data) {
				init_data = data;
			}
		});
		
	}
	
	// Initialize appendGrid
	$('#position_list').appendGrid({
		hideRowNumColumn: false,
		initRows: 1,
		initData: init_data,
		columns: [
			{
				name: 'id',
				display: 'id',
				type: 'text',
				invisible: true,
			},{
				name: 'dd_unit_id',
				display: 'dd_unit_id',
				type: 'text',
				invisible: true,
			},{
				name: 'dd_unit_precision',
				display: 'dd_unit_precision',
				type: 'text',
				value: 0,
				invisible: true,
			},{
				name: 'ecmproductcategory_id',
				display: 'ecmproductcategory_id',
				type: 'text',
				invisible: true,
			},{
				name: 'ecmproduct_id',
				display: 'ecmproduct_id',
				type: 'text',
				invisible: true,
			}, {
				name: 'modified_user_id',
				display: 'modified_user_id',
				type: 'text',
				value: $("#current_user_id").val(),
				invisible: true,
			},{
				name: 'code',
				display: SUGAR.language.get("app_strings", "LBL_INDEX"),
				type: 'ui-autocomplete',
				displayCss: {
					'width': '10%',
					'vertical-align': 'middle',
				},
				ctrlCss: {
					'text-align': 'left',
					'vertical-align': 'middle',
				},
				uiOption: {
					source: function (request, response) {
						$.ajax({
							type: "POST",
							url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
							dataType: "json",
							async: true,
							data: {
								job: "AutocompliteProductCode",
								code: request.term,
								stock_id: $("#stock").val(),
							},
							success: function (data) {
								response(data);
							}
						});
					},
					minLength: 3,
					delay: 300,
					select: function (event, ui) {
						var dane_w_tabeli = $('#position_list').appendGrid('getAllValue');
						var lista_id = new Array();
						$.each(dane_w_tabeli,function (k, v){
							if(v['ecmproduct_id'] == ''){
								return; 
							}
							lista_id.push(v['ecmproduct_id']);
						});
						
						if(lista_id.indexOf(ui.item.id)!= -1){
							event.preventDefault();
							alert("Wybrany produkt jest już na liście");
						}else{
							var row = $(this).closest('tr');
							row.find('input[name^="position_list_dd_unit_precision_"]').val(ui.item.dd_unit_precision); // jednostka precyzja
							row.find('input[name^="position_list_name_"]').val(ui.item.name); //produkt nazwa
							row.find('input[name^="position_list_ecmproduct_id_"]').val(ui.item.id); //produkt id
							row.find('input[name^="position_list_dd_unit_name_"]').val(ui.item.dd_unit_name); // jednostka nazwa
							row.find('input[name^="position_list_dd_unit_id_"]').val(ui.item.dd_unit_id); // jednostka id
							row.find('input[name^="position_list_price_"]').val(FormatNumber(ui.item.price)); // produkt cena
							row.find('input[name^="position_list_stock_state_"]').val(FormatNumber(ui.item.stock_state,ui.item.dd_unit_precision));
							row.find('input[name^="position_list_ecmproductcategory_name_"]').val(ui.item.product_category_name); // kategoria nazwa
							row.find('input[name^="position_list_ecmproductcategory_id_"]').val(ui.item.product_category_id); // kategoria id
							row.find('input[name^="position_list_quantity_"]').val(FormatNumber(0,ui.item.dd_unit_precision)); // produkt ilosc
							row.find('input[name^="position_list_difference_"]').val(FormatNumber(-1*ui.item.stock_state,ui.item.dd_unit_precision));
							row.find('input[name^="position_list_difference_"]').css('color','red');
						}
					},
				},
				ctrlClass: 'inputs'
			}, {
				name: 'name',
				display: SUGAR.language.get("app_strings", "LBL_NAME"),
				type: 'ui-autocomplete',
				displayCss: {
					'width': '40%',
					'vertical-align': 'middle'
				},
				ctrlClass: 'inputs',
				uiOption: {
					source: function (request, response) {
						$.ajax({
							type: "POST",
							url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
							dataType: "json",
							async: true,
							data: {
								job: "AutocompliteProductName",
								name: request.term,
								stock_id: $("#stock").val(),
							},
							success: function (data) {
								response(data);
							}
						});
					},
					minLength: 3,
					delay: 300,
					select: function (event, ui) {
						var dane_w_tabeli = $('#position_list').appendGrid('getAllValue');
						var lista_id = new Array();
						$.each(dane_w_tabeli,function (k, v){
							if(v['ecmproduct_id'] == ''){
								return; 
							}
							lista_id.push(v['ecmproduct_id']);
						});
						
						if(lista_id.indexOf(ui.item.id)!= -1){
							event.preventDefault();
							alert("Wybrany produkt jest już na liście");
						}else{
							var row = $(this).closest('tr');
							row.find('input[name^="position_list_dd_unit_precision_"]').val(ui.item.dd_unit_precision); // jednostka precyzja
							row.find('input[name^="position_list_code_"]').val(ui.item.code); //produkt nazwa
							row.find('input[name^="position_list_ecmproduct_id_"]').val(ui.item.id); //produkt id
							row.find('input[name^="position_list_dd_unit_name_"]').val(ui.item.dd_unit_name); // jednostka nazwa
							row.find('input[name^="position_list_dd_unit_id_"]').val(ui.item.dd_unit_id); // jednostka id
							row.find('input[name^="position_list_price_"]').val(FormatNumber(ui.item.price)); // produkt cena
							row.find('input[name^="position_list_stock_state_"]').val(FormatNumber(ui.item.stock_state,ui.item.dd_unit_precision)); // aktualny stan magazynowy
							row.find('input[name^="position_list_ecmproductcategory_name_"]').val(ui.item.product_category_name); // kategoria nazwa
							row.find('input[name^="position_list_ecmproductcategory_id_"]').val(ui.item.product_category_id); // kategoria id
							row.find('input[name^="position_list_quantity_"]').val(FormatNumber(0,ui.item.dd_unit_precision)); // produkt ilosc
							row.find('input[name^="position_list_difference_"]').val(FormatNumber(-1*ui.item.stock_state,ui.item.dd_unit_precision));
							row.find('input[name^="position_list_difference_"]').css('color','red'); 
						}
					},
				},
				ctrlCss: {
					'text-align': 'left'
				},
			}, {
				name: 'dd_unit_name',
				display: SUGAR.language.get("app_strings", "LBL_JM"),
				type: 'text',
				displayCss: {
					'width': '5%',
					'vertical-align': 'middle'
				},
				ctrlClass: 'inputs',
				ctrlAttr: {
					disabled: 'disabled',
					readonly: 'readonly'
				},
			},  {
				name: 'quantity',
				display: 'Ilość remanentowa',
				type: 'custom',
				displayCss: {
					'width': '10%',
					'vertical-align': 'middle'
				},
				customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    var ctrl = $('<input/>', { type: 'text', id: ctrlId, name: ctrlId}).css({'text-align':'right'});
					ctrl.addClass('inputs');
					ctrl.on('click',function(){
						$(this).select();
					})
					ctrl.on('change',function(){
						var wiersz = $(this).closest('tr');
						var precyzja = wiersz.find('input[name^="position_list_dd_unit_precision_"]').val();
						
						var ilosc = UnformatNumber(FormatNumber($(this).val(),precyzja));
						
						
						
						$(this).val(FormatNumber(ilosc,precyzja));
						var cena_str = wiersz.find('input[name^="position_list_price_"]').val();
						if(cena_str==''){
							return;
						}
						var cena = UnformatNumber(cena_str);
						
						var stan = UnformatNumber(wiersz.find('input[name^="position_list_stock_state_"]').val());
						
						var roznica = ilosc-stan;
						wiersz.find('input[name^="position_list_difference_"]').val(FormatNumber(roznica,precyzja));
						if(ilosc > stan){
							wiersz.find('input[name^="position_list_difference_"]').css('color','green');
						}
						if(ilosc < stan){
							wiersz.find('input[name^="position_list_difference_"]').css('color','red');
						}
						if(ilosc == stan){
							wiersz.find('input[name^="position_list_difference_"]').css('color','black');
						}
					});
                    $(ctrl).appendTo(parent);
                    return ctrl;
                },
                customGetter: function (idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    return UnformatNumber($('#'+ctrlId).val());
                },
                customSetter: function (idPrefix, name, uniqueIndex, value) {
					var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
					var precyzja = $(this).closest('tr').find('input[name^="position_list_dd_unit_precision_"]').val();
					$('#'+ctrlId).val(FormatNumber(value,precyzja));
                },
			}, {
				name: 'stock_state',
				display: 'Stan kartotekowy',
				type: 'custom',
				displayCss: {
					'width': '10%',
					'vertical-align': 'middle'
				},
				customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    var ctrl = $('<input/>', { type: 'text', id: ctrlId, name: ctrlId }).css({'text-align':'right','color':'black'}).prop({'disabled': 'disabled','readonly': 'readonly'});
					ctrl.addClass('inputs');
					ctrl.on('change',function(){
						var wartosc_przed = UnformatNumber($(this).val());
						$(this).val(FormatNumber(wartosc_przed));
					});
                    $(ctrl).appendTo(parent);
                    return ctrl;
                },
                customGetter: function (idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    return UnformatNumber($('#'+ctrlId).val());
                },
                customSetter: function (idPrefix, name, uniqueIndex, value) {
					var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
					$('#'+ctrlId).val(FormatNumber(value));
                },
			},{
				name: 'difference',
				display: 'Różnica',
				type: 'custom',
				displayCss: {
					'width': '10%',
					'vertical-align': 'middle'
				},
				customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    var ctrl = $('<input/>', { type: 'text', id: ctrlId, name: ctrlId }).css({'text-align':'right'}).prop({'disabled': 'disabled','readonly': 'readonly'});
					ctrl.addClass('inputs');
					ctrl.on('change',function(){
						var wartosc_przed = UnformatNumber($(this).val());
						$(this).val(FormatNumber(wartosc_przed));
					});
                    $(ctrl).appendTo(parent);
                    return ctrl;
                },
                customGetter: function (idPrefix, name, uniqueIndex) {
                    var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                    return UnformatNumber($('#'+ctrlId).val());
                },
                customSetter: function (idPrefix, name, uniqueIndex, value) {
					var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
					$('#'+ctrlId).val(FormatNumber(value));
					
					if(value > 0){
						$('#'+ctrlId).css('color','green');
					}
					if(value < 0){
						$('#'+ctrlId).css('color','red');
					}
					if(value == 0){
						$('#'+ctrlId).css('color','black');
					}
					
                },
			},
		],
		i18n: {
			append: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_APPEND"),
			remove: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_REMOVE"),
			insert: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_INSERT"),
			moveUp: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_MOVEUP"),
			moveDown: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_MOVEDOWN"),
			removeLast: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_REMOVELAST"),
			rowEmpty: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_ROWEMPTY"),
			rowDrag: SUGAR.language.get("app_strings", "LBL_APPENDGRID_I18_ROWDRAG"),
		},
		customGridButtons: {
			insert: function () {
				var button = document.createElement('img');
				button.src = 'modules/EcmQuotes/images/add_position.gif';
				return button;
			},
			remove: function () {
				var button = document.createElement('img');
				button.src = 'modules/EcmQuotes/images/deleterow.gif';
				return button;
			},
			moveUp: function () {
				var button = document.createElement('img');
				button.src = 'modules/EcmQuotes/images/moverowup.gif';
				return button;
			},
			moveDown: function () {
				var button = document.createElement('img');
				button.src = 'modules/EcmQuotes/images/moverowdown.gif';
				return button;
			},
		},
		afterRowRemoved: function (caller, rowIndex) {
			var quantity = $('#position_list').appendGrid(
					'getRowCount');
			if (quantity == 0) {
				$('#position_list').appendGrid('appendRow', 1);
			}
		},
		hideButtons: {
			removeLast: true,
			append: true,
			moveUp: true,
			moveDown: true
		}
	});
	
	var tmp = {};
	$.each(init_data,function (k,v){
		tmp[v['ecmproduct_id']] = v;
	});
	
	var data_table = $('#position_list').appendGrid('getAllValue', false);
	// iteruje po tabelce by poprawić precyzje bo niestety kolejnosc zdarzen nie jest taka jaka bym chcial
	$.each(data_table,function (indeks_row, row_values){

		if(tmp[row_values['ecmproduct_id']]!== undefined){
			var id = $('#position_list').appendGrid('getUniqueIndex', indeks_row);
			var precyzja = tmp[row_values['ecmproduct_id']]['dd_unit_precision'];
			var stan = tmp[row_values['ecmproduct_id']]['stock_state'];
			var ilosc =  tmp[row_values['ecmproduct_id']]['quantity'];

			$('#position_list_stock_state_'+id).val(FormatNumber(stan,precyzja));
			$('#position_list_quantity_'+id).val(FormatNumber(ilosc,precyzja));
			var roznica = ilosc-stan;
			$('#position_list_difference_'+id).val(FormatNumber(roznica,precyzja));
			if(ilosc > stan){
				$('#position_list_difference_'+id).css('color','green');
			}
			if(ilosc < stan){
				$('#position_list_difference_'+id).css('color','red');
			}
			if(ilosc == stan){
				$('#position_list_difference_'+id).css('color','black');
			}
			
		}
	});
	
	
	
}

function confirmExit() {
	return "";
}

function lockEnter() {
	// prevent default
	$(window).keydown(function(event) {
		if (event.keyCode == 13 && $(":focus").prop('tagName')!='TEXTAREA') {
			event.preventDefault();
			return false;
		}
	});
}

function getCategoriesList() {
	var params = {
		job : 'getCategoriesList'
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
			var html = '<option value=""></option>';
			$.each(data, function(index, value) {
				html += '<option value="' + value.id + '">' + value.name
						+ '</option>';
				$("#productSearchCategory").html(html);
			});
		},
		data : params
	});
}

function createProduct() {
	var newProdId = document.getElementById("newProductId");
	newProduct  = window.open('index.php?module=EcmProducts&action=EditView&IamPopup=1', 'newProduct', 'toolbar=no,menubar=no,scrollbars=yes,scrollbars=1');
	newProduct.newProdId = newProdId;
	newProduct.focus();
}

var check_form_ = check_form;
check_form = function(formname,event) {
	//Sprawdzam czy jest uzupelniony nr dokumentu
	if($("#document_no").val()==''){
		alert("Nie podano numeru dokumentu!");
		setDETAILS();
		$("#document_no").focus();
		return false;
	}
	
	//Sprawdzam czy jest wybrany magazyn
	if($("#stock").val() == ''){
		alert("Nie wybrano magazynu!");
		setDETAILS();
		$("#stock").focus();
		return false;
	}
	
	if($("#register_date").val()==''){
		alert("Nie ustawiono daty dokumentu!");
		setDETAILS();
		$("#register_date").focus();
		return false;
	}
	//Sprawdzam czy jest uzupelniona tabela
	var right_data = new Array();
	$.each($('#position_list').appendGrid('getAllValue'), function (key,row){
		
	  if(row['ecmproduct_id']!=''){
		right_data.push(row);
	  }
	});
	if(right_data.length>0){
		$('#position_list').appendGrid('load', right_data);
		
		var tmp = {};
		$.each(right_data,function (k,v){
			tmp[v['ecmproduct_id']] = v;
		});

		var data_table = $('#position_list').appendGrid('getAllValue', false);
		// iteruje po tabelce by poprawić precyzje bo niestety kolejnosc zdarzen nie jest taka jaka bym chcial
		$.each(data_table,function (indeks_row, row_values){

			if(tmp[row_values['ecmproduct_id']]!== undefined){
				var id = $('#position_list').appendGrid('getUniqueIndex', indeks_row);
				var precyzja = tmp[row_values['ecmproduct_id']]['dd_unit_precision'];
				var stan = tmp[row_values['ecmproduct_id']]['stock_state'];
				var ilosc =  tmp[row_values['ecmproduct_id']]['quantity'];

				$('#position_list_stock_state_'+id).val(FormatNumber(stan,precyzja));
				$('#position_list_quantity_'+id).val(FormatNumber(ilosc,precyzja));
				var roznica = ilosc-stan;
				$('#position_list_difference_'+id).val(FormatNumber(roznica,precyzja));
				if(ilosc > stan){
					$('#position_list_difference_'+id).css('color','green');
				}
				if(ilosc < stan){
					$('#position_list_difference_'+id).css('color','red');
				}
				if(ilosc == stan){
					$('#position_list_difference_'+id).css('color','black');
				}
			}
		});
		
	}else{
		$('#position_list').appendGrid('load', right_data);
		$('#position_list').appendGrid('appendRow', 1);
		alert("Brak produktów na liście!");
		setITEMS();
		return false;
	}

	// zapobiega zapisywaniu dokumentu firefox bug, w przypadku nacisniecia enter w polu z autocomplete
	if(event.clientY==0 && event.clientX==0){
			return false;
	}
	window.onbeforeunload = null;
	var ecminventory_id = $("input[name='record']").val();
	var init_data = '';
	if(ecminventory_id ==''){
		var data_dokumentu_splited = $("#register_date").val().split(".");
		var data_dokumentu = data_dokumentu_splited[2] + "-" + data_dokumentu_splited[1] + "-" + data_dokumentu_splited[0];
		$.ajax({
			type: "POST",
			url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
			dataType: "json",
			async: false,
			data: {
				job: "createEcmInventory",
				name: name,
				document_no: $("#document_no").val(),
				stock_id: $("#stock_id").val(),
				register_date: data_dokumentu,
				ecmproductstockindex_id: $("#ecmproductstockindex_id").val(),
				pdf_text:  $("#pdf_text").val(),
			},
			success: function (data) {
				ecminventory_id = data;
				$("input[name='record']").val(ecminventory_id)
				console.log(ecminventory_id);
			},
			error: function (jqXHR, textStatus, errorThrown ){
				$.unblockUI();
				alert('Problem z połączeniem, proszę spróbować ponownie.');
				return false;
			},
		});
	}
	if(ecminventory_id !=''){
		$.blockUI({ message: '<h1>Trwa zapis danych, proszę czekać.</h1>' });
		delte_old_values = true;
		var i,j,temparray,chunk = 50;
		var data_to_send = $('#position_list').appendGrid('getAllValue');
		for (i=0,j=data_to_send.length; i<j; i+=chunk) {
			temparray = data_to_send.slice(i,i+chunk);
			$.ajax({
				type: "POST",
				url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
				dataType: "json",
				async: false,
				data: {
					job: "savePositionList",
					ecminventory_id: ecminventory_id,
					data: temparray,
					deleteOld: delte_old_values,
				},
				success: function (data) {
					console.log(data);
				},
				error: function (jqXHR, textStatus, errorThrown ){
					$.unblockUI();
					alert('Problem z połączeniem, proszę spróbować ponownie.');
					return false;
				},
			});
			delte_old_values = false;
		}
		$.unblockUI();
		return true;
	}
};

$.blockUI.defaults = { 
    // message displayed when blocking (use null for no message) 
    message:  '<h1>Ładowanie danych, proszę czekać...</h1>', 
 
    title: null,        // title string; only used when theme == true 
    draggable: true,    // only used when theme == true (requires jquery-ui.js to be loaded) 
 
    theme: false, // set to true to use with jQuery UI themes 
 
    // styles for the message when blocking; if you wish to disable 
    // these and use an external stylesheet then do this in your code: 
    // $.blockUI.defaults.css = {}; 
    css: { 
        padding:        0, 
        margin:         0, 
        width:          '30%', 
        top:            '40%', 
        left:           '35%', 
        textAlign:      'center', 
        color:          '#000', 
        border:         '3px solid #aaa', 
        backgroundColor:'#fff', 
        cursor:         'wait' 
    }, 
 
    // minimal style set used when themes are used 
    themedCSS: { 
        width:  '30%', 
        top:    '40%', 
        left:   '35%' 
    }, 
 
    // styles for the overlay 
    overlayCSS:  { 
        backgroundColor: '#000', 
        opacity:         0.6, 
        cursor:          'wait' 
    }, 
 
    // style to replace wait cursor before unblocking to correct issue 
    // of lingering wait cursor 
    cursorReset: 'default', 
 
    // styles applied when using $.growlUI 
    growlCSS: { 
        width:    '350px', 
        top:      '10px', 
        left:     '', 
        right:    '10px', 
        border:   'none', 
        padding:  '5px', 
        opacity:   0.6, 
        cursor:    null, 
        color:    '#fff', 
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius':    '10px' 
    },
     
    // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w 
    // (hat tip to Jorge H. N. de Vasconcelos) 
    iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
 
    // force usage of iframe in non-IE browsers (handy for blocking applets) 
    forceIframe: false, 
 
    // z-index for the blocking overlay 
    baseZ: 1000, 
 
    // set these to true to have the message automatically centered 
    centerX: true, // <-- only effects element blocking (page block controlled via css above) 
    centerY: true, 
 
    // allow body element to be stetched in ie6; this makes blocking look better 
    // on "short" pages.  disable if you wish to prevent changes to the body height 
    allowBodyStretch: true, 
 
    // enable if you want key and mouse events to be disabled for content that is blocked 
    bindEvents: true, 
 
    // be default blockUI will supress tab navigation from leaving blocking content 
    // (if bindEvents is true) 
    constrainTabKey: true, 
 
    // fadeIn time in millis; set to 0 to disable fadeIn on block 
    fadeIn:  200, 
 
    // fadeOut time in millis; set to 0 to disable fadeOut on unblock 
    fadeOut:  400, 
 
    // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock 
    timeout: 0, 
 
    // disable if you don't want to show the overlay 
    showOverlay: true, 
 
    // if true, focus will be placed in the first available input field when 
    // page blocking 
    focusInput: true, 
 
    // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) 
    // no longer needed in 2012 
    // applyPlatformOpacityRules: true, 
 
    // callback method invoked when fadeIn has completed and blocking message is visible 
    onBlock: null, 
 
    // callback method invoked when unblocking has completed; the callback is 
    // passed the element that has been unblocked (which is the window object for page 
    // blocks) and the options that were passed to the unblock call: 
    //   onUnblock(element, options) 
    onUnblock: null, 
 
    // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 
    quirksmodeOffsetHack: 4, 
 
    // class name of the message block 
    blockMsgClass: 'blockMsg', 
 
    // if it is already blocked, then ignore it (don't unblock and reblock) 
    ignoreIfBlocked: false 
};
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);