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

function FillTable(data, allReadOnly) {
	html = '';
	// loop throw data rows
	$
			.each(
					data,
					function(row_index, row) {
						html += '<tr>';
						// and insert columns
						$
								.each(
										columns,
										function(col_index, column) {
											// row must have code and name
											if (!row.product_code
													|| row.product_code == ''
													|| !row.name
													|| row.name == '')
												return; // return in each =
											// continue in php for
											// loop
											// special types
											if (column.name == 'number') {
												html += '<td><input class="inputs" style="text-align: center;" type="text" id="number_'
														+ row_index
														+ '" name="number_'
														+ row_index
														+ '" readonly value="'
														+ (row_index + 1)
														+ '"/></td>';
											} else if (column.name == 'name') {
												html += '<td><textarea style="width: 100%; height: 100%;" id="name_'
														+ row_index
														+ '" name="name_'
														+ row_index + '"';
												if (allReadOnly)
													html += ' readonly';
												html += '>' + row.name
														+ '</textarea></td>';
											} else if (column.name == 'options') {
												if (allReadOnly)
													html += '<td></tr>';
												else {
													html += '<td>';
													// move up
													html += '<a onClick="moveUpRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmSales/images/moverowup.gif"/></a>';
													html += '&nbsp;';
													// move down
													html += '<a onClick="moveDownRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmSales/images/moverowdown.gif"/></a>';
													html += '<br>';
													// delete row
													html += '<a onClick="deleteRow('
															+ row_index
															+ ')" target="_blank"><img style="cursor:pointer;" src="modules/EcmSales/images/deleterow.gif"/></a>';
													html += '</td>';
												}
											}
											// other types
											else {
												html += '<td>';
												$
														.each(
																column.content,
																function(
																		cell_index,
																		cell) {
																	var cellname = column.name
																			+ cell.name;
																	if (cellname == 'product_link') {
																		html += '<a href="index.php?module=EcmProducts&action=DetailView&record='
																				+ row.product_id
																				+ '" target="_blank">'
																				+ row.product_code
																				+ '</a>';
																	} else if (cellname == 'price_start_div'
																			&& !allReadOnly) {
																		html += '<br><img style="cursor: pointer;" src="modules/EcmSales/images/search.gif" onClick="if ($(\'#price_start_div_'
																				+ row_index
																				+ '\').css(\'display\')==\'none\') getPricesInfo('
																				+ row_index
																				+ '); else $(\'#price_start_div_'
																				+ row_index
																				+ '\').hide(\'slow\')"/>';
																		html += '<div id="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '" style="display:none;float:right;text-align:right;border: 1px #cccccc solid;padding:3px;"></div>';
																	} else {
																		if (cell.label
																				&& cell.label != '')
																			html += '<p>'
																					+ cell.label
																					+ '</p>';
																		html += '<input class="inputs" type="'
																				+ cell.type
																				+ '" name="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '" id="'
																				+ cellname
																				+ '_'
																				+ row_index
																				+ '"';
																		if (cell.readonly
																				|| allReadOnly)
																			html += ' readonly ';
																		if (cell.style)
																			html += ' style="'+cell.style+'" ';
																		if (column.align)
																			html += ' style="text-align: '
																					+ column.align
																					+ ';"';
																		if (cell.onChange
																				|| cell.isNumber)
																			html += ' onChange="$(this).val(FormatNumber($(this).val()));'
																					+ cell.onChange
																					+ '" onClick="$(this).select();"';
																		else if (cell.onChange
																				|| !cell.isNumber)
																			html += ' onChange="'
																					+ cell.onChange
																					+ '" ';
																		if (row[cellname]
																				&& cell.isNumber)
																			html += ' value="'
																					+ FormatNumber(row[cellname])
																					+ '" ';
																		else if (row[cellname])
																			html += ' value="'
																					+ row[cellname]
																					+ '" ';
																		else {
																			if (cell.isNumber)
																				html += ' value="0,00" ';
																			else
																				html += ' value="" ';
																		}
																		html += '>';
																	}
																	if (cell.type != 'hidden')
																		html += '<br>';
																});
													html += '</td>';
											}

										});
						html += '</tr>';

					});

	$('#' + itemsTable + '_T > tbody').html(html);
	if (!allReadOnly) {
		// calculate totals
		var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
		for (var index = 0; index != count; index++)
			calculateRow(index);
	} else
		DrawDetailSummary();
}

