/*-------------------------[ comments ]------------------------------*/
function expandAllComments(level) {
  var attrs;
  var model;
  var parentId;
  var parentCommentId;

  if (!level) {
    level = 1;
  }

  var links = $('.expandLink.closed');

  var timeout = 0;

  if (level <= 3) {
    for (var i = 0; i < links.length; i++) {
      attrs = $(links[i]).attr('id').split('_');
      model = attrs[1];
      parentId = attrs[2];
      parentCommentId = attrs[3];
      canDeleteComments = attrs[4];
      setTimeout("commentExpandThread('"+model+"', "+parentId+", "+parentCommentId+", "+canDeleteComments+");", timeout);
      timeout += 100;
    }
    timeout += 200;
    setTimeout("expandAllComments("+(level + 1)+")", timeout);
    timeout += 100;
  }

  if (level == 1) {
    var linkHtml = $('#expandCollapseSpan').html();
    linkHtml = linkHtml.replace(/expandAllComments/, 'collapseAllComments').replace(/expand\.gif/, 'collapse\.gif').replace(_('Expand all'), _('Collapse all'));
    $('#expandCollapseSpan').html(linkHtml);
  }
}

function collapseAllComments() {
  var attrs;
  var model;
  var parentId;
  var parentCommentId;
  var links = $('.expandLink.opened');
  for (var i = 0; i < links.length; i++) {
    attrs = $(links[i]).attr('id').split('_');
    model = attrs[1];
    parentId = attrs[2];
    parentCommentId = attrs[3];
    canDeleteComments = attrs[4];

    commentCollapseThread(model, parentId, parentCommentId, canDeleteComments);
  }

  var linkHtml = $('#expandCollapseSpan').html();
  linkHtml = linkHtml.replace(/collapseAllComments/, 'expandAllComments').replace(/collapse\.gif/, 'expand\.gif').replace(_('Collapse all'), _('Expand all'));
  $('#expandCollapseSpan').html(linkHtml);
}

function addReplyForm(link) {
  var attrs = $(link).attr('id').split('_');
  var model = attrs[1];
  var parentId = attrs[2];
  var parentCommentId = attrs[3];

  //$('div.preview').remove();

  var formHtml = $('div.comments form').parent().html();
  var action = 'http://'+siteTopDomain+'/comments/add/'+model+'/'+parentId+'/'+parentCommentId;
  var commentTextareaId = 'comment_textarea_'+model+'_'+parentId+'_'+parentCommentId;

  if (formHtml === null) {
    formHtml = '<p class="indention">Please Log in or Sign up to add comment.</p>';
  } else if (formHtml.indexOf('<form') != -1 || formHtml.indexOf('<FORM') != -1) {
    var refererHidden = '<input type="hidden" name="referer" value="'+skatic.url.removeGetParams(skatic.ajax.current)+'">';
    formHtml = '<form method="post" action="'+action+'" class="nopad" style="margin-left:30px;"><h3>'+_('Reply to a comment')+'</h3><div class="clear"></div><textarea name="data[Comment][text]" rows="6" style="width: 97%; margin-bottom: 5px; background:#fff;" id="'+commentTextareaId+'"></textarea><div><input class="button grey small" value="Submit" type="submit"></div>'+refererHidden+'</form>';
  } else if(formHtml.indexOf('to add comment') != -1) {
    alert(_('Please log in or sign up to add comment.'));
    return false;
  } else {
    formHtml = '<p class="indention">'+_('Please log in or sign up to add comment.')+'</p>';
  }

  if ($('form[action="'+action+'"]').length == 0) {
    $('#comment_thread_'+parentCommentId).show();
    $('#comment_thread_'+parentCommentId).append(formHtml);
    $('form[action="'+action+'"]').show();

    //skatic.wysiwyg.addWysiwygToTextarea(commentTextareaId);
    //skatic.wysiwyg.focus(commentTextareaId);
    //$('form[action="'+action+'"] textarea').focus();

  } else if($('#comment_thread_'+parentCommentId).is(':visible') && $('form[action="'+action+'"]').is(':visible'))  {
    $('form[action="'+action+'"]').hide();
  } else {
    $('#comment_thread_'+parentCommentId).show();
    $('form[action="'+action+'"]').show();

    //$('form[action="'+action+'"] textarea').focus();
    //skatic.wysiwyg.focus(commentTextareaId);

  }

  setTimeout(function(){ $('form[action="'+action+'"]').ajaxForm({'success':skatic.ajaxResponse}); }, 100);

  return false;
}

