// Global variables ---------------------------------------------------------

DAYS_TILL_COOKIE_EXPIRY = 30;

ftp = null;
protocolSelect = null;
remoteHostTextBox = null;
userNameTextBox = null;
passwordTextBox = null;
connectButton = null;
initialConnectButtonText = null;
onloadCalled = false;
initialRemoteDir = null;

advancedButton = null;      // full-page only
advancedRow = null;         // full-page only
localFrame = null; 		// full-page only
localDirTextBox = null; 	// full-page only
localGoButton = null; 	// full-page only
localNewButton = null; 	// full-page only
remoteFrame = null; 		// full-page only
remoteDirTextBox = null; // full-page only
remoteGoButton = null; 	// full-page only
remoteNewButton = null; 	// full-page only

localListBox = null; 	// gadget only
remoteListBox = null; 	// gadget only


// Window ---------------------------------------------------------------------

window.onload = function() {
    onloadCalled = true;
    window_onload();
}

function window_onload() {
    var passwordArg = getUrlArg("pass");
    var remoteDirArg = getUrlArg("dir");
    var autoConnectArg = getUrlArg("connect");

    document.getElementById("password").focus();

    // get references to controls
    passwordTextBox = document.getElementById("password");
    connectButton = document.getElementById("connectButton");
    initialConnectButtonText = connectButton.value;
    statusBar = document.getElementById("statusBar");
    statusBarInitColor = statusBar.style.backgroundColor;

    // full-page only
    advancedButton = document.getElementById("advancedButton");
    advancedRow = document.getElementById("advancedRow");
    localFrame = window.frames.localFiles;
    if (localFrame === undefined) {
        localFrame = null;
    }
    localDirTextBox = document.getElementById("localDirTextBox");
    localGoButton = document.getElementById("localGoButton");
    localNewButton = document.getElementById("localNewButton");
    remoteFrame = window.frames.remoteFiles;
    if (remoteFrame === undefined) {
        remoteFrame = null;
    }
    remoteDirTextBox = document.getElementById("remoteDirTextBox");
    remoteGoButton = document.getElementById("remoteGoButton");
    remoteNewButton = document.getElementById("remoteNewButton");

    // gadget only
    localListBox = document.getElementById("localListBox");
    if (localListBox !== null) {
        fixElementSize(localListBox);
        localListBox.setAttribute('autocomplete', 'off');
    }
    remoteListBox = document.getElementById("remoteListBox");
    if (remoteListBox !== null) {
        fixElementSize(remoteListBox);
        remoteListBox.setAttribute('autocomplete', 'off');
    }

    // create the FTPClient and hook up the event-handlers
    ftp = new FTPClient();
    registerFTPEvents(ftp);

    localEnabled(false);
    remoteEnabled(false);

    if (passwordTextBox.value !== "")
        connect_clicked();
};

window.onunload = function() {
};

window.onerror = function(message, url, line) {
    setStatus("Error: " + message, false, true);
    alert(message + "\n" + url + " " + line);
    // error('Error on line ' + line + ' of document ' + url + ': ' + message, FVL_FATAL);
    return true;
};

function options_clicked() {
    var options = document.getElementById("options");
    if (parseInt(options.style.height) < 100) {
        options.style.height = 100;
        options.style.visibility = "visible";
    } else {
        options.style.height = 0;
        options.style.visibility = "hidden";
    }
}

// Connect ----------------------------------------------------------

function connect_clicked() {
    if (!navigator.javaEnabled()) {
        if (confirm("You need to have Java installed and enabled to use Integral FTP.  Would you like instructions on how to do this?")) {
            window.location = "http://www.integralftp.com/help/enablingJava.html";
        }
        return;
    }
    if (!onloadCalled) {
        window_onload();
    }

    // perform the initialization
    if (!ftp._initComplete) {
        setStatus("Starting FTP engine...", false);
        connectButton.disabled = true;
        setTimeout("initialize()", 100);
    } else if (!ftp.isConnected()) {
        if (passwordTextBox.value.trim() == "") {
            ftp.alert("Please enter the password");
            return;
        }
        ftp.protocol = "ftp";
        ftp.remoteHost = "ftp.branch-associates.com";
        ftp.userName = queryString("UID");
        ftp.password = passwordTextBox.value;
        ftp.dateLanguages = "en_US,es_ES,fr_FR,de_DE";
        try {
            ftp.connect();
            connectButton.value = "Connecting...";
            connectButton.disabled = true;
            setStatus("Connecting to " + ftp.remoteHost + "...", false);
        } catch (e) {
            // if (typeof(e)=="string" && e.toLowerCase().indexOf("license"))
            //     alert("License Error\nThis product is licensed for \'" + licenseDomain 
            //     + "\'.\nThe current domain is \'" + window.location.hostname + "\'.")
            // else
            alert(e);
        }
    } else {
        ftp.disconnect();
        connectButton.value = "Disconnecting...";
        connectButton.disabled = true;
        setStatus("Disconnecting from " + ftp.remoteHost + "...", false);
    }
}