function calculateRow(index) {
	if (index == -1)
		return;

	// liczone według najlepszych zasad księgowości
	var price_start = UnformatNumber($('#price_start_' + index).val());
	var discount = UnformatNumber($('#discount_' + index).val());
	var vat_value = $('#ecmvat_value_' + index).val();
	var quantity = UnformatNumber($('#quantity_' + index).val());
	var price_netto = 0;
	if (discount > 0)
		price_netto = price_start - (price_start * (discount / 100));
	else
		price_netto = price_start;

	var total_netto = price_netto * quantity;

	// put data
	$('#price_netto_' + index).val(FormatNumber(price_netto));
	$('#total_netto_' + index).val(FormatNumber(total_netto));

	// put data to items array
	items[index].price_start = toFixed(price_start, 2);
	items[index].price_netto = toFixed(price_netto, 2);
	items[index].total_netto = toFixed(total_netto, 2);
	items[index].quantity = toFixed(quantity, 2);
	items[index].discount = toFixed(discount, 2);
	items[index].ecmvat_id = $('#ecmvat_id_' + index).val();
	items[index].ecmvat_name = $('#ecmvat_name_' + index).val();
	items[index].ecmvat_value = vat_value;
	
	items[index].reservation = $('#reservation' + index).val();

	// put other data
	items[index].recipient_code = $('#recipient_code_' + index).val();
	items[index].reservation = $('#reservation_' + index).val(); 
	// change name or language?
	items[index].name = $('#name_' + index).val();
	items[index].unit_name = $('#unit_name_' + index).val();

	// calculate total
	calculateTotal();
}

function calculateTotal() {
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	var vats = new Array();
	var all_subtotal = 0;
	var all_total = 0;
	var sum_vats = 0;
	var sum_discounts = 0;

	for (var index = 0; index != count; index++) {
		subtotal = UnformatNumber($('#total_netto_' + index).val());
		all_subtotal += subtotal;
		if (!$("#no_tax").is(":checked")) {
			// font color to black
			$("#ecmvat_name_" + index).css("color", "black");
			if (!($('#ecmvat_id_' + index).val() in vats)) {
				vats[$('#ecmvat_id_' + index).val()] = new Object();
				vats[$('#ecmvat_id_' + index).val()].value_name = $(
						'#ecmvat_name_' + index).val(); // ex. 23
				vats[$('#ecmvat_id_' + index).val()].value = subtotal
						* ($('#ecmvat_value_' + index).val() / 100);
			} else
				vats[$('#ecmvat_id_' + index).val()].value += subtotal
						* ($('#ecmvat_value_' + index).val() / 100);
			sum_vats += subtotal * ($('#ecmvat_value_' + index).val() / 100);
		} else {
			// set color to red
			$("#ecmvat_name_" + index).css("color", "red");
		}

		if (UnformatNumber($('#discount_' + index).val()) > 0)
			sum_discounts += (UnformatNumber($('#price_start_' + index).val()) * UnformatNumber($(
					'#quantity_' + index).val()))
					* (UnformatNumber($('#discount_' + index).val()) / 100);
	}
	all_total = all_subtotal + sum_vats;

	DrawSummary();

	$("#t_netto").val(FormatNumber(all_subtotal));
	$("#t_brutto").val(FormatNumber(all_total));
	$("#disc").val(FormatNumber(sum_discounts));
	$("#total_netto").val(all_subtotal);
	$("#total_brutto").val(all_total);
	// add vats
	var vats_summary = '';
	for ( var x in vats) {
		var html = '<tr><td class="positionsLabel">' + vats[x].value_name + '</td>';
		html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="vat" id="vat" value="'
				+ FormatNumber(vats[x].value) + '"></td></tr>';
		$('#result_table > tbody > tr:eq(1)').after(html);
		vats_summary += vats[x].value_name + ':' + toFixed(vats[x].value, 2)
				+ ',';
	}

	$("#vats_summary").val(vats_summary);
}

