var comment = {};
(function($){

  function commenter(o){
    this.ID = 'comment_' + new Date().getTime();
    this.showing = false;
    this.minimized = false;
    this.working = false;
    this._mobile = navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i); 
  }
  
  commenter.prototype = {
    init : function(){
      var self = this;
      this._elem = $("#comment_dialog");
      this._name = this._elem.find("#comment_name");
      this._comment = this._elem.find("#comment_text");
      this._submitBtn = this._elem.find("#comment-dlg-submit");
      this._cancelBtn = this._elem.find("#comment-dlg-cancel");
      this._elem.find(".btn-minmax").click(function(){
        if (self.minimized) 
          self.maximize() 
        else 
          self.minimize();
        return false;
      });
      this._elem.find(".btn-close").click(function(){
        self.close();
        return false;
      });
      this._createButton(this._submitBtn,function(){
        self.submit();
      });
      this._createButton(this._cancelBtn,function(){
        self.close();
      });
      this._elem.find(".header").click(function(){
        self.maximize();
      });
    },
    show : function(){
      if (!this.showing){
          //this._elem.slideDown('fast');
          this._show( this._elem );
          //this._elem.show();
          this.showing = true;
          if (this._name.val() == '')
            this._name.focus();
          else
            this._comment.focus();
      } else
        this.maximize();
    },
    close : function(){
      if (this.showing){
          //this._elem.slideUp('fast');
          this._hide( this._elem );
          this.showing = false;
          this.maximize();
          this._comment.val('');
          this._error().hide();
          this._status().hide();
          this.working = false;
      }
      
    },
    submit : function(){
      if (this._name.val() == '' || this._comment.val() == ''){
        this._error().show();
        return;
      }
      var self = this;
      this._error().hide();
      this._status().show();
      this.working = true;
      $.ajax({
          url     : "/includes/comments.ajax.php",
          type    : "POST",
          data    : {
              id      : $("#post-entry").data('id'),
              name    : this._name.val(),
              text    : this._comment.val()
          },
          dataType  : "json",
          success   : function(r){
            if (r && r.success){
              $("#post-comments-contents").append(r.output);
              $(".post-comment-count").html(r.comment_count);            
            } else {
              $.prompts.alert("Our apologies: an error occurred while trying to process your request","Error");
            }
          },
          error     : function(){ 
            $.prompts.alert("Our apologies: an error occurred while trying to process your request","Error");
          },
          complete  : function(){
            self.close();
          }
      })
    },
    minimize : function(){
      if (!this.minimized){
        this._hide( this._elem.find(".contents") );
        //this._elem.find(".contents").slideUp("fast");
        this._elem.find(".icon-minmax").removeClass("minimize").addClass("maximize");      
        this.minimized = true;
      }      
    },
    maximize : function(){
      if (this.minimized){
        this._show( this._elem.find(".contents") );
        //this._elem.find(".contents").slideDown("fast");
        this._elem.find(".icon-minmax").removeClass("maximize").addClass("minimize");
        this.minimized = false;
      }      
    },
    _show : function(elem){
      if (this._mobile)
        elem.show();
      else
        elem.slideDown("fast");
    },
    _hide : function(elem){
      if (this._mobile)
        elem.hide();
      else
        elem.slideUp("fast");
    }, 
    _createButton : function(elem,options){
        var o = {className:'comment_button',hoverClass:'',pushedClass:'',addClasses:'',onClick:function(e){}};
        if (typeof options == 'function')
          o.onClick = options
        else
          $.extend(o,options);
        var h = o.hoverClass == '' ? o.className + '-hover' : o.hoverClass,
            d = o.pushedClass == '' ? o.className + '-down' : o.pushedClass,
            self = this;
        elem
          .addClass(o.className)
          .addClass(o.addClasses)
          .hover(function(){$(this).addClass(h)},function(){$(this).removeClass(h).removeClass(d)})
          .mousedown(function(){$(this).addClass(d)})
          .mouseup(function(){$(this).removeClass(d)})
          .click(function(){o.onClick(elem);return false;});
    },
    _error : function(){
      return this._elem.find("#comment_error");
    },
    _status : function(){
      return this._elem.find("#comment_working");
    }
  }

  comment = new commenter();

})(jQuery);


$(function(){
  // setup the Archives TreeViewer
  $('a','#blog-archive').live('click',function(){
    // determine if it needs to lazy load
    var a = $(this), 
        li = a.closest('li');
    if (!a.hasClass('blogpost')){
      var ul = li.children('ul');
      if (a.hasClass('isOpen')){
          ul.slideUp('fast');
          a.removeClass('isOpen icon-folderopen').addClass('icon-folderclosed');
      } else{
          if (ul.length==0){
              a.addClass('loading');
              var o = li.data('options');
              // retrieve the information from the server
              //alert(a.attr('href'));
              $.ajax({
                  type          : 'POST',
                  url           : '/js/blogs.ajax.php',
                  data          : {Y:o.y,M:o.m},
                  dataType      : 'json',
                  success       : function(r){
                    if (r.length > 0) {
                      var u = $('<ul>').appendTo(li).hide();
                      if (o.m == 0) {
                          for (var i=0;i<r.length;i++){
                            var l = $('<li>')
                                        .data('options',{y:o.y,m:r[i].month})
                                        .appendTo(u);
                            $('<a>')
                                .addClass('icon-folderclosed')
                                .attr('href','#')
                                .html(r[i].monthName)
                                .appendTo(l);
                          }
                      } else {
                          for (var i=0;i<r.length;i++){
                            var l = $('<li>').appendTo(u);
                            $('<a>')
                                .addClass('icon-blogpost blogpost')
                                .attr('href',r[i].link)
                                .html(r[i].name)
                                .appendTo(l);
                          }
                      }
                    }
                    //li.append(r);
                    //alert(r.length);
                    a.addClass('isOpen');
                    u.slideDown();
                    a.removeClass('loading icon-folderclosed').addClass('icon-folderopen');
                  }
              });
          } else {
              ul.slideDown();
              a.addClass('isOpen icon-folderopen').removeClass('icon-folderclosed');
          }
      }
      return false;
    }        
  });

})