function editCommentForm(link) {
  var attrs = $(link).attr('id').split('_');
  var commentId = attrs[1];

  var formHtml = $('#addCommentFormDiv').html();
  var action = 'http://'+siteTopDomain+'/comments/edit/'+commentId;
  var commentTextareaId = 'comment_textarea_'+commentId;

  /**
   * @deprecated
   * @since ajax get text
   */
//	var commentText = $('span#commentText_'+commentId).html();
//	commentText = commentText.replace(/<(div|DIV) class=[\"]?editedComment[\"]?>.*<\/(div|DIV)>/, '');

  /**
   * @deprecated
   * @since style in nicEdit.js
   */
//	var notClosingDivTag = '[^<]*[^\/]*[^d]*[^i]*[^v]*[^>]*';
//	var re = new RegExp('<(div|DIV) class=[\"]?quote[\"]?>('+notClosingDivTag+')<\/(div|DIV)>', 'ig');
//	commentText = commentText.replace(re, '<div class="quote" style="border:1px dotted black;">$1</div>');

  /**
   * @deprecated
   * @since removeImgOverflowDiv in controller
   */
//	var re2 = new RegExp('<div style="width:[^p]+px;[^o]*overflow-x:[^s]*scroll;">(<img alt="[^"]*" src="[^"]*"[^>]*>)</div>', 'ig');
//	commentText = commentText.replace(re2, '$1');

  var editImgSrc = $(link).find('img').attr('src');
  $(link).find('img').attr('src', '/img/working2.gif');

  $.ajax({
    'url':'/comments/getCommentTextForEdit/'+commentId+'/?call=ajax',
    'type':'GET',
    'cache':false,
    'success':function(response) {
      var commentText = response;
      editCommentAddForm(commentText, commentTextareaId, formHtml, action, commentId);

      $(link).find('img').attr('src', editImgSrc);
    }
  });

  return false;
}

function editCommentAddForm(commentText, commentTextareaId, formHtml, action, commentId) {
  if (formHtml.indexOf('<form') != -1 || formHtml.indexOf('<FORM') != -1) {
    formHtml = '<form method="post" action="'+action+'" class="nopad"><fieldset style="display: none;"><input name="_method" value="POST" type="hidden"></fieldset><h3>Edit comment</h3><div class="clear"></div><textarea name="data[Comment][text]" cols="30" rows="6" style="width: 350px; margin-bottom: 5px;" id="'+commentTextareaId+'">'+commentText+'</textarea><div><input class="btn button" value="Submit" type="submit"></div></form>';
  } else if(formHtml.indexOf('to edit comment') != -1) {
    alert(_('Please log in or sign up to edit comment.'));
    return false;
  } else {
    formHtml = '<p class="indention">'+_('Please log in or sign up to edit comment.')+'</p>';
  }

  if ($('form[action="'+action+'"]').length == 0) {
    //$('#comment_thread_'+parentCommentId).show();
    //$('#comment_thread_'+parentCommentId).append(formHtml);

    $('#editLink_'+commentId).parents('li.comment').append(formHtml);
    $('form[action="'+action+'"]').show();

    setTimeout(function(){
      var form = $('form[action="'+action+'"]');
      form.ajaxForm({'success':skatic.ajaxResponse,'addReferer':false, 'url':form.attr('action')+'?from='+skatic.ajax.current});
    });

//		skatic.wysiwyg.addWysiwygToTextarea(commentTextareaId);
//		skatic.wysiwyg.focus(commentTextareaId);
    //$('form[action="'+action+'"] textarea').focus();

  } else if($('form[action="'+action+'"]').is(':visible'))  {
    $('form[action="'+action+'"]').hide();
  } else {
    //$('#comment_thread_'+parentCommentId).show();
    $('form[action="'+action+'"]').show();

//		skatic.wysiwyg.focus(commentTextareaId);
  }

}

