/* Carroussel */

var nbLinks = 4;
var activLink = 1;
var interval;

function displayLinks() {	
	var i = 1;
	
	while (i <= nbLinks) { // Display all link
		if (i == activLink) {
			$('#screensLink'+i).html('<span class="activLink">'+i+'</span>');
		}
		else {
			$('#screensLink'+i).html(i);
		}
		i++;
	}
}

function displayScreen() {
	$('#screenImg').fadeOut(500, function() { 
		$('#screenImg').html('<img src="/images/prehomeScreen_'+activLink+'.jpg" onclick="displayBigScreen('+activLink+');" class="hand" />');
		$('#screenImg').fadeIn(700);
	});
}

function displayBigScreen() {
  GB_special('/prehome/index/bigscreen/screenid/'+activLink);
}

function carroussel() { // Function to callback XX seconds 
	if (activLink+1 <= nbLinks) {
		activLink++;
	}
	else { // Back to first
		activLink = 1;
	}
	
	displayLinks(); // Update links
	displayScreen(0); // Update screen
}

function displayLink(link) { // Display one particular screen
	if (activLink != link) {
		stopCarroussel();
		activLink = link;
		displayLinks();
		displayScreen();
		launchCarroussel();
	}
}

function displayNext() {
	if (activLink+1 <= nbLinks) {
		stopCarroussel();
		activLink++;
		displayLinks();
		displayScreen();
		launchCarroussel();
	}
}

function displayPrevious() {
	if (activLink-1 > 0) {
		stopCarroussel();
		activLink--;
		displayLinks();
		displayScreen();
		launchCarroussel();
	}
}

function launchCarroussel() {
	interval = setInterval('carroussel()', 5000);
}

function stopCarroussel() {
	clearInterval(interval);
}

/* Display tests */

function displayFirstTest() {
  $("#inscripTest_second").hide();
  $("#inscripTest_third").hide();
  $("#inscripTest_first").show();
}

function displaySecondTest() {
  $("#inscripTest_first").hide();
  $("#inscripTest_third").hide();
  $("#inscripTest_second").show();
}

function displayThirdTest() {
  $("#inscripTest_first").hide();
  $("#inscripTest_second").hide();
  $("#inscripTest_third").show();
}

function validTest() {
  // Add attributs/comps depends on the answers
  // First question
  var answer1 = $('input[name=answer_1]:checked').val();
  switch (answer1) {
    case 'answer1_1':
      addAttr('cou');
      addComp('Endurance'); addComp('Endurance');
      break;
    case 'answer1_2':
      addAttr('int');
      addComp('Ingénierie'); addComp('Ingénierie');
      break;
    case 'answer1_3':
      addAttr('cha');
      addComp('Management');
      addComp('Négociation');
      break;
    case 'answer1_4':
      addAttr('ins');
      addComp('Marketing');
      addComp('Investigation');
      break;
    case 'answer1_5':
      addAttr('soc');
      addComp('Psychologie'); addComp('Psychologie');
      break;
  }

  // Second question
  var answer2 = $('input[name=answer_2]:checked').val();
  switch (answer2) {
    case 'answer2_1':
      addAttr('soc');
      addComp('Négociation'); addComp('Négociation');
      break;
    case 'answer2_2':
      addAttr('cha');
      addComp('Psychologie'); addComp('Psychologie');
      break;
    case 'answer2_3':
      addAttr('ins');
      addComp('Marketing');
      addComp('Ingénierie');
      break;
    case 'answer2_4':
      addAttr('int');
      addComp('Endurance');
      addComp('Management');
      break;
    case 'answer2_5':
      addAttr('cou');
      addComp('Investigation'); addComp('Investigation');
      break;
  }

  // Third question
  var answer3 = $('input[name=answer_3]:checked').val();
  switch (answer3) {
    case 'answer3_1':
      addAttr('cou');
      break;
    case 'answer3_2':
      addAttr('int');
      break;
    case 'answer3_3':
      addAttr('cha');
      break;
    case 'answer3_4':
      addAttr('soc');
      break;
    case 'answer3_5':
      addAttr('ins');
      break;
  }

  // Last question (checkbox)

  if ( $("#marketingCheck").attr('checked') == true )
    addComp('Marketing');
  if ( $("#ingenierieCheck").attr('checked') == true )
    addComp('Ingénierie');
  if ( $("#managementCheck").attr('checked') == true )
    addComp('Management');
  if ( $("#negociationCheck").attr('checked') == true )
    addComp('Négociation');
  if ( $("#psychologieCheck").attr('checked') == true )
    addComp('Psychologie');
  if ( $("#investigationCheck").attr('checked') == true )
    addComp('Investigation');
  if ( $("#enduranceCheck").attr('checked') == true )
    addComp('Endurance');

  displayThirdTest();
}

