// misc routines to support annotations and tags (and QAPhase3 comments - kkf)

/**
refreshcookiename = 'refreshrequired-' + encodeURIComponent(window.location.pathname);
if ($.cookie(refreshcookiename) == 'true') { 
	$.cookie(refreshcookiename, null); 
	window.location.reload(); 
}
**/

if (window.location.hash == '#reloadOnBack') {
	window.location.hash = '#blob' ;
//alert("window.location.hash="+window.location.hash+", window.location="+window.location);
	window.location.reload() ;
}


function forceReloadOnBackButton() {

   window.location.hash = 'reloadOnBack';


/**

	$(window).unload(function() { 
		$.cookie(refreshcookiename, 'true'); 
	}); 
**/
}

function showDlg(dEle) {

	 $("#" + dEle).show() ;
}

function closeDialog(dEle) {

	$("#" + dEle).hide() ;
}
	

$().ready(function() {


    $('#LeftPane').bind('contextmenu', function(e) {

	var targ = (e.srcElement) ? e.srcElement : e.target ;
	var x = $(targ).attr("x") ;
	if (x) {
		var y = $(targ).attr("y") ;
		addAnnotation(x, y, $(targ)) ;
		return false ;
	}	
    });
});


var annotationX ;
var annotationY ;

function addAnnotation(x, y, targ) {

	annotationX = x ;
	annotationY = y ;

	$('#annoOf').html(targ.text()) ;
	$('#annoText').val('') ;
	$('#addAnno').show();
}

var editingAnnotationId ;

function editEAnno(seq, annotationId) {

	editingAnnotationId  = annotationId ;

	var annoContentsDiv = "#annoContent" + seq ;
	//alert("edit annotation=" + editingAnnotationId  + "\ncontents: " + $(annoContentsDiv).html()) ;
	$('#annoEditText').val($(annoContentsDiv).html()) ;
	$('#editAnno').show() ;
}


function saveAnnotation() {

	var annotatedContent = $('#annoText').val() ;
	var annoPublic = $('#rdocommentpublic').attr('checked') ;
	var privateFlag = annoPublic ? 'n' : 'y';

	if (typeof annotationX == 'undefined') {
		annotationX = 0;
	}
	if (typeof annotationY == 'undefined') {
		annotationY = 0;
	}

	if (annotatedContent.length < 1) {
		alert ("you haven't entered any content") ;
		return ;
	}

	var postRes = "" ;

	$.ajax({
		type: "POST",
		url: "/ndp/del/annotation",
		async: false,
		data: "simulatedMethod=put&articleId=" + articleId + "&articlePartId=" + articlePartId + 
				"&xy=" + annotationX + "," + annotationY + "&content=" + encodeURIComponent(annotatedContent) +
				"&private=" + privateFlag,
		success: function(msg){
			postRes = msg ;
		//	alert(postRes) ;
			alert("Your comment has been stored - refresh the page to view") ;
		},
		error: function(reqObj, msg, exceptionObj){
			postRes = "ERROR: " +  reqObj.statusText ;
		//	alert(postRes) ;
			alert("Your updates failed: " + postRes) ;
		}
	});

// NN
//	$('#addAnno').hide();
	$('#popup, #mask').remove();
	$('body').removeClass('popup');
	forceReloadOnBackButton();
}

function saveEditedAnnotation(annotationId) {

	var annotatedContent = $('#annoEditText').val() ;
	var annoPublic = $('#annoPublic').attr('checked') ;
	var privateFlag = annoPublic ? 'n' : 'y';

	if (annotatedContent.length < 1) {
		alert ("You haven't entered any content") ;
		return ;
	}

	var postRes = "" ;

		$.ajax({
			type: "POST",
			url: "/ndp/del/annotation",
			async: false,
//			data: "simulatedMethod=post&annotationId=" + editingAnnotationId + 
			data: "simulatedMethod=post&annotationId=" + annotationId + 
					"&content=" + encodeURIComponent(annotatedContent) + "&private=" + privateFlag,
			success: function(msg){
				postRes = msg ;
			//	alert(postRes) ;
				alert("Your comment has been updated - refresh the page to view") ;
			},
			error: function(reqObj, msg, exceptionObj){
				postRes = "ERROR: " +  reqObj.statusText ;
			//	alert(postRes) ;
				alert("Your updates failed: " + postRes) ;
			}
		});

//	$('#editAnno').hide();
	$('#popup, #mask').remove();
	$('body').removeClass('popup');
	forceReloadOnBackButton();
}

function deleteEditedAnnotation(annotationId, fromPopup) {

	if (confirm('Are you sure you want to remove this comment?')) {

		var postRes = "" ;

		$.ajax({
			type: "POST",
			url: "/ndp/del/annotation",
			async: false,
			data: "simulatedMethod=delete&annotationId=" + annotationId,
			success: function(msg){
				postRes = msg ;
				alert("This comment has been removed") ;
				$("#editAnnotation_" + annotationId).parent().parent().hide("slow") ;
			},
			error: function(reqObj, msg, exceptionObj){
				postRes = "ERROR: " +  reqObj.statusText ;
			//	alert(postRes) ;
				alert("The remove failed: " + postRes) ;
			}
		});
	}
	if (fromPopup) {
		$('#popup, #mask').remove();
		$('body').removeClass('popup');
	}
	forceReloadOnBackButton();
	return false ;
}

