jQuery().ready(function(){
	jQuery(".down").hide();
	 	jQuery(".answer").mouseover(function(){
		jQuery(this).find(".down").show();
	})	
 	jQuery(".down").click(function(){
		jQuery(this).parent().parent().parent().css("opacity", "0.2");
	})	
	jQuery(".answer").mouseout(function(){
		jQuery(this).find(".down").hide();
	})
});

function poll_vote(topicid, choice, up_down){
 jQuery.ajax({
   type: "GET",
   url: "http://www.she20.com/smf/index2.php?task=votePollChoice&topic="+topicid+".0&voteChoice="+choice+"&voteDirection="+up_down,
   success: function(msg){
     if(up_down==0){
     	jQuery("#vote_"+choice).remove();
     }
     jQuery("#vote_"+choice).children().removeAttr("onclick");
     jQuery("#vote_"+choice).addClass('rating-disabled');
     jQuery("#remove_"+choice).remove();
   }
 });	
}

function answer_vote(topicid, msg, up_down){
	jQuery.ajax({
		url: "http://www.she20.com/smf/index2.php?task=voteAnswer&topic="+topicid+".0&m="+msg+"&mode="+up_down,
		type: "GET",
		success: function(html){
			// if the text returned by the server is empty, 
			// put a marker as text in the original element
			var retdata = html.split("|"); 
			var returnCode = retdata[0];   							
			var returnMsg = retdata[1] ;
			var voteCountYes = retdata[2];
			var voteCountNo = retdata[3];
			
			//show the vote box
			if(returnCode == 0)
			{
				jQuery("#voting_yes_"+msg).html(voteCountYes);
				jQuery("#voting_no_"+msg).html(voteCountNo);
			}
			//some kind of error message
			else 
			{
				tb_show('Message', '#TB_inline?height=100&width=300', false, '<br>'+returnMsg);
			}
	
		},
		error: function(request) {
			jQuery.facebox('<b> Error </b></br> ' + request );
		}
	});
	
}

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:  "10",
		bg_over: "#ffc",
		bg_out:  "transparent",
		saving_text:   "Saving...",
		saving_image:  "",
		default_text:  "(Click here to add 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="submit" class="inplace_save" value="Save"/>',
		cancel_button: '<input type="submit" class="inplace_cancel" value="Cancel"/>',
		callback: null,
		success: null,
		topicid:0,
		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).css("background", settings.bg_over);
		})

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

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;

				//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" class="inplace_field" 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" name="inplace_value" autocomplete="off" class="inplace_field" id="newChoice" 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" class="inplace_field"><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>';
				}

				//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>');
									
				jQuery("#newChoice").autocomplete("http://www.she20.com/smf/index2.php?task=rpc", {width: 260,	selectFirst: false});

			}//END- if(!editing) -END

			if(click_count == 1)
			{
				//set the focus to the new input element
				original_element.children("form").children(".inplace_field").focus().select();

				//HIT ESC KEY
				jQuery(document).keyup(function(event){
				    if (event.keyCode == 27) {
				        editing = false;
						click_count = 0;

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

						//put back the original text
						original_element.html(original_html);

						return false;
				    }
				});

				//CLICK CANCEL BUTTON functionality
				original_element.children("form").children(".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
					original_element.html(original_html);

					return false;
				});

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

					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) {
						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;
						click_count = 0;
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
						jQuery.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + 
									original_element.attr("id") + settings.params + 
									'&' + settings.original_html + '=' + original_html,
							dataType: "text",
							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 retdata = html.split("|"); 
   							var returnCode = retdata[0];   							
								var new_text = retdata[1] || settings.default_text;
   							var newItemID = retdata[2];
								
								//show the vote box
								if(returnCode == 0)
								{
									original_element.before("<div id=\"vote_"+newItemID+"\" class=\"rating-widget\"><a class=\"up\" onclick=\"poll_vote("+settings.topicid+","+newItemID+",1)\">Vote yes</a></div>");
								}

								// put the newly updated info into the original element
								original_element.html(new_text);
								if (settings.success) settings.success(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

		});

	});

};