var nbChecked = 0;

function validCheckbox(checkbox) {
  if (checkbox.checked == true) { // Users has just checked
    nbChecked++;
  }
  else {
    nbChecked--;
  }

  if (nbChecked > 2) {
    alert('Vous ne pouvez sélectionner que deux compétences !');
    checkbox.checked = false;
    nbChecked--;
  }

}

/* Divisions list */

function displayDivisions() {
  $("#divisionContent").hide();
  $("#divisionsList").show();
}

function closeDivisions() {
  $("#divisionsList").hide();
  $("#divisionContent").show();
}

function changeDivision(divisionId) {
  // First ajax request changes division's name
  $.ajax({
    type: "GET",
    url: "/players/registration/changedivision",
    data: { 'divisionId' : divisionId },
    success:
      function(response) {
        $("#divisionContent").html(response);
      }
  })

  // Second ajax request change society's list
  $.ajax({
    type: "GET",
    url: "/players/registration/societylist",
    data: { 'divisionId' : divisionId },
    success:
      function(response) {
        $("#societyUl").html(response);
      }
  })

  // We must change the society

  defaultCompany(divisionId);

  // Close the list
  $("#divisionsList").hide();
  $("#divisionContent").show();
}

function defaultCompany(divisionId) {
  $.ajax({
    type: "GET",
    url: "/players/registration/defaultcompany",
    data: { 'divisionId' : divisionId },
    success:
      function(response) {
        $("#societyName").html(response);
      }
  })
}

function openSociety() {
  $("#societyInfos").hide();
  $("#societyList").show();
}

function closeSociety() {
  $("#societyList").hide();
  $("#societyInfos").show();
}

function changeSociety(companyId) {

  $.ajax({
    type: "GET",
    url: "/players/registration/changecompany",
    data: { 'companyId' : companyId},
    success:
      function(response) {
        $("#societyName").html(response);
      }
  })
  
  $("#societyList").hide();
  $("#societyInfos").show();
}

/* Save informations from testbox */

function saveInformations() {
  var divisionName = $("#divisionName").html();
  var companyName = $("#societyName").html();
  var avatarId = $("input[name=avatarChoice_value]:checked").val();

  if (avatarId == 'default') {
    alert('Vous devez choisir un avatar !');
  }
  else {

    $.ajax({
      type: "POST",
      url: "/players/registration/saveinformations",
      data: { 'companyName' : companyName,
              'avatarId' : avatarId },
      success:
        function(response) {
          if (response == 'OK')
            validChanges();
          else
            alert(response);
        }
    })
  }
}

/* Avatar selection */

var currentGroup = 1;
var maxGroup;

function setCurrentGroup(group) {
  currentGroup = parseInt(group);
}

function avatarsGroupInit() {
  displayCurrentGroup();
}

function displayCurrentGroup() {
  $("#avatarChoice_group_"+currentGroup).show();
  if (currentGroup <= 1) {
    $("#avatarChoice_previousArrow").hide();
  }
  else if (currentGroup >= maxGroup) {
    $("#avatarChoice_nextArrow").hide();
  }

  if (currentGroup < maxGroup) {
    $("#avatarChoice_nextArrow").show();
  }
  if (currentGroup > 1) {
    $("#avatarChoice_previousArrow").show();
  }
}

