/*
 *
 * Ephox EditLive! JavaScript Library
 * Copyright (c) 1999-2007 Ephox Corp. All rights reserved.
 * This software is provided "AS IS," without a warranty of any kind.
 *
 * Version: 6.2.4.139
 */

var hasQuickStarted = false;
var eljUseWebDAV = false;
var eljUseMathML = false;
var eljUseLiveConnect = true;

/** The designer class provides a simple API for setting parameters on the designer and
 * instantiating it.
 */
function EditLiveJava(name, width, height) {
    
    EditLiveCommonStatic_detectBrowser();
    
    this.paramNames = new Array();
    this.paramValues = new Array();
    this.overwrittenSubmit=false;
    this.width = width;
    this.height = height;
    this.name = name;
    this.borderStyle = "";
    this.bAutoSubmit = true;
    
    this.setDownloadDirectory = EditLiveCommon_setDownloadDirectory;
    this.setConfigurationFile = EditLiveCommon_setXMLURL;
    this.setXMLURL = EditLiveCommon_setXMLURL;
    this.setDebugLevel = EditLiveCommon_setDebugLevel;
    this.setLogger = EditLiveCommon_setLogger;
    this.setConfigurationText = EditLiveCommon_setXML;
    this.setXML	= EditLiveCommon_setXML;
    this.setMinimumJREVersion =  EditLiveCommon_setMinimumJREVersion;
    this.setJREDownloadURL = EditLiveCommon_setJREDownloadURL;
    this.setShowSystemRequirementsError = EditLiveCommon_setShowSystemRequirementsError;
    this.setCookie = EditLiveCommon_setCookie;
    this.setLocalDeployment = EditLiveCommon_setLocalDeployment;
    this.InsertHTMLAtCursor = EditLiveCommon_InsertHTMLAtCursor;
    this.InsertHyperlinkAtCursor = EditLiveCommon_InsertHyperlinkAtCursor;
    this.ScrollTo = EditLiveCommon_ScrollTo;
    this.setAutoSubmit = EditLiveCommon_setAutoSubmit;
    this.UploadFiles = EditLiveCommon_UploadFiles;
    this.UploadImages = EditLiveCommon_UploadFiles;
    this.setDownloadingMessage = EditLiveCommon_setDownloadingMessage;
    this.setLocale = EditLiveCommon_setLocale;
    this.setBorderStyle = EditLiveCommon_setBorderStyle;
    this.show = EditLiveCommon_show;
    this.setShowButtonText = EditLiveCommon_setShowButtonText;
    this.setShowButtonIconURL = EditLiveCommon_setShowButtonIconURL;
    this.setHideButtonText = EditLiveCommon_setHideButtonText;
    this.setHideButtonIconURL = EditLiveCommon_setHideButtonIconURL;
    this.showAsButton = EditLiveCommon_showAsButton;
    this.setUsername = EditLiveCommon_setUsername;
    
    this.setDocument = EditLiveJava_setDocument;
    this.setBody = EditLiveJava_setBody;
    this.setStyles = EditLiveJava_setStyles;
    this.setXSD = EditLiveJava_setXSD;
    this.addXSDAsString = EditLiveJava_addXSDAsString;
    this.setReturnBodyOnly = EditLiveJava_setReturnBodyOnly;
    this.GetDocument = EditLiveJava_GetDocument;
    this.GetBody = EditLiveJava_GetBody;
    this.GetSelectedText = EditLiveJava_GetSelectedText;
    this.GetWordAtCursor = EditLiveJava_GetWordAtCursor;
    this.GetHyperlinkAtCursor = EditLiveJava_GetHyperlinkAtCursor;
    this.SetDocument = EditLiveJava_setDocument;
    this.SetBody = EditLiveJava_setBody;
    this.GetStyles = EditLiveJava_GetStyles;
    this.GetWordCount = EditLiveJava_GetWordCount;
    this.GetCharCount = EditLiveJava_GetCharCount;
    this.GetBookmarkList = EditLiveJava_GetBookmarkList;
    this.IsDirty = EditLiveJava_IsDirty;
    this.SetProperties = EditLiveJava_SetProperties;
    this.PostDocument = EditLiveJava_PostDocument;
    this.addView = EditLiveJava_addView;
    this.addViewWithString = EditLiveJava_addViewWithString
    this.setUseTextarea = EditLiveJava_setUseTextarea;
    this.setTextareaRows = EditLiveJava_setTextareaRows;
    this.setTextareaCols = EditLiveJava_setTextareaCols;
    this.setPreload = EditLiveJava_setPreload;
    this.setOnInitComplete = EditLiveJava_setPreload;
    this.setHead = EditLiveJava_setHead;
    this.setBaseURL = EditLiveJava_setBaseURL;
    this.GetCurrentDocumentURL = EditLiveJava_GetCurrentDocumentURL;
    this.setOutputCharset = EditLiveJava_setOutputCharset;
    this.setCommentTemplate = EditLiveJava_setCommentTemplate;
    this.addJar = EditLiveJava_addJar;
    this.setPreserveInputStructure = EditLiveJava_setPreserveInputStructure;
    this.setHttpLayerManager = EditLiveJava_setHttpLayerManager;
    this.addParam = EditLiveJava_addParam;
    this.getParam = EditLiveJava_getParam;
    this.RaiseEvent = EditLiveCommon_RaiseEvent;
    this.setReadOnly = EditLiveJava_setReadOnly;
    this.addPlugin = EditLiveJava_addPlugin;
    this.addPluginAsText = EditLiveJava_addPluginAsText;
    
    // WebDAV Properties
    this.setUseWebDAV = EditLiveJava_setUseWebDAV;
    
    // MathML Properties
    this.setUseMathML = EditLiveJava_setUseMathML;
    
    // LiveConnect
    this.setUseLiveConnect = EditLiveCommonStatic_setUseLiveConnect;
    
    this.started = false;
    
    this.getAppletHTML = EditLiveJava_getAppletHTML;
    this.getHiddenFields = EditLiveJava_getHiddenFields;
    this.addCombinedParameter = EditLiveJava_addCombinedParameter;
    
    this.started = false;
    this.editXML = false;
    this.views = new Array();
    this.xsds = new Array();
    this.extraJars = new Array();
    this.pluginUrls = new Array();
    this.pluginText = new Array();
    this.pluginBases = new Array();
    this.classNames = "";
    this.preload = false;
    this.bForceUseTextArea = false;
    
    //default values
    var base = getScriptBase("editlivejava.js");
    this.setDownloadDirectory(base);
    this.setConfigurationFile(this.downloadDirectory + "sample_eljconfig.xml");
}

EditLiveJava.prototype.getVersion = function() {
    return '6.2.4.139';
}

function EditLiveCommonStatic_setUseLiveConnect(val) {
    eljUseLiveConnect = val;
}

function EditLiveJava_setCommentTemplate(val) {
    if (this.started) {
        return false;
    }
    
    this.addParam("commentTemplate", val);
    
    return true;
}

function EditLiveJava_addJar(jarUrl, className) {
    this.extraJars[this.extraJars.length] = jarUrl;
    this.classNames += className + " ";
}

function EditLiveJava_addPlugin(pluginUrl) {
    this.pluginUrls[this.pluginUrls.length] = pluginUrl;
}

function EditLiveJava_addPluginAsText(pluginText, pluginBaseUrl) {
    this.pluginText[this.pluginText.length] = pluginText;
    if (pluginBaseUrl == undefined) {
        pluginBaseUrl = "%"; // We use % to indicate that no URL was specified since it cannot ever appear by itself in a URL.
    }
    this.pluginBases[this.pluginBases.length] = pluginBaseUrl;
}

function EditLiveJava_addParam(name, value) {
    var i;
    var found = false;
    for (i = 0; i < this.paramNames.length; i++) {
        if (this.paramNames[i] == name) {
            this.paramValues[i] = value;
            found = true;
            break;
        }
    }
    
    if (!found) {
        var index = this.paramNames.length
        this.paramNames[index] = name;
        this.paramValues[index] = value;
        return true;
    }
}

function EditLiveJava_getParam(name) {
    var i;
    for (i = 0; i < this.paramNames.length; i++) {
        if (this.paramNames[i] == name) {
            return this.paramValues[i];
        }
    }
    return "";	
}

