//START:
$(document).ready(function() {
	InitializePositionList();
	$("#create_ks").on('click',create_ks);
});

function create_ks(){
	var potwierdzenie = confirm('Czy na pewno utworzyć dokumenty KS i wprowadzić zmiany na magazynie?');
	if(!potwierdzenie){
		return;
	}
	//Formatka do daty
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth()+1; //January is 0!
	var yyyy = today.getFullYear();

	if(dd<10){
	 dd = "0" + dd; 
	}

	if(mm<10){
	 mm = "0" + mm; 
	}
	var data_dokumentu = window.prompt("Data dokumentu KS:","" + dd + "." + mm + "." + yyyy);
	if(data_dokumentu === null){
		alert("Operacja anulowana.");
	}
	// Sprawdzamy wstepnie czy dobrze wyglada
	var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
	var dt = new Date(data_dokumentu.replace(pattern,'$3-$2-$1'));
	if ( isNaN( dt.getTime() ) ) {  // d.valueOf() could also work
		alert("Zły format daty. Operacja anulowana.");
		return;
	}
	// zmiana dla mysql
	data_dokumentu_splited  = data_dokumentu.split(".");
	data_dokumentu = data_dokumentu_splited[2] + "-" + data_dokumentu_splited[1]+ "-" + data_dokumentu_splited[0];
	
	  
	var id_dokumentu = $("input[name='record']").val();
	$.ajax({
		type: "POST",
		url: "index.php?module=EcmInventorys&action=ajax&to_pdf=1",
		dataType: "json",
		async: false,
		data: {
			job: "create_ks_documents",
			ecminventory_id: id_dokumentu,
			ks_date_document : data_dokumentu
		},
		success: function (data) {
			console.log(data);
			if(data==1){
				location.reload();
			}else if(data==-1){
				alert('Nie wprowadzono żadnych zmian. Brak różnic pomiędzy listą, a stanem magazynowym.');
			}else if(data == -2){
				alert('Podana data jest starsza niż ostatni dokument KS w bazie. Operacja anulowana.');
			}else{
				alert(data);
			}
		}
	});
}

function InitializePositionList() {
	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: 'text',
				displayCss: {
					'width': '10%',
					'vertical-align': 'middle',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				ctrlCss: {
					'text-align': 'left',
					'vertical-align': 'middle',
				},
				ctrlClass: 'inputs',
				ctrlAttr: {
					readonly: 'readonly'
				},
			}, {
				name: 'name',
				display: SUGAR.language.get("app_strings", "LBL_NAME"),
				type: 'text',
				displayCss: {
					'width': '40%',
					'vertical-align': 'middle',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				ctrlClass: 'inputs',
				ctrlCss: {
					'text-align': 'left'
				},
				ctrlAttr: {
					readonly: 'readonly'
				},
			}, {
				name: 'dd_unit_name',
				display: SUGAR.language.get("app_strings", "LBL_JM"),
				type: 'text',
				displayCss: {
					'width': '5%',
					'vertical-align': 'middle',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				ctrlClass: 'inputs',
				ctrlAttr: {
					readonly: 'readonly'
				},
			}, {
				name: 'ecmproductcategory_name',
				display: SUGAR.language.get("app_strings", "LBL_CATEGORY"),
				type: 'text',
				displayCss: {
					'width': '20%',
					'vertical-align': 'middle',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				ctrlCss: {
					'text-align': 'left'
				},
				ctrlClass: 'inputs',
				ctrlAttr: {
					readonly: 'readonly'
				},
			},  {
				name: 'quantity',
				display: 'Ilość remanentowa',
				type: 'custom',
				displayCss: {
					'width': '12%',
					'vertical-align': 'middle',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				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('change',function(){
						var wiersz = $(this).closest('tr');
						var ilosc = UnformatNumber($(this).val());
						var precyzja = wiersz.find('input[name^="position_list_dd_unit_precision_"]').val();
						
						$(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);
						wiersz.find('input[name^="position_list_total_"]').val(FormatNumber(ilosc*cena));
						
						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',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				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',
					'background-color': 'rgb(224,240,255)',
					'border': '1px solid rgb(48,192,255)',
				},
				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,
			insert: true,
			remove: 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');
			}
			
		}
	});
}