// global variables
$code = "0";
$last_prizes = [];
$active_menu_class = "";
$dont_hide = false;
$user_first_name = "Vorname";
$user_last_name = "Name";
$user_email = "E-Mail";

if(typeof($request_uri) == "undefined"){
  $request_uri = "faq.php";
}

// set up handlers on document ready
$(document).ready(function() {
  set_menu_classes('faq.php' == $request_uri ? 'faq' : 'start');
  
  $('#btn_s1_next_2').click(function() {
    s1_next(2);
    set_menu_classes('code');
    return false;
  });
  
  $(document).click(function(event){
    if (!$dont_hide) {
      set_menu_classes('faq.php' == $request_uri ? 'faq' : 'start');
      hide_tabs();
    }
    $dont_hide = false;
  });
  
  $('#contdiv_cont').click(function(event){
    return $dont_hide;
  });
  
  $('#popup_wrapper').click(function() {
    $('#popup_wrapper').css('display', 'none');
  });
  
  /*$('img[id^="winner_"]').click(function() {
    $w_id = $(this).attr('id').slice(-1);
    $('#popup_wrapper').css('display', 'none');
    $('#prize_img').attr('src', $last_prizes[$w_id-1]['image']);
    $('#prize_description').html($last_prizes[$w_id-1]['prize']);
    $('#popup_wrapper').css('display', 'block');
    $('#popup_wrapper').css('top', $(this).offset().top + $(this).height());
    $('#popup_wrapper').css('left', $(this).offset().left);
  });*/
  
  $('img[id^="winner_"]').mouseenter(function(){
    $w_id = $(this).attr('id').slice(-1);
    $('#popup_wrapper').css('display', 'none');
    $('#prize_img').attr('src', $last_prizes[$w_id-1]['image']);
    $('#prize_description').html($last_prizes[$w_id-1]['prize']);
    $('#winner_name').html($last_prizes[$w_id-1]['winner']);
    $('#winner_date').html($last_prizes[$w_id-1]['date']);
    $('#popup_wrapper').css('display', 'block');
    $('#popup_wrapper').css('top', $(this).offset().top + $(this).height());
    $('#popup_wrapper').css('left', $(this).offset().left);
  }).mouseleave(function(){
    $('#popup_wrapper').css('display', 'none');
  });
  
  // buena suerte popup handlers
  $('#txt_code_2').focus(function() {
    $('#popup_wrapper2').css('top', $(this).offset().top+$(this).height()-18);
    $('#popup_wrapper2').css('left', $(this).offset().left);
    $('#popup_wrapper2').fadeIn();
  });
  
  $('#txt_code_2').blur(function() {
    $('#popup_wrapper2').fadeOut();
  });
  
  /*$('#btn_start').click(function() {
    show_step('001');
  });
  
  // initialize facebook
  FB.init({
    appId  : '230692583642300',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true, // parse XFBML
    //channelURL : 'http://WWW.MYDOMAIN.COM/channel.html', // channel.html file
    oauth  : true // enable OAuth 2.0
  });*/
  
  // show last 6 prizes
  $.getJSON("ajax.php",
  {
    method: "get_last6"
  },
  function(response) {
    $.each(response.last_prizes, function (i, prize) {
      $last_prizes[i] = {};
      $last_prizes[i]['image'] = response.last_prizes[i].img;
      $last_prizes[i]['prize'] = response.last_prizes[i].name;
      $last_prizes[i]['winner'] = response.last_prizes[i].winner;
      $last_prizes[i]['date'] = response.last_prizes[i].date;
      $('#winner_'+(i+1)).attr('src', response.last_prizes[i].img_small);
    });
  });
  
  $('#tab_start').click(function() {
    set_menu_classes('start');
    hide_tabs();
  });
  
  $('#tab_code').click(function() {
    if ("code" == $active_menu_class) {
      $(document).click();
      return;
    }
    
    $.ajax({
  	  url: '_code_steps/step001.php',
  	  dataType: "html",
  	  cache: false,
  	  success: function(html) {
  	    hide_tabs();
        set_menu_classes('code');
  	    $('#contdiv_wrapper').css('display', 'block');
  	    $('#contdiv_cont').html(html);
  	  }
    });
    show_step('001');
  });
  
  $('#btn_showprizes').click(function() {
    $('#tab_prizes').click();
  });
  
  $('#tab_prizes').click(function() {
    if ("prizes" == $active_menu_class) {
      $(document).click();
      return;
    }
    
    $.ajax({
  	  url: '_prizes/prizes.php',
  	  dataType: "html",
  	  cache: false,
  	  success: function(html) {
  	    hide_tabs();
        set_menu_classes('prizes');
  	    $('#container_12_clearfix').append('<div id="popup_tab">'+html+'</div>');
        $('#popup_tab').click(function(event){
          return false;
        });
  	  }
    });
  });
  
  $('#tab_beer').click(function() {
    if ("beer" == $active_menu_class) {
      $(document).click();
      return;
    }
    
    $.ajax({
  	  url: '_beer/beer.php',
  	  dataType: "html",
  	  cache: false,
  	  success: function(html) {
  	    hide_tabs();
        set_menu_classes('beer');
  	    $('#container_12_clearfix').append('<div id="popup_tab">'+html+'</div>');
        $('#popup_tab').click(function(event){
          return false;
        });
  	  }
    });
  });
  
  // show code count if logged into facebook
  /*FB.getLoginStatus(function(response) {
    if (response.authResponse) {
      // logged in and connected user, someone you know
      $.getJSON("ajax.php",
      {
        method: "get_count"
      },
      function(response) {
        $('#flasche').html(response.count + ' Code(s)');
      });
    } else {
      // no user session available, someone you dont know
      $('#flasche').html('not connected');
    }
  });*/
  
  
});

