/**************************************
 * 
 * UI
 * 
 **************************************/

function set_ui(fb_profile) {
	if (fb_profile!=null && $.cookie('meexo_ab_id')==null) {
	  var abId;
	  var aMatcher = /[12345]$/;
	  if (fb_profile.id.match(aMatcher)) {
	        abId = 'A';
	  } else {
	        abId = 'B';
	  }
	  $.cookie('meexo_ab_id', abId);
	}

  step = current_step();
  switch(step)
  {
    // First time on the website 
    case "photo_upload":
      UI_update_container_photo_selection(fb_profile.first_name, fb_profile.id);
      break;
    // Photo has been uploaded
    case "info_upload":
      UI_update_container_user_info_selection(fb_profile.email, fb_profile.first_name, fb_profile.last_name, fb_profile.gender, fb_profile.birthday);
      break;
    // Information has been saved
    case "info_ok":
      UI_update_container_congratulations();
      break;
  }
};

function UI_update_container_user_not_connected()
{
  $('#container').html('<div class="early">' +
             '<div class="meexo-img"></div>' +
             '<div class="label">get in early</div>' +
             '<div class="label">meexo will be on your iPhone soon</div>' +
             '<div class="label">sign up now for premium placement and more</div>' +
             '</div>' +
             '<div id="fb-block">' +
             '<div id="fb-button"></div>' +
             '<div class="comment">it\'ll only take a minute</div>' +
             '<div class="comment">nothing will be posted on your wall</div>' +
             '</div>'
  );
  
  FB_login_button();
};

function UI_update_container_photo_selection(first_name, uid)
{
  if (first_name == null || uid == null) {
    $('#container').html('<div class="title">No facebook data</div>');
    return;
  }
  link = 'http://graph.facebook.com/' + uid + '/picture?type=large';
  
  $('#container').css('width', '550px');
  
  $('#container').html('<div class="title">select your photo</div>' +
              '<div id="photo"><img src="' + link + '" alt="' + first_name + '"></img></div>' +
              '<div class="label2">use your facebook profile picture.</div>' +
              '<div class="line"></div>' +
              '<div class="label2">select an image file on your computer (4MB max):</div>' +
              '<form id="photo-submit" enctype="multipart/form-data" method="post" action="/">' +
              '<div><input name="userfile" type="file"></div>' +
              '<div style="clear: both"></div>' +
              '<div id="submit-button"><input type="image"  class="continue" src="/images/continue-button-orange.png" width="150" height="40"/></div>' +
              '</form>'
  );
  
  Handler_photo_submit(uid);
};

function validateAccountForm() {
  if (
    $("#first_name").val().trim()=='' || $("#last_name").val().trim()==''
  || $("#email").val().trim()=='' || $("#birthday").val().trim()=='' 
  || (!$("#seeking_gender_m").is(':checked') && !$("#seeking_gender_f").is(':checked')) 
     ) {
    if ($("#error_message").html().indexOf("are required") > -1) {
      $("#error_message").html("All fields are seriously required.")
    } else {
      $("#error_message").html("All fields are required.")
    }
    return false;
  }
    return true;  
}

