
	/**
	 * Окно подписки
	 */
	var Subscribe = {
	
		popup:  null,
		fields: ['train', 'seq', 'direction', 'route'],
		
		/**
		 * 
		 */
		config: {
			qtip: {
				tip: {
					show: {delay: 0, when: {target: false, event: 'click'}},
					hide: {delay: 0, when: {target: false, event: 'click'}},
					style: {
						padding: 5,
						width: 246,
						background: '#E1EBBC',
						color: 'black',
						textAlign: 'center',
						border: {width: 1, radius: 0, color: '#818A5C'},
						tip: 'topRight'
					},
					position: {corner: {target: 'centerBottom', tooltip: 'rightTop'}}
				},
				error: {
					show: {delay: 0, when: {event: 'mouseover'}, effect: {type: 'fade', length: 0}},
					hide: 'mouseout',
					style: {
						padding: 5,
						background: '#FFDDDD',
						color: 'black',
						textAlign: 'center',
						border: {width: 1, radius: 0, color: '#818A5C'}
					},
					position: {corner: {target: 'topLeft', tooltip: 'bottomLeft'}, adjust: {y: -4, x: 0}}
				}
			}
		},
		
		/**
		 * Создаёт окно подписки и показывает его
		 */
		createWindow: function(parameters) {
			var self = this;
			this.removeWindow();
			
			this.popup = $(
				$.template(this.template, this.fields)
					.html(parameters)
			);
			
			this.popup.css(parameters.position);
		
			$('body').append(this.popup);
			
			this.popup.find('.tabs').tabs({
				show: function(event, ui) {
					var id = $(ui.panel).attr('id');
					self.toggleForm(id);
				}
			});
			
			this.popup.find('.close').click(function() {
				self.removeWindow();
				return false;
			});
			
			var help = this.popup.find('.help_button');
			help.qtip($.extend(this.config.qtip.tip, {
				api: {
					onShow: function() {
						$(document).bind('click.qtip', function() {
							help.qtip('hide');
							console.log('click.qtip');
							$(document).unbind('click.qtip');
						})
					}
				},
				content: 'Подписавшись на оповещение, Вы получите уведомление по E-mail или SMS сразу же, как только билеты поступят в продажу. <a href="http://www.mobiticket.ru/index.php?page=alerts" target="_blank">Подробнее о сервисе</a>'
			}));
			
			this.popup.find('input[name="date"]')
				.val(parameters.date)
				.datePickerMultiMonth({
					numMonths: 2,
					horizontalOffset: -200,
					verticalOffset: 20,
					showYearNavigation: false,
					startDate: (new Date()).asString(),
					endDate: (new Date()).addMonths(6).asString()
				});
			
			this.popup.find('form').ajaxForm({
				url: '/subscribe/create.php',
				type: 'post',
				dataType: 'json',
				success: function(response, status, form) {
					if ('errors' == response.status) {
						$(form).errors('options', self.config.qtip.error);
						$(form).errors('set', response.errors);
						return;
					}
					self.setSuccess();
				},
				error: function(xhr, status, form) {
					console.log(arguments);
				}
			});
			
			this.popup.show();
		},
		
		/**
		 * Переключает поля, специфичные для режима работы формы.
		 * Форма работает в двух режимах: подписка на поезд и подписка на направление. Каждый из режимов имеет специфичные для него поля.
		 * 
		 * @param String id
		 */
		toggleForm: function(id) {
			// Раздизаблим все поля, специфичные для закладок
			this.popup
				.find('fieldset input:disabled')
				.attr('disabled', null);
			
			// Задизаблим все поля, специфичные для закладок, не относящиеся к включенной закладке
			this.popup
				.find('fieldset:not(.' + id + ')')
					.find('input')
					.attr('disabled', true);
			
			this.popup
				.find('form input[name="type"]').val(id);
		},
		
		/**
		 * Показывает сообщение об успешной подписке
		 */
		setSuccess: function() {
			this.popup
				.find('.tabs, form')
				.hide();
			
			this.popup
				.find('.success')
				.show();
		},
		
		/**
		 * Удаляет окно подписки
		 */
		removeWindow: function() {
			if (this.popup) {
				this.popup.find('.help_button').qtip('destroy');
				$(document).unbind('click.qtip');
				this.popup.remove();
				this.popup = null;
			}
		},
		
		/**
		 * Шаблон окна
		 */
		template: [
			'<div class="subscribe">',
				'<h2>Сервис оповещений</h2>',
				
				 '<span class="help_button" href="#"></span>',
				 
				 '<a class="close close_button" href="#"></a>',
				
				'<div class="tabs">',
					'<ul>',
						'<li><a href="#train">Поезд {%= train %}, {%= direction.from.name %} &mdash; {%= direction.to.name %}</a></li>',
						'<li><a href="#direction">Любой поезд</a></li>',
					'</ul>',
					'<div id="train">',
						'<div class="content">',
							'<p class="train">Оповестить о наличии билетов<br/>из {%= route.from.name %} в {%= route.to.name %}</p>',
						'</div>',
					'</div>',
					'<div id="direction">',
						'<div class="content">',
							'<p class="direction">Оповестить о наличии билетов<br/>из {%= route.from.name %} в {%= route.to.name %}<br/>на любой поезд</p>',
						'</div>',
					'</div>',
				'</div>',
				
				'<form>',
					'<input name="type"      type="hidden">',
					'<input name="departure" type="hidden" value="{%= route.from.id %}">',
					'<input name="arrival"   type="hidden" value="{%= route.to.id %}">',
					
					'<label for="subscribe-date">Отправление:</label>',
					'<input name="date" class="date" id="subscribe-date">',

					'<select name="delta" id="subscribe-range">',
						'<option value="0">точная дата</option>',
						'<option value="1" selected>+1 день</option>',
						'<option value="2">+2 дня</option>',
						'<option value="3">+3 дня</option>',
					'</select>',
					
					'<label for="subscribe-email">Email:</label>',
					'<input name="email" class="email" id="subscribe-email">',
					
					'<label class="image" for="defence_email">',
						'<img src="/defence.php" class="defence">',
					'</label>',
					'<label class="defence" for="defence">Код на картинке:</label>',
					'<input class="defence" name="code" id="defence" type="text">',
					
					'<input type="submit" class="submit" value="Ок">',
					
					'<fieldset class="train hidden">',
						'<input name="train" type="hidden" value="{%= train %}">',
						'<input name="seq"   type="hidden" value="{%= seq %}">',
					'</fieldset>',
				'</form>',
				
				'<div class="success">',
					'<p>На указанный адрес отправлено письмо со ссылкой для подтверждения подписки.</p>',
				'</div>',
				
				'<a class="close close_link" href="#">закрыть</a>',
			'</div>'
		].join('')
	
	};
