var commentarea;
var docomment = false;
var underline;
var commenticon;
var commentrange;
var commentpopup;
var acceptedCommentTags = '|LI|P|H2|H3|H4|';
var isCommentScriptLoaded = false;

function initcomments() {
	commentarea = document.getElementById('contents');
	
	if (ie) 
		commentrange = document.body.createTextRange();
	
	if (commentarea.addEventListener) {
		commentarea.addEventListener('mousemove', commenttarget, false);
		commentarea.addEventListener('click', addcomment, false);
		commentarea.addEventListener('mouseout', commentout, false);
	}
	else if (commentarea.attachEvent) {
		commentarea.attachEvent('onmousemove', commenttarget);
		commentarea.attachEvent('onclick', addcomment);
		commentarea.attachEvent('onmouseout', commentout);
	}
		
		
	underline = document.createElement('div');
	underline.className = 'underline';
	document.body.appendChild(underline);
	
	commenticon = document.createElement('div');
	commenticon.className = 'commenticon';
	document.body.appendChild(commenticon);
	
	commentpopup = document.createElement('div');
	commentpopup.className = 'tooltip largetooltip commentpopup';
	
	strhtml = '<div>' +
		'<p>' + translate('Your comment') + '</p>' +
		'<a href="#" onclick="deleteComment(this); return false;" >' + translate('Delete comment') + '</a>' +
		'</div>' + 
		'<textarea id="commenttext" onblur="updateComment(this);"></textarea>';
		
	
	commentpopup.innerHTML = strhtml;	
	document.body.appendChild(commentpopup);
	
	applyInvitation();
	
	/*
	1. Kolla om man är inloggad 
	2. Om man är det så ska getComments läsas in
	3. läs in remoteSave
	*/
	var hash = loadHash();
    if(hash != null) //user is logged in
    {
        loadCommentScripts(hash);
        
        //give scripts time to load
        //setTimeout('placeAllComments()',100);
	}
}

function placeAllComments()
{
	commentManager.parseCommentaArray();
	var aComments = commentManager.getComments();
	
    //create a page handler to populate the page
    var page = new PageHandler();
    page.populateComments(aComments);
}

function loadCommentScripts(hash)
{
    if(!isCommentScriptLoaded)
    {
        //add script getComments
        var script = document.createElement('script');
        script.src = 'http://cybercom.commentserver.ar.halvarsson.se/remoteSave/getComment.aspx?hash=' + hash;
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);
        
        //add script remoteSave
        /*script = document.createElement('script');
        script.src = '/2007/javascript/comments/remoteSave.js';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);*/
        isCommentScriptLoaded = true;
    }
}

// aktiveras vid mousemove. Den identifierar vilket ord man hovrar och lägger en ikon precis innan ordet.
function commenttarget(e) {
	if (docomment) {
		/*
		init the cursor style on commentstart
		commentarea.style.cursor = 'default';*/
		commenticon.style.top = (e.clientY + 10) + 'px';
		commenticon.style.left = (e.clientX + 10) + 'px';
		commenticon.style.display = 'block';
		
		if (ie) { // the visual mouseover-effect is only applicable for IE
			commentrange.moveToPoint(e.clientX, e.clientY);
			commentrange.expand("word");
			if (acceptedCommentTags.indexOf('|' + e.srcElement.tagName + '|') == -1 || commentrange.boundingLeft >= ((columnWidth + 100) * 2)) {
				commentout(e);
			}
			else {
				underline.style.left = (commentrange.boundingLeft - 4) + 'px';
				underline.style.top = (commentrange.boundingTop - 1) + 'px';
				underline.style.display = 'block';
			}
		}
	}
}

function addcomment(e) {
	if (docomment) {
		var el;
		go = false;
		if (ie) {
			el = e.srcElement;
			if (acceptedCommentTags.indexOf('|' + el.tagName + '|') > -1) {
			    if(el.parentNode.className != 'comment') //do not comment a comment...
			    {
				    go = true;
				    var commentLength = commentrange.text.length;
				    commentrange.pasteHTML('<span class="comment" onmouseout="commentmouseout(this);" onmouseover="commenthover(this);" onclick="commentclick(this);" id="newcomment">' + commentrange.text + '</span>');
				}
			}
		}
		else {
			el = e.target;
			if (acceptedCommentTags.indexOf('|' + el.tagName + '|') > -1) {
				go = true;
				sel = window.getSelection();
				startpos = sel.anchorOffset;
				endpos = startpos;
				sel.collapse(sel.anchorNode, startpos);
				range = document.createRange();
				range.setStart(sel.anchorNode, startpos);
				range.setEnd(sel.anchorNode, endpos + 1);
				
				// move the pointer to the beginning of a word or paragraph
				while (startpos > 0) {
					startpos--;
					range.setStart(sel.anchorNode, startpos);
					if (range.toString().substring(0, 1) == ' ') {
						startpos++;
						range.setStart(sel.anchorNode, startpos);
						break;
					}
				}
				
				// move the pointer to the end of a word or paragraph
				while (true) {
					endpos++;
					try {
						range.setEnd(sel.anchorNode, endpos);
					}
					catch(ex) {
						// this will fail if it tries to expand the range outside the node
						endpos -= 2;
						range.setEnd(sel.anchorNode, endpos);
						break;
					}
					if (range.toString().substring(range.toString().length-1) == ' ') {
						endpos--;
						range.setEnd(sel.anchorNode, endpos);
						break;
					}
				}
				
				commentLength = endpos - startpos;
				span = document.createElement('span');
				span.className = 'comment';
				span.id = 'newcomment';
				
				
                try
                {
                    addEvent(span, 'mouseout', commentmouseout);
                    addEvent(span, 'mouseover', commenthover);
                    addEvent(span, 'click', commentclick);
//                    span.onmouseout = function(){ commentmouseout(this); };
//                    span.onmouseover  = function() { commenthover(this); };
//                    span.onclick  = function() { commentclick(this); };
				}
				catch(exc)
				{
				    alert('failed adding events to comment' + exc);
				}
				
				span.innerHTML = range.toString();
				range.deleteContents();
				range.insertNode(span);
			}
		}
		if (go) {
		
		    //get the created comment
            createdComment = document.getElementById('newcomment');
            if(createdComment != null)
            {
			    //create pagehandler to get page hash
			    var page = new PageHandler();
    			
			    //create a comment object and populate with values
			    var remote = commentManager.createComment(); //new RemoteComments();
                remote.path = page.getPagePath(el);
                remote.start = page.getStartAtPosForComment(el);
                remote.wordlength = commentLength;
                
                remote.pl = page.getPageHash();
                remote.row = "-1";
                remote.col = "-1";
                remote.userId = loadHash();
                remote.addComment();
                createdComment.id = 'comment' + remote.CommentId;
                commenthover(createdComment);
                commentclick(createdComment);
            }
            
            //quit adding comment, even if last ine wasnt added
            docomment = false;
		}
	}
}

function commentout(e) {
	underline.style.display = 'none';
	commenticon.style.display = 'none';
}

function DELETEDcreateCommentNode()
{
	
}

function applyInvitation() {
	var invited = location.href.indexOf('#user=');
	if (invited > -1) {
		var usrHash = location.href.substr(invited + 6, 32);
		saveHash(usrHash);
	}
}