function delTag(ele) {

	var f = $(ele).parent() ;
	var tval = f.children("a:first").text() ;
	
	if (confirm("Are you sure you want to delete your tag: " + tval + " ?")) {

		$.ajax({
			type: "POST",
			url: "/ndp/del/tag",
			async: false,
			data: "simulatedMethod=delete&articleId=" + articleId  + "&name=" + tval,
			success: function(msg){
				postRes = msg ;
			//	alert(postRes) ;
				f.hide("slow") ;
			},
			error: function(reqObj, msg, exceptionObj){
				postRes = "ERROR: " +  reqObj.statusText ;
			//	alert(postRes) ;
				alert("Your updates failed: " + postRes) ;
			}
		});
	}		
	return false ;
}

function editTags() {

	$('#ttagText').val('') ; 
	$('#addTags').show();
}

function checkAndSaveTags(knownUser) {
	var tagContent = $('#ttagText').val() ;
	var tags = tagContent.split(',');
	var errMsg = '';

	// No more than 50 tags
	if (tags.length > 50) {
		errMsg = 'You have exceeded the maximum number of tags for an article (50)';
	} else {
		// A tag should not exceed 60 characters
		for (var i = 0; i < tags.length; ++i) {
			var tag = tags[i].replace(/[^a-zA-Z0-9' \\-]/g, ' ').replace(/\s\s+/g, ' ').replace(/^\s+/, '').replace(/\s+$/, '');
			if (tag.length > 60) {
				errMsg = 'One of your tags exceeded 60 characters';
				break;
			}
		}
	}

	if (errMsg != '') {
		alert(errMsg);
	} else {
		saveTags(knownUser);
	}
	return false ;
}

function saveTags(knownUser) {

	var tagContent = $('#ttagText').val() ;
	var tagPublic = $('#rdoworkpublics13260765').attr('checked') ;
	var privateFlag = tagPublic ? 'n' : 'y';

	var postRes = "" ;

	$.ajax({
		type: "POST",
		url: "/ndp/del/tag",
		async: false,
		data: "simulatedMethod=put&articleId=" + articleId  + "&name=" + encodeURIComponent(tagContent) + "&private=" + privateFlag,
		success: function(msg){
			postRes = msg ;
//			alert(postRes) ;
			var start = 0 ;
			while (true) {
				var i = postRes.indexOf("<tag tr", start) ;
				if (i < 0) break ;
				var j = postRes.indexOf(">", i) ;
				if (j < 0) break ;
				var k = postRes.indexOf("<", j) ;
				if (k < 0) break ;
				var tn = postRes.substring(j+1, k).replace("'", "&#39;") ;
//alert(tn) ;
				if (knownUser)	
				$("#arttags").append("<nobr><a href='/result?l-usertag=" + tn +
                                        "' title='all items tagged by you as " + tn + "'>" + tn + "</a>" +
                                        (("y" == privateFlag) ? " <span class='private' title='Private tag'>[Private]</span>" : "") +
                                        " <a class='tagdelete' onclick='return delTag(this)' title='Delete tag " +
                                        tn + "' href='#'></a></nobr> ") ;
				else $("#arttags").append("<a href='/result?l-publictag=" + tn +
                                        "' title='all items tagged as " + tn + "'> " + tn + " </a> ") ;

				start = k ;
			}
			alert("Your tags have been added") ; //updates have been applied - refresh the page to view") ;
		},
		error: function(reqObj, msg, exceptionObj){
			postRes = "ERROR: " +  reqObj.statusText ;
		//	alert(postRes) ;
			alert("Your updates failed: " + postRes) ;
		}
	});

// NN
//	$('#addTags').hide();
	$('#popup, #mask').remove();
	$('body').removeClass('popup');
	forceReloadOnBackButton();
}

function saveQAPhase3Note() {

	var notes = $('#QAPhase3Note').val() ; 
	var postRes = "" ;

	$.ajax({
		type: "POST",
		url: "/ndp/del/QAPhase3ExtraSampleArticleNote",
		async: false,
		data: "simulatedMethod=put&articleId=" + articleId  + "&notes=" + notes,
		success: function(msg){
			postRes = msg ;
		//	alert(postRes) ;
			alert("Your note has been saved") ;
		},
		error: function(reqObj, msg, exceptionObj){
			postRes = "ERROR: " +  reqObj.statusText ;
		//	alert(postRes) ;
			alert("Your update failed: " + postRes) ;
		}
	});
}

function removeFromList(listId) {

//	alert("removeFromList =" + listId) ;
	if (confirm('Are you sure you want to remove this article from this list?')) {
	$.ajax({
		type: "POST",
		url:  "/list",
		data: "functionid=deleteItem&listId=" + listId + 
				"&target=" + encodeURI("a" + articleId),
		dataType: "json",
		success: function(resp){
//alert(resp.result) ;
			if (resp.result != 'ok') alert("The following error occurred whilst attempting to remove this item from list:\n \n" + resp.result) ;
			else {
				for (var i=0;i<userItemLists.length;i++) {
					var t = userItemLists[i] ;
					if (t[0] == listId) { // remove
						t[0] = -1 ;
						$('#mdList' + listId).remove() ;
						break ;
					}
				}
			}		 
 
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			commonErrorAlert(XMLHttpRequest, textStatus, errorThrown) ;
		}
	});
	}
	return false ;
}


