dojo.require("dojo.debug.console");
dojo.require("dojo.lang.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.Menu2");
dojo.require("dojo.widget.Dialog");
dojo.require("dojo.widget.LayoutContainer");
dojo.require("dojo.widget.FloatingPane");
dojo.require("dojo.widget.ContentPane");
dojo.require("dojo.widget.SplitContainer");
dojo.require("dojo.widget.Tree");
dojo.require("dojo.widget.TreeCommon");
dojo.require("dojo.widget.TreeRPCController");
dojo.require("dojo.widget.TreeSelector");
dojo.require("dojo.widget.TreeNode");
dojo.require("dojo.rpc.JsonService");
dojo.require("dojo.Deferred");

// Blueprint (SMD) for JSON-RPC methods for Dojo. All methods call the save service URL, and are differentiated by the "method" block function name
var jsonRPCMethods =
{	"serviceType":"JSON-RPC", "serviceURL":"cgi?action=getJSONRPC",
	"methods":[
		{	// GetFileList retrieves a listing of files for a specific share/directory
			"name":"GetFileList",
			"parameters":[ { "name":"requestPath" } ]
		}
	]
};

//******************************************************
// Flash MP3 Player
//******************************************************
var newMP3PlayerWindow;
function OpenMP3Player(recursive) {
	var playlistLogin = (server_LoggedInUser != "") ? "yes" : "no";
	var playlistRecursive = (recursive) ? "yes" : "no";
	var thisUrl = document.URL.split('/')[0] + "//" + document.URL.split('/')[2] + "/";
	
	var playlistUrl = "?playlist_url=" + currentDirectory + "&recursive=" + playlistRecursive +
		"&login=" + playlistLogin + "&incomingUrl=" + thisUrl;
	newMP3PlayerWindow = window.open('/audioplayer/extended/xspf_player.swf' + playlistUrl,'',
	'scrollbars=no,menubar=no,height=200,width=400,resizable=yes,toolbar=no,location=no,status=no');
	setTimeout('RenameMP3PlayerWindow()',200);
}
function RenameMP3PlayerWindow() {
//	newMP3PlayerWindow.document.title = "LinkStation Player";
	return;
}
//******************************************************
// END Flash MP3 Player
//******************************************************

//******************************************************
// GetFileList Method and FileListPane/DirTree Integration
//******************************************************
// This var contains the current working directory. It is set when a user clicks on a dir from the tree
var currentDirectory;
// This var contains an array of booleans, corresponding to each current file in the FileListPane. Its value is whether or not they are currently visible.
var fileListVisible;
var noChangeVisible = false;
// Gets the file listing back from the server, and creates content for fileListPane
function jsonGetFileList_CallBack(fileInfo) {
	// Reset the visible array
	fileListVisible = new Array();
	
	// Create table for fileListPane
	var fileListPaneContent = '<table width=100% style="border: 1px;">';
	fileListPaneContent +=
		'<tr class="header"><td width="24px"></td><td width="75%">Name</td><td>Type</td><td>Size</td></tr>';
	
	// Iterate through files (result is an array of file objects, each object with props: fileName, isDirectory, and fileSize)
	for (x=0; x<fileInfo.length; x++) {
		var fileType;				// array for file info (icon, type name, open window)
		var quickOpenHrefPath;		// quick open link
		var quickOpenJSHider = "";	// hides 'javascript' in the status bar
		
		// Make default visible status false
		fileListVisible[x] = false;
		
		// Create function and file info for directory
		if (fileInfo[x].isDirectory) {
			fileType = ["folder.gif", "Folder", ""];
			fileInfo[x].fileSize = "";
			
			quickOpenHrefPath = "javascript:moveDirTreeFromFileList('" +
					currentDirectory + fileInfo[x].fileName + "');";
			quickOpenJSHider = ' onmouseover=\'window.status="";return true;\'';
		}
		// Create href path and file info for file
		else {
			fileType = GetFileType(fileInfo[x].fileName);
			
			// 2007/10/12 y-okumura add
			fileInfo[x].fileName2 = encodeURI(fileInfo[x].fileName);
			currentDirectory2 = encodeURI(currentDirectory);
			quickOpenHrefPath = "/shares/" + currentDirectory2.split(":")[0] +
					currentDirectory2.split(":")[1] + fileInfo[x].fileName2;
		}
		
		// Get the file details for the details pane
		var fileDetails = GetFileDetails(fileInfo[x].fileName,
						fileInfo[x].isDirectory,
						currentDirectory,
						fileType[2]);
		
		// Create Row for file
		var row = '<tr onclick=\'ChangeFileListVisible(this,' + x + ')\'>';
		row += '<td><img src="/images/icons/' + fileType[0] + '"></td>';
		row += '<td>' +	fileInfo[x].fileName +
				' <a style="font-size:70%;color:#a11a11;" href="' + quickOpenHrefPath +
				'" target="' + fileType[2] + '" onclick="noChangeVisible=true;">open</a>' +
				'</td>';
		row += '<td>' + fileType[1] + '</td>';
		row += '<td>' + fileInfo[x].fileSize + '</td></tr>';
		row += '<tr id="fileListNumber' + x +
			'" style="display:none"><td class="fileDetailsLeftBorder">&nbsp</td><td class="fileDetails">' +
			fileDetails + '</td><td class="fileDetailsRightBorder">&nbsp</td><td></td></tr>';
		
		// Add row to table
		fileListPaneContent += row;
	}
	fileListPaneContent += "</table>";
	dojo.widget.getWidgetById("fileListPane").setContent(fileListPaneContent);
}
var jsonMethods = new dojo.rpc.JsonService({smdObj: jsonRPCMethods});

