// Globals
var BLOCKING = false;
var FOLDER_ID = -1;
var CURRENT_OBJECTS = {folder:[], doc:[]};
var NEW_OBJECTS = {folder:[], doc:[]};
var CELL_STYLES = [
	{width:25, CSSclass:"cb", halign:'center'},
	{width:20, CSSclass:null, halign:'center'},
	{width:"100%", CSSclass:"listCell", halign:'left'},
	{width:null, CSSclass:"listCell", halign:'left'},
	{width:80, CSSclass:"listCell", halign:'left'},
	{width:80, CSSclass:"listCell", halign:'left'},
	{width:80, CSSclass:"listCell", halign:'left'},
	{width:135, CSSclass:"listCell", halign:'left'}
];
var THIS_baseURL;
var THIS_relURL;

//-------------------------------
// VOID jumpToFolder( folderList )
//--
// STRING folderList	= ID of the drop-down box containing the folder tree
//--
// Jumps directly to the chosen folder.
//-------------------------------
function jumpToFolder(folderList) {

	// BLOCKING
	if(BLOCKING) return false;
	BLOCKING = true;

	// Vars
	folderList = getHTMLElement(folderList);
	var folderID = folderList.options[folderList.selectedIndex].value;

	// Move to browse chosen folder
	self.location = EXNT_genHREF('doc', 'browse', {id:folderID});
}

//-------------------------------
// VOID toggleSelectAll( box )
//--
// HTMLElement box	= The checkbox representing 'select all'
//--
// Toggles each check box to reflect the same value as the 'select all' box.
//-------------------------------
function toggleSelectAll(box) {

	// Set all check boxes to same as top box
	for(var i in CURRENT_OBJECTS) {
		for(var j in CURRENT_OBJECTS[i]) {
			var e = getHTMLElement('checkBox['+i+']['+CURRENT_OBJECTS[i][j]+']');
			e.checked = box.checked;
		}
	}
}

//-------------------------------
// VOID deleteSelected()
//--
// Submits the form to delete all the selected folders/documents
//-------------------------------
function deleteSelected() {

	// Blocking
	if(BLOCKING) return false;
	BLOCKING = true;

	// Confirm
	if(!confirm('Are you sure you want to remove\nthe selected folders/documents?')) {
		BLOCKING = false;
		return false;
	}

	// Vars
	var form = getHTMLElement('form_interface');
	var oper = form['oper'];

	// Setup and submit
	oper.value = 'deleteSelected';
	form.submit();
}

//-------------------------------
// VOID moveSelected()
//--
// Submits the form to move all the selected folders/documents to the specified folder.
//-------------------------------
function moveSelected() {

	// Blocking
	if(BLOCKING) return false;
	BLOCKING = true;

	// Confirm
	if(!confirm('Are you sure you want to move\nthe selected folders/documents?')) {
		BLOCKING = false;
		return false;
	}

	// Vars
	var form = getHTMLElement('form_interface');
	var oper = form['oper'];

	// Setup and submit
	oper.value = 'moveSelected';
	form.submit();
}

//-------------------------------
// VOID lockSelected()
//--
// Submits the form to lock/unlock the selected folders/documents.
//-------------------------------
function lockSelected() {

	// Blocking
	if(BLOCKING) return false;
	BLOCKING = true;

	// Confirm
	if(!confirm("Are you sure you want to toggle the lock status\nfor each of the selected folders/documents?\n\nA locked document can only be modified\nby you or your Controlling Administrator.")) {
		BLOCKING = false;
		return false;
	}

	// Vars
	var form = getHTMLElement('form_interface');
	var oper = form['oper'];

	// Setup and submit
	oper.value = 'lockSelected';
	form.submit();
}

