/*
 * jQuery blockUI plugin
 * Version 1.26  (07/05/2007)
 * @requires jQuery v1.1.1
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 (function($) {
/**
 * blockUI provides a mechanism for blocking user interaction with a page (or parts of a page).
 * This can be an effective way to simulate synchronous behavior during ajax operations without
 * locking the browser.  It will prevent user operations for the current page while it is
 * active ane will return the page to normal when it is deactivate.  blockUI accepts the following
 * two optional arguments:
 *
 *   message (String|Element|jQuery): The message to be displayed while the UI is blocked. The message
 *              argument can be a plain text string like "Processing...", an HTML string like
 *              "<h1><img src="busy.gif" /> Please wait...</h1>", a DOM element, or a jQuery object.
 *              The default message is "<h1>Please wait...</h1>"
 *
 *   css (Object):  Object which contains css property/values to override the default styles of
 *              the message.  Use this argument if you wish to override the default
 *              styles.  The css Object should be in a format suitable for the jQuery.css
 *              function.  For example:
 *              $.blockUI({
 *                    backgroundColor: '#ff8',
 *                    border: '5px solid #f00,
 *                    fontWeight: 'bold'
 *              });
 *
 * The default blocking message used when blocking the entire page is "<h1>Please wait...</h1>"
 * but this can be overridden by assigning a value to $.blockUI.defaults.pageMessage in your
 * own code.  For example:
 *
 *      $.blockUI.defaults.pageMessage = "<h1>Bitte Wartezeit</h1>";
 *
 * The default message styling can also be overridden.  For example:
 *
 *      $.extend($.blockUI.defaults.pageMessageCSS, { color: '#00a', backgroundColor: '#0f0' });
 *
 * The default styles work well for simple messages like "Please wait", but for longer messages
 * style overrides may be necessary.
 *
 * @example  $.blockUI();
 * @desc prevent user interaction with the page (and show the default message of 'Please wait...')
 *
 * @example  $.blockUI( { backgroundColor: '#f00', color: '#fff'} );
 * @desc prevent user interaction and override the default styles of the message to use a white on red color scheme
 *
 * @example  $.blockUI('Processing...');
 * @desc prevent user interaction and display the message "Processing..." instead of the default message
 *
 * @name blockUI
 * @param String|jQuery|Element message Message to display while the UI is blocked
 * @param Object css Style object to control look of the message
 * @cat Plugins/blockUI
 */
$.blockUI = function(msg, css) {
    $.blockUI.impl.install(window, msg, css);
};

// expose version number so other plugins can interogate
$.blockUI.version = 1.26;

/**
 * unblockUI removes the UI block that was put in place by blockUI
 *
 * @example  $.unblockUI();
 * @desc unblocks the page
 *
 * @name unblockUI
 * @cat Plugins/blockUI
 */
$.unblockUI = function() {
    $.blockUI.impl.remove(window);
};

/**
 * Blocks user interaction with the selected elements.  (Hat tip: Much of
 * this logic comes from Brandon Aaron's bgiframe plugin.  Thanks, Brandon!)
 * By default, no message is displayed when blocking elements.
 *
 * @example  $('div.special').block();
 * @desc prevent user interaction with all div elements with the 'special' class.
 *
 * @example  $('div.special').block('Please wait');
 * @desc prevent user interaction with all div elements with the 'special' class
 * and show a message over the blocked content.
 *
 * @name block
 * @type jQuery
 * @param String|jQuery|Element message Message to display while the element is blocked
 * @param Object css Style object to control look of the message
 * @cat Plugins/blockUI
 */
