/*
Copyright (c) 2011, Yubo Dong @ www.jswidget.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the jswidget.com nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,  BUT NOT LIMITED TO,  THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS  FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN  NO  EVENT  SHALL  JSWIDGET.COM BE LIABLE FOR ANY DIRECT, 
INDIRECT,   INCIDENTAL,   SPECIAL,  EXEMPLARY,  OR  CONSEQUENTIAL   DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR  TORT 
(INCLUDING  NEGLIGENCE  OR  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

function EasyComment(){
   this.commentUL = null;
}

EasyComment.prototype.init = function(container,path,moderate,nHeight,bHasSubject, bEmail, bSite, nMaxReply,countPerPage, upload){
   this.moderate = moderate ? 1 : 0;
   this.maxReply = nMaxReply;
   this.currentPage = 0; 
   this.countPerPage = countPerPage; // 0: no paging
   this.upload = upload;
      
   this.path = path;
   
   if ( container ){
      this.container = container;
   }else{
      $("body").append(this.container = $("<div id='ec-page'></div>")[0]);
   }
   if ( nHeight !== null ){
      if ( nHeight === "" || isNaN(nHeight) ){
         $(this.container).css("height","auto");
      }else{
         $(this.container).css("height",nHeight + "px");
      }
   }
   this.hasSubject = (bHasSubject === true)?true:false;
   this.hasEmail   = (bEmail === true)?true:false;
   this.hasSite    = (bSite === true)?true:false;
                this.addCmtForm();
   $(this.container).addClass("ec-comment-pane")
      .append(
         this.totalComment = $("<div class='ec-total'></div>").html("Legyen &Ouml;n az els&#337; hozz&aacute;szol&oacute;!")[0]
      );
   if ( this.countPerPage > 0 ){
      $(this.container).append(this.paging = $("<div class='ec-paging'></div>")[0]);
   }
   
   $(this.container).append(
      this.commentUL = $("<ul></ul>").addClass("ec-comment-list")[0]
   );
   
   
   var _this = this;
   $(this.container).find("button[name=reply]").live("click",function(){
      var id = $(this).attr("id").split("_")[1];
      $(_this.replyFormContainer).find("button[name=submit_reply]")
         .data("reply_id",id);
      
      var pos = $(this).offset(),h = $(this).outerHeight();
      var left = pos.left, top = pos.top + h;
      _this.showReplyForm(left,top);
   });
   

   this.addReplyForm();
   var w = $(this.commentForm).width();
   if ( w > 500 ){
      $(this.commentForm).width(640);
      $(this.replyForm).width(500);
   }
   this.loadComment(0);
};
EasyComment.prototype._getFormFields = function(){
   return   '<fieldset style="margin-right:26px;">'+
            '<legend>Ihr Name:<span title="Required field" style="color:red;">*</span></legend>'+
            '<input type="text" class="komment_type_txt" value="" name="name">'+
            '</fieldset>'+
            (( this.hasSubject )?(
            '<fieldset>'+
            '<legend><span style="color:red;margin-right:5px;"></span>Subject:</legend>'+
            '<input type="text" style="width:100%" value="" name="subject">'+
            '</fieldset>'):"")+

            (( this.hasEmail )?(
            '<fieldset>'+
            '<legend><span style="color:red;margin-right:5px;"></span><span style="">Ihre E-mail Adresse:</span></legend>'+
            '<input type="email" class="komment_type_txt" value="" name="email">'+
            '</fieldset>'):"")+

            (( this.hasSite )?(
            '<fieldset>'+
            '<legend><span style="color:red;margin-right:5px;"></span>Web Site:</legend>'+
            '<input type="url" style="width:100%" value="" name="site">'+
            '</fieldset>'):"")+
             
            '<fieldset>'+
            '<legend>Ihre Antwort:<span title="Required field" style="color:red;margin-right:5px;">*</span></legend>'+
            '<div style="vertical-align:top;">'+
            '<textarea class="komment_area" name="message" type="text"></textarea>'+
            '</div>'+
            '</fieldset>';
};

EasyComment.prototype._getUploadControl = function() {
    if (!this.upload) return null;
    return '<div id="FileUpload">' +
             '<div class="FileUpload_caption">Fügen Sie eine Datei hinzu:</div>' +  
             '<img class="loading" src="files/jscripts/Easy_comment/AjaxFileUploaderV2.1/loading.gif" style="display:none;">' + 
             '<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input" />' +
           '</div>';
};

EasyComment.prototype.addCmtForm = function(){
   var _this = this;
   var arrForm = [
            '<div class="ec-comment-form">',
            '<form method="post" name="ec-comment-form" enctype="multipart/form-data">',
            '<fieldset>',
            '<div class="komment_title">Fügen Sie hier Ihren Text ein!</div>',
            this._getFormFields(),
                     
            '<div style="text-align:right; margin-top: 290px;">',
            this._getUploadControl(),
            '<button name="submit" class="komment_kuldese">Senden</button>&nbsp;&nbsp;&nbsp;',
            '</div>',
            '</fieldset>',
            '</form>',
            '</div>'
   ]; 
   $(this.container).append(arrForm.join(""));
   this.commentForm = $(this.container).find(".ec-comment-form form[name=ec-comment-form]")[0];
   
   $(this.commentForm).find("button[name=submit]").click(function(){    
       
      var name = $.trim($(_this.commentForm).find("input[name=name]").val()),
          message  = $.trim($(_this.commentForm).find("textarea[name=message]").val());              
       if (name === "" ){
          $(_this.commentForm).find("input[name=name]").focus();
          return false;
       }
       if (message === "" ){
          $(_this.commentForm).find("textarea[name=message]").focus();
          return false;
       }          
       
      if (!_this.upload || !$("#fileToUpload").val().length) {
          _this.submitMessage(_this.commentForm,false,"");
      } else {
        $(this).parent().find('.loading').ajaxStart(function(){
            //alert("start");
            $(this).show();
        })
        .ajaxComplete(function(){
            //alert("finish");
            $(this).hide();
        });           

        $.ajaxFileUpload({
            url:'files/jscripts/Easy_comment/AjaxFileUploaderV2.1/uploadattachment.php', 
            secureuri:false,
            fileElementId:'fileToUpload',
            dataType: 'json',
            data: {
                    uploadFolder: _this.upload
                },
            success: function (result, status) {
                if(!result.isSuccessful) {
                    alert(result.errorMessage);
                    return;
                }
                
                //return;
                _this.submitMessage(_this.commentForm,false,"", result.fileID, result.fileName);
            },
            error: function (data, status, e) {
                alert(e);
            }
        });
      }
      
      return false;
   });
   
   return this;
};

EasyComment.prototype.addReplyForm = function(){
   var arrForm = [
      '<div class="ec-comment-form ec-comment-reply-form" style="display:none;">',
      '<div class="close_button"></div>',
      '<form method="post" name="ec-comment-reply-form">',
      '<fieldset>',
      this._getFormFields(),               
      '<p>&nbsp;</p><div class="comment-box-ie" style="text-align:right;position:relative;">',
      '<button name="submit_reply" class="komment_kuldese">&nbsp;&nbsp;&nbsp;&nbsp;Antworten</button>&nbsp;&nbsp;&nbsp;',
      '<button class="komment_kuldese">&nbsp;&nbsp;&nbsp;&nbsp;Abbrechen</button>&nbsp;&nbsp;&nbsp;',      
      '</div>',
      '</fieldset>',
            
      '</form>',
      '</div>'
   ];      
   $("body").append(this.replyFormContainer = $(arrForm.join(""))[0]);

   this.replyForm = $(this.replyFormContainer).find("form[name=ec-comment-reply-form]")[0];
    
   
   var _this = this;
   
   $(this.replyFormContainer).find(".close_button").click(function(){
      _this.hideReplyForm();
      return false;
   });
   $(this.replyFormContainer).find("button[name=submit_reply]").click(function(){
      var id = $(this).data("reply_id");
      _this.submitMessage(_this.replyForm,true,id);
      return false;
   });
   
   return this;
};

EasyComment.prototype._renderComment = function(arrLI,parent_id){
   var i;
   /*if ( !this.commentUL ){
      $(this.paging).after(
         this.commentUL = $("<ul></ul>").addClass("ec-comment-list")[0]
      );
      for ( i = 0; i < arrLI.length; i ++ ){
         $(this.commentUL).append(arrLI[i]);
      }
   }else{*/
      var _this = this;
      for ( i = 0; i < arrLI.length; i ++ ){
         if ( parent_id === "" ){
            $(this.commentUL).prepend(
               arrLI[i]
            );
         }else{
            //look for nested ul
            var ul = $(this.commentUL).find("#" + parent_id + " ul")[0];
            if ( !ul ){
               $(this.commentUL).find("#" + parent_id).append(ul = $("<ul></ul>").addClass("ec-comment-list")[0]);
            }
            $(ul).prepend(arrLI[i]);
         }
      }         
   //}
};

