﻿/* TRIM - remove whitespace characters */
/**
 * 
 * @param str
 * @param chars
 * @return str
 * Without the second parameter, Javascript function will trim these characters:

    * ” ” (ASCII 32 (0×20)), an ordinary space.
    * “\t” (ASCII 9 (0×09)), a tab.
    * “\n” (ASCII 10 (0×0A)), a new line (line feed).
    * “\r” (ASCII 13 (0×0D)), a carriage return.
    * “\0″ (ASCII 0 (0×00)), the NUL-byte.
    * “\x0B” (ASCII 11 (0×0B)), a vertical tab.

 */
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
/* ---------------------------------------------- */
	
function refresh_case_status(pubid) {
	new Ajax.Updater('case_status', '../submission/inc.case_status.php', { parameters: { pubid : pubid } });
}

function resizeTextArea(id) {
	var t = $(id);
	var s = t.value;
	if (s.match(/[\n]{3}/)) { // just gecko based browsers
		s = s.replace(/[\n]{3}/i, "\n\n");
		var pos = t.selectionStart - 1;
		t.value = s;
		t.selectionStart = pos;
		t.selectionEnd = pos;
	}

	var a = s.match(/\r\n/) ? t.value.split('\r\n') : t.value.split('\n');
	var b = 1;
	for (var x=0; x<a.length; x++) {
		if (a[x].length >= t.cols)
			b += Math.floor(a[x].length/t.cols);
	}
	b += a.length;
	t.rows = typeof document.selection != "undefined" ? parseInt(b*1.2) : b;

	// count words
	maxwords =$(id + '_maxwords').value;
	if (maxwords > 0) {
		s = s.replace(/\s/i, ' ');
		s = trim(s.replace(/[\s]{2,100}/i, ' '));
		words = s.split(' ').length
		if (words > maxwords)
			$(id + '_words').innerHTML = '<span style="color:red">' + words + ' / ' + maxwords + ' words</span>';
		else
			$(id + '_words').innerHTML = words + ' / ' + maxwords + ' words';
	}
}

function insert_tag(id, aTag, eTag) {
	var nothingselected = 'Please select a character or word first!';
	var input = $(id);
	input.focus();
	if (typeof document.selection != "undefined") {
		// für Internet Explorer
		// Einfügen des Formatierungscodes
		var range = document.selection.createRange();
		var insText = range.text;
		if (trim(insText).length == 0) {
			alert(nothingselected);
			return false;
		}
		if (trim(insText) != insText) eTag += ' ';
		range.text = aTag + trim(insText) + eTag;
		// Anpassen der Cursorposition
		range = document.selection.createRange();
		if (insText.length == 0)
			range.move('character', -eTag.length);
		else
			range.moveStart('character', aTag.length + insText.length + eTag.length);
		range.select();
	} else if (typeof input.selectionStart != "undefined") {
		// für neuere auf Gecko basierende Browser
		// Einfügen des Formatierungscodes
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		if (trim(insText).length == 0) {
			alert(nothingselected);
			return false;
		}
		if (trim(insText) != insText) eTag += ' ';
		input.value = input.value.substr(0, start) + aTag + trim(insText) + eTag + input.value.substr(end);
		// Anpassen der Cursorposition
		var pos;
		if (insText.length == 0)
			pos = start + aTag.length;
		else
			pos = start + aTag.length + insText.length + eTag.length;
		input.selectionStart = pos;
		input.selectionEnd = pos;
	} else {
		// für die übrigen Browser
		// Abfrage der Einfügeposition 
		var pos;
		var re = new RegExp('^[0-9]{0,3}$');
		while (!re.test(pos))
			pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
		if (pos > input.value.length)
			pos = input.value.length;
		// Einfügen des Formatierungscodes
		var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
		input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
	}
}

function trim(str) {
    return str.replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '');
}

function edit_section(id) {
	$('sections_' + id + '_edit').show();
	$('sections_' + id + '_view').hide();

	content = $('sections_' + id).value;
	content = content.replace(/[\n]{3,100}/, '\n\n');
	content = content.replace(/[\r\n]{3,100}/, '\r\n\r\n');
	$('sections_' + id).value = content;
	resizeTextArea('sections_' + id);
	$('sections_' + id).focus();
}