function EditLiveJava_getAppletHTML(preserveContent) {
    if (!this.cookie) {
        this.setCookie(document.cookie);
    }
    
    // Determine the applet class to use.
    var appletClass;
    if (IsMac) {
        appletClass = "com.ephox.editlive.osx.EditLiveJava";
    } else if (IsLinux) {
        appletClass = "com.ephox.editlive.linux.EditLiveJava";
    } else if (IsSolaris) {
        appletClass = "com.ephox.editlive.solaris.EditLiveJava";
    } else {
        appletClass = "com.ephox.editlive.win.EditLiveJava";
    }
    
    // Determine the classpath.
    jarList = this.downloadDirectory + "editlivejava.jar" + EditLiveCommonStatic_getJarVersion();
    if (eljUseMathML) {
        jarList += "," + this.downloadDirectory + "WebEQEphox.jar" + EditLiveCommonStatic_getJarVersion();
    }
    
    plugins = "";
    var urlCounter;
    for (urlCounter = 0; urlCounter < this.extraJars.length; urlCounter++) {
        if (urlCounter != 0) {
            plugins += ",";
        }
        plugins += this.extraJars[urlCounter];
    }
    
    // Standard parameters for branding the loading image.
    
    var paramLength = this.paramNames.length;
    this.paramNames[paramLength] = "BeanListenerClasses";
    this.paramValues[paramLength] = this.classNames;
    
    // Add the plugin URLs to the parameter list
    this.addCombinedParameter("PluginUrls", this.pluginUrls);
    // Add the plugin configs that were added as text.
    this.addCombinedParameter("PluginText", this.pluginText);
    // Add the base URLs for plugins added as text.
    this.addCombinedParameter("PluginTextBaseUrls", this.pluginBases);
    
    classpath = jarList;
    var appletName = this.name + "_elj";
    hiddenName = this.name;
    
    if (this.editXML) {
        var i = 0;
        var nameParam = "";
        var valueParam = "";
        var isUrlParam = "";
        for (i = 0; i < this.views.length; i++) {
            var view = this.views[i];
            nameParam += escape(view[0]) + ":";
            valueParam += escape(view[1]) + ":";
            isUrlParam += view[2] + ":";
        }
        var propLength = this.paramNames.length;
        this.paramNames[propLength] = "viewNames";
        this.paramValues[propLength] = nameParam;
        propLength++;
        this.paramNames[propLength] = "viewValues";
        this.paramValues[propLength] = valueParam;
        propLength++;
        this.paramNames[propLength] = "viewIsURLs";
        this.paramValues[propLength] = isUrlParam;
        propLength++;
        var xsdParam = "";
        for (i = 0; i < this.xsds.length; i++) {
            xsdParam += this.xsds[i];
        }
        this.paramNames[propLength] = "XSDString";
        this.paramValues[propLength] = xsdParam;
    }
    
    if (((IsWindows && IsMSIE) || checkSupportsLiveConnect(appletName)) && preserveContent) {
        // Attach our window.onload function for this instance
        var currentWindowOnload = window.onload;
        window.onload = function() {
            if (currentWindowOnload) {
                currentWindowOnload.apply(window);
            }
            EditLiveCommonStatic_SendPageLoaded(appletName);
        };
    } else {
        var propLength = this.paramNames.length;
        this.paramNames[propLength] = "pageLoaded";
        this.paramValues[propLength] = true;
        propLength++;
    }
    
    var appletTag = EditLiveCommonStatic_generateAppletTag(this.width, this.height, appletName, classpath, plugins,
    appletClass, this.paramNames, this.paramValues, this.preload, this.bForceUseTextArea);
    if (appletTag == '' && this.preload) {
        for (var i = 0; i < this.paramNames.length; i++) {
            if (this.paramNames[i] == 'setPreload') {
                setTimeout(this.paramValues[i] + "()", 20);
            }
        }
    }
    
    var result = EditLiveCommonStatic_getEditorLayout(appletTag, this.borderStyle, this.width, this.height);
    return result;
}

function EditLiveCommonStatic_getJarVersion() {
    // for now we are not using the version as a part of the loading of edit live
    // and so are returning an empty string.
    //This is because of multiple classloader issues stopping this from working.
    // environments with issues include the vs.net control.
    return '';
    if (IsOpera) {
        return '';
    } else {
        return ';6.2.4.139';
    }
}

function EditLiveJava_addCombinedParameter(paramName, pluginValues) {
    var combinedValue = "";
    var counter;
    for (counter = 0; counter < pluginValues.length; counter++) {
        if (counter != 0) {
            combinedValue += "|";
        }
        combinedValue += pluginValues[counter];
    }
    var paramLength = this.paramNames.length;
    this.paramNames[paramLength] = paramName;
    this.paramValues[paramLength] = combinedValue;
}

function EditLiveJava_getHiddenFields() {
    var fields = new Array();
    fields[0] = this.name;
    fields[1] = this.name + "_styles";
    return fields;
}

function EditLiveJava_setUseWebDAV(bValue){
    if (this.started == true){
        return false;
    }
    dalert("Use WebDAV: " + bValue);
    eljUseWebDAV = bValue;
}

function EditLiveJava_setUseMathML(bValue) {
    if (this.started == true) {
        return false;
    }
    dalert("Use MathML: " + bValue);
    eljUseMathML = bValue;
}

function EditLiveJava_setOutputCharset(charset) {
    if (this.started == true) {
        return false;
    }
    dalert("Output Charset: " + charset);
    
    this.addParam("outputCharset", charset);
}

function EditLiveJava_setDocument(src){
    if(this.started == true){
        EditLiveCommonStatic_CustomAction("setdocument", src, this.name + "_elj");
    } else {
        dalert("Document    " + src);
        
        this.addParam("Document", src);
    }
} //setDocument

function EditLiveJava_setBody(src){
    if(this.started == true){
        EditLiveCommonStatic_CustomAction("setbody", src, this.name + "_elj");
    } else {
        dalert("Body    " + src);
        this.addParam("Body", src);
    }
} //setBody

function EditLiveJava_setStyles(src){
    if(this.started == true){
        return false;
    }//end if
    dalert("Styles   "+src);
    
    this.addParam("Styles", src);
}//setStyles


function EditLiveJava_setReturnBodyOnly(bValue){
    if(this.started == true){
        return false;
    } //end if
    dalert("ReturnBodyOnly    " + bValue);
    
    this.addParam("setReturnBodyOnly", bValue);
} //setReturnBodyOnly



function EditLiveJava_setPreserveInputStructure(bValue) {
    if(this.started == true){
        return false;
    }
    dalert("PreserveInputStructure    " + bValue);
    
    this.addParam("setPreserveInputStructure", bValue);
}

function EditLiveJava_setXSD(val) {
    if (this.started == true) {
        return false;
    }
    
    this.addParam("XSD", val);
}

function EditLiveJava_addXSDAsString(val) {
    if (this.started == true) {
        return false;
    }
    this.xsds[this.xsds.length] = val;
}

function EditLiveJava_GetDocument(){
    if(arguments.length == 1) {
        EditLiveCommonStatic_CustomAction("getdocument", arguments[0], this.name + "_elj");
    } else if(arguments.length == 2) {
        var sArgs = arguments[0];
        EditLiveCommonStatic_CustomAction("getdocument", arguments[0] + "##ephox##" + arguments[1], this.name + "_elj");
    }
} //EditLiveJava_GetDocument

function EditLiveJava_GetBody(){
    if(arguments.length == 1) {
        EditLiveCommonStatic_CustomAction("getbody", arguments[0], this.name + "_elj");
    } else if(arguments.length == 2) {
        var sArgs = arguments[0];
        EditLiveCommonStatic_CustomAction("getbody", arguments[0] + "##ephox##" + arguments[1], this.name + "_elj");
    }
} //EditLiveJava_GetBody

function EditLiveJava_GetSelectedText(){
    EditLiveCommonStatic_CustomAction("getselectedtext", arguments[0], this.name + "_elj");
} //EditLiveJava_GetSelectedText