EasyComment.prototype._registerReply = function(btn){
   var _this = this;
   $(btn).live("click",function(){
      var id = $(this).attr("id").split("_")[1];
      $(_this.replyFormContainer).find("button[name=submit_reply]")
         .data("reply_id",id);
      
      var pos = $(this).offset(),h = $(this).outerHeight();
      var left = pos.left, top = pos.top + h;
      _this.showReplyForm(left,top);
   });            
};
EasyComment.prototype.showReplyForm = function(left,top){
      $(this.replyFormContainer)
         .css({"left":left + "px",
               "top":top + "px",
               "opacity":0,
               "display":""})
         .animate({"opacity":1},300);
};
EasyComment.prototype.hideReplyForm = function(){
      $(this.replyFormContainer)
         .animate({"opacity":0},300,function(){$(this).css("display","none");});
};

EasyComment.prototype.submitMessage = function(form,bReply,parent_id, newCommentID, attachment){
   var data = {
      flag     : "1",
      domid    : $(this.container).attr("id"),
      title    : document.title,
      id       : bReply ? parent_id : "",
      newCommentID : newCommentID,
      attachment: attachment,
      uploadFolder : this.upload,
      moderate : this.moderate,
      max      : this.maxReply,
      path     : this.path,
      url      : this.getPageURL(),
      name     : $.trim($(form).find("input[name=name]").val()),
      subject  : (this.hasSubject)?$.trim($(form).find("input[name=subject]").val()):"",
      email    : (this.hasEmail)?$.trim($(form).find("input[name=email]").val()):"",
      site     : (this.hasSite)?$.trim($(form).find("input[name=site]").val()):"",
      message  : $.trim($(form).find("textarea[name=message]").val())
   };   
   if ( data.name === "" ){
      $(form).find("input[name=name]").focus();
      return;
   }
   if ( data.message === "" ){
      $(form).find("textarea[name=message]").focus();
      return;
   }
   var _this = this;
   $.ajax({
      url:this.path + "ec-comment.php",
      data:data,
      dataType:"json",
      type:"POST",
      cache:false,
      success:function(data){
         if ( data ){
            _this._renderComment([data.comment],parent_id);
            var tc = $(_this.totalComment).data('total-comment');
            if ( parent_id === "" ){
               tc ++;
            }else{
               _this.hideReplyForm();
            }
            _this.showTotalComment(tc);
         }            
      },
      error:function(s){
      }
   });
};
EasyComment.prototype.getPageURL = function(){
   var sURL = location.href;
   //
   // to avoid confusion
   //
   sURL = sURL.replace(/www\./,"");
   
   if ( sURL.indexOf("#") != -1 ){
      var s = sURL.split("#");
      sURL = s[0];
   }
   if ( sURL.indexOf("?") != -1 ){
      var s = sURL.split("?");
      sURL = s[0];
   }
   return sURL;
};
EasyComment.prototype.loadComment = function(pageNo){
   var data = {
      flag      : "2",
      max       : this.maxReply,
      domid     : $(this.container).attr("id"),
      url       : this.getPageURL(),
      pageno    : (pageNo)?pageNo:0,
      pagecount : this.countPerPage,
      uploadFolder : this.upload
   };
   this.currentPage = pageNo;
   
   var _this = this;
   $.ajax({
      url:this.path + "ec-comment.php",
      data:data,
      dataType:"json",
      type:"POST",
      cache:false,
      success:function(data){
         if ( data ){
            if ( data.total_comment > 0 ){
               $(_this.commentUL).empty();
               _this._renderComment(data.comments,"");
            }
            _this.showTotalComment(data.total_comment);
            _this.showPaging(data.total_comment);
         }            
      },
      error:function(s){
      }
   });
};
EasyComment.prototype.showTotalComment = function(nTotal){
   var sHTML = " Hozz&aacute;sz&oacute;l&aacute;sok sz&aacute;ma: " + nTotal + " darab  ";
   
   $(this.totalComment).html(sHTML)
      .data("total-comment",nTotal);
};
EasyComment.prototype.showPaging = function(nTotal){
   if ( this.countPerPage > 0 && nTotal > this.countPerPage ){
      $(this.paging).empty();
      var total_page = Math.ceil(nTotal / this.countPerPage);
      var _this = this;
      var nRest = nTotal - (this.currentPage+1) * this.countPerPage;
      var sNext = "";
      if ( nRest > this.countPerPage ){
         sNext = "Next " + this.countPerPage + " comments";
      }else{
         if ( nRest < 0 ){nRest = this.countPerPage;}
         sNext = "Next " + nRest + " comments";
      }
      //if ( this.currentPage != 0 ){
         $(this.paging)
            .append(
               $("<button></button>").html("Previous " + this.countPerPage + " comments")
                  .data("page_no",this.currentPage)
                  .attr("disabled",(this.currentPage == 0))
                  .click(function(){
                     _this.loadComment($(this).data("page_no")-1);return false;
                  })
            );
      //}
      
      //if ( this.currentPage < total_page - 1 ){
            $(this.paging)
               .append(
                  $("<button></button>").html(sNext)
                  .data("page_no",this.currentPage)
                  .attr("disabled",(this.currentPage == total_page - 1))
                  .click(function(){
                     _this.loadComment($(this).data("page_no")+1);return false;
                  })
               );
      //}
   }
};

