<commit_before>// These remember which buttons on the 3 filters have been clicked and are passed
// to the browser's storage when going to the map
var sportsToBeSubmitted = new Array();
var daysToBeSubmitted = new Array();
var priceToBeSubmitted = "membership,free";

// the xAngle is set to 90 degrees because initially when the cube is spawned
// it has to be rotated on 90 degrees. Therefore initially the user sees
// the bottom side of the cube (the central one is actually the map)
var xAngle = 90, yAngle = 0;

// the distance on which the cube will have to be translated in order to be
// visually "resized"
var depth;

// flag that determines in which direction the cube should go - inwards for
// zoom in or backwards for zoom out
var inwards = false;
// specifies the current wall so that the others can be made invisible
var currentWall = "bottom";

// the new side of the screen which determines how far the cube will have to
// be translated; the formula according to which the translation happens was
// derived by Yordan and Dimitar (dimy93) in one sunny (or not that
// much actually) afternoon and it can be seen in the adjust() function
// <NAME> (bob) reflowed this comment in 6 am and was appalled
var determiningSide;

// used to reverse the adjust function, applied before another adjustment
var currentDeterminerAxis;

// used to reverse the adjust function, applied before another adjustment
var currentDeterminerDirection;

// the axis on which the cube will be translated in order to be visually
// "resized"
var determinerAxis;

// used to "recognize" the browser
var version

// + or - direction of translation in the axis
var determinerDirection;

// used to manage the problem with the resizing of the default android
// browser when in landscape mode and when the address bar hides
var windowHeight;

// used to lock cube when demonstrating the tutorial
var cubeNotLocked = 'all';

var tutorialMode = false;
var helpPressed = false;

var numberOfSportsPages;

// pointing the page which is currently showed on the sports slider
var currentSportsPage = 1;

// used to determine whether the recursive swipe animation to be executed
var swipeAllowed = true

// Determine browser
var props = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' ');
var prop;
var el = document.createElement('div');

for (var i = 0, l = props.length; i < l; i++) {
  if (typeof el.style[props[i]] !== "undefined") {
    prop = props[i];
    break;
  }
}

// setting the interval at which activityTimer() is going to be executed
var inactivity = 1000;
var interval = setInterval(function(){activityTimer();}, inactivity);

// this function adjusts the cube (translates it) so that it is resized
// every time the orientation of the screen changes
// by default every side of the cube is 500px and every time the screen size is
// <500px adjust() helps the cube not to go out of the screen. Instead of
// literally resizing everything we just translate the cube in depth ("away"
// from the user) making it look smaller and fitting the screen. The result is
// having a responsive website
function adjust(){
  var height = $(window).height();
  var width = $(window).width();

  //putting the help button on the right of the screen
  $('#help').css('margin-left', (width-60) + "px");
  
  // aligning the cube equally from the left and the righr of the screen;
  // 500 is the side of the cube
  $('#cube').css('margin-top', ((height - 500) / 2) + "px");

  // this is still just the alignment; next is the "resizement"; if we use 620
  // for the alignment the cube won't be in the centre; this is because
  // initially it is 500px and after that the side seems to be like 610px;
  $('#cube').css('margin-left', ((width - 500) / 2) + "px");

  // Determining the side that will say how big the cube will be and how much
  // we will go away from the screen in order to see it as such; the cube is
  // never resized - it all comes from the perspective
  if (height > width){
    determiningSide = width;

    // It's 620 because when one of the sides that is 500px is translated
    // 360px towards us (280 + 80)it becomes as if it is 610px. We add 10px
    // for both up and bottom margins.
    if (determiningSide < 610) {
      $('#cube').css('margin-left', "-" + (250 - determiningSide / 2) + "px");
    }
  }
  else {
    determiningSide = height;
    if (determiningSide < 610){
      $('#cube').css('margin-top', "-" + (250 - determiningSide / 2) + "px");
    }
  }
  
  //alert('Determinig Side: '+determiningSide);

  // Here is the GOLDEN FORMULA according to which happens the calculation of
  // the distance of translation; we use 630 because in the beginning the
  // side of the cube is 500px but after we translate it 360px towards us on
  // the Y axis in order to get the 3D effect it seems as it is 610px. We add
  // 20 extra px for the up and bottom margins of 10px each
  
  if( (determiningSide < 700 && inwards) || (determiningSide > 700 && inwards == false)  ){
  	if(determinerDirection == '+'){
	    determinerDirection = '-';
		currentDeterminerDirection = '+';
	}
	else{
	    determinerDirection = '+';
		currentDeterminerDirection = '-';
	}
  }
  
  // balances the the cube from coming too inwards the user
  var inwardsOffset = 0;
  inwards = false;
  // the default on my laptop is 643
  if(determiningSide > 700){
  // 100 works fine on chrome and mozilla but because of the viewport problem in
  // the android default browser and safari mobile we differentiate it in 2 cases:
  // when the user has android default or mobile safari we do not zoom the cube
  // too much if the screen is bigger, hence the 2 values - 100 and 250
  // 100 comes from the zoomIn func - 80px inwards + 20px margin
  if(version == 'chrome' || version == 'firefox' || version == 'iphone'){
      inwardsOffset = 100;
  }
  else{
      inwardsOffset = 250;
  }
  inwards = true;
  }
  depth = 2000 * (630 / (determiningSide-inwardsOffset) - 1);
  
  //alert(depth);
  
  if (depth < 0){
    depth = Math.abs(depth);
  }

  // the actual transition
  document.getElementById('cube').style[prop] += "translate" + determinerAxis +
                              "(" + determinerDirection + "" + depth + "px)";
}