//-------------------------------
// ARRAY addRow( blockName )
//--
// STRING blockName	= ID of the block to which a row will be added
//--
// Adds a rows to the specified table body block and returns the resulting, pre-made cells
//-------------------------------
function addRow(blockName) {

	// vars
	var blocks = ['FOLDER_LIST', 'DOCUMENT_LIST', 'NEW_FOLDER_LIST', 'NEW_DOCUMENT_LIST'];
	var cells = [];
	var c;

	// Get block and count preceding rows
	var b;
	var block;
	var rowCount = 0;
	for(i in blocks) {
		b = getHTMLElement(blocks[i]);
		rowCount += b.rows.length;
		if(blocks[i]==blockName) {
			block = b;
			break;
		}
	}

	// Inert row
	var row = block.insertRow(block.rows.length);
	if (rowCount%2!=0) { row.style.background='#EEE'; }

	// Insert cells
	for(var i=0; i<8; i++) {
		c = row.insertCell(i);
		c.className = CELL_STYLES[i].CSSclass;
		c.width = CELL_STYLES[i].width;
		c.align = CELL_STYLES[i].halign;
		cells.push(c);
	}

	// Result
	return cells;
}

//-------------------------------
// VOID clearBlock( blockName )
//--
// STRING blockName	= ID of the table body block to cear all rows from
//--
// Removes all rows from the specified block
//-------------------------------
function clearBlock(blockName) {

	// vars
	var blocks = ['FOLDER_LIST', 'DOCUMENT_LIST', 'NEW_FOLDER_LIST', 'NEW_DOCUMENT_LIST'];
	var cells = [];
	var c;

	// Get block and count preceding rows
	var b;
	var block;
	var rowCount = 1;
	for(var i in blocks) {
		b = getHTMLElement(blocks[i]);
		rowCount += b.rows.length;
		if(blocks[i]==blockName) {
			block = b;
			break;
		}
	}

	// Remove all rows
	while(block.childNodes.length > 0) {
		block.removeChild(block.firstChild);
	}
}

//-------------------------------
// VOID addNewFolder()
//--
// Adds a new folder to the current session
//-------------------------------
function addNewFolder() {

	// Add folder to list and refresh the HTML and permissions boxes
	var newFolder = {name:'New Folder'};
	NEW_OBJECTS.folder.push(newFolder);
	buildNewFolderList(true);
	updatePermBoxes();
}

//-------------------------------
// VOID removeNewFolder( id )
//--
// INT id	= ID of the folder to remove
//--
// Removes a newly created folder from the current session
//-------------------------------
function removeNewFolder(id) {

	// Remove folder from list and update the HTML and permissions boxes
	NEW_OBJECTS.folder.splice(id, 1);
	buildNewFolderList();
	updatePermBoxes();
}

//-------------------------------
// VOID deleteFolder( id )
//--
// INT id	= ID of the folder to remove from the system
//--
// Redirects the browser to a URL through which this folder will be removed.
//-------------------------------
function deleteFolder(id) {

	// Confirm
	if(confirm("Are you sure you want to\nremove this folder?")) {
		self.location = EXNT_genHREF('doc', 'browse', {id:id, fid:id, remove:1});
		event.returnValue = false;
		return true;
	}
}

//-------------------------------
// VOID addNewDocument()
//--
// Adds a new document to this session.
//-------------------------------
function addNewDocument() {

	// Add document to list and refresh the HTML and permissions boxes
	var newDoc = {name:'New Document', filename:'', removed:false};
	NEW_OBJECTS.doc.push(newDoc);
	var newID = NEW_OBJECTS.doc.length-1;
	updatePermBoxes();

	// Add row
	var cells = addRow('NEW_DOCUMENT_LIST');
	cells[0].innerHTML = "&nbsp;";
	cells[1].innerHTML = '<img src="'+THIS_relURL+'/images/fileIcons/newDocument.gif" width="16" height="16" alt="New Document" />';
	cells[2].innerHTML = '<div id="FDiv['+newID+']"><input type="file" class="file" name="doc['+newID+'][file]" onChange="chosenFile('+newID+', this);" /></div>';
	cells[2].innerHTML += '<div id="DNDiv['+newID+']" style="display: none;"><input type="text" class="text" name="doc['+newID+'][name]" value="" onChange="updateNewDocumentName('+newID+', this);" /><input type="button" class="button" name="btnRemoveNew" value="Remove" onclick="removeNewDocument('+newID+');" /></div>';
	cells[2].innerHTML += '<input type="hidden" name="doc['+newID+'][filepath]" value="" />';
	cells[3].innerHTML = cells[4].innerHTML = cells[5].innerHTML = cells[6].innerHTML = cells[7].innerHTML = '-';
	//cells[7].innerHTML = '<a href="javascript:void(0);" onClick="removeNewDocument('+newID+');">delete</a>'; 
}

