// 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 remoteHostArg = getUrlArg("server");
    var protocolArg = getUrlArg("protocol");
    var userArg = getUrlArg("user");
    var passwordArg = getUrlArg("pass");
    var remoteDirArg = getUrlArg("dir");
    var autoConnectArg = getUrlArg("connect");
    
    if (userArg=="anonymous" || userArg=="ftp")
        passwordArg = "anonymous";

	// get references to controls
	protocolSelect = document.getElementById("protocol");
	remoteHostTextBox = document.getElementById("remoteHost");
	userNameTextBox = document.getElementById("userName");
	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);
	
    if (protocolArg!==null && protocolArg!=="")
        setSelectValue(protocolArg, protocolSelect, 0);
    else 
        setSelectToCookieValue("protocol", protocolSelect, 0);
	if (remoteHostArg!==null && remoteHostArg!=="")
        remoteHostTextBox.value = remoteHostArg;
    else 
        setTextBoxToCookieValue("remoteHost", remoteHostTextBox);
	if (remoteHostTextBox.value!=="") {
		remoteHostTextBox.style.backgroundImage = "";
	}	
	if (userNameTextBox!==null) {
		if (userArg!==null && userArg!=="")
            userNameTextBox.value = userArg;
        else 
            setTextBoxToCookieValue("userName", userNameTextBox);
	}
    if (passwordArg!==null && passwordArg!=="")
        passwordTextBox.value = passwordArg;
	if (localDirTextBox!==null) {
		setTextBoxToCookieValue("localDir", localDirTextBox);
	}
	if (remoteDirTextBox!=null && remoteDirArg!==null)
	   remoteDirTextBox.value = remoteDirArg;
	
	localEnabled(false);
	remoteEnabled(false);
	
	if (remoteHostTextBox.value!==""
	    && userNameTextBox.value!==""
	    && passwordTextBox.value!==""
	    && autoConnectArg!=="no")
	    connect_clicked();
};

window.onunload = function() {
    if (protocolSelect!==null) {
        setCookie("protocol", protocolSelect.options[protocolSelect.selectedIndex].value);
    }
	if (remoteHostTextBox!==null) {
		setCookie("remoteHost", remoteHostTextBox.value);
	}
	if (userNameTextBox!==null) {
		setCookie("userName", userNameTextBox.value);
	}
//	if (passwordTextBox!==null) {
//		setCookie("password", passwordTextBox.value);
//	}
	if (localDirTextBox!==null) {
		setCookie("localDir", localDirTextBox.value);
	}
};

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 (remoteHostTextBox.value.trim()=="") {
			ftp.alert("Please enter the server address");
			return;
		}
		if (userNameTextBox.value.trim()=="") {
			ftp.alert("Please enter the user-name");
			return;
		}
		if (passwordTextBox.value.trim()=="") {
			ftp.alert("Please enter the password");
			return;
		}
		if (!ftp.isRemoteHostValid(remoteHostTextBox.value)) {
			ftp.alert("Invalid server address: must be of the form 'address[:port]'");
		}
		ftp.protocol = protocolSelect.options[protocolSelect.selectedIndex].value;
		ftp.remoteHost = remoteHostTextBox.value;
		ftp.userName = userNameTextBox.value;
		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 remoteHostTextBox_KeyPress(ev) {
	if (enterPressed(ev) && readyToConnect())
		connect_clicked();
}

function userNameTextBox_KeyPress(ev) {
	if (enterPressed(ev) && readyToConnect())
		connect_clicked(ev);
}

function passwordTextBox_KeyPress(ev) {
	if (enterPressed(ev) && readyToConnect())
		connect_clicked();
}

function readyToConnect() {
	if (remoteHostTextBox===null || userNameTextBox===null || passwordTextBox===null)
		return false;
	return remoteHostTextBox.value.trim().length>0
		&& userNameTextBox.value.trim().length>0
		&& 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>");
}
