// ==UserScript==
// @name           meneame preview
// @namespace      http://javierperez.eu
// @description    Visualiza una preview de tu comentario en menéame
// @include        http://meneame.net/story/*
// @include        http://meneame.dev/story/*
// ==/UserScript==

// Constantes
// - nombre de la cookie
var ms_cookie = 'meneame_signature';
var mson_cookie = 'meneame_signature_on';

// Buscamos el FORM de envío de comentario (div.commentform)
// NOTA: en jQuery sería $('div.commentform > form')

// - obtenemos todos los div's
var divs = unsafeWindow.document.getElementsByTagName('div');
// - buscamos el div con className = 'commentform'
//		y obtenemos el form
var f = null;
for (var i=0; i<divs.length && !(f=divs[i].className=='commentform'?divs[i].getElementsByTagName('form')[0]:null); i++);
if (f) {
	// - añadimos evento onsubmit
	f.onsubmit = function(){
		// - guardamos la firma en la cookie
		setSignatureToCookie(getSignatureFromForm());
		// - añadimos la firma al textarea de envío de comentario
		this.comment_content.value = this.comment_content.value + getSignature();
		return true;
	};
	// - añadimos textarea con la firma
	var d = unsafeWindow.document.createElement('div');
	d.innerHTML =
		  '<label for="comment-signature">Firma</label>'
		+ '<textarea id="comment-signature" '+(signatureOn()?'':'disabled="disabled"')+'>'+readSignatureFromCookie()+'</textarea>'
		+ '<input id="signature-on" type="checkbox" '+(signatureOn()?'checked="checked"':'')+' onchange="document.getElementById(\'comment-signature\').disabled=!this.checked; this.form.comment_content.onkeyup();" /> '
		+ '<label for="signature-on">Adjuntar firma</label>';
	f.comment_content.parentNode.appendChild(d);
}

// Añadimos una capa donde mostrar el comentario que estamos escribiendo, tal y
//	como se vería publicado en menéame

// - hay que buscar el contenedor de comentarios: ol.comments-list
var comments = searchClassed('ol','comments-list');
if (comments && comments.length) {
	// - encontramos nuestro contenedor de comentarios
	comments = comments[0];
} else {
	// - no encontramos el contenedor, creamos uno
	// - se inserta entre ul.tabsub y div.commentform
	var d = searchClassed('div', 'commentform')[0];
	if (!d) return;

	comments = newElement('ol');
	comments.className = 'comments-list';
	d.parentNode.insertBefore(comments, d);
}

// - se crea una entrada nueva (LI)
var comment = newElement('li', comments);
var c_body = newElement('div', comment);

c_body.className = 'comment-body';
c_body.innerHTML = '<a href="#comment-preview"><strong>#preview</strong></a> '
	+ '<span id="comment-preview"></span>';

// - obtenemos id del contenedor del comentario
var preview = getElement('comment-preview');

// Añadimos evento onkeyup al textarea del comentario
f.comment_content.onkeyup = getElement('comment-signature').onkeyup = function() {
	writePreview(f.comment_content.value);
};
writePreview(f.comment_content.value);