$.fn.block = function(msg, css) {
    return this.each(function() {
		if (!this.$pos_checked) {
            if ($.css(this,"position") == 'static')
                this.style.position = 'relative';
            if ($.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
            this.$pos_checked = 1;
        }
        $.blockUI.impl.install(this, msg, css);
    });
};

/**
 * Unblocks content that was blocked by "block()"
 *
 * @example  $('div.special').unblock();
 * @desc unblocks all div elements with the 'special' class.
 *
 * @name unblock
 * @type jQuery
 * @cat Plugins/blockUI
 */
$.fn.unblock = function() {
    return this.each(function() {
        $.blockUI.impl.remove(this);
    });
};

/**
 * displays the first matched element in a "display box" above a page overlay.
 *
 * @example  $('#myImage').displayBox();
 * @desc displays "myImage" element in a box
 *
 * @name displayBox
 * @type jQuery
 * @cat Plugins/blockUI
 */
$.fn.displayBox = function(css, fn, isFlash) {
    var msg = this[0];
    if (!msg) return;
    var $msg = $(msg);
    css = css || {};

    var w = $msg.width()  || $msg.attr('width')  || css.width  || $.blockUI.defaults.displayBoxCSS.width;
    var h = $msg.height() || $msg.attr('height') || css.height || $.blockUI.defaults.displayBoxCSS.height ;
    if (w[w.length-1] == '%') {
        var ww = document.documentElement.clientWidth || document.body.clientWidth;
        w = parseInt(w) || 100;
        w = (w * ww) / 100;
    }
    if (h[h.length-1] == '%') {
        var hh = document.documentElement.clientHeight || document.body.clientHeight;
        h = parseInt(h) || 100;
        h = (h * hh) / 100;
    }
    
    var ml = '-' + parseInt(w)/2 + 'px';
    var mt = '-' + parseInt(h)/2 + 'px';
    
    // supress opacity on overlay if displaying flash content on mac/ff platform
    var ua = navigator.userAgent.toLowerCase();
    var noalpha = isFlash && /mac/.test(ua) && /firefox/.test(ua);

    $.blockUI.impl.install(window, msg, { width: w, height: h, marginTop: mt, marginLeft: ml }, fn || 1, noalpha);
};


// override these in your code to change the default messages and styles
$.blockUI.defaults = {
    // the message displayed when blocking the entire page
    pageMessage:    '<h1>Please wait...</h1>',
    // the message displayed when blocking an element
    elementMessage: '', // none
    // styles for the overlay iframe
    overlayCSS:  { backgroundColor: '#fff', opacity: '0.5' },
    // styles for the message when blocking the entire page
    pageMessageCSS:    { width:'250px', margin:'-50px 0 0 -125px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #aaa' },
    // styles for the message when blocking an element
    elementMessageCSS: { width:'250px', padding:'10px', textAlign:'center', backgroundColor:'#fff'},
    // styles for the displayBox
    displayBoxCSS: { width: '400px', height: '400px', top:'50%', left:'50%' },
    // allow body element to be stetched in ie6
    ie6Stretch: 1,
    // supress tab nav from leaving blocking content?
    allowTabToLeave: 0,
    // Title attribute for overlay when using displayBox
    closeMessage: 'Click to close'
};

// the gory details
$.blockUI.impl = {
    box: null,
    boxCallback: null,
    pageBlock: null,
    pageBlockEls: [],
    op8: window.opera && window.opera.version() < 9,
    ffLinux: $.browser.mozilla && /Linux/.test(navigator.platform),
    ie6: $.browser.msie && /6.0/.test(navigator.userAgent),
    install: function(el, msg, css, displayMode, noalpha) {
        this.boxCallback = typeof displayMode == 'function' ? displayMode : null;
        this.box = displayMode ? msg : null;
        var full = (el == window);
        noalpha = noalpha || this.op8 || this.ffLinux;
        if (full && this.pageBlock) this.remove(window);
        // check to see if we were only passed the css object (a literal)
        if (msg && typeof msg == 'object' && !msg.jquery && !msg.nodeType) {
            css = msg;
            msg = null;
        }
        msg = msg ? (msg.nodeType ? $(msg) : msg) : full ? $.blockUI.defaults.pageMessage : $.blockUI.defaults.elementMessage;
        if (displayMode)
            var basecss = jQuery.extend({}, $.blockUI.defaults.displayBoxCSS);
        else
            var basecss = jQuery.extend({}, full ? $.blockUI.defaults.pageMessageCSS : $.blockUI.defaults.elementMessageCSS);
        css = jQuery.extend(basecss, css || {});
        var f = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:1000;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;document.write(\'\');"></iframe>')
                                 : $('<div class="blockUI" style="display:none"></div>');
        var w = $('<div class="blockUI" style="z-index:1001;cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
        var m = full ? $('<div class="blockUI blockMsg" style="z-index:1002;cursor:wait;padding:0;position:fixed"></div>')
                     : $('<div class="blockUI" style="display:none;z-index:1002;cursor:wait;position:absolute"></div>');
        w.css('position', full ? 'fixed' : 'absolute');
        if (msg) m.css(css);
        if (!noalpha) w.css($.blockUI.defaults.overlayCSS);
        if (this.op8) w.css({ width:''+el.clientWidth,height:''+el.clientHeight }); // lame
        if ($.browser.msie) f.css('opacity','0.0');

        $([f[0],w[0],m[0]]).appendTo(full ? 'body' : el);

        // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
        var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
        if (this.ie6 || expr) { 
            // stretch content area if it's short
            if (full && $.blockUI.defaults.ie6Stretch && $.boxModel)
                $('html,body').css('height','100%');

            // fix ie6 problem when blocked element has a border width
            if ((this.ie6 || !$.boxModel) && !full) {
                var t = this.sz(el,'borderTopWidth'), l = this.sz(el,'borderLeftWidth');
                var fixT = t ? '(0 - '+t+')' : 0;
                var fixL = l ? '(0 - '+l+')' : 0;
            }
            
            // simulate fixed position
            $.each([f,w,m], function(i,o) {
                var s = o[0].style;
                s.position = 'absolute';
                if (i < 2) {
                    full ? s.setExpression('height','document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"') 
                         : s.setExpression('height','this.parentNode.offsetHeight + "px"');
                    full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                         : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                    if (fixL) s.setExpression('left', fixL);
                    if (fixT) s.setExpression('top', fixT);
                }
                else {
                    if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                    s.marginTop = 0;
                }
            });
        }
        if (displayMode) {
            w.css('cursor','default').attr('title', $.blockUI.defaults.closeMessage);
            m.css('cursor','default'); 
            $([f[0],w[0],m[0]]).removeClass('blockUI').addClass('displayBox');
            $().click($.blockUI.impl.boxHandler).bind('keypress', $.blockUI.impl.boxHandler);
        }
        else
            this.bind(1, el);
        m.append(msg).fadeIn();
        if (msg.jquery) msg.fadeIn();
        if (displayMode) return;
        if (full) {
            this.pageBlock = m[0];
            this.pageBlockEls = $(':input:enabled:visible',this.pageBlock);
            setTimeout(this.focus, 20);
        }
        else this.center(m[0]);
    },
    remove: function(el) {
        this.bind(0, el);
        var full = el == window;
        if (full) {
            $('body').children().filter('.blockUI').fadeOut('slow',function(){
				$('body').children().filter('.blockUI').remove();
			})
            this.pageBlock = this.pageBlockEls = null;
        }
        else $('.blockUI', el).remove();
    },
    boxRemove: function(el) {
        $().unbind('click',$.blockUI.impl.boxHandler).unbind('keypress', $.blockUI.impl.boxHandler);
        if (this.boxCallback)
            this.boxCallback(this.box);
        $('body .displayBox').fadeOut('slow',function(){
			$(this).remove();
		});
    },
    // event handler to suppress keyboard/mouse events when blocking
    handler: function(e) {
        if (e.keyCode && e.keyCode == 9) {
            if ($.blockUI.impl.pageBlock && !$.blockUI.defaults.allowTabToLeave) {
                var els = $.blockUI.impl.pageBlockEls;
                var fwd = !e.shiftKey && e.target == els[els.length-1];
                var back = e.shiftKey && e.target == els[0];
                if (fwd || back) {
                    setTimeout(function(){$.blockUI.impl.focus(back)},10);
                    return false;
                }
            }
        }
        if ($(e.target).parents('div.blockMsg').length > 0)
            return true;
        return $(e.target).parents().children().filter('div.blockUI').length == 0;
    },
    boxHandler: function(e) {
        if ((e.keyCode && e.keyCode == 27) || (e.type == 'click' && $(e.target).parents('div.blockMsg').length == 0))
            $.blockUI.impl.boxRemove();
        return true;
    },
    // bind/unbind the handler
    bind: function(b, el) {
        var full = el == window;
        // don't bother unbinding if there is nothing to unbind
        if (!b && (full && !this.pageBlock || !full && !el.$blocked)) return;
        if (!full) el.$blocked = b;
        var $e = full ? $() : $(el).find('a,:input');
        $.each(['mousedown','mouseup','keydown','keypress','click'], function(i,o) {
            $e[b?'bind':'unbind'](o, $.blockUI.impl.handler);
        });
    },
    focus: function(back) {
        if (!$.blockUI.impl.pageBlockEls) return;
        var e = $.blockUI.impl.pageBlockEls[back===true ? $.blockUI.impl.pageBlockEls.length-1 : 0];
        if (e) e.focus();
    },
    center: function(el) {
		var p = el.parentNode, s = el.style;
        var l = ((p.offsetWidth - el.offsetWidth)/2) - this.sz(p,'borderLeftWidth');
        var t = ((p.offsetHeight - el.offsetHeight)/2) - this.sz(p,'borderTopWidth');
        s.left = l > 0 ? (l+'px') : '0';
        s.top  = t > 0 ? (t+'px') : '0';
    },
    sz: function(el, p) { return parseInt($.css(el,p))||0; }
};

})(jQuery);

