$(document).ready(function(){
	Subscribe.init();
	Manager.init();
	Profile.init();
	Login.init();
	Home.init();
	Global.init();
	Initialize.init();
});

/**
 * Initialize
 *
 */
var Initialize = function() {

	var init = function()
	{
		$("body").addClass('js-enabled');

		$(".empty-focus").each(function(){
			el = $(this);
			el.attr('prefilled', el.val());
			el.focus(function(){
				if ($(this).val() == $(this).attr('prefilled')) {
					$(this).val('');
				}
			});
		});
	}

	return {
		init : function() { init(); }
	}
}();

/**
 * Global
 *
 */
var Global = function() {

	/**
	 * Global.init
	 *
	 * @param void
	 * @return void
	 */
	var init = function()
	{
		flushMessage();
	};

	/**
	 * Global.flushMessage
	 * Fades out all currently displayed system messages
	 *
	 * @param void
	 * @return void
	 */
	var flushMessage = function()
	{
		if ($("#system-messages").length) {
			setTimeout(function(){
				$("#system-messages-wrap").fadeOut("slow", function(){
					$("#system-messages").remove();
					$("#system-messages-wrap").removeClass('system-messages-active');
					$("#system-messages-wrap").css('display', 'block');
				});
			}, 5500);
		}
	}

	return {
		init : function() { init(); },
		flushMessage : function() { flushMessage(); }
	}
}();

/**
 * Home
 *
 */
var Home = function() {

	/**
	 * Home.init
	 * Tabifies the standings on the homepage
	 *
	 * @param void
	 * @return void
	 */
	var init = function()
	{
		var counter = 1;
		var html = '<ul class="generated-tabs">';
		var wrapper = '';
		var elm_classes = '';
		var total = jQuery(".product-shop .tab-header").length;
		jQuery("#ranking-tabs .tab-header").each(function(){
			wrapper = jQuery(this);
			while(wrapper[0].nodeName != 'div' && wrapper[0].parentNode && !wrapper.hasClass('tab-content')) {
				wrapper = wrapper.parent();
			}
			elm_classes = counter == 1 ? 'active' : '';
			if (counter == total) {
				elm_classes += ' last';
			}
			html += '<li class="'+ elm_classes +' ' + jQuery(this).attr('id') + '"><a href="#" id="tab-'+counter+'" class="tab-nav">'+jQuery(this).text()+'<span class="corner corner-tl"></span><span class="corner corner-tr"></span></a></li>';
			wrapper.attr('id', 'tab-'+counter+'-content');

			if (counter != 1) {
				wrapper.addClass('hide');
			}
			jQuery(this).addClass('hide');
			counter++;
		});
		html += '</ul>';
		jQuery("#ranking-tabs").prepend(html);
		jQuery("#ranking-tabs .tab-nav").click(function(){
			interaction(this);
			return false;
		});
		jQuery("#ranking-tabs .tab-nav").focus(function(){
			interaction(this);
			return false;
		});
	};

	/**
	 * Home.interaction
	 * Interaction for focus and clicking on tabs
	 *
	 * @param void
	 * @return void
	 */
	var interaction = function(el)
	{
		jQuery(".generated-tabs li.active").removeClass('active');
		jQuery(el).parents('li').eq(0).addClass('active');
		jQuery("#ranking-tabs .tab-content").addClass('hide');
		jQuery('#'+jQuery(el).attr('id')+'-content').removeClass('hide');
	};

	return {
		init : function() { init(); }
	}
}();

/**
 * Login
 *
 */
var Login = function() {

	var init = function()
	{
		$('#loginform').submit(function(){
			var proceed = true;
			if (!$('#login-password').val()) {
				General.addError(
					'#login-password',
					'Er is geen wachtwoord ingevuld'
				);
				proceed = false;
			}

			var regex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,6})+$/;
			if (!regex.test($('#login-email').val())) {
				General.addError(
					'#login-email',
					'Het opgegeven adres is geen geldig e-mailadres.'
				);
				proceed = false;
			}
			return proceed;
		});

		$('#forgot-password').submit(function(){
			var proceed = true;
			var regex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,6})+$/;
			if (!regex.test($('#resend-email').val())) {
				General.addError(
					'#resend-email',
					'Het opgegeven adres is geen geldig e-mailadres.'
				);
				proceed = false;
			}
			return proceed;
		});
	}

	return {
		init : function() { init(); }
	}
}();