// Changes the visible status of a file listing
function ChangeFileListVisible(startingElement, fileNumber) {
	if (noChangeVisible) { noChangeVisible = false; return; }
	if (fileListVisible[fileNumber]) {
		document.getElementById("fileListNumber" + fileNumber).style.display = "none";
		fileListVisible[fileNumber] = false;
	}
	else {
		document.getElementById("fileListNumber" + fileNumber).style.display = "";
		fileListVisible[fileNumber] = true;
	}
}

// Displays file listings in file list pane
function displayFileList() {
	this.update = function(message) {
		// Set currentDirectory to objectId
		currentDirectory = message.node.objectId;
		// Expand current tree directory (if possible)
		var currentNode = dojo.widget.manager.getWidgetById('dirTreeSelector').selectedNode;
		currentNode.onTreeClick();
		currentNode.expand();
		// Ask server for the file listing
		jsonMethods.GetFileList(message.node.objectId).addCallback(jsonGetFileList_CallBack);
	};
}
// Sets up the above displayFileList function as a listener to the directory tree
dojo.event.topic.getTopic("listSelected").subscribe(new displayFileList(), "update");

// Moves the currently selected node in the tree if a user clicks on a directory
function moveDirTreeFromFileList(childObjectId) {
	var dirSelector = dojo.widget.manager.getWidgetById('dirTreeSelector');
	var childDirs = dirSelector.selectedNode.children;
	for (x=0; x<childDirs.length; x++) {
		if (childDirs[x].objectId == (childObjectId + '/')) {
			// Select Child Node
			dirSelector.deselect();
			dirSelector.doSelect(childDirs[x]);
			// Expand current tree directory (if possible)
			dirSelector.selectedNode.onTreeClick();
			dirSelector.selectedNode.expand();
			// Set currentDirectory to objectId
			currentDirectory = dirSelector.selectedNode.objectId;
			// Update FileListPane
			jsonMethods.GetFileList(dirSelector.selectedNode.objectId).addCallback(jsonGetFileList_CallBack);
		}
	}
}
//******************************************************
// END GetFileList Method and FileListPane/DirTree Integration
//******************************************************

// Test function
function WebAxsTest () {
}

//******************************************************
// Setup Functions
//******************************************************
// Login button / indicator in top left of client
function SetupLoginArea() {
	var loginAreaContent =
		"<div style=\"padding-top:10px;\"><a style=\"color:black;\" href=\"/login/\">" +
			server_login_Login + "</a></div>";
	if (server_LoggedInUser != "")
		loginAreaContent = "<div style=\"padding-top:10px;color:black;text-decoration:underline\">" +
			server_login_LoggedIn + " " + server_LoggedInUser + "</div>";
	dojo.widget.byId("logoDiv").setContent(loginAreaContent);
}

