Webinar = {
	checkViewRecorded: function () {
		var matches = window.location.search.match(/rec=([^&]+)/);
		return matches && decodeURIComponent(matches[1]);
	},
	
	launchPresentation: function () {
		jQuery('#swf-recorded').click();
	}
}

jQuery(document).ready(function () {
	/*
		On form submit, send an ajax request
		to the same page with POST data
		to avoid page refresh.
	*/
	jQuery('form#form-register').submit(function (event) {
		// Change submit button with Please Wait image
		jQuery('[name=submit_data]').
			attr('src', '/images/webinars/webinar-button-wait-anim.gif').
			get(0).disabled = true;
		
		// Send AJAX request
		jQuery.ajax({
			data: function () {
				data = {};
				jQuery('#form-register :input').each(function () {
					j = jQuery(this);
					data[j.attr('name')] = j.val();
				});
				data['addanother'] = jQuery('#addanother').get(0).checked ? 1 : 0;
				return data;
			} (),
			dataType: 'json',
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				// Network or other type of serious error occured
				jQuery('.new-form-container-mid').removeClass('info').addClass('error');
				jQuery('.webinar-message-headline').hide().text('Error processing request!').fadeIn('slow');
				jQuery('.webinar-message-body').hide().text('If the problem persists, contact support.').fadeIn('slow');
			},
			success: function (data, textStatus) {
				if (data.valid && data.success) {
					// Everything OK
					jQuery('.new-form-container-mid').removeClass('error').addClass('info');
					jQuery('.webinar-message-headline').hide().text('Successfully registered!').fadeIn('slow');
					jQuery('.webinar-message-body').hide().text('Please check your email for confirmation.').fadeIn('slow');
					
					// Clear all the inputs
					jQuery('#form-register :input').not('[type=hidden]').each(function () {
						var j = jQuery(this);
						if (this.tagName.toLowerCase() == 'select') {
							j.val(-1);
						}
						else {
							j.val('');
						}
					});
					
					// If user wanted to add another participant also, re-populate the relevant fields
					// Parse options and re-group in an array
					var matches = this.data.match(/(\w)+=([^&]+)/g);
					var options = [];
					for (var i = 0; i < matches.length; i++) {
						var splits = matches[i].split('=');
						options[splits[0]] = decodeURIComponent(splits[1].replace('+', ' '));
					}
					
					if (options['addanother'] == '1') {
						var fields = ['company', 'country', 'city', 'captcha'];
						for (var i = 0; i < fields.length; i++) {
							jQuery('[name=' + fields[i] + ']').val(options[fields[i]]);
						}
						jQuery('#addanother').get(0).checked = false;
						jQuery('[name=fullname]').focus();
					}
					else {
						// Form is emptied. Re-generate captcha.
						jQuery('#captcha-img').attr('src', '/mail-server/captcha.php?r=' + Date.now());
						jQuery('[name=company]').focus();
					
						// If a USA state was selected, assure the State Select will be hidden now
						if (options['state'] != '-1') {
							jQuery('[name=state]').parent().hide();
						}
					}
				}
				else if (!data.valid) {
					// Form data was invalid
					jQuery('.new-form-container-mid').removeClass('info').addClass('error');
					jQuery('.webinar-message-headline').hide().text('Submitted data is invalid!').fadeIn('slow');
					jQuery('.webinar-message-body').hide().text('Please fill in all mandatory fields.').fadeIn('slow');
					
					// Highlight invalid fields
					for (var i = 0; i < data.errors.length; i++) {
						input = jQuery('[name=' + data.errors[i] + ']');
						if (!input.hasClass('error')) {
							input.addClass('error');
							if (input.get(0).tagName.toLowerCase() == 'input') {
								input.val('Please fill in');
							}
							if (input.attr('name') == 'captcha') {
								input.val('Invalid code');
							}
						}
					}
				}
				else {
					// DB save or mail sending failed
					jQuery('.new-form-container-mid').removeClass('info').addClass('error');
					jQuery('.webinar-message-headline').hide().text('Error processing request!').fadeIn('slow');
					jQuery('.webinar-message-body').hide().text('If the problem persists, contact support.').fadeIn('slow');
				}
			},
			complete: function (xhr, textStatus) {
				// Re-display the Submit Data button after Please Wait was shown
				// during AJAX request
				var gif = jQuery('[name=addanother]').get(0).checked ?
					'/images/webinars/webinar-button-continue.gif' :
					'/images/webinars/webinar-button-submit.gif';
				jQuery('[name=submit_data]')
					.attr('src',gif)
					.get(0).disabled = false;				
			},
			type: 'POST',
			url: window.location.pathname
		});
		
		event.preventDefault();
	});

	/*
		onClick on form inputs (selects, text etc.)
		removes the error class so that fields are editable after
		highlighted if invalid
	*/
	jQuery('#form-register :input').bind('click focus', function (event) {
		var j = jQuery(this);
		if (!j.hasClass('error')) return;
		
		if (j.get(0).tagName.toLowerCase() == 'input') {
			j.val('');
		}
		j.removeClass('error');
	});
	
	/*
		Country select onChange. Hide/Show State select field
		if USA is selected/unselected.
	*/
	jQuery('[name=country]').change(function () {
		if (jQuery(this).val() == 222) {
			jQuery('[name=state]').parent().show();
		}
		else {
			jQuery('[name=state]').val(-1).parent().hide();
		}
	});
	
	/*
		OnClick on Add Another Participant
		The submit image changes to Continue if this is the case,
		or changes back to Submit Data when unchecked
	*/
	jQuery('#addanother').click(function (event) {
		if (this.checked) {
			jQuery('[name=submit_data]').attr('src', '/images/webinars/webinar-button-continue.gif');
		}
		else {
			jQuery('[name=submit_data]').attr('src', '/images/webinars/webinar-button-submit.gif');
		}
	});

	/*
		Check for view recorded request (rec={hash} GET parameter present)
		If it is a correct request, make a JSON AJAX request to check for the validity
		of the hash, and if it is ok, launch the video overlay.
	*/
	// First, set up prettyPhoto overlay once per page request
	var jrecorded = jQuery('#swf-recorded');
	if (jrecorded.length) {
		jrecorded.prettyPhoto({showTitle: true, theme: 'dark_rounded'});
	}
	
	var rec_hash = Webinar.checkViewRecorded()
	if (rec_hash) {
		jQuery.getJSON(
			window.location.pathname,
			{'view-recorded': rec_hash},
			function (data, textStatus) {
				if (data.valid) {
					Webinar.launchPresentation();
				}
			}
		);
	}
	
	// When a launch presentation button is present on the page, assign handler to it
	var jbutton = jQuery('#launch-presentation');
	if (jbutton.length) {
		jbutton.click(Webinar.launchPresentation);
	}
});