//inplace editor
/*
+-----------------------------------------------------------------------+
| Copyright (c) 2007 David Hauenstein			                        |
| All rights reserved.                                                  |
|                                                                       |
| Redistribution and use in source and binary forms, with or without    |
| modification, are permitted provided that the following conditions    |
| are met:                                                              |
|                                                                       |
| o Redistributions of source code must retain the above copyright      |
|   notice, this list of conditions and the following disclaimer.       |
| o Redistributions in binary form must reproduce the above copyright   |
|   notice, this list of conditions and the following disclaimer in the |
|   documentation and/or other materials provided with the distribution.|
|                                                                       |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
| "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
| LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
| OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
| LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
|                                                                       |
+-----------------------------------------------------------------------+
*/

/* $Id: jquery.inplace.js,v 0.9.9 2007/03/06 18:00:00 tuupola Exp $ */

/**
  * jQuery inplace editor plugin.  
  *
  * Created by: David Hauenstein
  * http://www.davehauenstein.com/blog/
  *
  *
  * Nate Wiger (http://www.dangerrabbit.com) added callbacks, exposed 
  * more settings, added required values and "selected" options,
  * and enabled compatibility with jQuery.noConflict() mode.
  * Thanks to Joe and Vaska for helping me get this working on jQuery 1.1
  * Thanks to Pranav (http://www.startupdunia.com/) for finding a scope bug (0.9.4 release)
  * Thanks to Simon for finding some extraneous code (0.9.5 release)
  *
  *
  * @name  editInPlace
  * @type  jQuery
  * @param Hash    options						additional options 
  * @param String  options[url]					POST URL to send edited content
  * @param String  options[params]				paramters sent via the post request to the server; string; ex: name=dave&last_name=hauenstein
  * @param String  options[field_type]			can be: text, textarea, select; default: text
  * @param String  options[select_options]		this is a string seperated by commas for the dropdown options, if field_type is dropdown
  * @param String  options[textarea_cols]		number of columns textarea will have, if field_type is textarea; default: 25
  * @param String  options[textarea_rows]		number of rows textarea will have, if field_type is textarea; default: 10
  * @param String  options[bg_over]				background color of editable elements on HOVER
  * @param String  options[bg_out]				background color of editable elements on RESTORE from hover
  * @param String  options[saving_text]			text to be used when server is saving information; default: 'Saving...'
  * @param String  options[saving_image]		specify an image location instead of text while server is saving; default: uses saving text
  * @param String  options[value_required]		if set to true, the element will not be saved unless a value is entered
  * @param String  options[element_id]			name of parameter holding element_id; default: element_id
  * @param String  options[update_value]		name of parameter holding update_value; default: update_value
  * @param String  options[original_html]		name of parameter holding original_html; default: original_html
  * @param String  options[save_button]			image button tag to use as "Save" button
  * @param String  options[cancel_button]		image button tag to use as "Cancel" button
  * @param String  options[callback]			call function instead of submitting to url
  *           
  * @param String  options[ajax_callback]			call function instead of submitting to url            
  */

