document.observe("dom:loaded", handleStartup);

function handleStartup() {
	processPhotos();
//	attachModalboxActions();
	convertTemperature(Settings.temp);
	convertWeight(Settings.weight);
	findWeather();
	convertMicroformatsToMaps();
	makeEditable();
	attachToDos();
	attachBatchCodeWatchers();
	formatDates(Settings.date_format);
	attachToolTips();
/*	hideArchived();*/
	showApiariesMap();
	makeHivesSortable();
	if($('flashMessage')) {
		new Effect.Highlight('flashMessage', {duration: 2});		
	}
}

function attachToolTips() {
	$$('.tooltip').each(function(el) {
	    new Tip(el, el.title,{
		  title: 'Notes',
		  stem: 'bottomMiddle',
		style: 'protogrey',
		radius: 3,
		border: 3,
		  hook: { tip: 'bottomMiddle'},
		  offset: { x: 10, y: 10 },
			hideOthers: true
		});
		el.title = '';
	  });
}

function attachBatchCodeWatchers() {
	if (!$('HarvestBatchCode')) {
		return;
	}
	$('HarvestHarvestDateDay').observe('change', updateBatchCode);
	$('HarvestHarvestDateMonth').observe('change', updateBatchCode);
	$('HarvestHarvestDateYear').observe('change', updateBatchCode);
	$('HarvestHiveId').observe('change', updateBatchCode);
	if ($F('HarvestBatchCode') =='') {
		updateBatchCode(null);
	}
}

function updateBatchCode(e) {
	var d = $F('HarvestHarvestDateDay');
	var m = $F('HarvestHarvestDateMonth');
	var y = $F('HarvestHarvestDateYear').substr(2);
	var h = $F('HarvestHiveId');
	
	var c = h + 'H' + y + m + d;
	$('HarvestBatchCode').value = c;
}
var scriptsLoading = {};
function loadScript(filename) {	
	if(scriptsLoading[filename]) {
		return;
	}
	scriptsLoading[filename] = true;
	var head;
	var script;
	head = $$('head')[0];
	if (head) {
	    script = new Element('script', { type: 'text/javascript', src: filename});
	    head.appendChild(script);
	}
}

function convertMicroformatsToMaps() {
	if ($$('.geo').length == 0) {
		return;
	}
	
		if (typeof OpenLayers == 'undefined') {
			loadScript('/js/openlayers/OpenLayers.js');
			watchForSymbol({symbol: ['OpenLayers'], onSuccess: function(o) {
				window.setTimeout("convertMicroformatsToMaps()", 500);
			}});

			return;
		} else if ( typeof OpenLayers.Layer.OSM.Mapnik == 'undefined'){
			loadScript('//www.openstreetmap.org/openlayers/OpenStreetMap.js');
			watchForSymbol({symbol: ['OpenLayers.Layer.OSM.Mapnik'], onSuccess: function(o) {
				window.setTimeout("convertMicroformatsToMaps()", 500);
			}});
		} else {
			$$('.geo').each(buildMap);
		}
}

function attachToDos() {
	if ($('InspectionHiveId')) {
		$('InspectionHiveId').observe('change', function(e) {
			showToDoBoxes();
		});
	showToDoBoxes();
	
	} 
}



function showToDoBoxes() {
	$$('.todos input').each(function(item) {
		item.checked = false;
	});
	var id = $('InspectionHiveId').value;

	
	$$('.todos').each(function(item) {
		if (item.id == ('todos-' + id)) {
			item.show();
		} else {
			item.hide();
		}
	});
}

function makeEditable() {
	$$('.editableInPlace').each(function(item) {
		var b = item.id.split('-');
		if(b.length < 3) {
			return;
		}
		var url = '/' + b[0] + 's/editinplace/' + b[2] + '/field:' + b[1];
		if (b.length > 3) {
			for (var i = 3; i < b.length; i++) {
				url += '/' + b[i];
			}
		}
		var options = {
			cancelControl: 'button',
			okText: Settings.translations['Save'],
			cancelText: Settings.translations['Cancel'],
			rows: 1
		}
		
		if (item.hasClassName('autocomplete')) {
			options.onEnterEditMode = function(e) {
				setInPlaceAutoComplete(e, url);
			}
		}
		
		if (b[2] == '0') {
			options.onComplete = editableNewCallback
		}
		item.editor = new Ajax.InPlaceEditor(item, url, options);
	});
}
function setInPlaceAutoComplete (e, url) {
	var c = e.element.id.split('-')[0];
	var url = '/' + c + 's/autoComplete';
	
	var id = e.element.id + '-inplaceeditor_input';
	var opts = id + '_options';
	window.setTimeout("doSetinPlaceAutocomplete('" + id + "', '" + opts + "', '" + url + "')", 500);
}

