/*
 * InputNotes - jQuery plugin to add notes below textareas and input fields based on regex patterns
 * 
 * Copyright (c) 2010 Fredi Bach
 * www.fredibach.ch
 *
 * Usage:
 
	$("#texareaid").inputNotes( 
		{
			warning1: {
				pattern: /(^|\s)sex(\s|$)/ig,
				type: 'warning',
				text: 'Do not type "sex"!' 
			},
			note1: {
				pattern: /[0-9]/,
				type: 'note',
				text: 'Do not type numbers!' 
			}
		}
	);

 * Plugin page: http://fredibach.ch/jquery-plugins/inputnotes.php
 *
 */
(function($) {
	
	$.fn.inputNotes=function(notes) {
		
		var area = this;
		
		area.after('<div id="'+this.attr('id')+'_inputnotes" class="inputnotes"></div>');
		var containerdiv = '#'+area.attr('id')+'_inputnotes';
		$(containerdiv).hide();
	
		var notebox = $('#'+area.attr('id')+'_inputnotes');
		notebox.css({ 'width': area.outerWidth() });
		
		showNotes();
	
		function showNotes(){
			var content = area.val();
			var removeItems = [];
			for(var item in notes){
				var itemdiv = containerdiv+' #note_'+item;
				if (content.match(notes[item].pattern)){
					if ($(itemdiv).size() == 0){
						$(containerdiv).append('<div id="note_'+item+'" class="'+notes[item].type+'">'+notes[item].text+'</div>');
						if ($(containerdiv).is(':hidden')){
							$(containerdiv).show();
						}
						$(area).trigger('inputnote_added',{ note: item });
						if (typeof notes[item].addCallback == 'function'){
							notes[item].addCallback.call(area,item,notes[item].type);
						}
						$(itemdiv).hide().slideDown('fast');
					}
				} else {
					if ($(itemdiv).size() > 0){
						removeItems[item] = true;
					}
				}
			}
			for(var item in removeItems){
				var itemdiv = containerdiv+' #note_'+item;
				$(area).trigger('inputnote_removed',{ note: item });
				if (typeof notes[item].removeCallback == 'function'){
					notes[item].removeCallback.call(area,item,notes[item].type);
				}
				$(itemdiv).slideUp('fast', function(){
					$(itemdiv).remove();
					if ($(containerdiv).html() == ''){
						$(containerdiv).hide();
					}
				});
			}
		}
	
		this.keyup(function(e){
			showNotes();
		});
		
		return this;
	
	};
	
	$.fn.hasInputNotes=function(type) {
		if ($(this).is('form')){
			var hasNotes = false;
			$(this).find('input, textarea').each(function(i) {
				if ($(this).attr('id')){
					if (type != undefined){
						if ($('#'+$(this).attr('id')+'_inputnotes div.'+type).size() > 0){ 
							hasNotes = true; 
						}
					} else {
						if ($('#'+$(this).attr('id')+'_inputnotes div').size() > 0){ 
							hasNotes = true;
						}
					}
				}
			});
			return hasNotes;
		} else {
			if (type != undefined){
				if ($('#'+this.attr('id')+'_inputnotes div.'+type).size() > 0){ 
					return true; 
				} else { 
					return false; 
				}
			} else {
				if ($('#'+this.attr('id')+'_inputnotes div').size() > 0){ 
					return true; 
				} else { 
					return false; 
				}
			}
		}
		return this;
	};
	
})(jQuery);