
var holdFocus = null;

$(document).ready(function() { 	

	$("#template").change(function(){
		var parent = $(this);		


		if ($(this).val().length) {

			$.jGrowl("Loading... Please wait..." , { life: 500 });
			$(".variables-holder").slideUp(
				function () {
					
					$(".variables-holder").load(
						parent.val(),
						function(){
							ProcessTemplateVariables();
							$(".variables-holder").slideDown();

							$('.variables-holder .variables-tooltip').tooltip({
								placement: 'bottom',
								html: 'true',
								container : $("body")
							});

						}
					);
				}
			);
		}
	});

	$("input.FormItemTextbox, textarea").focus(function() {
		holdFocus = $(this);
	});

});	


function ProcessTemplateVariables() {

	$(".variables-holder li, .variables-holder span").each(function(e){
		//$(this).attr("title" , "Click to insert");
	
	});

	$(".variables-holder tbody td").tooltip({
		container : $("body")
	});

	$(".variables-holder tbody td").click(function(e) {
		e.preventDefault();

		if ($(".cke_focus").length){
			var id = $(".cke_focus").attr("id").replace("cke_" , "");
			CKEDITOR.instances[id].insertText($(this).html());
		} else {	

			if (holdFocus == null){
				Alert("You must select the field where you want to insert the variable!");
			} else {
				holdFocus.val(holdFocus.val() + $(this).html());
			}
		}

	});
}