function commentExpandCollapse(link) {
  var attrs = $(link).attr('id').split('_');
  var model = attrs[1];
  var parentId = attrs[2];
  var parentCommentId = attrs[3];
  var canDeleteComments = attrs[4];
  //	var divClass = $('#comment_'+parentCommentId).attr('class');

  if ($('#comment_thread_'+parentCommentId).is(':visible')) {
    commentCollapseThread(model, parentId, parentCommentId, canDeleteComments);
  } else {
    commentExpandThread(model, parentId, parentCommentId, canDeleteComments);
  }
}

function commentExpandThread(model, parentId, parentCommentId, canDeleteComments) {
  var link = $('#expandLink_'+model+'_'+parentId+'_'+parentCommentId+'_'+canDeleteComments);
  var thread = $('#comment_thread_'+parentCommentId).html();

  if ($.browser.msie) {
    var loaded = thread.toLowerCase().trim() != '<div class=clear></div>';
  } else {
    var loaded = thread.indexOf('div id="comment_') != -1;
  }

  if (loaded) {
    $('#comment_thread_'+parentCommentId).show();
//		$('#comment_'+parentCommentId+' .reply_toggle').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
    $(link).find('img').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
    $(link).removeClass('closed').addClass('opened');
  } else {
    $(link).removeClass('closed').addClass('opened');

    var repliesCount = $(link).contents()[1].data.trim();
    var re = /([0-9]+)/;
    repliesCount = re.exec(repliesCount)[1];
    if (repliesCount == 0) {
      return;
    }

    var repliesImg = $(link).children('img');
    if ($(repliesImg).attr('src').indexOf('working2.gif') != -1) { //ajax working
      return;
    }
    $(repliesImg).attr('src', $(repliesImg).attr('src').replace('toggle/closed.gif', 'working2.gif'));

    $.ajax({
      'url':"/comments/expand/"+model+"/"+parentId+"/"+parentCommentId+'/1/'+canDeleteComments+'?call=ajax&locationChanged=false',
      'type':'GET',
      'cache':false,
      'success':function(response){
        $(repliesImg).attr('src', $(repliesImg).attr('src').replace('working2.gif', 'toggle/open.gif'));

        if (response == 'empty') {
          return;
        }

        $('#comment_thread_'+parentCommentId).prepend(response);
        $('#comment_thread_'+parentCommentId).show();

        setTimeout(function(){skatic.ajax.replaceLinksWithAnchors();}, 100);
      },
      'dataType':'html'
    });
  }

//	$(link).unbind('click');
//	$(link).bind('click', function() {
//		commentCollapseThread(link);return false;
//	});
}

function commentCollapseThread(model, parentId, parentCommentId, canDeleteComments) {
  var link = $('#expandLink_'+model+'_'+parentId+'_'+parentCommentId+'_'+canDeleteComments);
  $(link).removeClass('opened').addClass('closed');

  $('#comment_thread_'+parentCommentId).hide();
  $('#comment_'+parentCommentId+' .reply_toggle').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('open', 'closed'));

//	$(link).unbind('click');
//	$(link).bind('click', function() {
//		commentExpandThread(link);return false;
//	});
}