function press_participate() {
  $.ajax({
    url: '_code_steps/step001.php',
    dataType: "html",
    cache: false,
    success: function(html) {
      hide_tabs();
      set_menu_classes('code');
      $('#contdiv_wrapper').css('display', 'block');
      $('#contdiv_cont').html(html);
    }
  });
  show_step('001');
};

function hide_tabs() {
  $('#contdiv_wrapper').css('display', 'none');
  $('#popup_tab').remove();
}

function set_menu_classes($currentTab) {
  $active_menu_class = $currentTab;
  $('#tab_start').removeClass('current');
  $('#tab_code').removeClass('current');
  $('#tab_prizes').removeClass('current');
  $('#tab_beer').removeClass('current');
  $('#tab_faq').removeClass('current');
  $('#tab_start').css('color', '');
  $('#tab_code').css('color', '');
  $('#tab_prizes').css('color', '');
  $('#tab_beer').css('color', '');
  $('#tab_faq').css('color', '');
  $('#tab_'+$currentTab).addClass('current');
  $('#tab_'+$currentTab).css('color', '#FFFFFF');
}

// show steps
function show_step($step) {
  if ('002' == $step) {
    $.getJSON("ajax.php",
    {
      method: "skip_002",
      code: $code
    },
    function(response) {
      if ("true" == response.skip_002) {
        show_step('003');
      }
      else {
        show_step_force($step);
      }
    });
    
    return;
  }
  
  show_step_force($step);
}

function show_step_force($step) {
  $.ajax({
	  url: "_code_steps/step" + $step + ".php?code=" + $code,
	  dataType: "html",
	  cache: false,
	  success: function(html) {
	    //$('div[id^="step"]').css('display', 'none');
	    //$('#step' + $step).html(html);
	    //$('#step' + $step).css('display', 'inline');
	    $('#contdiv_cont').html(html);
	    
	    register_handlers($step);
	    initialize_fields($step);
      $('#contdiv_wrapper').css('display', 'block');
	  }
  });
}