function browserRec( userAgent ){
  if(userAgent.indexOf('chrome') > -1)
      version = "chrome"
  else if(userAgent.indexOf('firefox') > -1)
      version = "firefox"
  else if(userAgent.indexOf('android') > -1 || 
          userAgent.indexOf('mobile safari') > -1)
	  version = "default android"
  else if(userAgent.indexOf('iphone') > -1)
	  version = "iphone";
  else if(userAgent.indexOf('ipad') > -1)
      version = "ipad"
  else if(userAgent.indexOf('chrome') == -1 &&
          userAgent.indexOf('safari') > -1)
      version = "safari"
}


$(document).ready(function() {  

  // tries to differentiate between chrome, firefox and default android/safari 
  // browsers to determine how much closer to bring the cube inwards in case the 
  // screen is too big. If it is the default android browser and safari the cube
  // goes out of the viewport when it comes too close, unlike chrome and firefox
  
  browserRec(navigator.userAgent.toLowerCase());
	  
  // draw and populate the activities side
  var sportsList = ['Football', 'Basketball', 'Golf', 'Swimming','Cricket','BMX',
				  'Cycling','Badminton','Gym','Skateboard','Gymnastics',
				  'Table tennins','Rugby','Hockey','Tennins','Athletics',
				  'Volleyball','Bowling', '1','2','3','4','5','6','7','8','9',
				  '10','11','12','13','14','15','16','17','18','Football',
				  'Basketball', 'Golf', 'Swimming','Cricket','BMX','Cycling',
				  'Badminton','Gym','Skateboard','Gymnastics','Table tennins',
				  'Rugby','Hockey','Tennins','Athletics','Volleyball','Bowling',
				  'test1', 'test2', 'test3']
  numberOfSportsPages = Math.ceil(sportsList.length / 18);
  drawActivities(sportsList);
  
  // we have the click handler for the sports togglers here because unlike the
  // price and time togglers, the activities ones are generated dynamically by
  // the function above - drawActivities
  $('.yes-no-button-sports').click(function(){

    var btn = $(this);
    var state = btn.data('clicked');
    if (state === "yes"){
      btn.css('background-position','0px 0px');
      btn.data('clicked', 'no');
      var sport = btn.parent().text().toLowerCase();
      var index = sportsToBeSubmitted.indexOf(sport);
      sportsToBeSubmitted.splice(index, 1);
    }
    else {
      btn.css('background-position','0px -35px');
      btn.data('clicked', 'yes');
      var sport = btn.parent().text().toLowerCase();
      sportsToBeSubmitted.push(sport);
    }

    // if in tutorial mode - display the explanations
    if(tutorialMode == true){
    	 setTimeout(function(){$('#back-explanation').fadeIn(1000);
    	 $('#swipe-back').fadeIn(1000, function(){
    	 animateSwipe('left', 'back')
     });
    }, 500)}

  })

// check if we are coming from the map and "click" on the filters
// that the user had already selected
// in this way we remember his/her preferences and they don't have to
// input them again at each transition between the map and the cube

  if (sessionStorage.isComingFromMap === "yes"){
    sessionStorage.isComingFromMap = "no";
    var days = sessionStorage.days.split(",");
    if (days.length === 7){
      $("#whole_toggler > div").trigger("click");
    }
    else {
      for (var x in days){
        $("#" + days[x] + "_toggler > div").trigger("click");
      }
    }

    var sports = sessionStorage.sports.split(",");
    for (var x in sports){
      $("#" + sports[x].replace(" ", "") + "_toggler > div").trigger("click");
    }

    var price = sessionStorage.price.split(',')[0];
      $("#"+price).trigger("click");
  }
  else {
    sessionStorage.sports = null;
    sessionStorage.days = null;
    sessionStorage.price = 'membership, free';
  }
	
  // set some default properties and rotate the cube to the Bottom (Intro) side
  
  // debuging
  //alert("Width: "+$(window).width()+", Height: "+ $(window).height())

  windowHeight = $(window).height();
	
  $('#bigWrapper').css('width', "100%");
  $('#bigWrapper').css('height', windowHeight);
  $('#bigWrapper').css('position', "absolute");
  $('#bigWrapper').css('left', "0");
  
  //alert("Width: "+$('#bigWrapper').css('width')+", Height: "+ $('#bigWrapper').css('height'))
  
  document.getElementById('cube').style[prop] =
                          "rotateX(" + xAngle + "deg) rotateY("+yAngle+"deg)";
  determinerAxis = "Y";
  determinerDirection = "-";
  currentDeterminerAxis = "Y";
  currentDeterminerDirection = "+";

  adjust();
  
})