// Funciones preview -----------------------------------------------------------
// - escribe el comentario en la preview
function writePreview(text) {
	preview.innerHTML = text2html((text + getSignature())).split('\n').join('<br />');
}
function smiley(str) {
	var SMILEYS_URL = '/img/smileys/';
	str=str.replace(/:-{0,1}\)/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'smiley.gif" alt=":-)" title=":-)"/>');
	str=str.replace(/^;-{0,1}\)|[^t];-{0,1}\)/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'wink.gif" alt=";)" title=";)" />');
	str=str.replace(/:-{0,1}&gt;/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'cheesy.gif" alt=":->" title=":->" />');
	str=str.replace(/:-{0,1}D|:grin:/gi, '<img width="15px" height="15px" src="' + SMILEYS_URL + 'grin.gif" alt=":-D" title=":-D"/>');
	str=str.replace(/:oops:|&lt;:\(/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'embarassed.gif" alt="&lt;&#58;(" title="&#58;oops&#58; &lt;&#58;(" />');
	str=str.replace(/&gt;:-{0,1}\(/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'angry.gif" alt="&gt;&#58;-(" title="&gt;&#58;-(" />');
	str=str.replace(/\?(:-){0,1}\(/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'huh.gif" alt="?(" title="?(" />');
	str=str.replace(/:-{0,1}\(/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'sad.gif" alt=":-(" title=":-(" />');
	str=str.replace(/:-{0,1}O/g, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'shocked.gif" alt=":-O" title=":-O" />');
	str=str.replace(/8-{0,1}[D\)]|:cool:/g, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'cool.gif" alt="8-D" title=":cool: 8-D"/>');
	str=str.replace(/:roll:/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'rolleyes.gif" alt=":roll:" title=":roll:" />');
	str=str.replace(/^:-{0,1}P| :-{0,1}P/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'tongue.gif" alt=":-P" title=":-P" />');
	str=str.replace(/:-{0,1}x/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'lipsrsealed.gif" alt=":-x" title=":-x" />');
	str=str.replace(/([^ps]|^):-{0,1}\//gi, '$1 <img width="15px" height="15px" src="' + SMILEYS_URL + 'undecided.gif" alt=":-/" title=":-/ :/" />');
	str=str.replace(/:'\(|:cry:/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'cry.gif" alt=":\'(" title=":cry: :\'(" />');
	str=str.replace(/( |^)[xX]D+|:lol:/g, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'laugh.gif" alt="xD" title=":lol: xD" />');
	str=str.replace(/ :-{0,1}S/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'confused.gif" alt=":-S" title=":-S :S"/>');
	str=str.replace(/:-{0,1}\|/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'blank.gif" alt=":-|" title=":-| :|"/>');
	str=str.replace(/:-{0,1}\*/gi, ' <img width="15px" height="15px" src="' + SMILEYS_URL + 'kiss.gif" alt=":-*" title=":-* :*"/>');
	return str;
}
function text2html(text) {
	text = smiley(text);
	text = text.replace(/([\(\[:\.\s]|^)(https*:\/\/)([^ \t\n\r\]\(\)\&]{5,70})([^ \t\n\r\]\(\)]*)([^ .\t,\n\r\(\)\"\'\]\?])/gi, '$1<a href="$2$3$4$5">$3$5</a>');
	text = text.replace(/(^|[;,\.:\s])_([^\s<>]+)_/gi, "$1<em>$2</em>");
	text = text.replace(/(^|[;,\.:\s])\*([^\s<>]+)\*/gi, "$1<strong>$2</strong>");
	text = text.replace(/(^|[\s\W])#([1-9][0-9]*)/gi, "$1<a class='tt' href=\"#comment-$2\" onmouseover=\"return tooltip.c_show(event, 'id', '$2');\" onmouseout=\"tooltip.hide(event);\"  onclick=\"tooltip.hide(this);\">#$2</a>");
	return text;
}


// Funciones de firma ----------------------------------------------------------
// - obtiene el texto de la firma
function getSignature() {
	if (!getElement('signature-on').checked) return '';
	
	return '\n\n---\n' + getSignatureFromForm();
}
// - obtiene la firma del textarea
function getSignatureFromForm() {
	return getElement('comment-signature').value;
}

// Funciones DOM ---------------------------------------------------------------
// - obtiene elementos del tipo div.className
function searchClassed(tag, classname) {
	var els = unsafeWindow.document.getElementsByTagName(tag);
	var e = [];
	for (var i=0; i<els.length; i++)
		 if (els[i].className==classname) e.push(els[i]);
	return e;
}
// - crear un elemento
function newElement(tag, appendTo) {
	var e = unsafeWindow.document.createElement(tag);
	if (appendTo) appendTo.appendChild(e);
	return e;
}
// - obtener un elemento por id
function getElement(id) {
	return unsafeWindow.document.getElementById(id);
}

// Funciones para cookies-------------------------------------------------------
// @link http://www.quirksmode.org/js/cookies.html

// Pregunta por una firma mediante ventana modal
function setSignatureToCookie(signature) {
	unsafeWindow.document.cookie = ms_cookie+'='+encodeURIComponent(signature)+'; path=/';
	unsafeWindow.document.cookie = mson_cookie+'='+encodeURIComponent(getElement('signature-on').checked?'on':'off')+'; path=/';
}

// Lee la cookie con nuestra firma
function readSignatureFromCookie() {
	return getCookie(ms_cookie) || '';
}
function signatureOn() {
	var son = getCookie(mson_cookie);
	//console.log(son);
	son = (son == 'on') || (son == null);
	return son;
}
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = unsafeWindow.document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
	}
	return null;
}


