$.widget("ui.productsearch", $.ui.dialog, {
	options: {
		showPrices: 0
	},
	_dialogCreate: $.ui.dialog.prototype._create,
	_create: function() {
		var $this = this;
		this._dialogCreate();
		this.option({
			autoOpen: false,
			modal: true,
			width: 810,
			height: $(window).height() -30,
			title: 'Tuotehaku',
			buttons: this._getButtons(true)
		});
		this.pagination = $('<p></p>');
		this.rowsTable = $('<table cellspacing="0" cellpadding="0"><tr><th>Tuotenro</th><th>Nimi</th><th>Yks.</th><th>Myyntihinta</th><th>Lisää lähetteelle</th></tr></table>').hide();
		this.element.load('tuotteet', function() { //Search Form
			$(this).append($this.pagination);
			$(this).append($this.rowsTable);
			$(this).find('input[type="submit"]').button().removeClass('button');
			$(this).find('form').submit(function() {
				$.post($(this).attr('action'), $(this).serialize(), function(data) {$this._handleSearchResult(data);}, 'json');
				return false;
			});
		});
	},
	_getButtons: function(onlyCancel) {
		var $this = this;
		var ret = {};
		ret['Peruuta'] = function() {$this.close();}
		if (!onlyCancel) {
			ret['Lisää lähetteelle'] = function() {
				var rows = [];
				$this.rowsTable.find('input.amount').each(function(key, element) {
					if ($(element).val()) {
						rows.push($.extend({amount: $(element).val()}, $(element).closest('tr').data('item')));
					}
				});
				$this._trigger('rowsAdded', null, {rows: rows});
				$this.element.find('tr.productrow td input.amount').val('');
			}
		}
		return ret;
	},
	_handleSearchResult: function(data) {
		var $this = this;
		if (data.errors) {
			$('<div />').validationerrordialog({
				validationErrors: data.errors
				});
		}
		else {
			var cacheId = data.cacheid;
			var offset = data.offset;
			var totalCount = data.count;
			var resultsperpage = data.resultsperpage;
			var totalPages = Math.ceil(totalCount / resultsperpage);
			if (totalPages > 20) {
				totalPages = 20;
			}
			this.pagination.html('').append('Tuotteet ' + data.start + '-' + data.end + '/' + totalCount + ' Sivut: ');
			for (var i=1; i<=totalPages; i++) {
				var pageOffset = (i-1) * resultsperpage;
				var anchor = $('<a href="tuotteet/hakutulos/' + cacheId + ';' + pageOffset + '"></a>');
				if (pageOffset == Number(offset)) {
					anchor.html('<strong>' + i + '</strong>');
				}
				else {
					anchor.text(i);
				}
				anchor.click(function() {
					$.getJSON($(this).attr('href'), function(data) {$this._handleSearchResult(data);});
					return false;
				});
				this.pagination.append(anchor).append(' ');
			}
			this.rowsTable.find('.productrow').remove();
			$.each(data.rows, function(key, row) {
				var rowElem = $('<tr class="productrow"><td>' + row.id + '</td><td>' + row.name1 + ' ' + row.name2 + '</td><td>' + row.unit + '</td><td class="salesprice">' + formatNumber(row.salesprice) + '</td><td><input type="text" size="4" class="amount small" /></td></tr>').data('item', row);
				if ($this.option('showPrices') == 0) {
					rowElem.find('td.salesprice').text('-');
				}
				else if ($this.option('showPrices') == 2) {
					rowElem.find('td.salesprice').text(formatNumber(parseFloat(row.salesprice) + parseFloat(row.salesprice) * parseFloat(row.vat) / 100));
				}
				$this.rowsTable.append(rowElem);

			});
			this.rowsTable.show();
			this.option('buttons', this._getButtons());
		}
	}
});








/*
	$('a.productsearch').click(function() {
		searchDiv.html('');
		searchDiv.addClass('ajax-loading');
		$.get($(this).attr('href'), function(data) {
			updateSearchDialog(searchDiv, data);
		});
		searchDiv.dialog('open');
		$(this).blur();
		return false;
	});*/



	
/*
updateSearchDialog = function(searchDiv, data) {
	searchDiv.removeClass('ajax-loading');
	searchDiv.html(data);
	searchDiv.find('a.cancel').click(function() {
		searchDiv.dialog('close');
		return false;
	});
	setButtons(searchDiv.find('input[type=submit]'), searchDiv.find('a.cancel'));
	//setSelectmenu(searchDiv.find('select'));
	var searchForm = searchDiv.find('#form-prdsearch');
	searchForm.submit(function() {
		searchDiv.addClass('ajax-loading');
		$.post(searchForm.attr('action'), searchForm.serialize(), function(data) {
			updateSearchDialog(searchDiv, data);
			var searchResultForm = searchDiv.find('#form-searchresults');
			searchDiv.dialog('option', 'buttons', getButtons(searchDiv, searchResultForm.find('tr').length <= 1));

			searchResultForm.submit(function() {
				addRowsFromSearch($(this));
				searchDiv.dialog('close');
				return false;
			});
		});
		return false;
	});
}*/