// using the HTML5 web storage instead of cookies to remember the user's
// preferences when going from the cube to the map and backwards
$('#linkToMap').click(function(){
  sessionStorage.sports = sportsToBeSubmitted;
  sessionStorage.days = daysToBeSubmitted;
  sessionStorage.price = priceToBeSubmitted;
  alert("Sports: " + sportsToBeSubmitted + " Days: " + daysToBeSubmitted + " Price: " + priceToBeSubmitted)
  sessionStorage.isComingFromMap = "yes";
  window.location = "http://testpilot.x10.mx/sportscubed/map.html";
})

// this is the animation showing how to use the cube [TO BE CHANGED]
// TODO Change this
$(document).on( "click", "#how-to", function(){

  cubeNotLocked = "all";
  $('#help-window').remove();
  $('#'+currentWall+' > div').show();
  
  switch(currentWall){
     case "front":
	 gesturePerformed("up")
	 break;
	 
	 case "left":
	 gesturePerformed("left")
	 gesturePerformed("up")
	 break;
	 
	 case "right":
	 gesturePerformed("right")
	 gesturePerformed("up")
	 break;
	 
	 case "back":
	 gesturePerformed("left")
	 gesturePerformed("left")
	 gesturePerformed("up")
	 break;
	 
	 case "top":
	 gesturePerformed("up")
	 gesturePerformed("up")
	 break;
  }
  
  tutorialMode = true;
  cubeNotLocked = 'left';
  setTimeout(function(){$('#bottom-explanation').fadeIn(1000);},500);
  setTimeout(function(){$('#swipe-bottom').fadeIn(1000, function(){
	animateSwipe('left', 'bottom')
  });},500);
})

$('#help').click(function(){
  
  if(helpPressed == false){
    $(this).attr('src','img/help-dis.png').css('cursor','default')
    helpPressed = true;
    cubeNotLocked = '';
    $('#'+currentWall+' > div').hide();
    $('#'+currentWall).append('<div id="help-window">' +
  		'<img id="close-help" src="img/help-close.png"><br/><br/><br/><br/>'+
  		'Sports Cubed <br/><br/><br/> Help' +
  	    '<img id="how-to" class="help-buttons" src="img/how-to.jpg">'+
  		'<a href="about.html" target="blank">' +
		     '<img id="about-auth" class="help-buttons" src="img/about-auth.jpg">'+
	    '</a>' +
        '</div>')
    $('#curtain').fadeIn();
  }
  
  
})

$( document ).on( "click", "#close-help", function() {

  $('#help').attr('src','img/help.png').css('cursor','pointer')
  helpPressed = false;
  cubeNotLocked = 'all';
  $('#help-window').remove();
  $('#'+currentWall+' > div').show();
  $('#curtain').hide();
});

$('#sports-left-navigator').click(function(){
	if(currentSportsPage > 0){
		var currentMargin = parseInt($('#sports-slider').css('margin-left'))
		if(currentMargin < 0){
			currentMargin += 438;
		$('#sports-slider').stop(true, false).animate({
		'marginLeft': currentMargin + 'px'}, 200)
		}
		currentSportsPage -= 1;
	}
})

$('#sports-right-navigator').click(function(){
    if(currentSportsPage < 4){
		var currentMargin = parseInt($('#sports-slider').css('margin-left'))
		if(currentMargin > -2190){
		currentMargin -= 438;
		$('#sports-slider').stop(true, false).animate({
		'marginLeft': currentMargin + 'px'}, 200)
		}
		currentSportsPage += 1;
	}
})

// draws all the choices on the activities side of the cube
// takes an array of sports that is fetched from the DB
// for now the array is static until Borkata works it out.
function drawActivities(sportsList){
	listLength = sportsList.length;
	while(listLength != 0){
		if(listLength > 6){
			drawSportsWrapper(sportsList.slice(0,6))
			sportsList.splice(0,6)
			listLength = sportsList.length;
		}
		else{
			drawSportsWrapper(sportsList.slice(0, listLength))
			sportsList.splice(0,listLength)
			listLength = sportsList.length;
		}
	}
}

function drawSportsWrapper(wrapperList){
	n = wrapperList.length
	var sportsWrapperSource = '<section class="sports-wrapper">'
	for(var i = 0; i < n; i++){
		sportsWrapperSource += drawSportsLine(wrapperList[i]);
	}
	sportsWrapperSource += '</section>';

	var sportsSliderSource = $('#sports-slider').html()
	$('#sports-slider').html(sportsSliderSource + sportsWrapperSource)
}

