/**
*
* Er moeten minstens twee opties doorgegeven worden.
* emoticonsEl geeft het element aan waar de emoticon lijst neergezet moet worden. 
* textAreaEl geeft aan in welke textarea de emoticons neergezet moeten worden.
*
* Voorbeeld:
*
*  // Vervangen van de smilies in een div.
*  jQuery('.comment_text').emoticons();
*
*  Het is eventueel ook mogelijk zelf een smilies pad en/of smilies te definieren.
*
*  jQuery('.comment_text').emoticons( {
*	imagePath: '/templates/eztemplate/apart_smilies/'
*     emoticons:  {
*	'X-(': 'angry',
*	':-/': 'confused'
*  });
*
*  Er wordt dat bijvoorbeeld /templates/eztemplate/aparte_smilies/angry.gif bestaat.
*
*
*  Het toevoegen van de smilies balk aan een formulier.
*
*  Deze functie verwacht 1 optie, emoticonsEl.
*  Het emoticonsEl moet je zelf aanmaken en dan doorgeven aan de functie.
*  Dit is het element waarbinnen de smilies worden geplaatst, het mag dus ook een bestaand element zijn.:w
* 
*  Bijvoorbeeld :
*
*  var emoticonsEl = jQuery('#submit').prepend('<div class="smiley_form"></div>');
*
*  jQuery('#reply_message').emoticonForm({ emoticonsEl: emoticonsEl });
*
*/
(function($) {
   var opts; 

   jQuery.fn.emoticons = function(options) {

   // build main options before element iteration
   opts = jQuery.extend({}, jQuery.fn.emoticons.defaults, options);

     // iterate and reformat each matched element
     return this.each(function() {
	jQuery(this).html(jQuery.fn.emoticons.markup(jQuery(this).html()));
     });

   };

   jQuery.fn.emoticons.markup = function(content) {
	for(var k in opts.emoticons) {
	  content = jQuery.fn.emoticons.format(content, k, 'span');
	}
	return content;
   };

   /**
    *
    * Te gebruiken in andere functies
    *
    * jQuery.fn.emoticons.format('Dit is mijn tekst ;-)', ';-)', 'div');
    *
    * Genereerd: 
    *
    *   "Dit is mijn tekst <div class="smiley"><img src="/templates/standard/common/image/emoticons/wink.gif" /></div>"
    *
    */
   jQuery.fn.emoticons.format = function(line, emoticon, tag)
   {
	  return line.replace( new RegExp( emoticon.replace('(','\\(').replace(')','\\)').replace('/','\\/') , 'ig'), "<"+tag+" class=\"smiley\"><img src=\"" + opts.imagePath + "/" + opts.emoticons[emoticon] + ".gif\"  /></"+tag+">");
   };

   jQuery.fn.emoticons.defaults = {
     imagePath:  '/templates/standard/common/image/emoticons',
     emoticons:  {
	'X-(': 'angry',
	':-/': 'confused',
	':"(': 'embarrased',
	':-)': 'happy',
	':)': 'happy',
	':-(': 'sad',
	':(': 'sad',
	':-O': 'surprised',
	':O': 'surprised',
	':-P': 'tongue',
	':P': 'tongue',
	';)': 'wink',
	';-)': 'wink'
     }
   };

// snippet uit: http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
function insertAtCaret(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var range;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") { 
		txtarea.focus();
		range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	} else if (br == "ff") {
		strPos = txtarea.selectionStart;
	}
	
	var front = (txtarea.value).substring(0,strPos);  
	var back = (txtarea.value).substring(strPos,txtarea.value.length); 
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") { 
		txtarea.focus();
		range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	} else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}


   jQuery.fn.emoticonForm = function(options) {

	// build main options before element iteration
	opts = jQuery.extend({}, jQuery.fn.emoticons.defaults, options);

	if(typeof options == 'undefined') {
		alert('Options emoticonsEl and textAreaEl are missing.');
	}

	if(!options.emoticonsEl) {
		alert('emoticonsEl option not specified!');
	}

	var theEl = jQuery('<div class="emoticons_list"></div>');
	jQuery(options.emoticonsEl).append(theEl);

	var smileList = jQuery('<ul></ul>');
	jQuery(theEl).append(smileList);

	var textarea = jQuery(this);
	
	var content;
	var smilies = [];
	var unique = [];
	for(var c in opts.emoticons) {
		unique[opts.emoticons[c]] = c;
	}

	var removeHover = function() {
		jQuery(this).removeClass('hover');
	};

	var addHover = function() {
		jQuery(this).addClass('hover');
	};

	var clickSmiley = function() {
		// insert smiley at current cursor pos in textarea, + extra spatie
		insertAtCaret(textarea.attr('id'), ' '+jQuery(this).data('smileycode'));
	};

	for(var k in unique) {
		
		var smiley = jQuery(jQuery.fn.emoticons.format(unique[k], unique[k], 'li'))
			.attr('class', 'pointer')
			.data('smileycode', unique[k])
			.hover(addHover,removeHover)
			.click(clickSmiley);

		smileList.append(smiley);
	}

   };

})(jQuery);
