





function nicheGetLastInitial (lname) {
  var initialAndPeriod = lname;
  if (lname.length > 1) {
    initialAndPeriod = lname.charAt(0)+".";
  }
  return initialAndPeriod;
}

(function( $ ){

  var tmpmarkup = '<div class="comment-container-{{= commentLevel}}" id="comment-{{= id}}"><a class="comment-flag" href="#">flag</a><p class="comment-name">{{= name}}</p><p class="comment-subject">{{= subject}}</p><p class="comment-text">{{= commentText}}</p><p class="comment-timestamp">{{= created}}</p></div>';
  
  var tmpmarkup_niche = '<div class="comment-container-{{= commentLevel}}" id="comment-{{= id}}"><a class="comment-flag" href="#">flag</a><p class="comment-name">{{= firstname}} {{= nicheGetLastInitial(lastname)}}</p><p class="comment-subject">{{= subject}}</p><p class="comment-text">{{= commentText}}</p><p class="comment-timestamp">{{= created}}</p></div>';
  
  $.template("dCommentsDefault", tmpmarkup);
  
  $.template("dCommentsNiche", tmpmarkup_niche);
  
  var defaultProfile = '';
  
  var sendBackURL = encodeURIComponent(location.href);

  var methods = {
    init : function (options) {
      var settings = {
        'profile'           : defaultProfile,
        'formPosition'      : 'top',
        'formTemplate'      : 'default',
        'recaptcha'         : true,
        'recaptchaTheme'    : 'clean',
        'resourceid'        : '0',
        'defaultPagination' : true,
        'loginLinkText'     : '<a href="/content/system/modules/com.dispatch.registration/pages/login.jsp?sendback='+sendBackURL+'#comment">Login</a> or <a href="/content/system/modules/com.dispatch.registration/pages/signup.jsp?sendback='+sendBackURL+'#comment">register</a> to post a comment.',
        'commentsPerPage'	: 50,
        'page'            : 1,
        'getLevel'        : 'public', // flagged, deleted, blocked, unapproved
        'templateName'    : 'dCommentsDefault',
        'logintoview'     : false,
        'logintopost'     : true,
        'commentPrompt'   : 'Place comment here',
        'syndicatePrompt' : 'Post to Facebook or Twitter',
        'commentOrder'    : 'newestlast',
        'successCallback' : '',
        'errorCallback'   : 'userReport',
        'updateCallback'  : false, // provides a callback for when the list of comments is updated/displayed
        'disabled'        : '' // true, [false or ''], nowrite
        
      };
      
      if (settings.logintoview && settings.logintopost) {
        settings.loginLinkText = '<a href="/content/system/modules/com.dispatch.registration/pages/login.jsp?sendback='+sendBackURL+'#comment">Login</a> or <a href="/content/system/modules/com.dispatch.registration/pages/signup.jsp?sendback='+sendBackURL+'#comment">register</a> to view and post comments.';
      }
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      $('a.comment-flag').live('click', function () {
      
        $commetContainer = $(this).parent();
        commentid = $commetContainer.attr('id').substr(8);
        
        $.ajax({
          type: "POST",
          jsonp: null,
            jsonpCallback: null,
          url: '/content/system/modules/com.dispatch.comments/rest/flag',
          data: {
            'c'       : commentid,
            'r'       : 'user'
          },
          dataType: "json",
          success: function(commdata) {
            if ("error" in commdata) {
              $commetContainer.find('.comment-flag').html("<strong>Flag Error</strong>");
            } else {
              $commetContainer.find('.comment-flag').html("<strong>Comment Flagged</strong>");
            }
          }
        });
        
        return false;
        
      });
      
      $('span.dpg-pages a').live('click', function () {
        settings.page = $(this).text();
        $this.dcomments('getComments', settings);
        return false;
      });
      
      return this.each(function() {
        
        if (settings.disabled != 'true') {
        
          $this = $(this);
          
          var $wraps = $('<div class="dcommentswrap"><div class="dcomments"><div id="dcpagination_top" class="dcpagination"></div><div class="comments"></div><div id="dcpagination_bottom" class="dcpagination"></div></div></div>');
          var form_wrap = '<div class="commentForm"></div>';
          
          $this.html($wraps);
          
          if (settings.formPosition == 'top') {
            $('.dcommentswrap').prepend(form_wrap);
          } else {
            $('.dcommentswrap').append(form_wrap);
          }
          
          $this.dcomments('getComments', settings);
          
          commentForm(settings);
        
        }
        
      });
      
    },
    
    getComments : function (options) {
      var settings = {
        'profile'         : defaultProfile,
        'page'            : 1,
        'getLevel'        : 'public', // flagged, deleted, blocked, unapproved
        'resourceid'      : '0',
        'templateName'    : 'dCommentsDefault',
        'commentsPerPage'	: 50,
        'commentOrder'    : 'newestlast',
        'logintoview'     : false
      };
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      var getAction, cmt_tmpl;
      
      var cmt_tmpl_holder = $('#'+settings.templateName);
      if (cmt_tmpl_holder.length) {
        $.template(settings.templateName, cmt_tmpl_holder);
      }
      
      switch(settings.getLevel) {
        case 'flagged':
          getAction = '/content/system/modules/com.dispatch.comments/rest/getflaggedcomments';
          break;
        case 'deleted':
          getAction = '/content/system/modules/com.dispatch.comments/rest/getdeletedcomments';
          break;
        case 'blocked':
          getAction = '/content/system/modules/com.dispatch.comments/rest/getblockedcomments';
          break;
        case 'unapproved':
          getAction = '/content/system/modules/com.dispatch.comments/rest/getunapprovedcomments';
          break;
        case 'approved':
          getAction = '/content/system/modules/com.dispatch.comments/rest/getapprovedcomments';
          break;
        default:
          getAction = '/content/system/modules/com.dispatch.comments/rest/getcomments';
          break;
      }
      
      return this.each(function() {
        
        $.ajax({
          type: "POST",
          url: getAction,
          jsonp: null,
            jsonpCallback: null,
          data: {
            'profile' : settings.profile,
            'r'       : settings.resourceid,
            'p'       : settings.page
          },
          dataType: "json",
          success: function(commdata) {
            if ("error" in commdata) {
              if (settings.updateCallback != false) {
			settings.updateCallback.call(true);
		}
            } else {
              commdata.Comments.reverse();
              updateComments(commdata.Comments, settings.templateName);
              pagination(settings.page, settings.commentsPerPage, settings.resourceid, settings);
              // use the update callback if defined
              if (settings.updateCallback != false) {
			settings.updateCallback.call(true);
		}
            }
          }
        });
      });
      
    },
    
    moderate : function (options) {
      var settings = {
        
      };
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      return this.each(function() {
        
        $this = $(this);
        
      });
      
    },
    
    getCommentCount : function (options) {
      var settings = {
        'resourceid'        : '0'
      };
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      var ccount = 0;
      
      $.ajax({
          type: "POST",
          async: false,
          jsonp: null,
            jsonpCallback: null,
          url: '/content/system/modules/com.dispatch.comments/rest/getcount',
          data: {
            'r'       : settings.resourceid
          },
          dataType: "json",
          success: function(commdata) {
            if ("error" in commdata) {
              //console.log("Comment Load Fail (dcomments): "+commdata.error);
            } else {
              ccount = commdata;
            }
          }
        });
      
      return ccount.count;
      
    }
    
  };
  
  function updateComments (commentDateObject, templateName, loginLink, settings){
  
    var commentHolder = $(".comments");
    commentHolder.html('');
    $.tmpl(templateName, commentDateObject).appendTo('.comments');  
    
  };
  
  function pagination (p, ncpp, rid, settings) {
  	$.ajax({
          type: "POST",
          jsonp: null,
            jsonpCallback: null,
          url: '/content/system/modules/com.dispatch.comments/rest/getcount',
          data: {
            'r'       : rid
          },
          dataType: "json",
          success: function(commdata) {
            if ("error" in commdata) {
              //console.log("Comment Load Fail (dcomments): "+commdata.error);
            } else {
              var np;
              if (commdata.count % ncpp > 0) {
              	np = ((commdata.count - (commdata.count % ncpp)) / ncpp) + 1;
              } else {
              	np = (commdata.count / ncpp);
              }
              
              if (np>1) {
              
                var paginationHTML = '<span class="dc-mc">More comments: </span><a class="dpg-first" href="#">First</a><a class="dpg-prev" href="#">Prev</a><span class="dpg-pages">';
                
                if (np > 10) {
  	              for (tp = 1; tp<=np; tp++) {
  	              	linkclass = "";
  	              	if (tp == p) {
  	              	  linkclass="current-page";
  	              	}
  	                paginationHTML += '<a class="'+linkclass+'" href="#">'+tp+'</a>';
  	              }
                } else {
                	for (tp = 1; tp<=np; tp++) {
  	              	linkclass = "";
  	              	if (tp == p) {
  	              	  linkclass="current-page";
  	              	}
  	              	paginationHTML += '<a class="'+linkclass+'" href="#">'+tp+'</a>';
  	              }
                }
                
                paginationHTML += '</span><a class="dpg-next" href="#">Next</a><a class="dpg-last" href="#">Last</a><div class="clear"></div>';
                
                $('#dcpagination_top').html(paginationHTML);
                $('#dcpagination_bottom').html(paginationHTML);
                
              } else {
                $('.dcpagination').remove();
              }
              
            }
          }
        });
  };
  
  function commentForm (settings) {
  
    var commentformcode = $('<div />').addClass('dpc_comments_form')
              .html('<p id="dcalert">&nbsp;</p><form name="dcomments" class="dcommentForm" action="post" action="#"><ul><li class="commentInstructions"><p class="commentInstructions"></p></li><li class="s"><input type="text" name="s" /><label for="s">Title</label></li><li class="t"><label for="t">Comment</label><br /><textarea name="t"></textarea></li><li class="recaptcha"><div id="recaptcha_div"></div></li><li class="syndicate"><input type="checkbox" name="syndicate" val="yes" /><label for="syndicate">Share your comment</label></li><li class="post"><input type="submit" id="submit-button" name="submit-button" value="Post" /></li><li><a class="dcomments-logout" href="/content/system/modules/com.dispatch.registration/pages/logout.jsp?sendback='+sendBackURL+'">Log Out / Change User</a></li></ul></form>');
    var commentFormHiddenFields = '<input type="hidden" name="profile" value="'+settings.profile+'" /><input type="hidden" name="r" value="'+settings.resourceid+'" /><input type="hidden" name="p" value="" />';
    
    var loginlinkcode = $('<div />').addClass('dpc_comments_form')
              .html(settings.loginLinkText);
              
    var anonhtml = '<li><input type="text" name="s" /><label for="s">Display Name</label></li><li><input type="text" name="e" /><label for="e">Email</label></li>';
    
    if (settings.disabled != 'nowrite') {
      if ($.fn.daccount('isGuest')) {
        $('.commentForm').append(loginlinkcode);
      } else {
        if (settings.formTemplate == 'default') {
          $('.commentForm').append(commentformcode);
        } else {
          $('.commentForm').append('<form name="dcomments" class="dcommentForm" action="post" action="#">'+$('#'+settings.formTemplate).html()+'</form>');
        }
      }
    }
    
    $('.commentForm').find('form').prepend(commentFormHiddenFields);
    $('textarea[name=t]').val(settings.commentPrompt).focus(function(){if($(this).val()==settings.commentPrompt){$(this).val('')}}).blur(function(){if($(this).val()==''){$(this).val(settings.commentPrompt)}});
    $('label[for=syndicate]').text(settings.syndicatePrompt);
    $('a.dcomments-logout').css({
      'text-align':'right',
      'font-size': '11px',
      'font-family': 'arial',
      'color': '#666',
      'text-decoration': 'none',
      'border': 'none',
      'float':'right',
      'margin-top':'-16px'
    });
    //a.dcomments-logout{text-align:right; font-size: 11px; font-family: arial; color: #333; text-decoration: none;}
    
    if (settings.recaptcha) {
      var recaptchaoptions = {
        'theme' : settings.recaptchaTheme,
        'tabindex' : 3
      };
            
      Recaptcha.create('6LdMVsESAAAAAHIkQexP-a3ve5_BJ1exIKON9hT7', "recaptcha_div", recaptchaoptions);
    }
    
    $("form.dcommentForm").submit(function () {
    
      if (($('textarea[name=t]').val() != '') && ($('textarea[name=t]').val() != settings.commentPrompt)) {

        var $form = $('form.dcommentForm');
        
        $('input[type=submit]', $form).attr('disabled', 'disabled');
  
        var commentpost = {};
        commentpost.e = $("input[name=e]", $form).val();
        commentpost.p = $("input[name=p]", $form).val();
        commentpost.m = $("input[name=m]", $form).val();
        commentpost.profile = $("input[name=profile]", $form).val();
        commentpost.r = $("input[name=r]", $form).val();
        commentpost.s = $("input[name=s]", $form).val();
        commentpost.t = $("textarea[name=t]", $form).val();
        if (settings.recaptcha) {
        	commentpost.c = Recaptcha.get_challenge();
        	commentpost.v = Recaptcha.get_response();
        }
        commentpost.m = '';
        
        if ($('input[name=syndicate]').attr('checked')) {
          RPXNOW.init({appId: 'cfockpaeeccahlmhlkmg',
          xdReceiver: '/content/digital/config/rpx_xdcomm.html'});
          
          RPXNOW.loadAndRun(['Social'], function () {
            var activity = new RPXNOW.Social.Activity(
               "Share your comment",
               commentpost.t,
               window.location.href);
            RPXNOW.Social.publishActivity(activity);
          });
        }
        
        $.ajax({
  	        type: "POST",
  	        url: '/content/system/modules/com.dispatch.comments/rest/add',
  	        data: commentpost,
  	        jsonp: null,
            jsonpCallback: null,
  	        dataType: "json",
  	        success: function(commdata) {
  	          if (commdata["error"] || commdata["errors"]) {
  	            
  	            if($.isFunction(settings.errorCallback)){
                  settings.errorCallback.call(commdata);
                }
  	            
  	          } else {
  	            //commdata.Comments.reverse();
  	            //updateComments(commdata.Comments, settings.templateName);
  	            
  	            //<div class="comment-container-{{= commentLevel}}" id="comment-{{= id}}"><a class="comment-flag" href="#">flag</a><p class="comment-name">{{= name}}</p><p class="comment-subject">{{= subject}}</p><p class="comment-text">{{= commentText}}</p><p class="comment-timestamp">{{= created}}</p></div>
  	            var posted = {
  	              'id' : 'new',
  	              'name': 'you',
  	              'firstname' : 'you',
  	              'lastname' : ' ',
  	              'subject' : commentpost.s,
  	              'commentText' : commentpost.t,
  	              'created' : 'just now'
  	            };
  	            
  	            //ccount = $.fn.dcomments('getCommentCount', {'r':commentpost.r});
  	            
  	            //if (ccount <= $('.comments').length) {
                  $.tmpl(settings.templateName, posted).appendTo('.comments');
                //}
                
                userReport('Your comment has been posted.');
  	            
  	            $(".dpc_comments_form form").find(':input').each(function() {
                  switch(this.type) {
                    case 'password':
                    case 'select-multiple':
                    case 'select-one':
                    case 'text':
                    case 'textarea':
                      $(this).val('');
                      break;
                    case 'checkbox':
                    case 'radio':
                      this.checked = false;
                      break;
                  }
                });
                
                $('textarea[name=t]').val(settings.commentPrompt);
                
                if($.isFunction(settings.successCallback)){
                  settings.successCallback.call(commdata);
                }
                
                if (settings.recaptcha) {
                  Recaptcha.create('6LdMVsESAAAAAHIkQexP-a3ve5_BJ1exIKON9hT7', "recaptcha_div", recaptchaoptions);
                }
                
                $('input[type=submit]', $form).removeAttr("disabled");     
                
  	          }
  	        }
  	      });
	      
	    }
      
      return false;
      
    });
    
    function userReport (message) {
      $('#dcalert').css({opacity:0}).text(message).animate({opacity: 1}, 'fast', function () {$('#dcalert').delay(500).animate({opacity: 0}, 'slow'); $('#dcalert').click(function() {$('#dcalert').animate({opacity: 0}, 'fast')})});
    }
    
    return false;
    
  };
  
  $.fn.dcomments = function ( method ) {
    
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist.' );
    }
    
  }
  
})( jQuery );
