var MyEcobuild = {
	hideOtherField: function(name){
		return $('select[name="'+name+'"]')
				.nextAll('input[type=text]')
				.hide()
				.attr('disabled', true)
				.val('')
				.removeClass('required');
	},

	setOtherField: function(name, value){
		var field = this.showOtherField(name).val(value);
		$('select[name="'+field.attr('name')+'"] option[value=other]').attr('selected', 'selected');
	},

	showOtherField: function(name){
		return $('select[name="'+name+'"]')
			.nextAll('input[type=text]')
			.show()
			.removeAttr('disabled')
			.addClass('required');
	},

	groupRegistration: {

		confirmActions: false,

		removedVisitors: [],

		loadedVisitors: [],

		id: 1,

		node:'',

		show: function(){			
			$('.form-controls').after(this.node);

			this._initOtherFieldSelector($('.group-visitors select.other-available'));
		},

		hide: function(){
			var form = $('.group-visitor-form');
			this.node = form.clone();
			form.remove();
		},

		isHidden: function(){
			return $('.group-visitor-form:visible').length === 0;
		},

		incrementId: function(){
			return ++this.id;
		},

		addVisitor: function(){
			var id = this.incrementId();

			var clone = $('.group-visitors .group-visitor:last').clone(false);

			var element = $('<div class="group-visitor">' + (clone.get(0).innerHTML.replace(/registrations\[([a-z_]+)\]\[[0-9]+\]/g, 'registrations[$1]['+id+']')) + '</div>');

			element.find('input[type=text], select').val('').removeClass('invalid');
			element.find('small').remove();
			element.find('input[type=checkbox]').removeAttr('checked').removeAttr('disabled');
			// remove the hidden id field
			element.find('.remove-field input[type=hidden]').val('');

			$('.group-visitors').append(element);

			var other_field = element.find('select.other-available');

			this._initOtherFieldSelector(other_field);			

			MyEcobuild.hideOtherField(other_field.val('').attr('name'));
		},

		_initOtherFieldSelector: function (dropdown){
			dropdown.change(function(){
				$('option:selected', this).text().match(/^other$/i) !== null ? MyEcobuild.showOtherField($(this).attr('name')) : MyEcobuild.hideOtherField($(this).attr('name'));
			});
		},

		countVisitors: function(){
			return $('.group-visitors tr.group-visitor').length;
		},

		removeVisitor: function(node){
			if ( $('input[type=text]:blank', node).length < 3 && ! confirm('Are you sure you want to remove this visitor from your group booking?')){
				return;
			}

			var removed_id = $('input[type=hidden]', node).val();

			if (removed_id && removed_id.length){
				node.parents('form').append('<input type="hidden" name="deleted[]" value="' + removed_id + '" />');
			}		

			this.removeVisitorInput(node);
		},

		removeVisitorInput: function(node){
			if (node.siblings().length < 2){
				$('input[name=is_group][value=0]').click();
				// empty itself
				$('input', node).val('');
				return;
			}

			node.remove();	
		},
		
		isDirty: function(){
			var self = this;

			$(this.loadedVisitors).each(function(i, v){
				if ( ! $('.group-visitor.loaded.badge-' + v).length){					
					self.removedVisitors.push(v);
				}
			});

			return self.removedVisitors.length > 0;
		},

		/**
		 * Remove the ones that have been added but nor filled out
		 */
		removeEmpty: function(){
			var self = this;

			// remove the completely empty ones
			$('.group-visitor').each(function(){
				if ($(this).find('input[type=text]').length === $(this).find('input[type=text]:blank').length){					
					self.removeVisitorInput($(this));
				}
			});
		},
		
		showErrors: function(){
			$('.group-errors-container').fadeIn();
		},
		
		hideErrors: function(){
			$('.group-errors-container').fadeOut();
		},

		init: function(){
			var self = this;

			this.id = this.countVisitors() + 1;

			$('.my-ecobuild-registration .form-controls input').click(function(e){
				$(this).val() == 1 ? self.show() : self.hide();
			});

			$('.group-visitor-add').live('click', function(){
				self.addVisitor();
				return false;
			});

			$('.group-visitor-remove').live('click', function(){
				self.removeVisitor($(this).parents('.group-visitor'));
				return false;
			});		

			// get the loaded visitors if any
			$('.group-visitor.loaded').each(function(i, visitor){
				var badge = visitor.className.match(/badge-(\d+)/);
				
				if (badge.length > 1){
					self.loadedVisitors.push(badge[1]);
				}				
			});			

			// now set up the validation
			$('#myecobuild-registration-form').submit(function(){
				self.removeEmpty();				

				// check for dirty state
				if (self.isDirty() && self.confirmActions){
					if ( ! confirm('You are about to delete '+self.removedVisitors.length+' visitors from your group. Are you sure?')){
						return false;
					}
				}
			});

			// hide the actual form initially if we have no badges
			if (parseInt($('input[name=is_group]:checked').val()) !== 1) this.hide();
		}
	},

	registration: {
		countryUK: 260,
		_ukAddressShown: false,
		
		showOtherField: function(name){			
			return $('select[name='+name+']')
				.nextAll('input[type=text]')
				.show()
				.removeAttr('disabled')
				.addClass('required');
		},

		hideOtherField: function(name){
			return $('select[name='+name+']')
					.nextAll('input[type=text]')
					.hide()
					.attr('disabled', true)
					.val('')
					.removeClass('required');
		},

		setOtherField: function(name, value){
			var field = this.showOtherField(name).val(value);
			$('select[name='+field.attr('name')+'] option[value=other]').attr('selected', 'selected');
		},

		showUkAddress: function(){			
			var dropdown = $('#myecobuild-registration-form .uk-address').show();
			dropdown.find('select').attr('disabled', false);
			this._ukAddressShown = true;
		},

		hideUkAddress: function(){
			var ukAddress = $('#myecobuild-registration-form .uk-address').hide();
			if (this._ukAddressShown){
				ukAddress.find('option:selected').attr('selected', false);
			}
			ukAddress.find('select').attr('disabled', true);
		},

		showPrimaryActivityOptions: function(name){
			$('select[name=visitor_primary_activity_id]').each(function(){
				if ($(this).hasClass(name)){
					$(this).parents('.stacked-form').show();
					$(this).show()
						.removeAttr('disabled')
						.removeClass('disabled')
						.addClass('required');
				}else{
					$(this)
						.hide()
						.attr('disabled', true)
						.find('option:selected')
						.attr('selected', false)
						.removeClass('required');
				}
			});					

			this.hideOtherField('visitor_primary_activity_id');
		},

		disablePrimaryActivity: function(){
			$('select[name=visitor_primary_activity_id]').attr('disabled', true).parents('.stacked-form').hide();
		},
		
		init: function(){
			var self = this;

			self.hideUkAddress();

			// disable primary activity if there is no main business selected
			if ($('select[name=visitor_main_business_id] option:selected').val() === ''){
				self.disablePrimaryActivity();
			}

			$('select.other-available').change(function(){				
				$('option:selected', this).text().match(/^other$/i) !== null ? self.showOtherField($(this).attr('name')) : self.hideOtherField($(this).attr('name'));
			});

			$('select[name=visitor_main_business_id]').change(function(){
				if ($(this).val() === ''){
					self.disablePrimaryActivity();
					return;
				}

				self.showPrimaryActivityOptions($(this).val() === '1' ? 'construction' : 'non-construction');
			});

			$('select[name=visitor_country_id]').change(function(){			
				parseInt($(this).val()) === self.countryUK ? self.showUkAddress() : self.hideUkAddress();
			});

			$('#myecobuild-registration-form').validate({
				rules:{
					'username': {
						minlength: 4,
						maxlength: 127,
						required: true,
						email: true,
						remote: {
							url: baseurl + '/register/email-available',
							beforeSend: function(xhr){								
								$('#myecobuild-registration-form label[for=username]').parent().addClass('email-checking');
							},
							complete: function(xhr){
								if (xhr.responseText === 'false'){
									$('.email-exists').fadeIn();									
									$('html,body').animate({'scrollTop': $('.email-exists').offset().top - 20});
									
									$('.email-exists a').each(function(i, link){
										var field = $(link).attr('href').indexOf('password') === -1 ? 'username' : 'email';

										$(link).attr('href',
											$(link).attr('href') + '?' + field + '=' + $('#myecobuild-registration-form input[name=username]').val());
									});
								}else{
									$('.email-exists').fadeOut();
								}

								$('#myecobuild-registration-form label[for=username]').parent().removeClass('email-checking');
							}
						}
					},
					'password': {
						minlength: 5,
						maxlength: 42
					},
					'password_confirm': {
						equalTo: $('#myecobuild-registration-form input[name=password]')						
					}
				},

				messages: {
					'username':{
						remote: 'this email address is already in use'
					},
					'password_confirm':{
						equalTo: 'passwords do not match'
					}
				},
				errorElement: 'small',
				errorClass: 'invalid'
			});
		}
	}
}

$(function(){
	// add maxlen validators
	$([6,10,20,30,40,50,60]).each(function(i,v){
		$.validator.addClassRules("maxlen-"+v, {
			maxlength: v
		});
	});

	MyEcobuild.groupRegistration.init();

	MyEcobuild.registration.init();

	$('.print-badges').click(function(){
		window.open($(this).attr('href'), '', 'status=0,toolbar=0,scrollbars=1,location=0,width=750,height=1000');
		return false;
	});
});
