
/**
 * 
 */
function WF() {
	
	WF.transitions = true;
	WF.useAudio = true;
	
	// The string identifier of the current step
	WF.currentStep;
	
	// Maps steps to preload audio files for following step
	WF.audioRef = {'0' : ['1'],
				'1' : ['2'],
				'2' : ['3-herrn', '3-frun'],
				'3-herrn' : ['3-error', '4', '5'],
				'3-frun' : ['3-error', '4', '5'],
				'3-error' : null,
				'4' : null,
				'5' : null
			};
	//Holds instances of all loaded audio tracks
	WF.audio = {'1' : null,
				'2' : null,
				'3-herrn' : null,
				'3-frun' : null,
				'3-error' : null,
				'4' : null,
				'5' : null
			};
	
	// Holds all of the user data that gets collected throughout the questionnaire 
	WF.userData = {
		isMale: null,
		email: '',
		forename: '',
		surname: ''
	};
	
	/**
	 * The "constructor" of this class.
	 */
	WF.initialize = function() {
		
		// iphone/ipad		
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { 
			WF.transitions = false;
			WF.useAudio = false;
		}
		// IE doesn't get to play audio at all
		if( $.browser.msie ) {
			 WF.useAudio = false;
		}
		
		$(window).resize(WF.updateLayout);
		
		this.inputSetup();
		this.buttonSetup();
		this.updateLayout();
				
		$('#logowall').show();
		
		if(WF.useAudio) {
			this.navigateTo(0);
		}
		else {
			this.navigateTo(1);
		}
	};
	
	/**
	 * 
	 */
	WF.inputSetup = function() {
		$('.emailInput').labelInput();
		$('.nameInput').labelInput();
		
		$(".emailForm").bind('submit', function(event) {
			event.preventDefault();
			
			WF.submitEmail($('.emailInput', event.currentTarget).val());
			
			// Copy the email address from the input field to the error screen
			$('#step3-error .emailInput').attr( 'value', $('.emailInput', event.currentTarget).val() );
			
			// Kill focus from this input field to avoid spam during transition
			$('.emailInput', this).blur();
			
			return false;
		});
		
		$(".nameForm").submit(function(event) {
			event.preventDefault();
			var name = $(".nameInput").val();
			if(name!="")
			{
				WF.submitName(name);
			}
			return false;
		});
	}
	
	/**
	 * 
	 */
	WF.buttonSetup = function() {
		
		// Make sure these buttons are not clicked multiple times
		
		$('#submitStep0').one('click', function() {
			WF.navigateTo(1);
			return false;
		});
		
		$('#submitStep1').one('click', function() {
			WF.navigateTo(2);
			return false;
		});
		
		$('#submitStep2a').one( 'click', function() {
			WF.submitGender(true);
			return false;
		});
		
		$('#submitStep2b').one( 'click', function() {
			WF.submitGender(false);
			return false;
		});
	}
	
	/**
	 * Navigates to a new step.
	 *
	 * @param {String} newStep the step to navigate to
	 * @param {Boolean} fade flags if the transition should
	 * be a fade, if not it will slide
	 */
	WF.navigateTo = function(newStep) {
		
		this.updateLayout();
		this.preloadAudio(newStep);

		var targetX = ($(window).width()*.5)-($('#steps .step').width()*.5);
		
		if (newStep == WF.currentStep && WF.transitions) {
			// If we are navigating to the same step, we run a special slide "out and back in again" animation
			$('#step' + WF.currentStep).animate({ left: -$(window).width() }, 800, 'easeInQuint' ).delay(100).animate( { left: targetX }, 900, 'easeOutQuint' )
		}
		else {

			if(WF.transitions) {
				// Hide the previous step
				$('#step' + WF.currentStep).animate({ left: -$(window).width() }, 1200, 'easeInOutQuint', function(){
					$(this).hide();
				});
				
				// Slide in the next step
				$('#step' + newStep).css( 'left', $(window).width() );
				$('#step' + newStep).css( 'display', 'block' );
				$('#step' + newStep).animate( {left: targetX }, 1200, 'easeInOutQuint' );
			}
			else {
				$('#step' + WF.currentStep).hide();
				$('#step' + newStep).css('left', targetX).show()
			}
		}

	
		WF.playAudio( newStep );	
		WF.currentStep = newStep;
	}
	
	/**
	 * Starts preloading audio for he next step
	 * @param {int} newStep
	 */
	WF.preloadAudio = function (newStep) {
		
		// get next step
		var steps = this.audioRef[newStep];

		if(steps != null) {
			WF.loadAudio(steps);
		}
	}
	
	/**
	 * @param {array} steps
	 */
	WF.loadAudio = function (steps) {
		
		if(!WF.useAudio)
			return;
		
		var extension = null;
		
		// Firefox & Opera get to play Ogg Vorbis tracks
		if( $.browser.mozilla || $.browser.opera ) {
			extension = 'ogg';
		}
		// The rest can play mp3's
		else {
			extension = 'mp3';
		}	
		
		// preload all files in the array
		for(var i in steps) {
			
			if(this.audio[steps[i]] == null) {
				this.audio[steps[i]] = new Audio('audio/slide' + steps[i] + '.' + extension);
				this.audio[steps[i]].pause(); // trigger pause immediately to force file to load and prevent cut off beginning
			}		
		}
	}
	
	/**
	 * Plays back an audio file using the HTML5
	 * audio support.
	 * 
	 * @param {String} file the URL of the file
	 * to play
	 */
	WF.playAudio = function( id ) {
		
		if (WF.useAudio) {
			
			// pause all files
			for (var i in this.audio) {
				
				if(this.audio[i] != null) {
					this.audio[i].pause();
				}
			}
			
			if(this.audio[id] != null) {

				// check if we have enough data to play
				if(this.audio[id].readyState === this.audio[id].HAVE_ENOUGH_DATA) {
					this.audio[id].play();
				}
				else {
					// or wait 1 second
					var audio = this.audio;
					setTimeout(function () {
						audio[id].play();
					}, 1000);
				}
				
			}
		}
	}
	
	
	
	
	
	/**
	 *
	 */
	WF.submitGender = function(male){
		this.userData.isMale = male;
		
		if (this.userData.isMale) {
			this.navigateTo('3-herrn');
		}
		else {
			this.navigateTo('3-frun');
		}
	}
	
	/**
	 *
	 */
	WF.submitEmail = function(email){
		// Store the email in our "session"
		this.userData.email = email;
		
		// Call the web service
		this.submit(this.userData.email, null, function(data){
			// If proceed is 0 that means the user is getting a previously generated name 
			// back and there is no need to show the enter name step
			if (data.error == 'bademail') {
				// Skip to the last step
				WF.navigateTo('3-error');
			}
			else {
				if (data.proceed == 0) {
					// Add the forename & surname to the user data
					WF.userData.forename = data.forename;
					WF.userData.surname = data.surname;
					
					// Skip to the last step
					WF.navigateTo(5);
					
					WF.writeGivenName();
				}
				else {
					// Add the surname to the user data
					WF.userData.surname = data.surname;
					
					// Show the name input step
					WF.navigateTo(4);
				}
			}
		});
		
	}
	
	/**
	 *
	 */
	WF.submitName = function(forename){
		// Store the name in our "session"
		this.userData.forename = forename;
		
		// Call the web service
		this.submit(this.userData.email, this.userData.forename, function(data){
			WF.navigateTo(5);
			
			WF.writeGivenName();
		});
	}
	
	/**
	 * 
	 */
	WF.writeGivenName = function() {
		var name = '';
		
		name += this.userData.isMale ? 'Herr' : 'Fru';
		name += ' ' + this.userData.forename;
		name += ' ' + this.userData.surname;
		
		if( this.userData.forename.length > 5 ) {
			$('#givenName').attr( 'class', 'medium' );
		}
		
		if( this.userData.forename.length > 9 ) {
			$('#givenName').attr( 'class', 'small' );
		}
		
		$('#givenName').text( name );
	}
	
	
	/**
	 * 
	 */
	WF.updateLayout = function() {
		
		var top = $(window).height() * 0.5;
	
		top -=  ( ( $("#steps").height() + $("#logowall").height() ) * 0.5 );
		top -= 10; // Move the content to be slightly above the middle
		top = Math.max( top, 0 ); // Make sure we never move the content above 0
		
		var left = ($(window).width()*.5) - ($('#steps .step').width() * 0.5);
		left = Math.max( left, 0 );
		
		// Center the steps container
		$("#steps").css('margin-top', top);
		$("#steps").css( 'margin-left', left );
		
		// Center the current step (it's on an absolute position)
		$('#step' + WF.currentStep).css( 'left', left );
	}
	
	
	/**
	 * Submits information to the web service.
	 */
	WF.submit = function(email, name, callback){
		var variables = '';
		
		// If there is an email provided, submit it
		if (email) {
			variables += 'email=' + email;
		}
		
		// If there is a name provided, submit it
		if (name) {
			variables += '&name=' + name;
		}
		
		$.ajax({
			type: "POST",
			url: "http://projects2.f-i.com/webbfredag/submit.php",
			data: variables,
			success: function(data, status){
				var responseVars = data.split('&');
				var responseData = {};
				
				for (var i = 0; i < responseVars.length; i++) {
					var pair = responseVars[i].split("=");
					responseData[pair[0]] = pair[1];
				}
				
				callback(responseData);
			},
			error: function(data){
				// Error communicating with the web service
			}
		});
	}
	
	WF.initialize();
}
