var checkProductIsConsignment = function() {
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	for (var index = 0; index != count; index++) {
		//if ($('#product_is_consignment_' + index).val() == '1') {			
			var f = $('#quantity_' + index).attr('onchange');
			f += 'showConsignmentsOptions(\'' + index + '\');';
			$('#quantity_' + index).attr('onchange', f);
			var f2 = $('#quantity_' + index).attr('onchange');
			if (UnformatNumber($('#quantity_'+index).val())<=0) 
				if (!items[index].product_consignment_id || items[index].product_consignment_id=='' )
					getConsignmentsDiv(index);
		//}
	}
	$('#quantity_' + (count - 2)).focus();
	$('#quantity_' + (count - 2)).select();
	addRowClickHandler();
}

function addRowClickHandler() {
	$('#itemsTable').find('tr').click(function() {
		var count = $('#' + itemsTable + '_T tr').length - 1;
		for (var index = 0; index != count; index++) {
			if ($('#product_is_consignment_' + index).val() != '1')
				continue;
			var qty = UnformatNumber($('#quantity_' + index).val());
			var div_size = $('#consignments_div_' + index).size();
			// if (index == $(this).index() && div_size>0) continue;
			if (index == $(this).index() && qty > 0 && div_size == 0) {
				getInsertConsignmentsDiv(index);
			} else if (index != $(this).index() && qty > 0)
				$('#consignments_div_' + index).hide('slow', function() {
					$(this).remove();
				});
		}
	});
}

var showConsignmentsOptions = function(index) {
	checkConsignments(index);
	console.log(items[index].product_is_consignment);
	if (items[index].product_is_consignment != '1') {
		console.log('nie partia');
		if (UnformatNumber($('#quantity_' + index).val()) > 0)
			$('#consignments_div_'+index).remove();
		else
			if (!items[index].product_consignment_id || items[index].product_consignment_id=='')
				getConsignmentsDiv(index);
	} else {
		console.log('partia');
		if (UnformatNumber($('#quantity_' + index).val()) > 0)
			getInsertConsignmentsDiv(index);
		else
			if (!items[index].product_consignment_id || items[index].product_consignment_id=='')
				getConsignmentsDiv(index);
	}
}

var getInsertConsignmentsDiv = function(index) {
if($('#product_id_' + index).val()=='' || $('#product_is_consignment_' + index).val() != '1') return '';
	$('#consignments_div_' + index).remove(); // panel exists
	var part = '';
	
	if (items[index].product_consignment_part!='')
		part = items[index].product_consignment_part;
	var container = $('#itemsTable_T > tbody').find('#name_' + index).parent()
			.parent();
	var div = $('<div></div>');
	div.attr('id', 'consignments_div_' + index);
	div.attr('name', 'consignments_div_' + index);
	div.css('float', 'left');
	div.css('text-align', 'left');
	div.css('border', '1px solid rgb(204,204,204)');
	div.css('padding', '3px');
	div.css('display', 'none');
	div.css('width', '90%');
	input = $('<input></input>');
	input.attr('id', 'consignment_part_no');
	input.keyup(function(event) {
		var t = $(event.target);
		$('#product_consignment_part_' + index).val(t.val());
		items[index].product_consignment_part = t.val();
	});
	
	input.css('width', '90%');
	
	input.val(part);
	div.append('Nr parti:&nbsp;');
	div.append(input);
	container.append(div);
	div.show('slow');
	//input.focus();
	if($('#product_consignment_part_' + index).val()=='')getPartNumber(index);
}

var checkConsignments = function(index) {
	var qty =  UnformatNumber($('#quantity_' + index).val());
	if (qty<0 && Math.abs(qty)>items[index].product_consignment_qty) {
		items[index].product_consignment_part='';
		items[index].product_consignment_id='';
		items[index].product_consignment_qty='';
		$('#product_consignment_part'+index).val('');
		$('#product_consignment_id'+index).val('');
	}
}

