// Basic Setting
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

// Main Form Functions

$(document).ready(function(){

  // Unhide the add-item links
  $('.form-item-add').show();

  // Toggle Hover State for Submit Buttons
  $('input.submit-button') 
      .livequery(function(){ 
        // use the helper function hover to bind a mouseover and mouseout event 
        $(this) 
            .hover(function() { 
                $(this).attr("src", '/images/submit_hover.png'); 
            }, function() { 
                $(this).attr("src", '/images/submit.png'); 
            }); 
      }, function() { 
          // unbind the mouseover and mouseout events 
          $(this) 
              .unbind('mouseover') 
              .unbind('mouseout'); 
      }); 

  // Insert the characters name dynamically into questions
  $('#character_first_name') 
      .livequery('change', function(event) { 
          $('.fieldset-toggle span.question').insertCharacterName($(event.target).val())
          return false; 
      }); 

  // Initially hide the toggleable fieldsets if they aren't checked
  $('.fieldset-toggle').each(function(){
    if (/^toggle_([\w-]+)$/i.test($(this).attr("id"))) {
      var $elem = $('#'+RegExp.$1);
      // Hide them if they aren't selected
      if ( $(":checked", $(this)).val() == 0) 
        $elem.hide();
    }
  })
  
  // Hide/Show the toggleable fieldsets via radio button
  $('.fieldset-toggle :radio').each(function(){
      $(this).click(function(){
        var toggle_elem = $(this).parents('.fieldset-toggle').attr('id').replace(/^toggle_/, ''),
            elem        = $('#'+ toggle_elem)
        if ($(this).val() == 1) {
          elem.slideDown();
          $(':input', elem).each(function() { $(this).removeAttr("disabled") });
        } else if ($(this).val() == 0 && elem.is(':visible')) {
          elem.slideUp();
          // Disable Attributes if hidden
          $(':input', elem).each(function() { $(this).attr("disabled", true) });
        }
      })
  })

  // Observe the gender field and show alternative field if 'other' is selected

  $('#character_sex').change(function(event){
      $this = $(this);
      if ( $this.val() == 'other' ) {
        $('#character_sex_other').parent('.form-item').show().end().removeAttr('disabled');
      } else {
        if ($('#character_sex_other').parent('.form-item:visible'))
          $('#character_sex_other').parent('.form-item').hide().end().attr('disabled', true);
        else 
          return;
      }
  });

});

function insertName(str, name){
  if (replacement = str.match(/(were)\stheir/i) )
    str = str.replace(/(were)\s?their/i, replacement[1][0] + 'as ' + name+"'s");
  if (/^.*their.*$/i.test(str))
    str = str.replace(/their/i, name + "'s");
  if (replacement = str.match(/^.*(for|to|about)\sthem.*$/i) )
    str = str.replace(/(for|to|about)\sthem/i, replacement[1] + ' ' + name);
  if (replacement = str.match(/(were)\sthey/i) )
    str = str.replace(/(were)\s?they/i, replacement[1][0] + 'as ' + name);
  if (/^.*are\sthey.*$/i.test(str))
    str = str.replace(/(are\s)?they/i, 'Is ' + name);
  
  //str = str.replace(/.*them\s.+$/i, name);
  //str = str.replace(/.*they\s.+$/i, name);
  return str;
}

$.fn.insertCharacterName = function(name){

  return this.each(function(){
    var str =  insertName($(this).html(), name)
    $(this).html(str);
  })
}


$.fn.clearForm = function() {
  return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
	  return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
	  this.value = '';
	else if (type == 'checkbox' || type == 'radio')
	  this.checked = false;
	else if (tag == 'select')
	  this.selectedIndex = -1;
  });
};

