var download = {
	sTempEmail: '',
	sURL: '/process-download.asp',
	sCookie: 'i2_user',
	sLocation: '',
	oElement: {
		sContinue: '',
		sName: ''
	},

	CheckForCookie: function(sLocation) {
		this.sLocation = sLocation === undefined ? '' : sLocation;
		var sEmail = $.cookie(this.sCookie);
		sEmail = undefined;
		(sEmail !== undefined && sEmail !== null) ? download.AddCalls(true, sEmail) : download.AddCalls(false);
	},

	AddCalls: function(bPreRegistered, sEmail) {
		download.AddCallsToForm();
		var aoIR = $('#quicklinks a[href$="/information-request"]');
		$(aoIR).each(function(i, o) { $(o).attr('title', 'Information Request'); $(o).addClass('download'); })
		$('#quicklinks a.more').each(function(i, o) { $(o).addClass('download'); })
		var aoDownloads = $('a.download');
		for (var i = 0; i < aoDownloads.length; i++) {
			var oDownload = aoDownloads[i];
			if (bPreRegistered && $(oDownload).attr('title') != 'Information Request') {
				$('div#register-download #email').val(sEmail);
				download.sTempEmail = sEmail;
				$(oDownload).click(function(e) {
					e.preventDefault();
					download.oElement.sContinue = $(this).attr('href');
					download.oElement.sName = $(this).attr('title');
					download.TrackClick();
					return false;
				});
				$(oDownload).rightClick(function() { $(this).click(); return false; })
			} else {
				$(oDownload).click(function() { download.ShowForm(this); return false; });
				$(oDownload).rightClick(function() { download.ShowForm(this); return false; });
			}
		}
	},

	ShowForm: function(oDownload) {
		this.oElement = {
			sContinue: $(oDownload).attr('href'),
			sName: $(oDownload).attr('title')
		}
		$('div#register-download').fadeIn('slow', function() { $('input#email').focus() })
	},

	HideForm: function() {
		$('div#register-download').fadeOut('slow')
	},

	AutoFillOthers: function(sEmail) {
		$.post(this.sURL, {
			sFunction: 'GetAdditionalInformationFromEmail',
			'sEmail': sEmail,
			sArguments: 'sEmail'
		}, function(oResponse) {
			download.AutoFillOthers_Complete(oResponse);
		});
	},

	AutoFillOthers_Complete: function(xml) {
		if (xml == 'ok') { this.ShowDetails(); return; }
		var sEmail = this.sTempEmail;
		$.cookie(this.sCookie, sEmail);
		this.TrackClick();

	},

	SubmitForm: function() {
		var bOk = true;
		while (bOk == true) { $('.mandatory').each(function(i, o) { if ($(o).val() == '') { bOk = false; } }); break; };
		if (bOk == false) { this.Error('Please complete all required fields before submitting'); return false; }

		var oFields = {}
		var asFields = [];
		var asKeys = [];
		for (var i = 0; i < this.asFields.length; i++) {
			var sKey = this.asFields[i];
			var sValue = (sKey.indexOf('b_') == 0) ? $('#' + this.asFields[i]).is(':checked') : $('#' + this.asFields[i]).val();
			/*var sValue = $('#' + this.asFields[i]).val();*/
			oFields[sKey] = sValue;
			asKeys[asKeys.length] = sKey
			asFields[asFields.length] = sValue;
		}
		$.post(this.sURL, {
			sFunction: 'ProcessAdditionalInformation',
			'sEmail': $.trim($('div#register-download #email').val()),
			'asKeys': asKeys.join('||'),
			'asFields': asFields.join('||'),
			sArguments: 'sEmail,asKeys,asFields'
		}, function(oResponse) {
			//(oResponse == 'ok') ? download.ContinueToDestination(download.sTempEmail) : download.Error('There was a problem saving your information');
			(oResponse == 'ok') ? download.TrackClick() : download.Error('There was a problem saving your information');
		});
	},

	/* I should really consolidate these */

	SubmitOptional: function() {
		var oFields = {}
		var asFields = [];
		var asKeys = [];
		for (var i = 0; i < this.asOptionalFields.length; i++) {
			var sKey = this.asOptionalFields[i];
			var sValue = (sKey.indexOf('b_') == 0) ? $('#' + this.asOptionalFields[i]).is(':checked') : $('#' + this.asOptionalFields[i]).val();
			/*var sValue = $('#' + this.asFields[i]).val();*/
			oFields[sKey] = sValue;
			asKeys[asKeys.length] = sKey
			asFields[asFields.length] = sValue;
		}
		$.post(this.sURL, {
			sFunction: 'ProcessOptionalInformation',
			'sEmail': $('div#register-download #email').val(),
			'asKeys': asKeys.join('||'),
			'asFields': asFields.join('||'),
			'iClick': this.iClick,
			sArguments: 'sEmail,asKeys,asFields,iClick'
		}, function(oResponse) {
			(oResponse == 'ok') ? download.ContinueToDestination() : download.Error('There was a problem saving your information');
		});
	},

	asFields: ['first-name', 'last-name', 'job-title', 'organisation', 'telephone', 'address', 'industry-sector', 'city', 'country', 'postcode', 'b_mailing', 'b_existing'],

	asOptionalFields: ['additional', 'b_brochure', 'b_callback', 'b_pricing'],

	osOptionalTriggers: { 'Information request': true, 'Information Request': true },

	ContinueToDestination: function(sEmail) {
		if (download.oElement.sContinue.search(/.*(mp4|flv|swf|jpg|gif|pdf|doc|docx|xls|xlsx|ppt|pps|pptx|rtf)$/g) == -1) {
			window.location = download.oElement.sContinue
		} else if (download.oElement.sContinue.search(/.*(mp4|flv|swf|jpg|gif)$/g) != -1) {
			this.HideForm();
			$.prettyPhoto.open(download.oElement.sContinue, download.oElement.sName, '');
		} else {
			var viewer = null;
			viewer = window.open(download.oElement.sContinue);
			if (viewer == null) { window.location = download.oElement.sContinue } // if Pop Up is disabled then we open in same window else in new tab
			this.HideForm();
		}
	},

	TrackClick: function() {
		$.post(this.sURL, {
			sFunction: 'TrackClick',
			sEmail: this.sTempEmail,
			sLocation: this.sLocation,
			sItem: this.oElement.sName,
			sDestination: this.oElement.sContinue,
			sArguments: 'sEmail,sLocation,sItem,sDestination'
		}, function(sResponse) {
			if (download.osOptionalTriggers[download.oElement.sName]) {
				try { download.iClick = parseInt(sResponse); } catch (e) { }
				$('div#register-download').fadeIn('slow', function() { $('#step-1').hide(); })
				download.ShowOptional();
			} else {
				download.ContinueToDestination();
			}
		});
	},

	CheckEmail: function() {
		var sEmail = $.trim($('div#register-download #email').val());
		if (!this.bValidEmail(sEmail)) { download.Error('Not a valid email'); return false; }
		this.sTempEmail = sEmail;
		$.post(this.sURL, {
			sFunction: 'iCheckEmail',
			'sEmail': sEmail,
			sArguments: 'sEmail'
		}, function(oResponse) {
			download.AutoFillOthers(download.sTempEmail);
		});
	},

	ShowDetails: function(bExisting) {
		this.HideError();
		$('#step-1').fadeOut('fast', function() {
			;
			$('#step-2').fadeIn('slow', function() {
				$('#' + download.asFields[0]).focus();
			})
		});
	},

	ShowOptional: function(bExisting) {
		this.HideError();
		$('#step-2').fadeOut('fast', function() {
			;
			$('#step-3').fadeIn('slow', function() {
				$('#' + download.asOptionalFields[0]).focus();
			})
		});
	},

	Error: function(sError) {
		$('.error').html(sError);
		if ($('.error:visible')) {
			$('.error').fadeIn();
		}
	},

	HideError: function() {
		$('.error').fadeOut();
	},

	AddCallsToForm: function() {
		$('#email').keypress(function(oKey) { if (oKey.keyCode == 13) { download.CheckEmail(); return false; }; });
		$('button#check-email').click(function() { download.CheckEmail(); return false; });
		$('button#ok').click(function() { download.SubmitForm(); return false; }); // angry
		$('button#ok_optional').click(function() { download.SubmitOptional(); return false; }); // angry
		$('button[value="cancel"]').click(function() { download.HideForm(); return false; })
	},

	bValidEmail: function(sEmail) {
		var sMatch = sEmail.match(/^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)
		return (sMatch !== null);
	}

}

