/*Copyright Covariable 2008*/

ESObject = new Object();ESObject.init = function() {}
ESObject.setup = function() {}
function Subclass(classObj)
{function f(){};f.prototype = classObj;var o = new f();o.superClass = classObj;return o;}
function Allocate(classObj)
{function f(){};f.prototype = classObj;var o = new f();return o;}
ESXMLHTTP = Subclass(ESObject);ESXMLHTTP.init = function()
{try {this.x = new XMLHttpRequest();} catch(e) {var XMLHTTP_IDS = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];for(var i in XMLHTTP_IDS) {try { this.x = new ActiveXObject(XMLHTTP_IDS[i]); return; }
catch(e) {}
}
alert("unable to create xmlhttprequest");return null;}
}
ESXMLHTTP.getXML = function(url)
{this.x.open('GET', url, false);this.x.send("");if(this.x.status == 200)
return this.x.responseXML;else return null;}
ESXMLHTTP.getText = function(url, forcetype)
{this.x.open('GET', url, false);if(forcetype)this.x.overrideMimeType(forcetype);this.x.send("");if(this.x.status == 200)
return this.x.responseText;else return null;}
ESXMLHTTP.postText = function(url, type, data)
{this.x.open('POST', url, false);this.x.setRequestHeader("Content-type", type);this.x.send(data);if(this.x.status == 200)
return this.x.responseText;else return null;}
ESResponder = Subclass(ESObject);ESResponder.mouseDown = function() { }
ESResponder.mouseUp = function() { }
ESResponder.click = function() { }
ESResponder.mouseMoved = function() { }
ESView = Subclass(ESResponder);ESView.init = function(){this.size= null;this.subViews = [];this.dom = document.createElement("div");this.dom.id = this.packageId;this.dom.style.position = "absolute";if(this.style)
this.setStyle(this.style);if(this.cssClassName)
this.setCSSClass(this.cssClassName);if(this.font)
this.setFont(this.font);if(this.position) { 
this.position.horzCenter = ESUtil.parseBoolean(this.position.horzCenter, false);this.__setPosition(this.position);}
if(this.backgroundColor)
this.dom.style.backgroundColor = this.backgroundColor;if(this.borderColor)
{this.dom.style.borderColor = this.borderColor;if(!this.dom.style.borderWidth)
this.dom.style.borderWidth = "2px";}
if(this.borderStyle)
{this.dom.style.borderStyle = this.borderStyle;if(!this.dom.style.borderWidth)
this.dom.style.borderWidth = "2px";}
if(this.dom.style.borderWidth)
{var bw = parseFloat(this.dom.style.borderWidth);shrinkPosition(this.position, bw);}
var self = this;this.dom.onmousedown = function(event) { this._isclick=1; self.mouseDown(event); }
this.dom.onclick = function(event) { if(this._isclick)self.click(event); }
this.dom.onmouseup = function(event) { self.mouseUp(event); }
this.dom.onmousemove = function(event) { this._isclick=0; self.mouseMoved(event); }
this.dom.style.overflow = "hidden";this.visible = this.initiallyVisible = ESUtil.parseBoolean(this.initiallyVisible, true);}
ESView.buildTree = function() {if(this.parentCanvas) {try { 
this.parentCanvas.addSubView(this);} catch(e) {ESUtil.log("Could not addSubView!!!");}
}
}
ESView.setup = function() {if(this.visible) 
this.show();else
this.hide();if(this.position) {this.__setPosition(this.position);this.__setPosition(this.position);}
}
ESView.isVisible = function() {if(this.getDOM().style.display=='none' || this.getDOM().parentNode == null)
return false;if(this.parentCanvas && !this.parentCanvas.isVisible())return false;return true;}
ESView.getDOM = function() {if(this.superDOM)
return this.superDOM;else
return this.dom;}
ESView.getHTMLPosition = function() {var top = this.dom.offsetTop;var height= this.dom.offsetHeight;var left = this.dom.offsetLeft;var width = this.dom.offsetWidth;if(this.dom.offsetParent != null) {var parentWidth = this.dom.offsetParent.offsetWidth;var parentHeight = this.dom.offsetParent.offsetHeight;var bot = parentHeight-top-height;var right = parentWidth-left-width;}
return {top:top, bottom: bot, height:height, left:left, right:right, width:width};}
ESView.hide = function() { 
if(this.superDOM)
this.superDOM.style.display = "none";this.dom.style.display = "none";this.visible = false;}
ESView.show = function() { 
if(this.superDOM)
this.superDOM.style.display = "block";this.dom.style.display = "block";this.visible = true;if(this.isVisible()) this.handleResize();}
ESView.setBackgroundColor = function(backgroundColor) {this.dom.style.backgroundColor = backgroundColor;}
ESView.setStyle = function(styles) {for(var x in styles) {this.dom.style[x] = styles[x];}
}
ESView.setCSSClass = function(className) {this.dom.className = className;}
ESView.setCSSText = function(text) {this.dom.style.cssText += text;}
ESView.setFont = function(font) {if(font.size != null) {if(((typeof font.size) == "string" && font.size.match(/^[0-9]+$/g) != null) || font.size instanceof Number)
this.dom.style.fontSize = font.size + "px";else
this.dom.style.fontSize = font.size + "px";}
if(font.variant != null)
this.dom.style.fontVariant = font.variant;if(font.weight != null) 
this.dom.style.fontWeight = font.weight;if(font.style != null)
this.dom.style.fontStyle = font.style;if(font.family != null)
this.dom.style.fontFamily = font.family;}
ESView.addSubView = function(subView) {this.subViews.push(subView);if(subView.superDOM)
this.dom.insertBefore(subView.superDOM, this.dom.firstChild);else this.dom.appendChild(subView.getDOM());subView.handleResize();}
ESView.removeSubView = function(subView) {for(var i=0; i < this.subViews.length; i++)	
if(this.subViews[i] == subView) {this.dom.removeChild(subView.getDOM());this.subViews.splice(i, 1);return;}
}
ESView.pointInView = function(coords) {var pos = ESUtil.getObjAbsPos(this.getDOM());if(!this.size)this.size = this.getHTMLPosition();if(coords.x - pos.x < 0 || coords.x - pos.x > this.size.width ||
coords.y - pos.y < 0 || coords.y - pos.y > this.size.height)
return false;else return true;}
ESView.findSubView = function(coords) {for(var i=this.subViews.length-1; i >= 0; i--)	
{if(this.subViews[i].isVisible() && this.subViews[i].pointInView(coords))
return this.subViews[i];}
return null;}
ESView.__setPosition = function(posObj) {var dom = this.dom;function toDim(value) {if(value == null)
return '';if(typeof(value) == 'string')
{if(value.search('%') != -1)return value;if(value.search('em') != -1)return value;return Math.max(0,parseFloat(value)) + "px";}
else return parseFloat(value) + "px";}
if(posObj.left !=null)
dom.style.left = toDim(posObj.left);if(posObj.right != null)
dom.style.right = toDim(posObj.right);if(posObj.top != null)
dom.style.top = toDim(posObj.top);if(posObj.bottom != null)
dom.style.bottom = toDim(posObj.bottom);if(posObj.width != null)
dom.style.width = toDim(posObj.width);if(posObj.height != null)
dom.style.height = toDim(posObj.height);}
ESView.reposition = function(posObj) {this.__setPosition(posObj);this.handleResize();}
ESView.resize = function(posObj){this.reposition(posObj);}
ESView.handleResize = function() {var pos = this.getHTMLPosition();if(this.position.horzCenter == true && this.position.width != null && this.dom.parentNode != null) {var parentPos = ESUtil.getObjRelPos(this.dom.parentNode);if(parentPos.width != null) {this.dom.style.left = (parentPos.width-this.position.width)/2 + "px";}
}
if(this.size == null || pos.width != this.size.width || pos.height != this.size.height) {for(var i=0; i < this.subViews.length; i++)
if(this.subViews[i].isVisible())
this.subViews[i].handleResize();}
this.size = pos;}
ESOverflowableView = Subclass(ESView);ESOverflowableView.init = function() {ESOverflowableView.superClass.init.call(this);this.dom.style.overflow = "auto";}
ESSubcanvas = Subclass(ESView) 
ESSubcanvas.init = function(){ESSubcanvas.superClass.init.call(this);}
ESControl = Subclass(ESView);function shrinkPosition(pos, by){if(pos.left)pos.left = parseInt(pos.left) + by;if(pos.top)pos.top = parseInt(pos.top) + by;if(pos.right)pos.right = parseInt(pos.right) + by;if(pos.bottom)pos.bottom = parseInt(pos.bottom) + by;if(pos.width)pos.width = parseInt(pos.width) - by*2;if(pos.height)pos.height = parseInt(pos.height) - by*2;}
ESControl.init = function(){ESControl.superClass.init.call(this);}
ESControl.setup = function() {ESControl.superClass.setup.call(this);}
ESControl.setValue = function(value) {this.dom.appendChild(document.createTextNode(value));}
ESButton = Subclass(ESControl);ESButton.handleResize = function() {ESButton.superClass.handleResize.call(this);this.setValue(this.value);}
ESButton.init = function(){ESButton.superClass.init.call(this);if(this.buttonStyle == null)
this.buttonStyle = "theme";else 
this.buttonStyle = this.buttonStyle.toLowerCase();if(this.buttonStyle == "div") {this.dom.style.border = "2px inset #aaa";this.dom.style.textAlign = "center";this.dom.style.cursor = "pointer";this.mouseDown = ESUtil.eventClosureWithThis(this.handleClick, this);this.dom.appendChild(document.createTextNode(this.value));} else if(this.buttonStyle == "theme") {this.dom.style.textAlign = "center";this.dom.style.cursor = "pointer";this.preloadImages();} else if(this.buttonStyle.toLowerCase()=="htmlbutton") {var button = document.createElement("button");button.innerHTML = ESUtil.HTMLSafeText(this.value);if(this.action)
button.onclick = ESUtil.eventClosureWithThis(this.handleClick, this);button.style.top=button.style.bottom=button.style.left=button.style.right="0px";button.style.position="absolute";this.button = button;this.dom.appendChild(button);}
else ESUtil.log("Help! this.buttonStyle = " + this.buttonStyle);}
ESButton.theme = {lightColor: {r: 255, g: 255, b: 255},darkColor: {r: 180, g: 180, b: 180},hilightColor: {r: 128, g: 128, b: 160},textColor: {r:0, g:0, b:0}
};ESTheme = {mousedObject: null
};ESButton.makeImage = function(border, grad0, grad1, textc, text) {var img = document.createElement("img");var url = "http://stevenstanek.com/cgi-bin/gd.cgi?";url += "text=" + text;url += "&border_r=" + border.r / 255;url += "&border_g=" + border.g / 255;url += "&border_b=" + border.b / 255;url += "&grad0_r=" + grad0.r / 255;url += "&grad0_g=" + grad0.g / 255;url += "&grad0_b=" + grad0.b / 255;url += "&grad1_r=" + grad1.r / 255;url += "&grad1_g=" + grad1.g / 255;url += "&grad1_b=" + grad1.b / 255;url += "&text_r=" + textc.r / 255;url += "&text_g=" + textc.g / 255;url += "&text_b=" + textc.b / 255;if(this.position.width)
{img.width = this.position.width;url += "&width=" + img.width;}
if(this.position.height)
{img.height = this.position.height;url += "&height=" + img.height;}
img.src = url;return img;}
ESButton.preloadImages = function() {if(this._preloadedImageValue == this.value)return;this._preloadedImageValue = this.value;this.normal = this.makeImage(this.theme.hilightColor, this.theme.lightColor, this.theme.darkColor, this.theme.textColor, this.value);this.over = this.makeImage(this.theme.lightColor, this.theme.lightColor, this.theme.darkColor, this.theme.textColor, this.value);this.down = this.makeImage(this.theme.lightColor, this.theme.hilightColor, this.theme.darkColor, this.theme.textColor, this.value);var self = this;this.dom.onmouseover = function() { if(ESTheme.mousedObject==self.dom)return; if(ESTheme.mousedObject)ESTheme.mousedObject.onmouseout(); self.dom.replaceChild(self.over, self.dom.firstChild); ESTheme.mousedObject = self.dom; }
this.dom.onmouseout = function() { self.dom.replaceChild(self.normal, self.dom.firstChild); if(ESTheme.mousedObject==self.dom)ESTheme.mousedObject = null; }
this.over.onmousedown = function(ev) { ESUtil.cancelEventDefault(ev); self.dom.replaceChild(self.down, self.over); }
this.down.onmouseup = function(event) { self.dom.replaceChild(self.over, self.down); self.handleClick(event); }
this.dom.innerHTML="";this.dom.appendChild(this.normal);}
ESButton.handleClick = function(event) {ESUtil.cancelEventDefault(event);if(this.action != null)
this.action(this, event);}
ESButton.setValue = function(value) {if(this.buttonStyle.toLowerCase() =="div") {var coords = this.getHTMLPosition();this.dom.innerHTML = "<table style='height:" +coords.height + "px; width:100%;'> <tr><td style='vertical-align:middle; text-align:center;'> "+ESUtil.HTMLSafeText(value)+"</td></tr></table>";}
else if(this.buttonStyle.toLowerCase() =="htmlbutton")
this.button.innerHTML = ESUtil.HTMLSafeText(value);else
{this.value = value;this.preloadImages();}
}
ESLabel = Subclass(ESView);ESLabel.init = function() {shrinkPosition(this.position, 2);ESLabel.superClass.init.call(this);if(this.value)
this.setValue(this.value)
if(this.align)
this.setAlign(this.align);}
ESLabel.setValue = function(value) {this.value = value;this.dom.innerHTML = "";this.dom.appendChild(document.createTextNode(value));}
ESLabel.setAlign = function(align) {this.align = align;this.dom.style.textAlign = align;}
ESImageView = Subclass(ESControl);ESImageView.init = function(){if(!ESImageView.sneakydom)
{ESImageView.sneakydom = document.createElement("div");ESImageView.sneakydom.style.position = 'absolute';ESImageView.sneakydom.style.width = '0px';ESImageView.sneakydom.style.height = '0px';ESImageView.sneakydom.id='sneakydom';document.body.appendChild(ESImageView.sneakydom);}
ESImageView.superClass.init.call(this);this.img = document.createElement("img");this.img.onload = ESUtil.closureWithThis(this.handleLoad, this);this.preserveAspect = ESUtil.parseBoolean(this.preserveAspect, true);this.resizeToPosition = ESUtil.parseBoolean(this.resizeToPosition, true);this.dom.innerHTML = "";if(this.action)
{var self=this;this.img.onclick = function() { self.action(self); };this.img.style.cursor = "pointer";}
this.dom.appendChild(this.img);this.loaded = false;if(this.value)
this.img.src = this.value;}
ESImageView.handleResize=function() {ESImageView.superClass.handleResize.call(this);if(this.resizeToPosition && this.loaded)	{var coords = this.getHTMLPosition();if(coords.width <=0 || coords.height <=0) {return;}
if(this.preserveAspect && this.originalSize != null) {var origRatio = this.originalSize.width / this.originalSize.height;var frameRatio = coords.width / coords.height;if(frameRatio > origRatio) {this.img.style.width = (coords.height * origRatio) + "px";this.img.style.height = coords.height +"px";} else {this.img.style.width = coords.width + "px";this.img.style.height = (coords.width / origRatio) + "px";}
} else {this.img.style.width = coords.width + "px";this.img.style.height = coords.height +"px";}
}
}
ESImageView.setValue = function(src){this.value = src;this.loaded = false;this.img.src = this.value;}
ESImageView.handleLoad = function() {this.loaded = true;this.dom.removeChild(this.img);ESImageView.sneakydom.appendChild(this.img);this.originalSize = {width: this.img.width, height:this.img.height};ESImageView.sneakydom.removeChild(this.img);this.dom.appendChild(this.img);this.handleResize();if(this.loadHandler)
this.loadHandler();}
ESImageView.hasLoaded = function() {return this.loaded;}
ESImageView.getImgSize = function() {if(this.loaded)
return this.originalSize;else
return null;}
ESMovieView = Subclass(ESControl);ESMovieView.init = function() {if(this.type)
this.type = this.type.toLowerCase();ESMovieView.superClass.init.call(this);this.showControls = ESUtil.parseBoolean(this.showControls, true);this.autoPlay = ESUtil.parseBoolean(this.autoPlay, false);this.createHTML();}
ESMovieView.createHTML = function() { 
var embedHTML = "<embed ";if(this.value != null)
embedHTML += "src=\"" + ESUtil.HTMLSafeText(this.value) + "\" ";if(!this.showControls)
embedHTML += "controller=\"false\" ";embedHTML += "autoplay=\"" + (this.autoPlay) +"\" ";if(this.width)
embedHTML += "width=\"" + this.width +"\" ";if(this.height) {this.height = parseFloat(this.height)
if(this.showControls)
this.height += 16;embedHTML += "height=\"" + this.height +"\" ";}
embedHTML += "></embed>";this.dom.innerHTML = embedHTML;}
ESMovieView.setValue = function(value) {this.value = value;this.createHTML();}
ESTable = Subclass(ESControl)
ESTable.init = function(){ESTable.superClass.init.call(this);this.columns = new Array();this.rows = new Array();this.tabdom = document.createElement("table");this.tabdom.style.left = "0px";this.tabdom.style.right ="0px";this.tabdom.style.top = "0px";this.tabdom.style.bottom = "0px";this.thead = document.createElement("thead");this.tabdom.appendChild(this.thead);this.tbody = document.createElement("tbody");this.tabdom.appendChild(this.tbody);this.dom.appendChild(this.tabdom);this.hrow = document.createElement("tr");this.thead.appendChild(this.hrow);this.dom.style.border="2px inset #aaa";this.dom.style.overflow="auto";this.selectedRow = null;if(this.tableStyle == null)
this.tableStyle = {};this.tableStyle.variableColoring = ESUtil.parseBoolean(this.tableStyle.variableColoring, false);if(this.tableStyle.selectColor == null)
this.tableStyle.selectColor = "#8af";if(this.tableStyle.evenColor == null)
this.tableStyle.evenColor = "#CFC";if(this.tableStyle.cellColor == null)
this.tableStyle.cellColor = (this.tableStyle.variableColoring) ? "#CCF" : "white";this.selectable = ESUtil.parseBoolean(this.selectable, true);}
ESTable.rowIdToIdx = function(id) {for(var i=0; i < this.rows.length; i++)
if(this.rows[i].id == id)
return i;return null;}
ESTable.clear = function(){while(this.tbody.firstChild)
this.tbody.removeChild(this.tbody.firstChild);this.selectedRow = null;this.value = null;this.rows = new Array();}
ESTable.setColumns = function(cols){while(this.hrow.firstChild)this.hrow.removeChild(this.hrow.firstChild);for(var x=0;x<cols.length;x++)
{var th = document.createElement("th");th.appendChild(document.createTextNode(cols[x]));this.hrow.appendChild(th);}
}
ESTable.setWidths = function(widths){this.widths = widths;for(var x=0;x<widths.length;x++) {this.hrow.cells[x].style.width = Math.max(0,widths[x]) + "px";this.hrow.cells[x].width = Math.max(0,widths[x]) + "px";}
}
ESTable.setTableStyle = function(style) {if(style.variableColoring)
this.tableStyle.variableColoring = style.variableColoring;if(style.selectColor)
this.tableStyle.selectColor = style.selectColor;if(style.evenColor)
this.tableStyle.evenColor = style.evenColor;if(style.cellColor)
this.tableStyle.cellColor = style.cellColor;this.refreshStyle();}
ESTable.setSelectable = function(selectable) {this.selectable = selectable;if(selectable == false && this.selectedRow != null) {var old = this.selectedRow;this.selectedRow = null;this.refreshColorForRow(old);}
}
ESTable.getSelectable = function() {return this.selectable;}
ESTable.refreshStyle = function() {for(var i=0; i < this.rows.length; i++)
this.refreshColorForRow(i);}
ESTable.refreshColorForRow = function(rowNum) {if(this.selectedRow != rowNum) {if(rowNum%2 == 0 || !(this.tableStyle.variableColoring))
this.rows[rowNum].tr.style.backgroundColor = this.tableStyle.cellColor;else 
this.rows[rowNum].tr.style.backgroundColor = this.tableStyle.evenColor;}
else
this.rows[rowNum].tr.style.backgroundColor = this.tableStyle.selectColor;}
ESTable.findSubDrag = function(coords) {for(var i=0;i<this.rows.length;i++)
{var row = this.rows[i];var tr = row.tr;var pos = ESUtil.getObjAbsPos(tr);var x = coords.x - pos.x, y = coords.y - pos.y;var h = tr.offsetHeight;if(y>0 && y<h)
{var self = this;return {canAcceptDrag: function(type) { return self.canDropOnRow(row.id, row.data, type); },dragEntered: function(coords) { tr.style.background = '#99c'; },dragLeft: function(coords) { self.refreshColorForRow(i); },acceptDrag: function(type, dropdata) { self.finalizeDropOnRow(row.id, row.data, type, dropdata); },findSubView: function(coords) { return null; }
};}
}
}
ESTable.makeDragRow = function(tr) {var div = document.createElement("div");div.innerHTML = "<table style='table-layout:fixed'><tr>" + tr.innerHTML + "</tr></table>";if(this.widths)
for(var i=0;i<this.widths.length;i++){div.firstChild.rows[0].cells[i].style.width = Math.max(0,this.widths[i]) + "px";div.firstChild.rows[0].cells[i].width = Math.max(0,this.widths[i]) + "px";}
return div;}
ESTable.finalizeDragRow = function(id, tr, data) { return null; }
ESTable.typeForDragRow = function(id, data) { return null; }
ESTable.finalizeDropOnRow = function(id, data, type, dropdata) { return null; }
ESTable.canDropOnRow = function(id, data, type) { return false; }
ESTable.handleRowDragStart = function(ev, id, tr, data) {var type = this.typeForDragRow(id, data);if(!type)return;ESDragDrop.launchDrag(ev, type, tr,ESUtil.closureWithThis(this.makeDragRow, this, tr),ESUtil.closureWithThis(this.finalizeDragRow, this, id, tr, data), 7, this);}
ESTable.addRow = function(row, id, data){var tr = document.createElement("tr");tr.onclick = ESUtil.closureWithThis(this.handleSelect, this, this.rows.length, data);if(this.onDblClick)
tr.ondblclick = ESUtil.closure(this.onDblClick, this, this.rows.length, data);tr.onmousedown = ESUtil.eventClosureWithThis(this.handleRowDragStart, this, id, tr, data);for(var x=0;x<row.length;x++)
{var td = document.createElement("td");if(typeof(row[x]) == "object" && row[x] != null)
{if(row[x].getDOM)
{td.style.position='relative';td.appendChild(row[x].getDOM());}
else td.appendChild(row[x]);}
else td.appendChild(document.createTextNode(row[x]));tr.appendChild(td);}
this.tbody.appendChild(tr);this.rows.push({values: row, tr: tr, data:data, id:id});this.refreshColorForRow(this.rows.length-1);if(id == this.value) 
tr.onclick();}
ESTable.handleSelect = function(row) {if(this.selectable == false) {if(this.action)
this.action(this);return;}
var oldRow=  this.selectedRow;this.selectedRow = row;if(oldRow != null)
this.refreshColorForRow(oldRow);this.refreshColorForRow(row);this.value = this.rows[row].id;this.data = this.rows[row].data;if(this.action)
this.action(this);}
ESTable.getData = function() {if(this.selectedRow != null)
return this.rows[this.selectedRow].data;return null;}
ESTable.getSelectedRow = function() {return this.selectedRow;}
ESTable.upArrow = function() {var sr = this.getSelectedRow();if(sr == null || sr<=0)this.handleSelect(0);else this.handleSelect(sr-1);}
ESTable.downArrow = function() {var sr = this.getSelectedRow();if((sr == null && sr!=0) || sr==this.rows.length-1)this.handleSelect(this.rows.length-1);else this.handleSelect(sr+1);}
ESTable.getValue = function() {if(this.selectedRow != null)
return this.rows[this.selectedRow].id;return null;}
ESTable.setValue = function(id){if(id==null) {if(this.selectedRow)this.rows[this.selectedRow].tr.style.background = this.cellColor;this.selectedRow = null;} else {var idx = this.rowIdToIdx(id);if(idx != null)
this.rows[idx].tr.onclick();}
}
ESTable.populateFromXML = function(xml, objectsXPath, columnNames, columnXPaths, idXPath){this.setColumns(columnNames);var	xmlObjects = xml.xpathQuery(objectsXPath);for(var i=0;i<xmlObjects.length;i++)
{var o = xmlObjects[i];var vals = new Array();for(var j=0;j<columnXPaths.length;j++)
vals.push(xml.xpathQuery(columnXPaths[j], o)[0]);var id = i;if(idXPath)id = xml.xpathQuery(idXPath, o)[0];this.addRow(vals, id, {document: xml, node: o});}
}
ESTable.populateFromXMLFileAtURL = function(url, objectsXPath, columnNames, columnXPaths, idXPath){var xml = Allocate(ESXMLDatabase);xml.init(url);if(!xml.xml)return null;this.populateFromXML(xml, objectsXPath, columnNames, columnXPaths, idXPath);return xml;}
ESSortableTable = Subclass(ESTable);ESSortableTable.init = function() {ESSortableTable.superClass.init.call(this);this.colsLowSorts = null;}
ESSortableTable.setColumns = function(cols){this.colsLowSorts = new Array();while(this.hrow.firstChild)this.hrow.removeChild(this.hrow.firstChild);for(var x=0;x<cols.length;x++)
{var th = document.createElement("th");th.appendChild(document.createTextNode(cols[x]));th.onclick = ESUtil.eventClosureWithThis(this.handleSortClick, this, x, null);this.hrow.appendChild(th);this.colsLowSorts[x] = true;}
}
ESSortableTable.handleSortClick = function(ev, col) {ESUtil.cancelEventDefault(ev);this.sortByCol(col);}
ESSortableTable.sortByCol = function(col, smallestFirst) {var newRows = [];var i=0;if(smallestFirst == null) {smallestFirst = this.colsLowSorts[col];this.colsLowSorts[col] = ! this.colsLowSorts[col];}
for(var x in this.rows) {newRows[i] = this.rows[x];i ++;}
var insensitive = this.caseInsensitive;newRows.sort(function(x,y) {var vx = x.values[col], vy = y.values[col];if(insensitive) { vx = vx.toLowerCase(); vy = vy.toLowerCase(); }
var cmp = (vx>vy)?1:(vx<vy)?-1:0;if(smallestFirst)return cmp;else return -cmp;});this.clear();for(i=0; i < newRows.length; i++) {this.addRow(newRows[i].values, newRows[i].id, newRows[i].data);}
this.sortedCol = col;this.sortedDir = smallestFirst;}
ESSortableTable.sort = function() {if(this.sortedCol == undefined)return;this.sortByCol(this.sortedCol, this.sortedDir);}
ESDatabase = Subclass(ESObject);ESXMLDatabase = Subclass(ESDatabase);ESXMLDatabase.init = function(url) {var req = Allocate(ESXMLHTTP);req.init();this.xml = req.getXML(url);return this.xml?true:false;}
ESXMLDatabase.initWithXML = function(xmlstring) {if(window.ActiveXObject)
{var doc = new ActiveXObject("Microsoft.XMLDOM");doc.async = "false";doc.loadXML(xmlstring);this.xml = doc;}
else
{var parser = new DOMParser();this.xml = parser.parseFromString(xmlstring, "text/xml");}
return this.xml?true:false;}
ESXMLDatabase.xpathQuery = function(xpath, context) {if(!context)context = this.xml;if(xpath.charAt(0) == "'" && xpath.charAt(xpath.length-1) == "'")
{var res = xpath.substring(1, xpath.length-1);return [res];}
xpath = xpath.replace(/\/\//g, "/descendent-or-self::node()/");steps = xpath.split("/");if(steps[0].length==0)
{var nodeSet = [this.xml];steps.splice(0,1);}
else var nodeSet = [context];for(var i=0;i<steps.length;i++)
{var step = steps[i];var firstPred = step.search(/\[/);if(firstPred == -1)
{var axisTest = step;var predicates = [];}
else
{var axisTest = step.substring(0, firstPred);var predicates = step.substring(firstPred+1, step.length - 1).split("][");}
if(axisTest.search("@") == 0)
axisTest = axisTest.replace("@", "attribute::");if(axisTest == "..")axisTest = "parent::node()";if(axisTest == ".")axisTest = "self::node()";var cc = axisTest.search("::");if(cc == -1)
{axis = "child";test = axisTest;}
else
{axis = axisTest.substring(0, cc);test = axisTest.substring(cc+2, axisTest.length);}
var newNodeSet = new Array();for(var j=0;j<nodeSet.length;j++)
newNodeSet = newNodeSet.concat(this.xpathStep(nodeSet[j], axis, test, predicates));nodeSet = newNodeSet;}
return nodeSet;}
ESXMLDatabase.duplist = function(list) {var nlist = new Array();for(var i=0;i<list.length;i++)
nlist.push(list[i]);return nlist;}
ESXMLDatabase.filterNodes = function(list, test, defaultType) {if(test == "*")
{for(var i=0;i<list.length;i++)
if(list[i].nodeType != defaultType)list.splice(i--, 1);return list;}
if(test == "node()")return list;if(test == "comment()")
{for(var i=0;i<list.length;i++)
if(list[i].nodeType != 8)list.splice(i--, 1);return list;}
if(test == "text()")
{for(var i=0;i<list.length;i++)
if(list[i].nodeType != 3)list.splice(i--, 1);else list.splice(i, 1, list[i].nodeValue);return list;}
if(test == "processing-instruction()")
{for(var i=0;i<list.length;i++)
if(list[i].nodeType != 7)list.splice(i--, 1);return list;}
for(var i=0;i<list.length;i++)
{if(list[i].nodeType != defaultType)list.splice(i--, 1);else if(defaultType == 1 && list[i].tagName != test)list.splice(i--, 1);else if(defaultType == 2 && list[i].name != test)list.splice(i--, 1);else if(defaultType == 2)list.splice(i, 1, list[i].value);}
return list;}
ESXMLDatabase.getChildren = function(node, test) { 
return this.filterNodes(node.childNodes ? this.duplist(node.childNodes) : [], test, 1);}
ESXMLDatabase.getAncestors = function(node, test, withself) {var nodes = new Array();if(withself)nodes.push(node);for(var c = node.parentNode;c;c = c.parentNode)
nodes.push(c);return this.filterNodes(nodes, test, 1);}
ESXMLDatabase.getDescendents = function(node, test, withself) {var nodes = new Array();if(withself)nodes.push(node);for(var c = node.firstChild;c;c = c.nextSibling)
nodes = nodes.concat(this.getDescendents(c, test, true));return this.filterNodes(nodes, test, 1);}
ESXMLDatabase.getParent = function(node, test) { 
return this.filterNodes(node.parentNode?[node.parentNode]:[], test, 1);}
ESXMLDatabase.getSelf = function(node, test) { 
return this.filterNodes([node], test, 1);}
ESXMLDatabase.getAttributes = function(node, test) { 
return this.filterNodes(this.duplist(node.attributes), test, 2);}
ESXMLDatabase.xpathStep = function(node, axis, test, predicates) {switch(axis)
{case	"child": var axisNodes = this.getChildren(node, test); break;case	"ancestor": var axisNodes = this.getAncestors(node, test, false); break;case	"ancestor-or-self": var axisNodes = this.getAncestors(node, test, true); break;case	"descendent": var axisNodes = this.getDescendents(node, test, false); break;case	"descendent-or-self": var axisNodes = this.getDescendents(node, test, true); break;case	"parent": var axisNodes = this.getParent(node, test); break;case	"attribute": var axisNodes = this.getAttributes(node, test); break;case	"self": var axisNodes = this.getSelf(node, test); break;default:	throw "Unsupported XPath axis: " + axis;}
var okNodes = new Array();for(var i=0;i<axisNodes.length;i++)
{for(var j=0;j<predicates.length;j++)
if(!this.checkPredicate(axisNodes[i], i, axisNodes.length, predicates[j]))
break;if(j==predicates.length)
okNodes.push(axisNodes[i]);}
return okNodes;}
ESXMLDatabase.checkPredicate = function(node, pos, count, pred) {var eq = pred.search("=");if(eq == -1)throw "predicate '" + pred + "' not implemented";else
{var a = eq-1, b = eq+1;while(pred.charAt(a) == ' ')a--;var lhs = pred.substring(0, a+1);while(pred.charAt(b) == ' ')b++;var rhs = pred.substring(b, pred.length);var lhsv = this.xpathQuery(lhs, node);var rhsv = this.xpathQuery(rhs, node);if(!lhsv.length || !rhsv.length)return 0;if(lhsv[0] == rhsv[0])return 1;return 0;}
}
ESXMLDatabase.makeXML = function(x) {if(!x)
{return "<?xml version='1.0' encoding='UTF-8'?>\n" + this.makeXML(this.xml.firstChild);}
if(x.nodeType == 1)
{var str = "<" + x.tagName;for(var a=0;a<x.attributes.length;a++)
{str += " " + x.attributes[a].name + '="';var v = x.attributes[a].value;str += v.toString().replace(/"/g, '\\"').replace(/\\/g, '\\\\');str += '"';}
if(x.firstChild)
{str += ">";for(var c=x.firstChild;c;c=c.nextSibling)
str += this.makeXML(c);str += "</" + x.tagName + ">";}
else str += "/>";return str;}
if(x.nodeType == 3)return x.nodeValue;return "";}
ESMutableControl = Subclass(ESControl);ESMutableControl.init = function() {ESMutableControl.superClass.init.call(this);this.storedValue = null;}
ESMutableControl.setValue = function(value) {} 
ESMutableControl.getValue = function(value) {} 
ESMutableControl.handleChange = function(event) {var value = this.getValue();if(this.storedValue != value) {if(this.action)
this.action(this, event);this.storedValue = value;}
}
ESTextArea = Subclass(ESMutableControl) ;ESTextArea.init= function() {shrinkPosition(this.position, 2);ESTextArea.superClass.init.call(this);this.readOnly = ESUtil.parseBoolean(this.readOnly, false);this.textarea = document.createElement("textarea");this.textarea.style.position="absolute";this.textarea.style.width="100%";this.textarea.style.height="100%";this.textarea.style.left = "0px";this.textarea.style.right ="0px";this.textarea.style.top="0px";this.textarea.style.bottom="0px";this.dom.style.padding='2px';if(this.readOnly)
this.textarea.readOnly = this.readOnly;if(this.action)
this.textarea.onchange = ESUtil.eventClosureWithThis(this.handleChange, this);this.dom.appendChild(this.textarea);if(this.value)
this.setValue(this.value);}
ESTextArea.setup = function() {ESTextArea.superClass.setup.call(this);}
ESTextArea.handleResize = function() {	
ESTextArea.superClass.handleResize.call(this);var pos = this.getHTMLPosition();this.textarea.style.width = Math.max(0,pos.width-4)+"px";this.textarea.style.height = Math.max(0,pos.height-4)+"px";}
ESTextArea.setValue = function(value) {if(this.textarea)
this.textarea.value = value;}
ESTextArea.getValue = function() {return this.textarea.value;}
ESTextArea.setReadOnly = function(readOnly) {this.readOnly = readOnly;this.textArea.readOnly = readOnly;}
ESTextArea.getReadOnly = function() {return this.readOnly;}
ESTextInput = Subclass(ESMutableControl) ;ESTextInput.init = function(){shrinkPosition(this.position, 2);ESTextInput.superClass.init.call(this);if(this.type)
this.type = this.type.toLowerCase();else
this.type="text";if(ESUtil.isIE())
{var t = this.type=='password'?'password':'text';this.input = document.createElement("<input type='"+t+"'>");}
else this.input = document.createElement("input");this.input.style.position="absolute";this.input.style.left = "0px";this.input.style.right = "0px";this.input.style.top = "0px";this.input.style.bottom = "0px";this.dom.appendChild(this.input);this.input.onchange= ESUtil.eventClosureWithThis(this.handleChange, this);if(this.value != null)
this.setValue(this.value);}
ESTextInput.setup = function() {ESTextInput.superClass.setup.call(this);if(this.type == "password")
this.input.type = "password";else
this.input.type = "text";}
ESTextInput.handleResize = function() {ESTextInput.superClass.handleResize.call(this);this.input.style.width = Math.max(0,this.getHTMLPosition().width - 4) + "px";}
ESTextInput.setValue = function(value) {this.value = value;this.input.value = value;}
ESTextInput.getValue = function() {this.value = this.input.value;return this.input.value;}
ESTextInput.select = function() {this.input.focus(); this.input.select();}
ESFormattedTextInput = Subclass(ESTextInput);ESFormattedTextInput.init = function() {ESFormattedTextInput.superClass.init.call(this);if(!this.reformatter)
return;this.reformatter= this.reformatter.toLowerCase();switch(this.reformatter) {case "integer": 
this.reformatterFunc = this.integerOnlyReformatter;break;case "decimal":
this.reformatterFunc = this.decimalOnlyReformatter;break;case "letter": case "alpha":
this.reformatterFunc = this.lettersOnlyReformatter;break;case "alphanum":
this.reformatterFunc = this.alphaNumOnlyReformatter;break;case "custom":
break;default:
}
}
ESFormattedTextInput.handleChange = function() {var value = this.input.value;if(this.reformatterFunc)
value = this.reformatterFunc(value);this.value = value;this.input.value = value;if(this.action)
this.action(this);}
ESFormattedTextInput.regExpReformatter = function(str, regExp, maxMatches) {var matches = str.match(regExp);maxMatches = (maxMatches == null) ? matches.length  : maxMatches;var returnme = "";for(var i=0; matches != null && i < matches.length && i < maxMatches; i++)
returnme += matches[i];return returnme;}
ESFormattedTextInput.integerOnlyReformatter = function(str) {return ESFormattedTextInput.regExpReformatter(str, /[+-]?\d+/g, 1);}
ESFormattedTextInput.decimalOnlyReformatter = function(str) {return ESFormattedTextInput.regExpReformatter(str, /[+-]?\d*(\.\d*)?/g, 1);}
ESFormattedTextInput.lettersOnlyReformatter = function(str) {return ESFormattedTextInput.regExpReformatter(str, /[A-Za-z]+/);}
ESFormattedTextInput.alphaNumOnlyReformatter = function(str) {return ESFormattedTextInput.regExpReformatter(str, /[A-Za-z0-9]+/g);}
ESFormInput = Subclass(ESView);ESFormInput.init = function() {ESFormInput.superClass.init.call(this);this.inputs = [];this.labels = [];var fieldHeight =25;if(this.labelWidth == null)
this.labelWidth = 150;for(var i=0; i < this.fields.length; i++) {var lbl = Allocate(ESLabel);lbl.value = this.fields[i].name;lbl.parentCanvas = this;lbl.position = {height:fieldHeight, top:(5+fieldHeight)*i+5,left: 5, width:this.labelWidth};lbl.init();this.labels[i] = lbl;var pres = null;if(this.fields[i].reformatter) {pres = Allocate(ESFormattedTextInput);pres.reformatter = this.fields[i].reformatter;}
else
pres = Allocate(ESTextInput);if(this.fields[i].value)
pres.value = this.fields[i].value;pres.position={height:fieldHeight,top:(5+fieldHeight)*i+5,right:5,left:this.labelWidth+10};pres.parentCanvas = this;pres.init();this.inputs[i] = pres;}
}
ESFormInput.setup = function() {ESFormInput.superClass.setup.call(this);for(var i=0; i < this.inputs.length; i++) {this.inputs[i].buildTree();this.inputs[i].setup();this.labels[i].buildTree();this.labels[i].setup();}
}
ESFormInput.getValues = function() {var returnme = [];for(var i=0; i < this.inputs.length; i++)
returnme[i] = this.inputs[i].getValue();return returnme;}
ESFormInput.setValues = function(values) {for(var i=0; i < values.length && i < this.inputs.length; i++)
this.inputs[i].setValue(values[i]);}
ESFormInput.focus = function() {if(this.inputs[0] != null)
this.inputs[0].select()
}
ESFormInput.select = function(){ 
this.focus();}
ESMultiInput = Subclass(ESMutableControl);ESMultiInput.init = function() {ESMultiInput.superClass.init.call(this);if(this.values == null)
this.values = [];this.createDialog();this.lastAdded = null;this.lastRemoved = null;}
ESMultiInput.createDialog = function() {var textInput = Allocate(ESTextInput);var addBtn = Allocate(ESButton);var removeBtn = Allocate(ESButton);var inputSelector = Allocate(ESButtonSelector);if(!this.orientation || this.orientation=='horizontal')
{textInput.position = {left: 5, top: 5, height:32, width: 100};addBtn.position = {left: 5, top: 38, height: 24, width: 100};removeBtn.position = {left: 5, top: 70, height: 24, width: 100};inputSelector.position = {left: 110, top: 5, right: 5, bottom: 5};}
else
{textInput.position = {left: 5, top: 5, height:23, right: 5};addBtn.position = {left: 5, top: 28, height: 20, width: 60};removeBtn.position = {left: 70, top: 28, height: 20, width: 80};inputSelector.position = {left: 5, top: 50, right: 5, bottom: 5 };}
textInput.parentCanvas = this;textInput.init();textInput.buildTree();textInput.setup();this.textInput = textInput;addBtn.value = "Add";addBtn.parentCanvas = this;addBtn.action = ESUtil.closureWithThis(this.handleAddClick, this);addBtn.init();addBtn.buildTree();addBtn.setup();this.addBtn = addBtn;removeBtn.value = "Remove";removeBtn.parentCanvas = this;removeBtn.action = ESUtil.closureWithThis(this.handleDelClick, this);removeBtn.init();removeBtn.buildTree();removeBtn.setup();this.removeBtn = removeBtn;inputSelector.parentCanvas = this;inputSelector.values = [];inputSelector.borderStyle="solid";inputSelector.borderColor ="black";inputSelector.action = ESUtil.closureWithThis(this.handleSelection, this);inputSelector.init();inputSelector.buildTree();inputSelector.setup();this.inputSelector = inputSelector;}
ESMultiInput.handleAddClick = function() {var text=this.textInput.getValue();if(text == "")
return;this.values.splice(0,0,text);this.inputSelector.setButtons(this.values);this.lastAdded = text;if(this.action)
this.action(this);if(this.onAdd)
this.onAdd(this);}
ESMultiInput.handleDelClick = function() {var idx = this.inputSelector.getIndex();this.lastRemoved = this.values[idx];if(idx!=null &&idx < this.values.length && idx >= 0)
this.values.splice(idx,1);this.inputSelector.setButtons(this.values);if(this.action)
this.action(this);if(this.onRemove !=null)
this.onRemove(this);}
ESMultiInput.add = function(val) {this.values.splice(0,0,val);this.inputSelector.setButtons(this.values);}
ESMultiInput.getValue = function() {return this.values.concat([]);}
ESMultiInput.setValue = function(val) {this.values = val;this.inputSelector.setButtons(this.values);}
ESMultiInput.getSelected = function() {return this.inputSelector.getValue();}
ESMultiInput.setSelected = function(value) {this.inputSelector.setValue(value);}
ESMultiInput.getSelectedIdx = function() {return this.inputSelector.getIndex();}
ESMultiInput.setSelectedIdx = function(idx) {this.inputSelector.setIndex(idx);}
ESMultiInput.handleSelection = function() {if(this.onSelection)
this.onSelection(this);}
ESMultiInput.getLastAddition = function() {return this.lastAdded;}
ESMultiInput.getLastDeletion = function(){return this.lastRemoved;}
ESHTMLSelector = Subclass(ESMutableControl);ESHTMLSelector.init = function() {shrinkPosition(this.position, 2);ESHTMLSelector.superClass.init.call(this);if(this.values == null)
this.values=[]
this.createSelector();}
ESHTMLSelector.createSelector = function() {this.dom.innerHTML = "";this.selector = document.createElement("select");this.selector.style.position = "absolute";this.selector.style.top = "0px";this.selector.style.bottom = "0px";this.selector.style.left = "0px";this.selector.style.right = "0px";if(this.action)
{var self=this;this.selector.onchange=function() { self.action(self); }
}
for(var i=0; i < this.values.length; i++) {	
var presOption = document.createElement("option");presOption.value = this.values[i];presOption.appendChild(document.createTextNode(this.values[i]));this.selector.appendChild(presOption);}
this.dom.appendChild(this.selector);if(this.selectedValue)
this.setValue(this.selectedValue);else if(this.selectedIndex)
this.setIndex(this.selectedIndex);}
ESHTMLSelector.setValues = function(values) {this.values = values;this.createSelector();}
ESHTMLSelector.handleResize = function() {ESHTMLSelector.superClass.handleResize.call(this);this.selector.style.width = Math.max(4,this.getHTMLPosition().width-4) + "px";}
ESHTMLSelector.setValue = function(value) {for(var i=0; i < this.values.length; i++) {if(this.values[i] == value) {this.setIndex(i);return;}
}
}
ESHTMLSelector.setIndex = function(index) {this.selector.selectedIndex = index;}
ESHTMLSelector.getValue = function() {return this.selector.value;}
ESHTMLSelector.getIndex = function() {return this.selector.selectedIndex;}
ESHTMLSelector.getValues = function() {return this.values.concat([]);}
ESButtonSelector = Subclass(ESMutableControl);ESButtonSelector.init = function() {ESButtonSelector.superClass.init.call(this);this.presIndex = null;if(this.regularBGColor == null)
this.regularBGColor = (this.backgroundColor? this.backgroundColor: "#FFFFFF");if(this.selectedBGColor == null)
this.selectedBGColor = "#AAAAFF";this.createButtons();this.selectOnMouseOver=ESUtil.parseBoolean(this.selectOnMouseOver, false);if(this.selectedIndex != null)
this.setIndex(this.selectedIndex);if(this.selectedValue != null)
this.setValue(this.selectedValue);}
ESButtonSelector.createButtons = function() {if(this.values) {this.dom.style.overflow ="auto";this.buttons = [];this.dom.innerHTML = "";for(var i=0; i < this.values.length; i++ ){var button = document.createElement('div');button.style.display="block";button.style.padding = "5px";button.style.height = "16px";button.style.backgroundColor = this.regularBGColor;button.style.cursor = "pointer";button.innerHTML = ESUtil.HTMLSafeText(this.values[i]);button.onmousedown = ESUtil.eventClosureWithThis(this.handleButtonClick, this, i);if(this.selectOnMouseOver)
button.onmouseover = ESUtil.eventClosureWithThis(this.handleButtonClick, this, i);this.buttons.push(button);this.dom.appendChild(button);}
this.presIndex = null;}
}
ESButtonSelector.getValue = function() {if(this.presIndex != null) {return this.values[this.presIndex];}
}
ESButtonSelector.setValue = function(val) {for(var i=0; i < this.values.length; i++) {if(this.values[i] == val)
this.setIndex(i);}
}
ESButtonSelector.getIndex = function() {return this.presIndex;}
ESButtonSelector.setIndex = function(idx) {idx = parseInt(idx);if(idx < 0 || idx > this.values.length)	
throw("Invalid index");if(this.presIndex != null)
this.buttons[this.presIndex].style.backgroundColor = this.regularBGColor;this.buttons[idx].style.backgroundColor = this.selectedBGColor;this.presIndex = idx;}
ESButtonSelector.setButtons = function(buttons) {this.values = buttons;this.createButtons();}
ESButtonSelector.getButtons = function() {return this.values.concat([]);}
ESButtonSelector.getValues = function() {return this.getButtons();}
ESButtonSelector.handleButtonClick = function(ev, buttonNum) {ESUtil.cancelEventDefault(ev);this.setIndex(buttonNum);if(this.action)
this.action(this);}
ESChecklist = Subclass(ESMutableControl);ESChecklist.init = function() {ESChecklist.superClass.init.call(this);if(this.values == null)
this.values=[];this.cbs = null;this.createList();}
ESChecklist.createList = function() {this.cbs = [];this.dom.innerHTML = "";var table = document.createElement("table");var tbody = document.createElement("tbody");table.appendChild(tbody);for(var i=0; i  < this.values.length; i++) {var tr = document.createElement("tr");tbody.appendChild(tr);var checkTD = document.createElement("td");tr.appendChild(checkTD);var checkBox = document.createElement("input");checkBox.type = "checkbox";checkBox.checked = false;checkBox.onclick = ESUtil.closureWithThis(this.handleClick, this, this.values[i]);checkBox.name = this.values[i];checkTD.appendChild(checkBox);this.cbs[i] = checkBox;var nameTD = document.createElement("td");tr.appendChild(nameTD);nameTD.appendChild(document.createTextNode(this.values[i]));}
this.dom.appendChild(table);}
ESChecklist.handleClick = function(cbName) {if(this.action)
this.action(this);}
ESChecklist.setValues = function(values) {this.values = values;this.createList();}
ESChecklist.getValues = function() {return this.values.concat([]);}
ESChecklist.setChecked = function(checkedVals) {for(var x in checkedVals) {for(var i=0; i < this.values.length; i++){if(this.values[i] == x) {this.cbs[i].checked = checkedVals[x];break;}
}
}
}
ESChecklist.getChecked = function() {var returnme = {};for(var i=0; i < this.cbs.length; i++)
returnme[this.cbs[i].name] = ESUtil.parseBoolean(""+this.cbs[i].checked);return returnme;}
ESSlider = Subclass(ESMutableControl);ESSlider.init = function() {ESSlider.superClass.init.call(this);this.liveUpdate = ESUtil.parseBoolean(this.liveUpdate, false);if(!this.scaleMin)
this.scaleMin = 0;else
this.scaleMin = parseFloat(this.scaleMin);if(!this.scaleMax)
this.scaleMax = 100;else
this.scaleMax = parseFloat(this.scaleMax);if(this.scaleMax <= this.scaleMin) {throw("Scales are illegal for slider ");}
if(this.thumbRelPos == null)
this.thumbRelPos = 0;this.clickStartCoords = null;this.clickStartRelPos = this.thumbRelPos;this.sliderThumb = null;this.sliderBar = null;}
ESSlider.setup = function() {ESSlider.superClass.setup.call(this);}
ESSlider.handleResize = function() {ESSlider.superClass.handleResize.call(this);this.setValue(this.value);}
ESSlider.createSlider = function() {} 
ESSlider.handleMouseDown = function(ev) {ESUtil.cancelEventDefault(ev);document.body.onmousemove = ESUtil.eventClosureWithThis(this.handleMouseMove, this);document.body.onmouseup = ESUtil.eventClosureWithThis(this.handleMouseUp, this);this.clickStartCoords = ESUtil.getEventCoords(ev);this.clickStartRelPos=this.thumbRelPos;}
ESSlider.handleMouseMove = function(ev) {} 
ESSlider.handleMouseUp = function(ev) {document.body.onmousemove=null;document.body.onmouseup=null;if(this.action)
this.action(this);}
ESSlider.setScale = function(scaleMin, scaleMax) {this.scaleMin = scaleMin;this.scaleMax = scaleMax;}
ESSlider.setPos = function(value) {} 
ESSlider.getPos = function(){return this.thumbRelPos;}
ESSlider.setValue = function(value) {this.setPos(this.valueToPos(value));}
ESSlider.getValue = function() {return this.value;}
ESSlider.computeBarLength = function() {} 
ESSlider.posToValue = function(pos) {var barLen = this.computeBarLength();if(pos < 0)
pos =0;if(pos > barLen)
pos = barLen;var dist = this.scaleMax-this.scaleMin;return (pos/barLen) * dist + this.scaleMin;}
ESSlider.valueToPos = function(value) {var dist = this.scaleMax-this.scaleMin;return (value - this.scaleMin)/dist*this.computeBarLength();}
ESSlider.absToRelCoords = function(coords) {return {x: coords.x - this.clickStartCoords.x, y: coords.y - this.clickStartCoords.y};}
ESHorzSlider = Subclass(ESSlider);ESHorzSlider.init = function() {ESHorzSlider.superClass.init.call(this);this.thumbWidth = 6;this.createSlider();}
ESHorzSlider.createSlider = function() {var sliderBarHeight = 8;var thumbHeight = this.position.height -4;var thumbMargin = (this.position.height - sliderBarHeight)/2;var thumbLeft = this.thumbRelPos;this.dom.style.position = "absolute";this.dom.style.display = "block";this.dom.style.fontSize ="1px";var sliderBar = document.createElement("div");sliderBar.className = "sliderBar";sliderBar.style.top = "25%";sliderBar.style.bottom = "25%";sliderBar.style.left = "2px";sliderBar.style.right = (2+this.thumbWidth) + "px";sliderBar.style.position = "absolute";sliderBar.style.background ="white";sliderBar.style.border = "1px solid black";sliderBar.style.fontSize = "1px";this.dom.appendChild(sliderBar);this.sliderbar = sliderBar;var sliderThumb = document.createElement("div");sliderThumb.className = "sliderThumb";sliderThumb.style.width = this.thumbWidth + "px";sliderThumb.style.top = "0px";sliderThumb.style.bottom = "0px";sliderThumb.style.left = thumbLeft + "px";sliderThumb.style.position = "absolute";sliderThumb.style.background = "white";sliderThumb.style.border ="1px solid black";sliderThumb.style.fontSize = "1px";sliderThumb.onmousedown = ESUtil.eventClosureWithThis(this.handleMouseDown, this);this.dom.appendChild(sliderThumb);this.sliderThumb = sliderThumb;}
ESHorzSlider.handleMouseMove = function(ev) {var relCoords = ESUtil.getEventRelativeCoords(ev, this.dom);this.setPos(relCoords.x);if(this.liveUpdate && this.action != null)
this.action(this);}
ESHorzSlider.computeBarLength = function() {var domWidth = this.getHTMLPosition().width;return domWidth - 4 - this.thumbWidth;}
ESHorzSlider.setPos = function(pos) {	
var sliderBarWidth = this.computeBarLength();if(pos < 0 || isNaN(pos))
pos =0;if(pos > sliderBarWidth)
pos = sliderBarWidth;if(this.sliderThumb) {this.sliderThumb.style.left = pos +"px";}
this.value = this.posToValue(pos);}
ESVertSlider = Subclass(ESSlider);ESVertSlider.init = function() {ESVertSlider.superClass.init.call(this);this.thumbHeight = 6;this.createSlider();}
ESVertSlider.createSlider = function(){ 
this.sliderBarHeight = this.position.height-2-this.thumbHeight;var sliderBarWidth = 8;var thumbWidth = this.position.width - 4;var thumbMargin = (this.position.width-sliderBarWidth-2)/2;var thumbTop = this.thumbRelPos;this.dom.style.position = "absolute";this.dom.style.display = "block";this.dom.style.fontSize = "1px";var sliderBar = document.createElement("div");sliderBar.className = "sliderBar";sliderBar.style.height = this.sliderBarHeight + "px";sliderBar.style.top = "2px";sliderBar.style.bottom = (2+this.thumbHeight) +"px";sliderBar.style.left= "25%";sliderBar.style.right = "25%";sliderBar.style.position = "absolute";sliderBar.style.background ="white";sliderBar.style.border = "1px solid black";sliderBar.style.fontSize = "1px";this.dom.appendChild(sliderBar);this.sliderbar = sliderBar;var sliderThumb = document.createElement("div");sliderThumb.className = "sliderThumb";sliderThumb.style.height = this.thumbHeight + "px";sliderThumb.style.width = thumbWidth + "px";sliderThumb.style.top = thumbTop + "px";sliderThumb.style.left = "0px";sliderThumb.style.position = "absolute";sliderThumb.style.background = "white";sliderThumb.style.border ="1px solid black";sliderThumb.style.fontSize = "1px";sliderThumb.onmousedown = ESUtil.eventClosureWithThis(this.handleMouseDown, this);this.dom.appendChild(sliderThumb);this.sliderThumb = sliderThumb;}
ESVertSlider.handleMouseMove = function(ev) {var relCoords = ESUtil.getEventRelativeCoords(ev, this.dom);this.setPos(this.computeBarLength()-relCoords.y);if(this.liveUpdate && this.action != null)
this.action(this);}
ESVertSlider.computeBarLength = function() {return this.getHTMLPosition().height-4 - this.thumbHeight;}
ESVertSlider.setPos = function(pos) {var barLen = this.computeBarLength();if(pos < 0)
pos = 0;if(pos > barLen)
pos =barLen;if(this.sliderThumb)
this.sliderThumb.style.top = (barLen-pos)  + "px";this.value = this.posToValue(pos);}
ESSwatchColorPicker = Subclass(ESMutableControl);ESSwatchColorPicker.init = function() {ESSwatchColorPicker.superClass.init.call(this);if(!this.swatchSize)
this.swatchSize=16;this.r=this.g=this.b=null;this.createPicker();}
ESSwatchColorPicker.setup = function() {ESSwatchColorPicker.superClass.setup.call(this);}
ESSwatchColorPicker.handleResize = function() {ESSwatchColorPicker.superClass.handleResize.call(this);var coords = this.getHTMLPosition();if(coords.width == 0 ||  coords.height ==0)
throw("Illegal coords.width, or coords.height in ESSwatchColorPicker");this.pickerTable.style.width = coords.width+"px";this.pickerTable.style.height = coords.height+"px";}
ESSwatchColorPicker.baseColors=function() {var colorStrs = ["F0F8FF", "FAEBD7", "00FFFF", "7FFFD4", "F0FFFF", "F5F5DC", "FFE4C4", "000000", "FFEBCD", "0000FF", "8A2BE2", "A52A2A", "DEB887", "5F9EA0", "7FFF00", "D2691E", "FF7F50", "6495ED", "FFF8DC", "DC143C", "00FFFF", "00008B", "008B8B", "B8860B", "A9A9A9", "A9A9A9", "006400", "BDB76B", "8B008B", "556B2F", "FF8C00", "9932CC", "8B0000", "E9967A", "8FBC8F", "483D8B", "2F4F4F", "2F4F4F", "00CED1", "9400D3", "FF1493", "00BFFF", "696969", "696969", "1E90FF", "B22222", "FFFAF0", "228B22", "FF00FF", "DCDCDC", "F8F8FF", "FFD700", "DAA520", "808080", "808080", "008000", "ADFF2F", "F0FFF0", "FF69B4", "CD5C5C", "4B0082", "FFFFF0", "F0E68C", "E6E6FA", "FFF0F5", "7CFC00", "FFFACD", "ADD8E6", "F08080", "E0FFFF", "FAFAD2", "D3D3D3", "D3D3D3", "90EE90", "FFB6C1", "FFA07A", "20B2AA", "87CEFA", "778899", "778899", "B0C4DE", "FFFFE0", "00FF00", "32CD32", "FAF0E6", "FF00FF", "800000", "66CDAA", "0000CD", "BA55D3", "9370D8", "3CB371", "7B68EE", "00FA9A", "48D1CC", "C71585", "191970", "F5FFFA", "FFE4E1", "FFE4B5", "FFDEAD", "000080", "FDF5E6", "808000", "6B8E23", "FFA500", "FF4500", "DA70D6", "EEE8AA", "98FB98", "AFEEEE", "D87093", "FFEFD5", "FFDAB9", "CD853F", "FFC0CB", "DDA0DD", "B0E0E6", "800080", "FF0000", "BC8F8F", "4169E1", "8B4513", "FA8072", "F4A460", "2E8B57", "FFF5EE", "A0522D", "C0C0C0", "87CEEB", "6A5ACD", "708090", "708090", "FFFAFA", "00FF7F", "4682B4", "D2B48C", "008080", "D8BFD8", "FF6347", "40E0D0", "EE82EE", "F5DEB3", "FFFFFF", "F5F5F5", "FFFF00", "9ACD32"];var returnme = [];for(var i=0; i < colorStrs.length; i++) {returnme.push(this.colorStrToStruct(colorStrs[i]));}
return returnme;}
ESSwatchColorPicker.colorStrToStruct = function(cStr) {var returnme = new Object();var intVal = parseInt(cStr, 16);returnme.b = intVal % 256;returnme.g = Math.round(intVal / 256)%256;returnme.r = Math.round(intVal/65536)%256;return returnme;}
ESSwatchColorPicker.createPicker = function() {var pickerTable = document.createElement("table");var tdCount =0;var daTR = null
var rowSize =12;var colorsArr = this.baseColors();colorsArr = this.orderFromDarkest(colorsArr);for(var i=0; i < colorsArr.length; i++) {if(tdCount == rowSize || tdCount == 0) {daTr = document.createElement("tr");pickerTable.appendChild(daTr);tdCount =0 ;}
var r = colorsArr[i].r;var g = colorsArr[i].g;var b = colorsArr[i].b;var daTd = document.createElement("td");daTd.style.backgroundColor="rgb("+ r + "," + g + "," +b +")";daTd.style.border="1px solid black";daTd.style.margin="0px";daTd.style.padding="0px";daTd.style.fontSize="1px";daTd.style.cursor="pointer";daTd.onclick = ESUtil.eventClosureWithThis(this.pickHandler, this, r, g, b);daTr.appendChild(daTd);tdCount ++;}
this.pickerTable = pickerTable;this.dom.appendChild(pickerTable);}
ESSwatchColorPicker.pickHandler = function(ev,r,g,b) {this.r=r;this.b=b;this.g=g;ESUtil.cancelEventDefault(ev);if(this.action)
this.action(this);}
ESSwatchColorPicker.getRGB=function() {var returnme = {r: this.r, g:this.g, b:this.b};return returnme;}
ESSwatchColorPicker.orderFromDarkest = function(colorsArr) {	
var colorSizeF = function(c) {return Math.sqrt(c.r*c.r+c.g*c.g+c.b*c.b);}
var mostSimilarF = function(colors, comp) {var closestedIdx = 0;var closestVal = 9999999999999;for(var i=0; i < colors.length; i++) {var dist = Math.pow(colors[i].r-comp.r, 2) + Math.pow(colors[i].g-comp.g, 2) + Math.pow(colors[i].b-comp.b, 2);if(dist < closestVal) {closestIdx  = i;closestVal = dist;}
}
return closestIdx;}
var colorDist = function(c1, c2) {return Math.sqrt(Math.pow(c1.r-c2.r,2) + Math.pow(c1.g-c2.g,2) + Math.pow(c1.b-c2.b,2));}
var filterSimilarColors = function(colors) {var thres = 6;var returnme = [];returnme.push(colors[0]);for(var i=1; i < colors.length; i++) {if(colorDist(colors[i], colors[i-1]) >= thres)
returnme.push(colors[i]);}
return returnme;}
var smallest=colorSizeF(colorsArr[0]), smallestIdx=0;for(var i=0; i < colorsArr.length; i++) {if(colorSizeF(colorsArr[i]) < smallest) {smallestIdx = i;smallest = colorSizeF(colorsArr[i]);}
}
var returnme = new Array();var last = colorsArr[smallestIdx];returnme.push(last);while(colorsArr.length > 0){var idx = mostSimilarF(colorsArr, last);last = colorsArr[idx];colorsArr.splice(idx,1);returnme.push(last);}
returnme = filterSimilarColors(returnme);return returnme;}
ESSwatchColorPicker.setValue = function(colorRGB) {this.r = colorRGB.r;this.g = colorRGB.g;this.b = colorRGB.b;}
ESSwatchColorPicker.getValue = function() {return this.getRGB();}
ESHSVColorPicker = Subclass(ESMutableControl) 
ESHSVColorPicker.init = function(){ESHSVColorPicker.superClass.init.call(this);this.h = this.s= this.v =1;ESHSVColorPicker.defaultWidth = "250px";ESHSVColorPicker.defaultHeight = "250px";this.VSlider = null;this.wheelWidth=200;}
ESHSVColorPicker.setup = function() {ESHSVColorPicker.superClass.setup.call(this);this.createPicker();}
ESHSVColorPicker.createPicker = function() {this.dom.style.width=ESHSVColorPicker.defaultWidth;this.dom.style.height =ESHSVColorPicker.defaultHeight;var label = document.createElement("div");label.innerHTML = "Current Color: ";label.style.position = "absolute";label.style.top = "5px";label.style.left = "5px";this.dom.appendChild(label);var swatch = document.createElement("div");swatch.style.position = "absolute";swatch.style.top = "10px";swatch.style.width="50px";swatch.style.height="30px";swatch.style.right = "10px";swatch.style.position = "absolute";swatch.style.border = "1px solid black";this.dom.appendChild(swatch);this.swatch = swatch;var slider = Allocate(ESVertSlider);slider.position = {top:100, right:10, bottom:10, width:24};slider.parentCanvas = this;slider.action = ESUtil.closureWithThis(this.handleVChange, this);slider.scaleMin =0;slider.scaleMax = 1.0;slider.value=1.0;slider.liveUpdate = "true";slider.init();slider.buildTree();slider.setup();this.Vslider= slider;var wheelImg = document.createElement("img");wheelImg.src = "http://sweaglesw.org/~tofu702/espresso/colorWheel.png";wheelImg.style.position = "absolute";wheelImg.style.left = "5px";wheelImg.style.bottom = "5px";wheelImg.style.cursor ="crosshair";wheelImg.onmousedown = ESUtil.eventClosureWithThis(this.handleHSMouseDown, this);this.dom.appendChild(wheelImg);var blackImg = document.createElement("img");blackImg.src = "http://sweaglesw.org/~tofu702/espresso/blackWheel.png";blackImg.style.position = "absolute";blackImg.style.left="5px";blackImg.style.bottom="5px";blackImg.style.cursor ="crosshair";blackImg.onmousedown = ESUtil.eventClosureWithThis(this.handleHSMouseDown, this);blackImg.style.opacity = 0;this.dom.appendChild(blackImg);this.blackWheelImg = blackImg;}
ESHSVColorPicker.reposition = function(posObj) {ESHSVColorPicker.superClass.reposition.call(this, posObj);this.dom.style.width = ESHSVColorPicker.defaultWidth;this.dom.style.height = ESHSVColorPicker.defaultWidth;}
ESHSVColorPicker.handleHSMouseDown=function(ev) {ESUtil.cancelEventDefault(ev);window.onmousemove = ESUtil.eventClosureWithThis(this.handleHSSel, this);window.onmouseup = ESUtil.eventClosureWithThis(this.handleHSMouseUp, this);}
ESHSVColorPicker.handleHSMouseUp = function(ev) {ESUtil.cancelEventDefault(ev);window.onmousemove=null;}
ESHSVColorPicker.handleHSSel=function(ev) {var coords = ESUtil.getEventRelativeCoords(ev, this.blackWheelImg);var h =0;var s =0;var v = this.v;var rad = this.wheelWidth/2;var rX = coords.x - rad;var rY = coords.y - rad;s = Math.sqrt(rX*rX + rY*rY);if(s > rad)
return;s /= rad;h = Math.atan2(rY, rX);h = h * 360/(2*Math.PI);if(h < 0)
h+=360;h = 359.999999 - h;this.setHSV(h,s,v);if(this.action)
this.action(this);}
ESHSVColorPicker.handleVChange = function(){ 	
var val = this.Vslider.getValue();this.setHSV(this.h, this.s, val);if(this.action)
this.action(this)
}
ESHSVColorPicker.convertHSVToRGB = function(h,s,v) {	
var returnme = new Object();var Hi = Math.floor(h/60) % 6;var f= h/60-Hi;var p=v*(1-s);var q=v*(1-f*s);var t=v*(1-(1-f)*s);v*=255;t*=255;p*=255;q*=255;switch(Hi) {case 0:
returnme.r = v;returnme.g = t;returnme.b = p;break;case 1:
returnme.r = q;returnme.g = v;returnme.b = p;break;case 2:
returnme.r = p;returnme.g = v;returnme.b = t;break;case 3:
returnme.r = p;returnme.g = q;returnme.b = v;break;case 4:
returnme.r = t;returnme.g = p;returnme.b = v;break;case 5:
returnme.r = v;returnme.g = p;returnme.b = q;break;default:
break;}
return returnme;}
ESHSVColorPicker.convertRGBToHSV = function(r,g,b) {r /= 255.0;g /= 255.0;b /= 255.0;var MIN = Math.min(r,g,b);var MAX = Math.max(r,g,b);var h = null;var s = null;if(MIN == MAX) {h = 0;} else if(MAX == r && g > b) {h = 60*(g-b)/(MAX-MIN);} else if(MAX == r && g < b) {h = 60*(g-b)/(MAX-MIN)+360;} else if(MAX == g) {h = 60 * (b-r)/(MAX-MIN)+120;} else if(MAX == b) {h= 60*(r-g)/(MAX-MIN)+240;}
if(MAX == 0)
s = 0;else 
s = 1- MIN/MAX;v = MAX;return {h:h, s:s, v:v};}
ESHSVColorPicker.refreshView = function() {}
ESHSVColorPicker.setRGB = function(r, g, b)  {var hsv = this.convertRGBToHSV(r,g,b);this.setHSV(hsv.h, hsv.s, hsv.v);}
ESHSVColorPicker.setHSV = function(h,s,v) {var rgb = this.convertHSVToRGB(h,s,v);this.h = h;this.s = s;this.v = v;this.blackWheelImg.style.opacity = 1-v;this.swatch.style.backgroundColor = "rgb(" + Math.round(rgb.r) + "," + Math.round(rgb.g) + "," + Math.round(rgb.b) + ")";}
ESHSVColorPicker.getRGB = function() {return this.convertHSVToRGB(this.h, this.s, this.v);}
ESHSVColorPicker.setValue = function(colorRGB) {this.setRGB(colorRGB.r, colorRGB.g, colorRGB.b);}
ESHSVColorPicker.getValue = function() {return this.getRGB();}
ESDateSelector = Subclass(ESMutableControl);ESDateSelector.init = function() {ESDateSelector.superClass.init.call(this);var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];this.dom.appendChild(document.createTextNode("Month: "));this.monthSel = document.createElement("select");var self=this;this.monthSel.onchange = function() { self.action(self); };for(var i=0; i < months.length; i++)  {var presMonth=document.createElement("option");presMonth.value = months[i];presMonth.appendChild(document.createTextNode(months[i]));this.monthSel.appendChild(presMonth);}
this.dom.appendChild(this.monthSel);this.dom.appendChild(document.createTextNode(" Day: "));this.dayField = document.createElement("input");this.dayField.type ="text";this.dayField.style.width = "30px";this.dayField.onchange = ESUtil.closureWithThis(this.legalizeIntInput, this, this.dayField, 1, 31);this.dom.appendChild(this.dayField);this.dom.appendChild(document.createTextNode(" Year: "));this.yearField = document.createElement("input");this.yearField.type ="text";this.yearField.style.width = "50px";this.yearField.onchange = ESUtil.closureWithThis(this.legalizeIntInput, this, this.yearField, 0, 9999);this.dom.appendChild(this.yearField);if(this.value != null)
this.setValue(this.value);}
ESDateSelector.legalizeIntInput = function(input, min, max) {var value = input.value;var newVal ="";for(var i=0; i <  value.length; i++) {if(value[i] < "0" || value[i] > "9")
continue;newVal += value[i];}
var intVal = parseInt(newVal);if(intVal < min || intVal > max)
input.value = "";else if(newVal != value)
input.value = newVal;if(this.action)
this.action(this);}
ESDateSelector.setValue = function(date) {if(date.month) {this.monthSel.selectedIndex = date.month-1;}
if(date.day) {this.dayField.value = date.day;}
if(date.year) {this.yearField.value = date.year;}
}
ESDateSelector.getValue = function() {if(this.yearField.value == "" || this.dayField.value == "")
return null;return {month: this.monthSel.selectedIndex+1, day: this.dayField.value, year: this.yearField.value};}
var ESSQLDatabase = Subclass(ESDatabase);ESSQLDatabase.init = function(url)
{this.url = url;}
ESSQLDatabase.query = function(sql)
{var req = Allocate(ESXMLHTTP);req.init();var json = req.postText(this.url, "text/plain", sql);try {return eval(json);} catch(ex) { alert(ex + " : " + json); return null; }
}
ESCookie = Subclass(ESObject);ESCookie.read = function(name){var cookies = document.cookie.split(";");for(var i=0;i<cookies.length;i++)
{var parts = cookies[i].split("=");if(parts[0].replace(/^ */, "") == name)
{if(parts.length==1)return null;parts.splice(0,1);return unescape(parts.join("="));}
}
return null;}
ESCookie.write = function(name, value, path){if(path)document.cookie = name + "=" + escape(value) + ";path=" + path;else document.cookie = name + "=" + escape(value);}
ESCookie.deleteCookie = function(name, path) {if(path) document.cookie = name + "=;path=" + path + ";expires=" + (new Date()).toGMTString();else document.cookie = name + "=;expires=" + (new Date()).toGMTString();}
ESText = Subclass(ESView);ESText.init = function()
{ESText.superClass.init.call(this);var self = this;this.focused = true;this.dom.onmousedown = function(ev) {if(!self.focused)self.focus();if(!ev)ev=window.event;ev.cancelBubble = true;if(ev.stopPropagation)ev.stopPropagation();if(ev.preventDefault)
ev.preventDefault();self.expectingSpuriousBlur = true;setTimeout(function(){self.expectingSpuriousBlur = false;}, 200);}
this.dom.style.border='2px inset #88c';this.dom.style.overflow='auto';this.ta = document.createElement("textarea");this.ta.onkeypress = function(ev) { self.keypress(ev, 0); }
this.ta.onfocus = function() { if(!self.focused)self.focus(); }
this.ta.onblur = function() { if(self.expectingSpuriousBlur){self.ta.focus(); return;} if(self.focused)self.blur(); }
this.ta.style.position='absolute';this.ta.style.opacity='0';this.ta.style.fontSize='0px';this.dom.appendChild(this.ta);var topmargin = document.createElement("div");topmargin.style.height='8px';topmargin.style.left='0px';topmargin.style.right='0px';topmargin.style.top='0px';topmargin.style.margin='0px';this.dom.appendChild(topmargin);this.inspt = document.createElement("img");this.inspt.style.background='black';this.inspt.style.height='18px';if(!this.cursorWidth)this.cursorWidth = 1;this.inspt.style.width=this.cursorWidth + 'px';this.inspt.style.marginRight=-this.cursorWidth + 'px';this.inspt.style.marginBottom='-3px';this.inspt.style.marginTop='-5px';this.ipflash = true;this.flasher = Allocate(ESRepeatingTimer);this.flasher.interval = 500;this.flasher.func = function() {self.ipflash = !self.ipflash;if(self.ipflash)self.inspt.style.background = 'black';else self.inspt.style.background = 'none';};this.flasher.init(); this.flasher.start();this.lines = [];this.selpt = [-1,0];this.newLine();this.blur();}
ESText.focus = function()
{this.focused = true;this.ta.focus();this.inspt.style.background='black';this.flasher.start();this.dom.style.border='2px inset #88c';var self=this;if(!this.capturePaste) this.capturePaste = function(ev) {if(!ev)ev=window.event;var str = String.fromCharCode(ev.which);if(str=="v" && (ev.ctrlKey || ev.metaKey))
self.keypress(ev, 1);};if(document.addEventListener)
document.addEventListener("keypress", this.capturePaste, true);}
ESText.blur = function()
{this.ta.blur();this.flasher.stop();this.inspt.style.background='#bbb';this.focused = false;this.dom.style.border='2px inset #888';if(this.capturePaste && document.removeEventListener)
document.removeEventListener("keypress", this.capturePaste, true);}
ESText.keypress = function(ev, maypaste)
{if(!this.focused)return;if(!ev)ev=window.event;var self=this;var mods = {command: (ev.metaKey || ev.ctrlKey), shift: ev.shiftKey, alt: ev.altKey};var str = String.fromCharCode(ev.which);if(!mods.command && !mods.alt)
{this.ipflash = false;var which = ev.which;if(!str || str=="" || which==0)
{if(ev.keyCode == 38)which = 63232;if(ev.keyCode == 40)which = 63233;if(ev.keyCode == 37)which = 63234;if(ev.keyCode == 39)which = 63235;if(ev.keyCode == 46)which = 63272;if(ev.keyCode == 9)str = "\t";}
switch(which)
{case	63232:	this.moveCursor(mods.shift, -1,0);	break;case	63233:	this.moveCursor(mods.shift, 1,0);	break;case	63234:	this.moveCursor(mods.shift, 0,-1);	break;case	63235:	this.moveCursor(mods.shift, 0,+1);	break;case	63272:	this.forwardDelete();	break;case	13: case	10:	this.typeNewLine();	break;case	8:	this.backspace(); break;default:
if(str && str!="")
this.type(str, ev.keyCode);break;}
}
else
{if(mods.command)switch(str) {case	"x":
this.ta.value = this.copyText();if(this.selfrom)this.clearSelText();this.ta.select(0, this.ta.value.length);setTimeout(function() { self.ta.value=''; }, 200);break;case	"c":
this.ta.value = this.copyText();this.ta.select(0, this.ta.value.length);setTimeout(function() { self.ta.value=''; }, 200);break;case	"v":
if(!maypaste)return;this.ta.value = "";this.ta.select(0,0);setTimeout(function() { self.pasteText(self.ta.value); }, 100);break;case	"z":
alert("undo");break;}
}
if(!mods.command)
{ev.cancelBubble = true;if(ev.stopPropagation)ev.stopPropagation();if(ev.preventDefault)
ev.preventDefault();}
}
ESText.pasteText = function(text)
{if(this.selfrom)this.clearSelText();for(var i=0;i<text.length;i++)
{var c = text.charAt(i);if(c=='\n' || c=='\r')
this.newLine();else this.insertChar(c);}
}
ESText.copyText = function()
{if(!this.selfrom)return "";var line1 = this.selfrom[0], line2 = this.selto[0];var col1 = this.selfrom[1], col2 = this.selto[1];var order = (line1<line2 || (line1==line2 && col1<col2));var top = order?line1:line2, bot = order?line2:line1;var topcol = order?col1:col2, botcol = order?col2:col1;if(top == bot)return this.lines[top].copyText(topcol, botcol);else
{var text = "";var topline = this.lines[top];var botline = this.lines[bot];var text = topline.copyText(topcol, topline.cols);for(var i=top+1;i<bot;i++)
text += "\n" + this.lines[i].copyText(0, this.lines[i].cols);text += "\n" + botline.copyText(0, botcol);return text;}
}
ESText.getText = function()
{var text = '';for(var i=0;i<this.lines.length;i++)
text += ((i==0)?'':'\n') + this.lines[i].copyText(0, this.lines[i].cols);return text;}
ESText.setText = function(text)
{this.selfrom = [0,0];this.selto = [this.lines.length-1, this.lines[this.lines.length-1].cols];this.clearSelText();this.pasteText(text);}
ESText.mousedown = function(mods, line, col)
{if(mods.shift)
{if(this.selfrom)
this.dragfrom = this.selfrom;else this.dragfrom = this.selpt;}
else this.dragfrom = [line, col];this.mousemove(mods, line, col);this.flasher.stop();this.inspt.style.background='black';}
ESText.mouseup = function(mods, line, col)
{this.ipflash = true;this.flasher.start();this.dragfrom = null;}
ESText.mousemove = function(mods, line, col)
{if(!this.dragfrom)return;if(line==this.dragfrom[0] && col==this.dragfrom[1])
this.setselpt(line, col);else
this.setselrange(this.dragfrom[0], this.dragfrom[1], line, col);}
ESText.backspace = function()
{if(!this.selfrom)
{if(this.selpt[1]==0)
{if(this.selpt[0]==0)return;var first = this.lines[this.selpt[0]-1];var second = this.lines[this.selpt[0]];var prevlen = first.cols;this.lines.splice(this.selpt[0], 1);this.dom.removeChild(second.dom);first.joinLine(second);this.setselpt(this.selpt[0]-1, prevlen);}
else
{this.lines[this.selpt[0]].delChar(this.selpt[1]-1);this.setselpt(this.selpt[0], this.selpt[1]-1);}
}
else this.clearSelText();}
ESText.forwardDelete = function()
{if(this.selfrom) { this.backspace(); return; }
else if(this.selpt[0] == this.lines.length-1 && this.selpt[1] == this.lines[this.lines.length-1].cols)return;this.moveCursor(0, 0, 1);this.backspace();}
ESText.clearSelText = function()
{if(!this.selfrom)return;var line1 = this.selfrom[0], line2 = this.selto[0];var col1 = this.selfrom[1], col2 = this.selto[1];var order = (line1<line2 || (line1==line2 && col1<col2));var top = order?line1:line2, bot = order?line2:line1;var topcol = order?col1:col2, botcol = order?col2:col1;if(top == bot)this.lines[top].cutText(topcol, botcol);else
{var topline = this.lines[top];var botline = this.lines[bot];for(var i=top+1;i<=bot;i++)
this.dom.removeChild(this.lines[i].dom);this.lines.splice(top+1, bot-top);topline.cutText(topcol, topline.cols);botline.cutText(0, botcol);topline.joinLine(botline);}
this.selfrom = null;this.selto = null;this.setselpt(top, topcol);}
ESText.moveCursor = function(extendsel, lines, cols)
{if(!extendsel && this.selfrom)
{var order = (this.selfrom[0]<this.selto[0] ||
(this.selfrom[0]==this.selto[0] && this.selfrom[1]<this.selto[1]))
if(lines>0 || cols>0)order = !order;var line = order?this.selfrom[0]:this.selto[0];var col = order?this.selfrom[1]:this.selto[1];}
else
{var line = this.selpt[0] + lines;var col = this.selpt[1] + cols;if(line >= this.lines.length) { line = this.lines.length-1; col = this.lines[line].cols; }
if(line < 0) { line = 0; col = 0; }
if(col < 0)
{if(line > 0 && cols) { line--; col = this.lines[line].cols; }
else col = 0;}
if(col > this.lines[line].cols)
{if(line < this.lines.length-1 && cols) { line++; col = 0; }
else col = this.lines[line].cols;}
}
if(extendsel)
{if(!this.selfrom) { this.selfrom = this.selpt; this.selto = this.selpt; }
this.setselrange(this.selfrom[0], this.selfrom[1], line, col);}
else this.setselpt(line, col);}
ESText.lineNumberOf = function(line)
{for(var i=0;i<this.lines.length;i++)
if(this.lines[i] == line)return i;return this.lines.length;}
ESText.insertChar = function(ch)
{if(this.selfrom)this.clearSelText();this.lines[this.selpt[0]].addChar(ch, this.selpt[1]);this.setselpt(this.selpt[0], this.selpt[1]+1);}
ESText.type = function(ch)
{this.insertChar(ch);}
ESText.typeNewLine = function()
{this.newLine();}
ESText.newLine = function()
{var l = Allocate(ESTextLine); l.init(this);var lnum = this.selpt[0]+1;if(lnum == this.lines.length)
this.dom.appendChild(l.dom);else this.dom.insertBefore(l.dom, this.lines[lnum].dom);this.lines.splice(lnum, 0, l);if(this.selpt[0]>=0)
{var lprev = this.lines[this.selpt[0]];if(this.selpt[1] != lprev.cols)
l.addText(lprev.cutText(this.selpt[1], lprev.cols), 0);}
this.setselpt(lnum, 0);}
ESText.setselpt = function(line, col)
{if(this.selfrom)this.clearselrange();if(this.inspt.parentNode)
this.inspt.parentNode.removeChild(this.inspt);if(!this.lines[line])alert("setselpt " + line + "," + col + ": no this.lines[line]");this.lines[line].showinspt(col, this.inspt);this.selpt = [line, col];}
ESText.clearselrange = function()
{if(!this.selfrom)return;var top = this.selfrom[0], bot = this.selto[0];if(top>bot) { top=this.selto[0]; bot=this.selfrom[0]; }
for(var i=top;i<=bot;i++)this.lines[i].clearselrange();this.selfrom = null;this.selto = null;}
ESText.setselrange = function(line1, col1, line2, col2)
{if(this.selfrom)this.clearselrange();if(this.inspt.parentNode)
this.inspt.parentNode.removeChild(this.inspt);if(line1==line2 && col1==col2)
{this.setselpt(line1, col1);this.selfrom = null;this.selto = null;return;}
var order = (line1<line2 || (line1==line2 && col1<col2))
var top = order?line1:line2, bot = order?line2:line1;var topcol = order?col1:col2, botcol = order?col2:col1;this.selfrom = [line1, col1];this.selto = [line2, col2];if(top == bot)this.lines[top].setselrange(topcol, botcol);else
{this.lines[top].setselrange(topcol, this.lines[top].cols);for(var i=top+1;i<bot;i++)
this.lines[i].setselrange(0, this.lines[i].cols);this.lines[bot].setselrange(0, botcol);}
this.selpt = this.selto;}
ESTextLine = Subclass(ESObject);ESTextLine.init = function(textObject)
{this.text = textObject;this.dom = document.createElement("div");this.dom.style.position='relative';this.dom.style.padding='0px';this.dom.style.margin='0px';this.dom.style.marginLeft = "8px";this.dom.style.marginRight = "8px";this.dom.style.whiteSpace = 'pre';this.temp = document.createElement("span");this.temp.innerHTML="\t";this.dom.appendChild(this.temp);this.cols = 0;}
ESTextLine.reportEvent = function(callback, cell, ev)
{if(!ev)ev=window.event;var mods = {command: (ev.metaKey || ev.ctrlKey), shift: ev.shiftKey, alt: ev.altKey};var coords = ESUtil.getEventRelativeCoords(ev, cell);if(coords.x > cell.offsetWidth/2)var add=1;else var add=0;for(var i=0;i<this.cols;i++)
if(this.dom.childNodes[i] == cell)break;callback.call(this.text, mods, this.text.lineNumberOf(this), i+add);}
ESTextLine.configureHandlers = function(cell)
{var self = this;cell.onmousedown = function(ev) { self.reportEvent(self.text.mousedown, cell, ev); }
cell.onmouseup = function(ev) { self.reportEvent(self.text.mouseup, cell, ev); }
cell.onmousemove = function(ev) { self.reportEvent(self.text.mousemove, cell, ev); }
}
ESTextLine.addChar = function(ch, col)
{if(this.temp.parentNode == this.dom)
this.dom.removeChild(this.temp);var cell = document.createElement("span");cell.appendChild(document.createTextNode(ch));if(col == this.cols)
this.dom.appendChild(cell);else this.dom.insertBefore(cell, this.dom.childNodes[col]);this.cols++;this.configureHandlers(cell);}
ESTextLine.showinspt = function(col, inspt)
{if(this.cols==0)
{this.temp.insertBefore(inspt, this.temp.firstChild);return;}
if(col < this.cols)
{this.dom.childNodes[col].insertBefore(inspt, this.dom.childNodes[col].firstChild);return;}
this.dom.childNodes[this.cols-1].appendChild(inspt);}
ESTextLine.joinLine = function(line)
{if(line.cols == 0)return;if(this.cols == 0)
this.dom.removeChild(this.temp);while(line.dom.firstChild)
{var cell = line.dom.firstChild;line.dom.removeChild(cell);this.dom.appendChild(cell);this.configureHandlers(cell);}
this.cols += line.cols;}
ESTextLine.delChar = function(col)
{this.cols--;this.dom.removeChild(this.dom.childNodes[col]);if(!this.cols)
this.dom.appendChild(this.temp);}
ESTextLine.addText = function(text, col)
{for(var i=0;i<text.length;i++)
this.addChar(text.charAt(i), col++);}
ESTextLine.copyText = function(from, to)
{var text = "";for(var i=from;i<to;i++)
{if(this.dom.childNodes[i].firstChild.tagName)
text += this.dom.childNodes[i].lastChild.nodeValue;else text += this.dom.childNodes[i].firstChild.nodeValue;}
return text;}
ESTextLine.cutText = function(from, to)
{var text = this.copyText(from, to);for(var i=from;i<to;i++)
this.delChar(from);return text;}
ESTextLine.clearselrange = function()
{for(var i=0;i<this.cols;i++)
this.dom.childNodes[i].style.background = 'white';}
ESTextLine.setselrange = function(from, to)
{for(var i=from;i<to;i++)
this.dom.childNodes[i].style.background = '#ddf';}
ESTextLine.colorrange = function(from, to, color)
{for(var i=from;i<to;i++)
this.dom.childNodes[i].style.color = color;}
ESCodeEditor = Subclass(ESText);ESCodeEditor.init = function()
{ESCodeEditor.superClass.init.call(this);this.dom.style.fontFamily = "courier";if(this.emulateVI == null)
this.emulateVI=false;else
this.emulateVI = ESUtil.parseBoolean(this.emulateVI);}
ESCodeEditor.setup = function()
{ESCodeEditor.superClass.setup.call(this);if(!this.colorMaps)
this.colorMaps = [];if(!this.tokenizers)
this.tokenizers = " \t[]{}()+-=_|!@#$%^&*/?.,><~`:;";this.commandMode = false;}
ESCodeEditor.backspace = function()
{ESCodeEditor.superClass.backspace.apply(this, arguments);this.rehilight(this.lines[this.selpt[0]]);if(this.selpt[0]+1 < this.lines.length)
this.rehilight(this.lines[this.selpt[0]+1]);}
ESCodeEditor.pasteText = function()
{ESCodeEditor.superClass.pasteText.apply(this, arguments);for(var i=0;i<this.lines.length;i++)
this.rehilight(this.lines[i]);}
ESCodeEditor.cutText = function()
{ESCodeEditor.superClass.cutText.apply(this, arguments);for(var i=0;i<this.lines.length;i++)
this.rehilight(this.lines[i]);}
ESCodeEditor.rehilight = function(line)
{var text = line.copyText(0, line.cols);line.colorrange(0, line.cols, "black");for(var i=0;i<this.colorMaps.length;i++)
{var match = this.colorMaps[i].match;var color = this.colorMaps[i].color;var c = text, m = match.exec(c);var offset = 0;while(m && m[0])
{var matchlen = m.index+m[0].length;var istoken = 1;var prevch = offset + m.index-1;if(prevch<0)prevch = ' ';else prevch = text.charAt(prevch);var nextch = offset + matchlen;if(nextch>=text.length)nextch = ' ';else nextch = text.charAt(nextch);if(this.tokenizers.indexOf(prevch) == -1)istoken = 0;if(this.tokenizers.indexOf(nextch) == -1)istoken = 0;if(istoken)line.colorrange(offset + m.index, offset+matchlen, color);offset += matchlen;c = c.substring(matchlen, c.length);m = match.exec(c);}
}
}
ESCodeEditor.commandKey = function(ch, kk)
{if(kk==27) { this.commandModeAwaitingMovement = null; return; }
if(this.selfrom)this.setselpt(this.selto[0], this.selto[1]);if(!this.commandModeAwaitingMovement) switch(ch)
{case	'd':	this.commandModeAwaitingMovement = 'd';	return;case	'c':	this.commandModeAwaitingMovement = 'c';	return;}
else
{var command = this.commandModeAwaitingMovement;var from = [this.selpt[0], this.selpt[1]];this.commandModeAwaitingMovement = null;if(command == ch) {from[1] = 0;var to = [from[0],from[1]]; to[1] = this.lines[to[0]].cols;if(ch=='d' && from[0]>0) { from[0]--; from[1] = this.lines[from[0]].cols; }
else if(ch=='d' && to[0]+1<this.lines.length) { to[0]++; to[1] = 0; }
}
else
{if(command=='c' && ch=='w')ch='e';this.commandKey(ch, kk);if(ch == 'e')this.moveCursor(false, 0, 1);var to = [this.selpt[0], this.selpt[1]];}
this.setselrange(from[0], from[1], to[0], to[1]);switch(command)
{case	'd':	this.clearSelText(); return;case	'c':	this.clearSelText(); return this.leaveCommandMode();}
}
switch(ch)
{case	'o':
this.commandKey('A');return this.typeNewLine();case	'O':
this.commandKey('I');this.typeNewLine();return this.moveCursor(false, -1, 0);case	'i':
return this.leaveCommandMode();case	'I':
var line = this.lines[this.selpt[0]];var text = line.copyText(0,line.cols);for(var i=0;i<text.length;i++)
{var ch = text.charAt(i);if(ch != ' ' && ch != '\t')break;}
this.setselpt(this.selpt[0], i);return this.leaveCommandMode();case	'a':
this.moveCursor(false, 0, 1);return this.leaveCommandMode();case	'A':
this.setselpt(this.selpt[0], this.lines[this.selpt[0]].cols);return this.leaveCommandMode();case	'j':	this.moveCursor(false, 1, 0);	return;case	'k':	this.moveCursor(false, -1, 0);	return;case	'h':	this.moveCursor(false, 0, -1);	return;case	'l':	this.moveCursor(false, 0, 1);	return;case	'x':	this.forwardDelete();	return;case	'w':
var i = this.selpt[1];var line = this.lines[this.selpt[0]];var text = line.copyText(0,line.cols);if(" \t".indexOf(text.charAt(i)) >= 0)return this.advanceToWord();if(this.tokenizers.indexOf(text.charAt(i)) >= 0)i++;else for(var i=this.selpt[1]+1;i<text.length;i++)
if(this.tokenizers.indexOf(text.charAt(i)) >= 0)break;this.setselpt(this.selpt[0], i);return this.advanceToWord();case	'b':
var i = this.selpt[1];if(i==0)this.moveCursor(false, 0, -1);this.moveCursor(false, 0, -1);this.retreatToWord();var i = this.selpt[1];var line = this.lines[this.selpt[0]];var text = line.copyText(0,line.cols);if(this.tokenizers.indexOf(line.copyText(i, i+1)) >= 0)return;while(i-1>=0 && this.tokenizers.indexOf(text.charAt(i-1)) < 0)i--;this.setselpt(this.selpt[0], i);return;case	'e':
this.moveCursor(false, 0, 1);var i = this.selpt[1];var line = this.lines[this.selpt[0]];if(i == line.cols || " \t".indexOf(line.copyText(i, i+1)) >= 0)this.commandKey('w');var i = this.selpt[1];var line = this.lines[this.selpt[0]];var text = line.copyText(0,line.cols);if(this.tokenizers.indexOf(text.charAt(i)) >= 0)return;while(i+1<text.length && this.tokenizers.indexOf(text.charAt(i+1)) < 0)i++;this.setselpt(this.selpt[0], i);return;}
}
ESCodeEditor.advanceToWord = function()
{var j = this.selpt[0];var i = this.selpt[1];do { var contin = 0;var line = this.lines[j];var text = line.copyText(0,line.cols);while(" \t".indexOf(text.charAt(i)) >= 0 && i<text.length)i++;if(i==text.length && j+1 < this.lines.length) { j++; i=0; contin = 1; }
} while(contin);this.setselpt(j, i);}
ESCodeEditor.retreatToWord = function()
{var j = this.selpt[0];var i = this.selpt[1];do { var contin = 0;var line = this.lines[j];var text = line.copyText(0,line.cols);if(i>=text.length)i--;while(i>=0 && " \t".indexOf(text.charAt(i)) >= 0 && i<text.length)i--;if(i<0 && j > 0) { j--; i=this.lines[j].cols; contin = 1; }
} while(contin);this.setselpt(j, i);}
ESCodeEditor.enterCommandMode = function()
{if(this.selfrom)this.setselpt(this.selto[0], this.selto[1]);else if(this.selpt[1] > 0)this.moveCursor(false, 0, -1);this.flasher.stop();this.inspt.style.background='#a00';this.inspt.style.opacity='0.5';this.commandMode = true;}
ESCodeEditor.leaveCommandMode = function()
{this.inspt.style.background='black';this.inspt.style.opacity='1';this.flasher.start();this.commandMode = false;}
ESCodeEditor.typeNewLine = function()
{if(this.commandMode)return this.commandKey("\n", null);this.newLine();var prevtext = this.lines[this.selpt[0]-1].copyText(0, this.lines[this.selpt[0]-1].cols);for(var i=0;i<prevtext.length;i++)
{if(prevtext.charAt(i) == '\t')
this.insertChar('\t');else break;}
this.rehilight(this.lines[this.selpt[0]]);this.rehilight(this.lines[this.selpt[0]-1]);}
ESCodeEditor.type = function(ch, kk)
{if(this.commandMode)return this.commandKey(ch, kk);if(this.emulateVI && kk==27)return this.enterCommandMode();this.insertChar(ch);this.rehilight(this.lines[this.selpt[0]]);if(this.selpt[0]+1 < this.lines.length)
this.rehilight(this.lines[this.selpt[0]+1]);}
ESProgressBar = Subclass(ESControl);ESProgressBar.init = function(){ESProgressBar.superClass.init.call(this);if(!this.minValue)this.minValue = 0;if(!this.maxValue)this.maxValue = 1;if(!this.value)this.value = this.minValue;this.shaded = document.createElement("div");this.shaded.style.position = "absolute";this.shaded.style.left = "0px";this.shaded.style.top = "0px";this.shaded.style.bottom = "0px";this.shaded.style.background = "#44a";this.dom.style.border = '1px solid black';this.dom.appendChild(this.shaded);this.setValue(this.value);}
ESProgressBar.setValue = function(v){this.value = v;this.render();}
ESProgressBar.getValue = function(){return this.value;}
ESProgressBar.getBounds = function() {return {min: this.minValue, max: this.maxValue};}
ESProgressBar.render = function(){var p = (this.value - this.minValue) / (this.maxValue - this.minValue);var per = Math.round(p*100) + "%";this.shaded.style.width = per;}
ESUtil = Subclass(ESObject);ESUtil.isProduction= true;ESUtil.objDup = function(obj) {var returnme = new Object();for(var x in obj) {if(typeof(obj[x]) == "object")
returnme[x] = ESUtil.objDup(obj[x]);else
returnme[x] = obj[x];}
}
ESUtil.getObjAbsPos = function(dom) {var x = 0;var y = 0;for(var pres=dom; pres.offsetParent != null; pres = pres.offsetParent) {x += pres.offsetLeft;y += pres.offsetTop;if(pres != dom && pres.scrollTop)y -= pres.scrollTop;if(pres != dom && pres.scrollLeft)x -= pres.scrollLeft;}
return {x: x, y: y};}
ESUtil.getObjRelPos = function(dom) {var top = dom.offsetTop;var height= dom.offsetHeight;var left = dom.offsetLeft;var width = dom.offsetWidth;if(dom.offsetParent != null) {var parentWidth = dom.offsetParent.offsetWidth;var parentHeight = dom.offsetParent.offsetHeight;var bot = parentHeight-top-height;var right = parentWidth-left-width;}
return {top:top, bottom: bot, height:height, left:left, right:right, width:width};}
ESUtil.getEventCoords = function(ev) {if(!ev) 
ev = window.event;if(ev.pageX) 
return {x: ev.pageX, y:ev.pageY};else
return {x: ev.clientX, y:ev.clientY};}
ESUtil.getEventRelativeCoords = function(ev, dom) {var absEventCoords = ESUtil.getEventCoords(ev);var absObjCoords = ESUtil.getObjAbsPos(dom);return {x: absEventCoords.x - absObjCoords.x, y:absEventCoords.y-absObjCoords.y};}
ESUtil.cancelEventDefault=function(ev) {if(!ev)
ev = window.event;if(ev.preventDefault)
ev.preventDefault();else
ev.returnValue = false;}
ESUtil.closure = function (f) {var args = new Array();for (var i=1; i < arguments.length; i++)
args[i-1] = arguments[i];return function(){return f.apply(this, args)};}
ESUtil.closureWithThis = function (f, myThis) {var args = new Array();for (var i=2; i < arguments.length; i++)
args[i-2] = arguments[i];return function(){return f.apply(myThis, args)}
}
ESUtil.eventClosureWithThis = function(f, myThis) {var args = new Array();for (var i=2; i < arguments.length; i++)
args[i-2] = arguments[i];return function(ev){var newArgs = ([ev]).concat(args);return f.apply(myThis, newArgs)
}
}
ESUtil.closureArgCombWithThis = function(f, mythis) {var origArgs = [];for(var i=2; i < arguments.length; i++) 
origArgs[i-2] = arguments[i];return function() {var calledArgs = [];for(var i=0; i < arguments.length; i++) 
calledArgs[i] = arguments[i];var newArgs = origArgs.concat(calledArgs);return f.apply(mythis, newArgs);}
}
ESUtil.addEventListener = function(dom, eventName, f) {	
if(eventName.substring(0,2) != "on")
eventName = "on" + eventName;if(dom.addEventListener != null)
dom.addEventListener(eventName.substr(2), f, false);else if(dom.attachEvent != null)
{if(dom==document.body)dom=document;dom.attachEvent(eventName,f);}
}
ESUtil.removeEventListener = function(dom, eventName, f) {if(eventName.substring(0,2) != "on")
eventName = "on" + eventName;if(dom.removeEventListener)
dom.removeEventListener(eventName.substr(2), f, false);else if(dom.detachEvent)
{if(dom==document.body)dom=document;dom.detachEvent(eventName, f);}
}
ESUtil.HTMLSafeText = function(string) {string = string.replace(new RegExp("&", "g"), "&amp;");string = string.replace(new RegExp("<", "g"), "&lt;");string = string.replace(new RegExp(">", "g"),"&gt;");string = string.replace(new RegExp("\"", "g"),"&quot;");string = string.replace(new RegExp("'", "g"), "&apos;");return string;}
ESUtil.isIE = function() {return (navigator.appName == "Internet Explorer");}
ESUtil.escapeStringQuotes = function(str) {return str.replace(/'/g, "\\'").replace(/\\/g, "\\\\");}
ESUtil.urlEncodeString = function(string){return encodeURIComponent(string);}
ESUtil.urlDecodeString = function (string){return decodeURIComponent(string);}
ESUtil.parseBoolean = function(str, optDefault) {if(str != null && (str.toLowerCase() == "true" || str.toLowerCase() == "t"))
return true;else if(str != null && (str.toLowerCase() == "false" || str.toLowerCase() == "f"))
return false;else 
return (optDefault == null)? false : optDefault;}
ESUtil.log = function(str) {if(ESUtil.isProduction)
return;if(!ESUtil.logDiv) {ESUtil.logDiv = document.createElement("div");ESUtil.logDiv.style.position='absolute';ESUtil.logDiv.style.border='1px solid black';ESUtil.logDiv.style.background='white';ESUtil.logDiv.style.width='400px';ESUtil.logDiv.style.height='400px';ESUtil.logDiv.style.overflow = "auto";ESUtil.logDiv.style.right="0px";ESUtil.logDiv.style.bottom="0px";ESUtil.logDiv.style.fontSize = "11px";ESUtil.logDiv.style.zIndex = "999";var collapsed=false;ESUtil.logDiv.onclick = function() {if(!collapsed)
{ESUtil.logDiv.style.width='15px';ESUtil.logDiv.style.height='15px';}
else
{ESUtil.logDiv.style.width='400px';ESUtil.logDiv.style.height='400px';}
collapsed = !collapsed;}
document.body.appendChild(ESUtil.logDiv);}
ESUtil.logDiv.innerHTML += ESUtil.HTMLSafeText(str) + "<br>";}
ESUtil.objToString = function(obj) {if(!(obj instanceof Object))
return "\"" + obj + "\"";var str ="{";var count =0;for(var i in obj) {if(count != 0)
str +=", ";str += i + ":" + ESUtil.objToString(obj[i]);count ++;}
str += "}"
return str;}
ESUtil.structDefaultMerge = function(dest, defaults) {for(var i in defaults) {if(defaults[i] instanceof Object) {if(dest[i] == null)
dest[i] = {};ESUtil.structDefaultMerge(dest[i], defaults[i]);}
else if(dest[i] ==null)
dest[i] = defaults[i];}
}
ESRepeatingTimer = Subclass(ESObject);ESRepeatingTimer.init = function() {ESRepeatingTimer.superClass.init.call(this);this.timerId = null;this.running = false;this.callCount = 0;this.runPtr = null;}
ESRepeatingTimer.start = function() {if(this.running)return;this.runPtr = ESUtil.closureWithThis(this.run, this);this.running = true;this.timerId = window.setTimeout(this.runPtr, this.interval);}
ESRepeatingTimer.stop = function() {if(!this.running)return;this.running=false;window.clearTimeout(this.timerId);}
ESRepeatingTimer.run = function() {if(this.func && this.running) {this.callCount ++;this.func();this.timerId = window.setTimeout(this.runPtr, this.interval);}
}
ESRepeatingTimer.getCount = function(){return this.callCount;}
function ESGetSourceFile(url, flags) {if(flags == 'onlyonce')
{if(!ESGetSourceFile.alreadyLoaded)
ESGetSourceFile.alreadyLoaded = new Object();if(ESGetSourceFile.alreadyLoaded[url])
return ESGetSourceFile.alreadyLoaded[url].value;}
var req = Allocate(ESXMLHTTP);req.init();if(url.substring(0, 7) != "http://" && url.charAt(0) != '/' && ESGetSourceFile.basePath)
url = ESGetSourceFile.basePath + url;var script = req.getText(url);try {var result = eval(script);if(flags == 'onlyonce')
ESGetSourceFile.alreadyLoaded[url] = {value: result};return result;} catch(ex) {throw ("error evaluating script file (" + url + "): " + ex);}
}
function ESGetPackage(url) {var packagefunc = ESGetSourceFile(url);if(typeof(packagefunc) == "function")
return packagefunc();throw ("package script file (" + url + ") evaluated to a " + typeof(packagefunc) + " (not a function).");}
function ESPlacePackage(packURL, div) {var pkg = ESGetPackage(packURL);pkg.init();pkg.buildTree();if(!pkg.rep)throw "Package has no representative object.";div.appendChild(pkg.rep.getDOM());var closure = function(ev) {if(div.id=='mydiv')
{div.style.position='absolute';div.style.left='0px';div.style.top='0px';if(window.innerWidth != undefined)
{div.style.width=window.innerWidth+"px";div.style.height=window.innerHeight+"px";}
else
{div.style.width=document.documentElement.clientWidth+"px";div.style.height=document.documentElement.clientHeight+"px";}
}
pkg.rep.handleResize();};window.onresize = closure;pkg.setup();return pkg.rep;}
ESMailCenter = Subclass(ESObject);ESMailCenter.messagesTable = [];ESMailCenter.registerFunction=function(messageName, func) {if(ESMailCenter.messagesTable["messageName"] == null)
ESMailCenter.messagesTable["messageName"] = [];ESMailCenter.messagesTable["messageName"].push(func);}
ESMailCenter.sendMessage=function(messageName, data) {if(ESMailCenter.messagesTable["messageName"] == null)
return;var sendTo = ESMailCenter.messagesTable["messageName"];for(var i=0; i < sendTo.length; i++) 
sendTo[i](data);}
ESTabView = Subclass(ESMutableControl);ESTabView.defaultStyle = {buttonStyleType: "div", 
regButtonStyle: {backgroundColor: "white"},clickedButtonStyle: {backgroundColor: "#99CCFF"},subViewStyle: {}
};ESTabView.init = function() {ESTabView.superClass.init.call(this);if(this.value == null && this.values != null && this.values.length > 0)
this.value = this.values[0].name;if(this.tabStyle == null)
this.tabStyle = {};ESUtil.structDefaultMerge(this.tabStyle, ESTabView.defaultStyle);this.buttons = null;this.displayedView = null;this.viewArea = null;this.createView();}
ESTabView.setup = function() { 
ESTabView.superClass.setup.call(this);this.setValue(this.value);}
ESTabView.handleResize = function() {ESTabView.superClass.handleResize.call(this);if(this.displayedView != null)
this.displayedView.handleResize();}
ESTabView.createView = function() {var tabTable = document.createElement("table");tabTable.style.position = "absolute";tabTable.style.top = "0px";tabTable.style.height = "25px";tabTable.style.width = "100%"
tabTable.style.borderCollapse = "collapse";var tbody = document.createElement("tbody");tabTable.appendChild(tbody);var tabRow = document.createElement("tr");tbody.appendChild(tabRow);this.buttons = new Array();for(var i=0; i < this.values.length; i++ ){var tabName = this.values[i].name;var presButton = Allocate(ESButton);presButton.position = {top: "0px", bottom: "0px", right:"0px", left:"0px"};presButton.value = tabName;presButton.buttonStyle = this.tabStyle.buttonStyleType;presButton.action = ESUtil.closureWithThis(this.setClickedTab, this, i);presButton.init();presButton.setup();this.buttons[i] = presButton;var presTD = document.createElement("td");presTD.style.position="relative";var enclosing = document.createElement("div");enclosing.style.position = "relative";enclosing.style.top = "0px";enclosing.style.height = "25px";enclosing.style.left = "0px";enclosing.style.right = "0px";enclosing.appendChild(presButton.getDOM());presTD.appendChild(enclosing);tabRow.appendChild(presTD);}
this.dom.appendChild(tabTable);var viewArea = document.createElement("div");viewArea.style.padding = "0px";viewArea.style.margin = "0px";viewArea.style.position = "absolute";viewArea.style.top = "29px";viewArea.style.bottom = "0px";viewArea.style.right = "0px";viewArea.style.left = "0px";for(var x in this.tabStyle.subViewStyle)
viewArea.style[x] = this.tabStyle.subViewStyle[x];this.viewArea = viewArea;this.dom.appendChild(viewArea);}
ESTabView.setClickedTab = function(tabIdx) {if(this.values[tabIdx] != null) {if(this.viewArea.firstChild)
this.viewArea.removeChild(this.viewArea.firstChild);this.displayedView = this.values[tabIdx].view;this.viewArea.appendChild(this.displayedView.getDOM());this.values[tabIdx].view.handleResize();this.value = this.values[tabIdx].name;}
else
alert("Don't have a view for that tabIdx: '" + tabIdx + "'");this.selectButton(tabIdx);}
ESTabView.selectButton = function(tabIdx) {for(var i=0; i < this.buttons.length; i++) {if(i != tabIdx)
this.buttons[i].setStyle(this.tabStyle.regButtonStyle);else {this.buttons[i].setStyle(this.tabStyle.clickedButtonStyle);}
}
}
ESTabView.setValue = function(tabName) {var i=0;for(i=0; i < this.values.length; i++) {if(this.values[i].name == tabName)
break;}
if(i== this.values.length)
throw("Error: Cannot set selected tab to " + tabName + " because it is not in the tabView");this.setClickedTab(i);}
ESTabView.getValue = function() {return this.value;}
ESTabView.setStyle = function(tabStyle) {this.tabStyle = tabStyle;ESUtil.structDefaultMerge(this.tabStyle, ESTabView.defaultStyle);}
ESBarChart = Subclass(ESMutableControl);ESBarChart.init = function() {ESBarChart.superClass.init.call(this);if(this.scaleMin == null) {this.scaleMin = 0;}
if(this.scaleMax == null) {var max = this.values[0].height;for(var i=0; i < this.values.length; i++)
if(this.values[i].height > max)
max = this.values[i].height;this.scaleMax = max*1.01;}
if(this.barStyle == null)
this.barStyle = {backgroundColor:"3366AA", border:"1px solid black"};if(this.selBarStyle == null)
this.selBarStyle = {backgroundColor:"3366FF", border:"1px solid black"};if(this.selectMode == null)
this.selectMode = "over";this.barDivs = null;this.createChart();}
ESBarChart.createChart = function() {this.dom.style.borderBottom = "1px solid black";this.dom.style.borderLeft = "1px solid black";this.barDivs=  [];var numBars = this.values.length;var barWidth = (100.0 /numBars)
var barWidthStr = barWidth + "%";for(var i=0; i < numBars; i++) {var containerDiv = document.createElement("div");containerDiv.style.position="absolute";var height = ((this.values[i].height - this.scaleMin)/(this.scaleMax-this.scaleMin))*100+"%";containerDiv.style.height = height;containerDiv.style.bottom = "0px";containerDiv.style.left = i * barWidth + "%";containerDiv.style.right = (numBars-i-1)* barWidth + "%";var barDiv = document.createElement("div");this.barDivs[i] = barDiv;barDiv.style.position = "absolute";barDiv.style.top = "0px";barDiv.style.bottom = "0px";barDiv.style.left = "0px";barDiv.style.right = "0px";this.setBarStyle(i);var mouseOverStr = "";if(this.values[i].name)
mouseOverStr = this.values[i].name;mouseOverStr +=  "(" + this.values[i].height + ")";barDiv.title = mouseOverStr;if(this.selectMode == "over")
barDiv.onmouseover = ESUtil.closureWithThis(this.handleSelect, this, i);else if(this.selectMode == "click")
barDiv.onmousedown = ESUtil.closureWithThis(this.handleSelect, this ,i);containerDiv.appendChild(barDiv);this.dom.appendChild(containerDiv);}	
}
ESBarChart.setBarStyle=function(barIdx) {for(var x in this.barStyle) {if(x == "width" || x == "height" || x=="position" || x=="left" || x=="right" 
|| x=="top" || x=="bottom") 
continue;this.barDivs[barIdx].style[x] = this.barStyle[x];}
if(this.values[barIdx].color != null)
this.barDivs[barIdx].style.backgroundColor = this.values[barIdx].color;if(this.getSelectedIdx() == barIdx) {for(var x in this.selBarStyle) {if(x == "width" || x == "height" || x=="position" || x=="left" || x=="right" 
|| x=="top" || x=="bottom") 
continue;this.barDivs[barIdx].style[x] = this.selBarStyle[x];}
}
}
ESBarChart.handleSelect = function(barNum){this.setSelectedIdx(barNum);if(this.action)
this.action(this);}
ESBarChart.setSelectedIdx = function(barNum) {if(barNum <0 || barNum >= this.barDivs.length)
throw("Illegal bar div number: " + barNum);this.lastIdx = barNum;for(var i=0; i < this.values.length; i++)
this.setBarStyle(i);}
ESBarChart.getSelectedIdx = function() {return this.lastIdx;}
ESBarChart.getValue = function() {if(this.getSelectedIdx() == null)
return null;else
return this.values[this.getSelectedIdx()].name;}
ESBarChart.setValue = function(value) {for(var i=0; i < this.values.length; i++) {if(this.values[i].name == value) {this.setSelectedIdx(i);break;}
}
}
ESTreeView = Subclass(ESMutableControl);ESTreeView.init = function() {ESTreeView.superClass.init.call(this);if(this.hilightColor == null)
this.hilightColor = "#ccf";this.storedDom = null;this.storedValue = null;this.valueMap = new Array();this.dom.onmousedown = ESUtil.cancelEventDefault;this.dom.style.overflow = "auto";if(this.contents !=null) {this.setContents(this.contents);}
}
ESTreeView.setup = function() {ESTreeView.superClass.setup.call(this);if(this.value) {ESUtil.log("Trying to set value to: " + this.value);this.setValue(this.value);}
}
ESTreeView.findTree = function(value, doms) {if(!doms)doms = this.dom.childNodes;for(var i=0;i<doms.length;i++)
{if(doms[i].getAttribute && this.valueMap[doms[i].getAttribute("treeViewSeq")] == value)
return doms[i];var sub = this.findTree(value, doms[i].childNodes);if(sub)return sub;}
return null;}
ESTreeView.deleteNode = function(value, dom) {if(!dom)
dom = this.dom;var doms = dom.childNodes;for(var i=0; i < doms.length; i++) {if(doms[i].getAttribute && this.valueMap[doms[i].getAttribute("treeViewSeq")] == value) {{delete this.valueMap[doms[i].getAttribute("treeViewSeq")];dom.removeChild(doms[i]);}
} else
this.deleteNode(value, doms[i])
}
}
ESTreeView.setValue = function(value) {if(this.storedDom)
this.storedDom.firstChild.style.background = "none";this.storedDom = this.findTree(value);if(!this.storedDom)throw "Tried to set ESTreeView to a value not in the tree";this.storedDom.firstChild.style.backgroundColor = this.hilightColor;this.storedValue = value;}
ESTreeView.getValue = function() { 
return this.storedValue;}
ESTreeView.setCurrentNode = function(dom) {if(this.storedDom)
this.storedDom.firstChild.style.background = "none";this.storedDom = dom;this.storedDom.firstChild.style.backgroundColor = this.hilightColor;}
ESTreeView.setContents = function(contents) {var oldStored = this.storedDom;for(var i=0; contents != null && i < contents.length; i++) {this.storedDom = this.newItem(contents[i].value);this.setContents(contents[i].children);}
this.storedDom = oldStored;}
ESTreeView.getContents = function(startLoc) {if(startLoc == null)
startLoc = this.dom;var value = this.valueMap[startLoc.getAttribute("treeViewSeq")];var children = [];for(var i=0; i < startLoc.childNodes.length; i++) {var pres = startLoc.childNodes[i];if(pres.getAttribute) {var attrVal = pres.getAttribute("treeViewSeq");if(attrVal != null && attrVal != "")
children.push(this.getContents(pres));}
}
return {value: value, children: children};}
ESTreeView.clear = function() {this.dom.innerHTML = "";this.storedDom = null;}
ESTreeView.setupItemDiv = function(div, value, forXMLNode){div.appendChild(document.createTextNode(value));}
ESTreeView.newItem = function(value, forXMLNode){if(!this.storedDom)
var par = this.dom;else var par = this.storedDom;var dom = document.createElement("div");dom.style.cursor = "pointer";dom.style.marginLeft = "15px";dom.setAttribute("treeViewSeq", this.valueMap.length);this.valueMap[this.valueMap.length] = value;var text = document.createElement("div");text.className = "ESTreeViewItem";this.setupItemDiv(text, value, forXMLNode);dom.appendChild(text);par.appendChild(dom);var self = this;text.onclick = ESUtil.eventClosureWithThis(this.handleNodeClick, this, value);if(this.onDblClick !=null)
text.ondblclick = ESUtil.closureWithThis(this.handleNodeDblClick, this, value);return dom;}
ESTreeView.handleNodeClick = function(ev, value) {this.setValue(value);if(this.action)	
this.action(this);}
ESTreeView.handleNodeDblClick = function(value) {this.setValue(value);if(this.onDblClick != null)	
this.onDblClick(this);}
ESTreeView.populateFromXML = function(xml, valueXPath){var first = null;var self = this;if(this.storedDom)
this.storedDom.firstChild.style.background = "none";function loadItems(par, x) {var val = xml.xpathQuery(valueXPath, x);self.storedDom = par;var dom = self.newItem(val, x);if(!first)first = dom;for(var c = x.firstChild;c;c = c.nextSibling)
if(c.nodeType == 1)
loadItems(dom, c);}
for(var c = xml.xml.firstChild.firstChild;c;c = c.nextSibling)
if(c.nodeType == 1) loadItems(this.dom, c);if(first)this.setValue(first.firstChild.firstChild.nodeValue);}
ESTreeView.xmlTagForItem = function(dom){var open = "<item>";open += this.valueMap[dom.getAttribute("treeViewSeq")];return [open, "</item>"];}
ESTreeView.toXMLString = function(dom){if(!dom)
{var str = "";for(var c=this.dom.firstChild;c;c=c.nextSibling)
str += this.toXMLString(c);return str;}
var doms = dom.childNodes;if(!doms || !doms.length)return "";var tags = this.xmlTagForItem(dom);var str = tags[0];for(var i=1;i<doms.length;i++)
str += this.toXMLString(doms[i]);return str + tags[1];}
ESDynamicTreeView = Subclass(ESTreeView);ESDynamicTreeView.setupItemDiv = function(div, value) {if(value.opener)
{var img = document.createElement("img");img.src = 'http://sweaglesw.org/espresso/disclosure-closed.png';var self=this;function open(ev) {img.onclick = close;img.src = 'http://sweaglesw.org/espresso/disclosure-open.png';self.setCurrentNode(div.parentNode);value.opener(self);if(!ev)ev=window.event;ev.cancelBubble=true;if(ev.stopPropagation)ev.stopPropagation();ESUtil.cancelEventDefault(ev);}
function close(ev) {img.onclick = open;img.src = 'http://sweaglesw.org/espresso/disclosure-closed.png';while(div.parentNode.lastChild != div)
div.parentNode.removeChild(div.parentNode.lastChild);if(!ev)ev=window.event;ev.cancelBubble=true;if(ev.stopPropagation)ev.stopPropagation();ESUtil.cancelEventDefault(ev);}
img.onclick = open;div.appendChild(img);}
else div.style.paddingLeft='15px';div.appendChild(document.createTextNode(value.text));}
ESVectorArt = Subclass(ESView);ESVectorArt.init = function(){ESVectorArt.superClass.init.call(this);this.tx = this.ty = 0;this.mx = [1, 0];this.my = [0, 1];this.stack = [];}
ESVectorArt.translate = function(dx, dy){this.tx += dx;this.ty += dy;}
ESVectorArt.rotate = function(theta){var rx = [Math.cos(theta), -Math.sin(theta)];var ry = [Math.sin(theta), Math.cos(theta)];var newmx = [this.mx[0] * rx[0] + this.mx[1] * ry[0], this.mx[0] * rx[1] + this.mx[1] * ry[1]];var newmy = [this.my[0] * rx[0] + this.my[1] * ry[0], this.my[0] * rx[1] + this.my[1] * ry[1]];this.mx = newmx; this.my = newmy;}
ESVectorArt.rotateAround = function(cx, cy, theta){this.translate(-cx, -cy);this.rotate(theta);this.translate(cx * Math.cos(-theta) - cy * Math.sin(-theta), cx * Math.sin(-theta) + cy * Math.cos(-theta));}
ESVectorArt.scale = function(sx, sy){if(!sy)sy = sx;this.tx *= sx;this.ty *= sy;this.mx[0] *= sx; this.mx[1] *= sx;this.my[0] *= sy; this.my[1] *= sy;}
ESVectorArt.push = function(){ 
this.stack.push({tx: this.tx, ty: this.ty, mx: this.mx, my: this.my});}
ESVectorArt.pop = function(){if(!this.stack.length)throw "ESVectorArt stack underflow";var data = this.stack.pop();this.tx = data.tx;this.ty = data.ty;this.mx = data.mx;this.my = data.my;}
ESVectorArt.transformPt = function(x, y){x += this.tx;y += this.ty;return [this.mx[0]*x + this.mx[1]*y,this.my[0]*x + this.my[1]*y];}
ESVectorArt.line = function(x0, y0, x1, y1){var p0 = this.transformPt(x0, y0); x0 = p0[0]; y0 = p0[1];var p1 = this.transformPt(x1, y1); x1 = p1[0]; y1 = p1[1];var dx = x1-x0, dy = y1-y0;var dir = 0, tmp;if(dx==0 && dy==0)return null;if(dx<0) { dir = !dir; tmp=x0;x0=x1;x1=tmp; dx = -dx; }
if(dy<0) { dir = !dir; tmp=y0;y0=y1;y1=tmp; dy = -dy; }
var img = document.createElement("img");img.style.position = "absolute";img.style.left = Math.round(x0) + "px";img.style.top = Math.round(y0) + "px";if(dx > 0) img.style.width = Math.ceil(dx) + "px";else img.style.width = "1px";if(dy > 0)img.style.height = Math.ceil(dy) + "px";else img.style.height = "1px";var slope = dy / dx;dir = dir?"up":"down";if(slope <= 1)
{var rise = Math.ceil(16 * slope);if(rise==0)rise = 1;var url = "lines/16_" + rise + "_" + dir + ".gif";}
else
{var run = Math.ceil(16 / slope);if(run==0)run = 1;var url = "lines/" + run + "_16_" + dir + ".gif";}
img.src = "http://sweaglesw.org/espresso/images/" + url;this.dom.appendChild(img);return img;}
ESVectorArt.circle = function(x, y, r, segs){this.push();this.translate(x, y);var twopi = 3.1415926 * 2;var det = (this.mx[0] * this.my[1] - this.mx[1] * this.my[0]);if(det<0)det = -det;var circumf = twopi * r * Math.sqrt(det);if(!segs)segs = circumf / 16;var dt = twopi / segs;var imgs = new Array();for(var t=0;t < twopi;t += dt)
{if(t+dt >= twopi)dt = twopi - t + 0.01;var x0 = r * Math.cos(t), y0 = r * Math.sin(t);var x1 = r * Math.cos(t+dt), y1 = r * Math.sin(t+dt);imgs.push(this.line(x0,y0,x1,y1));}
this.pop();return imgs;}
ESVectorArt.clear = function(){this.dom.innerHTML="";this.tx = this.ty = 0;this.mx = [1, 0];this.my = [0, 1];this.stack = [];}
ESVectorArt.remove = function(what) {if(what.length) for(var i=0;i<what.length;i++)
this.remove(what[i]);else this.dom.removeChild(what);}
ESVectorArt.relativeCoords = function(ev){var rel = ESUtil.getEventRelativeCoords(ev, this.dom);var det = (this.mx[0] * this.my[1] - this.mx[1] * this.my[0]);var xinv = [(this.my[1] / det), -this.mx[1] / det];var yinv = [-(this.my[0] / det), this.mx[0] / det];return {x:rel.x * xinv[0] + rel.y * xinv[1], y:rel.x * yinv[0] + rel.y * yinv[1]};}
ESVectorArt.mouseDown = function(ev) {if(this.onmousedown) {ESUtil.cancelEventDefault(ev);this.onmousedown(this.relativeCoords(ev));}
}
ESVectorArt.mouseMoved = function(ev){if(this.onmousemove) {ESUtil.cancelEventDefault(ev);this.onmousemove(this.relativeCoords(ev));}
}
ESVectorArt.mouseUp = function(ev){if(this.onmouseup) {ESUtil.cancelEventDefault(ev);this.onmouseup(this.relativeCoords(ev));}
}
ESDraggableView = Subclass(ESControl);ESDraggableView.init = function() {ESDraggableView.superClass.init.call(this);this.dom.style.cursor = "move";this.dom.onmousedown=ESUtil.eventClosureWithThis(this.handleMouseDown, this);if(this.onDoubleClick)
this.dom.ondblclick = ESUtil.eventClosureWithThis(this.handleDBLClick, this);this.lastCoords = null;}
ESDraggableView.handleMouseDown = function(ev) {this.lastCoords = ESUtil.getEventCoords(ev);this.dom.onmousemove = ESUtil.eventClosureWithThis(this.handleMouseMove, this);document.onmouseup = ESUtil.eventClosureWithThis(this.handleMouseUp, this);ESUtil.cancelEventDefault(ev);}
ESDraggableView.handleMouseMove = function(ev) {var presCoords = ESUtil.getEventCoords(ev);var moveX = presCoords.x - this.lastCoords.x;var moveY = presCoords.y - this.lastCoords.y;this.lastCoords = presCoords;this.scrollBy(moveX, moveY);ESUtil.cancelEventDefault(ev);if(this.action)
this.action(this);}
ESDraggableView.handleMouseUp = function(ev) {this.dom.onmousemove = null;document.onmouseup=null;}
ESDraggableView.handleDBLClick = function(ev) {this.daEvent = ev;if(this.onDoubleClick) 
this.onDoubleClick();}
ESDraggableView.scrollBy = function(dx, dy) {} 
ESDraggableContainer = Subclass(ESDraggableView);ESDraggableContainer.init = function() {ESDraggableContainer.superClass.init.call(this);if(this.startX == null)
this.startX = 0;if(this.startY == null)
this.startY = 0;this.presPos = {x:this.startX, y:this.startY};this.containerDiv = null;}
ESDraggableContainer.setup = function() {ESDraggableContainer.superClass.setup.call(this);this.createSubView();}
ESDraggableContainer.createSubView = function() {this.dom.style.overflow = "hidden";if(!this.srcObj)
return;var containerDiv = this.srcObj.getDOM();containerDiv.style.position = "absolute";containerDiv.style.top = "0px";containerDiv.style.left = "0px";containerDiv.style.display = "block";containerDiv.style.padding="0px";containerDiv.style.margin ="0px";containerDiv.style.border = "0px";this.containerDiv = containerDiv;this.dom.appendChild(containerDiv);}
ESDraggableContainer.scrollBy = function(dx, dy) {this.setCoords(this.presPos.x - dx, this.presPos.y - dy);}
ESDraggableContainer.refreshView = function() {this.containerDiv.style.top = -1*this.presPos.y + "px";this.containerDiv.style.left = -1*this.presPos.x + "px";}
ESDraggableContainer.setCoords = function(x,y) {var srcCoords = this.srcObj.getHTMLPosition();var myCoords = this.getHTMLPosition();x=Math.max(0, x);y=Math.max(0, y);x=Math.min(x, srcCoords.width-myCoords.width);y=Math.min(y, srcCoords.height-myCoords.height);this.presPos.x = x;this.presPos.y = y;this.refreshView();}
ESDraggableContainer.getCoords = function() {return ESUtil.objDup(this.presPos);}
ESDraggableContainer.setValue = function(val) {this.setCoords(val.x, val.y);}
ESDraggableImage = Subclass(ESDraggableContainer);ESDraggableImage.init = function () {var img = Allocate(ESImageView);img.position = {left:0, right:0, top:0, bottom:0};if(this.value)
img.value = this.value;img.loadHandler = ESUtil.closureWithThis(this.handleImgLoad, this);img.init();img.setup();this.srcObj = img;ESDraggableImage.superClass.init.call(this);this.hasLoaded = false;}
ESDraggableImage.setValue = function(value) {this.srcObj.setValue(value);}
ESDraggableImage.handleImgLoad = function() {var size = this.srcObj.getImgSize();ESUtil.log("Got the image load, setting size to: " + size.width + ", " + size.height);this.srcObj.resize({width:size.width, height:size.height});this.refreshView();if(this.loadHandler != null)
this.loadHandler();}
ESDraggableTable = Subclass(ESDraggableContainer);ESDraggableTable.init = function() {this.srcObj = Allocate(ESTable);this.srcObj.init();this.srcObj.setup();}
ESDraggableTable.getTable = function() {return this.srcObj;}
ESDraggableTable.setTable = function(table) {this.srcObj = table;this.refreshView();}
ESOnDemandImage = Subclass(ESDraggableView);ESOnDemandImage.init = function() {	
ESOnDemandImage.superClass.init.call(this);this.images = null;this.viewImgX = this.viewImgY = null;this.ULTileNumX = this.ULTileNumY = null;if(this.startX == null)
this.startX = 0;if(this.startY == null)
this.startY = 0;this.fullWidth = parseInt(this.fullWidth);this.fullHeight = parseInt(this.fullHeight);this.segWidth = parseInt(this.segWidth);this.segHeight = parseInt(this.segHeight);this.viewXTiles = parseInt(this.viewXTiles);this.viewYTiles =  parseInt(this.viewYTiles);this.startX = parseInt(this.startX);this.startY = parseInt(this.startY);if(this.segWidth <= 0 || this.segHeight <= 0) 
throw("Illegal segWidth or segHeight");this.createView();}
ESOnDemandImage.setup = function() {ESOnDemandImage.superClass.setup.call(this);}
ESOnDemandImage.handleResize = function() {ESOnDemandImage.superClass.handleResize.call(this);this.scrollBy(0,0);}
ESOnDemandImage.createView = function() { 
var ulImgX, ulImgY;var borders = this.computeBorders();var approxViewX = this.startX - borders.x;var approxViewY = this.startY - borders.y;var ULTileNumX = Math.floor(approxViewX / this.segWidth);var ULTileNumY = Math.floor(approxViewY / this.segWidth);this.createImgs(ULTileNumX, ULTileNumY);var ULTileScreenX = -1*(approxViewX - ULTileNumX*this.segWidth)-borders.x;var ULTileScreenY = -1*(approxViewY - ULTileNumY*this.segHeight)-borders.y;this.setViewScreenCoords(ULTileScreenX, ULTileScreenY);this.viewImgX = approxViewX;this.viewImgY = approxViewY;this.ULTileNumX = ULTileNumX;this.ULTileNumY = ULTileNumY;}
ESOnDemandImage.setValue = function(value) {for(var x in value)
this[x] = value[x];this.createView();}
ESOnDemandImage.setCoords = function(x, y) {this.startX = x;this.startY = y;this.createView();this.scrollBy(0,0);}
ESOnDemandImage.getCoords = function() {var border = this.computeBorders();return {x: this.viewImgX + border.x, y: this.viewImgY + border.y};}
ESOnDemandImage.setCenterCoords = function(x,y) {var myPos=this.getHTMLPosition();this.setCoords(x-myPos.width/2, y-myPos.height/2);}
ESOnDemandImage.getCenterCoords = function() {var myPos = this.getHTMLPosition();var coords = this.getCoords();coords.x += myPos.width/2;coords.y += myPos.height/2;return coords;}
ESOnDemandImage.getLRCoords = function() {var coords = this.getCoords();var myPos = this.getHTMLPosition();return {x:coords.x + myPos.width, y: coords.y + myPos.height};}
ESOnDemandImage.setLRCoords = function(x, y) {var myPos = this.getHTMLPosition();this.setCoords(x-myPos.width, y-myPos.height);}
ESOnDemandImage.getImageProperties = function() {var returnme = {fullWidth: this.fullWidth, fullHeight: this.fullHeight, segWidth: this.segWidth, segHeight: this.segHeight, viewXTiles: this.viewXTiles};}
ESOnDemandImage.scrollBy = function(dx, dy) {this.viewImgX -= dx;this.viewImgY -= dy;var border = this.computeBorders();var myPos = this.getHTMLPosition();this.viewImgX = Math.min(this.fullWidth-myPos.width-border.x, this.viewImgX);this.viewImgX = Math.max(-1*border.x, this.viewImgX);this.viewImgY = Math.min(this.fullHeight-myPos.height-border.y, this.viewImgY);this.viewImgY = Math.max(-1*border.y, this.viewImgY);var wantViewULX = Math.floor(this.viewImgX / this.segWidth);var wantViewULY = Math.floor(this.viewImgY / this.segHeight);while(wantViewULX < this.ULTileNumX) { 
this.shiftRight();} 
while(wantViewULX > this.ULTileNumX) { 
this.shiftLeft();}
while(wantViewULY < this.ULTileNumY) {this.shiftDown()
}
while(wantViewULY > this.ULTileNumY) {this.shiftUp();}
var borders = this.computeBorders();var ULTileScreenX = -1*(this.viewImgX - wantViewULX*this.segWidth)-borders.x;var ULTileScreenY = -1*(this.viewImgY - wantViewULY*this.segHeight)-borders.y;this.setViewScreenCoords(ULTileScreenX, ULTileScreenY);}
ESOnDemandImage.computeBorders = function() {var myPos = this.getHTMLPosition();var viewWidth = this.segWidth * this.viewXTiles;var viewHeight = this.segHeight * this.viewYTiles;var borderX = (viewWidth - myPos.width)/2;var borderY = (viewHeight - myPos.height)/2;return {x: borderX, y: borderY};}
ESOnDemandImage.setViewScreenCoords = function(x, y) { 
x = Math.round(x);y = Math.round(y);for(var i=0; i < this.images.length; i++ ) {for(var j=0; j < this.images[i].length; j++) {this.images[i][j].style.left = x + i*this.segWidth + "px";this.images[i][j].style.top = y + j*this.segHeight + "px";}
}
}
ESOnDemandImage.createImgs = function(x, y) {this.images = new Array();while(this.dom.firstChild != null)
this.dom.removeChild(this.dom.firstChild);for(var i=0; i < this.viewXTiles; i ++){this.images[i] = new Array();for(var j=0; j < this.viewYTiles; j++) {var presImg = this.createImg(i+x,j+y);this.images[i][j] = presImg;this.dom.appendChild(presImg);}
}
}
ESOnDemandImage.createImg = function(picNumX, picNumY) {if(picNumX != picNumX)
throw("Got a NaN");var presImg = document.createElement("img");var maxX = Math.ceil(this.fullWidth / this.segWidth);var maxY = Math.ceil(this.fullHeight / this.segHeight);if(picNumX >= maxX || picNumY >= maxY || picNumX < 0 || picNumY < 0)  {presImg.src = this.value + "overflowImg.jpg";}
else
presImg.src = this.value + picNumX + "_" + picNumY + ".jpg";presImg.style.position = "absolute";return presImg;}
ESOnDemandImage.shiftRight = function() { 
var newX = this.ULTileNumX - 1;var oldColumn = this.images.pop();var newColumn = [];for(var i=0; i < oldColumn.length; i++) {this.dom.removeChild(oldColumn[i]);var newImg = this.createImg(newX, this.ULTileNumY+i);newColumn[i] = newImg;this.dom.appendChild(newImg);}
this.images.splice(0,0, newColumn);this.ULTileNumX --;}
ESOnDemandImage.shiftLeft = function() {var newX = this.ULTileNumX + this.viewXTiles;var oldColumn = this.images[0];this.images.splice(0,1);var newColumn = [];for(var i=0; i < oldColumn.length; i++) {this.dom.removeChild(oldColumn[i]);var newImg = this.createImg(newX, this.ULTileNumY+i);newColumn[i] = newImg;this.dom.appendChild(newImg);}
this.images.push(newColumn);this.ULTileNumX ++;}
ESOnDemandImage.shiftDown = function() {var newY = this.ULTileNumY - 1;for(var i=0; i < this.images.length; i++){this.dom.removeChild(this.images[i].pop());var newImg = this.createImg(this.ULTileNumX+i, newY);this.dom.appendChild(newImg);this.images[i].splice(0,0,newImg);}
this.ULTileNumY --;}
ESOnDemandImage.shiftUp = function() {var newY = this.ULTileNumY + this.viewYTiles;for(var i=0; i < this.images.length; i++) {this.dom.removeChild(this.images[i][0]);this.images[i].splice(0,1);var newImg = this.createImg(this.ULTileNumX+i, newY);this.dom.appendChild(newImg);this.images[i].push(newImg);}
this.ULTileNumY ++;}
ESOnDemandImage.isLoading = function() {for(var i=0; i < this.images.length; i++ ){for(var j=0; j < this.images.length; j++) {if(images[i][j].complete == false)
return true;}
}
return false;}
ESDialogs = Subclass(ESObject);ESDialogs.alert = function(message, callback) {ESDialogs.createShield();var dialog = Allocate(ESAlertDialog);dialog.message = message;dialog.action = ESDialogs.createCallback(callback);dialog.position = {left:250, width: 300, top: 10, height: 200};dialog.backgroundColor = "#FFCCCC";dialog.borderStyle = "inset";dialog.borderColor = "black";dialog.init();dialog.buildTree();dialog.setup();document.body.appendChild(dialog.getDOM());}
ESDialogs.confirm = function(message, callback) {ESDialogs.createShield();var dialog = Allocate(ESConfirmDialog);dialog.message = message;dialog.position = {left:250, width: 300, top: 10, height: 200};dialog.action = ESDialogs.createCallback(callback);dialog.backgroundColor = "#FFCCCC";dialog.borderStyle = "inset";dialog.borderColor = "black";dialog.init();dialog.buildTree();document.body.appendChild(dialog.getDOM());dialog.setup();}
ESDialogs.prompt = function(message, defaultText, callback) {ESDialogs.createShield();var dialog = Allocate(ESPromptDialog);dialog.value = defaultText;dialog.message = message;dialog.position = {left:250, width: 300, top: 10, height: 200};dialog.action = ESDialogs.createCallback(callback);dialog.backgroundColor = "#FFCCCC";dialog.borderStyle = "inset";dialog.borderColor = "black";dialog.init();dialog.buildTree();document.body.appendChild(dialog.getDOM());dialog.setup();}
ESDialogs.createShield = function(zIndex) {if(!ESDialogs.shield) { 
ESDialogs.shield = document.createElement("div");ESDialogs.shield.style.position = "absolute";ESDialogs.shield.style.left = "0px";ESDialogs.shield.style.right = "0px";ESDialogs.shield.style.top = "0px";ESDialogs.shield.style.bottom = "0px";ESDialogs.shield.style.backgroundColor = "black";ESDialogs.shield.style.opacity = ".3";}
ESDialogs.shield.style.filter = "alpha(opacity=30)";var shield = ESDialogs.shield;if(zIndex == null && zIndex != "0")
zIndex = 1;shield.style.zIndex = zIndex;document.body.appendChild(ESDialogs.shield);}
ESDialogs.closeShield = function() {document.body.removeChild(ESDialogs.shield);}
ESDialogs.createCallback = function(callback) {return function() {ESDialogs.closeShield();var newArgs = [];for(var i=1; i < arguments.length; i++)
newArgs[i-1] = arguments[i];if(callback)
callback.apply(this, newArgs);}
}
ESDialog = Subclass(ESControl);ESDialog.init = function() {ESDialog.superClass.init.call(this);if(this.buttonStyle == null)	
this.buttonStyle = "div";this.open = (this.parentCanvas != null);}
ESDialog.setup = function() {ESDialog.superClass.setup.call(this);this.dom.style.zIndex = "1";}
ESDialog.handleClose = function() {this.dom.parentNode.removeChild(this.dom);this.open = false;if(this.runningModal)
ESDialogs.closeShield();this.runningModal = false;}
ESDialog.isOpen = function() {return this.open;}
ESDialog.runModal = function() {if(this.getDOM().parentNode != null && this.getDOM().parentElement != null) 
return;ESDialogs.createShield();this.dom.zIndex="10";document.body.appendChild(this.getDOM());this.runningModal = true;this.handleResize();}
ESAlertDialog = Subclass(ESDialog);ESAlertDialog.init = function() {ESAlertDialog.superClass.init.call(this);this.displayDiv = document.createElement("div");this.displayDiv.style.position = "absolute";this.displayDiv.style.bottom = "50px";this.displayDiv.style.left = "5px";this.displayDiv.style.right = "5px";this.displayDiv.style.top = "0px";this.displayDiv.style.overflow = "hidden";if(this.titleText == null)
this.titleText = "alert";if(this.message ==null)
this.message = "";this.displayDiv.innerHTML = "<h2>"+ESUtil.HTMLSafeText(this.titleText)+"</h2><div style='position: absolute; top: 50px; left:10px; right: 10px; bottom: 0px; border: 1px solid black; overflow:auto;'>" + ESUtil.HTMLSafeText(this.message) + "</div>";this.dom.appendChild(this.displayDiv);var okButton = Allocate(ESButton);okButton.value = "Ok";okButton.position = {height:25, right:100, left:100, bottom:10};okButton.buttonStyle= this.buttonStyle;okButton.parentCanvas = this;okButton.action = ESUtil.closureWithThis(this.handleOk, this);okButton.init();this.okButton = okButton;} 
ESAlertDialog.setup = function() {ESAlertDialog.superClass.setup.call(this);this.okButton.buildTree();this.okButton.setup();}
ESAlertDialog.handleOk = function() {if(this.action)
this.action(this);this.handleClose();}
ESConfirmDialog = Subclass(ESDialog);ESConfirmDialog.init = function() {ESConfirmDialog.superClass.init.call(this);this.value = null;this.displayDiv = document.createElement("div");this.displayDiv.style.position = "absolute";this.displayDiv.style.bottom = "50px";this.displayDiv.style.left = "5px";this.displayDiv.style.right = "5px";this.displayDiv.style.top = "0px";this.displayDiv.style.overflow = "hidden";this.displayDiv.innerHTML = "<h2>Confirm:</h2><div style='position:absolute; top:50px; left:10px; right:10px; bottom:5px; border: 1px solid black; overflow:auto;'>" + ESUtil.HTMLSafeText(this.message)  + "</div>";this.dom.appendChild(this.displayDiv);var yesButton = Allocate(ESButton);yesButton.value = "Yes";yesButton.position = {height: 25, right:150, width: 90, bottom:10};yesButton.buttonStyle = this.buttonStyle;yesButton.parentCanvas = this;yesButton.action = ESUtil.closureWithThis(this.handleYesClick, this);yesButton.init();this.yesButton = yesButton;var noButton = Allocate(ESButton);noButton.value = "No";noButton.position = {height: 25, right:50, width: 90, bottom:10};noButton.buttonStyle = this.buttonStyle;noButton.parentCanvas = this;noButton.action = ESUtil.closureWithThis(this.handleNoClick, this);noButton.init();this.noButton = noButton;}
ESConfirmDialog.setup = function() {ESConfirmDialog.superClass.setup.call(this);this.yesButton.buildTree();this.yesButton.setup();this.noButton.buildTree();this.noButton.setup();}
ESConfirmDialog.handleYesClick = function() {this.value = true;if(this.action)
this.action(this, true);this.handleClose();}
ESConfirmDialog.handleNoClick = function() {this.value = false;if(this.action)
this.action(this, false);this.handleClose();}
ESConfirmDialog.getValue = function() {return this.value;}
ESPromptDialog = Subclass(ESDialog);ESPromptDialog.init = function() {ESPromptDialog.superClass.init.call(this);this.displayDiv = document.createElement("div");this.displayDiv.style.position = "absolute";this.displayDiv.style.bottom = "100px";this.displayDiv.style.left = "5px";this.displayDiv.style.right = "5px";this.displayDiv.style.top = "0px";this.displayDiv.style.overflow = "hidden";this.displayDiv.innerHTML = "<h2>Prompt:</h2><div style='position:absolute; top:50px; left:10px; right:10px; bottom:0px; border: 1px solid black; overflow:auto;'>" + ESUtil.HTMLSafeText(this.message)  + "</div>";this.dom.appendChild(this.displayDiv);this.promptTextArea = document.createElement("input");this.promptTextArea.type = "text";this.promptTextArea.style.position = "absolute";this.promptTextArea.style.left = "15px";this.promptTextArea.style.right = "15px";this.promptTextArea.style.bottom = "60px";this.promptTextArea.style.height = "30px";this.promptTextArea.value = this.value;this.value = null;this.dom.appendChild(this.promptTextArea);var okButton = Allocate(ESButton);okButton.value = "Ok";okButton.position = {height: 25, right:150, width: 90, bottom:10};okButton.buttonStyle = this.buttonStyle;okButton.parentCanvas = this;okButton.action = ESUtil.closureWithThis(this.handleOkClick, this);okButton.init();this.okButton = okButton;var cancelButton = Allocate(ESButton);cancelButton.value = "Cancel";cancelButton.position = {height: 25, right:50, width: 90, bottom:10};cancelButton.buttonStyle = this.buttonStyle;cancelButton.parentCanvas = this;cancelButton.action = ESUtil.closureWithThis(this.handleCancelClick, this);cancelButton.init();this.cancelButton = cancelButton;}
ESPromptDialog.setup = function() {ESPromptDialog.superClass.setup.call(this);this.okButton.buildTree();this.okButton.setup();this.cancelButton.buildTree();this.cancelButton.setup();if(this.promptTextArea.focus)
this.promptTextArea.focus();}
ESPromptDialog.handleOkClick = function() {this.value = this.promptTextArea.value;if(this.action)
this.action(this, this.value);this.handleClose();}
ESPromptDialog.handleCancelClick = function() {this.value = null;if(this.action)
this.action(this, null);this.handleClose();}
ESPromptDialog.getValue = function() {return this.value;}
ESFormDialog = Subclass(ESDialog);ESFormDialog.init = function() {ESFormDialog.superClass.init.call(this);this.runningModal = false;if(this.heading == null)
this.heading = "";this.headingView = Allocate(ESLabel);this.headingView.value = this.heading;this.headingView.position = {left:5, right:5, top:5, height:30};this.headingView.align = "center";this.headingView.parentCanvas = this;this.headingView.init();this.formView = Allocate(ESFormInput);this.formView.fields= this.fields;this.formView.position = {top: 40, left: 5, right:5, bottom: 40};this.formView.parentCanvas = this;if(this.labelWidth)
this.formView.labelWidth = this.labelWidth;this.formView.init();this.buttonsView = Allocate(ESView);this.buttonsView.position = {height: 40, bottom:0,  width: 220, horzCenter:"true"};this.buttonsView.parentCanvas = this;this.buttonsView.init();this.okButton = Allocate(ESButton);this.okButton.value = "Ok";this.okButton.action = ESUtil.closureWithThis(this.handleOk, this);this.okButton.position = {left: 5, width: 100, top:0, height: 25};this.okButton.parentCanvas = this.buttonsView;this.okButton.init();this.cancelButton = Allocate(ESButton);this.cancelButton.value = "Cancel";this.cancelButton.action = ESUtil.closureWithThis(this.handleClose, this);this.cancelButton.parentCanvas = this.buttonsView;this.cancelButton.position = {right: 5, width: 100, top:0, height: 25};this.cancelButton.init();}
ESFormDialog.setup = function() {ESFormDialog.superClass.setup.call(this);this.headingView.buildTree();this.headingView.setup();this.formView.buildTree();this.formView.setup();this.buttonsView.buildTree();this.buttonsView.setup();this.okButton.buildTree();this.okButton.setup();this.cancelButton.buildTree();this.cancelButton.setup();}
ESFormDialog.getValues = function() {return this.formView.getValues();}
ESFormDialog.setValues = function(values) {for(var i=0; i < values.length; i++)
this.formView.setValues(values);}
ESFormDialog.handleOk = function() {if(this.action)
this.action();if(this.runningModal)
ESDialogs.closeShield();this.runningModal = false;this.handleClose();}
ESFormDialog.runModal = function() {ESFormDialog.superClass.runModal.call(this);this.formView.focus();}
ESFormDialog.focus = function() {this.formView.focus();}
ESFormDialog.select = function() {this.formView.select();}
ESDragDrop = Subclass(ESObject);ESDragDrop.launchDrag = function(ev, type, relativeElement, dommaker, finalizer, minDist, eschain)
{while(eschain.parentCanvas)eschain = eschain.parentCanvas;ESUtil.cancelEventDefault(ev);var c = ESUtil.getEventRelativeCoords(ev, document.body);var trc = ESUtil.getEventRelativeCoords(ev, relativeElement);var dragRecord = {start: c,trc: trc,type: type,minDist: minDist,dommaker: dommaker,finalizer: finalizer,started: false,chain: eschain,target: null};var mover = function(ev) { ESDragDrop._mouseMove(ev, dragRecord); }
var ender = function() {ESUtil.removeEventListener(document.body, "mousemove", mover);ESUtil.removeEventListener(document.body, "mouseup", ender);if(dragRecord.started)
document.body.removeChild(dragRecord.div);if(dragRecord.target)
{var data = dragRecord.finalizer();if(data) dragRecord.target.acceptDrag(type, data);dragRecord.target.dragLeft(c);}
}
ESUtil.addEventListener(document.body, "mousemove", mover);ESUtil.addEventListener(document.body, "mouseup", ender);}
ESDragDrop._mouseMove = function(ev, dr)
{ESUtil.cancelEventDefault(ev);var c = ESUtil.getEventRelativeCoords(ev, document.body);if(!dr.started) {if(Math.abs(c.x - dr.start.x) + Math.abs(c.y - dr.start.y) < dr.minDist)return;var div = dr.dommaker();div.style.position='absolute';div.style.opacity = '0.5';div.style.background = 'white';div.style.zIndex = 9;dr.div = div;document.body.appendChild(div);dr.started = true;}
dr.div.style.left = (c.x - dr.trc.x) + 'px';dr.div.style.top = (c.y - dr.trc.y) + 'px';var view = dr.chain, target = null;if(view.pointInView(c))
{while(view)
{if(view.canAcceptDrag && view.canAcceptDrag(dr.type))
target = view;if(view.findSubDrag)
view = view.findSubDrag(c);else if(view.findSubView)
view = view.findSubView(c);}
}
if(target != dr.target)
{if(dr.target)dr.target.dragLeft(c);dr.target = target;if(dr.target)dr.target.dragEntered(c);}
}
ESStdAppView = Subclass(ESView);ESStdAppView.init = function() {ESStdAppView.superClass.init.call(this);if(this.sidebarWidth != null)
this.sidebarWidth = parseInt(this.sidebarWidth);else
this.sidebarWidth = 200;this.selectedMainView = null;this.selectedSideView = null;if(this.selectedIndex == null)
this.selectedIndex = 0;this.createView();}
ESStdAppView.setup = function() {ESStdAppView.superClass.setup.call(this);this.setupView();if(this.value)
this.setValue(this.value);if(this.selectedIndex != null)
this.setIndex(this.selectedIndex);this.doReadOpening();}
ESStdAppView.doReadOpening = function() {var myThis = this;var readCB = function(file) {myThis.onOpen(file.data, file.type);}
ESFS.readOpening(readCB, null);}
ESStdAppView.createView = function() {this.buttonSelHeight = this.modes.length * 27+10;this.fileButtonViewHeight = 75;var modeNames = [];for(var i=0; i < this.modes.length; i++)
modeNames[i]  =this.modes[i].name;this.sidebarView = Allocate(ESView);this.sidebarView.position = {top:10, left: 10, bottom:10, width:this.sidebarWidth};this.sidebarView.parentCanvas = this;this.sidebarView.init();this.daButtonSelector = Allocate(ESButtonSelector);this.daButtonSelector.position = {top:5, left:5, right:5, height: this.buttonSelHeight};this.daButtonSelector.parentCanvas = this.sidebarView;this.daButtonSelector.borderStyle = "groove";this.daButtonSelector.borderWidth = 2;this.daButtonSelector.values = modeNames;this.daButtonSelector.action = ESUtil.closureWithThis(this.handleClick, this);this.daButtonSelector.init();if(this.value)
this.daButtonSelector.value = this.value;else if(this.selectedIndex)
this.daButtonSelector.selectedIndex = this.selectedIndex;this.fileButtonsView = Allocate(ESView);this.fileButtonsView.position = {top:10+this.buttonSelHeight, left:5, right:5, height:this.fileButtonViewHeight};this.fileButtonsView.borderStyle = "groove";this.fileButtonsView.borderWidth =2;this.fileButtonsView.parentCanvas = this.sidebarView;this.fileButtonsView.init();var buttonWidth = (this.sidebarWidth - 40)/2;this.newBtn = Allocate(ESButton);this.newBtn.position = {top:5, left:5, width:buttonWidth, height:25};this.newBtn.parentCanvas = this.fileButtonsView;this.newBtn.value = "New";this.newBtn.action = ESUtil.closureWithThis(this.handleNewClick, this);this.newBtn.init();this.openBtn = Allocate(ESButton);this.openBtn.position = {top:5, right:5, width:buttonWidth, height:25};this.openBtn.parentCanvas = this.fileButtonsView;this.openBtn.value = "Open";this.openBtn.action = ESUtil.closureWithThis(this.handleOpenClick, this);this.openBtn.init();this.saveBtn = Allocate(ESButton);this.saveBtn.position = {bottom:5, left:5, width:buttonWidth, height:25};this.saveBtn.parentCanvas = this.fileButtonsView;this.saveBtn.value = "Save";this.saveBtn.action = ESUtil.closureWithThis(this.handleSaveClick, this);this.saveBtn.init();this.saveAsBtn = Allocate(ESButton);this.saveAsBtn.position = {bottom:5, right:5, width:buttonWidth, height:25};this.saveAsBtn.parentCanvas = this.fileButtonsView;this.saveAsBtn.value = "Save As";this.saveAsBtn.action = ESUtil.closureWithThis(this.handleSaveAsClick, this);this.saveAsBtn.init();this.lowerSideView = Allocate(ESOverflowableView);this.lowerSideView.position = {top:this.buttonSelHeight+this.fileButtonViewHeight+15, left:5, right:5, bottom:5};this.lowerSideView.parentCanvas = this.sidebarView;this.lowerSideView.borderStyle = "groove";this.lowerSideView.borderWidth = "2px";if(this.sideBGColor != null)
this.lowerSideView.backgroundColor = this.sideBGColor;this.lowerSideView.init();this.mainView = Allocate(ESView);this.mainView.position = {top:15, left:this.sidebarWidth+5, right:15, bottom:15};this.mainView.parentCanvas = this;this.mainView.borderStyle = "groove";this.mainView.borderWidth ="2px";this.mainView.overflow = "auto";if(this.mainBGColor != null)
this.mainView.backgroundColor = this.mainBGColor;this.mainView.init();}
ESStdAppView.setupView = function() {this.sidebarView.buildTree();this.sidebarView.setup();this.daButtonSelector.buildTree();this.daButtonSelector.setup();this.fileButtonsView.buildTree();this.fileButtonsView.setup();this.newBtn.buildTree();this.newBtn.setup();this.openBtn.buildTree();this.openBtn.setup();this.saveBtn.buildTree();this.saveBtn.setup();this.saveAsBtn.buildTree();this.saveAsBtn.setup();this.lowerSideView.buildTree();this.lowerSideView.setup();this.mainView.buildTree();this.mainView.setup();}
ESStdAppView.setValue = function(value) {for(var i=0; i < this.modes.length; i++)
if(this.modes[i].name == value)
this.setIndex(i);}
ESStdAppView.getValue = function() {return this.modes[this.getIndex].name;}
ESStdAppView.setIndex = function(idx) {this.daButtonSelector.setIndex(idx);this.handleClick();}
ESStdAppView.getIndex = function() {return this.daButtonSelector.getIndex();}
ESStdAppView.handleClick = function() {var idx = this.getIndex();if(this.selectedSideView)
this.lowerSideView.removeSubView(this.selectedSideView);if(this.selectedMainView)
this.mainView.removeSubView(this.selectedMainView);this.selectedSideView = this.modes[idx].sidebarView;this.selectedMainView = this.modes[idx].mainView;this.lowerSideView.addSubView(this.selectedSideView);this.mainView.addSubView(this.selectedMainView);if(this.action)
this.action();}
ESStdAppView.handleNewClick = function() {var myThis = this;var confirmFunc = function(ok) {this.saveFD = null;if(ok)
myThis.onNew();}
ESDialogs.confirm("Are you sure you want to create a new document?", confirmFunc);}
ESStdAppView.handleSaveClick = function() {if(this.saveFD == null) {this.handleSaveAsClick();return;}
ESFS.writeFile(this.saveFD, this.saveMimetype, this.getSaveData());}
ESStdAppView.handleSaveAsClick = function() {var myThis = this;var saveCB = function(fd) {if(fd == null)
return;myThis.saveFD = fd;myThis.handleSaveClick.call(myThis);}
ESFS.saveDialog(saveCB);}
ESStdAppView.handleOpenClick = function() {var myThis = this;var readCB  = function(file) {myThis.onOpen(file.data, file.type);}
var openCB = function(fd) {myThis.saveFD = fd;ESFS.readFile(fd, readCB);}
var mts = [];mts.push(this.saveMimetype);for(var i=0; this.openMimetypes != null && i < this.openMimetypes.length; i++)
mts.push(this.openMimetypes[i]);ESFS.openDialog(mts, openCB);}
ESFileMenu = Subclass(ESView);ESFileMenu.init = function()
{ESFileMenu.superClass.init.call(this);}
ESFileMenu.buildTree = function()
{ESFileMenu.superClass.buildTree.call(this);this.dom.style.overflow = 'visible';var params = { openMimetypes: this.openMimetypes,saveMimetype: this.saveMimetype,load: this.load, save: this.save, newdoc: this.newdoc }
if(this.canReplace == true || this.canReplace=="true")
params.canReplace = true;else params.canReplace = false;this.menu = ESFS.makeFileMenu(params);this.dom.appendChild(this.menu);this.dom.style.zIndex = 8;}