function getCommentPage(link) {
  var attrs = $(link).attr('id').split('_');
  var model = attrs[1];
  var parentId = attrs[2];
  var parentCommentId = attrs[3];
  var page = attrs[4];
  var canDeleteComments = attrs[5];

  $.ajax({
    'url':'/comments/expand/'+model+'/'+parentId+'/'+parentCommentId+'/'+page+'/'+canDeleteComments+'?call=ajax&locationChanged=false',
    'type':'GET',
    'cache':false,
    'dataType':'html',
    'success':function(response){
      $('#getCommentPageDiv_'+model+'_'+parentId+'_'+parentCommentId+'_'+page+'_'+canDeleteComments).replaceWith(response);

      setTimeout(function(){skatic.ajax.replaceLinksWithAnchors();}, 100);
    }
  })
}

function commentPreview(link) {
  var formAction = $(link).parents('form').attr('action');
  formAction = formAction.substr(formAction.indexOf('/add/') + 5);
  if (formAction.charAt(formAction.length - 1) != '/') {
    formAction += '/';
  }
  var text = $(link).parent('p').siblings('textarea').val();

  $.ajax({
    'url':'/comments/preview/'+formAction+'?call=ajax&locationChanged=false',
    'type':'POST',
    'data':{'data[Comment][text]' : text},
    'dataType':'html',
    'cache':false,
    'success':function(response){
      response = '<div class="preview"><h4>Preview:</h4>'+response+'</div>';
      $('div.preview').remove();
      $(link).parents('form').find('h3').after(response);
      //$('#CommentText1').parent('form').parent().find('a.replyLink:last')
    }
  });

}

/*-------------------------------------------------[ wysiwyg ]--------------------------------------*/
skatic.wysiwyg = {
  'editors': {},
  'frames': {},
  'readyTosubmit' : false,
  'cssLoaded' : false
};

skatic.wysiwyg.addWysiwygToTextarea = function(textareaId){
  if (!skatic.wysiwyg.cssLoaded) {
    var fileref=document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", '/css/jquery.wysiwyg.css');
    document.getElementsByTagName("head")[0].appendChild(fileref);

    skatic.wysiwyg.cssLoaded = true;
  }

  $.requireScript(['/js/jquery.wysiwyg.js'], function() {

    var options = {
      'strikeThrough' : { 'visible' : true },
        'underline'     : { 'visible' : true },

        'separator00' : { 'visible' : false },

        'justifyLeft'   : { 'visible' : false },
        'justifyCenter' : { 'visible' : false },
        'justifyRight'  : { 'visible' : false },
        'justifyFull'   : { 'visible' : false },

        'separator01' : { 'visible' : true },

        'indent'  : { 'visible' : true },
        'outdent' : { 'visible' : true },

        'separator02' : { 'visible' : true },

        'subscript'   : { 'visible' : false },
        'superscript' : { 'visible' : false },

        'separator03' : { 'visible' : false },

        'undo' : { 'visible' : false },
        'redo' : { 'visible' : false },

        'separator04' : { 'visible' : false },

        'insertOrderedList'    : { 'visible' : false },
        'insertUnorderedList'  : { 'visible' : true },
        'insertHorizontalRule' : { 'visible' : false },

        'h1mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h1', 'command' : 'heading', 'arguments' : ['h1'], 'tags' : ['h1'], 'tooltip' : "Header 1" },
        'h2mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h2', 'command' : 'heading', 'arguments' : ['h2'], 'tags' : ['h2'], 'tooltip' : "Header 2" },
        'h3mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h3', 'command' : 'heading', 'arguments' : ['h3'], 'tags' : ['h3'], 'tooltip' : "Header 3" },
        'h4mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h4', 'command' : 'heading', 'arguments' : ['h4'], 'tags' : ['h4'], 'tooltip' : "Header 4" },
        'h5mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h5', 'command' : 'heading', 'arguments' : ['h5'], 'tags' : ['h5'], 'tooltip' : "Header 5" },
        'h6mozilla' : { 'visible' : false && $.browser.mozilla, 'className' : 'h6', 'command' : 'heading', 'arguments' : ['h6'], 'tags' : ['h6'], 'tooltip' : "Header 6" },

        'h1' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h1', 'command' : 'formatBlock', 'arguments' : ['<H1>'], 'tags' : ['h1'], 'tooltip' : "Header 1" },
        'h2' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h2', 'command' : 'formatBlock', 'arguments' : ['<H1>'], 'tags' : ['h1'], 'tooltip' : "Header 2" },
        'h3' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h3', 'command' : 'formatBlock', 'arguments' : ['<H3>'], 'tags' : ['h3'], 'tooltip' : "Header 3" },
        'h4' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h4', 'command' : 'formatBlock', 'arguments' : ['<H4>'], 'tags' : ['h4'], 'tooltip' : "Header 4" },
        'h5' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h5', 'command' : 'formatBlock', 'arguments' : ['<H5>'], 'tags' : ['h5'], 'tooltip' : "Header 5" },
        'h6' : { 'visible' : false && !( $.browser.mozilla ), 'className' : 'h6', 'command' : 'formatBlock', 'arguments' : ['<H6>'], 'tags' : ['h6'], 'tooltip' : "Header 6" },

        'separator07' : { 'visible' : false },

        'cut'   : { 'visible' : true },
        'copy'  : { 'visible' : true },
        'paste' : { 'visible' : true }
      };

    $('#'+textareaId).wysiwyg({'controls': options});

    skatic.wysiwyg.editors[textareaId] = $.data($('#'+textareaId)[0], 'wysiwyg');

    //skatic.wysiwyg.frames[textareaId] = (window.frames.length - 1);

  }, {'parallel':false});
};