jQuery.fn.editInPlace = function(options) {

	//#######################################################################
	//DEFINE THE DEFAULT SETTINGS, SWITCH THEM WITH THE OPTIONS USER PROVIDES
	var settings = {
		url: "",
		params: "",
		field_type: "text",
		select_options: "",
		textarea_cols:  "25",
		textarea_rows:  "11111",
		bg_over: "#ffc",
		bg_out:  "transparent",
		saving_text:   "Saving...",
		saving_image:  "",
		default_text:  "",
		select_text: "Choose new value",
		value_required: null,
		element_id:    "element_id",
		update_value:  "update_value",
		original_html: "original_html",
		save_button:   '<input type="image" class="inplace_save" title="save" src="/html/images/btn_accept.gif">',
		cancel_button: '<input type="image" class="inplace_cancel" title="cancel" src="/html/images/btn_decline.gif">',
		callback: null,
		success: null,
		error: function(request){
			alert("Failed to save value: " + request.responseText || 'Unspecified Error');
		}
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	//#######################################################################
	//preload the loading icon if it exists
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}

	//#######################################################################
	//THIS FUNCTION WILL TRIM WHITESPACE FROM BEFORE/AFTER A STRING
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};

	//#######################################################################
	//THIS FUNCTION WILL ESCAPE ANY HTML ENTITIES SO "Quoted Values" work
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&amp;")
							 .replace(/</g, "&lt;")
							 .replace(/>/g, "&gt;")
							 .replace(/"/g, "&quot;");
  };

	//#######################################################################
	//CREATE THE INPLACE EDITOR
	return this.each(function(){

		if(jQuery(this).html() == "") jQuery(this).html(settings.default_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = jQuery(this);

		var click_count = 0;

		jQuery(this)

		.mouseover(function(){
			jQuery(this).addClass(settings.bg_over);
		})

		.mouseout(function(){
			jQuery(this).removeClass(settings.bg_over);
		})

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;
				//alert($(this).html());
				//save original text - for cancellation functionality
				var original_html = jQuery(this).html();
				var buttons_code  = settings.save_button + ' ' + settings.cancel_button;

				//if html is our default text, clear it out to prevent saving accidentally
				if (original_html == settings.default_text) jQuery(this).html('');

				if (settings.field_type == "textarea")
				{
				
					var use_field_type = '<textarea name="inplace_value" rows="' + settings.textarea_rows +
										 '" cols="' + settings.textarea_cols + '">' + jQuery(this).text().trim().escape_html() +
										 '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" class="inplace_value" name="inplace_value" value="' +
											jQuery(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split('~');
					var use_field_type = '<select name="inplace_value"><option value="">' + 
																settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + 
												optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';

				}
				else if(settings.field_type == "multi")
				{
					var optionsArray = settings.select_options.split('~');
					var use_field_type = '<select name="inplace_value[]" multiple size="10"><option value="">' + 
																settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + 
												optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';

				}
				else if(settings.field_type == 'file')
				{
					var use_field_type = '<input type="file" class="inplace_value" name="txtFileName" value="' +
											jQuery(this).text().trim().escape_html() + '" /><input type="hidden" name="action" value="multiple" /> ';
				}

				if(settings.field_type!='file')
				{	
					//insert the new in place form after the element they click, then empty out the original element
					jQuery(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' +
					use_field_type + ' ' + buttons_code + '</form>');	
				}
				else
				{
					jQuery("body").append('<div id="image_iframe_holder"><iframe id="file_iframe" name="file_iframe" src=""></iframe></div>');
					jQuery(this).html('<form name="inplace_form" class="inplace_form" style="display: inline; margin: 0; padding: 0;" method="post" enctype="multipart/form-data" action="'+settings.url+'" target="file_iframe">' +
					use_field_type + ' ' + buttons_code + '<input type="hidden" name="element_id" value="'+original_element.attr("id")+'" /><input type="hidden" name="type" value="'+settings.field_type+'"></form>');
				
				}
				
					/* ONLY IN THE CASE OF THE SPECIAL INSTRUCTIONS */
					var test_id = jQuery(this).attr('id');
					if(test_id && test_id.match(/SpecialInstructions/)!=null)
					{
						
						//alert($(this).children('form').children('textarea').html())
						instruct.create(jQuery(this),$(this).children('form').children('textarea'));
					}

				/*
				 * MODIFIED TO ADD JS CALENDAR SUPPORT
				 */
				
				var id = jQuery(this).attr('id');
				if(id.match(/date/gi)!=null && id.match(/_date_/gi)==null)
				{
					$(this).children('form').children('input.inplace_value').calendar({dateFormat:datejscal});
				}
				
			}//END- if(!editing) -END

			if(click_count == 1)
			{
				//CLICK CANCEL BUTTON functionality
				original_element.children("form").children(".inplace_cancel").click(function(){
					editing = false;
					click_count = 0;
					jQuery("#image_iframe_holder").remove(); //remove the file upload iframe
					//put the original background color in
					original_element.removeClass(settings.bg_over);

					//put back the original text
					original_element.html(original_html);

					return false;
				});
				
				
			
				//need to use the form before we switch to a saving image for FILE uploads
				if(settings.field_type == 'file') //need to upload a file through the iframe, so no 'real' ajax here...
				{
						original_element.children("form").submit(function(){
							
						//set saving message
						if(settings.saving_image != ""){
							var saving_message = '<img src="' + settings.saving_image + '" alt="Saving..." />';
						} else {
							var saving_message = settings.saving_text;
						}	
							
						editing = false;
						click_count = 0;
						$(this).css('display','none');
						$(this).after(saving_message);
						
						return true;
					})
					
							//var current = document.getElementById(id);
							//alert(current.innerHTML);
					
					
				}
				else{
				
				//CLICK SAVE BUTTON functionality
				original_element.children("form").children(".inplace_save").click(function(){
					
					/*
					 * MODIFIED BY Michael Forbes to include EXTERNAL validation (make your own)
					 */
						var errors = validate.initialize(jQuery(this).parent().children(0));
						if(errors > 0)
						{
							editing = false;
							click_count = 0;
							original_element.html(original_html);
							
							return false;
						}
					
					/*
					 * END MODIFICATION
					 */
					
					//put the original background color in
					original_element.removeClass(settings.bg_over);

					var new_html = jQuery(this).parent().children(0).val();
					//set saving message
					if(settings.saving_image != ""){
						var saving_message = '<img src="' + settings.saving_image + '" alt="Saving..." />';
					} else {
						var saving_message = settings.saving_text;
					}
				

					//place the saving text/image in the original element
					original_element.html(saving_message);

					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}

					if(settings.callback) {
						//alert(settings.field_type);
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							// put the newly updated info into the original element
							original_element.html(html || new_html);
						} else {
							// failure; put original back
							alert("Failed to save value: " + new_html);
							original_element.html(original_html);
						}
					} else if (settings.value_required && new_html == "") {
						editing = false;
					
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
							
						if(settings.field_type!='file')
						{
							
							jQuery.ajax({
								url: settings.url,
								type: "POST",
								data: settings.update_value + '=' + encodeURIComponent(new_html) + '&' + settings.element_id + '=' + 
										original_element.attr("id") + settings.params + 
										'&' + settings.original_html + '=' + escape(original_html),
								dataType: "html",
								complete: function(request){
									editing = false;
									click_count = 0;
								},
								success: function(html){
									// if the text returned by the server is empty, 
	   							// put a marker as text in the original element
									var new_text = html || settings.default_text;
	
									// put the newly updated info into the original element
									original_element.html(new_text).highlightFade({color:'#ffff33',iterator:'sinusoidal',speed:1000});
									
									if (settings.success) 
									{
										str = settings.success+'(html,original_element)';
										eval(str);
									}
									//proposal_update(html, original_element);
								},
								error: function(request) {
									original_element.html(original_html);
									if (settings.error) settings.error(request, original_element);
								}
							});
						}
						
					}

					return false;
				});
				}
			}//END- if(click_count == 1) -END

		});

	});

};
