/**

    jquery.pollajax.js
    @author Arjan Widlak
    @version 1.0

    Poll a url with an ajax call until a condition is met.
 
    SYNOPSIS
 
        <tag class="function replace">
            <a href="/url/to/check/this/value?id=n">
                I need to be checked.
            </a>
        </tag>
        <tag class="function replaced hide">
            Everything is fine now
        </tag>
     
        <script type="text/javascript">
     
            $(document).ready(function() {
                $('.function.replace').pollajax();
            } );
         
        </script>
 
    DESCRIPTION
 
    This plugin will take all elements with the selected classes -
    in this case "function replace". It expects to find:
 
    a) a sibling class with classes "function replaced", or anything else
    b) a link within the selected class
 
    It will search for the first url within it and take that url as
    url to poll. The response will be considered a success if a json string is
    returned that contains { is_ready : 1 } among possibly other things. If the
    response is successfull, the tag with class 'function replace' will be
    hidden and the tag with class 'function replaced' will be shown. If the
    response is not successfull, the url is polled again.
 
    This plugin has some default options that can be overridden:
    - the classes to search for, a you usually do in jQuery
    - the url to poll, via the HTML
    - the time between requests, by passing a hash to the plugin
    - the success condition, also by passing a hash to the plugin
 
    The plugin is chainable:
 
        $('.function.replace').pollajax().css('color', 'red' );
     
    The plugin accepts one or more arguments as a hash:
 
        $('.function.replace').pollajax( { poll_interval : 1000 } );
        $('.function.replace').pollajax( {
            poll_interval       : 1000,
            success_condition   : "is_ready == 1",
            replace_class       : "function replaced"
        } );
 
    ARGUMENTS
 
    poll_interval
 
    This value can never by lower than 1000 ( 1 second ). The script will poll
    the url with an interval of this argument.
 
    success_condition
 
    It is expected that the json that is returned changes over time. When should
    we stop polling? The default is "is_ready : 1" for example in a json string
    like below, it will poll until is_ready changes.
 
    {
        is_waiting      : 0,
        is_ready        : 0,
        is_processing   : 0,
    }
 
    replace_class
 
    The name of the class to replace the content with on success. The default is
    "function replaced" but it can be anything, as long as it is a sibling of
    the searched class.

*/
/******************************************************************************/
// This is an anonymous function, referenced to by parantheses
// That gets passed the jQuery object - see at the end - as the parameter $.
(function( $ ){

  // Add a class to the jQuery.fn object
  // Names parameters to receive
  $.fn.pollajax = function( options ) {
    // Within this scope 'this' is the selected DOM object
     
    return this.each(function( ) {
      // Here this refers to a DOM object, use it like this.style.border
      // It seems undefined, because it is a self-reference.
      // And $(this) or jQuery(this) referes to the jQuery object, to $.fn
      // I could rename it to $self = jQuery(this)
   
      var $self           = jQuery( this );
      options             = options || { };

      // Part of the defaults
      $self.settings        = {
        replace_class     : '.function.replaced',
        poll_interval     : 5000,
        condition         : 'is_ready == 1'
      }
   
      //
      $self.replace_class = $self.siblings( options['replace_class'] ); // cache elements in jQuery object
      $self.url           = $self.find( 'a' ).attr( 'href' );
   
      // Override defaults with options
      if ( options ) {
        // Make sure we don't bang on the server
        if ( options['poll_interval'] < 1000 ) {
          options['poll_interval'] = 1000;
        }
        $.extend( $self.settings, options );
      }
   
      // Append the condition to the json object
      $self.settings['condition'] = 'data.'+$self.settings['condition'];
         
      // Let's do the actual work
      var i = setInterval( function ()
      {
        $.ajax({
            type: 'GET',
            url: $self.url,
            success: function( data, textStatus, jqXHR )
              {
                if ( eval( $self.settings['condition'] ) ) {
                  $self.addClass('hide');
                  $self.replace_class.removeClass('hide');
                  clearInterval(i);
                }
                else {
                  $self.hide("slow");
                  $self.show("slow");
                }
              },
           
            error: function( data, textStatus, jqXHR )
            {
              alert( $.dump( data ) );
              $self.prepend( 'failure...please click link: ' );
              clearInterval(i);
            },
            dataType: 'json'
        });
      }, $self.settings['poll_interval'] );

    });

 
  }
})( jQuery );


$(document).ready(function()
  {
    $('.function.replace').pollajax( );
  }
);