function makeHivesSortable() {
	return;
	$$('.hive.sortable').each(makeHiveSortable);
	Sortable.create('shed',{ghosting:false, dropOnEmpty: true, containment: $$('.sortable'), overlap: 'horizontal', constraint: false});
	
}

function makeHiveSortable(hive) {
	Sortable.create(hive,{ghosting:false, dropOnEmpty: true, containment: $('.sortable'), constraint: false});
}

function doSetinPlaceAutocomplete(id, opts, url) {
	$(id).insert({after: "<div class='auto_complete' style='display: none' id='" + opts + "'></div>"});
	new Ajax.Autocompleter(id,opts,url,{});
}

function editableNewCallback(transport, element) {
	element.editor.dispose();
	var h = transport.getHeader('X-Beetight-id');

	new Effect.Highlight(element, {startcolor: this.options.highlightColor});
	element.className = 'editableInPlace';
	var id = element.id;
	var b = id.split('-');
	
	var newid = b[0] + '-' + b[1] + '-' + h;
	element.id = newid;
	
	var el = new Element(element.tagName, {
		id: id,
		className: 'editableInPlace newItem autocomplete'
	});
	el.innerHTML = 'Click to add new task...'
	element.up().appendChild(el);
	makeEditable();
}

function findWeather() {
	$$('.weatherBox').each(function(item) {
		var apiary = item.id.substr(8);
		new Ajax.Updater(item, '/apiaries/weather/' + apiary, {onComplete: function(o) {
			convertTemperature(Settings.temp);
		}});
	});
}

function convertTemperature(units) {
	if (units == 'C') {		
		$$('.fahrenheit').each(function(item) {
			new PeriodicalExecuter(function(pe) {				
			pe.stop();
			
			if (item.done) {
				return;
			}
			var f = parseInt(item.innerText);
			var c = Math.round(5/9 * (f - 32));
			item.innerText = c + '°C';
			item.className = 'celsius';
			item.done = true;
		}, 0.1)});
	} else {
		$$('.celsius').each(function(item) {
			new PeriodicalExecuter(function(pe) {				
			pe.stop();
			if (item.done) {
				return;
			}
			
			var c = parseInt(item.innerText);
			var f = Math.round(c * 1.8+32 );
			item.innerText = f + '°F';
			item.className = 'fahrenheit';
			item.done = true;
		}, 0.1)});
	}
}

function convertWeight(units) {
	var factor = 2.204;
	$$('.weightDisplay').each(function(o) {
		if(o.down('.imperial')) {
			return;
		}
		var imperial = Builder.node('span', {className: 'imperial'}, [
			Builder.node("span", {className: 'lb'}), ' lb  ',
			Builder.node("span", {className: 'oz'}), ' oz'
			
		]);
		
		var kg = parseFloat(o.down('.kg').innerText);
		var lboz = kg * factor;
		var lb = Math.floor(lboz);
		var oz = Math.round((lboz - lb) * 16) ;
		imperial.down('.lb').innerText = lb;
		imperial.down('.oz').innerText = oz;
		o.appendChild(imperial);
		if (units == 'M') {
			imperial.hide();
		} else {
			o.down('.metric').hide();
		}
	});
	
	$$('.weightEdit').each(function(o) {
		var kg = o.down('.kg');
		if(o.down('.imperial')) {
			return;
		}
		
		var metric = Builder.node('span', {className: 'metric'}, [
			Builder.node("input", {className: 'kg'}), 'kg'
		]);
		
		o.appendChild(metric);
		
		var imperial = Builder.node('span', {className: 'imperial'}, [
			Builder.node("input", {className: 'lb'}), 'lb',
			Builder.node("input", {className: 'oz'}), 'oz'
			
		]);
		
		o.appendChild(imperial);
		
		var lb = imperial.down('.lb');
		var oz = imperial.down('.oz');
		var gr = o.down('.grams');
		
		
		gr.hide();
		var kg = metric.down('.kg');
		
		kg.observe('change', function (e) {
			convertToLbOz(kg,lb,oz,gr)
		});
	
		lb.observe('change', function (e) {
			convertToKg(kg,lb,oz,gr)
		});
		
		oz.observe('change', function (e) {
			convertToKg(kg,lb,oz,gr)
		});
		if (isNaN(parseInt(gr.value))) {
			gr.value = 0;
		}
		kg.value = parseInt(gr.value) / 1000;
		convertToLbOz(kg,lb,oz,gr);
		if (units == 'M') {
			o.down('.imperial').hide();
		} else {
			o.down('.metric').hide();
		}
		
	});
}

