$(window).bind('load', function () {
	
	WidgetNewsletter = {
		
		url: '',
		form: null,
		popup: null,
		
		default_value: '',
		
		handleSubmit: function () {
			var inp = this.popup.content.find('input[type="text"]');
			if (inp.val() == this.default_value) {
				inp.val('');
			}
			
			$.post(this.form.attr('action'), this.form.serialize(), $.proxy(function (data) {
				if (data && data.res) {
					this.popup.content
						.find('div.subscribe-step-ok').removeClass('hidden')
						.next().addClass('hidden');
				} else if (data.errors) {
					var err = [];
					for(var i in data.errors) {
						err.push(data.errors[i]);
					}
					
					this.popup.content.find('div.error').html(err.join('<br />')).removeClass('hidden');
				}
				
				this.popup.syncUI();
				
			}, this), 'json');
			
			return false;
		},
		
		bindUI: function () {
			var inp = this.popup.content.find('input[type="text"]');
			var def = this.default_value = inp.val();
			
			inp.focus(function () {
				if ($(this).val() == def) $(this).val('');
			});
			
			this.form = this.popup.content.find('form');
			this.form.submit($.proxy(this.handleSubmit, this));
		},
		
		loadContent: function (url) {
			
			$.ajax({
				'url': url + (url.indexOf('?') != -1 ? '&' : '?') + 'ajax=1',
				'type': 'GET',
				'dataType': 'html',
				'success': $.proxy(function (data) {
					this.popup.content.html(data);
					this.bindUI();
					this.popup.syncUI();
				}, this)
			});
			
		},
		
		open: function () {
			if (!this.popup) {
				var position = 'left';
				if (this.newsletter_link.hasClass('position-top')) {
					position = 'bottom';
				}
				
				this.popup = new jQuery.Popup(null, {
					'constrain': this.newsletter_link,
					'position': position
				});
				
				this.popup.show();
				this.popup.content.html('<div class="loading"></div>');
				this.popup.syncUI();
				this.loadContent(this.newsletter_link.attr('href'));
			} else {
				
				this.popup.content
					.find('div.subscribe-step-ok').addClass('hidden')
					.next().removeClass('hidden');
					
				this.popup.content
					.find('div.error').addClass('hidden');
					
				this.popup.content
					.find('input[type="text"]').val(this.default_value);
			}
			
			this.popup.show();
		},
		
		init: function () {
			
			this.newsletter_link = $('a[rel="popup[newsletter]"]');
			this.newsletter_link.click($.proxy(function (evt) {
				try {
					this.open();
				} catch (e) {
					$.log.error(e);
				}
				return false;
			}, this));
		}
		
	};
	
	WidgetNewsletter.init();
	
});

var WidgetNewsletter = {};
