/*
+-----------------------------------------------------------------------+
| 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.7 2007/01/20 01:00:00 tuupola Exp $ */

/**
  * jQuery inplace editor plugin.  
  *
  * Created by: David Hauenstein
  * http://www.davehauenstein.com/code/?a=inplace
  *
  *
  * 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
  *             
  */

$.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: "10",
		bg_over: "#ffc",
		bg_out: "transparent",
		saving_text: "Saving...",
		saving_image: "",
		novalue_text: "(bewerken)",
		table: "",
		rec_id: "",
		field: ""
	};

	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() {
		a = this.replace(/^\s+/, '');
		return a.replace(/\s+$/, '');
	};

	//#######################################################################
	//CREATE THE INPLACE EDITOR
	return this.each(function(){
		
		if($(this).html() == "") $(this).html(settings.novalue_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = $(this);

		var click_count = 0;

		$(this)

		.mouseover(function(){
			$(this).css("background", settings.bg_over);
		})

		.mouseout(function(){
			$(this).css("background", settings.bg_out);
		})

		.click(function(){
			click_count++;

			if(!editing) {
				editing = true;

				//save original text - for cancellation functionality
				var original_html = $(this).html();
				
				var original_value = $(this).text().trim();
				
				if (original_value == settings.novalue_text) {
					original_value = "";
					original_html = "";
				}
				
				var buttons_code = '<input type="submit" class="inplace_save" value="Opslaan"/> <input type="submit" class="inplace_cancel" value="Annuleren"/>';

				if(settings.field_type == "textarea"){
					
					if ($.browser.msie) {
						//MSIE
						var original_textarea = original_html.replace(/<br>/gi,"\n");
					} else {
						//FF
						var original_textarea = original_html.replace(/<br>/gi,"");
					}

					var use_field_type = '<textarea name="inplace_value" rows="' + settings.textarea_rows + '" cols="' + settings.textarea_cols + '">' + original_textarea /*original_value*/ + '</textarea>';

				} else if(settings.field_type == "text"){

					var use_field_type = '<input type="text" name="inplace_value" value="' + original_value + '" />';

				} else if(settings.field_type == "select"){

					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value"><option value="">Selecteer</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							use_field_type += '<option value="' + use_value.trim() + '">' + optionsValuesArray[0].trim() + '</option>';
						}
						use_field_type += '</select>';

				} else if(settings.field_type == "date") {
					var use_field_type = '<input id="date1" type="text" name="inplace_value" value="' + original_value + '" />';
					
				}

				//insert the new in place form after the element they click, then empty out the original element
				$(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');
				if (settings.field_type == "date") {
					$.datePicker.setDateFormat('ymd', '-');
					$.datePicker.setLanguageStrings(
						['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
						['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
						{p:'Vorige', n:'Volgende', c:'Sluiten', b:'Kies een datum'}
					);
					$('input#date1').datePicker();
				}
			}



			if(click_count == 1){
				//CLICK CANCEL BUTTON functionality
				$(".inplace_cancel").click(function(){
					editing = false;
					click_count = 0;

					//put the original background color in
					original_element.css("background", settings.bg_out);

					//put back the original text
					if (original_html == "") {
						original_element.html(settings.novalue_text);
					} else {
						original_element.html(original_html);
					}

					return false;
				});

				//CLICK SAVE BUTTON functionality
				$(".inplace_save").click(function(){
					//put the original background color in
					original_element.css("background", settings.bg_out);

					var new_html1 = $(this).parent().children(0).val();

					var new_html = new_html1.replace(/€/gi,"&euro;");					
					
		
					//set saving message
					if(settings.saving_image != ""){
						var saving_message = '<img src="' + settings.saving_image + '" alt="Bezig met opslaan..." />';
					} 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;
						settings.params = "&" + settings.params;
					}
/*
					$.ajax({
						url: settings.url,
						type: "POST",
						data: "update_value=" + escape(new_html) + "&element_id=" + original_element.attr("id") + settings.params + "&original_html=" + escape(original_html) + "&table=" + settings.table + "&id=" + settings.rec_id + "&field=" + settings.field,
						dataType: "html",
						complete: function(){},
						success: function(html){
							editing = false;
							click_count = 0;

							//if the text returned by the server is empty, put a marker as text in the original element
							var new_text = html || settings.novalue_text;

							//put the newly updated info into the original element
							original_element.html(new_text);
							
							// and in the possible other element
							document.getElementById("td_"+settings.field+"_"+settings.rec_id).innerHTML = new_text;
						},
						error: function(){}
					});
*/

					$.post(	settings.url + settings.params,
							{
								update_value: 		new_html,
								element_id:			original_element.attr("id"),
								original_html:		original_html,
								table:				settings.table,
								id:					settings.rec_id,
								field:				settings.field
							},
							function (html) {
								editing = false;
								click_count = 0;
	
								//if the text returned by the server is empty, put a marker as text in the original element
								var new_text = html || settings.novalue_text;
	
								//put the newly updated info into the original element
								original_element.html(new_text);
								
								// and in the possible other element
								$("#td_"+settings.field+"_"+settings.rec_id).html(new_text);	

							}
					);


					return false;
				});
			}

		});

	});

};