//-------------------------------
// VOID removeNewDocument( id )
//--
// INT id	= ID of the document to remove
//--
// Removes a newly created document from the current session
//-------------------------------
function removeNewDocument(id) {

	// Set document's 'removed' flag and update the HTML and permissions boxes
	NEW_OBJECTS.doc[id].removed = true;
	updatePermBoxes();

	// Disable form elements
	var list = getHTMLElement('NEW_DOCUMENT_LIST');
	var cell = list.rows[id].cells[2];
	cell.innerHTML = '[removed]';
}

//-------------------------------
// VOID deleteDocument( id )
//--
// INT folderID	= ID of the folder in which the document resides
// INT id	= ID of the document to remove from the system
//--
// Redirects the browser to a URL through which this document will be removed.
//-------------------------------
function deleteDocument(folderID, id) {

	// Confirm
	if(confirm("Are you sure you want to\nremove this document?")) {
		self.location = EXNT_genHREF('doc', 'browse', {id:folderID, did:id, remove:1});
		event.returnValue = false;
		return true;
	}
}

function updateNewFolderName(id, input) {

	// Update name
	NEW_OBJECTS.folder[id].name = input.value;
}

function updateNewDocumentName(id, input) {

	// Update name
	NEW_OBJECTS.doc[id].name = input.value;
}

function chosenFile(id, file) {

	// Store filename and toggle between upload field and naming field
	NEW_OBJECTS.doc[id].filename = file.value;
	var doc = NEW_OBJECTS.doc[id];
	var FDiv = getHTMLElement('FDiv['+id+']');
	var DNDiv = getHTMLElement('DNDiv['+id+']');
	FDiv.style.display = 'none';
	DNDiv.style.display = 'block';

	// Get file name from full path
	var name = getHTMLElement('doc['+id+'][name]');
	var filepath = getHTMLElement('doc['+id+'][filepath]');
	var pathSeparator = (file.value.indexOf('/')<0) ? '\\' : '/';
	name.value = file.value.substring(file.value.lastIndexOf(pathSeparator)+1, file.value.length);
	filepath.value = file.value;
}

function buildNewFolderList(hiliteLast) {

	// Vars
	if(hiliteLast==null) hiliteLast = false;
	var folderCount = NEW_OBJECTS.folder.length;
	clearBlock('NEW_FOLDER_LIST');

	// Build rows
	for(var i in NEW_OBJECTS.folder) {
		var folder = NEW_OBJECTS.folder[i];
		var cells = addRow('NEW_FOLDER_LIST');
	
		// Populate cells
		cells[0].innerHTML = '&nbsp;';
		cells[1].innerHTML = '<img src="' + THIS_relURL + '/images/fileIcons/folder_closed.gif" width="16" height="16" alt="New Folder" />';
		cells[2].innerHTML = '<input type="text" name="folder[' + i + '][name]" value="' + folder.name + '" onChange="updateNewFolderName(' + i + ', this);" /><input type="button" class="button" name="btnRemoveNewFolder" value="Remove" onclick="removeNewFolder(' + i + ');" />';
		cells[3].innerHTML = cells[4].innerHTML = cells[5].innerHTML = cells[6].innerHTML = cells[7].innerHTML ='-';
		//cells[7].innerHTML = '<a href="javascript:void(0);" onClick="removeNewFolder(' + i + ');">delete</a>';
	}

	// Focus on last folder name
	if(hiliteLast) {
		var n = getHTMLElement('folder['+ i +'][name]');
		n.focus();
		n.select();
	}
}

