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(sReturn) {
		var oReturn = jQuery.parseJSON(sReturn);
		$('select#country').removeAttr('selected');
		$('select#country option[value="' + oReturn['country'] + '"]').attr('selected', 'selected');
		$('select#salutation').removeAttr('selected');
		$('select#salutation option[value="' + oReturn['salutation'] + '"]').attr('selected', 'selected');
		$('input#first-name').val(oReturn['first-name'])
		$('input#last-name').val(oReturn['last-name'])
		$('input#job-title').val(oReturn['job-title'])
		$('input#organisation').val(oReturn['organisation'])
		$('input#telephone').val(oReturn['telephone'])
		$('select#industry-sector').removeAttr('selected');
		$('select#industry-sector option[value="' + oReturn['industry-sector'] + '"]').attr('selected', 'selected');
		$('input#address').val(oReturn['address'])
		$('input#mailpoint').val(oReturn['mailpoint'])
		$('input#city').val(oReturn['city'])
		$('input#state').val(oReturn['state'])
		$('input#postcode').val(oReturn['postcode'])
		$('input#b_mailing').attr('checked', oReturn['b_mailing'])
		$('input#b_existing').attr('checked', oReturn['b_existing'])
		$('input#b_contact-by-email').attr('checked', oReturn['b_contact-by-email'])
		$('input#b_contact-by-phone').attr('checked', oReturn['b_contact-by-phone'])
		$('input#b_contact-by-mail').attr('checked', oReturn['b_contact-by-mail'])
		this.ShowDetails();

		var country = oReturn['country'];
		WebFormTricks.MakeTelePhoneRequired(country);
		WebFormTricks.MakeSalutationRequired(country);
		WebFormTricks.MakeFirstNameRequired(country);
		WebFormTricks.MakeStateRequired(country);
		WebFormTricks.MakePostCodeNotReq(country);

		//Irrespective of User Registration status we are displaying the form update ie step2 to update the user profile.

		//var sEmail = download.sTempEmail;
		//$.cookie(download.sCookie, sEmail, { expires: 1 });
		//download.TrackClick();
	},

	SubmitForm: function() {
		var bOk = true;
		while (bOk == true) { $('.mandatory').each(function(i, o) { if ($(o).val() == '') { $(o).addClass('invalid'); 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': $.trim($('div#register-download #email').val()),
			'asKeys': asKeys.join('||'),
			'asFields': asFields.join('||'),
			sArguments: 'sEmail,asKeys,asFields'
		}, function(oResponse) {
			(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();
			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) {
			if (oResponse == 'ok') {
				download.ContinueToDestination()
			}
			else {
				download.Error('There was a problem saving your information');
			}
		});
	},

	asFields: ['salutation', 'first-name', 'last-name', 'job-title', 'organisation', 'telephone', 'address', 'industry-sector', 'mailpoint', 'city', 'state', 'country', 'postcode', 'b_mailing', 'b_existing', 'b_contact-by-email', 'b_contact-by-mail', 'b_contact-by-phone'],

	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; }
		download.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);
	}

}



/* Setting Mandatory and Not Mandatory for the Download Forms*/

WebFormTricks = {
	TelephonePhoneReq: ['Afghanistan', 'Australia', 'Brunei Darussalam', 'Burma', 'Cambodia', 'China', 'Fiji', 'Hong Kong', 'India', 'Indonesia', 'Japan', 'Korea, Republic of', 'Lao People\'s Deocratic Republic', 'Macau', 'Malaysia', 'Maldives', 'Nepal', 'New Zealand', 'Norfolk Island', 'Papua New Guinea', 'Philippines', 'Singapore', 'Sri Lanka', 'Taiwan, Province of China', 'Thailand', 'Vietnam'],
	SalutationReq: ['Austria', 'Belgium', 'France', 'Germany', 'Gibraltar', 'Ireland', 'Luxembourg', 'Monaco', 'Netherlands', 'United Kingdom'],
	FirstNameReq: ['Andorra', 'Austria', 'Belgium', 'Denmark', 'Faroe Islands', 'Finland', 'France', 'Iceland', 'Luxembourg', 'Macedonia', 'Monaco', 'Netherlands', 'Norway', 'Portugal', 'Spain', 'Swaziland', 'Sweden', 'Vatican City State'],
	StateReq: ['Australia', 'Canada', 'Iran (Islamic Republic Of)', 'Italy', 'Mexico', 'New Zealand', 'Taiwan, Province of China', 'United States of America'],
	NoPostCode: ['Afghanistan', 'Angola', 'Antigua And Barbuda', 'Aruba', 'Bahamas', 'Belize', 'Benin', 'Botswana', 'Bulgaria', 'Burkina Faso', 'Cameroon', 'Congo', 'Cote d\'Ivoire', 'Dominica', 'Equatorial Guinea', 'Fiji', 'Gambia', 'Ghana', 'Gibraltar', 'Guyana', 'Hong Kong', 'Jamaica', 'Macau', 'Madagascar', 'Malawi', 'Mali', 'Mauritania', 'Mauritius', 'Namibia', 'Netherland Antilles', 'Netherlands Antilles', 'Niger', 'Qatar', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Sierra Leone', 'Suriname', 'Syria', 'Tanzania', 'Trinidad and Tobago', 'Uganda', 'United Arab Emirates', 'United Republic of Tanzania', 'Yemen', 'Zimbabwe'],

	MakeTelePhoneRequired: function(country) {
		var o = $('input#telephone')
		$(o).parent().find('span.req').remove()
		o.removeClass('mandatory')
		if (WebFormTricks.TelephonePhoneReq.join(',').indexOf(country) > -1) {
			o.addClass('mandatory')
			o.after('<span class="req">*</span>')
		}
	},
	MakeSalutationRequired: function(country) {
		var o = $('select#salutation')
		$(o).parent().find('span.req').remove()
		o.removeClass('mandatory')
		if (WebFormTricks.SalutationReq.join(',').indexOf(country) > -1) {
			o.addClass('mandatory')
			o.after('<span class="req">*</span>')
		}
	},
	MakeFirstNameRequired: function(country) {
		var o = $('input#first-name')
		$(o).parent().find('span.req').remove()
		o.removeClass('mandatory')
		if (WebFormTricks.FirstNameReq.join(',').indexOf(country) > -1) {
			o.addClass('mandatory')
			o.after('<span class="req">*</span>')
		}
	},
	MakeStateRequired: function(country) {
		var o = $('input#state')
		$(o).parent().find('span.req').remove()
		o.removeClass('mandatory')
		if (WebFormTricks.StateReq.join(',').indexOf(country) > -1) {
			o.addClass('mandatory')
			o.after('<span class="req">*</span>')
		}
	},
	MakePostCodeNotReq: function(country) {
		var o = $('input#postcode')
		if (WebFormTricks.StateReq.join(',').indexOf(country) > -1) {
			$(o).parent().find('span.req').remove()
			o.removeClass('mandatory')
		}

	}
}


$(document).ready(function() {
	$('select#country').change(function() {
		var country = $("option:selected", this).val()
		WebFormTricks.MakeTelePhoneRequired(country);
		WebFormTricks.MakeSalutationRequired(country);
		WebFormTricks.MakeFirstNameRequired(country);
		WebFormTricks.MakeStateRequired(country);
		WebFormTricks.MakePostCodeNotReq(country);
	});

});
