$(document).ready(function() {
  
  var $comment = $('#comment'), commentVal = '';
  if ( $('ol.commentlist li').length > 120 ) return;
  
  var updatePreview = function(txtarea) {
    commentVal = $(txtarea).val();
    commentVal = commentVal.replace(/\n\n+/g, '<br /><br />').replace(/\n/g, "<br />");
    $('#live-preview').html( commentVal );
  },
  
  markitupSettings = {	
  	onShiftEnter:  	{keepDefault:false, replaceWith:'<br />\n'},
  	onCtrlEnter:  	{keepDefault:false, openWith:'\n<p>', closeWith:'</p>'},
    // onTab:       {keepDefault:false, replaceWith:'  '},
    afterInsert:  function() {updatePreview(document.getElementById('comment'));},
  	markupSet:  [ 	
  		{name:'Bold', key:'B', openWith:'(!(<strong>|!|<b>)!)', closeWith:'(!(</strong>|!|</b>)!)' },
  		{name:'Italic', key:'I', openWith:'(!(<em>|!|<i>)!)', closeWith:'(!(</em>|!|</i>)!)'  },
  		{name:'Pre/Code', key:'P', openWith:'<pre><code>', closeWith:'\n</code></pre>' },
  		{name:'Code', key:'C', openWith:'<code>', closeWith:'</code>' },
  		{separator:'---------------' },
  		{name:'Link', key:'L', openWith:'<a href="[![Link:!:http://]!]"(!( title="[![Title]!]")!)>', closeWith:'</a>', placeHolder:'Your text to link...' },
  		{separator:'---------------' },
  		{	name:'Encode Html special chars',
  			className:"encodechars", 
  			replaceWith:function(markItUp) { 
  				container = document.createElement('div');
  				container.appendChild(document.createTextNode(markItUp.selection));
  				return container.innerHTML; 
  			}
  		}
  	]
  };
    $('#comment').markItUp(markitupSettings);
    $comment.bind('focus',function() {
      if (!$('#preview-box').length) {
        $('#scomment').after(['<div id="preview-box">',
          '<div class="comment-by">',
          'Live Comment Preview',
          '</div>',
          '<div id="live-preview"></div>',
          '</div>'].join('')
        );
      } else {
        updatePreview(this);
      }
    }).keyup(function() {
      updatePreview(this);
    });
});
