var Newsletter = function (formIdSelector) {

	this.form = $(formIdSelector).get(0);
	if (this.form) {

		this.submitWindow = {};
		this.ajaxResponse = {};

		this.initAjaxSubmit();
		this.completeCsrf();
		
	}
};

Newsletter.PROMPT_LABEL_CLASS_SELECTOR = 'label.prompt-label';

Newsletter.prototype = {

	initAjaxSubmit: function () {

		var scope = this;
		this.form.onsubmit = function (e) {
			e = e || window.event;

			// devel note: if user has popup blocked, this script fail and user is redirected to result page
			scope.openResultWindow();
			scope.submitForm();

			if (e.preventDefault){
				e.preventDefault();
			};
			return false;
		};

	},

	openResultWindow: function () {

		// devel note: this script doesn't work in IETester but in regular IE 6+ do
		var scope = this;
		var width = window.screen.availWidth;
		var height = window.screen.availHeight;
		var route = document.getElementById('layout-popup-route').value;
		var options = {
			channelmode: 0,
			directories: 0,
			fullscreen: 0,
			'location': 0,
			menubar: 0,
			resizable: 0,
			scrollbars: 0,
			status: 0,
			titlebar: 0,
			toolbar: 0,
			width: + Math.round(width / 3),
			height: + Math.round(height / 3),
			left: + Math.round(width / 3),
			top: + Math.round(height / 3)
		};

		this.submitWindow = window.open(
			route,
			'_blank',
			(function(s){
				for (var o in options) {
					s += o + '	=' + options[o] + ',';
				};
				return s.substr(0, s.length - 1);
			})('')
		);

		this.submitWindow.onload = function () {
			scope.submitForm();
		}

	},

	submitForm: function () {

		var scope = this;
		var formAction = scope.form.getAttribute('action');
		var formMethod = scope.form.getAttribute('method');
		var formData = {
			ajax: true,
			newsletterEmailAddress: scope.form.newsletterEmailAddress.value,
			newsletterCsrf: scope.form.newsletterCsrf.value
		};

		$.ajax({
			url: formAction,
			type: formMethod.toUpperCase(),
			data:  formData,
			dataType: 'html',
			complete: function () {
				scope.processResponse.apply(scope, [].slice.apply(arguments));
			}
		});

	},

	processResponse: function (XMLHttpRequest, textStatus) {
		var bodyStyle = this.submitWindow.document.body.style;
		bodyStyle.background = '#fff';
		bodyStyle.margin = 0;
		this.submitWindow.document.getElementById('popup-content').innerHTML = XMLHttpRequest.responseText;
		this.submitWindow.redraw();
	},

	completeCsrf: function () {
		document.getElementById('newsletterCsrf').value = document.getElementById('newsletterCsrfValue').value;
	}

};