// draws a single line for a sport with the label and the button
function drawSportsLine(element){
	elementID = element.toLowerCase();
	elementID = elementID.replace(' ', '');
	return '<div class="sports-togglers" id="' + elementID + '_toggler">' + element +
		   '<br/><div class="yes-no-button-sports" data-clicked="no"></div></div>'
}


// the repeating swiping animation for the tutorial
function animateSwipe(direction, facingWall){

if(swipeAllowed){
	var swipeimage = $('#swipe-'+facingWall);

	switch (direction){
	case 'left':
		swipeimage.animate({
			marginLeft: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'right':
		swipeimage.animate({
			marginRight: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'down':
		swipeimage.animate({
			marginBottom: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'up':
		swipeimage.animate({
			marginTop: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	}
}
}

// setting what will be saved in the browser storage as price once we go to
// the map
$('#one-time').click(function(){ 

	var oneTimeCombo = $('#one-time').parent().find('select');
	var membershipCombo = $('#membership').parent().find('select');
	oneTimeCombo.removeAttr('disabled');
	membershipCombo.prop('disabled','disabled');
	priceToBeSubmitted = '';
	priceToBeSubmitted = 'one-time,' + oneTimeCombo.val();
	
})

$('#membership').click(function(){ 

	var oneTimeCombo = $('#one-time').parent().find('select');
	var membershipCombo = $('#membership').parent().find('select');
	oneTimeCombo.prop('disabled','disabled');
	membershipCombo.removeAttr('disabled');
	priceToBeSubmitted = '';
	priceToBeSubmitted = 'membership,' + membershipCombo.val()

})

$('#membership').parent().find('select').change(function(){

  // if in tutorial mode - display the explanations
	if(tutorialMode == true){
		setTimeout(function(){$('#left-explanation').fadeIn(1000);
		$('#swipe-left').fadeIn(1000, function(){
		animateSwipe('left', 'left')
		});
	}, 500)}
	
	var temp = priceToBeSubmitted.split(',')[0];
	priceToBeSubmitted = temp + ',' + $(this).val().replace('Below ','').replace('£','');

})

$('#one-time').parent().find('select').change(function(){

  // if in tutorial mode - display the explanations
	if(tutorialMode == true){
		setTimeout(function(){$('#left-explanation').fadeIn(1000);
		$('#swipe-left').fadeIn(1000, function(){
		animateSwipe('left', 'left')
		});
	}, 500)}
  
	var temp = priceToBeSubmitted.split(',')[0];
	priceToBeSubmitted = temp + ',' + $(this).val().replace('Below ','').replace('£','');

})

// setting what will be saved in the browser storage as days once we go to
// the map
$('.yes-no-button-time').click(function(){

  var btn = $(this);
  var btnLabel = btn.parent().text()
  var clicked = btn.data('clicked');
  if (btnLabel == "Whole week"){
    switch (clicked){
    case "no":
      $('.yes-no-button-time').css('background-position','0px -35px');
      $('.yes-no-button-time').data('clicked','yes');

	  var length = daysToBeSubmitted.length;
      daysToBeSubmitted.splice(0, length);
      daysToBeSubmitted.push("monday", "tuesday", "wednesday",
                             "thursday", "friday", "saturday", "sunday");
      break;
    case "yes":
      $('.yes-no-button-time').css('background-position','0px 0px');
      $('.yes-no-button-time').data('clicked','no');

      daysToBeSubmitted.splice(0, 7);
      break;
    }
  }
  else {
    switch (clicked){
    case "no":
      btn.css('background-position','0px -35px');
      btn.data('clicked','yes');

	  var day = btn.parent().text().toLowerCase();
	  daysToBeSubmitted.push(day);
      break;
    case "yes":
      btn.css('background-position','0px 0px');
      btn.data('clicked','no');
      $("#whole_toggler").find("div").css('background-position','0px 0px');
      $("#whole_toggler > div").data('clicked','no');

	  var day = btn.parent().text().toLowerCase();
      var index = daysToBeSubmitted.indexOf(day);
      daysToBeSubmitted.splice(index, 1);
      break;
    }
  }

  // if in tutorial mode - display the explanations
  if(tutorialMode == true){<commit_msg>Fixed the problem with reseting the sessionStorage while going from the cube to the map and vice versa.<commit_after>// These remember which buttons on the 3 filters have been clicked and are passed
// to the browser's storage when going to the map
var sportsToBeSubmitted = new Array();
var daysToBeSubmitted = new Array();
var priceToBeSubmitted = "membership,free";

// the xAngle is set to 90 degrees because initially when the cube is spawned
// it has to be rotated on 90 degrees. Therefore initially the user sees
// the bottom side of the cube (the central one is actually the map)
var xAngle = 90, yAngle = 0;

// the distance on which the cube will have to be translated in order to be
// visually "resized"
var depth;

// flag that determines in which direction the cube should go - inwards for
// zoom in or backwards for zoom out
var inwards = false;
// specifies the current wall so that the others can be made invisible
var currentWall = "bottom";

// the new side of the screen which determines how far the cube will have to
// be translated; the formula according to which the translation happens was
// derived by Yordan and Dimitar (dimy93) in one sunny (or not that
// much actually) afternoon and it can be seen in the adjust() function
// <NAME> (bob) reflowed this comment in 6 am and was appalled
var determiningSide;

// used to reverse the adjust function, applied before another adjustment
var currentDeterminerAxis;

// used to reverse the adjust function, applied before another adjustment
var currentDeterminerDirection;

// the axis on which the cube will be translated in order to be visually
// "resized"
var determinerAxis;

// used to "recognize" the browser
var version

// + or - direction of translation in the axis
var determinerDirection;

// used to manage the problem with the resizing of the default android
// browser when in landscape mode and when the address bar hides
var windowHeight;

// used to lock cube when demonstrating the tutorial
var cubeNotLocked = 'all';

var tutorialMode = false;
var helpPressed = false;

var numberOfSportsPages;

// pointing the page which is currently showed on the sports slider
var currentSportsPage = 1;

// used to determine whether the recursive swipe animation to be executed
var swipeAllowed = true

// Determine browser
var props = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' ');
var prop;
var el = document.createElement('div');

for (var i = 0, l = props.length; i < l; i++) {
  if (typeof el.style[props[i]] !== "undefined") {
    prop = props[i];
    break;
  }
}

// setting the interval at which activityTimer() is going to be executed
var inactivity = 1000;
var interval = setInterval(function(){activityTimer();}, inactivity);

// this function adjusts the cube (translates it) so that it is resized
// every time the orientation of the screen changes
// by default every side of the cube is 500px and every time the screen size is
// <500px adjust() helps the cube not to go out of the screen. Instead of
// literally resizing everything we just translate the cube in depth ("away"
// from the user) making it look smaller and fitting the screen. The result is
// having a responsive website
function adjust(){
  var height = $(window).height();
  var width = $(window).width();

  //putting the help button on the right of the screen
  $('#help').css('margin-left', (width-60) + "px");
  
  // aligning the cube equally from the left and the righr of the screen;
  // 500 is the side of the cube
  $('#cube').css('margin-top', ((height - 500) / 2) + "px");

  // this is still just the alignment; next is the "resizement"; if we use 620
  // for the alignment the cube won't be in the centre; this is because
  // initially it is 500px and after that the side seems to be like 610px;
  $('#cube').css('margin-left', ((width - 500) / 2) + "px");

  // Determining the side that will say how big the cube will be and how much
  // we will go away from the screen in order to see it as such; the cube is
  // never resized - it all comes from the perspective
  if (height > width){
    determiningSide = width;

    // It's 620 because when one of the sides that is 500px is translated
    // 360px towards us (280 + 80)it becomes as if it is 610px. We add 10px
    // for both up and bottom margins.
    if (determiningSide < 610) {
      $('#cube').css('margin-left', "-" + (250 - determiningSide / 2) + "px");
    }
  }
  else {
    determiningSide = height;
    if (determiningSide < 610){
      $('#cube').css('margin-top', "-" + (250 - determiningSide / 2) + "px");
    }
  }
  
  //alert('Determinig Side: '+determiningSide);

  // Here is the GOLDEN FORMULA according to which happens the calculation of
  // the distance of translation; we use 630 because in the beginning the
  // side of the cube is 500px but after we translate it 360px towards us on
  // the Y axis in order to get the 3D effect it seems as it is 610px. We add
  // 20 extra px for the up and bottom margins of 10px each
  
  if( (determiningSide < 700 && inwards) || (determiningSide > 700 && inwards == false)  ){
  	if(determinerDirection == '+'){
	    determinerDirection = '-';
		currentDeterminerDirection = '+';
	}
	else{
	    determinerDirection = '+';
		currentDeterminerDirection = '-';
	}
  }
  
  // balances the the cube from coming too inwards the user
  var inwardsOffset = 0;
  inwards = false;
  // the default on my laptop is 643
  if(determiningSide > 700){
  // 100 works fine on chrome and mozilla but because of the viewport problem in
  // the android default browser and safari mobile we differentiate it in 2 cases:
  // when the user has android default or mobile safari we do not zoom the cube
  // too much if the screen is bigger, hence the 2 values - 100 and 250
  // 100 comes from the zoomIn func - 80px inwards + 20px margin
  if(version == 'chrome' || version == 'firefox' || version == 'iphone'){
      inwardsOffset = 100;
  }
  else{
      inwardsOffset = 250;
  }
  inwards = true;
  }
  depth = 2000 * (630 / (determiningSide-inwardsOffset) - 1);
  
  //alert(depth);
  
  if (depth < 0){
    depth = Math.abs(depth);
  }

  // the actual transition
  document.getElementById('cube').style[prop] += "translate" + determinerAxis +
                              "(" + determinerDirection + "" + depth + "px)";
}


function browserRec( userAgent ){
  if(userAgent.indexOf('chrome') > -1)
      version = "chrome"
  else if(userAgent.indexOf('firefox') > -1)
      version = "firefox"
  else if(userAgent.indexOf('android') > -1 || 
          userAgent.indexOf('mobile safari') > -1)
	  version = "default android"
  else if(userAgent.indexOf('iphone') > -1)
	  version = "iphone";
  else if(userAgent.indexOf('ipad') > -1)
      version = "ipad"
  else if(userAgent.indexOf('chrome') == -1 &&
          userAgent.indexOf('safari') > -1)
      version = "safari"
}


$(document).ready(function() {  

  // tries to differentiate between chrome, firefox and default android/safari 
  // browsers to determine how much closer to bring the cube inwards in case the 
  // screen is too big. If it is the default android browser and safari the cube
  // goes out of the viewport when it comes too close, unlike chrome and firefox
  
  browserRec(navigator.userAgent.toLowerCase());
	  
  // draw and populate the activities side
  var sportsList = ['Football', 'Basketball', 'Golf', 'Swimming','Cricket','BMX',
				  'Cycling','Badminton','Gym','Skateboard','Gymnastics',
				  'Table tennins','Rugby','Hockey','Tennins','Athletics',
				  'Volleyball','Bowling', '1','2','3','4','5','6','7','8','9',
				  '10','11','12','13','14','15','16','17','18','Football',
				  'Basketball', 'Golf', 'Swimming','Cricket','BMX','Cycling',
				  'Badminton','Gym','Skateboard','Gymnastics','Table tennins',
				  'Rugby','Hockey','Tennins','Athletics','Volleyball','Bowling',
				  'test1', 'test2', 'test3']
  numberOfSportsPages = Math.ceil(sportsList.length / 18);
  drawActivities(sportsList);
  
  // we have the click handler for the sports togglers here because unlike the
  // price and time togglers, the activities ones are generated dynamically by
  // the function above - drawActivities
  $('.yes-no-button-sports').click(function(){

    var btn = $(this);
    var state = btn.data('clicked');
    if (state == "yes"){
      btn.css('background-position','0px 0px');
      btn.data('clicked', 'no');
      var sport = btn.parent().text().toLowerCase();
      var index = sportsToBeSubmitted.indexOf(sport);
      sportsToBeSubmitted.splice(index, 1);
    }
    else {
      btn.css('background-position','0px -35px');
      btn.data('clicked', 'yes');
      var sport = btn.parent().text().toLowerCase();
	  if( sportsToBeSubmitted.indexOf( sport ) == -1 ){
        sportsToBeSubmitted.push(sport);
	  }
    }

    // if in tutorial mode - display the explanations
    if(tutorialMode == true){
    	 setTimeout(function(){$('#back-explanation').fadeIn(1000);
    	 $('#swipe-back').fadeIn(1000, function(){
    	 animateSwipe('left', 'back')
     });
    }, 500)}

  })

// check if we are coming from the map and "click" on the filters
// that the user had already selected
// in this way we remember his/her preferences and they don't have to
// input them again at each transition between the map and the cube

  if (sessionStorage.isComingFromMap === "yes"){
    sessionStorage.isComingFromMap = "no";
	
	sportsToBeSubmitted = sessionStorage.sports.split(',')
	daysToBeSubmitted = sessionStorage.days.split(',')
	priceToBeSubmitted = sessionStorage.price
	
    var days = sessionStorage.days.split(",");
    if (days.length === 7){
      $("#whole_toggler > div").trigger("click");
    }
    else {
      for (var x in days){
        $("#" + days[x] + "_toggler > div").trigger("click");
      }
    }

    var sports = sessionStorage.sports.split(",");
    for (var x in sports){
      $("#" + sports[x].replace(" ", "") + "_toggler > div").trigger("click");
    }
	
  }
  else {
    sessionStorage.sports = null;
    sessionStorage.days = null;
    sessionStorage.price = 'membership, free';
  }
	
  // set some default properties and rotate the cube to the Bottom (Intro) side
  
  // debuging
  //alert("Width: "+$(window).width()+", Height: "+ $(window).height())

  windowHeight = $(window).height();
	
  $('#bigWrapper').css('width', "100%");
  $('#bigWrapper').css('height', windowHeight);
  $('#bigWrapper').css('position', "absolute");
  $('#bigWrapper').css('left', "0");
  
  //alert("Width: "+$('#bigWrapper').css('width')+", Height: "+ $('#bigWrapper').css('height'))
  
  document.getElementById('cube').style[prop] =
                          "rotateX(" + xAngle + "deg) rotateY("+yAngle+"deg)";
  determinerAxis = "Y";
  determinerDirection = "-";
  currentDeterminerAxis = "Y";
  currentDeterminerDirection = "+";

  adjust();
  
})

// using the HTML5 web storage instead of cookies to remember the user's
// preferences when going from the cube to the map and backwards
$('#linkToMap').click(function(){
  sessionStorage.sports = sportsToBeSubmitted;
  sessionStorage.days = daysToBeSubmitted;
  sessionStorage.price = priceToBeSubmitted;
  alert("Sports: " + sportsToBeSubmitted + " Days: " + daysToBeSubmitted + " Price: " + priceToBeSubmitted)
  sessionStorage.isComingFromMap = "yes";
  window.location = "http://testpilot.x10.mx/sportscubed/map.html";
})

// this is the animation showing how to use the cube [TO BE CHANGED]
// TODO Change this
$(document).on( "click", "#how-to", function(){

  cubeNotLocked = "all";
  $('#help-window').remove();
  $('#'+currentWall+' > div').show();
  
  switch(currentWall){
     case "front":
	 gesturePerformed("up")
	 break;
	 
	 case "left":
	 gesturePerformed("left")
	 gesturePerformed("up")
	 break;
	 
	 case "right":
	 gesturePerformed("right")
	 gesturePerformed("up")
	 break;
	 
	 case "back":
	 gesturePerformed("left")
	 gesturePerformed("left")
	 gesturePerformed("up")
	 break;
	 
	 case "top":
	 gesturePerformed("up")
	 gesturePerformed("up")
	 break;
  }
  
  tutorialMode = true;
  cubeNotLocked = 'left';
  setTimeout(function(){$('#bottom-explanation').fadeIn(1000);},500);
  setTimeout(function(){$('#swipe-bottom').fadeIn(1000, function(){
	animateSwipe('left', 'bottom')
  });},500);
})

$('#help').click(function(){
  
  if(helpPressed == false){
    $(this).attr('src','img/help-dis.png').css('cursor','default')
    helpPressed = true;
    cubeNotLocked = '';
    $('#'+currentWall+' > div').hide();
    $('#'+currentWall).append('<div id="help-window">' +
  		'<img id="close-help" src="img/help-close.png"><br/><br/><br/><br/>'+
  		'Sports Cubed <br/><br/><br/> Help' +
  	    '<img id="how-to" class="help-buttons" src="img/how-to.jpg">'+
  		'<a href="about.html" target="blank">' +
		     '<img id="about-auth" class="help-buttons" src="img/about-auth.jpg">'+
	    '</a>' +
        '</div>')
    $('#curtain').fadeIn();
  }
  
  
})

$( document ).on( "click", "#close-help", function() {

  $('#help').attr('src','img/help.png').css('cursor','pointer')
  helpPressed = false;
  cubeNotLocked = 'all';
  $('#help-window').remove();
  $('#'+currentWall+' > div').show();
  $('#curtain').hide();
});

$('#sports-left-navigator').click(function(){
	if(currentSportsPage > 0){
		var currentMargin = parseInt($('#sports-slider').css('margin-left'))
		if(currentMargin < 0){
			currentMargin += 438;
		$('#sports-slider').stop(true, false).animate({
		'marginLeft': currentMargin + 'px'}, 200)
		}
		currentSportsPage -= 1;
	}
})

$('#sports-right-navigator').click(function(){
    if(currentSportsPage < 4){
		var currentMargin = parseInt($('#sports-slider').css('margin-left'))
		if(currentMargin > -2190){
		currentMargin -= 438;
		$('#sports-slider').stop(true, false).animate({
		'marginLeft': currentMargin + 'px'}, 200)
		}
		currentSportsPage += 1;
	}
})

// draws all the choices on the activities side of the cube
// takes an array of sports that is fetched from the DB
// for now the array is static until Borkata works it out.
function drawActivities(sportsList){
	listLength = sportsList.length;
	while(listLength != 0){
		if(listLength > 6){
			drawSportsWrapper(sportsList.slice(0,6))
			sportsList.splice(0,6)
			listLength = sportsList.length;
		}
		else{
			drawSportsWrapper(sportsList.slice(0, listLength))
			sportsList.splice(0,listLength)
			listLength = sportsList.length;
		}
	}
}

function drawSportsWrapper(wrapperList){
	n = wrapperList.length
	var sportsWrapperSource = '<section class="sports-wrapper">'
	for(var i = 0; i < n; i++){
		sportsWrapperSource += drawSportsLine(wrapperList[i]);
	}
	sportsWrapperSource += '</section>';

	var sportsSliderSource = $('#sports-slider').html()
	$('#sports-slider').html(sportsSliderSource + sportsWrapperSource)
}

// draws a single line for a sport with the label and the button
function drawSportsLine(element){
	elementID = element.toLowerCase();
	elementID = elementID.replace(' ', '');
	return '<div class="sports-togglers" id="' + elementID + '_toggler">' + element +
		   '<br/><div class="yes-no-button-sports" data-clicked="no"></div></div>'
}


// the repeating swiping animation for the tutorial
function animateSwipe(direction, facingWall){

if(swipeAllowed){
	var swipeimage = $('#swipe-'+facingWall);

	switch (direction){
	case 'left':
		swipeimage.animate({
			marginLeft: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'right':
		swipeimage.animate({
			marginRight: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'down':
		swipeimage.animate({
			marginBottom: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	case 'up':
		swipeimage.animate({
			marginTop: '10px'
			}, 1500, function(){
			setTimeout(function(){swipeimage.css('margin-left','400px');animateSwipe(direction, facingWall);}, 1000)
			}
		)
		break;
	}
}
}

// setting what will be saved in the browser storage as price once we go to
// the map
$('#one-time').click(function(){ 

	var oneTimeCombo = $('#one-time').parent().find('select');
	var membershipCombo = $('#membership').parent().find('select');
	oneTimeCombo.removeAttr('disabled');
	membershipCombo.prop('disabled','disabled');
	priceToBeSubmitted = '';
	priceToBeSubmitted = 'one-time,' + oneTimeCombo.val();
	
})

$('#membership').click(function(){ 

	var oneTimeCombo = $('#one-time').parent().find('select');
	var membershipCombo = $('#membership').parent().find('select');
	oneTimeCombo.prop('disabled','disabled');
	membershipCombo.removeAttr('disabled');
	priceToBeSubmitted = '';
	priceToBeSubmitted = 'membership,' + membershipCombo.val()

})

$('#membership').parent().find('select').change(function(){

  // if in tutorial mode - display the explanations
	if(tutorialMode == true){
		setTimeout(function(){$('#left-explanation').fadeIn(1000);
		$('#swipe-left').fadeIn(1000, function(){
		animateSwipe('left', 'left')
		});
	}, 500)}
	
	var temp = priceToBeSubmitted.split(',')[0];
	priceToBeSubmitted = temp + ',' + $(this).val().replace('Below ','').replace('£','');

})

$('#one-time').parent().find('select').change(function(){

  // if in tutorial mode - display the explanations
	if(tutorialMode == true){
		setTimeout(function(){$('#left-explanation').fadeIn(1000);
		$('#swipe-left').fadeIn(1000, function(){
		animateSwipe('left', 'left')
		});
	}, 500)}
  
	var temp = priceToBeSubmitted.split(',')[0];
	priceToBeSubmitted = temp + ',' + $(this).val().replace('Below ','').replace('£','');

})

// setting what will be saved in the browser storage as days once we go to
// the map
$('.yes-no-button-time').click(function(){

  var btn = $(this);
  var btnLabel = btn.parent().text()
  var clicked = btn.data('clicked');
  if (btnLabel == "Whole week"){
    switch (clicked){
    case "no":
      $('.yes-no-button-time').css('background-position','0px -35px');
      $('.yes-no-button-time').data('clicked','yes');

	  var length = daysToBeSubmitted.length;
      daysToBeSubmitted.splice(0, length);
	  if( daysToBeSubmitted.length != 7 ){
      daysToBeSubmitted.push("monday", "tuesday", "wednesday",
                             "thursday", "friday", "saturday", "sunday");
	  }
      break;
    case "yes":
      $('.yes-no-button-time').css('background-position','0px 0px');
      $('.yes-no-button-time').data('clicked','no');

      daysToBeSubmitted.splice(0, 7);
      break;
    }
  }
  else {
    switch (clicked){
    case "no":
      btn.css('background-position','0px -35px');
      btn.data('clicked','yes');

	  var day = btn.parent().text().toLowerCase();
	  if( daysToBeSubmitted.indexOf( day ) == -1 ){
        daysToBeSubmitted.push(day);;
	  }
      break;
    case "yes":
      btn.css('background-position','0px 0px');
      btn.data('clicked','no');
      $("#whole_toggler").find("div").css('background-position','0px 0px');
      $("#whole_toggler > div").data('clicked','no');

	  var day = btn.parent().text().toLowerCase();
      var index = daysToBeSubmitted.indexOf(day);
      daysToBeSubmitted.splice(index, 1);
      break;
    }
  }

  // if in tutorial mode - display the explanations
  if(tutorialMode == true){
{'fraction_non_alphanumeric': 0.1613947825185876, 'fraction_numerical': 0.017823372451490894, 'mean_word_length': 3.734698883846437, 'pattern_counts': {'":': 18, '<': 65, '<?xml version=': 0, '>': 87, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3452687', 'n_tokens_mistral': 12974, 'n_tokens_neox': 11849, 'n_words': 3461}