/**
 * General
 *
 */
var General = function() {

	/**
	 * General.parseBudget
	 * Parse budget to millions
	 * Talking about making money fast..
	 *
	 * @param value integer
	 * @return string
	 */
	var parseBudget = function(value)
	{
		value = value / 100;
		var regex = new RegExp(/[^.]+\.?([0-9]{0,2})?/);
		var result = regex.exec(value);

		if (result[1] && result[1].length == 2) {
			// 2 decimals is enough
		} else if (result[1] && result[1].length == 1) {
			value = value + '0';
		} else {
			value = value + '.00';
		}
		return value + ' mln';
	};

	/**
	 * General.addError
	 * Create general error msg and append it to target wrap
	 *
	 * @param target object
	 * @param error string
	 * @param parentElm string
	 * @return string
	 */
	var addError = function(target, error, parentElm)
	{
		var parentElm = parentElm || 'p';
		var target = $(target);

		target.addClass('validation-failed');
		var parent = target.parents(parentElm).eq(0);

		$(".error-msg", parent).remove();
		parent.append("<span class=\"error-msg\">"+error+"</span>");
	};

	return {
		parseBudget : function(value) { return parseBudget(value); },
		addError : function(target, error, parentElm) { return addError(target, error, parentElm); }
	}
}();

/**
 * Subscribe
 *
 */
var Subscribe = function() {

	var init = function()
	{
		var form = $("#subscribe-form");
		if (!form.length) return false;

		var regex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,6})+$/;
		var input = $("#subscribe-email");
		var parent = false;
		form.submit(function(){
			if (!$("#subscribe-name").val()) {
				$("#subscribe-name").addClass('validation-failed');
			}
			if (!regex.test(input.val())) {
				input.addClass('validation-failed');
				parent = input.parents('p').eq(0);
				$(".error-msg", parent).remove();
				parent.append("<span class=\"error-msg\">'"+input.val()+"' is geen geldig e-mailadres.</span>");
				return false;
			}
		});
	};

	return {
		init : function() { init(); }
	}
}();

/**
 * Manager
 *
 */
