$.widget("ui.salaryeventquickinput", $.ui.dialog, {
	options: {
		salarytypes: {},
		publicMemoTemplate: '',
		privateMemoTemolate: '',
		showOnlyDefaultSalarytypes: true
	},

	_dialogCreate: $.ui.dialog.prototype._create,
	_create: function() {
		var $this = this;
		this._dialogCreate();
		this.option({
			title: 'Uusi palkkatapahtuma',
			width: 950,
			height: 315,
			modal: true,
			buttons: [
				{
					text: 'Lisää',
					click: function() {
						var tabindex = $this.tabs.tabs('option', 'selected');
						var eventdate = ec.formatDate($this.datePicker.datepicker('getDate'));
						var salarytypeid = $('#fe-salarytypeid option:selected').val();
						var covid = null, covecomid = null, projectid = null, subprojectid = null;
						if (tabindex == 0) {
							covid = $this.coveringnoteCovId;
							if (!covid) {
								covecomid = $this.coveringnoteInput.val();
							}
						}
						else if ($this.options.allowProjectInput) {
							projectid = $this.projectInput.val();
							subprojectid = $this.subProjectInput.val();
						}
						var start = $('#neweventstart').val();
						var end = $('#neweventend').val();
						var hours = $('#neweventhours').val();
						var publicmemo = $('#neweventpublicmemo').val();
						var memo = $('#neweventmemo').val();
						var data = {
							event: {
								'EventDate': eventdate,
								'SalaryTypeId': salarytypeid,
								'EventStart': start,
								'EventEnd': end,
								'Hours': hours,
								'PublicMemo': publicmemo,
								'Memo': memo
							}
						};
						if (covid) {
							data['event']['CovId'] = covid;
						}
						else {
							data['event']['CovEcomId'] = covecomid;
						}
						if (projectid) {
							data['event']['ProjectId'] = projectid;
						}
						if (subprojectid) {
							data['event']['SubProjectId'] = subprojectid;
						}

						$.ajax({
							data: data,
							type: 'POST',
							url: 'palkkatapahtumat/pikasyotto',
							dataType: 'json',
							success: function(data) {
								if (data.message == 'OK') {
									$this._trigger('eventAdded', null, {data: data.events});
								}
								else {
									var allowed = $this._trigger('validationFailed', null, {errors: data.errors});
									if (allowed !== false) {//Eventtiä ei ole käsitelty (ei palautettu falsea)
										$('<div />').validationerrordialog({
											validationErrors: data.errors
										});
									}
								}
							}
						});
					}
				}
			]
		});
		/*if ($(window).height() < 530) {
			this.option({
				height: 300,
				width: 950,
				position: ['left', 'top']
			});
		}*/
		this.element.addClass('salaryeventquickinput');
		this.datePickerContainer = $('<div />').css('float', 'left');//.attr('style', 'float: left;');
		this.datePickerContainer.append($('<h3 />').text('1. Päivämäärä'));
		this.datePicker = $('<div id="quickinputdatepicker" />').css('float', 'left').datepicker().appendTo(this.datePickerContainer);
		this.datePicker.find('.ui-datepicker-inline').css('display', 'block');
		//this.datePicker.find('.ui-datepicker-today').find('a.ui-state-highlight').removeClass('ui-state-highlight');
		this.salaryTypeSwitch = $('<a href="#">Näytä kaikki</a>').click(function() {
			if ($this.option('showOnlyDefaultSalarytypes')) {
				$this.populateSalaryTypes(true);
				$this.option('showOnlyDefaultSalarytypes', false);
				$(this).text('Näytä vain oletuspalkkalajit');
			}
			else {
				$this.populateSalaryTypes(false);
				$this.option('showOnlyDefaultSalarytypes', true);
				$(this).text('Näytä kaikki');
			}
			return false;
		});
		this.salaryTypes = $('<div />').attr({
			'style': 'margin-left: 20px; margin-right: 20px; float: left;'
		}).append($('<h3 />').text('2. Palkkalaji'))
			.append(this.salaryTypeSwitch)
			.append('<br />');
		this.salaryTypeSelect = $('<select />').attr({
			'id': 'fe-salarytypeid',
			'name': 'salarytypeid',
			'class': 'nodropdown',
			'size': 11,
			'style': 'width: 220px;'
		});
		this.salaryTypes.append(this.salaryTypeSelect);
		this.populateSalaryTypes(false);
		this.tabs = $('<div style="float: left; width: 410px;"><ul><li><a href="#covnote">Lähete</a></li><li><a href="#project">Projekti</a></li></ul></div>');
		this.coveringnotes = $('<div id="covnote" />').attr('style', 'float: left;').append('Lähetenumero<br />').appendTo(this.tabs);
		this.coveringnoteInput = $('<input class="hasbutton" type="text" size="23" />').appendTo(this.coveringnotes);
		
		var lastMonth = new Date();
		if (lastMonth.getMonth() > 0) {
			lastMonth.setMonth(lastMonth.getMonth() - 1);
		}
		else {
			lastMonth.setMonth(11);
			lastMonth.setFullYear(lastMonth.getFullYear() - 1);
		}
		this.coveringnoteSearch = $('<div />').coveringnotelist({
			autoOpen: false,
			filter: {
				webicovnotesonly: 0,
				ownonly: 0,
				covdate: {
					max: ec.formatDate(new Date()),
					min: ec.formatDate(lastMonth)
				}
			},
			covNoteClicked: function(event, data) {
				$this.covInfo.html('&#160;').addClass('ajax-loading');
				var covnote = new ec.webi.Coveringnote();
				covnote.url = 'lahetteet/;' + data.Id + '?disableLocks=1';
				covnote.fetch({
					success: function(model, response) {
						$this.setCovInfo(model.get('EcomId'), model.get('Location'), model.get('Mark'), model.get('ProjectId'), model.get('Project'), model.get('SubProjectId'), model.get('SubProject'));
					},
					error: function(mode, response) {
						$this.covInfo.removeClass('ajax-loading').html('Lähetteen tietoja ei löytynyt');
					}
				});
				var ecomId = data.EcomId || '(numeroimaton)';
				$this.coveringnoteInput.val(ecomId);
				$this.coveringnoteCovId = data.Id;
				$(this).coveringnotelist('close');
			}
		});
		this.coveringnoteSearchButton = $('<a class="inputbutton" href="#">Hae lähetettä</a>').button({
			text: false,
			icons: {
				primary: 'ui-icon-search'
			}
		}).click(function() {
			$this.coveringnoteSearch.coveringnotelist('open');
			return false;
		}).appendTo(this.coveringnotes).find('.ui-button-text').css({
			'padding': 0,
			'padding-bottom': '0.2em'
		});
		this.covInfo = $('<div />').attr({
			'id': 'covinfo',
			'style': 'margin-top: 10px;'
		}).append($('<p />').attr('class', 'italic').text('Anna lähetenumero tai käytä lähetehakua.')).appendTo(this.coveringnotes);

		this.projects = $('<div id="project" />').attr('style', 'float: left;').appendTo(this.tabs);
		if (this.options.allowProjectInput) {
			this.projects.append('Projektinumero<br />');
			this.projectSearch = $('<div />').projectsearch({
				autoOpen: false,
				projectSelected: function(event, data) {
					$this.projectInput.val(data.projectid);
					$this.subProjectInput.val(data.subprojectid || '');
					$this.projectSearch.projectsearch('close');
					return false;
				}
			});
			this.projectInput = $('<input class="hasbutton" type="text" size="23" />').appendTo(this.projects);
			this.projectSearchButton = $('<a class="inputbutton" href="#">Hae projektia</a>').button({
				text: false,
				icons: {
					primary: 'ui-icon-search'
				}
			}).click(function() {
				$this.projectSearch.projectsearch('open');
				$this.projectSearch.projectsearch('performEmptySearch');
				return false;
			}).appendTo(this.projects).find('.ui-button-text').css({
				'padding': 0,
				'padding-bottom': '0.2em'
			});
			this.projects.append('<br />Alaprojektinumero<br />');
			this.subProjectInput = $('<input class="hasbutton" type="text" size="23" />').appendTo(this.projects);
			this.subProjectSearchButton = $('<a class="inputbutton" href="#">Hae alaprojektia</a>').button({
				text: false,
				icons: {
					primary: 'ui-icon-search'
				}
			}).click(function() {
				$this.projectSearch.projectsearch('listSubProjects', $this.projectInput.val());
				$this.projectSearch.projectsearch('open');
				return false;
			}).appendTo(this.projects).find('.ui-button-text').css({
				'padding': 0,
				'padding-bottom': '0.2em'
			});
		}
		else {
			this.projects.append('<p>Sinulla ei ole oikeutta lisätä palkkatapahtumia projektille');
		}
		this.salaryEventInfo = $('<div />').css({
			'float': 'left',
			'clear': 'left',
			'padding': '4px',
			'margin-top': '-4px'
		}).attr('class', 'ui-corner-all')
			//.append($('<h3 />').text('Tiedot'))
			.append($('<div />').css({
				'float': 'left',
				'clear': 'both'
			})
			.append($('<label />')
					.css({
						'display': 'block',
						'float': 'left',
						'margin-right': '5px'
					})
					.append('Aloitus')
					.append($('<br />'))
					.append($('<input />').attr({
						'id': 'neweventstart',
						'class': 'validator_time timetrigger eventstart',
						'type': 'text',
						'size': 5
					}).ecTimeValidator())
				).append($('<label />')
					.css({
						'display': 'block',
						'float': 'left',
						'margin-right': '5px'
					})
					.append('Lopetus')
					.append($('<br />'))
					.append($('<input />').attr({
						'id': 'neweventend',
						'class': 'validator_time timetrigger eventend',
						'type': 'text',
						'size': 5
					}).ecTimeValidator())
				).append($('<label />')
					.css({
						'display': 'block',
						'float': 'left',
						'margin-right': '5px'
					})
					.append('Määrä')
					.append($('<br />'))
					.append($('<input />').attr({
						'id': 'neweventhours',
						'class': 'hours',
						'type': 'text',
						'size': 5
					}))
				).append($('<div />')
					.css({
						'float': 'left',
						'margin-right': '5px'
					})
					.append('Muistio (julkinen)')
					.append($('<br />'))
					.append($('<input />').attr({
						'class': 'publicmemo',
						'type': 'text',
						'size': 14,
						'value': this.options.publicMemoTemplate
					})).append($('<div />')
						.attr('class', 'memodialog')
						.append($('<textarea></textarea>').attr({
							'id': 'neweventpublicmemo',
							'class': 'noresizable',
							'cols': 1,
							'rows': 10
						}).text(this.options.publicMemoTemplate || ''))
					)
				).append($('<div />')
					.css({
						'float': 'left',
						'margin-right': '5px'
					})
					.append('Muistio (sisäinen)')
					.append($('<br />'))
					.append($('<input />').attr({
						'class': 'memo',
						'type': 'text',
						'size': 14,
						'value': this.options.privateMemoTemplate
					})).append($('<div />')
						.attr('class', 'memodialog')
						.append($('<textarea></textarea>').attr({
							'id': 'neweventmemo',
							'class': 'noresizable',
							'cols': 1,
							'rows': 10
						}).text(this.options.privateMemoTemplate || ''))
					)
				));
		this.salaryEventInfoClear = $('<div />').css({
			'float': 'right',
			'display': 'none',
			'clear': 'both',
			'text-align': 'right'
		}).append($('<a />').text('Tyhjennä kentät').button({
			icons: {
				primary: 'ui-icon-close'
			}
		}).click(function() {
			$this.salaryEventInfo.find('input,textarea').val('');
			return false;
		}));
		this.salaryEventInfo.prepend(this.salaryEventInfoClear).hover(
			function() {
				$this.salaryEventInfoClear.show();
				var marginTop = $this.salaryEventInfoClear.outerHeight() + 4;
				$(this).css({
					'background-color': '#ccc',
					'margin-top': '-' + marginTop + 'px'
				});
			},
			function() {
				$(this).css({
					'background-color': '',
					'margin-top': '-4px'
				});
				$this.salaryEventInfoClear.hide();
			}
		);

		this.element.append(this.datePickerContainer);
		this.element.append(this.salaryTypes);
		this.element.append('<h3>3. Lähete tai projekti</h3>');
		this.element.append(this.tabs.tabs({cookie: { expires: 365 } }));
		this.uiDialog.find('.ui-dialog-buttonpane').append(this.salaryEventInfo);

		this.coveringnoteInput.change(function() {
			$this.covInfo.html('&#160;');
			$this.coveringnoteCovId = null;
			if ($(this).val()) {
				$this.covInfo.addClass('ajax-loading');
				var covnote = new ec.webi.Coveringnote();
				covnote.url = 'lahetteet/' + $(this).val() + '?disableLocks=1';
				covnote.fetch({
					success: function(model, response) {
						$this.setCovInfo(model.get('EcomId'), model.get('Location'), model.get('Mark'), model.get('ProjectId'), model.get('Project'), model.get('SubProjectId'), model.get('SubProject'));
						$this.coveringnoteCovId = model.get('Id');
					},
					error: function(mode, response) {
						$this.covInfo.removeClass('ajax-loading').html('Lähetteen tietoja ei löytynyt');
						$this.coveringnoteCovId = null;
					}
				});
			}
		});
	},
	populateSalaryTypes: function(showAll) {
		var $this = this;
		var visibleCount = 0;
		this.salaryTypeSelect.empty();
		$.each(this.options.salarytypes, function(id, type) {
			if (type.IsDefault || showAll) {
				var option = $('<option />').attr('value', id).text(id + ' - ' + type.Name).data('item', type);
				$this.salaryTypeSelect.append(option);
				visibleCount++;
			}
		});
		if (visibleCount == 0) {
			this.salaryTypeSwitch.click();
		}
	},
	setCovInfo: function(ecomid, location, mark, projectid, project, subprojectid, subproject) {
		mark = mark || '(ei merkkiä)';
		location = location || '(ei kohdetta)';
		var projectText = projectid || '(ei projektia)';
		var subProjectText = subprojectid || '(ei alaprojektia)';
		if (project) {
			projectText += ' ' + project.Name;
		}
		if (subproject) {
			subProjectText += ' ' + subproject.Name;
		}
		this.covInfo.html('').removeClass('ajax-loading')
			.append($('<p />').text('Kohde: ' + location))
			.append($('<p />').text('Merkki: ' + mark))
			.append($('<p />').text('Projekti: ' + projectText))
			.append($('<p />').text('Alaprojekti: ' + subProjectText));
	},	
	_dialogOpen: $.ui.dialog.prototype.open,
	open: function() {
		this._dialogOpen();
		var maxHeight = 0;
		$.each([this.datePickerContainer, this.salaryTypes, this.coveringnotes], function(key, element) {
			if (element.height() > maxHeight) {
				maxHeight = element.outerHeight();
			}
		});

		this.datePickerContainer.height(maxHeight);
		this.salaryTypes.height(maxHeight);
		//this.tabs.height(maxHeight);

		//this.tabs.width(this.datePickerContainer.outerWidth(true) + this.salaryTypes.outerWidth(true));
		//this.coveringnotes.width(this.datePickerContainer.outerWidth(true));
	}
});
