/*Copyright Covariable 2008*/
ESFS = new Object();ESFS.dialogTimer = null;ESFS.readCallbacks = new Array();ESFS.openCallbacks = new Array();ESFS.writableCallbacks = new Array();ESFS.writeCallbacks = new Array();urlEncodeString = function(string){string = string.replace(new RegExp("%", "g"), "%25");string = string.replace(new RegExp("#", "g"), "%23");string = string.replace(new RegExp("\\+", "g"), "%2B");string = string.replace(new RegExp("&", "g"), "%26");string = string.replace(new RegExp("=", "g"), "%3D");string = string.replace(new RegExp("/", "g"), "%2F");string = string.replace(new RegExp(" ", "g"), "+");return string;}
ESFS.dynascript = function(url){var scr = document.createElement("script");scr.src = this.baseURL + url + "&junk=" + (Math.random() * 1000000);if(!document.body)throw "No BODY to attach dynamic script to yet.  Try calling ESFS routines later in your code.";document.body.appendChild(scr);}
ESFS.readFile = function(fd, callback){var id = this.readCallbacks.length;this.readCallbacks[id] = function(doc) { callback(doc, fd); };this.dynascript("read.cgi?fd=" + fd + "&id=" + id);}
ESFS.openPref = function(path, callback){var id = this.openCallbacks.length;this.openCallbacks[id] = callback;this.dynascript("openPref.cgi?fn=" + urlEncodeString(path) + "&app=" + window.location + "&id=" + id);}
ESFS.docFD = function(){if(ESFS.docFD.override)return ESFS.docFD.override;if(window.location.search && window.location.search!='?')
return window.location.search.substring(1,window.location.search.length);else return null;}
ESFS.readOpening = function(callback, newdoc){if(ESFS.docFD())
this.readFile(ESFS.docFD(), callback);else if(newdoc)callback(newdoc());}
ESFS.getDialogKey = function(){var str = window.location.search;var args = str.split("&");for(var i=0;i<args.length;i++)
{var parts = args[i].split("=");if(parts[0]=='key' || parts[0]=='?key')
return parts[1];}
throw("No dialog key found.");}
ESFS.openDialog = function(mimetypes, callback){if(mimetypes == null)
mimetypes =[];if(!callback)callback = function(arg) {window.location.search = "?" + arg; }
ESFS.__dialogUserCallback = callback;if(window.XMLHttpRequest)	
ESFS.__dialogPath = ESFS.dialogURL + "open-save/browser.html?type=open";else ESFS.__dialogPath = ESFS.dialogURL + "../basic_open.html?" + mimetypes;ESFS.dynascript('initiateDialog.cgi?');}
ESFS.createShield = function() {if(!ESFS.shield) { 
ESFS.shield = document.createElement("div");var shield = ESFS.shield;shield.style.position = "absolute";shield.style.left = "0px";shield.style.right = "0px";shield.style.top = "0px";shield.style.bottom = "0px";shield.style.backgroundColor = "black";shield.style.opacity = ".3";shield.style.filter = "alpha(opacity=30)";}
document.body.appendChild(ESFS.shield);}
ESFS.closeShield = function() {document.body.removeChild(ESFS.shield);}
ESFS.ignoreEscape = function(ev) {if(!ev)ev = window.event;var esc = 27;if(ev.keyCode == esc)
{ev.preventDefault();return;}
}
ESFS.__dialogInitiator = function(key){if(document.addEventListener)
document.addEventListener("keydown", ESFS.ignoreEscape, true);var rand = Math.floor(Math.random() * 1000000);var ifr = document.createElement("iframe");ifr.src = ESFS.__dialogPath + "&key=" + key;ifr.style.width = "700px";ifr.style.height = "400px";ifr.style.border = "3px inset #333";ifr.style.background = "white";ifr.style.marginTop = "30px";ifr.name = "dialog" + rand;var div = document.createElement("div");div.style.position = 'absolute';div.style.left='0px';div.style.right='0px';div.style.top='0px';div.style.height='500px';div.style.textAlign='center';var cen = document.createElement("center");div.appendChild(cen);cen.appendChild(ifr);div.style.zIndex = 9;ESFS.createShield();document.body.appendChild(div);ESFS.__dialogBox = div;if(ifr.document && ifr.document.body.focus)ifr.document.body.focus();else if(ifr.contentDocument && ifr.contentDocument.body && ifr.contentDocument.body.focus)ifr.contentDocument.body.focus();if(ifr.focus)ifr.focus();if(ifr.contentWindow && ifr.contentWindow.focus)
{ifr.contentWindow.focus();setTimeout(function() { if(ESFS.__dialogBox)ifr.contentWindow.focus(); }, 500);setTimeout(function() { if(ESFS.__dialogBox)ifr.contentWindow.focus(); }, 1000);setTimeout(function() { if(ESFS.__dialogBox)ifr.contentWindow.focus(); }, 1500);setTimeout(function() { if(ESFS.__dialogBox)ifr.contentWindow.focus(); }, 2000);setTimeout(function() { if(ESFS.__dialogBox)ifr.contentWindow.focus(); }, 2500);}
if(ifr.window && ifr.window.focus)ifr.window.focus();setTimeout(function(){ESFS.__reissueDialog(key, null);}, 4000);}
ESFS.__reissueDialog = function(key, length) {if(ESFS.__dialogBox ==null)
return;if(length == null)
length = 31;length *= 1000;if(ESFS.dialogTimeout != null)
clearTimeout(ESFS.dialogTimeout);ESFS.dynascript("finishDialog.cgi?key="+key);ESFS.dialogTimeout = setTimeout(
function(){ESFS.__reissueDialog(key,length);}, length);}
ESFS.__dialogSystemCallback = function(arg){clearTimeout(ESFS.dialogTimeout);ESFS.dialogTimeout = null;if(this.__dialogBox)
{ESFS.closeShield();var ifr = this.__dialogBox;ifr.parentNode.removeChild(ifr);this.__dialogBox = null;}
if(document.removeEventListener)
document.removeEventListener("keydown", ESFS.ignoreEscape, true);if(arg == "//cancel")return;this.__dialogUserCallback.apply(window, arguments);}
ESFS.makeWritable = function(fd, callback){var id = this.writableCallbacks.length;this.writableCallbacks[id] = callback;this.dynascript('writable.cgi?fd=' + fd + "&id=" + id);}
ESFS.writeFile = function(fd, mimetype, data, successcb, editorURL){ESFS.makeWritable(fd, function(fdwr) {if(ESFS.writeThroughServer.path)
{if(0 == ESFS.writeThroughServer(fd, mimetype, data))
successcb();}
else
{var id = ESFS.writeCallbacks.length;if(!successcb)successcb = function() { }
ESFS.writeCallbacks[id] = successcb;var blocksize = 512;for(var i=0;i<data.length;i+=blocksize)
{var chunk = '';for(var j=i;j<i+blocksize && j<data.length;j++)
{if(typeof data == 'string')
var cc = data.charCodeAt(j);else var cc = data[j];var h0 = cc % 16;var h1 = (cc - h0) / 16;var map = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];chunk += map[h1] + map[h0];}
if(i+blocksize >= data.length)var isend = "&isend=true";else var isend = "&isend=false";var req = 'writescr.cgi?fd=' + fdwr + '&id=' + id + '&mt=' + mimetype + '&off=' + i;if(editorURL == null)
editorURL = "current";if(editorURL == "current") {l = window.location + "";end = l.indexOf("?");req += '&editor=' + ((end <0) ? l : l.substr(0, end)) + '?';} else if(editorURL != "none") 
req += '&editor=' + editorURL;req += "&data=" + chunk+isend;ESFS.dynascript(req);}
}
});}
ESFS.saveDialog = function(callback){if(!callback)throw("No save dialog callback.");ESFS.__dialogUserCallback = callback;if(window.XMLHttpRequest)	
ESFS.__dialogPath = ESFS.dialogURL + "open-save/browser.html?type=save";else ESFS.__dialogPath = ESFS.dialogURL + "../basic_save.html?";ESFS.dynascript('initiateDialog.cgi?');}
ESFS.saveAs = function(mimetype, data, editorUrl, successcb){this.saveDialog(function(fdwr) {ESFS.docFD.override = fdwr;var newcb = null;if(successcb != null) {newcb = function(){ successcb(fdwr); }
}
ESFS.writeFile(fdwr, mimetype, data, newcb, editorUrl);});}
ESFS.enableWriteThroughServer = function(path){ESFS.writeThroughServer.path = path;}
ESFS.writeThroughServer = function(fd, mimetype, data){function xmlh() {try { return 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 { return new ActiveXObject(XMLHTTP_IDS[i]); }
catch(e) {}
}
alert("unable to create xmlhttprequest");return null;} }
var req = xmlh();req.open('POST', urlEncodeString(ESFS.writeThroughServer.path) + '?fd=' + fd + '&mt=' + mimetype, false);req.setRequestHeader("Content-type", mimetype);req.send(data);if(req.status == 200 && req.responseText=='success\n') return 0;return -1;}
ESFS.makeFileMenu = function(params){var div = document.createElement("div");div.style.position='relative';div.style.width='100px';div.style.height='20px';div.style.border='2px inset #448';div.style.background='#e0e0e8';div.innerHTML = 'File |>';var haveOpenDoc = false;var savedData = null;if(params.load)
{var newtype = "text/plain";if(params.saveMimetype)newtype = params.saveMimetype;var newdoc = function() { return {type:newtype, data:""}; }
if(params.newdoc)newdoc = function() { return {type:newtype, data:params.newdoc()}; }
ESFS.readOpening(function(file) { haveOpenDoc = true; savedData = file.data; params.load(file.data); }, newdoc);}
function checkDirty() {if(haveOpenDoc && params.save && params.save() != savedData)
if(!confirm("Discard unsaved changes?"))return true;return false; }
var items = new Array();if(params.load && params.newdoc)items.push( {id:'esfsMenu_new',name:'New',method:function(){if(checkDirty())return;if(!params.canReplace)
window.location.search = '';else {ESFS.docFD.override = '';haveOpenDoc = false;params.load(params.newdoc());}
}} );if(params.openMimetypes)items.push( {id:'esfsMenu_open',name:'Open...',method:function(){if(checkDirty())return;var callback = null;if(params.canReplace)
callback = function(fd) {ESFS.docFD.override = fd;haveOpenDoc = true;ESFS.readFile(fd, function(file) {params.load(file.data, file.type);});};ESFS.openDialog(params.openMimetypes, callback);}} );if(!params.noClose)items.push( {id:'esfsMenu_close',name:'Close',method:function(){if(checkDirty())return;window.location = 'http://www.redfs.com/mydocs.html'; }} );if(params.save && params.saveMimetype)
{items.push( {id:'esfsMenu_saveAs',name:'Save As...',method:function(){var data = params.save();ESFS.saveAs(params.saveMimetype, data, params.editorURL, function() {savedData = data;haveOpenDoc = true;if(params.savedMessage)alert(params.savedMessage);}); }} );items.push( {id:'esfsMenu_save',name:'Save',method:function(){var data = params.save();ESFS.writeFile(ESFS.docFD(), params.saveMimetype, data, function() {savedData = data;if(params.savedMessage)alert(params.savedMessage);}); }} );}
function dispatcher(i) { return function() {if(items[i].disabled)return;items[i].method();}; }
var mdiv = document.createElement("div");mdiv.style.position='absolute';mdiv.style.background='#f8f8f0';mdiv.style.border='2px inset #80f080';var byid = new Object();for(var i=0;i<items.length;i++)
{var idiv = document.createElement("div");mdiv.appendChild(idiv);idiv.innerHTML = items[i].name;idiv.onmouseup = dispatcher(i);idiv.onmouseover = function() { this.style.background = '#6060c0'; }
idiv.onmouseout = function() { this.style.background = '#f8f8f0'; }
idiv.id = items[i].id;items[i].div = idiv;byid[idiv.id] = items[i];}
mdiv.style.display='none';mdiv.style.zIndex = 8;div.appendChild(mdiv);function reset() {if(byid['esfsMenu_save'])
byid['esfsMenu_save'].disabled = !(haveOpenDoc && params.save && savedData != params.save());if(byid['esfsMenu_close'])
byid['esfsMenu_close'].disabled = !haveOpenDoc;for(var i=0;i<items.length;i++) {if(items[i].disabled)
items[i].div.style.color='#b0b0b0';else items[i].div.style.color='#000';items[i].div.style.background='#f8f8f0';}
}
function ignorer(ev) {if(!ev)ev = window.event;if(ev.preventDefault)ev.preventDefault();if(ev.stopPropagation)ev.stopPropagation();window.event.returnValue = false; window.event.cancelBubble = true;return false;}
div.onmousedown = function(ev) {reset(); mdiv.style.display='block';if(!ev)ev = window.event;if(ev.preventDefault)ev.preventDefault();if(ev.stopPropagation)ev.stopPropagation();if(window.event) { window.event.returnValue = false; window.event.cancelBubble = true; }
document.onmouseup = function() {mdiv.style.display='none';if(document.detachEvent)
document.detachEvent("onselectstart",ignorer);}
if(document.body.attachEvent)
document.attachEvent("onselectstart", ignorer);return false;}
return div;}
ESFS.authParam = function(){if(!window.ESCookie)throw "ESFS.authParam called from untrusted code";return "&auth=" + ESUtil.urlEncodeString(ESCookie.read("auth"));}
ESFS.URLForFD = function(fd) {return ESFS.baseURL + "/read.cgi?fd=" + fd;}
ESFS.baseURL='http://www.redfs.com/cgi-bin/';ESFS.dialogURL='http://www.redfs.com/dialogs/';ESFS.dialogServer='http://www.redfs.com:2001/';