(function($){
 $.fn.cycleQuestion = function(options) {

  var defaults = {
   nextText: "Next",
   prevText: "Previous",
   ownQuestionId: 0,
   questions: [],
   current_questions: []
  };
  var settings = $.extend(defaults, options);
    
  return this.each(function() {
    var $container = $(this);
    $('.field-question', $container ).each(function(i){
      appendLinks($(this), i)
    })
    cycle('.cycle-field-question');
  });

  function appendLinks($e, i){
      var next_link = '<a id="next-question-' + i + '" class="cycle-field-question" href="#">' + settings.nextText +
                       '<img src="/images/icon_cycle_next.gif" alt="next question"/></a>',
          prev_link = '<a id="prev-question-' + i + '" class="cycle-field-question" href="#">' +
                       '<img src="/images/icon_cycle_prev.gif" alt="previous question"/>'+ settings.prevText + '</a>';
      var own_question = '<a class="cycle-field-question own-question" href="#">Write My Own</a>'
      $e.append(prev_link + ' | ' + next_link + own_question); 
  }

  function cycle(elems){
    var $elems = $(elems);
    $elems.livequery('click',function(event) { 
      event.preventDefault();
      if (event.target.tagName != 'A')
        var $elem = $(event.target).parent();
      else
        var $elem  = $(event.target);

        if ($elem.attr('id') != '')
          var action      = $elem.attr('id').match(/^(\w+)-question-.*$/)[1];

        var question_id = $elem.siblings('span').attr('id'),
            index       = question_id.match(/^question-(\d\d?)/)[1];

        removeUsedQuestions(question_id);

        if (action == 'next')
          index = nextQuestion(parseInt(index));
        else if (action == 'prev')
          index = prevQuestion(parseInt(index));
        else if ($elem.hasClass('own-question'))
          index = setOwnQuestion();
        else
          return false;

        updateDom($elem, index)
    }); 
  }

  function nextQuestion(index){
    var index = index + 1;
    if (index + 1 > settings.current_questions.length) 
      index = 0;
    return index;
  }

  function prevQuestion(index){
    var index = index - 1;
    if (index < 0 ) 
      index = settings.current_questions.length - 1;
    return index;
  }

  function setOwnQuestion(){
    for (i in settings.questions) {
      if (settings.questions[i][0] == settings.ownQuestionId) 
        return i;
    }
  }

  // Remove questions from the array that are already
  // in use elsewhere on the page
  function removeUsedQuestions(elem){
    // Clone the array
    settings.current_questions = settings.questions.concat();
    $('.field-question span').not('#'+elem).each(function(){
      var index  = $(this).attr('id').match(/^question-(\d\d?)/)[1];
      if (index != settings.ownQuestionId) 
        var removed = settings.current_questions.splice(parseInt(index), 1);
    });
    
  }

  function updateDom($link, index){
    var first_name = $('#character_first_name').val(),
        $target    = $('span', $link.parent()),
        question   = settings.current_questions[index];

    // Insert the question if it isn't a root character or there is no firstname
    if ($('#character_first_name').length > 0 && $('#character_first_name').val() != '')
      var question_body = insertName(question[1], $('#character_first_name').val());
    else
      var question_body = question[1]

    $target.html(question_body);

    // Update the span's id containing the question
    $target.attr('id', 'question-' + index);

    // Update the hidden question_id field
    $link.parent().next("input:hidden").val(question[0]);

    // Now hightlight the insertion
    // TODO clean this selector up
    $target.parents('span.field-question').children('span')
      .animate( { backgroundColor: '#ffffa7' }, 300)
      .animate( { backgroundColor: '#f3e8df' }, 600);
    $target.parents('span.field-question').children('span').queue(function () {
      $(this).attr("style", '');
      $(this).dequeue();
    });
  }

 };
})(jQuery);

 // Call on the containing element
 // 'insert' behaves differently if a target is specified.  If a target is
 // given 'beginning' will insert the item before the target, likewise 'end'
 // will insert the item after the target. If a target is omitted, it will
 // insert the item at the top or bottom of the container, respectively
(function($){
 $.fn.insertItem = function(options) {

  var defaults = {
    before: null,                  // A function to run right BEFORE the item is inserted
    after: null,                   // A function to run right AFTER the item is inserted
    item: 'The element to insert', // What gets inserted
    itemClass: 'insertable',       // You need to provide an item class if you want to limit the number of insertables
    itemLimit: null,               // Limit the number of insertables in the container
    insert: 'beginning',           // options: 'beginning' or 'end'
    target: null,                  // A target to insert the item before/after
    trigger: '.form-item-add a',   // What triggers a new insertion
    highlightStart: '#ff2222',     // Start highlight colour for when the insertion limit is reached
    highlightEnd: '#f3e8df'        // End highlight colour for when the insertion limit is reached (generally will be the background colour)
  };
  var settings = $.extend(defaults, options);

  return this.each(function() {
    var $container = $(this);
    // Insert New Form Elements on Click
    $(settings.trigger, $(this))
      .click(function(event){
        // Run anything specified by the before property
        // We do it like this to allow preventing insertion altogether 
        // by returning false
        if ( settings.before ){
          var before = settings.before( settings.target );
          if (!before) return false;
        }
        
        event.preventDefault();
        addItem($container, $(event.target));

        // Run anything specified by the after property
        if ( settings.after ) settings.after( settings.target );
    });

    // Allow inserted elements to be removed
    $('.action-link', $container).livequery('click', function(event){
      event.preventDefault();
      $elem = $(event.target)
        .parents('.remove-parent').parent()
        .fadeOut(300, function(){ $(this).remove(); });
    })
  });

  function addItem($container, $trigger){
    // Highlight the trigger if the limit is reached
    if (settings.itemLimit && $(' .' + settings.itemClass, $container).length >= settings.itemLimit){
      $trigger
        .animate( { backgroundColor: settings.highlightStart }, 200)
        .animate( { backgroundColor: settings.highlightEnd }, 200);
    // Otherwise insert the item at the correct location specified by settings.insert
    } else {
      //If target isn't specified make a guess
      var $target = (settings.target) ? $(settings.target) : $container;

      if ($target.length == 0)
        console.log("Target does not exist!")

      // Based upon whether we have a target or not
      // insert either before/after and fade it in
      if ( settings.insert == 'beginning') {
        if (settings.target) {
          $target.before(unescape(settings.item));
          var $item = $target.prev();
        } else {
          $target.prepend(unescape(settings.item));
          var $item = $( ':first-child', $target );
        }
      } else if ( settings.insert == 'end') {
        if (settings.target) {
          $target.after(unescape(settings.item));
          var $item = $target.next();
        } else {
          $target.append(unescape(settings.item));
          var $item = $( ':last-child', $target );
        }
      }
      $item.hide().fadeIn();
    }
  }

 };
})(jQuery);


