(function($){
  $.recetteRating = function( element ){
    this.$element = $( element );
    this.initialize();
  };

  $.recetteRating.prototype.extend = $.extend;

  $.recetteRating.prototype.extend({ 
    initialize: function(){
      var states = [];
      var id, label, $block;

      this.$element.find( 'label' ).each( function( i, block ){
        $block  = $( block );
        id      = $block.find( 'input' ).attr( 'id' );
        // label   = $block.find( 'label' ).text();

        label   = typeof $block[0].textContent=='undefined' ? $block[0].innerText : $block[0].textContent;
        states.push({ id: id, label: label });
      });

      this.states = states;

      this.prepareDOM();
    },

	setValue: function(ui) {
	  var id        = '#' + this.states[ ui - 1 ].id;
      var $selected = this.$element.find( id ).eq(0);

      this.$labels.find( '.active' ).removeClass( 'active' );
      this.$labels.find( 'li' ).eq( ui - 1 ).addClass( 'active' );
      $selected.attr( 'checked', true );
	},

    prepareDOM: function(){
	  var value = this.$element.find('input:checked').eq(0).val();
	  if (!value) {
	    value = 1;
	  }
      this.$element.hide();
      this.$element.after( '<div class="recette-slider"><ul class="labels"></ul><div class="ruler"><div class="slider"></div></div></div>' );

      this.$container = this.$element.next( '.recette-slider' );
      this.$labels    = this.$container.children( '.labels' );
      this.$ruler     = this.$container.children( '.ruler' );
      this.$slider    = this.$ruler.find( '.slider' );

      this.$slider.slider({ min:1, max: this.states.length, step: 1, slide: $.proxy( this.change, this ), value: value });

      this.$handle = this.$slider.find( 'a' );

      this.$slider.css( 'width', 160 - ( 160 / this.states.length + 15 ));

      $.each( this.states, $.proxy( function( i, state ){
        this.$labels.append( '<li class="' + state.id + '">' + state.label + '</li>' );
      }, this ) );

      this.$labels.find( 'li' ).css( 'width', (160 - 40) / this.states.length );
      this.$labels.find( 'li' ).eq(0).addClass( 'active' ).addClass( 'first' );
      this.$labels.find( 'li' ).eq( this.$labels.find( 'li' ).length - 1 ).addClass( 'last' );
	  
	  this.setValue(value);
    },


    change: function( event, ui ){
	  this.setValue(ui.value);
      // var id        = '#' + this.states[ ui.value - 1 ].id;
      // var $selected = this.$element.find( id ).eq(0);

      // this.$labels.find( '.active' ).removeClass( 'active' );
      // this.$labels.find( 'li' ).eq( ui.value - 1 ).addClass( 'active' );
      // $selected.attr( 'checked', true );
    }
  });


  $.fn.recetteRating = function(){
    return this.each( function(){
      ( new $.recetteRating( this ) );
    });
  };

  // dom ready
  $( function(){
    $( '.pure-right .recette-radios' ).recetteRating();
  });
})(jQuery);