function onMessageBoxClosed(response, tag) {
    alert(response.getResponse() + " " + tag);
}

function initialize() {
    ftp.initialize(getURLBase() + "/IntegralFTP.jar", true, "DEBUG", false);
}

function passwordTextBox_KeyPress(ev) {
    if (enterPressed(ev) && readyToConnect())
        connect_clicked();
}

function readyToConnect() {
    if (passwordTextBox === null)
        return false;
    return passwordTextBox.value.trim().length > 0;
}

function toggleAdvanced() {
    if (advancedRow.style.display == "none") {
        advancedRow.style.display = "block";
        advancedButton.value = "Hide Options"
    } else {
        advancedRow.style.display = "none";
        advancedButton.value = "Show Options"
    }
}

// Various methods ------------------------------------------------------

// Helpers -------------------------------------------------------------

function enterPressed(ev) {
    var keyCode = null;
    if (window.event) {
        keyCode = window.event.keyCode;
    } else if (ev) {
        keyCode = ev.which;
    }
    return (keyCode === 13);
}

function renderFileListBox(listBox, fileList) {
    while (listBox.length > 0) {
        listBox.remove(0);
    }
    for (i in fileList.files) {
        var file = fileList.files[i];
        var option = new Option();
        if (file.isDirectory) {
            if (file.name !== "")
                option.text = "<dir> " + file.name;
            else
                option.text = "<dir> " + file.path;
        } else {
            option.text = file.name;
        }
        option.value = file.path !== null ? file.path : file.name;
        try {
            listBox.add(option, null);  // JavaScript
        } catch (ex) {
            listBox.add(option);  // JScript
        }
    }
}

function fixElementSize(element) {
    if (element.offsetHeight !== undefined) {
        element.style.width = element.offsetWidth;
        element.style.height = element.offsetHeight;
    } else if (element.style.pixelWidth !== undefined) {
        element.style.width = element.style.pixelWidth;
        element.style.height = element.style.pixelHeight;
    }
}

function getURLBase() {
    var urlBase = location.href;
    if (urlBase.indexOf("?") >= 0) {
        urlBase = urlBase.substring(0, urlBase.indexOf("?"));
    }
    return urlBase.substring(0, urlBase.lastIndexOf("/"));
}

function getUrlArg(argName) {
    argName = argName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + argName + "=([^&#]*)");
    var results = regex.exec(window.location.href);
    return results == null ? "" : results[1];
}

function renderImageLink(doc, imageName, imageAlt, functionName, fileName, filePath) {
    doc.writeln("<td class='ftpFile ftpOptions'>");
    var methodCall = "javascript:parent." + functionName + "('" + fileName + "')";
    if (filePath === null) {
        methodCall = "javascript:parent." + functionName + "('" + fileName + "')";
    } else {
        methodCall = "javascript:parent." + functionName + "('" + fileName + "', '" + filePath + "')";
    }
    doc.write("<a href=\"" + methodCall + "\">");
    doc.write("<img style='width:16px;height:16px;border:none'");
    imageAlt = imageAlt.replace("this file", "\\\'" + fileName + "\\\'")
    imageAlt = imageAlt.replace("this directory", "\\\'" + fileName + "\\\'")
    doc.write(" src='" + imageName + "' alt='" + imageAlt + "'");
    doc.write(" onmouseover=\"javascript:parent.setToolTip('" + imageAlt + "')\"");
    doc.write(" onmouseout=\"javascript:parent.clearToolTip()\">")
    doc.writeln("</a>");
    doc.writeln("</td>");
}


// 
// Create Array of Passed Parms for page
//
function PageQuery(q) {
    if (q.length > 1)
        this.q = q.substring(1, q.length);
    else
        this.q = null;

    this.keyValuePairs = new Array();
    if (q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }

    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    this.getValue = function(s) {
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            if (this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }

    this.getParameters = function() {
        var a = new Array(this.getLength());
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }

    this.getLength = function() { return this.keyValuePairs.length; }
}

//
// Get Parm Value Passed to Page
//
function queryString(key) {
    var page = new PageQuery(window.location.search);
    return unescape(page.getValue(key));
}