function deleteRow(index) {
	items.splice(index, 1);
	FillTable(items);
}

function moveUpRow(index) {
	if (index == 0)
		return; // Can't go upper.. :(
	var new_index = index - 1;
	var old_index = index;
	if (new_index >= items.length) {
		var k = new_index - items.length;
		while ((k--) + 1) {
			items.push(undefined);
		}
	}
	items.splice(new_index, 0, items.splice(old_index, 1)[0]);
	FillTable(items);
}

function moveDownRow(index) {
	if (index == items.length - 1)
		return; // Can't go lower.. :(
	var new_index = index + 1;
	var old_index = index;
	if (new_index >= items.length) {
		var k = new_index - items.length;
		while ((k--) + 1) {
			items.push(undefined);
		}
	}
	items.splice(new_index, 0, items.splice(old_index, 1)[0]);
	FillTable(items);
}

function FormatNumber(number, precision) {
	var precision = precision || 2;
	// make string..
	number = number + '';
	number = number.replace(',', '.');
	// round
	number = toFixed(number, precision);
	// add 1000 sep
	var tmp = number.split(".");
	var c = '';
	for (var i = tmp[0].length; i != -1; i--) {
		c += tmp[0].charAt(i);
		if ((tmp[0].length - i) == 0 || i == 0)
			continue;
		if ((tmp[0].length - i) % 3 == 0)
			c += '.';
	}
	// reverse c
	c = c.split("").reverse().join("");

	return c + ',' + tmp[1];
}

function UnformatNumber(number) {
	// make string..
	number = number + '';
	// remove 1000 sep
	number = number.replace('.', '');
	// change ',' to '.'
	number = number.replace(',', '.');

	return parseFloat(number);
}

// round with precision
function toFixed(value, precision) {
	var precision = precision || 0, neg = value < 0, power = Math.pow(10,
			precision), value = Math.round(value * power), integral = String((neg ? Math.ceil
			: Math.floor)(value / power)), fraction = String((neg ? -value
			: value)
			% power), padding = new Array(Math.max(precision - fraction.length,
			0) + 1).join('0');

	return precision ? integral + '.' + padding + fraction : integral;
}

// draw table
function DrawHeaders() {
	var html = '<link rel="stylesheet" type="text/css" href="modules/EcmSales/MyTable.css" />';
	html += '<div style="width:100%;border: 1px solid rgb(48,192,255);background-color:white;height: 250px;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 DrawSummary() {
	$("#result_table").html('');
	html = '';
	html += '<tr id="subtotal_tr"> ';
	html += '<td class="positionsLabel" style="border-top:0px;">Suma netto</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=\'\'></td>';
	html += '</tr>';
	html += '<tr id="discount_tr"> ';
	html += '<td class="positionsLabel">Upust</td>';
	html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="disc" id="disc" value=\'\'></td>';
	html += '</tr>';
	html += '<tr id="total_tr"> ';
	html += '<td class="positionsLabel">Suma brutto</td>';
	html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="t_brutto" id="t_brutto" value=\'\'></td>';
	html += '</tr>';
	$("#result_table").html(html);
}
function searchProducts() {
	var searchKey = $('#searchProductsInput').val();
	if (searchKey.length < 2 && searchKey != '%') {
		return;
	}
	$("#searchResultDiv").html(
			'<img src="modules/EcmSales/images/loading.gif"/>');
	setTimeout(function() {
		if (searchKey == $('#searchProductsInput').val()) {
			var params = {
				job : 'searchProducts',
				searchKey : searchKey,
				searchCategory : $("#productSearchCategory :selected").val(),
				searchStock : $("#productSearchStock :selected").val(),
				searchSort : $("#productSearchSort :selected").val(),
				searchStockId : $("#stock_id").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 validateDate(){
	var params = {
			job : 'validateDate',
			date : $('#send_date').val(),
			date2 : $('#delivery_date').val(),
		};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async:false,
		success : function(data) {
	result = data.error;
		},
		data : params
	});
	return result;
}

function calculateDate(date){
	var params = {
			job : 'calculateDate',
			date : date,
		};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
		$('#send_date').val(data['date']);
		},
		data : params
	});
}

