// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, 
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// JavaScript for the main ui of filesystem.
// Watch the tree for changes, and when they occur send them off to
// DataStore.

var tree;
var t = document.getElementById("test");
var path = document.getElementById("path").value;
var lastSavedVal = t.value;
var saveTimeout = 500; // 500 milliseconds of quiet before autosave
var idleTimeout = 10000; // 10 seconds idle sync -- Increase this later to make it stable for large file system
var gears;
var timerId;
var snapshot;
var store;
var j=0

function init() {
  gears = new Gears();
  store = new DataStore(onsync);

  document.getElementById("login-bar").style.display = "";
  document.getElementById("logged-in-as").appendChild(
  document.createTextNode(store.email));
  sync();
}

function scheduleSync(timeout) {
  cancelSchedule();
  timerId = window.setTimeout(sync, timeout);
}

function cancelSchedule() {
  if (timerId) {
    timerId = window.clearTimeout(timerId);
  }
}

function sync() {
	cancelSchedule();
	snapshot = t.value;
	var newshot = snapshot;
	listFiles();
	newshot = t.value;
//	document.getElementsByTagName("test").value = newshot;
	if (newshot != lastSavedVal) 
	{
		setStatus("Saving...", "orange");
//		alert("Line 73:"+newshot);
		store.sync(newshot);
		lastSavedVal = newshot;
		print_it();
	} 
	else 
	{
		setStatus("Syncing...", "orange");
		store.sync(null);
	}

}

function onsync(newContent) {
  // If the File Tree has changed since the sync was sent, then the result is
  // invalid and the sync must be redone. This can happen since syncs from 
  // scan are delayed and server requests are asynchronous.
  if (snapshot != t.value) {
    sync();
    return;
  }

  if (newContent !== null) {
    t.value = newContent;
  }

  lastSavedVal = t.value;

  if (store.online) {
    setStatus('Online.', 'green');
  } else {
    setStatus('Offline.', 'orange');
  }

  scheduleSync(idleTimeout);
}

function setStatus(msg, color) {
  var elm = document.getElementById("status")
  elm.className = color;
  elm.innerHTML = msg;
}

function logout() {
  eraseCookie("c");
  location.href = "login.php";
}

function setupOffline() {
  if (!gears.hasGears) {
    location.href = 'getgears.php';
    return;
  }

  if (!gears.hasDb) {
    gears.createDatabase();
  }

  gears.addUser(store.userId,
                unescape(readCookie('c')),
                t.value,
                store.version,
                store.clientId);

  if (!gears.isCaptured) {
    gears.capture();
  } else {
    location.reload();
  }
}

function promptToOverrideConflict() {
  return confirm(
     'The note has been changed on another computer. Override changes?');
}

// NEW YUI TREE

function retraverse_it(tree_text, root) {
		if(tree_text.hasChildNodes()) {
                for(var i=0; i<tree_text.childNodes.length; i++)
				{
					if(tree_text.childNodes[i].tagName == "Directory")
						{
//							alert(tree_text.childNodes[i].firstChild.firstChild.nodeValue);
							var tmpNode = new YAHOO.widget.TextNode(tree_text.childNodes[i].firstChild.firstChild.nodeValue, root, false);
							retraverse_it(tree_text.childNodes[i], tmpNode);
						}
					else if(tree_text.tagName == "FileName")
					{

						var name = tree_text.firstChild.nodeValue;
						var info = "<b>Name: </b>"+name;
//						var tmpNode = new YAHOO.widget.TextNode(name, root, false);
						var next = tree_text.nextSibling;
						info = info +  "<br/><b>Path: </b>"+next.firstChild.nodeValue;
//						new YAHOO.widget.TextNode(next.firstChild.nodeValue, tmpNode, false);
						next = next.nextSibling;
						info = info +  "<br/><b>Size: </b>"+next.firstChild.nodeValue;
//						new YAHOO.widget.TextNode(next.firstChild.nodeValue, tmpNode, false);
						next = next.nextSibling;
						info = info +  "<br/><b>Date: </b>"+next.firstChild.nodeValue;
//						new YAHOO.widget.TextNode(next.firstChild.nodeValue, tmpNode, false);

						var tmpNode = new YAHOO.widget.TextNode({label:name, customData:info}, root, false);
						tmpNode.labelStyle = "icon-gen";
						tmpNode.onLabelClick = onClick;

					}
					else
						{
							retraverse_it(tree_text.childNodes[i], root);
						}
				}
        }
		return;
}