function EditLiveJava_GetWordAtCursor(){
    EditLiveCommonStatic_CustomAction("getwordatcursor", arguments[0], this.name + "_elj");
} //EditLiveJava_GetWordAtCursor

function EditLiveJava_GetHyperlinkAtCursor(){
    EditLiveCommonStatic_CustomAction("gethyperlinkatcursor", arguments[0], this.name + "_elj");
} //EditLiveJava_GetHyperlinkAtCursor

function EditLiveJava_GetCurrentDocumentURL(sActionValue){
    EditLiveCommonStatic_CustomAction("getcurrentfile", sActionValue, this.name + "_elj");
} //EditLiveJava_GetCurrentDocumentURL

function EditLiveJava_GetStyles(sActionValue){
    EditLiveCommonStatic_CustomAction("getstyles", sActionValue, this.name + "_elj");
} //EditLiveJava_GetStyles

function EditLiveJava_GetWordCount(sActionValue){
    EditLiveCommonStatic_CustomAction("getwordcount", sActionValue, this.name + "_elj");
} //EditLiveJava_GetStyles

function EditLiveJava_GetCharCount(sActionValue){
    EditLiveCommonStatic_CustomAction("getcharcount", sActionValue, this.name + "_elj");
} //EditLiveJava_GetStyles

function EditLiveJava_GetBookmarkList(sActionValue){
    EditLiveCommonStatic_CustomAction("listbookmarks", sActionValue, this.name + "_elj");
}

function EditLiveJava_SetProperties(sActionValue) {
    EditLiveCommonStatic_CustomAction("setproperties", sActionValue, this.name + "_elj");
}

function EditLiveJava_setHttpLayerManager(value) {
    
    if(this.started == true){
        EditLiveCommonStatic_CustomAction("sethttplayer", sActionValue, this.name + "_elj");
    } else {      
        dalert("HttpLayer    " + value);
        
        this.addParam("HttpLayer", value);
    }
}

function EditLiveJava_IsDirty(sActionValue){
    EditLiveCommonStatic_CustomAction("isdirty", sActionValue, this.name + "_elj");
} //EditLiveJava_IsDirty

function EditLiveJava_PostDocument() {
    var val = "";
    var argPosition;
    for (argPosition = 0; argPosition < arguments.length; argPosition++) {
        val += arguments[argPosition];
        if (argPosition + 1 < arguments.length) {
            val += "##ephox##";
        }
    }
    EditLiveCommonStatic_CustomAction("postdocument", val, this.name + "_elj");
}

function EditLiveJava_addViewWithString(name, value) {
    if (this.started == true) {
        return false;
    }
    dalert("Add view: " + name + " - " + value);
    var view = new Array();
    view[0] = name;
    view[1] = value;
    view[2] = "false";
    this.views[this.views.length] = view;
}

function EditLiveJava_addView(name, value) {
    if (this.started == true) {
        return false;
    }
    dalert("Add view: " + name + " - " + value);
    var view = new Array();
    view[0] = name;
    view[1] = value;
    view[2] = "true";
    this.views[this.views.length] = view;
}

function EditLiveJava_Print(html) {
    var newWin;
    newWin = window.open("", "", "toolbar=no,resizable=yes"); //, "toolbar=no,location=no,menu=no")
    newWin.document.open();
    newWin.document.write('<html><head><title>Print Preview</title></head><frameset rows="60, *"><frame name="Print"><frame name="content"></frameset></html>');
    newWin.document.close();
    newWin['Print'].document.open();
    newWin['Print'].document.write('<html><body><form><input type="button" value="Print" onclick="parent[\'content\'].focus();parent[\'content\'].print();"><input type="button" value="Close" onclick="parent.close();"></form></body></html>');
    newWin['Print'].document.close();
    newWin['content'].document.open();
    newWin['content'].document.write(html);
    newWin['content'].document.close();
    
}


// BEGIN SHARED SECTION
// Script below here must be identical in each of the javascript files.

var DEBUG = false;

var bOnsubmit = false;
var bGetContent = false;
var hiddenName;
var sDebugLevel = "off";
var sLogger = "console";
var bLocalDeploy = false;
var sJREDownloadURL = "";
var sMinimumJREVersion = "1.4.2";
var bShowErrorMessage = "true";
var eljLoadingMessage = "Updating components and initializing...";
var bUseTextArea = false;
var iTARows = 17;
var iTACols = 55;
var cookie = false;

// The classpath for applets.
var classpath;

var plugins;

// The Path to the EditLive download directory.
var downloadPath;

// The original onsubmit function.
var fOnSubmit;

// The new window opened for submitting on Netscape 4.
var wNewWindow;

// True if we are in Netscape.
var IsNetscape = false;

// True if we are on windows.
var IsWindows = false;

// True if we are on mac.
var IsMac = false;

// True if this is Mac OS X.
var IsOSX = false;

// True if we are on Solaris.
var IsSolaris = false;

// True if we are on linux.
var IsLinux = false;

// True if we are in IE.
var IsMSIE = false;

// True if we are in safari.
var IsSafari = false;

// True is we are in Opera
var IsOpera = false;

// True if we are in the IE DHTML control.
var IsMSIEDHTML = false;

// The PageID
var iPageID = 0;

var AllowMacNetscape = true;

function setAllowNetscapeOnMac(value) {
    AllowMacNetscape = value;
}

/********************************************************
 Globals
 *********************************************************/

