$(document).ready(function(){
	/*
	 * set some basic variables
	 * */
	var reg        = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var validEmail = false;
	var validE     = true;//email
	var validM     = true;//message
	var validN 	   = false;//name
	
	/*
	 * if the mask plugin is loaded, add the mask to the form-element
	 */
	if(jQuery.mask)
	{
		$("#dateBirth").mask("99/99/9999");
	}
	
    $(".btn-submit2").click(
    	function() {
    		var amountMember = '';
    		$("div.listRow span.memberText").each(
    			function() {
    				amountMember += (amountMember.length == 0 ? $(this).text() : "|" + $(this).text());
    			}
    		);
    		if (amountMember.length > 0) {
    		    $("#member").val(amountMember);
    		}

    		$("#registrationForm").submit();
    	}
    );
    
    //submit login form in sidebar
    $('.btn-submit').click(function(){
    	$('.login-form').submit();
    });
    
    //submit update student form
    $('.btn-submit3').click(function(){
    	$('#registrationForm').submit();
    });
    
    //submit questions form
    $('.btn-submit3').click(function(){
    	$('#questionsForm').submit();
    });
    
    //submit update student and vragen form
    $('#contactBtn').click(function(){
    	$('#contactForm').submit();
    });
    
    //submit add a class form
    $('#addClassSubmit').click(function(){
    	$('#addClass').submit();
    });
    
    /*
     * handles ajax request to accept friendship
     * */
    $('.friendAccept').click(function(){
    	var loading;
    	var thisClick  = this;
    	var requestId  = $(thisClick).attr('rel').replace('user-','');
    	var thisParent = $(thisClick).parent();
    	
    	$(thisClick).parent().find('.btn-submit4').fadeOut(280,function(){
    		if(loading){ return; }
    		loading = true;
    		$(thisClick).parent().append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	
    	setTimeout(function(){$.post('/student/invites/process',{ requestAction: "confirm", id: requestId }, function(data) {
    		$(thisParent).replaceWith('<p>'+data+'</p>');
    	})},1000);
    });
    
    /*
     * handles ajax request to deny friendship
     * */
    $('.friendDeny').click(function(){
    	var loading;
    	var thisClick  = this;
    	var requestId  = $(thisClick).attr('rel').replace('user-','');
    	var thisParent = $(thisClick).parent();
    	
    	$(thisClick).parent().find('.btn-submit4').fadeOut(280,function(){
    		if(loading){ return; }
    		loading = true;
    		$(thisClick).parent().append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	
    	setTimeout(function(){$.post('/student/invites/process',{ requestAction: "deny", id: requestId }, function(data) {
    		$(thisParent).replaceWith('<p>'+data+'</p>');
    	})},1000);
    });
    
    /*
     * publish a game
     * */
    $('#publishGame1').click(function(){
    	var loading;
    	var thisVote = this;
    	var thisVoteParent = $(thisVote).parent();
    	var gameId = $('#gameId1').text();
    	$('.buttonHolder').fadeOut(280,function(){
    		if(loading){ return; }
    		loading = true;
    		$('.voteButtons').append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	setTimeout(function(){$.post('/publish',{ game_id: gameId }, function(data) {
    		$('.voteButtons').html('<p>'+data+'</p>').fadeIn(280);
    	})},1000);
    });
    
    $('#publishGame2').click(function(){
    	var loading;
    	var thisVote = this;
    	var thisVoteParent = $(thisVote).parent();
    	var gameId = $('#gameId2').text();
    	$('.buttonHolder').fadeOut(280,function(){
    		if(loading){ return; }
    		loading = true;
    		$('.voteButtons').append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	setTimeout(function(){$.post('/publish',{ game_id: gameId }, function(data) {
    		$('.voteButtons').html('<p>'+data+'</p>').fadeIn(280);
    	})},1000);
    });
    
    /*
     * votes on a game
     * */
    $('#voteGame1').click(function(){
    	var thisVote = this;
    	var thisVoteParent = $(thisVote).parent();
    	var gameId = $('#gameId1').text();
    	$(thisVote).fadeOut(280,function(){
    		$(thisVoteParent).append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	setTimeout(function(){$.post('/vote',{ game_id: gameId }, function(data) {
    		$(thisVoteParent).html('<p>'+data+'</p>').fadeIn(280);
    	})},1000);
    });
    
    $('#voteGame2').click(function(){
    	var thisVote = this;
    	var thisVoteParent = $(thisVote).parent();
    	var gameId = $('#gameId2').text();
    	$(thisVote).fadeOut(280,function(){
    		$(thisVoteParent).append('<img style="float:left" src="/images/loading.gif" width="20" />');
    	});
    	setTimeout(function(){$.post('/vote',{ game_id: gameId }, function(data) {
    		$(thisVoteParent).html('<p>'+data+'</p>').fadeIn(280);
    	})},1000);
    });
    
    /*
     * when the invite submit button is clicked, validate the form then submit it
     * */
    $('#inviteFormSubmit').click(function(){
    	validE=true;
    	validN=true;
    	validM=true;
    	//loop through all fields
    	$('#inviteForm .emailValidate').each(function(){
    		var emailadres = $(this).val();
    		if(reg.test(emailadres) === false)
    		{
    			validE = false;
    			$(this).next().html('Geen geldig emailadres');
    		}
    	});
    	
    	$('#inviteForm .nameValidate').each(function(){
    		var name = $(this).val();
    		if(name.length < 1)
    		{
    			validN = false;
    			$(this).next().html('Naam moet nog ingevuld worden');
    		}
    	});
    	
    	if($('#message').val().length < 2 || $('#message').val().length > 4000)
    	{
    		validM = false;
    		$('.header-box span').html('Het bericht moet langer dan 2 en korter dan 4000 karakters zijn');
    	}else
    	{
    		$('.header-box span').html('&nbsp;');
    	}
    	
    	if(validE == true && validN == true && validM == true)
    	{
    		$('#inviteForm').submit();
    	}else
    	{
    		$('#errorMessageInvite').html('Niet alles is goed ingevuld.');

    	}
    	
    });
    
    /*
     * validates field when the focus changes
     * 
     * */
    $('body').delegate(
    	'#inviteForm .emailValidate',
    	'blur',
    	function(){
    		if(validEmail === false)
			{
				if($(this).next('span').html().length == 6)
				{
					$(this).next().html('Email is niet juist');
				}
			}else
			{
				if($(this).next('span').html().length > 6)
				{
					$(this).next().html('&nbsp;');
				}
			}
    	}
    );
    
    /*
     * validates with regular expression emailadres
     *
     */
    $('body').delegate(
    	'#inviteForm .emailValidate',
    	'keyup',
    	function() {
			var email = $(this).val();
    		
			if(email.length > 5)
			{
				if(reg.test(email) != false)
				{
					validEmail = true;
				}else
				{
					validEmail = false;
				}
			}
    	}
    );
    
    //multiple invites
    $('#addMoreInvites').click(function(){
    	//the html
    	var wrapBegin  = '<div class="inviteContainer">';
    	var wrapEnd    = '</div>';
    	var appendHtml = '<div class="row">';
    	appendHtml    += '<label for="Voornaam">Naam:</label>';
    	appendHtml    += '<div class="text"><input type="text" class="nameValidate" name="Voornaam[]" value="" /><span style="margin-left:20px;color:#cc0000">&nbsp;</span></div>';
    	appendHtml    += '</div><div style="margin-bottom:15px;" class="row"><label for="Email">Email:</label>';
    	appendHtml    += '<div class="text"><input type="text" class="emailValidate" name="Email[]" value="" /><span style="margin-left:20px;color:#cc0000">&nbsp;</span></div></div>';
    	//replace the multi-div with the new form elements + append the multi-div again for multiple invites
    	$('#multi').replaceWith( wrapBegin + appendHtml + wrapEnd + '<div id="multi"></div>' );
    	//hide the appended-html first, when faded in remove the inviteContainer
    	//this because we want to only fadein the 2 form elements we just appended
    	$('.inviteContainer').hide().fadeIn( 'slow', function(){
    		$('.inviteContainer').replaceWith( appendHtml );
    	});
    	
    });
    
    //password checker
    $('pwError').html('');
    $('#newpass2').keyup(function(){
    	var lengthPass = $.trim($('#newpass').val()).length;
    	var lengthPass2 = $.trim($('#newpass2').val()).length;
    	if($('#newpass').val() === this.value)
    	{
    		$('.pwError').html('<span style="color:#009900;font-style:italic;">Wachtwoorden zijn gelijk aan elkaar</span>');
    	}else if(lengthPass < lengthPass2)
    	{
    		$('.pwError').html('<span style="color:#cc0000;font-style:italic;">Het wachtwoord is langer.</span>');
    	}else if(lengthPass2 < lengthPass)
    	{
    		$('.pwError').html('');
    	}else
    	{
    		$('.pwError').html('<span style="color:#cc0000;font-style:italic;">De wachtwoorden komen niet overeen.</span>');
    	}
    	
    });
    initBrowserDetect();
});

function initBrowserDetect()
{
	var u = navigator.userAgent.toLowerCase();
	var _html = document.getElementsByTagName("html")[0];
	
	if(is("win")) addClass("win");
	else if(is("mac")) addClass("mac");
	else if(is("linux") || is("x11")) addClass("linux");
	
	if(is("msie 8.0")) addClass("msie8");
	else if(is("msie 7.0")) addClass("msie7");
	else if(is("msie 6.0")) addClass("msie6");
	else if(is("firefox/2")) addClass("ff2");
	else if(is("firefox/3")) addClass("ff3");
	else if(is("opera/9")) addClass("opera");
	else if(is("safari") && is("version/3")) addClass("safari3");
	else if(is("safari") && is("version/4")) addClass("safari4");
	else if(is("safari") && is("version/5")) addClass("safari");
	else if(is("safari") && is("version/6")) addClass("safari");
	else if(is("chrome")) addClass("chrome");
	else if(is("safari")) addClass("safari2");
	else if(is("unknown")) addClass("unknown");
		
	function is(browser)
	{
		if(u.indexOf(browser) !=-1) return true;
	}
	function addClass(_class)
	{
		_html.className += (" " + _class);
	}
}
if (window.addEventListener)
	window.addEventListener("load", initBrowserDetect, false);
else if (window.attachEvent)
	window.attachEvent("onload", initBrowserDetect);