// facebook connect
function facebook_connect($step) {
  FB.login(function(response) {
    if (response.authResponse) {
      get_participant($step);
    } 
  }, {scope: 'user_birthday,user_location,email'}
  );
}

// get participant data
function get_participant($step) {
  $.getJSON("ajax.php",
  {
    method: "get_participant"
  },
  function(response) {
    if (0 != response.fb_id) {
      $('#txt_s' + $step + '_first_name').val(response.first_name);
      $('#txt_s' + $step + '_last_name').val(response.last_name);
      $('#txt_s' + $step + '_birthday').val(response.birthday);
      $('#txt_s' + $step + '_street').val(response.street);
      $('#txt_s' + $step + '_plz').val(response.zip);
      $('#txt_s' + $step + '_ort').val(response.city);
      $('#txt_s' + $step + '_email').val(response.email);
      $('#txt_s' + $step + '_email_confirm').val(response.email);
      $('#cb_s' + $step + '_female').attr('checked', "female" == response.sex);
      $('#cb_s' + $step + '_male').attr('checked', "male" == response.sex);
      $('#btn_s' + $step + '_fbc').css('display', 'none');
    }
  });
}

// facebook logout
function facebook_logout($step) {
  FB.logout(function(response) {
    $('#btn_s' + $step + '_fblogout').css('display', 'none');
  });
}

// register jquery handlers for the given step
function register_handlers($step) {
  if ('001' == $step) {
    // step 1 'next' buttons
    $('#btn_s1_next_1').click(function() {
      s1_next(1);
    });
    // buena suerte popup handlers
    $('#txt_code_1').focus(function() {
      $('#popup_wrapper2').css('top', $(this).offset().top+$(this).height()-18);
      $('#popup_wrapper2').css('left', $(this).offset().left);
      $('#popup_wrapper2').fadeIn();
    });
    
    $('#txt_code_1').blur(function() {
      $('#popup_wrapper2').fadeOut();
    });
  }
  else if ('002' == $step) {
    // step 2 'skip' button
    $('#btn_s2_skip').click(function() {
      s2_skip();
    });
    // step 2 'next' button
    $('#btn_s2_next').click(function() {
      s2_next();
    });
    // step 2 'facebook connect' button
    $('#btn_s2_fbc').click(function() {
      facebook_connect(2);
    });
    // step 2 'back2one' button
    $('#btn_s2_back2one').click(function() {
      show_step('001');
    });
    $('#cb_datenschutz').click(function(event){
      $dont_hide = true;
    });
    $('#cb_teilnahmebed').click(function(event){
      $dont_hide = true;
    });
    $('#a_datenschutz').click(function(event){
      $dont_hide = true;
    });
    $('#a_teilnahmebed').click(function(event){
      $dont_hide = true;
    });
    // focus events
    $focus_std_vals = {'txt_s2_first_name': 'Vorname', 'txt_s2_last_name': 'Name', 'txt_s2_birthday': 'Geburtsdatum', 'txt_s2_email': 'E-Mail', 'txt_s2_email_confirm': 'E-Mail wiederholen'};
    $('#frm_address').find('input').focus(function() {
      if ($focus_std_vals[$(this).attr('id')] == $(this).val()) {
        $(this).val('');
      }
    });
    $('#frm_address').find('input').blur(function() {
      if ("" == $(this).val()) {
        $(this).val($focus_std_vals[$(this).attr('id')]);
      }
    });
  }
  else if ('003' == $step) {
    // step 3 'next' button
    $('#btn_s3_next').click(function() {
      s3_next();
    });
    // step 3 'facebook connect' button
    $('#btn_s3_fbc').click(function() {
      facebook_connect(3);
    });
    // step 3 'back2one' button
    $('#btn_s3_back2one').click(function() {
      show_step('001');
    });
  }
  else if ('004' == $step) {
    // step 4 'next' button
    $('#btn_s4_next').click(function() {
      s4_next();
    });
    $('#cb_datenschutz').click(function(event){
      $dont_hide = true;
    });
    $('#cb_teilnahmebed').click(function(event){
      $dont_hide = true;
    });
    $('#a_datenschutz').click(function(event){
      $dont_hide = true;
    });
    $('#a_teilnahmebed').click(function(event){
      $dont_hide = true;
    });
    $('#rb_s4_female').click(function(event){
      $dont_hide = true;
    });
    $('#rb_s4_male').click(function(event){
      $dont_hide = true;
    });
    // focus events
    $focus_std_vals = {'txt_s4_first_name': 'Vorname', 'txt_s4_last_name': 'Name', 'txt_s4_street': 'Strasse', 'txt_s4_street_nb': 'Nr.', 'txt_s4_zip': 'Plz', 'txt_s4_city': 'Ort', 'txt_s4_email': 'E-Mail', 'txt_s4_email_confirm': 'E-Mail wiederholen'};
    $('#frm_address').find('input').focus(function() {
      if ($focus_std_vals[$(this).attr('id')] == $(this).val()) {
        $(this).val('');
      }
    });
    $('#frm_address').find('input').blur(function() {
      if ("" == $(this).val()) {
        $(this).val($focus_std_vals[$(this).attr('id')]);
      }
    });
  }
  else if ('005' == $step) {
    // step 5 'back2one' button
    $('#btn_s5_back2one').click(function() {
      show_step('001');
    });
  }
}

