//             PROGRESSIVE REGISTRATION

if (!Chem){ var Chem = {}; }

if(typeof logc !== 'function'){
	function logc(inp){
		if (window.console){ console.log(inp); }
		return inp;
	}
}

Chem.ProgReg = (function(){
	var instance = null;
	return function(options){
		if (instance !== null){ return instance; }

		var options = $.extend({
			seq: [1, 2, 3, 4, 5, 6]
		}, options || {}),
		cnst = new Chem.Const(options),
		data = new Chem.Data({
			currentStep: 0,
			formIsComplete: false,
			emailIsComplete: false
		});

		this.form = $('.progreg').addClass('js');
		this.getData = $.proxy(data.getData, data);
		this.setData = function(key, val){
			data.setData(key, val);
			return this;
		};
		this.getConst = $.proxy(cnst.getConst, cnst);

		this.init();

		instance = this;
	}
})();

Chem.ProgReg.prototype = {
	setPanels: function(){
		var seq = this.getConst('seq'),
		$all = this.form.find('div.panel').hide(),
		$panels = $all.not('div.complete'),
		$completed = $panels.filter('div.complete').find('.specified').attr('value', 'True').end();

		return this.setData('all', $all).setData('panels', $panels).setData('completed', $completed).activatePanel();
	},
	bindEvents: function(){
		this.form.bind({
			showNext: $.proxy(this.showNext, this),
			submitForm: $.proxy(this.submit, this)
		}).find('.continue').click($.proxy(this.click, this));
	},
	activatePanel: function(){
		var d = this.getData(),
		seq = this.getConst('seq');

		for(i=0; i<seq.length; i++){
			var $a = d.all.eq(seq[i]-1);
			if (!$a.hasClass('complete')){
				$a.show();
				this.setData('currentStep', i);
				break;
			}
		}
        if (0 !== d.currentStep) { $("p.submit .signin").css("visibility", "hidden"); } /* seems weird but this effectively "hides" the sign in info while keeping the line-height in the span so the continue button doesn't move */
		return this;
	},
	showNext: function(){
//		this.submitForm();
//		return;

		var d = this.getData(),
		seq = this.getConst('seq'),
		num = this.getData('currentStep');

		d.all.eq(seq[num]-1).addClass('complete').find('.specified').attr('value', 'True');
/*
		d.all.eq(seq[num]-1).log().addClass('complete');
		$.each(rules, function(key, dat){
			var $el = $('#' + key);
			if ($el.attr('value').length != 0){
				$el.parents('div.panel:first').find('.specified').attr('value', 'True');
			}
		});
		if (!seq[num+1]){ this.submitForm(); return; }
*/
		if (!seq[num+1] || ($('#Email').attr('value').length != 0 && !$('#Email').parents('.step:first').hasClass('complete'))){ this.submitForm(); return; }
		d.all.hide();
		this.activatePanel();
	},
	click: function(){
		this.form.trigger('ValidateForm');
		return false;
	},
	submitForm: function(){
		this.buildDOB().form.trigger('submit');
	},
	buildDOB: function(){
		if (!$('#BirthMonth').attr('value').match(/^\d{1,2}$/) || !$('#BirthDay').attr('value').match(/^\d{1,2}$/) || !$('#BirthYear').attr('value').match(/^\d{4}$/)){ return this; }
		var d = $('#BirthMonth').attr('value') + '/' + $('#BirthDay').attr('value') + '/' + $('#BirthYear').attr('value');
		$('#UserAnswers_DateOfBirth').attr('value', d);
		return this;
	},
	init: function(){
		this.setPanels().bindEvents();
	}
};

Chem.FormValidator = (function(){
	return function(element, rules){
		var options = {
			rules: rules || {}
		},
		data = new Chem.Data(),
		cnst = new Chem.Const(options);

		this.form = element;
		this.getData = $.proxy(data.getData, data);
		this.getConst = $.proxy(cnst.getConst, cnst);

		this.setData = function(key, val){
			data.setData(key, val);
		};

		this.init();
	}
})();

