// JavaScript Document

//jQuery
$(document).ready(function() {
						   
	//Facebook actions
	$('.friend_li').live('click', function() {
		var thisID = $(this).attr('id');
		var checked = $("input[class="+thisID+"]:checked").length;
		if (checked == 0) {
			if (!isCheckedById()) {
				$('#fb-message').html('Voit kutsua vain 30 yst&#228;v&#228;&#228; kerralla.');	//You can only invite 30 friends each time.
				$('#fb-message').show();
				$('#fb-message').animate({opacity: 1.0}, 2500).fadeOut();
				return false;
			} else {
				$("input[class="+thisID+"]").attr('checked', true);
				$(this).removeClass('off').addClass('on');
			}
		} else {
				$("input[class="+thisID+"]").attr('checked', false);
				$(this).removeClass('on').addClass('off');	
		}
	});

						   		
	//Header
	$("a.anchorLink").anchorAnimate();
	
	$('#close-warning').click(function(){
		$('#ie6-warning').fadeOut();
	});
	
	//Steps
	$('#login a').click(function(){
								 
		var type = $(this).attr('id');
		
		if (type == "go-fb"){
			tryConnect();
			$('<img class="loader" src="style/img/fb_loading.gif" alt="Loading" />').appendTo('#login-message');
			nextStep( $('#login'), $('#login-message') );
			$('<img class="loader" src="style/img/fb_loading.gif" alt="Loading" />').appendTo('#fb-friends-ul');
		} else {
			nextStep( $('#login'), $('#login-email') );
		}
		
	});
	
	//Replace Form field values on focus
	var valArray = new Array();
	
	function getValues(){
		$('input[type="text"]').each(function(){
			var value = $(this).attr('value');
			valArray.push(value);
		});
	};
	getValues();
	
	$('input[type="text"]').focus(function(){
		var index = $('input[type="text"]').index(this);
		var value = $(this).attr('value');
		if (value == valArray[index]){
			$(this).attr('value', '');	
		}
		
	});
	
	$('input[type="text"]').blur(function(){
		var index = $('input[type="text"]').index(this);
		var value = $(this).attr('value');
		if (value == ''){
			$(this).attr('value', valArray[index]);	
		}
	});
	
	//Form validation routine
	$('input[type="text"]').keyup(function() {
		validateField( $(this) );
	});
	
	$('input[type="text"]').change(function() {
		validateField( $(this) );
	});
	
	//
	function validateField( input ) {
		//
		var field = input.attr('class');
		var value = input.attr('value');
		
		markInput( input, true );
		
		if (field == 'name') {
			if ( checkName( input.attr('value')) ) {
				markInput( input, false );
			}
		}
		
		if (field == 'email') {			
			if ( checkEmail( input.attr('value')) ) {
				markInput( input, false );
			}
		}
		
	}
	
	//Mark the input valid or invalid
	function markInput( input, valid ) {
		//
		if (valid) {
			input.parent().addClass('valid');
		} else {
			input.parent().removeClass('valid');
		}
		
	}
	
	//
	function checkName( value ) {
		//check name
		if (value.length <= 2 || value == 'Nimi') {
			//Name is invalid
			return true;
		}
	}
	
	//
	function checkEmail( value ) {
		//check email
		var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		
		if (!value.length || !filter.test(value)) {
			//Email is invalid
			return true; 
		} 
		
		if (value == 'email@example.com') {
			//Email is invalid
			return true; 
		} 
	}
	
	//Validate #email-submit form
	function validForm() {
		//
		var errors = new Array();
		errors[0] = checkName( $('#email-submit .name').attr('value') );
		errors[1] = checkEmail( $('#email-submit .email').attr('value') );
		
		var invalid = jQuery.inArray(true, errors);
		
		if (invalid == -1 || invalid == undefined ) {
			return true;
		}
		
	}
	
	//
	function showMsg( toHide, toShow, type, msg ) {
		
		var content = $('<h2 class="' + type + '">Voi ei</h2><p>' + msg + '</p>');
		
		toShow.append( content );
		
		if ( jQuery.support.opacity ) {
			toHide.fadeOut(
						   
				function() {
					toShow
					.fadeIn()
					.delay(1000)
					.fadeOut(
						function(){ content.remove(); }
					);
				}
				
			).delay(1800).fadeIn();
		} else {
			toHide.hide(100,
						   
				function() {
					toShow
					.show()
					.delay(1500)
					.hide(100,
						function(){ content.remove(); }
					);
				}
				
			).delay(1500).show(100);
		}
	};
	
	//Form submit
	$('#email-submit').submit(function(){
		//
		if ( validForm() ) {
			//disable button to avoid double submit
			$('#email-submit .submit').attr('disabled', 'disabled');
			var form = $(this);
			$.post(
				'steps/register_mail.php',			//url	A string containing the URL to which the request is sent
				form.serialize(),					//data	A map or string that is sent to the server with the request.
				//success	A callback function that is executed if the request succeeds
				function(data, status, request){
					// do something with response
					process(data, 'email');
				}
				//dataType	The type of data expected from the server (text, xml, json)
			)
		} else {
			//Show invalid message
			showMsg( $('#login-email'), $('#login-message'), 'error', 'You have to insert a valid name and email!' );
		}
		return false;
	});
	
	//Form submit
	$('#fb-submit').submit(function(){
		if (!friendsEmpty()){
			$('#fb-message')
			.html('Valitse v&#228;hint&#228;&#228;n YKSI yst&#228;v&#228;!')	//You have to select at least one friend!
			.fadeIn()
			.delay(2000)
			.fadeOut();
			return false;
		}
		else {
			nextStep( $('#invite'), $('#invite-message') );
			$('#fb-friends').hide();
			var form = $(this);
			$.post(
				'steps/register_friends.php',			//url	A string containing the URL to which the request is sent
				form.serialize(),		//data	A map or string that is sent to the server with the request.			
				//success	A callback function that is executed if the request succeeds
				function(data, status, request){
					// do something with response
					process(data, 'fb');		
				}
			//dataType	The type of data expected from the server (text, xml, json)
			)
			return false;
		}
	});

	//Form Cancel
	$('#reset-fb').click(function(){
		$('#fb-friends').hide();
		nextStep( $('#login-message'), $('#login') );
		return false;
	});
	
	//Validate #friends-submit form
	function validFormFriends() {
		
		var valid = false;
		
		$('#friends-submit .email').each(function() {
			
			var value = $(this).attr('value');
	   
			if( !checkEmail(value) ) {
				valid = true;
			}
		})
		
		return valid;
	};
	
	//Form submit
	$('#friends-submit').submit(function(){
		//
		if (validFormFriends()) {
			nextStep( $('#invite-email'), $('#invite-message') );
			var form = $(this);
			$.post(
				'steps/send_mail.php',   //url A string containing the URL to which the request is sent
				form.serialize(),    //data A map or string that is sent to the server with the request.   
				//success A callback function that is executed if the request succeeds
				function(data, status, request){
					// do something with response
					process(data, 'friends');  
				}
			//dataType The type of data expected from the server (text, xml, json)
			)
		} else {
   			//Show invalid message
		}
		return false;
	});	
	//
	
	//Form Cancel
	$('#reset-friends').click(function(){
		nextStep( $('#login-message'), $('#login') );
		nextStep( $('#invite-email'), $('#invite') );
		return false;
	});
	//
	function process(data, type) {
		//split response in the comma to get status message
		var response = data.split(',');
		switch(type){
			case 'email':
				outputMessageEmail( response );
				break;
			case 'fb':
				outputMessageFB( response );
				break;
			case 'friends':
				outputMessageFriends( response );
				break;
  			default:
				//Caso erro
		}		
	};
	
	//
	function outputMessageEmail( response ) {
		//get status text
		var status = response[0];
		if (status == 'success') {
			var name = response[1];
			var email = response[2];
			var id = response[3];
			//You're in! name, now choose some friends to win a trip for you.
			$('<h2 class="success">Olet peliss&#228; mukana!</h2><p>' + name + ', valitse nyt yst&#228;vi&#228; <br />osallistumaan arvontaan.</p>').appendTo('#login-message');
			$('<input name="user_name" type="hidden" value="' + name + '" />'
			 +'<input name="user_mail" type="hidden" value="' + email + '" />'
			 +'<input name="user_id" type="hidden" value="' + id + '" />').appendTo('#hide-data');
			nextStep( $('#login-email'), $('#login-message') );
			nextStep( $('#invite'), $('#invite-email') );
		} else {
			var errorMessage = response[1];
			//Oh no! An error occurred. Please try again later.
			$('<h2 class="error">Voi ei!</h2><p>' + errorMessage + '</p>').appendTo('#login-message');
			nextStep( $('#login-email'), $('#login-message') );
			
			if (response[2] == "share")
			nextStep( $('#share'), $('#share-this') );
		}
	};
	
	function outputMessageFB( response ) {
		//get status text
		var status = response[0];
		if (status == 'success') {
			
			var name = response[1];
			//Well done! Tomorrow you can play again! Now tell your friends and make them invite you.
			$('#invite-message').html('<h2 class="success">Hyvin tehty!</h2><p>Kerro nyt kavereillesi, <br />ja odota paluukutsua kilpailuun.</p>');
			nextStep( $('#share'), $('#share-this') );
		} else {
			var errorMessage = response[1];
			//Oh no! An error occurred. Please try again later.
			$('#invite-message').html('<h2 class="error">Voi ei!</h2><p>An error ocurred. Please try again later.</p>');
			
			if (response[2] == "share")
			nextStep( $('#share'), $('#share-this') );
		}
	};

	function outputMessageFriends( response ) {
		//get status text
		var status = response[0];
		if (status == 'success') {
			
			var name = response[1];
			//Well done! Tomorrow you can play again! Now tell your friends and make them invite you.
			$('#invite-message').html('<h2 class="success">Hyvin tehty!</h2><p>Voit pelata huomenna uudestaan! <br />Kerro nyt kavereillesi, ja odota paluukutsua kilpailuun.</p>');
			nextStep( $('#share'), $('#share-this') );
		} else {
			var errorMessage = response[1];
			//Oh no! An error occurred. Please try again later.
			$('#invite-message').html('<h2 class="error">Voi ei!</h2><p>' + errorMessage + '</p>');
			
		}
	};

	//
	$('#more-friends').toggle(function() {
		nextStep( $('#set1'), $('#set2') );
		$(this).addClass('toggle');
	}, function() {
		nextStep( $('#set2'), $('#set1') );
		$(this).removeClass('toggle');
	});
		
	//
	function nextStep(toHide, toShow){
		//
		if ( jQuery.support.opacity ) {
			toHide.fadeOut('fast', function(){
				toShow.fadeIn('normal');
			});
		} else {
			toHide.hide();
			toShow.show();
		}
		
		return false;
		
	};

	
	//About Isostar box
	$('<span class="close"></span>').appendTo('#mika-isostar');
	$('.close').click(function(){
		closeBox('#mika-isostar');
	});
	//
	$('#mika-isostar').hide();
	//
	$('.link-window').click(function(e){
		var id = $(this).attr('href');
		$(id).addClass('over-layer');
		
		if ($.browser.msie) {
			$(id).show();
		} else {
			$(id).fadeIn('normal');
		}
		
		e.stopPropagation();
		
	});
	//
	$('#mika-isostar').click(function(e){
		e.stopPropagation();
	});

	//
	$(document).click(function(){
		closeBox('#mika-isostar');
	});
	
	//
	function closeBox(box){
		if ($.browser.msie) {
			$(box).hide();
		} else {
			$(box).fadeOut('fast');
		}
	}
	
	//ShareThis
	var shared_object = SHARETHIS.addEntry({
		title: document.title,
		url: document.location.href
	});
	
	shared_object.attachButton(document.getElementById("ck_sharethis"));
	shared_object.attachChicklet("email", document.getElementById("ck_email"));
	shared_object.attachChicklet("facebook", document.getElementById("ck_facebook"));
	shared_object.attachChicklet("twitter", document.getElementById("ck_twitter"));

//End document.ready
}); 

//Animated scroll function
jQuery.fn.anchorAnimate = function(settings) {

	settings = jQuery.extend({
		speed : 700
	}, settings);	
	
	return this.each(function(){
		var caller = this
		$(caller).click(function (event) {	
			event.preventDefault()
			var locationHref = window.location.href
			var elementClick = $(caller).attr("href")
			
			var destination = $(elementClick).offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
				window.location.hash = elementClick
			});
			return false;
		})
	})


}
function isCheckedById() {
	var checked = $("input[@name='friends[]']:checked").length;
	if (checked >= 30) {
		return false;
	}
	else {
		return true;
	}
}
function friendsEmpty() {
	var checked = $("input[@name='friends[]']:checked").length;
	if (checked == 0) {
		return false;
	}
	else {
		return true;
	}
}