// initialize fields for given step (if necessary)
function initialize_fields($step) {
  if ('002' == $step) {
    get_participant(2);
  }
  else if ('003' == $step) {
    // if there is a prize to display, display the prize
    if ($("#img_prize").length > 0) {
      $.getJSON("ajax.php",
      {
        method: "get_prize",
        code: $code
      },
      function(response) {
        $('#prize_name').html(response.prize.name);
        $('#img_prize').attr('src', response.prize.img);
      });
    }
    
    // get form data from step 2
    $('#btn_s3_fbc').css('display', $('#btn_s2_fbc').css('display'));
    $('#txt_s3_first_name').val($('#txt_s2_first_name').val());
    $('#txt_s3_last_name').val($('#txt_s2_last_name').val());
    $('#txt_s3_birthday').val($('#txt_s2_birthday').val());
    $('#txt_s3_street').val($('#txt_s2_street').val());
    $('#txt_s3_plz').val($('#txt_s2_plz').val());
    $('#txt_s3_ort').val($('#txt_s2_ort').val());
    $('#txt_s3_email').val($('#txt_s2_email').val());
    $('#txt_s3_email_confirm').val($('#txt_s2_email_confirm').val());
    $('#cb_s3_female').attr('checked', $('#cb_s2_female').attr('checked'));
    $('#cb_s3_male').attr('checked', $('#cb_s2_male').attr('checked'));
  }
  else if ('004' == $step) {
    $('#txt_s4_first_name').val($user_first_name);
    $('#txt_s4_last_name').val($user_last_name);
    $('#txt_s4_email').val($user_email);
    $('#txt_s4_email_confirm').val($user_email);
    /*FB.getLoginStatus(function(response) {
      if (response.authResponse) {
        // logged in and connected user, someone you know
        $('#btn_s' + $step + '_fblogout').css('display', 'inline');
      } else {
        // no user session available, someone you dont know
        $('#btn_s' + $step + '_fblogout').css('display', 'none');
      }
    });*/
  }
}

// step 1 -> next
function s1_next($s1_next_btn) {
  if (1 == $s1_next_btn) {
    $code = $('#txt_code_1').val();
  }
  else if (2 == $s1_next_btn) {
    $code = $('#txt_code_2').val();
  }
  // code gets checked implicitly
  show_step('002');
}

// step 2 -> skip
function s2_skip() {
  // skip grand prize page without checking anything
  show_step('003');
}