function updatePermBoxes() {

	// Vars
	var permFolder = getHTMLElement('PERMBOX_folder');
	var permDoc = getHTMLElement('PERMBOX_document');
	//var saveBtn = getHTMLElement('saveBtn');

	// Count number of documents that haven't been removed
	var docCount = 0;
	for(var i in NEW_OBJECTS.doc) {
		docCount += NEW_OBJECTS.doc[i].removed ? 0 : 1;
	}

	// Toggle display
	permFolder.style.display = NEW_OBJECTS.folder.length>0 ? 'block' : 'none';
	permDoc.style.display = docCount>0 ? 'block' : 'none';

	// Toggle save button
	//saveBtn.disabled = (NEW_OBJECTS.folder.length+docCount>0) ? false : true;
	document.getElementById('saveWarning').style.display = (NEW_OBJECTS.folder.length+docCount>0) ? 'block' : 'none';

	// Set form action
	//document.forms['form_interface'].target = docCount>0 ? "UWIN_"+Math.round(Math.random()*1000000) : '_self';
}

function saveChanges() {

	// Blocking
	if(BLOCKING) return false;
	BLOCKING = true;

	// Vars
	var formInt = document.forms['form_interface'];
	//var useBGProcess = (formInt.target!='_self' && formInt.target!='') ? true : false;
	//var isPopup = formInt.isPopup;
	var sid = formInt['sid'].value;

	// Count the number of documents ready to be uploaded
	var docCount = 0;
	for(var i in NEW_OBJECTS.doc) {
		docCount += NEW_OBJECTS.doc[i].removed ? 0 : 1;
	}

	// Upload files using the progress bar
	if(docCount>0) {
		EXNT_uploadFiles(formInt, sid, EXNT_genHREF('doc', 'browse', {id:FOLDER_ID, sid:sid}), EXNT_genHREF('doc', 'browse', {id:FOLDER_ID}));
		return true;
	}

	// Upload form data via the main window if no documents are to be uploaded
	formInt.submit();
	return true;

	//---------------------- delete old code below -----------------

	// Alert to warn about new window
	//if(formInt.target=='_blank') {
	if(useBGProcess) {

		// Ask user if they want to use a background-process window
		/*var msg = "A background process window will now open\n";
		msg += "through which the new documents will be uploaded.\n\n";
		msg += "If you would prefer not to use this background\n";
		msg += "process, press 'Cancel'.";
		if(confirm(msg)) {*/

			// Open target window
			//var win = window.open('', formInt.target, 'width=400,height=400,scrollbars=yes');

			// Prepare popup window for display progress bar and the uploading script
			var win = window.open('', 'EXNT_docUploadWindow', 'width=400,height=400,scrollbars=yes');
			win.document.write('<frameset rows="80%,20%"><frame name="'+formInt.target+'">');
			win.document.write('<frame name="EXNT_docUploadWindowBOT"></frameset>');

			// Progress Bar
			var now = new Date();
			var start = now = Math.floor(now.getTime()/1000);
			var BOTLocation = EXNT_genHREF('doc', 'browse', {progress:1, iTotal:-1, iRead:0, iStatus:1, sid:sid, dtnow:now, dtstart:start});
			win.EXNT_docUploadWindowBOT.location = BOTLocation;

			// Upload script
			formInt.action = '/cgi-bin/upload.cgi?sid='+sid;
		/*}
		else {
			// Reset to not use background process
			formInt.target = '_self';
			useBGProcess = false;
		}*/
	}

	// Submit the main form
	isPopup.value = useBGProcess ? 1 : 0;
	formInt.submit();
	window.focus();
	if(useBGProcess) self.location = EXNT_genHREF('doc', 'browse', {id:FOLDER_ID});

	// Return
	return true;
}