function view_section(case_id, section_id) {
	$('sections_' + section_id + '_indicator').show();
	var content = trim($('sections_' + section_id).value);
	new Ajax.Request('../submission/section_save.php', {
		parameters: { case_id:case_id, section_id:section_id, content:content },
		onComplete: function() {
			refresh_case_status(case_id);

			content = content.replace('<', '&lt;');
			content = content.replace('>', '&gt;');
			content = content.replace(/\[SUP:([^\]]+)\]/gi, '<sup>$1</sup>');
			content = content.replace(/\[SUB:([^\]]+)\]/gi, '<sub>$1</sub>');
			content = content.replace(/[\n]{3,100}/, '\n\n');
			content = content.replace(/[\r\n]{3,100}/, '\r\n\r\n');
			content = content.replace(/\r\n/, '<br />');
			content = content.replace(/\n/, '<br />');
			if (content.length == 0)
				content += '<a href="javascript:void(0)" onclick="edit_section(' + section_id + ')">Click to add text</a>';
			$('sections_' + section_id + '_view').innerHTML = content;
			$('sections_' + section_id + '_indicator').hide();
			$('sections_' + section_id + '_edit').hide();
			$('sections_' + section_id + '_view').show();
		}
	});
}

function sanitize_int(el) {
    v = el.value.replace(/[^0-9]+/g, '');
    if (v.length > 0) v = parseInt(v);
    el.value = v;
}

function mesh_tree(pubid) {
	Control.Modal.open(false,{
	    contents: 'Loading ...',
	    width: 580,
        height: 500
	});
	$('modal_container').style.backgroundColor = '#d5e0f4';
	new Ajax.Updater('modal_container', '../submission/mesh_tree.php?pubid=' + pubid);
}


function open_tree(nr, pubid) {
	if ($('arrow_' + nr).className == 'open') {
		$('arrow_' + nr).className = 'closed';
		$('mesh_' + nr + '_container').innerHTML = '';
		return void(0);
	}
	$('arrow_' + nr).className = 'open';
	$('mesh_' + nr + '_loading').show();

	new Ajax.Updater('mesh_' + nr + '_container', '../submission/mesh_tree.php', {
		parameters: { open_tree : nr, pubid : pubid },
		onComplete: function() {
			$('mesh_' + nr + '_loading').hide();
		}
	});
}

function select_mesh_nr(nr, pubid) {
	new Ajax.Request('../submission/mesh_tree.php', {
		parameters: { add_to_case : nr, pubid : pubid },
		onComplete: function() {
			load_mesh_list(pubid);
		}
	});
}

function remove_mesh_nr(nr, pubid) {
	if (!confirm('Please confirm removing this keyword!'))
		return void(0);
	new Ajax.Request('../submission/mesh_tree.php', {
		parameters: { remove_from_case : nr, pubid : pubid },
		onComplete: function() {
			refresh_case_status(pubid);
			$('mesh_' + nr).remove();
		}
	});
}

function load_mesh_list(pubid) {
	new Ajax.Updater('case_status', '../submission/inc.case_status.php?pubid=' + pubid);
	new Ajax.Updater('mesh_list', '../submission/case_mesh.php', {
		parameters: { pubid : pubid },
		onComplete: function() { Control.Modal.close(); }
	});
}

function load_references_list(pubid) {
	new Ajax.Updater('ref_list', '../submission/case_references.php', {
		parameters: { pubid : pubid }
	});
}