// Checks to make sure there are shares available -- otherwise, displays no share message box
function CheckForNoShares() {
	if (dojo.widget.byId("dirTree").getDescendants().length <= 1) {
		dojo.widget.byId("shareDialogPane").setContent("No shares available for " + server_LoggedInUser);
		dojo.widget.byId("shareDialog").show();
	}
}
// Auto-navigates to the correct starting directory
function GotoStartDir () {
	var dirSelector = dojo.widget.manager.getWidgetById('dirTreeSelector');
	var dirTree = dojo.widget.byId("dirTree");
	
	if (server_StartingDirectory) {
		// Add trailing slash to starting dir if none exists
		if (server_StartingDirectory[server_StartingDirectory.length-1] != '/') server_StartingDirectory += "/";
		// Find the first node to go to
		var children = dirTree.getChildrenOfType('TreeNode');
		for (x=0; x<children.length; x++) {
			if (server_StartingDirectory.indexOf(children[x].objectId) == 0) {
				dirSelector.doSelect(children[x]);
				dirSelector.selectedNode.onTreeClick();
				dirSelector.selectedNode.expand();
				// Use FindDir to recursively go through the rest
				FindDir();
			}
		}
	}
	else {
		// If no preference, select the top share, and open it
		dirSelector.doSelect(dirTree.getChildrenOfType('TreeNode')[0]);
		ExpandDir();
	}	
}
// Expands the currently selected dir, shows info on the FileListPane
function ExpandDir() {
	var dirSelector = dojo.widget.manager.getWidgetById('dirTreeSelector');
	// Expand current tree directory (if possible)
	dirSelector.selectedNode.onTreeClick();
	dirSelector.selectedNode.expand();
	// Set currentDirectory to objectId
	currentDirectory = dirSelector.selectedNode.objectId;
	// Update FileListPane
	jsonMethods.GetFileList(dirSelector.selectedNode.objectId).addCallback(jsonGetFileList_CallBack);
}
// Recursively finds a directory
function FindDir () {
	var dirSelector = dojo.widget.manager.getWidgetById('dirTreeSelector');
	// If dir info not loaded yet, call function again
	if (dirSelector.selectedNode.state != "LOADED") { setTimeout('FindDir()',100); return; }
	// If we have found the directory, expand it and stop
	if (dirSelector.selectedNode.objectId == server_StartingDirectory) { ExpandDir(); return; }
	// Otherwise, iterate through the dir's children to find the next node to go down
	var children = dirSelector.selectedNode.children;
	for (x=0; x<children.length; x++) {
		if (server_StartingDirectory.indexOf(children[x].objectId) == 0) {
			// deselect current dir (otherwise we have all the nodes we touch selected
			if (dirSelector.selectedNode) { dirSelector.deselect(); }
			dirSelector.doSelect(children[x]);
			dirSelector.selectedNode.onTreeClick();
			dirSelector.selectedNode.expand();
			setTimeout('FindDir()',100);
		}
	}
}
// Sets up the link bar in the bottom-left of the screen
function SetupLinkBar() {
	var buttonBarContent = '<div style="font-size:85%;text-decoration:underline;cursor:pointer;"' +
		'dojoType="ContentPane" id="audioLink" onclick=\'LinkBarOpen("audioMenu","audioLink");\' style="display:none;">Audio</div>';
	buttonBarContent += '<div dojoType="PopupMenu2" id="audioMenu" toggle="wipe">';
	buttonBarContent += '<div dojoType="MenuItem2" caption="Play MP3s (this folder)" ' +
		'onClick="OpenMP3Player(\'\');"></div>';
	buttonBarContent += '<div dojoType="MenuItem2" caption="Play MP3s (this folder and below)" ' +
		'onClick="OpenMP3Player(\'recursive\')"></div>';
	buttonBarContent += '</div>';
	dojo.widget.manager.getWidgetById('buttonBar').setContent(buttonBarContent);
}
// Opens a popup menu for the linkbar
function LinkBarOpen(menuId,linkId) {
	var menu = dojo.widget.getWidgetById(menuId);
	var link = dojo.widget.getWidgetById(linkId);
	var pos = dojo.html.getAbsolutePosition(link.domNode, false);
	menu.open(pos.x, pos.y+link.height, link);
}

//******************************************************
// END Setup Functions
//******************************************************

// Initialization
function init(e) {
	SetupLoginArea();
	CheckForNoShares();
	GotoStartDir();
	SetupLinkBar();
}

dojo.addOnLoad(init);