var Manager = function() {

	var validTeam = true;
	var exceededBudget = false;

	/**
	 * Manager.init
	 * Update expenses and balance after each teamchange
	 *
	 * @param void
	 * @return void
	 */
	var init = function()
	{
		if (!$("body.page-manager").length) return false;

		var patt, result, total, selection, budget, balance, current_bal;
		patt = new RegExp(/B:[-]?([0-9]+)/);
		$(".budget-toggle").change(function(){
			total = 0;
			selection = [];
			$(".budget-toggle option:selected").each(function(){
				result = patt.exec($(this).attr('class')) || false;
				if (result) {
					total += parseInt(result[1]);
				}
				selection.push($(this).attr('class'));
			});
			$("#costs").html('&euro; ' + General.parseBudget(total));

			budget = patt.exec($("#budget").attr('class'));
			balance = parseInt(budget[1])-parseInt(total);

			current_bal = patt.exec($("#balance").attr('class'));
			if (current_bal) {
				$("#balance").removeClass('B:'+current_bal[1]);
				$("#balance").removeClass('B:-'+current_bal[1]);
			}
			$("#balance").html(
				'&euro; ' + General.parseBudget(balance)
			);
			$("#balance").addClass('B:'+balance);

			$("#balance").removeClass('plus').removeClass('debt');
			exceededBudget = false;
			if (balance != 0) {
				$("#balance").addClass(balance > 0 ? 'plus' : 'debt');
				if (balance < 0) {
					exceededBudget = true;
				}
			}

			validateTeam(selection);
			jokerInteraction();
		});

		$(".teammanager-form").submit(function(){
			if (!validTeam) {
				displayError('De gekozen coureurs, chassis en motor moeten ieder van een ander team zijn.');
				return false;
			}

			if (!allTeamSpotsFilled()) {
				displayError('Je hebt nog niet je volledige team gekozen. Ontbrekende elementen zijn rood omcirkelt.');
				return false;
			}

			if (exceededBudget) {
				displayError('Je hebt te weinig budget om dit team te beheren.');
				return false;
			}
		});

		swapSelectionImage();
		jokerInteraction();
	};

	/**
	 * Manager.allTeamSpotsFilled
	 * Verifies that the user has filled out all blanks
	 *
	 * @param void
	 * @return void
	 */
	var allTeamSpotsFilled = function()
	{
		var state = true;
		$(".team-choice").each(function(){
			if ($(this).val() == 0) {
				$(this).addClass('validation-failed');
				state = false;
			}
		});
		return state;
	};

	/**
	 * Manager.jokerInteraction
	 * Highlight jokers and disable others when activating new one
	 *
	 * @param selection array
	 * @return void
	 */
	var jokerInteraction = function()
	{
		var id;
		$(".joker-block").click(function(){
			$(".joker-block").removeClass('joker-active');
			id = $(this).attr('id');

			if (!$('#'+id+'-block').is(':checked')) {
				$(this).addClass('joker-active');
			}


			$(".joker").each(function(){
				if ($(this).attr('id') != id+'-block') {
					$(this).attr('checked', false);
				}
			});
		});
	}

	/**
	 * Manager.validateTeam
	 * Validates the team setup, all entities must be unique
	 *
	 * @param selection array
	 * @return void
	 */
	var validateTeam = function(selection)
	{
		var patt, result, blacklist = [];
		var valid = true;
		patt = new RegExp(/T:([0-9]+)/);

		for(i=0, il = selection.length; i<il; i++) {
			result = patt.exec(selection[i]) || false;
			if (result) {
				if (blacklist[result[1]]) {
					valid = false;
					break;
				}
				blacklist[result[1]] = true;
			}
		}

		validTeam = true;
		if (!valid) {
			displayError('De gekozen coureurs, chassis en motor moeten ieder van een ander team zijn.');
			validTeam = false;
		}
	};

	/**
	 * Manager.displayError
	 * Displays the given error on screen
	 *
	 * @param body string
	 * @return void
	 */
	var displayError = function(body)
	{
		$("#system-messages").remove();
		html = '<div id="system-messages" class="error">';
		html += '<h2>Je team kan momenteel niet worden opgeslagen!</h2>';
		html += '<p>'+body+'</p>';
		html += '</div>';
		$("#system-messages-wrap").append(html);
		$("#system-messages-wrap").addClass('system-messages-active');

		Global.flushMessage();
	};

	/**
	 * Manager.swapSelectionImage
	 * Adjust the images upon changing the team selection
	 *
	 * @param selection array
	 * @return void
	 */
	var swapSelectionImage = function()
	{
		var ch, wrap, pattern, img, res, balance, budget;
		$(".budget-toggle").change(function(){
			pattern = new RegExp(/([^0-9]+)([^\.]+)(.*)/);
			ch = $(this);
			wrap = ch.parents('li').eq(0);
			img = $(".selection-image", wrap);
			res = pattern.exec(img.attr('src'));
			$(".selection-image", wrap).attr('src',
				res[1] + ch.val() + res[3]
			);
		});

		/* Can't be used in <= IE8.. :(
		$(".budget-toggle").click(function(){
			pattern = new RegExp(/B:([0-9]+)/);
			balance = $("#balance");
			budget = pattern.exec(balance.attr('class'));
			if (budget) {
				budget = budget[1];


				jQuery("option", this).each(function(){
					pattern = new RegExp(/B:([0-9]+)/);
					res = pattern.exec($(this).attr('class'));
					if (res) {
						if (parseInt(res[1]) < parseInt(budget)) {
							$(this).addClass('plus');
						}
						if (parseInt(res[1]) >= parseInt(budget)) {
							$(this).addClass('debt');
						}
					}
				});
			}
		});*/
	};


	return {
		init : function() { init(); }
	}
}();

