(function ($) {
	
	$(function () {
		var initForm = function () {
			var hackContainer = $('#__hackContainer');
			if (! hackContainer.length) {
				hackContainer = $('<div />').attr('id', '__hackContainer').css('display', 'none').css('width', 'auto').appendTo(document.body);
			}
			var closeObserver = function(event) {
				hackContainer.remove();
				document.stopObserving('lightview:hidden', closeObserver);
			}
			document.observe('lightview:hidden', closeObserver);
			
			// remove defoult handler and bind a new one for`cancel` button
			$('#new-ticket input[type="button"][name="cancel"]').attr('onclick', '').click(function () {
				Lightview.hide();
			});
			
			// bind submit action for form
			$('#new-ticket form').submit(function () {
				Lightview.hideContent();
				Lightview.startLoading();
				$(this).ajaxSubmit(function (response) {
					hackContainer.html(response);
					Lightview.show({
						href: '#__hackContainer',
						options: {
							autosize: true,
							topclose: true
						}
					});
					initForm();
				});
				
				return false;
			});
		};
			
		$('a.new-ticket').click(function () {
			Lightview.show({
				href: this.href,
				rel: 'ajax',
				options: {
					autosize: true,
					topclose: true,
					ajax: {
						onComplete: function (transport) {
							initForm();
						}
					}
				}
			});
			return false;
		});
	
	});

})(jQuery);