function EditLiveCommon_safariSubmit(url) {
    var win = window.open("", "eljSubmit", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=1,height=1");
    win.location = url;
}

function EditLiveCommon_setDownloadingMessage(message) {
    eljLoadingMessage = message;
}

function EditLiveCommon_setDownloadDirectory(sDir) {
    combineDownloadURL(sDir);
    if(sDir.charAt(sDir.length - 1) != "/"){
        sDir += "/";
    } //end if
    downloadPath = sDir;
    this.downloadDirectory = sDir;
    this.addParam("downloadDir", this.downloadDirectory);
}

function EditLiveCommon_setLocalDeployment(bDeploy) {
    bLocalDeploy = bDeploy;
}

function EditLiveCommon_setAutoSubmit(val) {
    this.bAutoSubmit = val;
}

function EditLiveCommon_setMinimumJREVersion(val) {
    if(val == "1.4.1" || val == "1.4.2" || val == "1.5.0"){
        sMinimumJREVersion = val;
    }
}

function EditLiveCommon_setJREDownloadURL(val) {
    sJREDownloadURL = val;
}

function EditLiveCommon_setShowSystemRequirementsError(val) {
    bShowErrorMessage = val;
}

function EditLiveCommon_setDebugLevel(val) {
    sDebugLevel = val;
}

function EditLiveCommon_setLogger(val) {
    sLogger = val;
}

//******************************

function EditLiveCommon_setXMLURL(strXMLURL){
    if(this.started == true){
        return false;
    } //end if
    
    this.addParam("setXMLURL", strXMLURL);
} //setXMLURL


function EditLiveCommon_setXML(strXML) {
    if(this.started == true){
        return false;
    } //end if
    
    this.addParam("setXML", strXML);
} //setXML


function EditLiveCommon_setCookie(cookie_) {
    dalert("in setCookie");
    if(this.started == true)
        return false;
    if(cookie_ != "") {
        this.cookie = true;
        
        if (cookie_ !=document.cookie &&document.cookie.length>0) {
            cookie_=document.cookie+";" + cookie_;
        }
        dalert("Cookie:    " + cookie_);
        this.addParam("Cookie", cookie_);
    }
}

function EditLiveCommon_setLocale(strLocale) {
    this.addParam("setLocale", strLocale);
}

function EditLiveJava_setUseTextarea(bUseText) {
    this.bForceUseTextArea = bUseText;
}


function EditLiveJava_setTextareaRows(iRows) {
    iTARows = iRows;
}

function EditLiveJava_setTextareaCols(iCols) {
    iTACols = iCols;
}

function EditLiveJava_setPreload(sPreload){
    if(this.started == true){
        return false;
    }
    this.preload = true;
    dalert("Preload:   " + sPreload);
    this.addParam("setPreload", sPreload);
}

function EditLiveJava_setHead(src){
    if(this.started == true){
        return false;
    }
    dalert("Head    " + src);
    
    this.addParam("Head", src);
} //setHead

function EditLiveJava_setBaseURL(url){
    if(this.started == true){
        return false;
    }
    dalert("Base    " + url);
    
    this.addParam("EphoxBaseURL", url);
} //setHead

function EditLiveJava_setReadOnly(bool){
    if(this.started != true){
        dalert("setReadOnly    " + true);
        
        this.addParam("setReadOnly", bool);
    }
} //setDocument

//****************************** JavaScript API Routines ******************************

function EditLiveCommon_InsertHTMLAtCursor(sActionValue){
    setTimeout("EditLiveCommonStatic_CustomAction('inserthtmlatcursor',\"" + sActionValue + "\", '" + this.name + "_elj');", 10);
}

function EditLiveCommon_InsertHyperlinkAtCursor(){
    if(arguments.length == 1) {
        EditLiveCommonStatic_CustomAction("inserthyperlinkatcursor", arguments[0], this.name + "_elj");
    } else {
        var i = 1;
        var sHyperlinkString = arguments[0];
        for(i = 1; i < arguments.length; i++) {
            sHyperlinkString += "##ephox##";
            sHyperlinkString += arguments[i];
        }
        EditLiveCommonStatic_CustomAction("inserthyperlinkatcursor", sHyperlinkString, this.name + "_elj");
    }
}

function EditLiveCommon_ScrollTo() {
    var val;
    if (arguments.length == 1) {
        val = arguments[0];
    } else {
        val = arguments[0] + ":" + arguments[1];
    }
    EditLiveCommonStatic_CustomAction("scrollto", val, this.name + "_elj");
}

function EditLiveCommon_RaiseEvent(sActionValue) {
    EditLiveCommonStatic_CustomAction("raiseevent", sActionValue, this.name + "_elj");
}

function EditLiveCommon_UploadFiles(sActionValue){
    EditLiveCommonStatic_CustomAction("uploadImages", sActionValue, this.name + "_elj");
}

/**
 * Detects if the specfied applet supports LiveConnect.
 * The result of this will change as the applet advances through its lifecycle.  An applet that initially doesn't support
 *  LiveConnect may end up supporting live connect later on.
 *
 * @param string containing the name of the applet
 * @return true if the applet supports LiveConnect
 */
function checkSupportsLiveConnect(name) {
    dalert("checking support for Live Connect");
    var result;
    var applet = EditLiveCommonStatic_GetAppletWithName(name);
    if (applet && IsWindows && IsMSIE) {
        dalert("Applet exist and is on IE");
        result = hasAppletEverBeenVisible(applet, name); //hasAppletEverBeenVisible
    } else if (IsWindows && IsMSIE) {
        dalert("Applet hasn't been fully written to the document yet and is on IE");
        // Applet hasn't been fully written to the document yet
        result = false;
    } else if (IsOpera) {
        dalert("Applet hasn't been fully written to the document yet and is on Opera");
        //Opera LiveConnect is broken when loading from cache
        result = false;
    } else {
        dalert("Applet hasn't been fully written to the document yet and is on FF");
        //Mozilla (and Safari) based browsers are our only other supported browsers
        result = true;
    }
    dalert("support for Live Connect is " + result);
    return result;
}

/**
 * Detects if a block is visible by checking itself
 * and all its parent elements for display set to none.
 *
 * This function will only work for IE (and is only called when using IE), as the currentStyle
 * is an IE only property. If you need to do this outside of
 * IE, try using window.getComputedStyle function
 *
 * On other browsers it always returns true.
 */
var AppletVisible = new Array();
function hasAppletEverBeenVisible(element, name) {
    //if we have ever been Visible (using the state), return true now.
    if (AppletVisible != null && AppletVisible[name]){
        return true;
    }
    while (element) {
        if (element.currentStyle.display == "none") {
            //set the state to remember the result
            AppletVisible[name] = false;
            return false;
        }
        element = element.parentElement
    }
    AppletVisible[name] = true;
    //set the state and return true.
    return true;
}

/**
 * Processes the bookmark list and passes it on to the 
 *
 * @param string containing the name of the applet
 */
function EditLiveCommonStatic_ProcessBookmarks(callback, list) {
    //ELJ adds an extra delimiter on the end to make parsing easier
    var EPHOX_DELIMITER = "##EPHOX##";
    var bookmarks = new Array();
    while (list.indexOf("##EPHOX##") > -1) {
        var temp = list.substring(0, list.indexOf(EPHOX_DELIMITER));
        bookmarks[bookmarks.length] = temp;
        list = list.substring(temp.length + EPHOX_DELIMITER.length);
    }
    eval(callback + "(bookmarks)");
}

/**
 * Executes the page loaded event, calls setTimeout()
 *
 * @param string containing the name of the applet
 */
function EditLiveCommonStatic_SendPageLoaded(name) {
    setTimeout("EditLiveCommonStatic_SendPageLoadedExecute('" + name + "');", 50);
}

/**
 * Sends the page loaded event to the specified applet, assuming it supports live connect
 *
 * @param string containing the name of the applet
 */
function EditLiveCommonStatic_SendPageLoadedExecute(name) {
    var cacheID = EditLiveCommonStatic_getCacheFieldValue(name);
    
    if (checkSupportsLiveConnect(name)) {
        var applet = EditLiveCommonStatic_GetAppletWithName(name);
        applet.pageLoaded(cacheID);
    }
}


function EditLiveCommonStatic_DoCustomAction() {
    var paramNames = new Array();
    var paramValues = new Array();
    
    paramNames[0] = "CustomAction";
    paramValues[0] = "customaction:" + ephoxGAction + ":" + ephoxGValue;
    paramNames[1] = "CustomActionTarget";
    paramValues[1] = ephoxGName;
    
    EditLiveCommonStatic_runPostApplet(paramNames, paramValues);
}

var ephoxGAction;
var ephoxGValue;
var ephoxGName;

function EditLiveCommonStatic_CustomAction(action, value, name) {
    if (eljUseLiveConnect && checkSupportsLiveConnect(name)) {
        var applet = EditLiveCommonStatic_GetAppletWithName(name);
        applet.performCustomActionLiveConnect("customaction:" + action + ":" + value);
        return;
    }
    
    ephoxGAction = action;
    ephoxGValue = value;
    ephoxGName = name;
    setTimeout("EditLiveCommonStatic_DoCustomAction()", 10);
}

function EditLiveCommonStatic_GetAppletWithName(name) {
    if (document.getElementById) {
        return document.getElementById(name);
    }
}

//**************************************************************************************

function EditLiveCommonStatic_detectBrowser() {
    var version = navigator.appVersion;
    if (version != "") {
        var iParen = version.indexOf("(", 0);
        var sUsrAgent = new String(navigator.userAgent);
        sUsrAgent = sUsrAgent.toLowerCase();
        
        navigator.clientVersion = version.substring(0, iParen - 1);
        if (sUsrAgent.indexOf("msie", 0) > 0) {
            IsMSIE = true;
            if (navigator.clientVersion.substring(0, 1) >= 4) {
                IsMSIEDHTML = true;
            }
        } else if (sUsrAgent.indexOf("safari", 0) >= 0) {
            IsSafari = true;
        }else if (sUsrAgent.indexOf("mozilla", 0) >= 0) {
            IsNetscape = true;
        } else if (sUsrAgent.indexOf("opera", 0) >= 0) {
            //IsMSIE = true;
            IsOpera = true;
        }
        
        if (sUsrAgent.indexOf("win", 0) > 0) {
            IsWindows = true;
        } else if (sUsrAgent.indexOf("mac", 0) > 0){
            IsMac = true;
            if (IsSafari || IsNetscape) {
                IsOSX = true;
            } else {
                for(i = 0; i < navigator.plugins.length; i++){
                    if(navigator.plugins[i].name == "Default Plugin Carbon.cfm") {
                        IsOSX = true;
                    }
                    if (navigator.plugins[i].name.indexOf("OS X") > -1) {
                        IsOSX = true;
                    }
                }
            }
        } else if (sUsrAgent.indexOf("sunos", 0) > 0){
            IsSolaris = true;
        } else if (sUsrAgent.indexOf("linux", 0) > 0){
            IsLinux = true;
        }
    }
}

// Determines whether or not the current browser is supported.
function EditLiveCommonStatic_isSupportedBrowser() {
    if (IsWindows) {
        return IsMSIE || IsNetscape || IsOpera;
    } else if (IsOSX) {
        return IsSafari || (IsNetscape && AllowMacNetscape) || IsOpera;
    } else if (IsSolaris) {
        return IsNetscape;
    } else if (IsLinux) {
        return IsNetscape;
    } else {
        return false;
    }
}

function getEphoxPageID() {
    if(iPageID == 0) {
        
        var dTemp = new Date();
        iPageID = dTemp.getTime();
    }
    return iPageID;
}

function ephoxQuickStart(downloadDir) {
    if (hasQuickStarted) {
        return;
    }
    hasQuickStarted = true;
    dalert("Quick Starting EditLive!");
    if (downloadDir.charAt(downloadDir.length - 1) != '/') {
        downloadDir += '/';
    }
    var classpath = downloadDir;
    EditLiveCommonStatic_detectBrowser();
    var javaInstalled = false;
    if (IsOSX) {
        javaInstalled = false;
    } else if (navigator && navigator.mimeTypes && navigator.mimeTypes.length) {
        javaInstalled = navigator.mimeTypes['application/x-java-applet;version=1.4'];
    } else if (IsWindows && IsMSIE && window.ActiveXObject) {
        try {
            var obj = new ActiveXObject("JavaWebStart.isInstalled");
            javaInstalled = obj != null;
            classpath = downloadDir + "editlivejava.jar," + downloadDir;
        } catch (e) {
            javaInstalled = false;
        }
    }
    if (javaInstalled) {
        dalert("classpath for Quick Start is " + classpath);
        var params = new Array();
        var paramValues = new Array();
        var kickStartCode = EditLiveCommonStatic_generateAppletTag(1, 1, "kickstart", classpath, new Array(), "QuickStartApplet", params, paramValues, null, false);
        dalert(kickStartCode);
        writeToDocument(kickStartCode);
    }
    return javaInstalled;
}

function EditLiveCommonStatic_generateAppletTag(width, height, name, classpath, plugins, applet, paramNames, paramValues, preload, bForceUseTextArea) {
    classpath += "," + plugins;
    getEphoxPageID();
    // Set the JRE download URL if it hasn't already been set.
    if (sJREDownloadURL == "") {
        sJREDownloadURL = downloadPath + "j2re-1_4_2_05-windows-i586-p.exe";
    }
    
    var str = "";
    var index = paramNames.length
    var bUpgradeOSXError = false;
    var bLinuxError = false;
    
    if (IsWindows == true) {
        if(IsMSIE == true || IsOpera==true) {
            //OBJECT start tag
            str += '<object';
            str += ' classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"';
            str += ' width="' + width +'"';
            str += ' height="' + height +'"';
            str += ' name="' + name + '"';
            str += ' id="' + name + '"';
            
            if(bLocalDeploy) {
                if(sMinimumJREVersion == "1.5.0"){
                    str += ' codebase="' + sJREDownloadURL + '#Version=1,5,0"'
                } else 	if(sMinimumJREVersion == "1.4.2"){
                    str += ' codebase="' + sJREDownloadURL + '#Version=1,4,2"'
                } else 	if(sMinimumJREVersion == "1.4.1"){
                    str += ' codebase="' + sJREDownloadURL + '#Version=1,4,1"'
                } else {
                    str += ' codebase="' + sJREDownloadURL + '#Version=1,4,0"'
                }				
            } else {		
                //download list is at http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/autodl-files.html
                if(sMinimumJREVersion == "1.5.0"){
                    str += ' codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0_01-windows-i586.cab#version=1,5,0"'
                } else if(sMinimumJREVersion == "1.4.2"){
                    str += ' codebase="https://java.sun.com/update/1.4.2/jinstall-1_4_2_14-windows-i586.cab#Version=1,4,2"'
                } else if(sMinimumJREVersion == "1.4.1"){
                    str += ' codebase="https://java.sun.com/update/1.4.1/jinstall-1_4_1_07-windows-i586.cab#version=1,4,1"'
                } else {			
                    str += ' codebase="https://java.sun.com/update/1.6.0/jinstall-6u2-windows-i586.cab#Version=1,4,2"'
                }
            }
            
            str += '>';
            
            //Standard PARAM elements
            str += '<param name="code" value="' + applet + '" >';
            if (sMinimumJREVersion == "1.5.0"){
                str += '<param name="type" value="application/x-java-applet;version=1.5">';
            } else if (sMinimumJREVersion == "1.4.2"){
                str += '<param name="type" value="application/x-java-applet;version=1.4.2">';
            } else if(sMinimumJREVersion == "1.4.1"){
                str += '<param name="type" value="application/x-java-applet;version=1.4.1">';
            } else {
                str += '<param name="type" value="application/x-java-applet;version=1.4">';
            }
            str += '<param name="archive" value="' + classpath + '" >'; 
            str += '<param name="cache_option" value="Plugin" >';
            str += '<param name="cache_archive" value="' + classpath + '" >';
            str += '<param name="cache_archive_ex" value="' + classpath + '" >';
            str += '<param name="name" value="' + name + '" >';
            if(IsOpera) {
                str += '<param name="scriptable" value="true">';
            } else {
                str += '<param name="scriptable" value="false">';
            }
            str += '<param name="MAYSCRIPT" value="true">';
            str += '<param name="progressbar" value="true">';
            str += '<param name="boxmessage" value="' + eljLoadingMessage + '">';
            str += '<param name="UserAgent" value="' + escape(navigator.userAgent) +'">';
            str += '<param name="DebugLevel" value="' + sDebugLevel + '">';
            str += '<param name="Logger" value="' + sLogger + '">';
            str += '<param name="PageID" value="' + iPageID + '">';
            
            //Custom PARAM elements
            var index = 0;
            while(index < paramNames.length) {
                str += '<param';
                str += ' name="' + paramNames[index] + '"';
                str += ' value="' + paramValues[index] + '"'
                str += '>';
                index++;
            } //end while
            
            //OBJECT end tag
            str += '</object>';
            //Content Cache field
            str += EditLiveCommonStatic_getCacheField(name);
            
        } else if (IsNetscape == true) {
            //Start of EMBED start tag
            str += '<EMBED';
            
            //Standard attributes
            if (sMinimumJREVersion == "1.5.0"){
                str += ' type="application/x-java-applet;version=1.5"';
            } else if (sMinimumJREVersion == "1.4.2"){
                str += ' type="application/x-java-applet;version=1.4.2"';
            } else if(sMinimumJREVersion == "1.4.1"){
                str += ' type="application/x-java-applet;version=1.4.1"';
            } else {
                str += ' type="application/x-java-applet;version=1.4"';
            }
            str += ' code="' + applet + '" ';
            str += ' codebase="' + getURLbase() + '"';
            str += ' cache_archive_ex="' + classpath + '"';
            str += ' cache_archive="' + classpath + '"';
            str += ' archive="' + classpath + '"';
            str += ' cache_option="Plugin"';
            str += ' name="' + name + '"';
            str += ' id="' + name + '"';
            str += ' width="' + width + '"';
            str += ' height="' + height + '"';
            str += ' scriptable="true" ';
            str += ' MAYSCRIPT=true ';
            
            str += ' UserAgent="' + escape(navigator.userAgent) +'"';
            str += ' DebugLevel="' + sDebugLevel + '"';
            str += ' Logger="' + sLogger + '"';
            str += ' PageID="' + iPageID + '" ';
            
            //Custom attributes
            var index = 0;
            while(index < paramNames.length){
                //Attribute name
                str += paramNames[index];
                //Attribute value
                str += '="' + paramValues[index] + '" ';
                index++;
            } //end while
            
            //Java plug-in install instructions for Netscape
            str += ' pluginspage="' + getURLbase() + downloadPath + 'plugin-install.html"';
            
            //End of EMBED start tag
            str += '>';
            
            //NOEMBED element
            str += '<NOEMBED>';
            str += '</NOEMBED>';
            
            //EMBED end tag
            str += '</EMBED>';
            
            //Content Cache field
            str += EditLiveCommonStatic_getCacheField(name);
            
        } else {
            // Unknown windows browser.
            str = '';
        }
        
    } else if (IsMac == true) {
        if(IsOSX) {
            if (IsSafari == true || (AllowMacNetscape && IsNetscape)) {
                //Start APPLET start tag
                str += '<applet';
                
                //Standard attributes
                str += ' code="' + applet + '"';
                
                str += ' cache_archive="' + classpath + '"';
                str += ' cache_option="Plugin"';
                str += ' archive="' + classpath + '"';
                str += ' cache_archive_ex="' + classpath + '"';
                str += ' codebase="' + getURLbase() + '"';
                str += ' name="' + name + '"';
                str += ' id="' + name + '"';
                str += ' width="' + width + '"';
                str += ' height="' + height + '"';
                
                //End APPLET start tag
                str += ' MAYSCRIPT>';
                str += '<param name="cache_archive_ex" value="' + classpath + '">';
                //Custom PARAM elements
                var index = 0;
                while(index < paramNames.length) {
                    str += '<param';
                    str += ' name="' + paramNames[index] + '" ';
                    str += ' value="' + paramValues[index] + '"';
                    str += '>';
                    index++;
                } //end while
                
                str += '<param name="UserAgent" value="' + escape(navigator.userAgent) +'">';
                str += '<param name="DebugLevel" value="' + sDebugLevel + '">';
                str += '<param name="Logger" value="' + sLogger + '">';
                str += '<param name="progressbar" value="true">';
                str += '<param name="boxmessage" value="' + eljLoadingMessage + '">';
                str += '<param name="PageID" value="' + iPageID + '">';
                
                //write out window loc
                var sFrameLoc = "";
                var sTemp = ".";
                var wCurrent = self;
                var wParent = self.parent;
                while (wParent != wCurrent) {
                    
                    for (i = 0; i < wParent.length; i++) {
                        if (wParent.frames[i] == wCurrent) {
                            sTemp = (".frames[" + i + "]") + sTemp;
                        }
                    }
                    wCurrent = wParent;
                    wParent = wParent.parent;
                }
                sTemp = "window" + sTemp;
                if (window.parent != self) {
                    sFrameLoc = sTemp;
                }
                
                str += '<param name="JSWindowLoc" ';
                str += ' value="' + sFrameLoc + '"';
                str += '>';
                
                //APPLET end tag
                str +='</applet>';
                
                //Content Cache field
                str += EditLiveCommonStatic_getCacheField(name);
                
            } else {
                str = '';
            }
        } else {
            str = '';
        }
    } else if(IsSolaris == true) {
        if(IsNetscape == true) {
            //Start of EMBED start tag
            str += '<EMBED';
            
            //Standard attributes
            str += ' type="application/x-java-applet;version=1.4"';
            str += ' code="' + applet + '" ';
            str += ' cache_archive_ex="' + classpath + '"';
            str += ' codebase="' + getURLbase() + '"';
            str += ' cache_archive="' + classpath + '"';
            str += ' archive="' + classpath + '"';
            str += ' cache_option="Plugin"';
            str += ' name="' + name + '"';
            str += ' id="' + name + '"';
            str += ' width="' + width + '"';
            str += ' height="' + height + '"';
            str += ' scriptable="true" ';
            str += ' MAYSCRIPT=true ';
            str += ' UserAgent="' + escape(navigator.userAgent) +'"';
            str += ' DebugLevel="' + sDebugLevel + '"';
            str += ' Logger="' + sLogger + '"';
            str += ' PageID="' + iPageID + '"';
            
            
            //Custom attributes
            var index = 0;
            while(index < paramNames.length) {
                //Attribute name
                str += paramNames[index];
                //Attribute value
                str += '="' + paramValues[index] + '" ';
                index++;
            } //end while
            
            //Java plug-in install instructions for Netscape
            str += ' pluginspage="https://java.sun.com/products/plugin/index.html#download"';
            
            //End of EMBED start tag
            str += '>';
            
            //NOEMBED element
            str += '<NOEMBED>';
            str += '</NOEMBED>';
            
            //EMBED end tag
            str += '</EMBED>';
        } else {
            // Unsupported browser.
            str = '';
        }
    } else if (IsLinux == true) {
        if (IsNetscape == true) {
            //Start of EMBED start tag
            str += '<EMBED';
            
            //Standard attributes
            str += ' type="application/x-java-applet;version=1.4"';
            str += ' code="' + applet + '" ';
            str += ' cache_archive_ex="' + classpath + '"';
            str += ' codebase="' + getURLbase() + '"';
            str += ' cache_archive="' + classpath + '"';
            str += ' archive="' + classpath + '"';
            str += ' cache_option="Plugin"';
            str += ' name="' + name + '"';
            str += ' id="' + name + '"';
            str += ' width="' + width + '"';
            str += ' height="' + height + '"';
            str += ' scriptable="true" ';
            str += ' MAYSCRIPT=true ';
            str += ' UserAgent="' + escape(navigator.userAgent) +'"';
            str += ' DebugLevel="' + sDebugLevel + '"';
            str += ' Logger="' + sLogger + '"';
            str += ' PageID="' + iPageID + '"';
            
            
            //Custom attributes
            var index = 0;
            while (index < paramNames.length) {
                //Attribute name
                str += paramNames[index];
                //Attribute value
                str += '="' + paramValues[index] + '" ';
                index++;
            } //end while
            
            //Java plug-in install instructions for Netscape
            str += ' pluginspage="https://java.sun.com/products/plugin/index.html#download"';
            
            //End of EMBED start tag
            str += '>';
            
            //NOEMBED element
            str += '<NOEMBED>';
            str += '</NOEMBED>';
            
            //EMBED end tag
            str += '</EMBED>';
            
            //Content Cache field
            str += EditLiveCommonStatic_getCacheField(name);
            
        } else {
            // Unsupported browser.
            str = '';
        }
    } //end if
    
    if(bForceUseTextArea) {
        bUseTextArea = true;
        bUpgradeOSXError = false;
        bLinuxError = false;
        bShowErrorMessage = false;
        str = '';
    }
    if (str == '' && !preload) {
        if (bShowErrorMessage) {
            if(IsMac && !IsOSX){
                str += "<p>The minimum operating system required to run EditLive! on Apple Macintosh is MacOS X Update 10.1.1.<br>EditLive! only supports Safari. Please ensure you are using Safari to browse.</p>"
            } else if(IsLinux){
                str += "<p>EditLive! only supports Netscape Navigator 7.1 or Mozilla 1.4 running JRE 1.5.0 on Linux. Please ensure you are using the correct browser and JRE.</p>"
            } else {
                str += "<p>This system does not meet the minimum requirements to run EditLive!. Now using a textarea instead.</p>";
            }
        }
        str += EditLiveCommonStatic_getTextArea(paramNames, paramValues);
    }
    return str;
}

function EditLiveCommonStatic_getTextArea(paramNames, paramValues) {
    var str = "";
    str += '<textarea name="'+hiddenName+'" id="' + hiddenName + '" rows='+ iTARows +' cols='+ iTACols +'>';
    var index = 0;
    while(index < paramNames.length) {
        if(paramNames[index] == "Body" || paramNames[index] == "Document"){
            var docSource = paramValues[index];
            str += unescape(docSource.replace(/\+/gi, "%20"));
        }
        index++;
    } //end while
    str += '</textarea>';
    bUseTextArea = true;
    return str;
}

/** Create a field to use for the cache ID, and return it as a string
 *
 * @param name the name of the object this is a cache for
 * @return a string containing the cache field
 */
function EditLiveCommonStatic_getCacheField(name) {
    var str;
    //Using a hidden form field for the moment
    str = '<input';
    str += ' type="hidden"';
    str += ' id="' + name + '_cache"';
    str += '/>';
    return str;
}

/** Return the value of the cache field, populating it if it is empty
 *
 * @param name the name of the object to get the cache ID for
 * @return the value of the field, if it exists
 */
function EditLiveCommonStatic_getCacheFieldValue(id) {
    //wrapper in case we decide to change the type of field later
    var name = id;
    id += '_cache';
    var cacheElement = document.getElementById(id);
    if (cacheElement) {
        if (cacheElement.value.length == 0) {
            // new page, populate the value
            cacheElement.value = getEphoxPageID() + name;
        }
        return cacheElement.value;
    }
    return "";
}
function elj_exists(elementId){
    
    return document.getElementById(elementId)!=null;
}
function EditLiveCommonStatic_getAuxDiv() {
    if (!elj_exists("eLAuxDiv")) {
        return EditLiveCommonStatic_createDiv("eLAuxDiv");
    }
}

function EditLiveCommonStatic_createDiv(name) {
    var str = "";
    if(IsMSIE || IsSafari) {
        str += '<div id="' + name + '" name="' + name + '" width="1" height="1"></div>';
    }
    else {
        var version = navigator.appVersion;
        if(version.charAt(0) != "4") {
            str += '<div id="' + name + '" name="' + name + '"></div>';
        } else {
            //str += '<layer id="' + name + '" name="' + name + '"></layer>';
        } //end if
    } //end if
    return str;
}

function EditLiveCommonStatic_getEditorLayout(appletTag, borderStyle, width, height) {
    var str = "";
    if (IsMac) {
        str = '<table border="0" width="';
        str += width;
        str += '" height="';
        str += height;
        str += '" ><tr><td>';
        str += '<div style="';
        str += borderStyle;
        str += '">';
        str += appletTag;
        str += '</div>';
        var auxDiv = EditLiveCommonStatic_getAuxDiv();
        if (auxDiv) {
            str += '</td><td>';
            str += auxDiv;
        }
        str += '</td></tr></table>';
    } else {
        str = appletTag;
        if (borderStyle != "") {
            str = '<div style="' + borderStyle + '">' + str + '</div>';
        }
        var auxDiv = EditLiveCommonStatic_getAuxDiv();
        if (auxDiv) {
            str += auxDiv;
        }
    }
    return str;
}

EditLiveJava.prototype.getEditorLayout = function (appletTag, borderStyle, width, height) {
    var str = '<div style="width: ' + 
    eljGetAsCssLength(width) + 
    '; height: ' + eljGetAsCssLength(height) + '; ' + borderStyle + '">';
    str += appletTag;
    str += '</div>';
    var auxDiv = EditLiveCommonStatic_getAuxDiv();
    if (auxDiv) {
        str += auxDiv;
    }
    return str;
}

function eljGetAsCssLength(size) {
    if (typeof(size) != "string" || size.indexOf("%") < 0) {
        return size + "px";
    } else {
        return size;
    }
}

function EditLiveCommon_setUsername(text) {
    this.addParam("setUsername", text);
}

function EditLiveCommon_setShowButtonText(text) {
    this.addParam("showButtonText", text);
}

function EditLiveCommon_setShowButtonIconURL(url) {
    this.addParam("showButtonIconURL", url);
}

function EditLiveCommon_setHideButtonText(text) {	
    this.addParam("hideButtonText", text);
}

function EditLiveCommon_setHideButtonIconURL(url) {
    this.addParam("hideButtonIconURL", url);	
}

function EditLiveCommon_showAsButton(popout) {
    this.expressEdit = false;
    this.addParam("showAsButton", "true");
    this.addParam("popout", popout);
    this.show();
}

function EditLiveCommon_show(preserveContent) {
    dalert("Show");
    
    if (!this.checkExpressEdit()) {
        //set the preservation to true if it wasn't passed through
        if (preserveContent == undefined) {
            preserveContent = true;
        }
        writeToDocument(this.getAppletHTML(preserveContent));
        this.started = true;
        
        if (!bUseTextArea) {
            var fields = this.getHiddenFields();
            var i = 0;
            while (i < fields.length) {
                writeToDocument('<input name="' + fields[i] + '" id="' + fields[i] + '" type="hidden">');
                i++;
            }
        }		
    }
    
    if (this.bAutoSubmit) {
        EditLiveCommonStatic_getOnSubmit();
    }
    dalert("End Show");
}

EditLiveJava.prototype.getHiddenFieldString = function() {
    return '<input name="' + this.name + '" id="' + this.name + '" type="hidden">';
}

EditLiveJava.prototype.checkExpressEdit = function() {
    if (this.expressEdit && this.expressEdit != "false") {
        if (this.loadExpressEditor()) {
            return true;
        }
    }
    return false;
}

/********************************************************
 Write to onSubmit
 *********************************************************/
function EditLiveCommonStatic_getOnSubmit(){
    var name = hiddenName;
    dalert("getOnSubmit: " + name);
    
    if(!bOnsubmit && EditLiveCommonStatic_isSupportedBrowser()){
        var bFound = false;
        bOnsubmit = true;
        //find form where ELJ exists
        var sAppletName = name;
        for(var formsIndex = 0; formsIndex < document.forms.length; formsIndex++){
            for(var elementsIndex = 0; elementsIndex < document.forms[formsIndex].elements.length; elementsIndex++){
                if(document.forms[formsIndex].elements[elementsIndex].name == sAppletName){
                    //found the form
                    fOnSubmit = document.forms[formsIndex].onsubmit;
                    document.forms[formsIndex].onsubmit = EditLiveCommonStatic_GetContent;
                    bFound = true;
                    dalert("Attached to onsubmit.");
                } 
                if(bFound){
                    break;
                }
            } //end for
            if(bFound){
                break;
            }
        } //end for
    } //end if
} //getOnSubmit

function EditLiveCommonStatic_getThisForm() {
    var name = hiddenName;
    var bFound = false;
    bOnsubmit = true;
    //find form where ELJ exists
    var sAppletName = name;
    for(var formsIndex = 0; formsIndex < document.forms.length; formsIndex++){
        for(var elementsIndex = 0; elementsIndex < document.forms[formsIndex].elements.length; elementsIndex++){
            if(document.forms[formsIndex].elements[elementsIndex].name == sAppletName){
                //found the form
                bFound = true;
                return document.forms[formsIndex];
            } 
            if(bFound){
                break;
            }
        } //end for
        if(bFound){
            break;
        }
    } //end for
}

function EditLiveCommonStatic_submitFunction() {
    setTimeout("EditLiveCommonStatic_doSubmit()", 100);
}

function EditLiveCommonStatic_doSubmit() {
    dalert("SubmitFunction");
    if(!IsMSIE && !IsSafari) {
        var version = navigator.appVersion;
        if(version.charAt(0) == "4") {
            wNewWindow.close();
        }
    }
    var sAppletName = hiddenName;
    for(var formsIndex = 0; formsIndex < document.forms.length; formsIndex++){
        for(var elementsIndex = 0; elementsIndex < document.forms[formsIndex].elements.length; elementsIndex++){
            if(document.forms[formsIndex].elements[elementsIndex].name == sAppletName){
                //found the form
                if(fOnSubmit == null) {
                    var submitIsObject;
                    if (IsNetscape) {
                        submitIsObject = ((typeof document.forms[formsIndex].submit) == "object");
                    } else {
                        if ((document.forms[formsIndex].submit.id == 'submit') || (document.forms[formsIndex].submit.name == 'submit')) {
                            submitIsObject = true;
                        } else {
                            submitIsObject = false;
                        }
                    }
                    if(submitIsObject){
                        document.forms[formsIndex].onsubmit=null;
                        document.forms[formsIndex].submit.click();
                    } else {
                        document.forms[formsIndex].submit();
                    }
                    bGetContent = false;					
                } else {
                    var rVal = fOnSubmit();
                    if(rVal != false) {
                        var submitIsObject = false;
                        var submitIsAnArray = false;
                        if (IsNetscape) {
                            submitIsObject = ((typeof document.forms[formsIndex].submit) == "object");
                            submitIsAnArray = document.forms[formsIndex].submit.length > 0;
                        } else {
                            submitIsObject = ((document.forms[formsIndex].submit.id == 'submit') || (document.forms[formsIndex].submit.name == 'submit'));
                            submitIsAnArray = typeof(document.forms[formsIndex].submit.length) != "undefined";
                        }
                        if (submitIsAnArray) {
                            document.forms[formsIndex].onsubmit=null;
                            document.forms[formsIndex].submit[0].click();
                        } else if (submitIsObject){
                            document.forms[formsIndex].onsubmit=null;
                            document.forms[formsIndex].submit.click();
                        } else {
                            document.forms[formsIndex].submit();
                        }
                    }
                    bGetContent = false;
                }
                
            }
        }
    }
}

/********************************************************
 Form submitting functions
 *********************************************************/

function EditLiveCommonStatic_runPostApplet(paramNames, paramValues) {
    
    if(IsMSIE) {
        document.all.item("eLAuxDiv").innerHTML = "";
    } //end if
    
    var appletName = '';
    var appletClass = 'com.ephox.editlive.java2.POSTApplet.class';
    var appletWidth = 1;
    var appletHeight = 1;
    if (IsMac) {
        appletHeight = 90;
    }
    
    
    var appletTag = EditLiveCommonStatic_generateAppletTag(appletWidth, appletHeight, appletName, classpath, plugins, appletClass,
    paramNames, paramValues, downloadPath, false, false);
    
    if (IsWindows && IsMSIE) {
        var myDiv = document.getElementById("eLAuxDiv");
        myDiv.innerHTML = appletTag;
    } else if (IsMSIE) {
        document.all.item("eLAuxDiv").innerHTML = appletTag;
    } else {
        var version = navigator.appVersion;
        if(version.charAt(0) == "4" && !IsSafari) {
            wNewWindow = window.open('','EditLive','width=' + 1 + ',height=' + 1 +',status=no,resizable=no,scrollbars=no,location=no,toolbar=no');
            wNewWindow.document.open();
            wNewWindow.document.write(appletTag);
            wNewWindow.document.close();
        } else {
            var myDiv = document.getElementById("eLAuxDiv");
            myDiv.innerHTML = appletTag;
        } //end if
    } //end if
}

function EditLiveCommonStatic_GetContent() {
    //check if an EditLive! applet exists
    var applet = EditLiveCommonStatic_GetAppletWithName(hiddenName + "_elj");
    
    // applet does not exist in the page. The user may be using the javascript
    // QuickEdit editor.
    if(applet == null) {
        // return true to ensure the onsubmit function continues to process
        return true;
    } else {
        dalert("Get Content");
        if(bGetContent){
            dalert("Already getting content.");
            return false;
        } //end if
        bGetContent = true;
        
        if (eljUseLiveConnect) {
            if (checkSupportsLiveConnect(hiddenName + "_elj")) {
                applet.processSubmit(getEphoxPageID());
                return false;
            }
        }
        var paramNames = new Array();
        var paramValues = new Array();
        
        paramNames[0] = "GetContent";
        paramValues[0] = "true";
        
        EditLiveCommonStatic_runPostApplet(paramNames, paramValues);
        return false;	
    }
}

function EditLiveCommon_setBorderStyle(style) {
    this.borderStyle = style;
}

//**************************** Support Functions ***********************
//This function is a regular combineURL but to make life easier it uses window.location.href
// as the absolute URL so we can use things like window.location.hostname instead of writing
// those functions somewhere else.
function combineDownloadURL( sDirectory ) {
    
    var relURL = sDirectory;
    
    //every other reference in this file assumes downloadDirectory has no
    // trailing "/".  Rather than try to fix everywhere else, we'll just
    // rip out the trailing "/" if it is there.
    if (relURL.charAt(relURL.length - 1) == "/") {
        relURL = relURL.substr(0, relURL.length - 1);
    }
    
    
    //if relURL is absolute, forget about combining
    if (relURL.indexOf("://") != -1) return relURL;
    
    //we only want the path of the URL
    var absURL = removeFilename(window.location.href);
    
    //do the combining work
    switch(relURL.charAt(0)) {
        
        //relative to hostname
        case '/':
            return window.location.protocol + "//" +
            window.location.hostname + relURL;
            break;
            
            //relative to absolute path
        case '.':
            var sOldURL;
            //cycle through relURL ripping directories off the absURL as we
            // go up
            while(relURL.substr(0,3) == "../") {
                sOldURL = absURL;
                absURL = absURL.substring(0, absURL.lastIndexOf('/'));
                relURL = relURL.substr(relURL.indexOf('/') + 1);
                //if the final two chars are "//" then the relative
                // URL goes back too many folders, undo the previous rip
                if (absURL.charAt(absURL.lastIndexOf('/') - 1) == ':') {
                    absURL = sOldURL
                }
            }
            return absURL + "/" + relURL;
            break;
            
            //is a subdir of the current dir
        default:
            return absURL + "/" + relURL;
            break;
    }
    
}

//get the main path of the URL, minus the xx.htm etc
function removeFilename( sURL ) {
    if (sURL.lastIndexOf('.') > sURL.lastIndexOf('/')) {
        return sURL.substring(0, sURL.lastIndexOf('/'));
    } else {
        return sURL;
    }
}

//Set value for hidden form field

function setFormValue(sName, sValue) {
    dalert("Set form item: " + sName + " to " + sValue);
    for(var formsIndex = 0; formsIndex < document.forms.length; formsIndex++){
        for(var elementsIndex = 0; elementsIndex < document.forms[formsIndex].elements.length; elementsIndex++){
            if(document.forms[formsIndex].elements[elementsIndex].name == sName){
                document.forms[formsIndex].elements[elementsIndex].value=sValue;
            } 
        } //end for
    } //end for
    return false;
} //setFormValue



function eljTransferFocus() {
    var myDiv;
    if(IsMSIE) {
        myDiv = document.all.item("eLAuxDiv");
    }
    else {
        var version = navigator.appVersion;
        if(version.charAt(0) == "4") {
            myDiv = document.ids.eLAuxDiv;
        } else {
            myDiv = document.getElementById("eLAuxDiv");
        } //end if
    }
    
    // Find the next element we can focus on.
    if (IsMSIE) {
        var parent = myDiv.parentElement;
        var num = myDiv.sourceIndex + 1;
        var nextElem = document.all[num];
        while (!isFocusable(nextElem)) {
            num++;
            nextElem = document.all[num];
        }
        nextElem.focus();
    } else {
        var parent = myDiv.parentNode;
        var foundFocusable = false;
        while (!foundFocusable) {
            var i = 0;
            var foundMyDiv = false;
            var firstDivMatch = true;
            while (i < parent.childNodes.length && !foundFocusable) {
                var child = parent.childNodes[i];
                if (child == myDiv) {
                    foundMyDiv = true;
                }
                if (foundMyDiv) {
                    if (firstDivMatch) {
                        firstDivMatch = false;
                    } else {
                        var focusable = eljSearchTree(child);
                        if (focusable) {
                            myDiv = focusable;
                            foundFocusable = true;
                            break;
                        }
                    }
                }
                i++;
            }
            if (!foundFocusable) {
                myDiv = parent;
                parent = parent.parentNode;
            }
        }
        
        //alert(myDiv.tagName);
        //var win2 = window.open('','EditLive','width=' + 1 + ',height=' + 1 +',status=no,resizable=no,scrollbars=no,location=no,toolbar=no');
        //win2.close();
        myDiv.focus();
    }
}

function getURLbase() {
    var src = window.location.href;
    var indLoc = src.lastIndexOf("/");
    var URLBase = src.substr(0, indLoc + 1);
    
    strPath = new String(document.location);
    strPath = strPath.substr(0, strPath.lastIndexOf("/") + 1);
    
    return URLBase;
}

function getScriptBase(scriptName) {
    scriptName = scriptName.toLowerCase();
    var scriptArray = document.getElementsByTagName("script");
    if (scriptArray && scriptArray.length) {
        for (i = 0; i < scriptArray.length; i++) {
            var scriptElement = scriptArray[i];
            if (scriptElement.src && scriptElement.src.toLowerCase().indexOf(scriptName) > -1) {
                return scriptElement.src.substring(0, scriptElement.src.lastIndexOf("/") + 1); 
            }
        }
    }
}

function dalert(message) {
    if (DEBUG) {
        alert(message);
    }
}

//DOM manipulation methods
function writeToDocument(htmlString) {
    document.write(htmlString);
}

function appendChild(parent, newNode) {
    parent.appendChild(newNode);
}

function replaceNode(existingNode, newNode) {
    existingNode.parentNode.insertBefore(newNode, existingNode);
    existingNode.parentNode.removeChild(existingNode);
}