function convertToLbOz(kgO,lbO,ozO, g) {
	var factor = 2.204;
	
	var kg = parseFloat(kgO.value);
	g.value = Math.round(kg * 1000);
	kgO.value = g.value / 1000;
	
	var lboz = kg * factor;
	var lb = Math.floor(lboz);
	var oz = Math.round((lboz - lb) * 16) ;
	lbO.value = lb;
	ozO.value = oz;
}

function convertToKg(kgO,lbO,ozO, g) {
	
	ozO.value = parseInt(ozO.value);
	if (ozO.value > 16) {
		var extraLbOz = ozO.value / 16;
		var extraLb = Math.floor(extraLbOz);
		ozO.value = Math.round((extraLbOz - extraLb) * 16);
		
		lbO.value = parseInt(lbO.value) + extraLb;
	} else {
		lbO.value = parseInt(lbO.value);
	}
	var kg = parseFloat(lbO.value) / 2.205;
	kg += parseInt(ozO.value) / 35.274;
	g.value = Math.round(kg * 1000);
	kgO.value = g.value / 1000;
	
}

function attachModalboxActions() {
	$$('.modalbox').each(function(item){
		var link = item.href;
		item.observe("click", function(event) {
			var title;
			if (item.title) {
				title = item.title;
			} else {
				title = item.innerText;
			}
			item.href='#';
			Modalbox.show(link, {title: title, width: 600, afterLoad: function() {
				convertTemperature(Settings.temp);
				convertWeight(Settings.weight);
			}});
			event.stop();
			item.href=link;
		});
	});
}

function processPhotos() {
	if ($$('.photos').length < 1) {
		return;
	}
	if ($$('.photos')[0].processed == 'yes') {
		return;
	}
	$$('.photos a').each(function(item) {
		var im = Builder.node('img', {src: '/img/silk/bin.png', className: 'deleteButton', id: 'delete-' + item.firstDescendant().id, title: 'Delete photo'});
		im.observe('click', deletePhotoFromButton)
		item.insert(im);
	});
	$$('.photos')[0].processed = 'yes';
}

function deletePhotoFromButton(event) {
	var id = event.element().id.substr(13);
	event.stop();
	
	deletePhoto(id);
}

function deletePhoto(id) {
	if (!confirm("Do you want to delete this photo? This cannot be undone.")) {
		return false;
	}
	new Ajax.Updater('content','/inspection_photos/delete/' + id + '?return=' + encodeURIComponent(document.location.pathname), 
		{asynchronous:true, evalScripts:true, onComplete: handleStartup, requestHeaders:['X-Update', 'content']});
}

function locationCallback(txt, li) {
	$('locationdisplayinner').innerHTML = li.innerHTML;
	$('locationdisplay').show();
	$('Address').hide();
	$('ApiaryWoeid').value = li.id.substr(6);
	var coords = li.attributes.rel.value.split(',');
	$('ApiaryLat').value = coords[0];
	$('ApiaryLon').value = coords[1];
}

function clearLocation() {
    $('locationdisplayinner').innerHTML = '';
    $('locationdisplay').hide();
    $('Address').show();
    $('Address').focus();
    $('ApiaryWoeid').value = null;
	$('ApiaryLat').value = null;
	$('ApiaryLon').value = null;
}

function forageLocationCallback(txt, li) {
	$('locationdisplayinner').innerHTML = li.innerHTML;
	$('locationdisplay').show();
	$('Location').hide();
	var coords = li.attributes.rel.value.split(',');
	$('ForageLat').value = coords[0];
	$('ForageLon').value = coords[1];
}