// step 2 -> next
function s2_next() {
  // teilnahmebedingungen and datenschutz accepted?
  $form_no_errors = true;
	if (!$('#cb_teilnahmebed').attr('checked')) {
    $('#cb_teilnahmebed').next().css('color', 'red');
    $form_no_errors = false;
	}
	else {
    $('#cb_teilnahmebed').next().css('color', '#303030');
	}
	if (!$('#cb_datenschutz').attr('checked')) {
    $('#cb_datenschutz').next().css('color', 'red');
    $form_no_errors = false;
	}
	else {
    $('#cb_datenschutz').next().css('color', '#303030');
	}
	
  // check form fields
  if ("" == $('#txt_s2_name').val()) {
    $form_no_errors = false;
  }
  if (!$('#txt_s2_birthday').val().match(/^([0-9]|[0-2][0-9]|3[0-1])\.([1-9]|0[1-9]|1[0-2])\.(\d\d|\d\d\d\d)$/)) {
    $('#txt_s2_birthday').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s2_birthday').css('color', 'white');
  }
  if (!$('#txt_s2_email').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
    $('#txt_s2_email').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s2_email').css('color', 'white');
  }
  if (!$('#txt_s2_email_confirm').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) || $('#txt_s2_email').val() != $('#txt_s2_email_confirm').val()) {
    $('#txt_s2_email_confirm').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s2_email_confirm').css('color', 'white');
  }
  
  if ($form_no_errors) {
    $user_first_name = $('#txt_s2_first_name').val();
    $user_last_name = $('#txt_s2_last_name').val();
    $user_email = $('#txt_s2_email').val();
    // put code into grand lottery
    $.getJSON("ajax.php",
    {
      method: "put_lottery",
      code: $code,
      //sex: ($('#cb_s2_female').attr('checked') ? "female" : "male"),
      last_name: $('#txt_s2_last_name').val(),
      first_name: $('#txt_s2_first_name').val(),
      //name: $('#txt_s2_name').val(),
      birthday: $('#txt_s2_birthday').val(),
      email: $('#txt_s2_email').val()
    },
    function(response) {
      // goto step 3
      show_step('003');
    });
  }
  
}

// step 3 -> next
function s3_next() {
  show_step('004');
  /*alert("agldagldsadasd");
  // check form fields
  $form_no_errors = true;
  $('#err_s3_sex').css('display', 'none');
  $('#err_s3_first_name').css('display', 'none');
  $('#err_s3_last_name').css('display', 'none');
  $('#err_s3_street').css('display', 'none');
  $('#err_s3_plz').css('display', 'none');
  $('#err_s3_ort').css('display', 'none');
  $('#err_s3_birthday').css('display', 'none');
  $('#err_s3_email').css('display', 'none');
  $('#err_s3_email_confirm').css('display', 'none');
  
  if (!$('#cb_s3_female').attr('checked') && !$('#cb_s3_male').attr('checked')) {
    $('#err_s3_sex').css('display', 'inline');
    $form_no_errors = false;
  }
  if ("" == $('#txt_s3_first_name').val()) {
    $('#err_s3_first_name').css('display', 'inline');
    $form_no_errors = false;
  }
  if ("" == $('#txt_s3_last_name').val()) {
    $('#err_s3_last_name').css('display', 'inline');
    $form_no_errors = false;
  }
  if ("" == $('#txt_s3_street').val()) {
    $('#err_s3_street').css('display', 'inline');
    $form_no_errors = false;
  }
  if (5 != $('#txt_s3_plz').val().length) {
    $('#err_s3_plz').css('display', 'inline');
    $form_no_errors = false;
  }
  if ("" == $('#txt_s3_ort').val()) {
    $('#err_s3_ort').css('display', 'inline');
    $form_no_errors = false;
  }
  if (!$('#txt_s3_birthday').val().match(/^([0-9]|[0-2][0-9]|3[0-1])\.([1-9]|0[1-9]|1[0-2])\.(\d\d|\d\d\d\d)$/)) {
    $('#err_s3_birthday').css('display', 'inline');
    $form_no_errors = false;
  }
  if (!$('#txt_s3_email').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
    $('#err_s3_email').css('display', 'inline');
    $form_no_errors = false;
  }
  if (!$('#txt_s3_email_confirm').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) || $('#txt_s3_email').val() != $('#txt_s3_email_confirm').val()) {
    $('#err_s3_email_confirm').css('display', 'inline');
    $form_no_errors = false;
  }
  
  if ($form_no_errors) {
    // submit address
    $.getJSON("ajax.php",
    {
      method: "submit_address",
      code: $code,
      sex: ($('#cb_s3_female').attr('checked') ? "female" : "male"),
      last_name: $('#txt_s3_last_name').val(),
      first_name: $('#txt_s3_first_name').val(),
      street: $('#txt_s3_street').val(),
      zip: $('#txt_s3_plz').val(),
      city: $('#txt_s3_ort').val(),
      birthday: $('#txt_s3_birthday').val(),
      email: $('#txt_s3_email').val()
    },
    function(response) {
      // goto step 4
      show_step('004');
    });
  }*/
  
}

