// $Id: ajax_betterpoll.js,v 1.1.2.2 2011/01/28 01:32:40 quicksketch Exp $
(function ($) {

/**
 * @file
 * Provides AJAX-voting capabilities to the normal Poll voting form.
 */

/**
 *  Behaviour to add Ajax results support to the polls.
 */
Drupal.behaviors.ajaxResults = function(context) {
  $('a.betterpoll_results:not(.betterpoll_results_processed)',context).addClass('betterpoll_results_processed').each(function() {
    $(this).click(function(){
      var $pollWrapper = $(this).parents('.content, .pane-content, .poll').filter(':first');
      var pat = /[0-9]+/;
      var nid = pat.exec($(this).attr('href'))[0];
      var type =  $(this).attr('rel');
      $.ajax({
          url: '/poll/ajax/results/'+nid+'/'+type,
          dataType: "json",
          success: function(msg){
            $pollWrapper.html(msg.output);
            Drupal.attachBehaviors($pollWrapper);
          }
      });

      return false;
    });
  });
}

/**
 * Behavior to add AJAX voting support to polls.
 */
Drupal.behaviors.ajaxPoll = function(context) {
  $('form.ajax-poll:not(.ajax-poll-processed)', context).addClass('ajax-poll-processed').each(function() {
    // Find the form and poll wrapper items that will be affected.
    var $form = $(this);
    //var $pollWrapper = $form.parents('.content, .poll').filter(':first');
    var $pollWrapper = $form.parents('.content, .pane-content').filter(':first');

    // Find all the settings for this form.
    var url = $form.find('input[name=ajax_url]').val();
    var disabledText = $form.find('input[name=ajax_text]').val();
    var enabledText = $form.find('input.form-submit').val();

    // Set up the options for the AJAX voting mechanism.
    var options = {
      url: url,
      beforeSubmit: function(values, form, options) {
        if (disabledText) {
          $form.find('input.form-submit').attr('disabled', true).val(disabledText);
          $('.form-radio',$form).attr('disabled',true);
        }
      },
      success: function(response, status) {
        // Remove previous messages and re-enable the buttons in case anything
        // goes wrong after this.
        $form.find('input.form-submit').attr('disabled', '').val(enabledText);
        $('.form-radio',$form).attr('disabled','');
        $pollWrapper.find('.messages').remove();

        // On success, replace the poll content with the new content.
        if (response.status) {
          $pollWrapper.html(response.output);
          // The action attribute will be the path of the AJAX Poll menu
          // callback. We fix this here for consistency, even though this will
          // be replaced by the AJAX Poll beforeSubmit() function above.
          $pollWrapper.find('form').attr('action', window.location.pathname);
          Drupal.attachBehaviors($pollWrapper.parent().get(0));
        }

        // Display any new messages.
        if (response.messages) {
          $pollWrapper.prepend(response.messages);
        }
      },
      complete: function(response, status) {
        $form.find('input.form-submit').attr('disabled', '').val(enabledText);

        if (status == 'error' || status == 'parsererror') {
          $form.prepend(Drupal.theme('ajaxPollError'));
        }
      },
      dataType: 'json',
      type: 'POST'
    };
//    $('#edit-vote',$form).removeAttr('disabled');
    $('.form-submit',$form).removeAttr('disabled');
    $('.form-radio',$form).removeAttr('disabled');

    // Add the handlers to the Poll form through the jquery.form.js library.
    $form.ajaxForm(options);
  });
};

/**
 * A fallback error that is shown upon a complete failure.
 *
 * This error is only used when the server cannot return a properly themed
 * error. This is usually because the server is unavailable or because the JSON
 * returned is invalid JSON.
 *
 * The second situation is most frequently caused by modules appending extra
 * information to requests and causing improper JSON. Modules that may do this
 * include Devel, Memcache Admin, and other development modules that output
 * debugging code.
 */
Drupal.theme.prototype.ajaxPollError = function() {
  return '<div class="messages error">A parsing or network error has occurred.</div>';
};

})(jQuery);

