(function ($) {

/**
 * Opens a dialog
 */ 
$.fn.dialog = function(options) {
	var o = $.extend({
		'url': null,
		'afterActivate': null,
		'noCloseButton': false
	}, options);
	if (!o.url) {
		alert('Please provide a url for the dialog');
		return false;
	}
	return this.each(function(index) {
		$this = $(this);
		var closers = o.noCloseButton ? '___________' : null;
		if (!$this.data('overlay')) {
			$this.overlay({
				oneInstance: false, 
				close: closers,
				onClose: function () {
					$('*', $this).trigger('pie-closingOverlay');
					Pie.removing($this.get(0));
					$this.removeClass('pie_overlay');
				}
			});
		}
		var ods = $('.dialog_slot', $this);
		var ots = $('.title_slot', $this);
		if (!ods.length) {
			alert("Please add an element with the class 'dialog_slot' before calling dialog()");
		}
		$this.addClass('pie_overlay');
		$this.data('overlay').load();
		$this.addClass('pie_loading');
		ods.empty().addClass('pie_throb');
		var slotNames = ots.length ? 'dialog,title' : 'dialog';
		var url = Pie.ajaxExtend(o.url, slotNames);
		$.getJSON(url, function(response) {
			if (!response) {
				alert("Response is empty");
				return;
			}
			if ('errors' in response) {
				$this.data('overlay').close();
				alert(response.errors[0].message);
				return;
			}
			if ('title' in response.slots) {
				ots.html($('<h2 class="pie_dialog_title" />').html(response.slots.title));
				ods.html(response.slots.dialog);
			} else {
				ods.html(response.slots.dialog);
			}
			ods.removeClass('pie_throb');
			$this.removeClass('pie_loading');
			if (('stylesheets' in response) && ('dialog' in response.stylesheets)) {
				Pie.addStylesheet(response.stylesheets.dialog);
			}
			var afterLoad = function(alreadyLoaded) {
				if (('scriptLines' in response) && ('dialog' in response.scriptLines)) {
					eval(response.scriptLines.dialog);
				}
				Pie.activate(ods.get(0));
				if (ots.length && ('title' in response.slots)) {
					Pie.activate(ots.get(0));
				}
				Pie.handle(o.afterActivate);
			};
			if (('scripts' in response) && ('dialog' in response.scripts)) {
				Pie.addScript(response.scripts.dialog, afterLoad);
			} else {
				afterLoad();
			}
		});
	});
}

/**
 * Zoomer tool
 *
 * Generates an image and zooms it
 */

$.fn.zoomer = function(options) {

	var options2 = $.extend({
		"overlayWidth": 75, 
		"overlayHeight": 75,
		"zoomedWidth": null,
		"zoomedHeight": null,
		"widthRatio": null,
		"heightRatio": null,
		"overlayClass": "zoomer"
	}, options);

	return this.each(function(index) {
		// they should all be images
		var $this = $(this);
		if (!$this.is('img')) {
			return;
		}
		
		var data = $this.data('zoomer');
		if (data) {
			$this.unbind('mousemove', data.onMouseMove);
			$this.unbind('mouseleave', data.onMouseLeave);

			data.o_div.unbind('mousemove', data.onZoomerMouseMove);
			data.o_div.unbind('mouseleave', data.onZoomerMouseLeave);
			data.o_div.remove();
			$this.data('zoomer', null);
		}
		if (options === 'remove') {
			return;
		}
		
		var o_div = $('<div />')
			.css('position', 'absolute')
			.css('display', 'none')
			.css('overflow', 'hidden')
			.addClass('zoomer')
			.addClass(options2.overlayClass);
		var z_img = $('<img />')
			.css('position', 'absolute');
		if (options2.zoomedWidth) {
			z_img.css('width', zoomedWidth);
		} else if (options2.widthRatio) {
			z_img.width((options2.widthRatio * $this.width()));
		}
		if (options2.zoomedHeight) {
			z_img.css('height', zoomedHeight);
		} else if (options2.heightRatio) {
			z_img.height((options2.heightRatio * $this.height()));
		}
		z_img.attr('src', $this.attr('src'));
		if (options2.overlayWidth) {
			o_div.width(options2.overlayWidth);
		}
		if (options2.overlayHeight) {
			o_div.height(options2.overlayHeight);
		}

		var onMouseMove = function(e) {
			var offset = $this.offset();
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			var iw = $this.width(); // not inner, because it's an img
			var ih = $this.height();
			var xf = x/iw;
			var yf = y/ih;
			var ow = o_div.width();
			var oh = o_div.height();
			var zw = z_img.width();
			var zh = z_img.height();
			var o_bw = o_div.css('borderWidth');
			var o_bh = o_div.css('borderHeight');
			
			var o_left = offset.left + xf * (iw - ow);
			var o_top = offset.top + yf * (ih - oh);
			var z_left = offset.left + xf * (iw - zw) - o_left;
			var z_top = offset.top + yf * (ih - zh) - o_top;

			o_div.css('left', o_left+'px')
				.css('top', o_top+'px');
			z_img.css('left', z_left+'px')
				.css('top', z_top+'px');
			o_div.css('position', 'absolute');
			o_div.css('display', 'block');
		};

		var onMouseLeave = function(e) {
			var offset = $this.offset();
			if (e.pageX < offset.left
				|| e.pageY < offset.top 
				|| e.pageX > offset.left + $this.width()
				|| e.pageY > offset.top + $this.height()) {
				o_div.css('display', 'none');
			}
		};
		
		var onZoomerMouseMove = function(e) {
			var offset = $this.offset();
			if (e.pageX < offset.left
				|| e.pageY < offset.top 
				|| e.pageX > offset.left + $this.width()
				|| e.pageY > offset.top + $this.height()) {
				onMouseLeave(e);	
			} else {
				onMouseMove(e);
			}
		};
		var onZoomerMouseLeave = onZoomerMouseMove;

		//this.css('height', '200px');
		$this.mousemove(onMouseMove);
		$this.mouseleave(onMouseLeave);
		
		o_div.mousemove(onZoomerMouseMove);
		o_div.mouseleave(onZoomerMouseLeave);
		
		o_div.html(z_img);
		o_div.appendTo('body');
		
		$this.data('zoomer', {
			'onMouseMove': onMouseMove,
			'onMouseLeave': onMouseLeave,
			'onZoomerMouseMove': onZoomerMouseMove,
			'onZoomerMouseLeave': onZoomerMouseLeave,
			'o_div': o_div
		});
	});
	
};

$.fn.autogrow = function(options) {

       var o = $.extend({
           maxWidth: 1000,
           minWidth: 0,
           comfortZone: 10,
           onResize: null
       }, options);

		this.filter('textarea').each(function (i) {
			var $t = $(this), t = this;
			var val = '';

			t.style.resize = 'none';
			t.style.overflow = 'hidden';

			var tVal = t.value;			
			t.style.height = '0px';
			t.value = "W\nW\nW";
			var H3 = t.scrollHeight;
			t.value = "W\nW\nW\nW";
			var H4 = t.scrollHeight;
			var H = H4 - H3;
			t.value = tVal;
			tVal = null;

			$t.before("<div id=\"ataa_"+i+"\"></div>");

			var $c = jQuery('#ataa_'+i),
				c = $c.get(0);

			c.style.padding = '0px';
			c.style.margin = '0px';

			$t.appendTo($c);

			$t.bind('focus', function(){
				t.startUpdating()
			}).bind('blur', function(){
				t.stopUpdating()
			});

			this.heightUpdate = function(){

				tVal = t.value;
				t.style.height = '0px';
				var tH = t.scrollHeight + H;
				t.style.height = tH + 'px';
				c.style.height = 'auto';
				c.style.height = c.offsetHeight + 'px';

			}

			this.startUpdating = function(){
				$(this).bind('keyup keydown blur update autogrowCheck', t.heightUpdate);
				t.timeout1 = setTimeout(t.heightUpdate, 0);
				t.timeout2 = setTimeout(t.heightUpdate, 100);
			}

			this.stopUpdating = function(){
				clearTimeout(t.timeout1);
				clearTimeout(t.timeout2);
			}
			
			this.heightUpdate();
			if (o.onResize) {
				o.onResize(newWidth);
			}
		});

       this.filter('input:text').each(function(){
           var minWidth = o.minWidth || 20,
               val = '',
               input = $(this),
               testSubject = $(this).data('pie-tester');
				if (!testSubject) {
					 testSubject = $('<div class="pie_tester"/>');
					$(this).data('pie-tester', testSubject);
           			testSubject.insertAfter(input);
				}
               var check = function() {
                 	val = input.val();
					if (!val) {
						val = input.attr('placeholder');
					}

                   // Enter new content into testSubject
                   var escaped = val.replace(/&/g, '&amp;')
						//.replace(/\s/g,'&nbsp;')
						.replace(/</g, '&lt;')
						.replace(/>/g, '&gt;');
					testSubject.css({
		                   position: 'absolute',
		                   top: -9999,
		                   left: -9999,
		                   width: 'auto',
		                   fontSize: input.css('fontSize'),
		                   fontFamily: input.css('fontFamily'),
		                   fontWeight: input.css('fontWeight'),
		                   letterSpacing: input.css('letterSpacing'),
						   padding: input.css('padding'),
		                   whiteSpace: 'nowrap'
		               });
                   testSubject.html(escaped);

                   // Calculate new width + whether to change
                   var testerWidth = testSubject.outerWidth();
					var newWidth = Math.max(testerWidth + o.comfortZone, minWidth);
					var currentWidth = input.outerWidth();
					var isValidWidthChange = (((newWidth < currentWidth && newWidth >= minWidth)
                                            || (newWidth > minWidth)) && newWidth <= o.maxWidth);

                   // Animate width
                   if (isValidWidthChange) {
						input.width(newWidth);
						if (o.onResize) {
							o.onResize(newWidth);
						}
                   }

               };

           $(this).bind('keyup keydown blur update autogrowCheck', check);
			check();

       });

       return this;

   };



if (!('Tools' in Pie)) {
	Pie.Tools = {};
}
if (!('utils' in Pie.Tools)) {
	Pie.Tools.utils = {};
}

// utility functions we can use

Pie.Tools.utils.setSelRange = function(inputEl, selStart, selend) { 
 if ('setSelectionRange' in inputEl) { 
  inputEl.focus(); 
  inputEl.setSelectionRange(selStart, selend); 
 } else if (inputEl.createTextRange) { 
  var range = inputEl.createTextRange(); 
  range.collapse(true); 
  range.moveEnd('character', selend); 
  range.moveStart('character', selStart); 
  range.select(); 
 } 
}

Pie.constructors['pie_inplace_tool'] = 
Pie.Tools.InPlace = function(prefix) {

	// constructor & private declarations
	var me = this;
	var blurring = false;
	var focusedOn = null;
	var dialogMode = false;
	var previousValue = null;
	var noCancel = false;

	var tool_div = $('#'+prefix+'tool');
	var container_span = $('.pie_inplace_tool_container', tool_div);
	var static_span = $('.pie_inplace_tool_static', tool_div);
	if (!static_span.length) {
		static_span = $('.pie_inplace_tool_blockstatic', tool_div);
	}
	var edit_button = $('button.pie_inplace_tool_edit', tool_div);
	var save_button = $('button.pie_inplace_tool_save', tool_div);
	var cancel_button = $('button.pie_inplace_tool_cancel', tool_div);
	var fieldinput = $(':input', tool_div).not('button').eq(0)
		.addClass('pie_inplace_tool_fieldinput');
	var undermessage = $('.pie_inplace_tool_undermessage', tool_div);
	var throbber_img = $('<img />')
		.attr('src', Pie.url('plugins/pie/img/throbbers/bars16.gif'));
	if (container_span.hasClass('pie_nocancel')) {
		noCancel = true;
	}
	fieldinput.css({
		fontSize: static_span.css('fontSize'),
       	fontFamily: static_span.css('fontFamily'),
       	fontWeight: static_span.css('fontWeight'),
       	letterSpacing: static_span.css('letterSpacing')
	});
	fieldinput.autogrow({
		maxWidth: tool_div.parent().innerWidth()
	});
	if (container_span.hasClass('pie_editing')) {
		fieldinput.data('inplace_widthWasAdjusted', true);
		fieldinput.data('inplace_heightWasAdjusted', true);
	}
	var onClick = function() {
		var field_width = static_span.outerWidth();
		var field_height = static_span.outerHeight();
		if (fieldinput.is('select')) {
			field_width += 40;
		} else if (fieldinput.is('input[type=text]')) {
			field_width += 5;
			field_height = static_span.css('line-height');
		} else if (fieldinput.is('textarea')) {
			field_height = Math.max(field_height, 10);
		}
		fieldinput.css({
			fontSize: static_span.css('fontSize'),
           	fontFamily: static_span.css('fontFamily'),
           	fontWeight: static_span.css('fontWeight'),
           	letterSpacing: static_span.css('letterSpacing')
		});
		previousValue = fieldinput.val();
		container_span.addClass('pie_editing');
		if (!fieldinput.is('select')) {
			if (!fieldinput.data('inplace_widthWasAdjusted')) {
				//fieldinput.width(Math.max(field_width, 16));
				fieldinput.data('inplace_widthWasAdjusted', true);
			}
			try {
				if (!fieldinput.data('inplace_heightWasAdjusted')) {
					//fieldinput.height(Math.max(field_height, 16));
					fieldinput.data('inplace_heightWasAdjusted', true);
				}
			} catch (e) {

			}
			fieldinput.trigger('autogrowCheck');
		}
		undermessage.empty().css('display', 'none').addClass('pie_error');
		focusedOn = 'fieldinput';
		fieldinput.focus();
		if (fieldinput.attr('type') == 'text') {
			if (fieldinput.select) {
				fieldinput.select();
			}
		} else if (fieldinput.is('textarea')) {
			Pie.Tools.utils.setSelRange(
				fieldinput[0], 
				fieldinput.val().length, 
				fieldinput.val().length
			);
		}
	};
	var onSave = function() {
		undermessage.html(throbber_img)
			.css('display', 'block')
			.removeClass('pie_error');
		focusedOn = 'fieldinput';
		var form = $('.pie_inplace_tool_form', tool_div);
		var method = (form.length) ? form.attr('method') : 'post';
		var url = form.attr('action');
		
		var used_placeholder = false;
		if (fieldinput.attr('placeholder')
		&& fieldinput.val() === fieldinput.attr('placeholder')) {
			// this is probably due to a custom placeholder mechanism
			// so clear the field, rather than saving the placeholder text
			fieldinput.val('');
			used_placeholder = true;
		}
		
		$.ajax({
			url: Pie.ajaxExtend(url, 'pie_inplace', {'method': method}),
			type: 'POST',
			data: form.serialize(),
			dataType: 'json',
			error: function(xhr, status, except) {
				onSaveErrors('ajax status: ' + status + '... try again');
			},
			success: function(response) {
				if (typeof response !== 'object') {
					onSaveErrors("returned data is not an object");
					return;
				}
				if (response.errors && response.errors.length) {
					onSaveErrors(response.errors[0].message);
					return;
				}
				onSaveSuccess(response);
			}
		});
		
		if (used_placeholder) {
			fieldinput.val(fieldinput.attr('placeholder'));
		}
	};
	var onSaveErrors = function(message) {
		alert(message);
		fieldinput.focus();
		undermessage.css('display', 'none');
		/*
			.html(message)
			.css('whiteSpace', 'nowrap')
			.css('bottom', (-undermessage.height()-3)+'px');
		*/
	}
	var onSaveSuccess = function(response) {
		var newval = fieldinput.val();
		if ('slots' in response) {
			if ('pie_inplace' in response.slots) {
				newval = response.slots.pie_inplace;
				if (fieldinput.is('textarea')) {
					newval = newval.replace(/\n/g, '<br>')
						//.replace(/ /g,'&nbsp;');
				}
			}
		}
		static_span.html(newval);
		undermessage.empty().css('display', 'none').addClass('pie_error');
		container_span.removeClass('pie_editing').removeClass('pie_nocancel');
		noCancel = false;
	}
	var onCancel = function(dontAsk) {
		if (noCancel) {
			return;
		}
		if (!dontAsk && fieldinput.val() != previousValue) {
			dialogMode = true;
			var continueEditing = confirm(
				"Would you like to save your changes?"
			);
			dialogMode = false;
			if (continueEditing) {
				onSave();
				return;
			}
		}
		fieldinput.val(previousValue);
		fieldinput.blur();
		focusedOn = null;
		container_span.removeClass('pie_editing');
	};
	var onBlur = function() {
		setTimeout(function () {
			if (focusedOn 
			 || dialogMode
			 || !container_span.hasClass('pie_editing')) {
				return;
			}
			if (fieldinput.val() == previousValue) {
				onCancel(); return;
			}
			onCancel();	
		}, 100)
	};
	container_span.mouseover(function() { 
		container_span.addClass('pie_hover'); 
	});
	container_span.mouseout(function() { 
		container_span.removeClass('pie_hover'); 
	});
	static_span.click(onClick);
	edit_button.click(onClick);
	cancel_button.click(function() { onCancel(true); return false; });
	cancel_button.bind('focus mousedown', function() { setTimeout(function() { 
		focusedOn = 'cancel_button'; }, 50); 
	});
	cancel_button.blur(function() { focusedOn = null; setTimeout(onBlur, 100); });
	save_button.click(function() { onSave(); return false; });
	save_button.bind('focus mousedown', function() { setTimeout(function() { 
		focusedOn = 'save_button'; }, 50); 
	});
	save_button.blur(function() { focusedOn = null; setTimeout(onBlur, 100); });
	fieldinput.keyup(function() {
		var invisible_span = $('.pie_inplace_tool_invisible_span', tool_div);
		invisible_span
			.css('font-family', fieldinput.css('font-family'))
			.css('font-size', fieldinput.css('font-size'));
		invisible_span.text(fieldinput.val());
		save_button.attr('display', (fieldinput.val() == previousValue) ? 'none' : 'inline');
	});
	fieldinput.focus(function() { focusedOn = 'fieldinput'; });
	fieldinput.blur(function() { focusedOn = null; setTimeout(onBlur, 100); });
	fieldinput.change(function() { fieldinput.attr(fieldinput.val().length.toString() + 'em;') });
	fieldinput.keydown(function(event) {
		if (!focusedOn) {
			return false;
		}
		if (event.keyCode == 13) {
			if (! fieldinput.is('textarea')) {
				onSave(); return false;
			}
		} else if (event.keyCode == 27) {
			onCancel(); return false;
		}
	});
	fieldinput.closest('form').submit(function () {
		onSave();
	});

};

Pie.constructors['pie_tabs_tool'] = function(prefix, options) {

	var me = this;
	
	var tool = $('#'+prefix+'tool');
	if (!options.slot || !options.selector || !options.urls) {
		return;
	}
	$('a.pie_tabs_tab', tool).click(function () {
		var name = $(this).attr('data-name');
		if (!options.urls[name]) {
			return;
		}
		var url = Pie.ajaxExtend(options.urls[name], options.slot);
		$.getJSON(url, function (response) {
			if (response.errors) {
				if (response.errors.length > 0) {
					alert(response.errors[0].message);
				}
				return;
			}
			var closest = tool.closest(options.selector);
			closest.html(response.slots[options.slot]);
			function afterLoad() {
				if (('scriptLines' in response) && (options.slot in response.scriptLines)) {
					eval(response.scriptLines[options.slot]);
				}
				Pie.activate(closest.get(0));
				Pie.handle(options.afterActivate);
			};
			afterLoad();
		});
		return false;
	});
	
};

Pie.constructors['pie_form_tool'] = function(prefix, options) {

	// constructor & private declarations
	var me = this;

	me.onSubmit = options.onSubmit;
	me.onResponse = options.onResponse;
	me.onSuccess = options.onSuccess;
	me.slotsToRequest = 'form';

	var tool_div = $('#'+prefix+'tool');
	var form = tool_div.closest('form');
	if (!form.length) return;
	if (form.data('pie_form_tool')) return;
	form.submit(function() {
		var onResponse = function(response, status, xhr) {
			if (window.console) {
				window.console.log(response);
			}
			$('button', tool_div).closest('td').removeClass('pie_throb');
			Pie.handle(me.onResponse, me, arguments);
			$('div.pie_form_undermessagebubble', tool_div).empty();
			$('tr.pie_error', tool_div).removeClass('pie_error');
			if ('errors' in response) {
				me.applyErrors(response.errors)
				$('tr.pie_error').eq(0).prev().find(':input').eq(0).focus();
				if (response.scriptLines && response.scriptLines['form']) {
					eval(response.scriptLines.form);
				}
			} else {
				if (response.scriptLines && response.scriptLines['form']) {
					eval(response.scriptLines.form);
				}
				Pie.handle(me.onSuccess, me, arguments);
			}
		};
		$('button', tool_div).closest('td').addClass('pie_throb');
		var url = Pie.ajaxExtend(form.attr('action'), me.slotsToRequest);
		var result = {};
		Pie.handle(me.onSubmit, me, [form, result]);
		if (result.cancel) {
			return false;
		}
		$.post(url, form.serialize(), onResponse, 'json');
		return false;
	});
	form.data('pie_form_tool', true);
	
	me.applyErrors = function(errors) {
		var tool_div = $('#'+prefix+'tool');
		var err = null;
		for (var i=0; i<errors.length; ++i) {
			if (!('fields' in errors[i]) || Pie.typeOf(errors[i].fields) !== 'array'
			|| !errors[i].fields.length) {
				err = errors[i];
				continue;
			}
			for (var j=0; j<errors[i].fields.length; ++j) {
				var k = errors[i].fields[j];
				var td = $("td[data-fieldname='"+k+"']", tool_div);
				if (!td.length) {
					err = errors[i];
				}
				var tr = td.closest('tr').next();
				tr.addClass('pie_error');
				$('div.pie_form_undermessagebubble', tr)
					.html(errors[i].message);
			}
		}
		if (err) {
			alert(err.message);
		}
	};
	
	me.updateValues = function(newContent) {
		var tool_div = $('#'+prefix+'tool');
		if (Pie.typeOf(newContent) == 'string') {
			tool_div.html(newContent);
			Pie.activate(tool_div.children().get());
		} else if ('fields' in newContent) {
			// enumerate the fields
			alert("An array was returned. Need to implement that.");
			for (k in newContent.fields) {
				switch (newContent.fields[k].type) {
				 case 'date':
					break;
				 case 'select':
					break;
				 case 'checkboxes':
					break;
				 case 'radios':
				 	break;
				 default:
					break;
				}
			}
		}
	};

};

Pie.constructors['pie_panel_tool'] =
Pie.Tools.Panel = function(prefix) {

	// constructor & private declarations
	var me = this;
	var form_val = null;
	var tool_div, container;
	Pie.Tool.apply(me, arguments);

	me.init = function() {
		var tool_div = $('#'+prefix+'tool');
		var form = $('form', tool_div);
		var form_tool_prefix = prefix+'pie_form_';
		var static_tool_prefix = prefix+'idstatic_pie_form_';
		var container = $('.pie_panel_tool_container', tool_div);
		if (form_tool_prefix in Pie.tools) {
			var form_tool = Pie.tools[form_tool_prefix];
			form_tool.onSuccess[prefix] = function() {
				form_val = form.serialize();
				container.removeClass('pie_modified');
				container.removeClass('pie_editing');
			};
			if (static_tool_prefix in Pie.tools) {
				var static_tool = Pie.tools[static_tool_prefix];
			}
			form_tool.onResponse[prefix] = function(response) {
				var buttons = $('.pie_panel_tool_buttons', tool_div);
				buttons.removeClass('pie_throb');
				if ('slots' in response) {
					if ('form' in response.slots) {
						form_tool.updateValues(response.slots.form);
					}
					if (('static' in response.slots) && static_tool) {
						static_tool.updateValues(response.slots.static);
					}
				}
			}
			form_tool.onSubmit[prefix] = function() {
				var buttons = $('.pie_panel_tool_buttons', tool_div);
				buttons.addClass('pie_throb');
			}
			form_tool.slotsToRequest = 'form,static';
		}
	};

	tool_div = $('#'+prefix+'tool');
	container = $('.pie_panel_tool_container', tool_div);
	var form = $('form', tool_div);
	var edit_button = $('.pie_panel_tool_edit', tool_div);
	var cancel_button = $('button.pie_panel_tool_cancel', tool_div);
	form_val = form.serialize();
	form.bind('change keyup keydown blur', function() {
		var new_val = form.serialize();
		if (form_val !== new_val) {
			container.addClass('pie_modified');
		} else {
			container.removeClass('pie_modified');
		}
	});	
	if (container.hasClass('pie_panel_tool_toggle_onclick')) {
		var header = $('.pie_panel_tool_header', container);
		header.click(toggleExpand);
	} else if (container.hasClass('pie_panel_tool_toggle_move')) {
		var header = $('.pie_panel_tool_header', container);
		header.mouseenter(function() {
			container.removeClass('pie_collapsed');
			container.addClass('pie_expanded');
		});
		container.mouseleave(function() {
			container.addClass('pie_collapsed');
			container.removeClass('pie_expanded');
		});
	}
	edit_button.click(function() {
		container.addClass('pie_editing');
		container.removeClass('pie_collapsed');
		container.addClass('pie_expanded');
		return false;
	});
	cancel_button.click(function() {
		container.removeClass('pie_editing');
		container.removeClass('pie_modified');
		return true; // really cancel the form
	});
	
	var toggleExpand = function() {
		if (container.hasClass('pie_collapsed')) {
			container.removeClass('pie_collapsed');
			container.addClass('pie_expanded');
		} else {
			container.addClass('pie_collapsed');
			container.removeClass('pie_expanded');
		}
	};
};


})(jQuery);