var onClick = function(oNode) {
	Tip(oNode.data.customData);
	return;
}

// ******** Display Remote File Structure********* //
function disp_it(text, tagname, mcname)
{
//	text = document.getElementById(id).value;
//	alert(text);
	if (window.ActiveXObject)
	{
		doc =new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(text);
	}
	else
	{
		var parser=new DOMParser();
		doc=parser.parseFromString(text,"text/xml");
	}
	var x=doc.documentElement;
	var tree = new YAHOO.widget.TreeView(tagname);
	root = tree.getRoot();
	var tmpNode = new YAHOO.widget.TextNode(mcname, root, false);
//	tmpNode.labelStyle = "fname";
	retraverse_it(x, tmpNode) ;
//	tree.subscribe("labelClick", function(node) {alert(node.data.label + " label was clicked"); });
	tree.draw();
	return;
}

// ******** Display ALL Remote File Structure********* //
function disp_all()
{
	var list = document.getElementsByName("id");
//	alert (list.length);
	for (var i=0; i<list.length ; i++ )
	{
		var id = list[i].value;
		var tagname = "treeDiv"+id;
		var content = document.getElementById(id).value;
		var mcname = document.getElementsByName(tagname)[0].value;
//		alert(content.value);
//		alert(tagname);
//		alert(mcname[0].value);
		disp_it(content, tagname, mcname);
	}
}

// ******** Display Local File Structure********* //
function print_it()
{
	var text = test.value;
	var mname = mcname.value;
//	mcname = mcname.toString();
	if (window.ActiveXObject)
	{
		doc =new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(text);
	}
	else
	{
		var parser=new DOMParser();
		doc=parser.parseFromString(text,"text/xml");
	}
	var x=doc.documentElement;
	var tree = new YAHOO.widget.TreeView("treeDiv1");
	var root = tree.getRoot();
	var tmpNode = new YAHOO.widget.TextNode(mname, root, false);
//	tmpNode.labelStyle = "mname";
	retraverse_it(x, tmpNode) ;
	tree.draw();
	return;
}


// ********  File Scanning ********* //

function listFiles() {
  var path = document.getElementById("path").value;
//  alert(path);
  netscape.security.PrivilegeManager.enablePrivilege('UniversalFileRead');
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  try {
    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath(path);
    var out = "<?xml version='1.0'?> \n";
	out = out + "<FileSystem> \n";
	out = out + iterate(file);
	out = out + "</FileSystem> \n";
//	list.innerHTML = out;
  }
  catch (e) { 
//	document.write("Error in listFiles " +e);
//	document.write("***"+"PATH: "+"***"+path+"***");
//	alert("Check this");
	document.write("<b><i><span class=\"error\">No Local Path Set for this Computer</span></i></b><br/>");
//	alert("wow");
	location.href = "settings.php";
	return false;
  }
  document.getElementById("test").value = out;
	return true;
}

// **** Form the XML **** //
function iterate(file)
{
	if(file.isDirectory()) {
      var dirlist = file.directoryEntries;
      var tempout = "";
	  var temp_date;
      while(dirlist.hasMoreElements()) {
        var next = dirlist.getNext().QueryInterface(Components.interfaces.nsIFile);
        if(next.isDirectory()) {
			//tempout += "\nDirectory Path: "+next.path + "\n";
			var dir = next.clone();
			tempout += "<Directory>";
			tempout += "<DirName>"+next.leafName + "</DirName>";
//			tempout += "<DirPath>"+next.path + "</DirPath>";
//			tempout += "<DirSize>" + next.fileSize + "</DirSize>";
//			temp_date = new Date(next.lastModifiedTime);
//			tempout += "<Date>" + temp_date.getMonth() +"/"+ temp_date.getDate()+ "/" + temp_date.getFullYear() +"</Date>";
			tempout = tempout + iterate(dir);
			tempout += "</Directory>";
        }
		else{
			tempout += "<File>" ;
			tempout += "<FileName>"+next.leafName + "</FileName>";
			tempout += "<FilePath>"+next.path + "</FilePath>";
			tempout += "<Size>" + next.fileSize + " Bytes</Size>";
			temp_date = new Date(next.lastModifiedTime);
			tempout += "<Date>" + temp_date.getMonth() +"/"+ temp_date.getDate()+ "/" + temp_date.getFullYear() +"</Date>";
			tempout += "</File>" ;
		}
      }
      return tempout;
	  }
}