(function($){
   $.fn.EasyComment = function(options){
      var settings = {
         path         : "/easy-comment/",
         maxReply     : 5,
         moderate     : false,
         height       : null,
         hasSubject   : false,
         hasEmail     : false,
         hasSite      : false,
         countPerPage : 10,
         upload       : false
      };
      if ( options ) { 
         $.extend( settings, options );
      }
      addStyle(settings.path);
      
      if (settings.upload) {
          settings.upload = $(this).attr("id") ? $(this).attr("id") : null;
      }

      return this.each(function(){                  
         var cp = new EasyComment()
            .init(
              this,
              settings.path,
              settings.moderate,
              settings.height,
              settings.hasSubject,
              settings.hasEmail,
              settings.hasSite,
              settings.maxReply,
              settings.countPerPage,
              settings.upload
            );
      });
      function addStyle(path){
         if ( $.fn.EasyComment.StyleReady ){
            return;
         }
         $.fn.EasyComment.StyleReady = true;
         var arrStyle = [
            "<style type='text/css'>",      


    

			
            ".ec-comment-reply{background-color:#f1f1f1; position:relative; min-height:48px; min-width:48px; padding:15px 15px 15px 120px; margin:0 15px 15px -10px; -khtml-border-radius:10px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border:2px solid #ccc; font-size:12px Verdana, Arial}",
            ".ec-comment-pane{position:relative; padding-left:6px; margin:5px 0; overflow:auto}",
            ".ec-comment-pane div.ec-total{font:16px Verdana, Arial; color:#996633; height:24px; line-height:25px; margin: -40px 0 20px 0; }",
            ".ec-comment-pane div.ec-paging{height:30px; line-height:30px;text-align:right;}",
            ".ec-comment-pane div.ec-paging>button{font:14px Verdana, Arial; height:30px; line-height:30px; margin-right:10px;}",
            ".ec-comment-pane ul.ec-comment-list{ position:relative; font-family:'Verdana', Arial; padding:15px 0px 15px 100px; color:#996633; font-size:14px; list-style-type:none; }",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment{color:#666666; font-family:Verdana,Arial; font-size:13px; letter-spacing:0.2pt; line-height:18px; background-image: -moz-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1));	background-image: -o-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1));background-image: -webkit-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1)); -pie-background: linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1)); position:relative; min-height:48px; min-width:48px; padding:15px 15px 15px 120px; margin:0 5px 15px -100px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border:2px solid #ccc; float:right; width:535px;}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment:last-child{border:2px solid #ccc; padding-bottom:5px; margin-top:25px; float:left; display:block;}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment button{font:12px Verdana, Arial; font-weight:bold; text-decoration: none;}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment a, ",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment .author{font-weight:normal; color:#336699; font-family:Verdana,Arial; font-size:22px; font-weight:normal; line-height:27px; text-decoration:none}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment a:hover{text-decoration:underline}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment div.avatar{position:absolute; top:0px; left:10px; height:45px; border:none; margin-top:10px; margin-left:15px; border-radius:4px; text-overflow:ellipsis; background:url(" + path + "ec-comment.png) no-repeat top left; width:64px;}",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment span.user-name{font-weight:normal; margin-right:0.5em; text-overflow:ellipsis}",	
            ".ec-comment-pane ul.ec-comment-list li.ec-comment li.ec-comment {background-color:#f9f9f9; width: 400px; }",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment li.ec-comment button {display: none; }",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment li.ec-comment:first-child {margin-top: 20px; }",
            ".ec-comment-pane ul.ec-comment-list li.ec-comment li.ec-comment:last-child {margin: 0 0 0 -110px; }",            
            ".ec-comment-pane ul.ec-comment-list li.ec-comment span.comment-time{font-size:12px; color:#999; line-height:25px; text-overflow:ellipsis,}",
            ".ec-comment-form{ font:14px Verdana, Arial;}",
            ".ec-comment-form form{ margin:0; padding:0;}",
            ".ec-comment-form form input, .ec-comment-form form textarea, .ec-comment-form form button{ font:12px Verdana, Arial; font-weight:bold; text-decoration: none;}",
            ".ec-comment-form fieldset{ display:block; width:640px; margin:15px 0 0 0px; padding: 15px; border:2px solid #d1d1d1; background-image: -moz-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1)); background-image: -o-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1)); background-image: -webkit-linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1));-pie-background: linear-gradient(top, rgba(250,250,250,1), rgba(240,240,240,1));z-index: 1000;}",
            ".ec-comment-form fieldset legend {background:#f1f1f1;  padding:5px 2px; color:#336699;  -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; }",
            ".ec-comment-form .title { color:#444;  line-height:40px; width:300px; align:center; margin:0px 0 0 0;}",
            ".ec-comment-form fieldset { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;}",
            ".ec-comment-form fieldset fieldset{ border:none;  background:none;  filter:none; float:left; padding:0; width:40%; margin-top:15px; margin-left:25px;}",
            ".ec-comment-form fieldset fieldset legend{ background:none;  border:none;  filter:none;}",
            ".ec-comment-reply-form{ position:absolute; left:-500px; top:0px; height:400px; margin-left: -527px;}",
            ".ec-comment-reply-form div.close_button{ position:absolute; left:555px;  right:-18px; top:-18px; width:36px; height:36px;  background:url(" + path + "ec-close_box.png) no-repeat;  cursor:pointer}",
            ".ec-comment-form{ display: none; }",    
            ".ec-comment-form.ec-comment-reply-form{ display: block; }", 
            "#fileToUpload{ border:2px solid #d1d1d1; margin:20px 24px 0 0;  }",  
            ".FileUpload_caption{ float: left; margin:20px 24px 0 30px;  }",                                 
            "</style>"
         ];
         $(arrStyle.join("")).appendTo("head");
      }
   };
})(jQuery);

