var itemsTable = 'itemsTable';
var items = new Array();
var displayArray = new Array();
var searchedProducts = new Array();
var ajax_url = "index.php?module=EcmStockDocInsideIns&action=javahelper&to_pdf=1";

// draw table
function DrawHeaders() {
	var html = '<link rel="stylesheet" type="text/css" href="modules/EcmQuotes/MyTable.css" />';
	html += '<div style="width:100%;border: 1px solid rgb(48,192,255);background-color:white;overflow:auto;" id="'
			+ itemsTable + 'DIV">';
	html += '<table class="positions" style="width:100%;" id="' + itemsTable
			+ '_T">';
	html += '<thead id="head">';
	html += '<tr id="tr">';
	// draw columns headers
	$.each(columns, function(index, column) {
		html += '<td width="' + column.width + '%">' + column.label + '</td>';
	});
	html += '</tr></thead><tbody></tbody></table>';
	html += '</div><br>';
	// totals table
	html += '<table width="100%"" cellpadding="0" cellspacing="0" border="0">';
	html += '<tr>';
	html += '<td width="55%" class="dataLabel" valign="top">';
	html += '&nbsp;';
	html += '</td>                                                                               <!--color:#b3b9cf;-->';
	html += '<td width="40%" class="dataField" style="text-align: left;">';
	html += '<br>';
	html += '<table  id="result_table" cellpadding="0" cellspacing="0" style="width:100%; height:100%; border: 1px solid rgb(48,192,255);">';
	html += '</table>';
	html += '</td>';
	html += '<td width="5%" class="dataField" style="text-align: left;">&nbsp;</td>';
	html += '</tr>';
	html += '</table>';
	// sort? why not!
	/*
	 * html += 'Sortowanie:&nbsp;'; html += '<select id="sort_field"
	 * onChange="sortTable();"'; html += '<option value=""></option>'; html += '<option
	 * value="name">Nazwa</option>'; html += '<option value="code">Kod</option>';
	 * html += '<option value="category">Kategoria</option>'; html += '<option
	 * value="category">Kategoria</option>'; html += '<option
	 * value="price">Cena po<br>upuście</option>'; html += '<option
	 * value="total">Wartość</option>'; html += '</select>';
	 */
	$('#' + itemsTable).html(html);
}
function addProducts() {
	$(".loading_panel").css("display", "block");
	clearEmpty();
	var products = new Array();
	$.each(searchedProducts, function(index, value) {
		if ($('#prod_' + value).is(':checked'))
			products[value] = true;
	});
	for ( var key in products) {
		var params = {
			job : 'getProduct',
			id : key,
			stockId : $("#stock_id :selected").val(),
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			dataType : "json",
			async : false,
			success : function(data) {
				if (data != '-1') {
					var p = new Object();
					p.product_id = data.id;
					p.name = data.name;
					p.product_code = data.code;
					p.price = data.price;
					p.unit_name = data.unit_name;
					p.price = data.price;
					p.unit_id = data.unit_id;
					p.stock_state = data.stock_state;
					p.product_category_id = data.product_category_id;
					p.product_precision = data.unit_precision; 
					p.unit_precision = data.unit_precision; 
					p.product_is_consignment = data.is_consignment;
					if ($("#searchInputQty").val() != ''
							&& !isNaN(parseFloat(UnformatNumber($(
									"#searchInputQty").val()))))
						p.quantity = $("#searchInputQty").val();
					items.push(p);
				}
			},
			data : params
		});
	}
	AddSearchRecord();
	FillTable(items);
	checkProductIsConsignment();
	// clear results
	$('#searchResultDiv').html('');
	searchedProducts = new Array();
	$('#searchProductsInput').val('');

	$(".loading_panel").css("display", "none");
}
function AddProduct(index,record){
	$(".loading_panel").css("display", "block");
	var record;
	var pricebook = $("#pricebook_id :selected").val();

		var params = {
				job : 'getProduct',
				id : record,
				stockId : $("#stock_out_id :selected").val(),
			};
			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					if (data != '-1') {
						
						items[index].product_id = data.id;
						items[index].name = data.name;
						items[index].product_code = data.code;
						items[index].product_id = data.id;
						items[index].ecmvat_id = data.ecmvat_id;
						items[index].ecmvat_value = data.ecmvat_value;
						items[index].ecmvat_name = data.ecmvat_name;
						items[index].product_ean = data.ean;
						items[index].discount = data.discount;
						items[index].product_ean2 = data.ean2;
						items[index].price = data.price;
						items[index].unit_name = data.unit_name;
						items[index].unit_id = data.unit_id;
						items[index].price_start = data.price_start;
						items[index].recipient_code = data.recipient_code;
						items[index].product_precision = data.unit_precision; 
						items[index].unit_precision = data.unit_precision; 
						items[index].product_is_consignment = data.is_consignment;
						items[index].stock_state = data.stock_state;
						if ($("#searchInputPrice").val() != ''
								&& !isNaN(parseFloat(UnformatNumber($(
										"#searchInputPrice").val()))))
							items[index].price_start = $("#searchInputPrice").val();
						if ($("#searchInputQty").val() != ''
								&& !isNaN(parseFloat(UnformatNumber($(
										"#searchInputQty").val()))))
							items[index].quantity = $("#searchInputQty").val();
						
					}
				},
				data : params
			});
	AddSearchRecord();
	FillTable(items);
	checkProductIsConsignment();
	$('#searchResultDiv').html('');
	$(".loading_panel").css("display", "none");
    $("#quantity_"+index).focus().select();
}
function getItems(editview) {
	var record = '';
	if ($("#duplicate").val() == true)
		record = $("input[name='return_id']").val();
	else
		record = $("input[name='record']").val();
	if (isNaN(editview))
		editview = true;
	var params = {
		job : 'getItems',
		record : record,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async: false,
		success : function(data) {
			items = data;
			if (editview)
				FillTable(items, false);
			else
				FillTable(items, true);
			$(".loading_panel").css("display", "none");
		},
		data : params
	});
}
/*
function searchAllProducts() {
	var searchKey = '%';
	$("#searchResultDiv").html(
			'<img src="modules/EcmSales/images/loading.gif"/>');
	setTimeout(function() {

			var params = {
				job : 'searchProducts',
				searchKey : searchKey,
				searchCategory : $("#productSearchCategory :selected").val(),
				searchStock : $("#productSearchStock :selected").val(),
				searchSort : $("#productSearchSort :selected").val(),
			};

			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				success : function(data) {
					if (data != '-1')
						if (data.length == 0)
							$('#searchResultDiv').html(
									'MOD.LBL_SEARCH_NO_RESULT');
						else
							createSearchResult(data);
				},
				data : params
			});
		
	}, 1000);
}
*/
function DrawDetailSummary() {
	$("#result_table").html('');
	html = '';
	html += '<tr id="subtotal_tr"> ';
	html += '<td class="positionsLabel" style="border-top:0px;">Suma dokumentu</td>';
	html += '<td class="positionsField" style="border-top:0px;"><input type="text" style="border:0px;font-weight:900;width:100%;text-align:right;" readonly="readonly" name="t_netto" id="t_netto" value=\''
			+FormatNumber($("#total_netto").val()) + '\'></td>';
	html += '</tr>';


	$("#result_table").html(html);
}