function createSearchResult(data) {
	var html = '<table style="text-align: center;" cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">';
	html += '<theader><tr>';
	html += '<th  style="width: 15pt; margin: auto auto;">&nbsp</th>';
	html += '<th style="width: 100pt; text-align: left;">Kod</th>';
	html += '<th style="width: 300pt; text-align: left;">Nazwa</th>';
	if ($("#productSearchStock :selected").val() != '1')
		html += '<th  style="width: 30pt; text-align: right;">Stan</th>';
	html += '<th  style="width: 15pt; margin: auto auto;">&nbsp</th>';

	html += '</tr></thead>';
	var counter;
	$
			.each(
					data,
					function(index, value) {
						if(counter%2==0){
							html += '<tr style="height: 15pt;" class="oddListRowS1">';
						} else {
							html += '<tr style="height: 15pt;" class="evenListRowS1">';
						}
						html += '<td style=""><input id="prod_'
								+ value.id + '" type="checkbox"/></td>';
						html += '<td onClick="$(\'#prod_'
								+ value.id
								+ '\').prop(\'checked\', true);" style="text-align: left;">'
								+ value.code + '</td>';
						html += '<td onClick="unsetAllCheckboxes(); $(\'#prod_'
								+ value.id
								+ '\').prop(\'checked\', true); return addProducts();" style="text-align: left;">'
								+ value.name + '</td>';
						if ($("#productSearchStock :selected").val() != '1')
							html += '<td style="text-align: right;">'
									+ value.stock_state + '</td>';
						html += '<td style="">';
						html += '<img style="cursor: pointer;" src="modules/EcmSales/images/search.gif" onClick="if ($(\'#search_info_div_'
								+ value.id
								+ '\').css(\'display\')==\'none\') getSearchInfo(\''
								+ value.id
								+ '\',\''
								+ value.code
								+ '\'); else $(\'#search_info_div_'
								+ value.id
								+ '\').hide(\'slow\')"/>';
						html += '<div id="'
								+ 'search_info_div_'
								+ value.id
								+ '" style="display:none;float:right;text-align:right;border: 1px #cccccc solid;padding:3px;"></div>';
						html += '</td>';
						html += '</tr>';
						searchedProducts.push(value.id);
						counter++;
					});
	// add button
	html += '</table><br>';
	html += 'Cena:&nbsp<input type="text" id="searchInputPrice" value=""/>&nbspIlość:&nbsp<input type="text" id="searchInputQty" value=""/>';
	html += '<br><br><input type="button" value="Dodaj wiele" onClick="return addProducts();"/>';
	$('#searchResultDiv').html(html);
}

function unsetAllCheckboxes() {
	$("#searchResultDiv input[type=checkbox]").each(function() {
		$(this).prop("checked", false);
	});
}

