/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function joinflash() {
		//$('.linkjoin').fadeOut(1000).fadeIn(1000, function() { joinflash(); });
		$('.linkjoin').animate({opacity: 0}, 1000, function() {
				$(this).animate({opacity: 1}, 1000, function() { joinflash(); });
		});
}

$(function () {

	$('.serverblock input')
	.mousedown(function () { $(this).addClass('down') })
	.mouseup(function () { $(this).removeClass('down') })
	.mouseout(function () { $(this).removeClass('down') })

	/** Signup button fade **/

	joinflash();

	/** Fancybox **/

	// Screenshots

	$("a[rel=screen_group]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'overlayOpacity'	: .7,
		'overlayColor'		: '#000000',
		'titleFormat'       : function(title, currentArray, currentIndex) {
		    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
		}
	});

	// Login

	var start_vals = {
		'input_user' : $('#loginform input#input_user').val(),
		'input_pass' : $('#loginform input#input_pass').val() };

	$('#loginform input#input_user, #loginform input#input_pass')
		.focus(function () { if ($(this).val() == start_vals[$(this).attr('id')]) $(this).val(''); })
		.blur(function () { if ($(this).val() == '') $(this).val(start_vals[$(this).attr('id')]); });

	$('.cancelfancy').click(function () {
		$.fancybox.close();
		return false;
	});

	$('#login').click(function () {
		var t = $(this);
		var ts = $('span', t.parent());
		var passanduser = $('#input_user, #input_pass');
		var userinput = $('#input_user');
		var passinput = $('#input_pass');

		t.fadeOut('fast', function () {
			ts.fadeIn('fast', function () {
				$.ajax({
					type	: "POST",
					cache	: false,
					url		: "?login",
					data	: 'user='+userinput.val()+'&pass='+passinput.val(),
					dataType: 'json',
					success	: function(data) {
						passanduser.removeAttr('disabled');
						if (data.ok) {
							$('strong', ts).html('Login OK...');
							window.location = fw_url;
						} else {
							$('.loginerror').fadeIn('normal', function () { $(this).fadeOut('slow'); });
							passinput.val('');
							ts.fadeOut('fast', function () {
								t.fadeIn('fast');
							});
						}
					},
					error : function() {
						passanduser.removeAttr('disabled');
						$('.loginerror').fadeIn('normal', function () { $(this).fadeOut('slow'); });
						passinput.val('');
						ts.fadeOut('fast', function () {
							t.fadeIn('fast');
						});
					}
				});
				passanduser.attr('disabled', 'disabled');
			});
		});

		return false;
	});

	$('#loginform').submit(function() {
		$('#login').trigger('click');
		return false;
	});

//alert($('#loginform').submit(function () { return true; }));


	// Sign up
	/*
	$.ajaxSetup({
			async: false
	});
	*/

	$.validator.addMethod(
			"regex",
			function(value, element, regexp) {
				var check = false;
				var re = new RegExp(regexp);
				return this.optional(element) || re.test(value);
			},
			"Please check your input."
	);
	$.validator.addMethod(
			"ajaxcheck",
			function(value, element, elem) {
				return this.optional(element) || $(elem).attr('checked');
			},
			"Checking..."
	);


	$("#signup_form").validate({
		rules: {
			username: {
				required: true,
				minlength: 4,
				maxlength: 10,
				regex: '^[a-zA-Z0-9]+$',
				ajaxcheck: '#signup_form #usernamecheck',
				remote: {
					url: '?validate',
					beforeSend: function(request, settings) {
						$("#signup_form #usernamecheck").attr('checked', false);
						$("#signup_form #username").valid();
					},
					complete: function(data) {
						$("#signup_form #usernamecheck").attr('checked', true);
						$("#signup_form #username").valid();
					},
					type: 'post' 
				}
			},
			usernamecheck: {
				required: true
			},
			yob: {
				required: true,
				range: [1920, 2005]
			},
			country: {
				required: true
			},
			email: {
				required: true,
				email: true
			},
			email_again: {
				required: true,
				equalTo: "#signup_form #email",
				email: true,
				ajaxcheck: '#signup_form #emailcheck',
				remote: {
					url: '?validate',
					beforeSend: function(request, settings) {
						$("#signup_form #emailcheck").attr('checked', false);
						$("#signup_form #email_again").valid();
					},
					complete: function(data) {
						$("#signup_form #emailcheck").attr('checked', true);
						$("#signup_form #email_again").valid();
					},
					type: 'post'
				}
			},
			password: {
				required: true,
				minlength: 5
			},
			password_again: {
				required: true,
				equalTo: "#signup_form #password"
			}
		},
		messages: {
			username: {
				required: 'Required',
				minlength: 'Between 4-10 characters',
				maxlength: 'Between 4-10 characters',
				regex: 'Only a-z A-Z and 0-9',
				remote: 'Username taken'
			},
			usernamecheck: {
				required: false
			},
			yob: {
				required: 'Required',
				range: 'Between 1920 to 2005'
			},
			country: {
				required: 'Required'
			},
			email: {
				required: 'Required',
				email: 'Not a valid email'
			},
			email_again: {
				required: 'Required',
				equalTo: 'Not the same',
				email: 'Not a valid email',
				remote: 'Email taken'
			},
			password: {
				required: 'Required',
				minlength: 'At least 5 characters'
			},
			password_again: {
				required: 'Required',
				equalTo: 'Not the same'
			}
		},
        success: function(label) {
            var name = label.attr('for');
			if (name == 'usernamecheck'){
				$(label).remove();
			}
			else if (name == 'password') {
				var strength = $('#signup_form #password').val().length > 7 ? 1 : 0;
				var arr = [/[a-z]+/, /[0-9]+/, /[A-Z]+/, /\W+/];
				$.each(arr, function(i, regexp) {
					if($('#signup_form #password').val().match(regexp))
						strength++;
				});
				if (strength<5 && $('#signup_form #password').val().length > 11)
					strength++;

				var strengthstring = [
					'','Weak though', 'Normal', 'Medium', 'Strong', 'Very Strong'
				]
				label.addClass('ok').html('OK! <span>' + strengthstring[strength] + '</span>');
			} else {
				label.addClass('ok').text('OK!');
			}
        }
	});

	$("#country").change(function() { $(this).valid(); })

	$("#signup_form").valid();

	$("#signup_form").bind("submit", function() {
		var emailinput = $("#email_again", $(this).parent());
		var email = emailinput.val();
		var formerror = $(".formerror", $(this).parent());
		var formok = $(".formok", $(this).parent());
		var inputs = $('input, select', $(this).parent());
		var formcontent = $('.inner', $(this).parent());

		if ($("#signup_form").valid()) {
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "?signup",
				data	: $(this).serializeArray(),
				dataType: 'json', //json
				success	: function(data) {
					//alert(data);
					$.fancybox.hideActivity();
					if (data.ok) {
						formerror.hide();
						formcontent.fadeOut('fast', function() {
							inputs.removeAttr('disabled');
							formok.html('Thank you, to activate the account please follow the instructions <br />that has been sent to <strong>'+email+'</strong><br />If you have not recived the email in 10 min please check your spam folder.');
							formok.fadeIn();
							$.fancybox.resize();
						});
					} else {
						inputs.removeAttr('disabled');
						formerror.html(data.msg);
						formerror.fadeIn();
						$.fancybox.resize();
					}
				},
				error : function() {
					$.fancybox.hideActivity();
					inputs.removeAttr('disabled');
					formerror.html('Something went wrong, please try again!');
					formerror.fadeIn();
					$.fancybox.resize();
				}
			});

			inputs.attr('disabled', 'disabled');
			$.fancybox.showActivity();
		};
		return false;
	});

	// Reset password

	$("#showlostpassword, .linkjoin").fancybox({
		'overlayOpacity': .7,
		'overlayColor'	: '#000000',
		'scrolling'		: 'no',
		'titleShow'		: false,
		'onStart'		: function() {
			$('#signup_form .inner').show();
			$('#signup_form .formok').hide();
			$('.linkjoin').clearQueue().stop(true);
		},
		'onClosed'		: function() {
			$(".formerror").hide();
			$(".formok").hide();
			$("#content form input[type=text], #content form input[type=password], #content form select").val('');
			$("#signup_form").valid();
			/*
			$('.linkjoin').hide().animate({opacity: 1}, 1000, function() {
				$(this).fadeIn(1000, function() { joinflash(); });
			})
			*/
			joinflash();
		}
	});

	$("#reset_pass_form").bind("submit", function() {
		var emailinput = $("#reset_email", $(this).parent());
		var formerror = $(".formerror", $(this).parent());
		var formok = $(".formok", $(this).parent());
		var inputs = $('input', $(this).parent());

		if (emailinput.val().length < 1) {
			formerror.html('Enter your account email');
			formerror.fadeIn();
		} else if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(emailinput.val())) {
			formerror.html('Thats not a valid email');
			formerror.fadeIn();
		} else {
			formok.hide();
			
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "?resetpassword",
				data	: $(this).serializeArray(),
				dataType: 'json',
				success	: function(data) {
					$.fancybox.hideActivity();
					if (data.ok) {
						formerror.hide();
						formok.html('Instructions have now been sent to '+emailinput.val());
						formok.fadeIn();
						emailinput.val('');
						$.fancybox.resize();
					} else {
						formerror.html(data.msg);
						formerror.fadeIn();
						$.fancybox.resize();
					}

					inputs.removeAttr('disabled');
				},
				error : function() {
					$.fancybox.hideActivity();
					formerror.html('Something went wrong, please try again!');
					formerror.fadeIn();
					$.fancybox.resize();

					inputs.removeAttr('disabled');
				}
			});

			inputs.attr('disabled', 'disabled');
			$.fancybox.showActivity();
		}

		$.fancybox.resize();

		return false;
	});

})