function edit_reference(refid, pubid) {
	if(document.getElementById('ref_help'))
		document.getElementById('ref_help').style.display = 'none';
	new Ajax.Updater('reference_' + refid + '_edit', '../submission/case_references.php', {
		parameters: { pubid : pubid, refid : refid },
		onComplete: function() {
			$('reference_' + refid + '_edit').show();
			$('reference_' + refid).hide();
			if (refid == 0) $('newref').show();
		}
	});
}
function check_valid_reference(string, field_to_change){
	string = trim(string); //remove whitespace
	var return_string = string;
	var string_plain = trim(string.replace(/([.,!?])/g, ""));//check if field contains only punctuation marks
	
	if(string_plain.length ==  0 ){
		return_string = '';
		if(field_to_change != ''){
			field_to_change.value = return_string; //empty invalid field
		}
	}	
	return return_string;
}
function save_reference(pubid, refid) {
	$('ref_indicator_' + refid).show();
	var reference = $('reference_reference_' + refid).value;
	var author = $('reference_author_' + refid).value;
	var year = $('reference_year_' + refid).value;
	var journal = $('reference_journal_' + refid).value;
	var pubmedid = $('reference_pubmedid_' + refid).value;
	var volume = $('reference_volume_' + refid).value;
	var page = $('reference_page_' + refid).value;
	var img = $('ref_indicator_' + refid).style;
	var error_msg = 'Please try again.';
	
	/* check for punctuation marks and reset field if invalid */
	reference = check_valid_reference(reference, $('reference_reference_' + refid));
	author = check_valid_reference(author, $('reference_author_' + refid));
	year = check_valid_reference(year, $('reference_year_' + refid));
	journal = check_valid_reference(journal, $('reference_journal_' + refid));
	volume = check_valid_reference(volume, $('reference_volume_' + refid));
	page = check_valid_reference(page, $('reference_page_' + refid));
	
	/* check if at least 2 fields are filled (excl. pubmed id)*/
	var ready_2_save = false;
	var fields_entered = 0;
	if (reference != '')
		fields_entered++;
	if (author != '')
		fields_entered++;
	if (year != '')
		fields_entered++;
	if (journal != '')
		fields_entered++;
	if (volume != '')
		fields_entered++;
	if (page != '')
		fields_entered++;
	
	if (fields_entered >= 2)
		ready_2_save = true;
	else
		error_msg = 'Please fill in at least two required fields for each reference. Thank you!'
		
	
	/* check if reference is longer than 35 words */
	var reference_words = reference.split(" ");
	var reference_wordcount = reference_words.length;
	if(reference_wordcount > 35 ){
		ready_2_save = false;
		error_msg = 'Title too long! Please use not more than 35 words.';
	}
	
	
	if(ready_2_save == true){	
	new Ajax.Request('../submission/case_references.php', {
		parameters: { pubid:pubid, refid:refid, reference:reference, pubmedid:pubmedid, author:author, year:year, journal:journal, volume:volume, page:page },
		onComplete: function() {
			load_references_list(pubid);
		}
	});
	} else {
		img.display = 'none';
		alert(error_msg);
	}
}

function cancel_edit_reference(refid) {
	$('reference_' + refid + '_edit').innerHTML = '';
	$('reference_' + refid + '_edit').hide();
	$('reference_' + refid).show();
	if (refid == 0) $('newref').hide();
}

function remove_reference(refid,pubid) {
	if (!confirm('Please confirm removing this reference!'))
		return void(0);
	new Ajax.Request('../submission/case_references.php', {
		parameters: { refid : refid, pubid : pubid, remove : 1 },
		onComplete: function() {
			$('reference_' + refid).remove();
			$('reference_' + refid + '_edit').remove();
		}
	});
}

function browse_pubmed() {
	var w = 932;
	var h = 640;
	var l = (screen.availWidth - w) / 2;
	var t = (screen.availHeight - h) / 2;
	var pubmedwindow = window.open('http://www.ncbi.nlm.nih.gov/entrez/queryd.fcgi', 'punmed', 'width=' + w + ',height=' + h + ',top=' + t + ',left=' + l + ',scrollbars=yes,dependent=yes,menubar=no,status=yes,toolbar=no');
	return false;
}

function delete_case(id) {
	if (!confirm('Please confirm deleting this case!'))
		return void(0);
	new Ajax.Request('case_delete.php', {
		parameters: { id : id },
		onComplete: function() {
			$('case_' + id).remove();
		}
	});
}

function withdraw_case(id) {
	if (!confirm('Please confirm withdrawing this case!'))
		return void(0);
	new Ajax.Request('case_withdraw.php', {
		parameters: { id : id },
		onComplete: function() {
			$('case_' + id).remove();
		}
	});
}