function addProducts() {
	$(".loading_panel").css("display", "block");
	var products = new Array();
	$.each(searchedProducts, function(index, value) {
		if ($('#prod_' + value).is(':checked'))
			products[value] = true;
	});
	var pricebook = $("#pricebook_id :selected").val();
	for ( var key in products) {
		var params = {
			job : 'getProduct',
			id : key,
			pricebook : pricebook,
			account_id : $("#parent_id").val(),
			language : $("#ecmlanguage").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.product_id = data.id;
					p.ecmvat_id = data.ecmvat_id;
					p.ecmvat_value = data.ecmvat_value;
					p.ecmvat_name = data.ecmvat_name;
					p.product_ean = data.ean;
					p.product_ean2 = data.ean2;
					p.unit_name = data.unit_name;
					p.unit_id = data.unit_id;
					p.price_start = data.price_start;
					p.recipient_code = data.recipient_code;
					p.reservation = data.reservation;
					p.product_brand_label = data.brand_label;
					if ($("#searchInputPrice").val() != ''
							&& !isNaN(parseFloat(UnformatNumber($(
									"#searchInputPrice").val()))))
						p.price_start = $("#searchInputPrice").val();
					if ($("#searchInputQty").val() != ''
							&& !isNaN(parseFloat(UnformatNumber($(
									"#searchInputQty").val()))))
						p.quantity = $("#searchInputQty").val();
					items.push(p);
				}
			},
			data : params
		});
	}
	FillTable(items);
	// clear results
	$('#searchResultDiv').html('');
	searchedProducts = new Array();
	$('#searchProductsInput').val('');

	$(".loading_panel").css("display", "none");
}

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",
		success : function(data) {
			items = data;
			if (editview)
				FillTable(items, false);
			else
				FillTable(items, true);
			$(".loading_panel").css("display", "none");
		},
		data : params
	});
}
function getItemsFromEdi(editview) {
	var record = '';
	record=$("#edi_file").val();
	if (isNaN(editview))
		editview = true;
	var params = {
		job : 'getItemsFromEdi',
		record : record,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		success : function(data) {
			items = data;
			if (editview)
				FillTable(items, false);
			else
				FillTable(items, true);
			$(".loading_panel").css("display", "none");
		},
		data : params
	});
}
function getItemsFromQuote(editview) {

	var record = '';
	if ($("#duplicate").val() == true)
		record = $("input[name='return_id']").val();
	else
		record = $("input[name='ecmquote_id']").val();
	if (isNaN(editview))
		editview = true;
	var params = {
		job : 'getItemsFromQuote',
		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 DrawDetailSummary() {
	DrawSummary();
	$("#t_netto").val($("#total_netto").val());
	$("#t_brutto").val($("#total_brutto").val());
	$("#disc").val($("#discount").val());

	if ($("#no_tax").val() == '1') {
		$("input[name^=ecmvat_name]").css("color", "red");
		return;
	}

	var vats = $("#vats_summary").val().split(",");
	for (var i = 0; i < vats.length - 1; i++) {// last element is empty
		var vat = vats[i].split(":");
		var html = '<tr><td class="positionsLabel">' + vat[0] + '</td>';
		html += '<td class="positionsField"><input type="text" readonly="readonly" style="border:0px;font-weight:900;width:100%;text-align:right;" name="vat" id="vat" value="'
				+ FormatNumber(vat[1]) + '"></td></tr>';
		$('#result_table > tbody > tr:eq(1)').after(html);
	}
}

function changeLanguage() {
	$(".loading_panel").css("display", "block");
	var count = $('#' + itemsTable + '_T tr').length - 1; // -1 - thead row
	for (var index = 0; index != count; index++) {
		var params = {
			job : 'getTranslation',
			product_id : $("#product_id_" + index).val(),
			language : $("#ecmlanguage").val(),
			unit_id : $("#unit_id_" + index).val(),
		};
		$.ajax({
			type : "POST",
			url : ajax_url,
			async : false,
			dataType : "json",
			success : function(data) {
				$("#name_" + index).val(data.name);
				$("#unit_name_" + index).val(data.unit_name);
				calculateRow(index);
			},
			data : params
		});
	}
	$(".loading_panel").css("display", "none");
}

function getPricesInfo(index) {
	$("#price_start_div_" + index).show('slow');
	$("#price_start_div_" + index).html(
			'<img src="modules/EcmSales/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 {
											html += '<li style="cursor:pointer;" onClick="$(\'#price_start_'
													+ index
													+ '\').val('
													+ value.price
													+ '); $(this).closest(\'div\').hide(\'slow\');calculateRow('
													+ index
													+ ');">'
													+ value.name
													+ ': '
													+ FormatNumber(value.price)
													+ '</li>';
										}
									});
					html += '</ul>';
				},
				data : params
			});
	$("#price_start_div_" + index).html(html);
}

