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 !== null) ? download.AddCalls(true, sEmail) : download.AddCalls(false);
	},

	AddCalls : function(bPreRegistered, sEmail){
		//download buttons
		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(){
					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($("status",xml).text() == "2") return;
		if (xml == 'ok') { this.ShowDetails(); return; /* response returned no information */ }
		//sigh...
		var sEmail = this.sTempEmail; //$('div#register-download #email').val();
		$.cookie(this.sCookie, sEmail);
		this.TrackClick();
		/*var oFields = eval('({' + xml + '})');
		for (sField in oFields) {
			$('#' + sField.replace(/\_/g,'-')).val(oFields[sField]);
		}
		this.ShowDetails();*/
	},
	
	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': $('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) {
		window.location = download.oElement.sContinue;
	},
	
	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 = $('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();
	},

	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})(\]?)$/)
	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) { download.CheckEmail(); return false; }; });
		$('button#check-email').click(function(){ download.CheckEmail(); return false; });
		//$('button[value="ok"]').click(function() { download.SubmitForm(); 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; })
	}

}
