
/* ANNOTATIONS */
/* SOME EXPERIMENTAL NEW COMMENTING STUFF */
Event.observe(window, 'load', markParagraphs, false);
function markParagraphs() {
	// Go through all content-boxes
	$$('#content div.entry_content').each(function(block) {
			var p_count = 0;
			block.childElements('p').each(function(p) {
				// Check if there is enought text on this pice
				if (p.innerHTML.length > 200 && p.className != 'comments_invite') {
					// Add the ruler element on the left
					ar = new Element('div');
					ar.setStyle({
							backgroundColor: '#efefef',
							height: p.getHeight() + 'px',
							width: '15px',
							position: 'relative',
							top: p.getHeight()*(-1) + 'px',
							left: '-20px',
							clear: 'both'
					});
					p.setStyle({ height: p.getHeight() + 'px'});
										
					// Set identifier for later reference
					id = block.id + "_" + (p_count+=1);
					p.id = "p_" + id; // Paragraph
					ar.id = "ar_" + id; // Annotation-ruler
					
					// Add actions to the ruler
					ar.observe('mouseover', function() {
							this.setStyle({ backgroundColor: '#fff2bb', cursor: 'pointer' });
					});
					ar.observe('mouseout', function() {
							this.setStyle({ backgroundColor: '#efefef', cursor: 'auto' });
					});
					ar.observe('click', fetchAnnotationsForParagraph);
					
					// Put it in the DOM
					p.appendChild(ar);
				}
			});
	});
	
	// Add the counts
	addCounts();
}

function addCounts() {
	var route = window.location.pathname;
	new Ajax.Request('/get-annotation-counts', {
			method: 'post',
			parameters: { route: route},
			onSuccess: function(transport) {
				annotations = transport.responseText.evalJSON(true);
				for each (var entry in annotations) {
					for each (var p in entry['paragraphs']) {
						addSingleMarker(entry['id'], p['id'], p['count']);
					}
				}
			}
	});
}

function addSingleMarker(entry_id, paragraph_id, count) {
	div = new Element('div', {'class': 'paragraph_marker', 'id': 'am_'+entry_id+'_'+paragraph_id});
	var top = ($('ar_'+entry_id+'_'+paragraph_id).getHeight()*2)*(-1);
	div.setStyle({ top: top+'px' });
	$('p_'+entry_id+'_'+paragraph_id).appendChild(div).update(count);
}

function showAnnotationBox(id, p, annotations) {
	var box = new Element('div', {'id':  'a_'+id, 'class': 'annotation_box'});
	
	// Annotations
	if (annotations != '[]') {
		var ann = new Element('div', {'class': 'paragraph_annotations'});
		annotations.evalJSON(true).each(function(a) {
				// Website/E-Mail?
				if (a.www_mail != '') {
					var strong = new Element('strong');
					var link;
					// Holy grap, this is bad code ...
					if (a.www_mail.search(/@/) != -1) {
						link = 'mailto:'+a.www_mail;
					} else {
						if (a.www_mail.search(/http:\/\//) == -1) {
							link = 'http://' + a.www_mail;
						} else {
							link = a.www_mail;
						}
					}
					strong.appendChild(new Element('a', {'href': link}).update(a.username + ': '));
					ann.appendChild(strong);
				} else {
					ann.appendChild(new Element('strong').update(a.username + ': '));
				}
				ann.appendChild(new Element('span').update(a.annotation));
				ann.appendChild(new Element('br'));
		});
		box.appendChild(ann);
	}
	
	// Form
	var form = box.appendChild(new Element('form', {'method': 'POST', 'action': '/', 'id': 'f_'+id, 'class': 'annotation_form'}));
	
	// If the user has allready a cookie
	if (readCookie('username')) {
		var www_mail_element = (readCookie('www_mail') != '') ? ' (' + readCookie('www_mail') + ')' : '';
		form.appendChild(new Element('cite').update(readCookie('username') + www_mail_element));
	} else {
		form.appendChild(new Element('label', {'for': 'username'}).update("Name: "));
		form.appendChild(new Element('input', {'type': 'text', 'name': 'username', 'id': 'f_username'}));
		form.appendChild(new Element('label', {'for': 'www_mail'}).update("E-Mail/Webseite: "));
		form.appendChild(new Element('input', {'type': 'text', 'name': 'www_mail', 'id': 'f_www_mail'}));
	}
	form.appendChild(new Element('br'));
	
	// Usual inputs (text, submit-button)
	ta = new Element('textarea', {'name': 'annotation', 'id': 'f_annotation'});
	ta.observe('keyup', checkTextareaLength);
	form.appendChild(ta);
	var submit = new Element('input', {'type': 'button', 'name': 'send_annotation', 'value': 'Anmerkung eintragen'}).disable();
	submit.observe('click', addAnnotation);
	form.appendChild(submit);
	
	new Insertion.After(p.id, box);
}

function checkTextareaLength(event) {
	var length = Event.element(event).getValue().length;
	var submitElement = $$('.annotation_form')[0].getInputs('button')[0];
	if (length >= 5) {
		submitElement.enable();
	} else {
		submitElement.disabled = true;
	}
	return true;
}

function fetchAnnotationsForParagraph(/*paramID=-1*/) {		
	var id = this.id.substring(3);
	//if (paramID != -1) id = paramID;
	var p = $('p_' + id);
	var toggleAndStop = false;
	
	// Check if there is allready a open submit-form on this page
	$$('.annotation_box').each(function(b) {
			// Toggle on the same paragraph
			if (b.id == 'a_'+id) toggleAndStop = true;
			b.remove();
	});
	
	if (!toggleAndStop) {
		new Ajax.Request('/get-annotations', {
				method: 'post',
				parameters: { p_id: p.id },
				onSuccess: function(transport) {
					annotations = transport.responseText;
					showAnnotationBox(id, p, annotations);
				}
		});
	}
}

function addAnnotation() {
	var username, www_mail;
	if (readCookie('username')) {
		username = readCookie('username');
		www_mail = readCookie('www_mail');
	} else {
		username = $('f_username').getValue();
		www_mail = $('f_www_mail').getValue();
		createCookie('username', username, 365);
		createCookie('www_mail', www_mail, 365);
	}
	var content = $('f_annotation').getValue();
	
	new Ajax.Request('/add-annotation', {
			method: 'post',
			parameters: {
				username: username,
				www_mail: www_mail,
				annotation: content,
				p_id: $$('.annotation_form')[0].id
			},
			onSuccess: function(transport) {
				var resp = transport.responseText || "Anmerkung fehlerhaft";
				var am_id = 'am_' + $$('.annotation_form')[0].id.substring(2);
				
				var ids = am_id.split('_');
				
				// If there is no marker yet, create one
				if (!$(am_id)) {
					addSingleMarker(
						ids[1], // Entry-ID
						ids[2], // Paragraph-ID
						'1'
					);
				// Otherwise update the counter
				} else {
					var old_count = parseInt($(am_id).innerHTML);
					$(am_id).update(old_count+1);
				}				
				
				$$('.annotation_box')[0].remove();
				
			}
	});
}