function generateNumber() {
	var params = {
		job : 'generateNumber',
		stock: $("#stock_id").val(),
		date : 	$("#register_date").val(),
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
			if (data == '-1') {
				// try loading again
				generateNumber();
			} else {
				$("#document_no").val(data.document_no);
				$("#number").val(data.number);
				$(".loading_panel").css("display", "none");
			}
		},
		data : params
	});
}
function getPricesInfo(index) {
	$("#price_start_div_" + index).show('slow');
	$("#price_start_div_" + index).html(
			'<img src="modules/EcmQuotes/images/loading.gif"/>');

	var params = {
		job : 'getPricesInfo',
		product_id : $("#product_id_" + index).val(),
		pricebook_id : $("#pricebook_id :selected").val(),
		account_id : $("#parent_id").val(),
	};
	$
			.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					html = '<ul style="font-size: 7pt;">';
					$
							.each(
									data,
									function(key, value) {
										if (value.name == 'pricebook') {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val(\''
													+ FormatNumber(value.price)
													+ '\'); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ')"><u>'
													+ $(
															"#pricebook_id :selected")
															.html()
													+ ': '
													+ FormatNumber(value.price)
													+ '</u></li>';
										} else if (value.name == $(
												"#ecmprice_name").val()) {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val('
													+ value.price
													+ '); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ');"><b>'
													+ value.name
													+ ': '
													+ FormatNumber(value.price)
													+ '</b></li>';
										} else {
										if(value.visible=='1'){
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val('
													+ value.price
													+ '); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ');">'
													+ value.name
													+ ': ';
													if(value.module=='EcmPrices'){
													html+='<font style="color:#7FFF00;">'+FormatNumber(value.price)+'</font>';
													}
													if(value.module=='EcmInvoiceOuts'){
													html+='<font style="color:#FF3333;">'+FormatNumber(value.price)+'</font>';
													}
													html+ '</li>';
											}
										}
									});
					html += '</ul>';
				},
				data : params
			});
	$("#price_start_div_" + index).html(html);
}
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 refreshStock(index) {
	var params = {
		job : 'getStockState',
		id : $("#product_id_" + index).val(),
		stockId : $("#stock_id").val(),
	};

	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			$("#stock_state_" + index).val(FormatNumber(data,$("#product_precision_" + index).val()));
		},
		data : params
	});
}
function checkProducts() {
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	var error = false; // hope :)
	var total_netto=0;
	for (var index = 0; index != count; index++) {
		if($("#product_id_" + index).val()!=''){
			var qty = UnformatNumber($("#quantity_" + index).val());
			var cat_id = $("#product_category_id_" + index).val();
			// refresh items array
			items[index].quantity = qty;
			items[index].price = UnformatNumber($("#price_" + index).val());
			items[index].total=items[index].quantity*items[index].price;
			$("#total_" + index).val(FormatNumber(items[index].total,2));
			total_netto+=items[index].total;
			var stock = UnformatNumber($("#stock_state_" + index).val());
			if(!(qty>0)){
				error=true;
				$("#quantity_" + index).css("color", "red");
			} else
				$("#quantity_" + index).css("color", "black");
		}
	}
	$("#total_netto").val(total_netto);
	DrawDetailSummary();
	if (error)
		return false;
	else
		return true;
}