var getConsignmentsDiv = function(index) {
	$('#consignments_div_' + index).remove(); // panel exists
	var prod_id = $('#itemsTable_T > tbody').find('#product_id_' + index).val();
	if (!prod_id || prod_id == "")
		return; // empty row
	var gcd = '#product_consignment_part_' + index;
	var gci = '#product_consignment_id_' + index;
	var container = $('#itemsTable_T > tbody').find('#name_' + index).parent();
	console.log(index);
	// if (handler.prev().attr('name') != 'vsbr') handler.before('<br
	// name="vsbr">'); //VerySpecialBR - first with name :)
	var qty = UnformatNumber($('#itemsTable_T > tbody').find(
			'#quantity_' + index).val());
	var div = $('<div></div>');
	div.attr('id', 'consignments_div_' + index);
	div.attr('name', 'consignments_div_' + index);
	div.css('float', 'left');
	div.css('text-align', 'left');
	div.css('border', '1px solid rgb(204,204,204)');
	div.css('padding', '3px');
	div.css('display', 'none');
	div.css('width', '90%');
	var qty = UnformatNumber($('#itemsTable_T > tbody').find(
			'#quantity_' + index).val());
	var prod_id = $('#itemsTable_T > tbody').find('#product_id_' + index).val();
	div.append('<table></table>');
	container.append(div);

	if (items[index].product_is_consignment == '1')
		div.append(getConsignments(prod_id, qty, $("#stock_id").val(), index));
	else{
		if( ($('#type').val()=='2dcd99ce-c2fe-6bbd-6d1a-5512a569c4e0') || ($('#type').val()=='1')){
			div.append(getDocuments(prod_id, qty, $("#stock_id").val(), index));
		} 
		
	}
		
}
var getDocuments = function(prod_id, qty, stock_id, index) {
	// AJAX call

	var a = jQuery
			.ajax({
				type : 'POST',
				url : 'index.php?module=EcmStockDocCorrects&action=javahelper&to_pdf=1',
				data : {
					job : 'getConsignmentsDocs',
					prod_id : prod_id,
					stock_id : stock_id
				},
				dataType : 'json',
				async : false,
			});
	var consignments = $.parseJSON(a.responseText);
	var last = consignments.length - 1;
	var container = $('<table></table>');
	container.css('width', '100%');
	$.each(consignments, function(i, c) {
		var p = $('<p></p>');
		var tr = $('<tr></tr>');
		tr.css('width', '100%');
		var a = $('<a></a>');
		a.html(c.part_no);
		a.attr('index', index);
		if (c.availability >= Math.abs(qty)) {
			a.click(function(event) {
				var t = $(event.target);
				var index = t.attr('index');
				$('#product_consignment_id_' + index).val(c.operation_id)
				$('#product_consignment_part_' + index).val(c.part_no);
				$('#product_consignment_qty_' + index).val(c.availability);
				console.log("tutut");
				
				if( ($('#type').val()=='2dcd99ce-c2fe-6bbd-6d1a-5512a569c4e0')){
					$('#quantity_' + index).val(FormatNumber(c.availability,c.precision));
				} else {
					$('#quantity_' + index).val(FormatNumber(c.availability*-1,c.precision));
				}
				//$('#quantity_' + index).attr('readonly', 'readonly');
				$('#price_'+index).val(FormatNumber(c.price));
				$('#price_old_'+index).val(FormatNumber(c.price));
				console.log($('#type').val());
				if ($('#type').val() == '2dcd99ce-c2fe-6bbd-6d1a-5512a569c4e0') {
					$('#price_old_'+index).attr('type','text');
					$('<br>').insertAfter('#price_'+index);
					$('#quantity_' + index).val(FormatNumber(c.availability,c.precision));
				} else {
					$('#quantity_' + index).val(FormatNumber(c.availability*-1,c.precision));
				}
				//insert max qty
				$('#max_quantity_'+index).remove();
				$('#quantity_'+index).parent().append('<p style="text-align: right;" id="max_quantity_'+index+'">(Max: '+FormatNumber(c.availability,c.precision)+')</p>');
				$('#quantity_'+index).focus();
				items[index].product_consignment_id = c.operation_id;
				items[index].product_consignment_part = c.part_no;
				items[index].product_consignment_qty = c.availability;
				calculateRow(index);
				var div = $('#consignments_div_' + index);
				div.hide('slow');
			});
			a.css('cursor', 'pointer');
			a.css('color', 'blue');
		} else
			a.css('color', 'red');
		var td = $('<td></td>');
		td.append(a);
		tr.append(td);
		var td = $('<td></td>');
		td.append(c.part_no);
		tr.append(td);
		var td = $('<td></td>');
		td.append(FormatNumber(c.availability,c.precision) + ' ' + c.unit);
		tr.append(td);
		var td = $('<td></td>');
		td.append(FormatNumber(c.price) + ' ' + c.currency + ' / ' + c.unit);
		tr.append(td);
		container.append(tr);
	});
	// show div
	$('#consignments_div_' + index).show('slow');
	return container;
}