function UI_update_container_user_info_selection(email, first_name, last_name, gender, birthday)
{
  gender = (gender == 'male') ? 'm' : 'f';
  
  $('#container').css('width', '500px');
  var errorMessage = $.cookie('meexo_error');
  if (errorMessage == null) {
    errorMessage = "";
  } else {
    errorMessage = errorMessage.replace(/\+/g,' ');
  }

  var aboutText = $.cookie('meexo_about');
  if (aboutText == null) {
    aboutText = "";
  } else {
    aboutText = aboutText.replace(/\+/g,' ');
  }
  
  var abId = $.cookie('meexo_ab_id');
  
  // totalInches = [user isMale] ? 66 : 62; // ref NHANES 2006 study, weighted for USA demographics
  
  var htmlString = '<form id="form-infos" action="/" onsubmit="return validateAccountForm()"  method="post">' +
             '<div class="title">You\'re almost done...</div>' + 
            '<div id="error_message" class="error">'+errorMessage+'</div>' +
               '<p>' +
                '<label for="first_name">display name :</label>' +
              '<input type="text" id="first_name" name="first_name" value="' + first_name + '"/>' +
              '</p>' +
              '<p>' +
                '<label for="email">email :</label>' +
                '<input type="text" id="email" name="email" value="' + email + '"/>' +
            '</p>' +
            '<input type="hidden" id="last_name" name="last_name" value="'+ last_name +'">' +
            '<input type="hidden" id="birthday" name="birthday" value="'+ birthday +'">' +                                    
              '<p>' +
                '<label for="height">height :</label>' +
                  '<select id="form_height" id="height" name="height">' +
                      '<option value="56">4\'8" - 142cm</option>' +
                      '<option value="57">4\'9" - 144.5cm</option>' +
                      '<option value="58">4\'10" - 147cm</option>' +
                      '<option value="59">4\'11" - 150cm</option>' +
                      '<option value="60">5\' - 152.5cm</option>' +
                      '<option value="61">5\'1" - 155cm</option>' +
                      '<option value="62"'+((gender=='m')?' selected="selected"':'')+'>5\'2" - 157.5cm</option>' +
                      '<option value="63">5\'3" - 160cm</option>' +
                      '<option value="64">5\'4" - 162.5cm</option>' +
                      '<option value="65">5\'5" - 165cm</option>' +
                      '<option value="66"'+((gender=='m')?' selected="selected"':'')+'>5\'6" - 167.5cm</option>' +
                      '<option value="67">5\'7" - 170cm</option>' +
                      '<option value="68">5\'8" - 172.5cm</option>' +
                      '<option value="69">5\'9" - 175cm</option>' +
                      '<option value="70">5\'10" - 177.5cm</option>' +
                      '<option value="71">5\'11" - 180cm</option>' +
                      '<option value="72">6\' - 183cm</option>' +
                      '<option value="73">6\'1" - 185.5cm</option>' +
                      '<option value="74">6\'2" - 188cm</option>' +
                      '<option value="75">6\'3" - 190.5cm</option>' +
                      '<option value="76">6\'4" - 193cm</option>' +
                      '<option value="77">6\'5" - 195.5cm</option>' +
                      '<option value="78">6\'6" - 198cm</option>' +
                    '</select>' +
              '</p>';
    htmlString = htmlString + '<p>' +
                    '<label for="about_me">about me : </label>' +
                    '<textarea rows="7" cols="24" id="about_me" name="about_me">'+aboutText+'</textarea>' +
                '</p>';
    
  htmlString = htmlString + '<p>' +
                  '<label for="gender">I am a : </label>' +
                  '<input type="radio" id="gender_m" name="gender" class="gender_control" value="m" '+ ((gender=='m')?'checked':'') +'/>' +
              '<div class="gender">man</div>' +
                  '<input type="radio" id="gender_f" name="gender" class="gender_control" value="f" '+ ((gender=='f')?'checked':'') +'/>' +
              '<div class="gender">woman</div>' +
              '</p>' +
              '<p>' + 
              '<label for="gender">Interested in : </label>' +
                  '<input type="checkbox" id="seeking_gender_m" name="seeking_gender[]" class="gender_control" value="m" />' +
              '<div class="gender">men</div>' +
                  '<input type="checkbox" id="seeking_gender_f" name="seeking_gender[]" class="gender_control" value="f" />' +
              '<div class="gender">women</div>' +
            '</p>' +          
              '<p>' +
                '<label for="my_phone">My phone : </label>' +
                  '<input type="checkbox" name="phone[]" value="iphone" />' +
                  '<div id="apple"></div>' +
                  '<input type="checkbox" name="phone[]" value="android" />' +
                  '<div id="android"></div>' +
              '</p>' +
            '<p style="margin-top:25px">' +
            '<div style="clear:both"></div>' +
            '<p class="terms">By clicking the button below, you agree to the Meexo <a href="/tos.html">Terms of Service</a></p>' +            
            '<label for="continue">&nbsp;</label>' +
                '<div id="submit-button-2"><input type="image" name="continue" class="continue2" src="/images/continue-button-orange.png" width="150" height="40" /></div>' +
            '</p>' +
               '</form>';
               
  $('#container').html(htmlString);
  
  
};

function UI_update_container_congratulations()
{
  $('#container').css('width', '500px');

  var subMessage = 'your profile has been succesfully created'; 
  var errorMessage = $.cookie('meexo_error');
  if (errorMessage != null) {
    subMessage =  errorMessage.replace(/\+/g,' ');
  }
  
  $('#container').html('<div class="title">congrats!</div>' +
              '<div class="label">'+subMessage+'</div>' +
              '<div class="label">You will receive an email as soon as Meexo launches</div>' +
              // '<p>' +
              //  '<label class="label-inline">Invite friends :</label>' +
              //  '<input type="text" id="url" name="url" value="http://www.meexo.com/getinearly"/>' +
              //  '<div id="d_clip_button">Copy</div>' +
              // '</p>' +
              '<br>'
  );
  
  ZeroClipboard.setMoviePath( '/zeroclipboard/ZeroClipboard.swf' );
  var clip = new ZeroClipboard.Client();
  clip.setText( "http://www.meexo.com/getinearly");
  clip.glue( 'd_clip_button' );
};

/**************************************
 * 
 * Handler
 * 
 **************************************/
function Handler_photo_submit(uid)
{
  $('#photo-submit').submit(function(){
    $.cookie('meexo_uid', uid);
  });
};

/**************************************
 * 
 * Cookies
 * 
 **************************************/
function current_step()
{
  return $.cookie('meexo_step');
};

/**************************************
 * 
 * Facebook
 * 
 **************************************/
function FB_check_login_status()
{
  FB.getLoginStatus(function(response) 
  {
    if (response.authResponse) {
      $.cookie('meexo_token', response.authResponse.accessToken);
      
      // User is logged in and connected, now fetching user information
      FB.api('/me', function(response){
          set_ui(response);
        });
    } else {
        // No user session available
      UI_update_container_user_not_connected();
    }
  });
};

/**************************************
 * 
 * Facebook
 * 
 **************************************/
function FB_login_button()
{
  $('#fb-button').click(function() 
  {
    FB.login(function(response) 
    {
      if (response.authResponse) 
      {
        // User logged in, now fetching user information
        FB.api('/me', function(response) 
        {
          set_ui(response);
           });
      }
      else
      {
        // User cancelled login or did not fully authorize
        //console.log('User cancelled login or did not fully authorize.');
      }
    },
    {scope: 'email, user_birthday, user_location, offline_access'});
  });
};

/**************************************
 * 
 * 
 * 
 **************************************/
$(document).ready(function() 
{
  window.setTimeout(FB_check_login_status, 1000);
});