function reload_figures(pubid) {
	new Ajax.Updater('case_status', '../submission/inc.case_status.php?pubid=' + pubid);
	new Ajax.Updater('figures', '../submission/inc.case_mediafiles.php', {
		parameters: { pubid : pubid, reload : 1 },
		onComplete: function() {
			$('addfigure').show();
		}
	});
	init_cinemascope();
}

function edit_figure(pubid, figid) {
	figid = parseInt(figid);
	modal(395, 565);
	$('modal_container').style.backgroundColor = '#ffe3b3';
	new Ajax.Updater('modal_container', '../submission/case_mediafile_edit.php', { parameters: { pubid : pubid, figid : figid, add : figid == 0 ? 1 : null } })
	new Ajax.Updater('case_status', '../submission/inc.case_status.php?pubid=' + pubid);

	$('modal_overlay').style.position = 'absolute'; // cursor problem fix
}

function delete_figure(pubid, figid) {
	if (!confirm('Please confirm deleting this figure!')) return false;
	new Ajax.Request('../submission/case_mediafile_edit.php', {
		parameters: { pubid : pubid, figid : figid, delete_group : 1 },
		onComplete: function() {
			reload_figures(pubid);
		}
	});
}

function move_figure(pubid, figid, dir) {
	new Ajax.Request('../submission/case_mediafile_edit.php', {
		parameters: { pubid : pubid, figid : figid, move : dir },
		onComplete: function() {
			reload_figures(pubid);
		}
	});
}

function delete_mediafile(pubid, figid, mediaid) {
	if (!confirm('Please confirm deleting this media file!')) return false;
	new Ajax.Request('../submission/case_mediafile_edit.php', {
		parameters: { pubid : pubid, figid : figid, mediaid : mediaid, delete_media : 1 },
		onComplete: function() {
			edit_figure(pubid, figid);
			//reload_figures(pubid);
		}
	});
}

function move_mediafile(pubid, figid, mediaid, dir) {
	new Ajax.Request('../submission/case_mediafile_edit.php', {
		parameters: { pubid : pubid, figid : figid, mediaid : mediaid, move : dir },
		onComplete: function() {
			edit_figure(pubid, figid);
			//reload_figures(pubid);
		}
	});
}

function set_upload(filename) {
	if (filename.length > 35)
		filename = '...' + filename.substring(filename.length-35);
	$('upload_txt').innerHTML = filename;
	$('upload_btn').show();
}

function dowload_certificate(id) {
	w = 280;
	h = 140;
	Control.Modal.open(false, {
		contents: 'Loading ...',
        width: w,
        height: h
    });
    new Ajax.Updater('modal_container', '../eurorad/my_certificate.php?id='+id);
    var h1 = Control.Modal.getWindowHeight() + 20;
	var h2 = document.body.scrollHeight + 20;
	$('modal_overlay').style.height = new String(h1 > h2 ? h1 : h2) + 'px';
	$('modal_overlay').style.position = 'absolute';
	
}
function dowload_pdf(id) {
	w = 280;
	h = 140;
	Control.Modal.open(false, {
		contents: 'Loading ...',
        width: w,
        height: h
    });
    new Ajax.Updater('modal_container', '../eurorad/my_pdf.php?id='+id);
    var h1 = Control.Modal.getWindowHeight() + 20;
	var h2 = document.body.scrollHeight + 20;
	$('modal_overlay').style.height = new String(h1 > h2 ? h1 : h2) + 'px';
	$('modal_overlay').style.position = 'absolute';
	
}


/**
 * REVIEWER
 */
function accept_review(id) {
	new Ajax.Request('../reviewer/reviewer_actions.php', {
		parameters: { pubid : id, action : 'accept_review' },
		onComplete: function() { top.location.reload(); }
	});
}

function decline_review(id) {
	if (!confirm('Case ' + id + ' will be removed from this list. Your section editor will be informed. \nPlease confirm!')) return false;
	new Ajax.Request('../reviewer/reviewer_actions.php', {
		parameters: { pubid : id, action : 'decline_review' },
		onComplete: function() { top.location.reload(); }
	});
}

