var fileTableGlobalRef = null;

function fileTable(){
	
	this.time = new Date();
	this.elementId = null;
	this.data = null;
	this.table = null;
	this.dataSource = null;
	this.type = null;
	fileTableGlobalRef = this;
	this.ajaxComm = new ajaxObj();

	this.currentMouseOverEle = null;
	this.currentMouseInterval = 0;

	this.fileTypes = {
		png: "image", jpg: "image", tiff: "image", jpeg: "image", gif: "image", bmp: "image", tif: "image", sid: "image", ecw: "image",
		htm: "web", html: "web", php: "web", 
		zip: "compressed", tar: "compressed", tgz: "compressed", gz: "compressed",
		meta: "meta",
		shp: "shape",
		dbf: "database", csv: "database", mdb: "database",
		xml: "xml", pdf: "xml", doc: "xml", txt: "xml"
	};

	this.icons = {
		image: "/website/images/image.png",
		web: "/website/images/www.png",
		xml: "/website/images/xml.png",
		compressed: "/website/images/compressed.png",
		meta: "/website/images/meta.png",
		shape: "/website/images/shape.png",
		database: "/website/images/database.png",
		preview: "/website/images/preview.png"
	}

	this.previewLocations = new Array("casil/remote_sensing/naip_2005/usda_file_archive/");
	this.isOpenLayersLoaded = 0;

	this.initialize = function( id, data ){
		this.elementId = id;
		this.setData(data);
	}

	this.setId = function(id){
		this.elementId = id;
	}

	this.setData = function(data){
    		this.data = { db: data };
	};

	
	this.mouseOverRowStart = function(oArgs){
		fileTable.tmpArgs = oArgs;
		var elTarget = oArgs.target;
		var ele = fileTable.table.getTrEl(elTarget);
		setTimeout( function(){fileTable.mouseOverRowAfterDelay(ele.id);}, 100 );
	}

	this.tmpArgs = null;

	this.mouseOverRowAfterDelay = function(delayId){
		var oArgs = fileTable.tmpArgs;
	  	var evt = oArgs.event;
	        var elTarget = oArgs.target;
		var ele = fileTable.table.getTrEl(elTarget);
		//how it worked
	//	if( ele && evt.target.tagName.match(/td/i)){
		if( ele && elTarget.tagName.match(/tr/i) && (delayId == ele.id)){
			fileTable.cele = elTarget;
			if( fileTable.currentMouseOverEle ){
				if(  fileTable.currentMouseOverEle.id != ele.id ){
					/// row selected, clear large (if happening) shrink old row
					clearInterval( fileTable.currentMouseInterval );
					fileTable.mouseOutRowStart(fileTable.currentMouseOverEle);
					fileTable.currentMouseOverEle = ele;
					//Changed
					fileTable.cimgEle = fileTable.cele.firstChild.firstChild.firstChild.firstChild.firstChild;
					if( navigator.appName.match(/Microsoft/i)){
						fileTable.cimg = fileTable.cimgEle.getAttribute("src");
						fileTable.cimg = fileTable.cimg.replace( /http:.*\//, "" ).split(".")[0];
						fileTable.cimg = "/website/images/"+fileTable.cimg;
					} else {
						fileTable.cimg = fileTable.cimgEle.getAttribute("src").split(".")[0];
					}
					fileTable.csize = 24;
					fileTable.currentMouseInterval = setInterval( fileTable.mouseOverRow, 50 );
					ele.style.fontWeight = "bold";
					ele.style.fontSize = "14px";
				}
			} else { // first time
				fileTable.currentMouseOverEle = ele;
				//Changed
				fileTable.cimgEle = fileTable.cele.firstChild.firstChild.firstChild.firstChild.firstChild;
				if( navigator.appName.match(/Microsoft/i)){
					fileTable.cimg = fileTable.cimgEle.getAttribute("src");
					fileTable.cimg = fileTable.cimg.replace( /http:.*\//, "" ).split(".")[0];
					fileTable.cimg = "/website/images/"+fileTable.cimg;
				} else {
					fileTable.cimg = fileTable.cimgEle.getAttribute("src").split(".")[0];
				}
				fileTable.csize = 24;
				fileTable.currentMouseInterval = setInterval( fileTable.mouseOverRow, 50 );
				ele.style.fontWeight = "bold";
				ele.style.fontSize = "14px";
			}
		}
	}

	this.mouseOverRow = function(){
		var rowId = fileTable.cele.id;
		var imgId = fileTable.cimgEle.id;
		var img = fileTable.cimg;
		var size = fileTable.csize;
		var ele = document.getElementById(imgId);
		var row = document.getElementById(rowId);
		if( size <= 36 ){
			if( ele ){
				ele.style.width = size+"px";
				// Changed
				//row.style.height = size+"px";
				ele.style.height = size+"px";
				var mTop = parseInt(ele.style.marginTop) - 1;
				ele.style.marginTop = mTop + "px";
				size += 2;
				fileTable.csize = size;
			}
		} else {
			clearInterval( fileTable.currentMouseInterval );
			img = img.replace(/36/g, "");
			ele.parentNode.parentNode.style.zIndex = "15";
			if( ele.src.match("36") ){ /// hack!!!!!!!!
				ele.src = img+".png";
			} else {
				ele.src = img+"36.png";
			}
		}
	}

	this.clearLargeRow = function(){
		if( fileTable.currentMouseOverEle ){
			fileTable.mouseOutRowStart(fileTable.currentMouseOverEle);
			fileTable.currentMouseOverEle = null;
		}
	}

	this.mouseOutRowStart = function(ele){
		//Changed
		var imgEle = ele.firstChild.firstChild.firstChild.firstChild.firstChild;
		var img;
		if( navigator.appName.match(/Microsoft/i)){
			img = imgEle.getAttribute("src");
			img = img.replace( /http:.*\//, "" ).split(".")[0];
			img = "/website/images/"+img;
		} else {
			img = imgEle.getAttribute("src").split(".")[0];
		}
		fileTable.mouseOutRow( ele.id, imgEle.id, img, parseInt(imgEle.style.width) );
		ele.style.fontWeight = "";
		ele.style.fontSize = "13px";
	}

	this.mouseOutRow = function( rowId, imgId, img, size ){
		var ele = document.getElementById(imgId);
		var row = document.getElementById(rowId);
		img = img.replace(/36/g, "");
		if( ele ){
			if( size >= 24  ){
				ele.style.width = size+"px";
				ele.style.height = size+"px";
				var mTop = parseInt(ele.style.marginTop) + 1;
				ele.style.marginTop = mTop + "px";
				//Changed
				//row.style.height = size+"px";
				size -= 2;
				setTimeout( "fileTable.mouseOutRow('"+rowId+"','"+imgId+"','"+img+"',"+size+")", "20" );
			} else {
				ele.src = img+".png";
				ele.style.marginTop = "0px";
				ele.parentNode.parentNode.style.zIndex = "10";
			}
		}
	}
	this.loadScripts = "";
	this.addIcon = function(dir){
		var ft = fileTableGlobalRef;
		var cl = window.location.href;
		if( !cl.match(/\/$/) ){
			cl += "/";
		}
		var t = "<div style='float: left; left: 0px; top:0px; text-align: center; height: 24px; position: relative'><div style='position:absolute; z-index: 10'>";
		if( dir[1].match( /^\.\.$/ )){
			text = "Previous Directory";
			var dirs = cl.split("/");
			var dir = dirs[dirs.length-2].replace("+", "\\+");
			var r = new RegExp( dir+"\/$" );
			t += "<a href='"+cl.replace(r, "")+"'><img style='margin: 0px 0px 0px 10px' id='"+dir[1]+"_icon' src='/website/images/perviousDir.png' /></a>";
		} else if( parseInt(dir[0]) == 1 ){
			t += "<a href='"+cl+dir[1]+"/'><img style='margin: 0px 0px 0px 10px' id='"+dir[1]+"_icon' src='/website/images/directory.png' /></a>";
		} else {
			var fileparts = dir[1].split(".");
			var fileType = fileparts[fileparts.length-1];
			if( ft.fileTypes[fileType] ){
				t += "<a href='"+cl+dir[1]+"'><img style='margin: 0px 0px 0px 10px' id='"+dir[1]+"_icon' src='"+ft.icons[ft.fileTypes[fileType]]+"' /></a>";
			} else {
				t += "<a href='"+cl+dir[1]+"'><img style='margin: 0px 0px 0px 10px' id='"+dir[1]+"_icon' src='/website/images/unknownFile.png'</a>";
			}
		}
		t += "</div></div>";
		if( cl.match(/\/casil\/remote_sensing\/naip_2005\/usda_file_archive\/\d+/) && !dir[1].match( /^\.\.$/ )){
			if( !ft.isOpenLayersLoaded ){
				ft.isOpenLayersLoaded = 1;
			}
			t += "<img style='margin-left: 30px; cursor: pointer' id='"+dir[1]+"_picon' title='Preview Image "+dir[1]+"' src='"+ft.icons["preview"]+"' onclick='map_display(\""+dir[1]+"\");' />";
		}
		return t;
	}

	this.addAnchorTag = function(text){
		var cl = window.location.href;
		if( !cl.match(/\/$/) ){
			cl += "/";
		}
		var t
		if( text.match( /^\.\.$/ )){
			text = "Previous Directory";
			var dirs = cl.split("/");
			var dir = dirs[dirs.length-2].replace("+", "\\+");
			var r = new RegExp( dir+"\/$" );
			var tmp = cl.replace(r, "");
			t = "<a href='"+tmp+"'>"+text+"</a>";
		} else if( text.match(/\./)){
			t = "<a href='"+cl+text+"'>"+text+"</a>";
		} else {
			t = "<a href='"+cl+text+"/'>"+text+"</a>";
		}
		return t;
	}

	this.addSize = function(text){
		if( parseInt(text) ) return parseInt(text);
		return text;
	}

	this.addFileInfo = function(text){
		return "<div title='"+text+"' style='font-size:90%; color: #999999; overflow: hidden; height: 17px'>"+text+"</div>";
	}

	this.createTable = function(effects){
		this.type = "search";
        	var myColumnDefs = [
			{key:"dir", label: "", sortable:false, resizeable:false, width: "10%"},
       			{key:"name", label: "FileName", sortable:true, resizeable:true, width: "45%"},
       			{key:"info", label: "File Info", sortable: true, resizeable:true, width: "25%"},
       			{key:"size", label: "Size (in bytes)", sortable:true, resizeable:true, width: "10%" },
       			{key:"mtime", label: "Last Modified", sortable:true, resizeable:true, width: "10%"}
        	];
		this.dataSource = new YAHOO.util.DataSource(this.data.db);
        	this.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        	this.dataSource.responseSchema = {
        		fields: [{key:"dir", parser:this.addIcon}, {key:"name", parser:this.addAnchorTag}, {key:"size", parser:this.addSize}, {key:"mtime", parser:this.formatTimestamp}, {key: "info", parser:this.addFileInfo}]
        	};
		var oConfigs = {};
		this.table = new YAHOO.widget.DataTable(this.elementId, myColumnDefs, this.dataSource, oConfigs);
		if( effects ){
			this.table.subscribe("rowMouseoverEvent", this.mouseOverRowStart);
		}
		this.getGforgeProjects();
	}

	this.getGforgeProjects = function(){
		var troveCats = window.location.href.split("/");
		var cat;
		if( troveCats[troveCats.length-1] ){
			cat = troveCats[troveCats.length-1];
		} else {
			cat = troveCats[troveCats.length-2];
		}
		this.ajaxComm.localRequest( "http://"+document.domain+"/cgi-bin/tools/getProjectsByTrove?cat="+cat+"&type=shortname", this.getGforgeProjectsResp, null, null, null);
		this.ajaxComm.localRequest( "http://"+document.domain+"/cgi-bin/tools/getPackagesByTrove?cat="+cat+"&type=shortname", this.getGforgePackagesResp, null, null, null);
	}

	this.getGforgePackagesResp = function(json){
		var jsonObj = eval('(' + json + ')');
		if( !jsonObj["ERROR"] ){
			for( var i in jsonObj ){
				var p = jsonObj[i];
				var pcount = 1;
				for( var j in jsonObj[i]["files"] ){
					var filename = jsonObj[i]["files"][j][0];
					var fileId = jsonObj[i]["files"][j][1];
					var d = fileTable.addIcon( ['0', filename] );
					var release_id = jsonObj[i]["files"][j][3];
					if( pcount == 1 ){ 
						var tObj = { dir: "<div style='float: left; left: 0px; top: 0px; text-align: center; height: 24px; position: relative;'><div style='position: absolute; z-index: 10;'><a href='http://gforge.casil.ucdavis.edu/frs/?group_id="+p["group_id"]+"&release_id="+release_id+"' target='_blank'><img title='Gforge Package' style='margin: 0px 0px 0px 10px' id='"+p["package_id"]+"_icon' src='/website/images/gforgePackage.png' /></a></div></div>", name: "<a href='http://gforge.casil.ucdavis.edu/frs/?group_id="+p["group_id"]+"&release_id="+release_id+"' target='_blank'> "+p["name"]+"</a>", size: "Package Link", mtime: "--", info: "" };
						fileTable.appendData( tObj );
					}
					pcount++;
					tObj = { dir: d, 
						name: "&nbsp;&nbsp;<img src='/website/images/packageFileArrow.png' style='margin-top: 2px'/><a href='http://gforge.casil.ucdavis.edu/frs/download.php/"+fileId+"/"+filename+"'> "+filename+" <span style='font-size: 70%'>(Package: "+p["name"]+", Release: "+p["last_release"]+")</span></a>", 
						size: jsonObj[i]["files"][j][2], 
						mtime: fileTable.formatTimestamp(p["release_date"]),
						info: ""
					 };
					fileTable.appendData( tObj );
				}
			}
		}
	}

	this.getGforgeProjectsResp = function(json){
		var jsonObj = eval('(' + json + ')');
		var repeats = {};
		if( !jsonObj["ERROR"] ){
			jsonObj = jsonObj["projects"];
			for( var i in jsonObj ){
				var p = jsonObj[i];
				if( !repeats[p["unix_group_name"]] ){
					var tObj = { dir: "<div style='float: left; left: 0px; top: 0px; text-align: center; height: 24px; position: relative;'><div style='position: absolute; z-index: 10;'><a href='http://gforge.casil.ucdavis.edu/projects/"+p["unix_group_name"]+"' target='_blank'/><img title='Gforge Project' style='margin: 0px 0px 0px 10px' id='"+p["unix_group_name"]+"_icon' src='/website/images/gforge.png' /></a></div></div>", name: "<a href='http://gforge.casil.ucdavis.edu/projects/"+p["unix_group_name"]+"/' target='_blank'> "+p["group_name"]+"</a>", size: "Project Link", mtime: "--" };
					fileTable.appendData( tObj );
					repeats[p["unix_group_name"]] = 1;
				}

			}
		}
	}

        this.formatTimestamp = function(ts){
                var milli = ts*1000;
                var d = fileTable.time.setTime(milli);
                return (fileTable.time.getMonth()+1)+"-"+(fileTable.time.getDay()+1)+"-"+fileTable.time.getFullYear();
                //return this.time.getMonth()+"/"+this.time.getDay()+"/"+this.time.getFullYear()+" - "+this.time.getHours()+":"+this.time.getMinutes();
        }


	this.appendData = function(obj){
		this.table.addRow( {dir: obj["dir"], name: obj["name"], size: obj["size"], mtime: obj["mtime"] } );
	}

	this.registerEffects = function(checkbox){
		if( checkbox.checked ){
			fileTable.table.subscribe("rowMouseoverEvent", this.mouseOverRowStart);
			document.cookie = "tableEffects=1";
		} else {
			this.clearLargeRow();
			fileTable.table.unsubscribe("rowMouseoverEvent");
			document.cookie = "tableEffects=0";
		}
	}

}
