/*
 * printform 1.0
 * By John Elliott (http://www.flipflops.org)
 * Copyright (c) 2008 John Elliott
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
   
/**
 * convert textareas and select tags to divs so that you HTML forms can be printed.
 *
 *
 *
 * @name printform
 * @type jQuery
 * @author John Elliott (http://www.flipflops.org)
 * @desc 
 * 
 * @example $('#tester').printform();
 * @desc call the plugin on #tester - any select or textareas will be replaced
 *
 * @param settings - not used, but included for future proofing! (I'm sure there will be options sometime...)
 *
*/

jQuery.fn.printform = function(settings){
	return this.each(function(){
		new jQuery.printform(this, settings);
	});
}



jQuery.printform = function(obj, settings) {
  
  	/*
  	* within a parent object - replace the textareas and select menus
  	*/
  
  
 	init(obj, 'textarea');
	init(obj, 'select');	
	
		
	function init(obj, fieldType) {
	
	/*
	* loop through each instance of an element within the parent 
	*/
		
		obj = jQuery(obj).attr('id');
			
		jQuery('#' + obj + ' ' + fieldType).each( function() {
					
			var id = jQuery(this).attr('id');
			
			field_replacer(id, fieldType);
		});
	}		
	
	
	function field_replacer(id, fieldType) {
	
	/*
	* function to replace the elements with divs
	*/
	
			str = jQuery('#' + id).val();
			str = str.replace(/\n/g, '<br />');
			
			if ( jQuery('#replace-' + id).length > 0 ) {
				// if a replacement div already exists for this element, then just show it.
				// update the content of the replacer with the edited content
				jQuery('#replace-' + id).html(str).show();			
			} else {
				// otherwise create a new replacement div for the element
				jQuery('#' + id).after('<div class="' + fieldType + '-replace" id="replace-' + id + '">' + str + '</div>');			
			}
			
			jQuery('#' + id).hide(); // hide the element that has just been replaced
			field_watcher(id, fieldType); // add event listeners
	}											
	
	function field_watcher(id,  fieldType) {
	
	/*
	* add listeners to the elements
	* onclick - show the original element and hide the replacer
	* onblur - call the field_replacer to update the page
	*/
	
		jQuery('#replace-' + id).click(function() {

		jQuery('#' + id).show().focus();
		jQuery('#replace-' + id).hide();

		jQuery('#' + id).blur(function() {
		
			field_replacer(id,  fieldType);								
			
		});
	});
	}
};