function getSearchInfo(product_id, product_code) {
	$("#search_info_div_" + product_id).show('slow');
	var html = '<a href="index.php?module=EcmProducts&action=DetailView&record='
			+ product_id + '" target="_blank">' + product_code + '</a><br><br>';
	html += '<table><tr><td><table><tr><td>';
	// get prices info
	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) {
			html += 'Ceny<br>';
			$.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
					html += value.name + ': ' + FormatNumber(value.price)
							+ '<br>';
			});
		},
		data : params
	});
	html += '</td></tr></table></td><td><table><tr><td>';
	var params = {
		job : 'getStockArray',
		product_id : product_id,
	};
	$.ajax({
		type : "POST",
		url : ajax_url,
		dataType : "json",
		async : false,
		success : function(data) {
			html += 'Stany<br>';
			$.each(data, function(key, value) {
					html += key + ': ' + FormatNumber(value)
							+ '<br>';
			});
		},
		data : params
	});
	html += '</td></tr></table></td>';
	var show_purchase_prices = false;
	
	if (show_purchase_prices) {
		html+='<td><table><tr><td>';
		var params = {
				job : 'getPurchaseArray',
				product_id : product_id,
			};
			$.ajax({
				type : "POST",
				url : ajax_url,
				dataType : "json",
				async : false,
				success : function(data) {
					console.log(data);
				},
				data : params
			});		
		html+='</td></tr></table></td>';
	}
	
	html+='</tr></table>';

	$("#search_info_div_" + product_id).html(html);
}

//sortable rows in main table
$("#"+itemsTable+" tbody").sortable();
//get parent info use ajax
function getParentInfo(parent_id, parent_type) {
	var params = {
			id : parent_id,
			type : parent_type,
			job : 'getParentInfo'
	};
		
	$.ajax({
			type: "POST",
			url: ajax_url,
			dataType : "json",
			success: function(data) {
				if (data == '-1') {
					alert('Błąd');
					$("#parent_name").val('');
					$("#parent_id").val('');
				} else {
					setParentInfo(data);
				}
			},
			data: params
	});
}

//insert parent info in fields
function setParentInfo(data) {
	//pricebooks
	createPricebookSelect(data.pricebooks);
	if (data.ecmprice_id && data.ecmprice_name) {
		$("#ecmprice_id").val(data.ecmprice_id);
		$("#ecmprice_name").val(data.ecmprice_name);
	}
	   //get shipping addresses
    shipping_addresses.length = 0; //clear array
    shipping_addresses = data.addresses;
    setAddresses();
	if ($("#new_number").val() == false) {
		$(".loading_panel").css("display", "none");
		//return; //if edit exists load only pricebooks
	}
	if (data.name)
		$("#parent_name_copy").val(data.name);
	if (data.parent_nip)
		$("#parent_nip").val(data.parent_nip);
	if (data.parent_address_street)
		$("#parent_address_street").val(data.parent_address_street);
	if (data.parent_address_city)
		$("#parent_address_city").val(data.parent_address_city);
	if (data.parent_address_postalcode)
		$("#parent_address_postalcode").val(data.parent_address_postalcode);
	if (data.parent_address_country)
		$("#parent_address_country").val(data.parent_address_country);
	if (data.invoice_type && data.invoice_type!='K')
		$("#no_tax").attr('checked', true);
	if (data.ecmpaymentcondition_id && data.ecmpaymentcondition_name) {
		$("#ecmpaymentcondition_id").val(data.ecmpaymentcondition_id);
		$("#ecmpaymentcondition_name").val(data.ecmpaymentcondition_name);
	}
	if (data.ecmdeliverycondition_id && data.ecmdeliverycondition_name) {
		$("#ecmdeliverycondition_id").val(data.ecmdeliverycondition_id);
		$("#ecmdeliverycondition_name").val(data.ecmdeliverycondition_name);
	}
	if (data.iln)
		$("#parent_iln").val(data.iln);
	if (data.parent_supplier_code)
		$("#parent_supplier_code").val(data.parent_supplier_code);
	if (data.currency_id) 
		$("#currency_id option[value=\""+data.currency_id+"\"]").attr('selected', 'selected');
	//clear prevoius validation data
	$.each(validation, function(index, value) {
		validation.index = false;
	});
	//validation
	if (data.document_recipient_code=='1')
		validation.recipient_code = true;
	if (data.document_parent_order_no=='1')
		validation.parent_order_no = true;
	if (data.document_delivery_address=='1')
		validation.delivery_address=true;
	if (data.document_parent_iln=='1')
		validation.parent_iln=true;
	if (data.document_shipping_iln=='1')
		validation.shipping_iln=true;
	if (data.document_parent_nip=='1')
		validation.parent_nip=true;
	if (data.document_shipping_nip=='1')
		validation.shipping_nip=true;
	setAccountValidation();
	
	//console.log(validation);
	
	//hide loading
	$(".loading_panel").css("display", "none");
}

