if (!window.G1) { var G1 = {}; }

// http://gameone.local/comments?commentable_id=457909&commentable_type=Post&page=1

/**
 * Adds ajaxified comment
 * funktionallity is pagination and adding new comments
 * @class
 */
 
G1.CommentsForm = {
  _initialized: false,

  // default option
  options: {},

  // merged options object
  _options: {},

  // Extenting the default options with user options.
  setOptions: function (options) {
    options = $.extend(this.options, options || {});
  },

  /**
  * @constructor
  * @public
  */
  init: function(options) {
    // set the options
    options = $.extend(this._options, this.options || {});    
    this.setOptions(options);		

    // check for existence, if not exit.
    var test = [];
    test.push($('#commentform')[0]);
    if (test.length === 0) { return; }

    this._initObserver();
    this._initialized = true; // Mark as initialized		
  },
  
  /**
  * adds the observer for the comments form
  * @private
  */
  _initObserver: function () {
    $('form#commentform').submit(function () {
      G1.CommentsForm._formSubmit(this);
      return false;
    });
    
    $('.comments_pagination a').live("click", function(event){
      G1.CommentsForm._paginate($(this), this);
      return false;
    });  
  },

  /**
  * paginate
  * @private
  */
  _paginate: function(link, element){
    var $link = link;
    var fallbackUrl = element.href;
    var url = "/comments.js"+
                "?commentable_id="+$('#commentable_id').val() +
                "&commentable_type="+$('#commentable_type').val() +
                "&page="+jQuery.url.setUrl(fallbackUrl).param("page");
    
    
    $.ajax({
      type: "GET",
      url: url,
      dataType: "text",
      beforeSend: function(){
        $('.comments_pagination').hide();
        $('#comments_wrapper').addClass('loading');
        $('#respond').hide();
      },
      error: function(respondText){
        document.location = fallbackUrl;
      },
      success: function(respondText){
        $('#comments_wrapper').replaceWith(respondText);
        $('#respond').show();
        FB.XFBML.parse();
				$('.comments .comment, ol.posts li.post').reply();
      }      
    });
  },
  

  /**
  * _formSubmit
  * submit the comment form
  * @private
  */
  _formSubmit: function (formElement) {
    
    //console.log(formElement);
    
    $.ajax({
      data: $.param($(formElement).serializeArray()),
      dataType: 'text/html', 
      type: 'post', 
      url: $(formElement).attr('action'),
      error: function () {
          alert('Error, pleaser reload the browser.');
      },
      beforeSend: function (XMLHttpRequest) {
          $(formElement).addClass('loading');
      },
      success: function (data, textStatus) {
          if (jQuery.url.param('page') == undefined || jQuery.url.param('page') == 1) {
              var html = $(data);

              // wenn error messages vorhanden!
              if ( html.find('input').length > 0 ) {
                  $('#respond form').replaceWith(data);
                  G1.CommentsForm._initObserver();
              } else {
                  if ($('#comments_list').length) {
                      $('#comments_list').prepend(data);
                  } else { // if no comments available
                      $('#respond').before('<ol id="comments_list" class="comments clear">' + data + '</ol>');
                  }

                  // show dialog
                  $('.dialog').dialog('open');
                  $('.dialog .tab').hide();
                  $('#flash_message').show();
                  $('.dialog').addClass('notice');

                  // check if the user is on a comment subPage
                  if (jQuery.url.param('page') == undefined || jQuery.url.param('page') == 1) {
                      $('#flash_message').html("<p>Dein Kommentar wurde gespeichert.</p>");
                  } else {
                      $('#flash_message').html("<p>Dein Kommentar wurde auf der <strong>ersten Seite</strong> der Kommentarliste gespeichert.</p>");
                  }

                  // no comments are allowed for 10 sec.
                  $('#comment_message').val('Bitte warte 10 Sekunden bis zu deinem nächsten Kommentar');
                  $('#commentform textarea, #commentform input').attr('disabled', 'disabled');
                  setTimeout(function () {
                      $('#comment_message').val('Jetzt kannst du!').end().focus().select();
                      $('#commentform textarea, #commentform input').removeAttr('disabled');
                  }, 10000);
              }
    
              if ($('.dialog .reply_to_user').css('display') === 'block') {
                  $('.dialog').dialog('close');
              }

              // html.find('.rating').ajaxified_rating();          
							if (FB.XFBML){ FB.XFBML.parse(); }
          }
      },
      complete: function (XMLHttpRequest, textStatus) {        
          $(formElement).removeClass('loading');        
      }
    });
  }
};

$.extend(G1, G1.CommentsForm);