window.onorientationchange = function() {
	if (window.orientation)
		document.body.setAttribute('class', 'landscape');
	else
		document.body.setAttribute('class', 'portrait');
		
	// Notify form controller of orientation change
	if (window.form) {
		form.orientationChange();
	}
}

function $(element) {
	this.element = element;
	this.getClasses = function() {
		return this.element.className.replace(/\s+/,' ').split(' ');
	}
	this.hasClass = function(className) {
		return (' ' + this.element.className + ' ').indexOf(' ' + className + ' ') > -1;
	}
	this.addClass = function(className) {
		if (!this.hasClass(className)) {
			this.element.className += (this.element.className ? ' ' :'') + className;
		}
	}
	this.removeClass = function(className) {
		this.element.className = this.element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
	}
	this.getPrevious = function(className) {
		var prev = this.element.previousSibling;
		while (prev) {
			if (prev.nodeType == 1 && $(prev).hasClass(className)) break;
			prev = prev.previousSibling;
		}
		return prev;
	}
	this.getNext = function(className) {
		var next = this.element.nextSibling;
		while (next) {
			if (next.nodeType == 1 && $(next).hasClass(className)) break;
			next = next.nextSibling;
		}
		return next;
	}
	return this;
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

var form = {
	initialized: false,

	initialize: function() {
		var self = this;

		if (document.forms.length == 0) return;
		this.form = document.forms[0];
		this.errorPanel = document.getElementById('errormsg');
		this.errorMsgs = [];

		// Input fields
		this.inputFields = [];
		var tmp = document.getElementsByTagName('INPUT');
		for (var i=0; i<4; i++) {
			this.inputFields.push(tmp[i]);
		}

		// Hook field events
		this.inputFields.forEach(function(field, index) {

			// Focus event
			field.addEventListener('focus', function(event) {
				if ($(this).hasClass("defaultvalue")) {
					this.value = "";
				}
				this.className = ""; // Remove all classes
				self.hideStar(this);
				if (this.name == 'password' || this.name == 'passwordconf') {
					this.type = 'password';
				}

				self.focusedField = this;
			}, false);

			// Blur event
			field.addEventListener('blur', function(event) {
				// Clean leading and trailing spaces
				this.value = this.value.replace(/^\s*/, '').replace(/\s*$/, '');

				if (this.value == "") {
					self.setDefault(this); // If field is empty, set defualt value
				} else {
					if (self.validateField(this)) {
						this.className = "valid"; // Remove any other class
						self.showTick(this);
					} else {
						this.className = ""; // Remove all classes
					}
				}

				self.focusedField = null;
			}, false);
			
			// Change event
			field.addEventListener('keypress', function(event) {
				this.className = ""; // Remove all classes
				self.hideStar(this);

				// On phone number, limit the characters allowed to enter
				if (event.charCode > 31) {
					if (self.focusedField && self.focusedField.name == "phone") {
						var key = String.fromCharCode(event.charCode);
						var validChars = "0123456789+";//"-().";
						if (validChars.indexOf(key) < 0)
							event.preventDefault();
						if (key == "+" && self.focusedField.value.length)
							event.preventDefault();
					}
				}

			}, false);
		});

		// Submit button
		this.submitBtn = document.getElementById('btn-submit');
		this.submitBtn.addEventListener('click', function(event) {
			event.preventDefault();
			self.submit();
		}, false);
		
		this.initialized = true;
	},

	clean: function() {
		// Clear error messages
		this.errorPanel.innerHTML = "";
		this.errorMsgs.length = 0;

		// Clear input field status
		this.inputFields.forEach(function(field, index) {
			$(field).removeClass("error");
		});
		
		this.hideStars();
	},

	setDefault: function(field) {
		$(field).removeClass("valid");
		$(field).removeClass("error");
		$(field).addClass("defaultvalue");

		// Registration page
		if (field.name == "FIRST_NAME")    { field.value = "First name"; }
		if (field.name == "LAST_NAME")     { field.value = "Last name"; }
		if (field.name == "PRIMARY_EMAIL_ADDR")        { field.value = "email@domain.com"; }
		if (field.name == "PRIMARY_EMAIL_ADDRconf")    { field.value = "Confirm email@domain.com"; }
		if (field.name == "password")     { field.value = "Choose a password"; field.type = 'text'; }
		if (field.name == "passwordconf") { field.value = "Confirm password";  field.type = 'text'; }
		
		// Success page
		if (field.name == "phone")        { field.value = "Phone number"; }
	},

	// Submit form
	submit: function() {
		if (this.onsubmit()) this.form.submit();
	},

	// Form submit event listener
	onsubmit: function(event) {
		this.clean();
		return this.validateAll();
	},

	validateAll: function() {
		var valid = true;
		var self = this;

		this.inputFields.forEach(function(field, index) {
			if (!self.validateField(field, true)) {
				$(field).addClass("error");
				valid = false;
			}
		});

		if (!valid) {
			this.showErrorPanel();
			window.scrollTo(0,0);
		}

		self.showStars();

		return valid;
	},

	validateField: function(field, showError) {

		if (field.name == "FIRST_NAME") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please fill in your first name');
				return false;
			}
			return true;
		}

		if (field.name == "LAST_NAME") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please fill in your last name');
				return false;
			}
			return true;
		}

		if (field.name == "PRIMARY_EMAIL_ADDR") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please fill in your email');
				return false;
			}
			if (!this.isEmail(field.value)) {
				if (showError) this.errorMsgs.push('Please correct your email address');
				return false;
			}
			return true;
		}

		if (field.name == "PRIMARY_EMAIL_ADDRconf") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please confirm your email');
				return false;
			}
			if (this.form.PRIMARY_EMAIL_ADDR.value != this.form.PRIMARY_EMAIL_ADDRconf.value) {
				if (showError) this.errorMsgs.push('The email confirmation does not match');
				return false;
			}
			return true;
		}

		if (field.name == "password") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please fill in your password');
				return false;
			}
			if (!this.isValidPassword(field.value)) {
				if (showError) this.errorMsgs.push('Your password needs at least 8 characters, with both letters and numbers');
				return false;
			}
			return true;
		}

		if (field.name == "passwordconf") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please confirm your password');
				return false;
			}
			if (this.form.password.value != this.form.passwordconf.value) {
				if (showError) this.errorMsgs.push('The password confirmation does not match');
				return false;
			}
			return true;
		}

		if (field.name == "phone") {
			if ($(field).hasClass("defaultvalue") || this.isEmptyText(field.value)) {
				if (showError) this.errorMsgs.push('Please fill in your phone number');
				return false;
			}
			if(!this.isPhone(field.value)) {
				if (showError) this.errorMsgs.push('Please enter a valid phone number');
				return false;
			}
			return true;
		}

		return false; // Field not found
	},

	isEmptyText: function(str) {
		return (str == null || str.length < 1);
	},

	isEmail: function (str) {
		var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
		return re.test(str);
	},

	isValidPassword: function(str) {
		// Password must be at least 8 characters and contain both numbers and letters
		return (/^[0-9a-zA-Z]{8,}$/.test(str)) && (/[0-9]/.test(str)) && (/[a-zA-Z]/.test(str));
	},

	isPhone: function (str) {
		// International phones (min 6 digits, + at the beginning optional)
		return /^(\+?)[0-9]{6,}$/.test(str);
	},

	showErrorPanel: function() {
		if (this.errorMsgs.length > 0) {
			var html = '<p>Whoops! Something is wrong:</p><ul>';
			for (i in this.errorMsgs) {
				html += '<li>' + this.errorMsgs[i] + '</li>';
			}
			html += '</ul>';
			this.errorPanel.innerHTML = html;
		}
	},
	
	showStar: function(field) {
		var star = $(field).getPrevious('star');
		star.style.display = 'block';
	},
	
	showStars: function() {
		var self = this;
		this.inputFields.forEach(function(field, index) {
			if ($(field).hasClass("error")) self.showStar(field);
		});
	},
	
	hideStar: function(field) {
		var star = $(field).getPrevious('star');
		star.style.display = 'none';
	},
	
	hideStars: function() {
		var self = this;
		this.inputFields.forEach(function(field, index) {
			self.hideStar(field); // Always hide
		});
	},
	
	showTick: function(field) {
		var tick = $(field).getNext('tick');
		$(field).addClass('tick');
		tick.style.opacity = 1;
		this.setTickTimer(field, tick);
	},
	
	setTickTimer: function(field, tick) {
		var self = this;
		setTimeout(function() { self.fadeTick(self, field, tick); }, 100);
	},

	fadeTick: function(self, field, tick) {
		tick.style.opacity = Math.max(0, tick.style.opacity - 0.05);
		if (tick.style.opacity > 0) {
			self.setTickTimer(field, tick);
		} else {
			$(field).removeClass('tick');
		}
	},
	
	orientationChange: function() {
		if (!this.initialized) return;
		this.hideStars();
		this.showStars();
	}
}

function hookSMSLink() {
	var smslink = document.getElementById('smslink');
	if (!smslink) return;
	smslink.addEventListener('click', function(event){
		event.preventDefault();
		form.clean();
		if (form.form.style.display == 'none') {
			form.form.style.display = 'block';
		} else {
			form.form.style.display = 'none';
		}
	}, false);
}

function hookVideoBtn() {
	var videoBtn = document.getElementById('btn-watch');
	if (!videoBtn) return;

	if (readCookie('videobtn')) {
		$(videoBtn).addClass('viewed');
	} else {
		videoBtn.addEventListener('click', function(event){
			if (!$(videoBtn).hasClass('viewed')) {
				createCookie('videobtn', 'viewed');
			}
		}, false);
	}
}


window.addEventListener('load', function() {
	window.onorientationchange();
	form.initialize();
	hookVideoBtn();
	hookSMSLink();
}, false);