Chem.FormValidator.prototype = {
	validate: function(){
		var f = this.form, c = this.getConst();
//		f.trigger('showNext');//	Temporarily disabling validation
//		return;
		$.each(c.rules, function(key, dat){
			var $el = $('#'+key), val = $el.attr('value'),
			$er = $('p.' + key + 'Error'), message = '', action = 'enter';

			if (!$el.parents('.panel').is(':visible')){ return; }
			if (val.length == 0){
				message = dat.name + ' is required';
			}
			else if (Chem.isSet(dat.minLength) && val.length < dat.minLength){
				message = dat.name + ' should contain a minimum of ' + dat.minLength + ' characters';
			}
			else if (Chem.isSet(dat.maxLength) && val.length > dat.maxLength){
				message = dat.name + ' can contain a maximum of ' + dat.maxLength + ' characters';
			}
			else if (Chem.isSet(dat.exp) && !val.match(dat.exp)){
				if ($el.is('select')){ action = 'select'; }
				message = 'Please ' + action + ' a valid ' + dat.name.toLowerCase();
			}
			if (message.length != 0){
				$er.show().html(message);
				$el.parent().addClass('validation-error');
			}
		});
		if (f.find('.validation-error-message:visible').length == 0){ f.trigger('showNext'); }
	},
	showError: function(){
		this.form.find('.validation-error-message').each(function(){
			if ($(this).text().length != 0){
				$(this).show();
			}
		});
		return this;
	},
	resetError: function(e){
		$(e.target).parents('div.panel:first')
			.find('.validation-error-message').hide().end()
			.find('.validation-error').removeClass('validation-error');
	},
	init: function(){
		var f = this.showError().form, c = this.getConst(),
		ev = f.bind({
			ResetError: $.proxy(this.resetError, this),
			ValidateForm: $.proxy(this.validate, this)
		});
		$.each(c.rules, function(key, dat){
			$('#' + key).focus(function(){
				$(this).trigger('ResetError');
			});
		});
		f.find('.dk_container').click(function(){
			$(this).trigger('ResetError');
		});
	}
};

Chem.CityMenu = (function(){
	var instance = null;
	return function(options){
		if (instance != null){ return instance; }
		var data = new Chem.Data();

		this.zip = $('#PostalCode');
		if (this.zip.length == 0){ return; }

		this.getData = $.proxy(data.getData, data);
		this.setData = function(key, val){
			data.setData(key, val);
			return this;
		};

		this.init();
		instance = this;
	}
})();

Chem.CityMenu.prototype = {
	getList: function(){
		var $city = $('#citycode').trigger('ResetError');
		if (this.zip.attr('value').length < 5){
			$city.hide().find('select').remove();
			return;
		}
		$.ajax({
			type: 'GET',
			success: $.proxy(this.buildMenu, this),
			data: { PostalCode: this.zip.attr('value') },
			url: Chem.BuildUrl('ProgRegForm', 'GetCityList')
		});
	},
	buildMenu: function(data){
		var $city = $('#citycode').hide().find('select').remove().end(),
		id = this.zip.attr('id'), $error = $('p.' + id + 'Error');
		if (data.length == 0){
			this.zip.parent().addClass('validation-error');
			$error.show().text('Please enter a valid Zip/Postal code');
			return this;
		}
		var opt = '<select id="citycodelist" name="UserAnswers.CityCode">';
		$.each(data, function(key, dat){
			opt += '<option value="' + dat.CityCode + '">' + dat.Name + '</option>';
		});
		opt += '</select>';
		$city.find('p').append(opt);
		if (data.length > 1){
			$city.show();
		}
		return this;
	},
	validate: function(){
		var $lst = $('#citycodelist');
		if ($lst.length == 0){ return; }
	},
	init: function(){
		if ($('#UserAnswers_CityCode').attr('value').length != 0){ return; }
		else { $('#UserAnswers_CityCode').remove(); }
		if (this.zip.attr('value').length != 0){
			this.getList();
		}
		this.zip.bind('keyup blur', $.proxy(this.getList, this));
		return this;
	}
};

$(function(){
	try {
		$('select').not('[multiple]').dropkick();
		new Chem.CityMenu();
		new Chem.FormValidator($('form.progreg'), {
			GenderSeek: {
				exp: /^[a-z ]+$/ig,
				name: 'GenderSeek'
			},
			PostalCode: {
				exp: /^[a-z0-9][a-z0-9 ]{3,}[a-z0-9]$/ig,
				minLength: 5,
				maxLength: 10,
				name: 'ZipCode'
			},
			FirstName: {
				exp: /^[a-z\'\- ]+$/ig,
				minLength: 1,
				maxLength: 20,
				name: 'First name'
			},
			Email: {
				exp: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ig,
				minLength: 5,
				maxLength: 200,
				name: 'Email'
			},
			Password: {
				exp: /^[a-z0-9]+$/ig,
				minLength: 5,
				maxLength: 200,
				name: 'Password'
			},
			BirthDay: {
				exp: /^\d{1,2}$/,
				name: 'Birth day'
			},
			BirthYear: {
				exp: /^\d{4}$/,
				name: 'Birth year'
			},
			BirthMonth: {
				exp: /^\d{1,2}$/,
				name: 'Birth month'
			}
		});
	}
	catch(error){ logc(error); }
});