function previousAvatarsGroup() {
  if (currentGroup > 1) {
    $("#avatarChoice_group_"+currentGroup).hide();
    currentGroup--;
    displayCurrentGroup();
  }
}

function nextAvatarsGroup() {
  if (currentGroup < maxGroup) {
    $("#avatarChoice_group_"+currentGroup).hide();
    currentGroup++;
    displayCurrentGroup();
  }
}

function setNbGroups(nb) {
  maxGroup = nb;
}

/* Registration */

function openRegistrationConfirmBox(email) {
  GB_special('/players/registration/confirmbox/email/'+email);
}

function closeRegistrationConfirmBox() {
  $("#registration_confirm_box").hide();
  $("#greybox").hide();
}

function closeRegistration() {
  $("#registration_box").hide();
  $("#greybox").hide();
}

function openReglement() {
  $("#registration_box").hide();
  $("#reglement_registration_box").show();
}

function closeReglement() {
  $("#reglement_registration_box").hide();
  $("#registration_box").show();
}

function openRegistration() {
  var email = $("#email").val();
  var godchild = $("#godchild").html();

  GB_special('/players/registration/registrationbox/email/'+email+'/godchild/'+godchild);
}

function submitRegistration(ajaxUrl) {

  var validUrl = '/players/registration/validate';

  var civility = document.getElementsByName('civility');
  var fname = document.getElementsByName('fname');
  var lname = document.getElementsByName('lname');
  var nickname = document.getElementsByName('nickname');
  var password = document.getElementsByName('password');
  var email = document.getElementsByName('email');
  var zipcode = document.getElementsByName('zipcode');
  var country = document.getElementsByName('country');
  var dbirthday = document.getElementsByName('Date_Day');
  var mbirthday = document.getElementsByName('Date_Month');
  var ybirthday = document.getElementsByName('Date_Year');
  var cgu = document.getElementsByName('cgu');
  var mycivility = 0;
  var mycgu = 0;

  if (civility[0].checked) // Gender Male
    mycivility = 1;
  else if (civility[1].checked) // Gender Female
    mycivility = 2;

  if (cgu[0].checked) // Cgu accepted
    mycgu = 1;

  $.ajax({
    type: "POST",
	  url: validUrl,
	  data: { 'fname' : fname[0].value,
            'lname' : lname[0].value,
            'nickname' : nickname[0].value,
            'password' : password[0].value,
            'email' : email[0].value,
            'zipcode' : zipcode[0].value,
            'country_id' : country[0].value,
            'Date_Day' : dbirthday[0].value,
            'Date_Month' : mbirthday[0].value,
            'Date_Year' : ybirthday[0].value,
            'mycivility' : mycivility,
            'mycgu' : mycgu
          },
	  success:
      function(response){
        // If all is OK, response = 'OK' else response = 'error1;error2;...'
        if (response != 'OK') {
          var errors = response.split(';');
          for (i in errors) {
            var errorNumber = parseInt(i)+1;
            $("#error"+errorNumber+"_content").html('');
            $("#error"+errorNumber).hide();
            if (errors[i] != '') {
              $("#error"+errorNumber).show();
              $("#error"+errorNumber+"_content").html(errors[i]);
            }
          }
        }
        else {
          // Create member
           pageTracker._trackPageview("/registration");
           
           $.ajax({
              type: "POST",
              url: ajaxUrl,
              data: { 'fname' : fname[0].value,
                      'lname' : lname[0].value,
                      'nickname' : nickname[0].value,
                      'password' : password[0].value,
                      'email' : email[0].value,
                      'zipcode' : zipcode[0].value,
                      'country_id' : country[0].value,
                      'Date_Day' : dbirthday[0].value,
                      'Date_Month' : mbirthday[0].value,
                      'Date_Year' : ybirthday[0].value,
                      'mycivility' : mycivility,
                      'mycgu' : mycgu
                    } 
           });

           closeRegistration();
           openRegistrationConfirmBox(email[0].value);
        }
	    }
	});
}