$(document).ready(function() {
 	$('#attach-wrapper').click(function (e) {
		if ((e.target.className == 'add_node_attachment') || (e.target.className == 'add_comment_attachment')){
			if (e.target.className == 'add_node_attachment'){
				txtArea = document.getElementById("edit-body");
			}
			else{
				txtArea = document.getElementById("edit-comment");
			}
			imgValue = "<img src='" + $(e.target).parents('tr').find('div[class^=description]').text() + "' alt='' />";
			if (document.selection) {   
				txtArea.focus();   
			  sel = document.selection.createRange();   
			  sel.text = imgValue;   
			}   
			else 
				if (txtArea.selectionStart || txtArea.selectionStart == '0') {   
					var startPos = txtArea.selectionStart;   
				  var endPos = txtArea.selectionEnd;   
				  txtArea.value = txtArea.value.substring(0, startPos) + imgValue + txtArea.value.substring(endPos, txtArea.value.length);   
			  }   
			  else {   
			    txtArea.value += imgValue;   
			  }   
		}
		return true;
	});
  $(".node_quote").click( function() {
		document.getElementById('comment-form').comment.value += '<quote="' + getNodeAuthor(getNodeType(this), this) + '">' + getSelText() + "</quote>";
    return false;
	});
	$(".node_author").click( function() {
    document.getElementById('comment-form').comment.value += '<strong>' + getNodeAuthor(getNodeType(this), this) + '</strong>';
    return false;
	});
});


function getSelText(){
	var txt = '';
  if (window.getSelection){
  	txt = window.getSelection();
  }
  	else if (document.getSelection){
    	txt = document.getSelection();
    }
    else 
    		if (document.selection){
        	txt = document.selection.createRange().text;
        }
	return txt;
}


function getNodeType(tag){
	// 1 - node, 2 - comment
	var htm = $(tag).parents('div[id^=comment]');
	var ntype = 2;
	if ($(htm).html() == null) ntype = 1;
   
	return ntype;
}

function getNodeAuthor(nodeType, tag){
	switch (nodeType){
		case 1: 
         author = $(tag).parents().filter('div[class^=node-wrapper]').find('div[class^=node-submitted] a').html(); 
         if (author == null){
            author = $(tag).parents().filter('div[class^=node-wrapper]').find('div[class^=node-submitted]').html(); 
         }
         break;
		case 2: 
         author = $(tag).parents('div[@class^=comment-inner]').find('div[class=created_by] a').html(); 
         if (author == null){
            author = $(tag).parents('div[@class^=comment-inner]').find('div[class=created_by]').html(); 
         }
         break;
	}
   if (author == null){ 
      author = 'Гость';
   }
	return author;
}