// step 4 -> next
function s4_next() {
  // teilnahmebedingungen and datenschutz accepted?
  $form_no_errors = true;
	if (!$('#cb_teilnahmebed').attr('checked')) {
    $('#cb_teilnahmebed').next().css('color', 'red');
    $form_no_errors = false;
	}
	else {
    $('#cb_teilnahmebed').next().css('color', '#303030');
	}
	if (!$('#cb_datenschutz').attr('checked')) {
    $('#cb_datenschutz').next().css('color', 'red');
    $form_no_errors = false;
	}
	else {
    $('#cb_datenschutz').next().css('color', '#303030');
	}
	
  // check form fields
  if (!$('#rb_s4_female').attr('checked') && !$('#rb_s4_male').attr('checked')) {
    $('#rb_s4_female').next('span').css('color', 'red');
    $('#rb_s4_male').next('span').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#rb_s4_female').next('span').css('color', null);
    $('#rb_s4_male').next('span').css('color', null);
  }
  if ("" == $('#txt_s4_name').val()) {
    $form_no_errors = false;
  }
  if ("" == $('#txt_s4_street').val()) {
    $form_no_errors = false;
  }
  if ("" == $('#txt_s4_street_nb').val()) {
    $form_no_errors = false;
  }
  if (5 != $('#txt_s4_zip').val().length) {
    $('#txt_s4_zip').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s4_zip').css('color', 'white');
  }
  if ("" == $('#txt_s4_city').val()) {
    $form_no_errors = false;
  }
  if (!$('#txt_s4_email').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
    $('#txt_s4_email').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s4_email').css('color', 'white');
  }
  if (!$('#txt_s4_email_confirm').val().match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) || $('#txt_s4_email').val() != $('#txt_s4_email_confirm').val()) {
    $('#txt_s4_email_confirm').css('color', 'red');
    $form_no_errors = false;
  }
  else {
    $('#txt_s4_email_confirm').css('color', 'white');
  }
  
  if ($form_no_errors) {
    // submit address
    $.getJSON("ajax.php",
    {
      method: "submit_address",
      code: $code,
      sex: ($('#rb_s4_female').attr('checked') ? "female" : "male"),
      last_name: $('#txt_s4_last_name').val(),
      first_name: $('#txt_s4_first_name').val(),
      //name: $('#txt_s4_name').val(),
      street: $('#txt_s4_street').val(),
      street_nb: $('#txt_s4_street_nb').val(),
      zip: $('#txt_s4_zip').val(),
      city: $('#txt_s4_city').val(),
      //birthday: $('#txt_s4_birthday').val(),
      email: $('#txt_s4_email').val()
    },
    function(response) {
      if (response.errors.length > 0) {
        alert("Fehler: " + response.errors[0]);
      }
      else {
        // goto step 5
        show_step('005');
      }
    });
  }
}