function getComponents(index) {
	$(".loading_panel").css("display", "block");
	var product_id = items[index].product_id;
	var qty = items[index].quantity;
	//var price = items[index].price;

	var params = {
		job : 'getComponents',
		product_id : product_id,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.length > 0) {
				items.splice(index, 1);
				$.each(data, function(index, value) {
					var p = new Object();
					p.product_id = value.id;
					p.name = value.name;
					p.product_code = value.code;
					p.price = value.price;
					p.unit_name = value.unit_name;
					p.unit_id = value.unit_id;
					p.quantity = qty * parseInt(value.quantity);
					p.product_category_id = value.product_category_id;
					
					if (p.product_category_id=='d7f876b0-1a3d-43a1-7c9b-511ba40df3d1')
						return;
					items.push(p);
				});
			};
		},
		data : params
	});
	FillTable(items);
	$(".loading_panel").css("display", "none");
}

function getSearchInfo2(product_id, product_code) {
	$("#search_info_div2_" + product_id).show().draggable();
	var html = '<img style="cursor: pointer;" align="left" src="themes/Sugar/images/close_inline.gif" onClick="$(\'#search_info_div2_'
								+ product_id
								+ '\').hide(\'slow\')"/>';
	 html += '<a href="index.php?module=EcmProducts&action=DetailView&record='
			+ product_id + '" target="_blank">' + product_code + '</a><br><br>';
	 html +='<table><tr><td style="text-align:left;">Magazyn</td><td>Ilość</td></tr>';
	var params = {
		job : 'getStockArray',
		product_id : product_id,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			$.each(data, function(key, value) {
					html += '<tr><td style="text-align:left;">'+key + '</td><td>' + FormatNumber(value)
							+ '</td></tr>';
			});
		},
		data : params
	});
	html += '</table>';

	$("#search_info_div2_" + product_id).html(html);
}
/*
function getSearchInfo(product_id, product_code) {
	$("#search_info_div_" + product_id).show().draggable();
	var html = '<img style="cursor: pointer;" align="left" src="themes/Sugar/images/close_inline.gif" onClick="$(\'#search_info_div_'
								+ product_id
								+ '\').hide(\'slow\')"/>';
	 html += '<a href="index.php?module=EcmProducts&action=DetailView&record='
			+ product_id + '" target="_blank">' + product_code + '</a><br><br>';
	// get prices info
	 html +='<table><tr><td style="text-align:left;">Nazwa</td><td>Ilość</td><td>Cena</td><td>Data dok</td></tr>';
	var params = {
		job : 'getPricesInfo',
		product_id : product_id,
		pricebook_id : $("#pricebook_id :selected").val(),
		account_id : $("#parent_id").val(),
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			$.each(data, function(key, value) {
				if (value.name == 'pricebook')
					html += $("#pricebook_id :selected").html() + ': '
							+ FormatNumber(value.price) + '<br>';
				if (value.name == $("#ecmprice_name").val())
					html += '<b>' + value.name + ': '
							+ FormatNumber(value.price) + '</b><br>';
				else

					if(value.module=='EcmStockDocIns'){
						html+='<tr><td style="text-align:left;">'+value.name + '</td><td>'+value.quantity+'</td><td> <font style="color:#7FFF00;text-align:right;">'+FormatNumber(value.price)+'</font></td><td>'+value.register_date+'</td></tr>';
					}
					//html += value.name + ': ' + FormatNumber(value.price)
						//	+ '<br>';
			});
		},
		data : params
	});
	html+='</tr></table>';

	$("#search_info_div_" + product_id).html(html);
}
*/
function getSearchInfo3(product_id, product_code) {
	$("#search_info_div3_" + product_id).show().draggable();
	var html = '<img style="cursor: pointer;" align="left" src="themes/Sugar/images/close_inline.gif" onClick="$(\'#search_info_div3_'
								+ product_id
								+ '\').hide(\'slow\')"/>';
	 html += '<a href="index.php?module=EcmProducts&action=DetailView&record='
			+ product_id + '" target="_blank">' + product_code + '</a><br><br>';
	// get prices info
	 html +='<table><tr><td style="text-align:left;">Nazwa</td><td>Cena</td></tr>';
	var params = {
		job : 'getPricesInfo',
		product_id : product_id,
		pricebook_id : $("#pricebook_id :selected").val(),
		account_id : $("#parent_id").val(),
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			$.each(data, function(key, value) {
				if (value.name == 'pricebook')
					html += $("#pricebook_id :selected").html() + ': '
							+ FormatNumber(value.price) + '<br>';
				if (value.name == $("#ecmprice_name").val())
					html += '<b>' + value.name + ': '
							+ FormatNumber(value.price) + '</b><br>';
				else

					if(value.module=='EcmPrices'){
						html+='<tr><td style="text-align:left;">'+value.name + ':</td><td> <font style="color:#7FFF00;text-align:right;">'+FormatNumber(value.price)+'</font></td></tr>';
					}
					if(value.module=='EcmInvoiceOuts'){
						html+='<tr><td "text-align:left;">'+value.name + ':</td><td> <font style="color:#FF3333;text-align:right;">'+FormatNumber(value.price)+'</font></td></tr>';
					}
					//html += value.name + ': ' + FormatNumber(value.price)
						//	+ '<br>';
			});
		},
		data : params
	});
	html+='</table>';

	$("#search_info_div3_" + product_id).html(html);
}
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();
}
// sortable rows in main table
$("#" + itemsTable + " tbody").sortable();