/* For any class='track_download' in the site */

$(document).ready(function() {
	$('.track_download').click(function(event) {
		event.preventDefault();
		Track_download.CheckForCookie();
	});
});

var Track_download = {
	sTempEmail: '',
	sURL: '/process-download.asp',
	sCookie: 'i2_user',
	oElement: {
		sContinue: '',
		sName: '',
		sLocation: ''
	},

	CheckForCookie: function() {
		var sEmail = $.cookie(this.sCookie);
		(sEmail !== undefined && sEmail !== null) ? Track_download.AddCalls(true, sEmail) : Track_download.AddCalls(false);
	},

	AddCalls: function(bPreRegistered, sEmail) {
		Track_download.AddCallsToForm();
		var aoDownloads = $('a.track_download');
		for (var i = 0; i < aoDownloads.length; i++) {
			var oDownload = aoDownloads[i];
			if (bPreRegistered) {
				//$('div#register-download #email').val(sEmail);
				Track_download.sTempEmail = sEmail;
				Track_download.oElement.sContinue = $(oDownload).attr('href');
				Track_download.oElement.sName = $(oDownload).attr('title');
				Track_download.oElement.sLocation = $(oDownload).attr('rel');
				Track_download.TrackClick();
			} else {
				Track_download.ShowForm(oDownload);
			}
		}
	},

	ShowForm: function(oDownload) {
		this.oElement = {
			sContinue: $(oDownload).attr('href'),
			sName: $(oDownload).attr('title'),
			sLocation: $(oDownload).attr('rel')
		}
		$('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) {
			Track_download.AutoFillOthers_Complete(oResponse);
		});
	},

	AutoFillOthers_Complete: function(xml) {
		if ($("status", xml).text() == "2") return;
		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();
			oFields[sKey] = sValue;
			asKeys[asKeys.length] = sKey
			asFields[asFields.length] = sValue;
		}
		$.post(this.sURL, {
			sFunction: 'ProcessAdditionalInformation',
			'sEmail': $('div#register-download #email').val(),
			'asKeys': asKeys.join('||'),
			'asFields': asFields.join('||'),
			sArguments: 'sEmail,asKeys,asFields'
		}, function(oResponse) {
			(oResponse == 'ok') ? Track_download.TrackClick() : Track_download.Error('There was a problem saving your information');
		});
	},

	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();
			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') ? Track_download.ContinueToDestination() : Track_download.Error('There was a problem saving your information');
		});
	},

	asFields: ['first-name', 'last-name', 'job-title', 'organisation', 'industry-sector', 'address', 'city', 'postcode', 'country', 'telephone', 'b_mailing', 'b_existing'],

	asOptionalFields: ['additional', 'b_brochure', 'b_callback', 'b_pricing'],

	ContinueToDestination: function(sEmail) {
		window.location = Track_download.oElement.sContinue;
	},

	TrackClick: function() {

		$.post(this.sURL, {
			sFunction: 'TrackClick',
			sEmail: this.sTempEmail,
			sLocation: this.oElement.sLocation,
			sItem: this.oElement.sName,
			sDestination: this.oElement.sContinue,
			sArguments: 'sEmail,sLocation,sItem,sDestination'
		}, function(sResponse) {
			try { Track_download.iClick = parseInt(sResponse); } catch (e) { }
			$('div#register-download').fadeIn('slow', function() { $('#step-1').hide(); })
			Track_download.ShowOptional();
		});
	},

	CheckEmail: function() {
		var sEmail = $('div#register-download #email').val();
		if (!this.bValidEmail(sEmail)) { Track_download.Error('Not a valid email'); return false; }
		this.sTempEmail = sEmail;
		$.post(this.sURL, {
			sFunction: 'iCheckEmail',
			'sEmail': sEmail,
			sArguments: 'sEmail'
		}, function(oResponse) {
			Track_download.AutoFillOthers(Track_download.sTempEmail);
		});
	},

	ShowDetails: function(bExisting) {
		this.HideError();
		$('#step-1').fadeOut('fast', function() {
			;
			$('#step-2').fadeIn('slow', function() {
				$('#' + Track_download.asFields[0]).focus();
			})
		});
	},

	ShowOptional: function(bExisting) {
		this.HideError();
		$('#step-2').fadeOut('fast', function() {
			;
			$('#step-3').fadeIn('slow', function() {
				$('#' + Track_download.asOptionalFields[0]).focus();
			})
		});
	},

	Error: function(sError) {
		$('.error').html(sError);
		if ($('.error:visible')) {
			$('.error').fadeIn();
		}
	},

	HideError: function() {
		$('.error').fadeOut();
	},

	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);
	},

	AddCallsToForm: function() {
		$('#email').keypress(function(oKey) { if (oKey.keyCode == 13) { Track_download.CheckEmail(); return false; }; });
		$('button#check-email').click(function() { Track_download.CheckEmail(); return false; });
		$('button#ok').click(function() { Track_download.SubmitForm(); return false; });
		$('button#ok_optional').click(function() { Track_download.SubmitOptional(); return false; });
		$('button[value="cancel"]').click(function() { Track_download.HideForm(); return false; })
	}

}