function clearForageLocation() {
    $('locationdisplayinner').innerHTML = '';
    $('locationdisplay').hide();
    $('Location').show();
    $('Location').focus();
	$('ForageLat').value = null;
	$('ForageLon').value = null;
}

function formatDates(format) {
	if (!format) {
		return;
	}
	$$('.date').each(function(item) {
		if(item.hasClassName('input')) {
			return;
		}
		var parts = item.innerText.split('-');
		if(parts.length != 3) {
			return;
		}
		
		var date = new Date();
		date.setFullYear(parseInt(parts[0], 10));
		
		/* Zero-indexed */
		date.setMonth(parseInt(parts[1], 10) - 1);
		date.setDate(parseInt(parts[2], 10));
		
		
		item.innerText = date.format(format);

		
	})
}    

/* Mapping */


/* For the mini microformat maps*/

function buildMap(element) {
	var mapBox = element.down('.map');
	var latSpan = element.down('.latitude');
	var lonSpan = element.down('.longitude');
	
	if (!mapBox || !lonSpan || !latSpan) {
		return;
	}
	element.down('.comma').hide();
	
	var lat = latSpan.innerHTML;
	
	latSpan.hide();
	var lon = lonSpan.innerHTML;
	lonSpan.hide();
	
	if (!lat || !lon) {
		return;
	}
	if (!mapBox.id) {
		mapBox.id = 'map' + Math.floor(Math.random() * 1000);
	}
	var map = new OpenLayers.Map(mapBox.id, {controls: [
            new OpenLayers.Control.Navigation(),
			new OpenLayers.Control.ZoomPanel()
        ]});
/*	var hybrid = new OpenLayers.Layer.VirtualEarth("Hybrid" + mapBox.id, { type: VEMapStyle.Hybrid});*/
	var baseMap = new OpenLayers.Layer.OSM.Mapnik("OSM"+ mapBox.id);
	
	map.addLayer(baseMap);
	var markers = new OpenLayers.Layer.Markers("Markers" + mapBox.id);
	var latlon = new OpenLayers.LonLat(lon,lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
	var m = new OpenLayers.Marker(latlon);
	map.addLayer(markers);
	
	markers.addMarker(m);
/*	map.addControl(new OpenLayers.Control.DragMarker(markers));*/
	map.setCenter(latlon, 12);
	element.map = map;
}

function showApiariesMap() {
	if (typeof OpenLayers == 'undefined') {
/*		loadScript('http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2');*/
		loadScript('/js/openlayers/OpenLayers.js');
		watchForSymbol({symbol: ['OpenLayers'], onSuccess: function(o) {
			window.setTimeout("showApiariesMap()", 500);
		}});
		
		return;
	} else if ( typeof OpenLayers.Layer.OSM.Mapnik == 'undefined'){
		loadScript('//www.openstreetmap.org/openlayers/OpenStreetMap.js');
		watchForSymbol({symbol: ['OpenLayers.Layer.OSM.CycleMap'], onSuccess: function(o) {
			window.setTimeout("showApiariesMap()", 500);
		}});
	} else {
		$$('.apiaryMap').each(doShowMap);
	}
}

function doShowMap(mapBox) {

	if (!mapBox.id) {
		mapBox.id = 'map' + Math.floor(Math.random() * 1000);
	}

	map = new OpenLayers.Map(mapBox.id, {controls: [
            new OpenLayers.Control.Navigation(),
			new OpenLayers.Control.PanZoomBar(),
			new OpenLayers.Control.Attribution()
        ]});
/*	var hybrid = new OpenLayers.Layer.VirtualEarth("Hybrid", { type: VEMapStyle.Hybrid});*/
	var baseMap = new OpenLayers.Layer.OSM.Mapnik("OSM");

	var style = new OpenLayers.Style({
	    externalGraphic: "http://www.beetight.com/img/hives/wbc.png",
	    graphicHeight: 16,
	    graphicWidth: 16,
	    graphicXOffset: 8,
	    graphicYOffset: 8,
		cursor: "pointer"
	});

	var styleMap = new OpenLayers.StyleMap({'default':style});

	var apiaries = new OpenLayers.Layer.Vector("KML", {
	                projection: map.displayProjection,
					styleMap: styleMap,
	                strategies: [new OpenLayers.Strategy.Fixed()],
	                protocol: new OpenLayers.Protocol.HTTP({
	                    url: "/apiaries/kml",
	                    format: new OpenLayers.Format.KML({
	                        extractStyles: true,
	                        extractAttributes: true
	                    })
	                })
	            });

        var select = new OpenLayers.Control.SelectFeature(apiaries);
        map.addControl(select);
        select.activate();
        apiaries.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect,
			"loadend": function() {
			                map.zoomToExtent(apiaries.getDataExtent());
			            }
        });

	var forages = new OpenLayers.Layer.Vector("KML", {
	                projection: map.displayProjection,
					styleMap: styleMap,
	                strategies: [new OpenLayers.Strategy.Fixed()],
	                protocol: new OpenLayers.Protocol.HTTP({
	                    url: "/forages/kml",
	                    format: new OpenLayers.Format.KML({
	                        extractStyles: true,
	                        extractAttributes: true
	                    })
	                })
	            });

        var select2 = new OpenLayers.Control.SelectFeature(forages);
        map.addControl(select2);
        select2.activate();  
 
        forages.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

		map.addLayers([baseMap, apiaries, forages]);

    }
    function onPopupClose(evt) {
        select.unselectAll();
    }
    function onFeatureSelect(event) {
        var feature = event.feature;
        // Since KML is user-generated, do naive protection against
        // Javascript.
        var content = feature.attributes.description;
        if (content.search("<script") != -1) {
            content = "Content contained Javascript! Escaped content below.<br>" + content.replace(/</g, "&lt;");
        }
        popup = new OpenLayers.Popup.FramedCloud("apre", 
                                 feature.geometry.getBounds().getCenterLonLat(),
                                 new OpenLayers.Size(200,200),
                                 content,
                                 null, true, onPopupClose);
        feature.popup = popup;
        map.addPopup(popup);
    }
    function onFeatureUnselect(event) {
        var feature = event.feature;
        if(feature.popup) {
            map.removePopup(feature.popup);
            feature.popup.destroy();
            delete feature.popup;
        }
    }