function back2author(id, role) {
	modal(400, 210);
	new Ajax.Updater('modal_container', '../reviewer/reviewer_actions.php', {
		parameters: { pubid : id, action : 'back2author', role : role }
	});
	$('modal_overlay').style.position = 'absolute'; // cursor problem fix
}

function back2editor(id, recommendation) {
	modal(400, 230);
	new Ajax.Updater('modal_container', '../reviewer/reviewer_actions.php', {
		parameters: { pubid : id, action : 'back2editor', recommendation : recommendation }
	});
	$('modal_overlay').style.position = 'absolute'; // cursor problem fix

}

function back2reviewer(id) {
	if (!confirm('Case ' + id + ' will be re-submitted and the reviewer informed. \nPlease make sure to enter your comments to the reviewer before re-submitting your case.\nPlease confirm!')) return false;
	document.resubmit.submit();
}

/**
 * COORDINATOR
 */
function language_edited(id, role) {
	if (!confirm('Case ' + id + ' will be flagged as language edited. \nPlease confirm!')) return false;

	if (role == 'LANGUAGE_EDITOR') {
		new Ajax.Request('../language_editor/language_editor_actions.php', {
			parameters: { pubid : id, action : 'langedit' },
			onComplete: function() {
				document.location.href = '../language_editor/cases_to_be_edited.php';
			}
		});
	}
	if (role == 'COORDINATOR') {
		new Ajax.Request('../coordinator/coordinator_actions.php', {
			parameters: { pubid : id, action : 'langedit' },
			onComplete: function() {
				new Ajax.Updater('case_' + id, '../coordinator/coordinator_actions.php', { parameters: { pubid : id, action : 'box' } });
			}
		});
	}
}
function assign_editor(id) {
	if (!confirm('Case ' + id + ' will be assigned to section editor. \nPlease confirm!')) return false;

	new Ajax.Request('../coordinator/coordinator_actions.php', {
		parameters: { pubid : id, action : 'assign_editor' },
		onComplete: function() { top.location.reload(); }
	});
}
function assign_reviewer(pubid, revid) {
	pubid = parseInt(pubid);
	revid = parseInt(revid);
	if (revid > 0) {
		new Ajax.Request('../editor/assign_reviewer.php', {
			parameters: { pubid : pubid, revid : revid },
			onComplete: function() { top.location.reload(); }
		});
	} else {
		new Ajax.Updater('reviewer_' + pubid, '../editor/assign_reviewer.php', { parameters: { pubid : pubid } });
	}
}
function publish_case(id) {
	if (!confirm('Case ' + id + ' will be published. \nPlease confirm!')) return false;

	new Ajax.Request('../editor/editor_actions.php', {
		parameters: { pubid : id, action : 'publish' },
		onComplete: function() { top.location.reload(); }
	});
}
function reject_case(id) {
	if (!confirm('Case ' + id + ' will be rejected. \nPlease confirm!')) return false;

	new Ajax.Request('../editor/editor_actions.php', {
		parameters: { pubid : id, action : 'reject' },
		onComplete: function() { top.location.reload(); }
	});
}
function change_status(pubid, status, newstatus) {
	if (newstatus) {
		new Ajax.Request('../coordinator/coordinator_actions.php', {
			parameters: { pubid : pubid, action : 'change_status', status : status, newstatus : newstatus },
			onComplete: function() {
				new Ajax.Updater('case_' + pubid, '../coordinator/coordinator_actions.php', { parameters: { pubid : pubid, action : 'box' } });
			}
		});
	} else {
		new Ajax.Updater('status_' + pubid, '../coordinator/coordinator_actions.php', { parameters: { pubid : pubid, action : 'change_status', status : status } });
	}
}
function change_section(pubid, section, newsection) {
	if (newsection) {
		new Ajax.Request('../coordinator/coordinator_actions.php', {
			parameters: { pubid : pubid, action : 'change_section', section : section, newsection : newsection },
			onComplete: function() {
				new Ajax.Updater('case_' + pubid, '../coordinator/coordinator_actions.php', { parameters: { pubid : pubid, action : 'box' } });
			}
		});
	} else {
		new Ajax.Updater('section_' + pubid, '../coordinator/coordinator_actions.php', { parameters: { pubid : pubid, section : section, action : 'change_section' } });
	}
}