$(document).ready(function(){
  // favorites
  $comments = $('ol#resp-list li');
  if ( $comments.length > 0 )
  {
    $.getJSON('/utilities/get_favorites',function(json){
      var favorites = json.favorites;
    
      // favorite HTML
      $fave = $('<li><a href="#" class="%CLASS%" title="%TITLE%">%TEXT%</a></li>');
      
      // preload the rollover image
      $img = $('<img src="/img/css/icn-fave-processing.gif" />');
      
      $comments.each(function(){
        var $li = $(this);
        var id = $li.attr('id').replace('response-','');
        var $control = $fave.clone();
        var classes = {
          favorite:    'unfave',
          nonfavorite: 'fave'
        };
        var titles = {
          favorite:    'This response is one of your favorites. Undo?',
          nonfavorite: 'Mark this response as one of your favorites'
        };
        var texts = {
          favorite:    'Unfavorite',
          nonfavorite: 'Favorite'
        };
        var state = 'nonfavorite';
        if ( in_array( id, favorites ) )
        {
          state = 'favorite';
        }
        $control.children('a:first').attr({
                                       'class': classes[state],
                                       'title': titles[state]
                                     })
                                    .text(texts[state])
                                    .click(function(e){
          e.preventDefault();
          $this = $(this).css('background','url(/img/css/icn-fave-processing.gif) 0 3px no-repeat');
          $this.fadeTo(
            1500, '1',
            function(){
              if ( state == 'favorite' )
              {$.post('/utilities/unfavorite',{'comment_id':id},function(data){
                  if ( data.type == 'success' )
                  {
                    state = 'nonfavorite';
                    $this.attr({
                            'title': titles[state],
                            'class': classes[state]
                          }).text(texts[state]);
                  }
                  else
                  {alert(data['text']);}
                  $this.blur()
                       .removeAttr('style');
                  fired = false;
                }, 'json');
              }
              else
              {$.post('/utilities/favorite',{'comment_id':id},function(data){
                  if ( data.type == 'success' )
                  {
                    state = 'favorite';
                    $this.attr({
                            'title': titles[state],
                            'class': classes[state]
                          }).text(texts[state]);
                  }
                  else
                  {alert(data['text']);}
                  $this.blur()
                       .removeAttr('style');
                  fired = false;
                }, 'json');
              }
            }               
          );
        });
        $li.find('ul.resp-util').prepend($control);
      });
    });
  }
  
  // comment previews
  var $commentform = $('#respond');
  if ( $commentform.length != 0 )
  {
    var $text = $commentform.find('#post-response');
    $('<fieldset id="add_comment_preview" style="display:none">' +
      '<legend>Preview</legend>' +
      '<div id="add_comment_preview_text"></div></fieldset>').appendTo($commentform);
    var $preview = $('#add_comment_preview_text');
    function updatePreview()
    {
      $preview.html($.textile($text.val()))
              .parents('fieldset:hidden')
              .animate({height:'show',opacity:'show'},'fast', function(){
                if ( typeof(sIFR) != 'undefined' )
                {
                  sIFR.replace( interstatecond, {
                    selector: '#add_comment_preview legend',
                    css: '.sIFR-root { background-color: transparent; color: #e22e37; ' +
                         'font-weight: bold; text-transform: uppercase; }'
                  });
                }
              });
    }
    if( $text.val().length > 0 )
    {updatePreview();}
    $text.keyup(updatePreview);
    
  }
  
  // Tab Interface
  if (typeof(TabInterface) != 'undefined')
  {
    var cabinets = Array();
    var collection = document.getElementsByTagName( '*' );
    var cLen = collection.length;
    for( var i=0; i<cLen; i++ ){
      if( collection[i] &&
          /\s*tabbed\s*/.test( collection[i].className ) ){
        cabinets.push( new TabInterface( collection[i], i ) );
      }
    }
  }
});