function watchForSymbol(options) {
	var stopAt;

	if (!options || !options.symbol || !Object.isFunction(options.onSuccess)) {
		throw "Missing required options";
	}
	options.onTimeout = options.onTimeout || Prototype.K;
	options.timeout = options.timeout || 10;
	stopAt = (new Date()).getTime() + (options.timeout * 1000);
	new PeriodicalExecuter(function(pe) {
		if (typeof options.symbol != 'object') {
			options.symbol = [options.symbol];
		}
		
		var ok = true;
		for (var i = 0; i < options.symbol.length; i++) {
			if (eval('typeof ' + options.symbol[i] ) == "undefined") {
				ok = false;
				break;
			}		
		}
		if (ok) {
			options.onSuccess(options.symbol);
			pe.stop();
		} else if ((new Date()).getTime() > stopAt) {
			options.onTimeout(options.symbol);
			pe.stop();
		}
	}, 0.5);
}





// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: Settings.translations.shortMonths,
	longMonths: Settings.translations.longMonths,
	shortDays: Settings.translations.shortDays,
	longDays: Settings.translations.longDays,
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};


//s.a.u overload
Ajax.InPlaceEditor.prototype.createEditField = function() {
    var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
    var fld;
    if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
      fld = document.createElement('input');
      fld.type = 'text';
      var size = this.options.size || this.options.cols || 0;
      if (0 < size) fld.size = size;
    } else {
      fld = document.createElement('textarea');
      fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
      fld.cols = this.options.cols || 40;
    }
    fld.name = this.options.paramName;
    fld.value = text; // No HTML breaks conversion anymore
    fld.className = 'editor_field';
/* Added! */
fld.id = this.options.formId + '_input';
    if (this.options.submitOnBlur)
      fld.onblur = this._boundSubmitHandler;
    this._controls.editor = fld;
    if (this.options.loadTextURL)
      this.loadExternalText();
    this._form.appendChild(this._controls.editor);
  }

/*Ajax.InPlaceEditor.prototype.updateChoices  function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount =
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;

      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  }*/
