$.widget("ui.customersearch", $.ui.dialog, {
	_dialogCreate: $.ui.dialog.prototype._create,
	_create: function() {
		var widget = this;
		widget._dialogCreate();
		var height = $(window).height();
		if (height > 690) {
			height = 690;
		}
		widget.option({
			title: 'Asiakashaku',
			modal: true,
			width: 600,
			height: height,
			buttons: {
				'Peruuta' : function() {
					widget.close();
				}
			}
		});
		widget.element.load('asiakkaat/haku', function() { //Search Form
			$(this).find('input[type="submit"]').button().removeClass('button');
			$(this).find('a.cancel').remove();
			$(this).find('#form-cmrsearch')
				.submit(function() {
					widget.searchResults.html('&#160;').addClass('ajax-loading');
					$.post($(this).attr('action'), $(this).serialize(), function(data) {
							widget._handleSearchResult(data);
						}, 'json')
					return false;
				}).find('.fieldset:last-child')
					.append($(this).find('#customeradd')
																	.button({icons: {primary: 'ui-icon-plus'}})
																	.click(function() {
																		widget._getNewCustomerForm();
																		return false;
																	})
																	.css('float', 'right'));
			$(this).find('.toolbar').remove();
			widget.pagination = $('<p></p>').appendTo($(this));
			widget.searchResults = $('<div>&#160;</div>').appendTo($(this));
		});
		$('a.customerselect').live('click', function() {
			var tr = $(this).parent().parent();
			var customerid = tr.find('.customerid').text();
			var customername = tr.find('.customername').text();
			var customeraddress = tr.find('.customeraddress').text();
			var customerphone = tr.find('.customerphone').text();
			widget._trigger('customerSelected', null, {
					customerid: customerid,
					customername: customername,
					customeraddress: customeraddress,
					customerphone: customerphone
			});
			return false;
		});
	},
	_handleSearchResult: function(data) {
		var widget = this;
		if (data.errors) {
			widget.searchResults.removeClass('ajax-loading');
			$('<div />').validationerrordialog({
				validationErrors: data.errors
			});
		}
		else {
			var cacheId = data.cacheid;
			var currentPage = data.page;
			var totalPages = data.lastpage;
			var totalCount = data.count;
			var resultsperpage = data.resultsperpage;
			if (totalPages > 20) {
				totalPages = 20;
			}
			var start = (currentPage - 1) * resultsperpage + 1;
			var end = start + resultsperpage - 1;
			if (end > totalCount) {
				end = totalCount;
			}
			this.pagination.html('').append('Asiakkaat ' + start + '-' + end + '/' + totalCount + ' Sivut: ');
			for (var i=1; i<=totalPages; i++) {
				var anchor = $('<a href="asiakkaat/haku/' + cacheId + ';' + i + '"></a>');
				if (i == currentPage) {
					anchor.html('<strong>' + i + '</strong>');
				}
				else {
					anchor.text(i);
				}
				anchor.click(function() {
					$.getJSON($(this).attr('href'), function(data) {widget._handleSearchResult(data);});
					return false;
				});
				this.pagination.append(anchor).append(' ');
			}
			var searchResultTable = $('<table cellpadding="0" cellspacing="0"><tr><th>Asiakasnro</th><th>Nimi</th><th>Osoite</th><th>Puhnro</th><th>&#160;</th></tr></table>');
			widget.searchResults.removeClass('ajax-loading').html('')
				.append(searchResultTable);
			$.each(data.rows, function(key, customer) {
				searchResultTable.append('<tr><td class="customerid">' + customer.Id + '</td><td class="customername">' + customer.Name + '</td><td class="customeraddress">' + customer.Street1 + ' ' + customer.Zip + ' ' + customer.City + '</td><td class="customerphone">' + customer.Phone1 + '</td><td><a class="customerselect" href="#">Valitse</td></tr>');
			});
		}
	},
	_getNewCustomerForm: function() {
		var widget = this;
		widget.option('title', 'Uusi asiakas');
		widget.element.load('asiakkaat/uusi', function() {
			$(this).find('a.cancel').remove();
			$(this).find('input.button').removeClass('button').button();
			$(this).find('form').submit(function() {
				$.post($(this).attr('action'), $(this).serialize(), function(data) {
					if (data.errors) {
						$('<div />').validationerrordialog({
							validationErrors: data.errors
						});
					}
					else {
						var customer = data.customer;
						var address = '';
						if (customer.Street1) {
							address += customer.Street1 + ' ';
						}
						if (customer.Zip) {
							address += customer.Zip + ' ';
						}
						if (customer.City) {
							address += customer.City;
						}
						widget._trigger('customerSelected', null, {
							customerid: customer.Id,
							customername: customer.Name,
							customeraddress: address,
							customerphone: customer.Phone1
						});
					}
				}, 'json')
				return false;
			});
		});
	},
	performSearch: function() {
		this.element.find('#form-cmrsearch').submit();
	}
});