/**
 * Profile
 *
 */
var Profile = function() {

	/**
	 * General.init
	 * Initiate subpoule password form toggles
	 *
	 * @param value integer
	 * @return string
	 */
	var init = function()
	{
		$('.page-profile .change-poule-password').addClass('hide');
		$('.page-profile .poule-options .password-add-toggle').removeClass('hide');

		var wrap;
		$('.password-add-toggle a').click(function(){
			wrap = $(this).parents('tbody').eq(0);
			$('.change-poule-password', wrap).toggleClass('hide');
			return false;
		});

		var password;
		$('.change-poule-password').submit(function(){
			password = $('.poule-password', this);
			if (password.val().length < 8) {
				password.addClass('validation-failed');
				parent = password.parents('p').eq(0);
				$(".error-msg", parent).remove();
				parent.append("<span class=\"error-msg\">Het wachtwoord moet minimaal 8 tekens bevatten.</span>");
				return false;
			}
		});

		$(".remove-manager").click(function(){
			if (!confirm('Weet je zeker dat je deze manager wil verwijderen?')) {
				return false;
			}
		});
	}

	/**
	 * General.subpoules
	 * Add validation events on subpoule add and invite
	 *
	 * @param void
	 * @return boolean
	 */
	var subpoules = function()
	{
		$('#create-poule').submit(function(){
			$(".error-msg", this).remove();
			$(".validation-failed", this).removeClass('validation-failed');

			var proceed = true;
			if (!$('#new-poulename').val()) {
				General.addError(
					'#new-poulename',
					'Er is geen naam voor de subpoule opgegeven'
				);
				proceed = false;
			}
			if ($('#new-poule-password').val().length > 0 && $('#new-poule-password').val().length < 8) {
				General.addError(
					'#new-poule-password',
					'Het wachtwoord moet minimaal 8 tekens bevatten.'
				);
				proceed = false;
			}
			if (!proceed) return false;
		});

		$('#poule-invite').submit(function(){
			$(".error-msg", this).remove();
			$(".validation-failed", this).removeClass('validation-failed');

			var proceed = true;
			if ($('#invite-poule').val() == -1) {
				General.addError(
					'#invite-poule',
					'Er is geen subpoule geselecteerd.'
				);
				proceed = false;
			}
			var regex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,6})+$/;
			if (!regex.test($('#invite-email').val())) {
				General.addError(
					'#invite-email',
					'Het opgegeven adres is geen geldig e-mailadres.'
				);
				proceed = false;
			}

			if (!proceed) return false;
		});
	};

	return {
		init : function() {
			init();
			subpoules();
		}
	}
}();


/**
 * Countdown
 *
 */
function Countdown(id, s, result, results)
{
	starttime = Math.floor(new Date().getTime()/1000);

	/**
	 * Countdown.two
	 * Adds leading 0
	 *
	 * @param value string
	 * @return string
	 */
	function two(value)
	{
		value = value+"";
		if (value.length < 2) {
			value = "0" + value;
		}
		return value;
	}

	/**
	 * Countdown.countdown
	 * Update countdown
	 *
	 * @param void
	 * @param string
	 */
	function countdown()
	{
		now		= Math.floor(new Date().getTime()/1000);
		diff	= Math.floor(s - (now - starttime));

		seconds  = two(Math.floor(diff / 1) % 60);
		minutes  = two(Math.floor(diff / 60) % 60);
		hours    = two(Math.floor(diff / 3600) % 24);
		days     = Math.floor(diff / 86400) % 86400;

		if (days == 0) {
			days = "";
		} else if (days == 1) {
			days = days+" "+result+" ";
		} else {
			days = days+" "+results+" ";
		}

		if (diff >= 0) {
			output = days+hours+":"+minutes+":"+seconds;
		} else {
			return 0;
		}
		document.getElementById(id).innerHTML = output;

		countdown.timer = setTimeout(countdown, 1000);
	}

	/**
	 * Countdown.start
	 * Trigger countdown
	 *
	 * @param void
	 * @param string
	 */
	function start()
	{
		this.timer = setTimeout(countdown, 1000);
	}

	start();
}