var getConsignments = function(prod_id, qty, stock_id, index) {
	// AJAX call
	var a = jQuery
			.ajax({
				type : 'POST',
				url : 'index.php?module=EcmStockDocCorrects&action=javahelper&to_pdf=1',
				data : {
					job : 'getConsignments',
					prod_id : prod_id,
					stock_id : stock_id
				},
				dataType : 'json',
				async : false,
			});
	var consignments = $.parseJSON(a.responseText);
	var last = consignments.length - 1;
	var container = $('<table></table>');
	container.css('width', '100%');
	$.each(consignments, function(i, c) {
		var p = $('<p></p>');
		var tr = $('<tr></tr>');
		tr.css('width', '100%');
		var a = $('<a></a>');
		a.html(c.document_no);
		a.attr('index', index);
		if (c.availability >= Math.abs(qty)) {
			a.click(function(event) {
				var t = $(event.target);
				var index = t.attr('index');
				$('#product_consignment_id_' + index).val(c.operation_id)
				$('#product_consignment_part_' + index).val(c.part_no);
				$('#product_consignment_qty_' + index).val(c.availability);
				if ($('#type').val() == '6ed5b076-ddd1-9809-b236-54e5b2bcbd97') {
					
                                        
                                        $('#price_old_'+index).remove();
                                        $('#onlyRemove_'+index).remove();
                                        
                                        $('#price_'+index).parent().append('<div id="onlyRemove_'+index+'"><p style="text-align:right">(było: '+FormatNumber(c.price)+')</p><input type="hidden" readonly="readonly" value="'+FormatNumber(c.price)+'" onclick="$(this).select();"  style="text-align: right;background-color:#ffffff;" id="price_old_'+index+'" name="price_old_'+index+'" class="inputs"></div>');
				$('#quantity_' + index).val(FormatNumber(c.availability,c.precision));
				$('#quantity_' + index).attr('readonly',true);
				} else {
					$('#quantity_' + index).val(FormatNumber(c.availability*-1,c.precision));
				}
				$('#price_'+index).val(FormatNumber(c.price));
				//insert max qty
				if ($('#type').val() == '6ed5b076-ddd1-9809-b236-54e5b2bcbd97') {
				$('#quantity_'+index).parent().append('<p style="text-align: right;" id="max_quantity_'+index+'">(Max: '+FormatNumber(c.availability,c.precision)+')</p>');
				} else {
					$('#quantity_'+index).parent().append('<p style="text-align: right;" id="max_quantity_'+index+'">(Max: '+FormatNumber(c.availability*-1,c.precision)+')</p>');
				}
				$('#quantity_'+index).focus();
				items[index].product_consignment_id = c.operation_id;
				items[index].product_consignment_part = c.part_no;
				items[index].product_consignment_qty = c.availability;
				calculateRow(index);
				var div = $('#consignments_div_' + index);
				div.hide('slow');
			});
			a.css('cursor', 'pointer');
			a.css('color', 'blue');
		} else
			a.css('color', 'red');
		var td = $('<td></td>');
		td.append(a);
		tr.append(td);
		var td = $('<td></td>');
		td.append(c.part_no);
		tr.append(td);
		var td = $('<td></td>');
		td.append(FormatNumber(c.availability,c.precision) + ' ' + c.unit);
		tr.append(td);
		var td = $('<td></td>');
		td.append(FormatNumber(c.price) + ' ' + c.currency + ' / ' + c.unit);
		tr.append(td);
		container.append(tr);
	});
	// show div
	$('#consignments_div_' + index).show('slow');
	return container;
}

function checkConsignmentsValues() {
	var count = items.length;//$('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	var NO_ERROR = true;
	for (var index = 0; index < count; index++) {
		if ($('#type').val()=='6ed5b076-ddd1-9809-b236-54e5b2bcbd97') {
			var tmp = items[index].product_consignment_part;
			if (!tmp) tmp = '';
			if (tmp.length==0) NO_ERROR = false;
		}
	}
	return NO_ERROR;
}