skatic.wysiwyg.focus = function(textareaId) {
  if (typeof window.frames[skatic.wysiwyg.frames[textareaId]] != "undefined") {
    window.frames[skatic.wysiwyg.frames[textareaId]].focus();
  } else if (typeof window.frames[textareaId] != "undefined") {
    window.frames[textareaId].focus();
  } else {
    $('iframe[name="'+textareaId+'"]').focus();
  }
};

skatic.wysiwyg.addAjaxToFormWithWysiwyg = function(form, textareaId, successFunction) {
  if (document.location.hash != '' && document.location.hash != '#') {
    var currentPage = document.location.hash.replace('#', '');
  } else {
    var currentPage = document.location.pathname;
  }

  var settings = {
    'success':successFunction,
    'addReferer':false,
    'url':form.attr('action')+'?from='+currentPage,
    'beforeSubmit':function(formData, jqForm, options) {
      //skatic.wysiwyg.editors[textareaId].instanceById(textareaId).saveContent();
      if (typeof textareaId == 'string') {
        skatic.wysiwyg.editors[textareaId].saveContent();
      } else { //array
        for (var i = 0; i < textareaId.length; i++) {
          skatic.wysiwyg.editors[textareaId[i]].saveContent();
        }
      }

      var post = {};

      for (var i = 0; i < formData.length; i++) {
        post[formData[i].name] = formData[i].value;
      }
      formData = [];
      for (var onePostVar in post) {
        if (typeof onePostVar == 'undefined' || onePostVar == 'undefined') {
          continue;
        }
        formData.push({
          'name':onePostVar,
          'value':post[onePostVar]
        });
      }

      formData.push({
        'name':$('#textareaId').attr('name'),
        'value':$('#textareaId').val()
      });

      if (!skatic.wysiwyg.readyTosubmit) {
        setTimeout(function(){
          skatic.wysiwyg.readyTosubmit = true;

          form.submit();

          skatic.wysiwyg.readyTosubmit = false;
        }, 100);

        return false;
      } else {
        return true;
      }
    }
  }

  form.ajaxForm(settings);
};