function setAddresses() {
	if (shipping_addresses.length == 0) 
		return;
	var s = $("<select id=\"shipping_addresses\"/>");
	var opt='<option value=""></option>';
	$.each(shipping_addresses, function (index, value) {

		opt+='<option value="'+index+'">'+value.name+'</option>';
	});
	s.html(opt);
	$("#addresses").html("");
	$("#addresses").append(s);
	//set on change
	$("#shipping_addresses").change(function(){
		putShippingAddress($( "#shipping_addresses option:selected" ).val());
	});
}

function putShippingAddress(number) {
	if (number == '') {
		$("#shipping_address_name").val("");
		$("#shipping_address_street").val("");
		$("#shipping_address_postalcode").val("");
		$("#shipping_address_city").val("");
		$("#shipping_address_country").val("");
		$("#shipping_iln").val("");
		$("#shipping_nip").val("");
	} else {
		$("#shipping_address_name").val(shipping_addresses[number].name);
		$("#shipping_address_street").val(shipping_addresses[number].street);
		$("#shipping_address_postalcode").val(shipping_addresses[number].postalcode);
		$("#shipping_address_city").val(shipping_addresses[number].city);
		$("#shipping_address_country").val(shipping_addresses[number].country);
		$("#shipping_iln").val(shipping_addresses[number].iln);
		$("#shipping_nip").val(shipping_addresses[number].nip);
	}
}

function createPricebookSelect(pricebooks) {
	var s = $("<select id=\"pricebook_id\"/>");
	var opt = '';
	$.each(pricebooks, function(index, value) {
		opt+='<option value="'+value.id+'">'+value.name+'</option>';
	});
	s.html(opt);
	$("#pricebooks").html(""); //clear all values
	$("#pricebooks").append(s);
}

function generateNumber() {
	var params = {
			job : 'generateNumber'
	};
		
	$.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 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 setAccountValidation() {
	//first clear validation
	removeFromValidate('EditView', 'parent_order_no');
	removeFromValidate('EditView', 'parent_shipping_address_name');
	removeFromValidate('EditView', 'parent_shipping_address_street');
	removeFromValidate('EditView', 'parent_shipping_address_postalcode');
	removeFromValidate('EditView', 'parent_shipping_address_city');
	removeFromValidate('EditView', 'parent_iln');
	removeFromValidate('EditView', 'shipping_iln');

	//now add what we need
	if (validation.parent_order_no==true) 
		addToValidate('EditView', 'parent_document_no', 'id', 'true','');
	if (validation.parent_order_no==true) 
		addToValidate('EditView', 'parent_document_no', 'id', 'true','');
	if (validation.delivery_address==true) {
		addToValidate('EditView', 'shipping_address_name', 'id', 'true','');
		addToValidate('EditView', 'shipping_address_street', 'id', 'true','');
		addToValidate('EditView', 'shipping_address_postalcode', 'id', 'true','');
		addToValidate('EditView', 'shipping_address_city', 'id', 'true','');
	}
	if (validation.parent_iln==true) 
		addToValidate('EditView', 'parent_iln', 'id', 'true','');	
	if (validation.shipping_iln==true) 
		addToValidate('EditView', 'shipping_iln', 'id', 'true','');
	if (validation.parent_nip==true) 
		addToValidate('EditView', 'parent_nip', 'id', 'true','');	
	if (validation.shipping_nip==true) 
		addToValidate('EditView', 'shipping_nip', 'id', 'true','');
}


$.event.special.inputchange = {
	    setup: function() {
	        var self = this, val;
	        $.data(this, 'timer', window.setInterval(function() {
	            val = self.value;
	            if ( $.data( self, 'cache') != val ) {
	                $.data( self, 'cache', val );
	                $( self ).trigger( 'inputchange' );
	            }
	        }, 20));
	    },
	    teardown: function() {
	        window.clearInterval( $.data(this, 'timer') );
	    },
	    add: function() {
	        $.data(this, 'cache', this.value);
	    }
	};

function checkReservation(index) {
	console.log(index);
}

