var prevAboutLibDef; // Used for properly fading in the word type definitions.
var currentAboutLibWordIndex = 0;
var currentWordTypeDefinition;
var aboutLibsCatName = "Madlib Actions";

function initAbout(currentSubmissionId, useAjax){
  // Make sure we arent past the word entry.
  if(! $('#content .about #about-libs')){
    return;
  }
  
  var wordsCompleted = false;
  
  useAjax = useAjax == undefined ? true : useAjax;
  
  // Set up the about-libs
  $('#content .about #about-libs').show();
  $('.word-entry:first').show();
  
  // Update the progress bar
  updateAboutLibsProgressBar(0);
  showWordTypeDefinition(0);
  
  $('#content .about #about-help-btn').click(function(){
    $.galog.event(aboutLibsCatName, 'click', "Madlib Help Button");
    $(currentWordTypeDefinition + ':hidden').fadeIn(100);
  });
  
  $('#content .about #about-help-btn').mouseout(function(){
    if($(currentWordTypeDefinition + ':visible'))$(currentWordTypeDefinition).fadeOut(300);
  });
  
  // Set up the paging for the word entries.
  $('#content .about #enter-word-fields').cycle({
    fx:'shuffle',
    shuffle:{top: -50, left: -30},
    speed:'fast',
    timeout:0,
    next:'#next-word-btn',
    nowrap: true,
    speed: 350,
    after: function(){
      // Dont make the user have to click to start typing the word.
      if(currentAboutLibWordIndex > 0){  // Have to wait for the second input so ie doesnt jump down the homepage.
        $(this).children(':text').get(0).select();
      }
    },
    prevNextClick: function(isNext, zeroBasedSlideIndex, slideElement){
      
      var nexInputText = $('#content .about #enter-word-fields div:nth-child(' + (zeroBasedSlideIndex+1) + ') :text').attr('value');
      
      // Change the color of the bg in the moving item.
      $('#content .about #enter-word-fields div:nth-child(' + zeroBasedSlideIndex + ')').css('background', '#f1a32f');
      
      currentAboutLibWordIndex = zeroBasedSlideIndex + 1;
      
      // Show or hide the next button based on the text entered in the next input field.
      if(nexInputText && nexInputText.length > 0){
        $('#content .about #next-word-btn').show();
      }else{
        $('#content .about #next-word-btn').hide();
      }
      
      showWordTypeDefinition(zeroBasedSlideIndex);
      
      // See if its the last item.
      var numEntries = parseInt($('#id_form-TOTAL_FORMS').attr('value'));
      
      // Update the progress bar
      updateAboutLibsProgressBar(zeroBasedSlideIndex);
      
      if(zeroBasedSlideIndex >= numEntries){
        $('#content .about #next-word-btn').hide();
        $('#content .about #static-submit-btn').show();
        $('#content .about #about-help-btn').hide();
        $('#content .about  #about-libs-words-head').text('Thats It! Please Provide Your Name.');
      }else{
        $('#content .about #about-help-btn').show();
      }
    }
  });
  
  // Listen for the user to type so we can tell if the next button should show for the current field.
  $('#content .about #about-libs-form :text').keyup(function(event){
    
    var isNameField = ($(this).attr('id') == 'id_name_aboutlib');
    var text = $(this).attr('value')
    
    switch(event.keyCode){
      case 13: // Enter
        if(text && text != '' && text.length > 0){
          if(isNameField){
            $('#content .about #static-submit-btn').click();
          }else{
            $('#content .about #next-word-btn').click();
          }
        }
        break;
      default:
        if(!isNameField){
          if(text && text != '' && text.length > 0){
            $('#content .about #next-word-btn').show();
          }else{
            $('#content .about #next-word-btn').hide();
          }
        }
    }
  });
  
  $('#content .about #about-libs-form :text').attr('text', '');
  
  // See if their is already text in the first field.
  $('#content .about #about-libs-form :text:first').keyup();
  
  
  $('#content .about #about-libs-form').submit(function(){
    // Stop the form from being submitted in the normal fashion.
    if(!wordsCompleted)return false;
    return true;
  });
  
  // Setup the ajax submit.
  $('#content .about #static-submit-btn').click(function(){
    
    $.galog.event(aboutLibsCatName, 'submit', "Madlib Subbmitted");
    
    // Hide the submit button.
    $('#content .about #static-submit-btn').hide();
    $('#content div.about #about-lib-submit-loading').fadeIn(300);
    
    if(useAjax){
      var formData = $('#content .about #about-libs-form').serialize();
      var url = $('#content .about #about-libs-form').attr('action');
      
      $.post(url, formData, function(data){
        $('#content .about #about-libs').hide();
        $('#content .about #about-libs').html(data);
        initAbout();
        $('#content .about #about-libs').fadeIn();
      });
    }else{
      wordsCompleted = true;
      $('#content .about #about-libs-form').submit();
    }
    
    return false;
  });
  
  initRatingBox(currentSubmissionId);
}

function updateAboutLibsProgressBar(i){
  // Update the progress bar
  var numEntries = parseInt($('#id_form-TOTAL_FORMS').attr('value'));
  var fullWidth = parseInt($('#content .about .progress-bar .bar').css('width'));
  var sizePerWord = fullWidth / numEntries;
  var newCoverWidth = sizePerWord * (numEntries - (i));
  $('#content .about .progress-bar .cover').animate({width: newCoverWidth}, 500);
}

function showWordTypeDefinition(i){
  // Show the proper word type definition
  currentWordTypeDefinition = '#content .about #def-' + i;
  
  var numEntries = parseInt($('#content .about #id_form-TOTAL_FORMS').attr('value'));
  if(i < numEntries){
    $('#content .about #progress-nums').html((i + 1) + ' of ' + numEntries);
  }
}

function initRatingBox(currentSubmissionId){
  
  $('#rate-about-lib-box #lame-btn').click(function(){
    
    $.galog.event(aboutLibsCatName, 'click', "Madlib Rated Lame");
    
    var url = $(this).attr('href');
    
    $('#rate-about-lib-box #lame-btn').hide();
    $('#rate-about-lib-box #awesome-btn').hide();
    
    $('#content div.about #rating-submit-loading').show();
    
    $.get(url, {}, function(data){
      $('#rating').html(data);
      $('#content div.about #rating-submit-loading').hide();
      $('#content div.about #voted-message').show();
    });
    
    return false;
  });
  
  $('#rate-about-lib-box #awesome-btn').click(function(){
    
    $.galog.event(aboutLibsCatName, 'click', "Madlib Rated Awesome");
    
    var url = $(this).attr('href');
    
    $('#rate-about-lib-box #lame-btn').hide();
    $('#rate-about-lib-box #awesome-btn').hide();
    
    $('#content div.about #rating-submit-loading').show();
    
    $.get(url, {}, function(data){
      $('#rating').html(data);
      $('#content div.about #rating-submit-loading').hide();
      $('#content div.about #voted-message').show()
    });
    
    return false;
  });
  
  $('#view-another-madlib-link').click(function(){
    if(currentSubmissionId) {
      
      $.galog.event(aboutLibsCatName, 'click', "View Another Madlib");
      
      var url = '/about/submission/view_new/' + currentSubmissionId + '/';
      
      $.get(url, {}, function(data){
        $('#view-submission-target').hide();
        $('#view-submission-target').html(data);
        $('#view-submission-target').fadeIn();
      });
    }
    return false;
  });
}
