/* file class */
var doubleClickTime = 650;

function html_entity_decode(str) {
	  var ta=document.createElement("textarea");
	  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	  return ta.value;
	}


function File() {
	//private vars
	this.lastClickedOnTime = 0;
	
	//public vars
	this.dbid = 0;
	this.isDirectory = false;
	this.name = '';
	this.path = '';
	this.iconSrc = '';
	this.selected = false;
	
	//methods
	this.getDiv = File_getDiv;
	this.getImg = File_getImg;
	
	this.click = File_click;
	this.doubleClick = File_doubleClick;
	
	this.select = File_select;
	this.deselect = File_deselect;
	this.startRename = File_startRename;
	this.setName = File_setName; //contacts server
	
	this.show = File_show;
	this.hide = File_hide;
	
	this.highlightIcon = File_highlightIcon;
	this.unhighlightIcon = File_unhighlightIcon;
	
	this.xyWithinImgBounds = File_xyWithinImgBounds;
	
	this.moveTo = File_moveTo; //contacts server
	this.putintemparea = File_putintemparea; //contacts server
	this.del = File_del; //contacts server
}


function File_getDiv() {
	return document.getElementById('file-'+this.dbid);
}

function File_getImg() {
	return document.getElementById('fileImg-'+this.dbid);
}

// manual detection of double click. some browsers do it for us.
function File_click() {
	//alert(this.name);
	//alert(html_entity_decode(this.name));
	
	var now = new Date().getTime();
	var dt = (now-this.lastClickedOnTime);
	if (dt < doubleClickTime) {
		this.doubleClick();
	} else {
		//document.title = "click! dt = "+dt;
	}
	this.lastClickedOnTime = now;
	this.select();
	
}

function File_doubleClick() {
	var baseUrl;
	if (window.location.hash) {
		window.location.hash = '';
		baseUrl = window.location.href.slice(0, -1);
	} else {
		baseUrl = window.location;
	}
	
	var urlSafeName = escape(html_entity_decode(this.path)); //first get rid of html entities, then put in URL form
	if (this.isDirectory) {
		window.location = "/files" + urlSafeName + "/";
	} else {
		window.location = "/files" + urlSafeName;
	}
}

function File_select() {
	var fileImg = document.getElementById("fileImg-"+this.dbid);
	fileImg.style.opacity = 0.3;
	//$("#fileImg-"+this.dbid).fadeTo(0, 0.3);
	var fileLabel = document.getElementById("fileLabel-"+this.dbid);
	fileLabel.style.background = 'lightblue';
	this.selected = true;
}

function File_deselect() {
	var fileImg = document.getElementById("fileImg-"+this.dbid);
	fileImg.style.opacity = 1.0;
	//$("#fileImg-"+this.dbid).fadeTo(0, 1.0);
	var fileLabel = document.getElementById("fileLabel-"+this.dbid);
	fileLabel.style.background = '';
	this.selected = false;
}

function File_show() {
	if (this.getDiv()) this.getDiv().style.display = '';
}

function File_hide() {
	if (this.getDiv()) this.getDiv().style.display = 'none';
}

function File_xyWithinImgBounds(x, y) {
	return areCoordsOverElement(x, y, this.getImg());
}

function File_highlightIcon() {
	this.getImg().src = '/static/images/fileicons/folder_highlighted.png';
}

function File_unhighlightIcon() {
	this.getImg().src = this.iconSrc;
}

function File_moveTo(dir, refresh) {
	var url = "/file/"+this.dbid+"/mv/"+dir.dbid;
	//console.log("AJAX: "+url)
	jajax(url, 'post', 'info', function(){
		if (refresh){
			window.location.reload(true);
		}
	}, null);
	this.hide();
}

function File_putintemparea() {
	var url = "/file/"+this.dbid+"/movetotemparea";
	//console.log("AJAX: "+url);
	jajax(url, 'post', 'info', function(){window.location.reload(true);}, null);
	this.hide();
}

function File_del() {
	var url = "/file/"+this.dbid+"/delete";
	//console.log("AJAX: "+url);
	jajax(url, 'post', 'info', function(){window.location.reload(true);}, null);
	this.hide();
}

function File_startRename() {
	globalDragLock = true;
	document.getElementById("fileLabel-"+this.dbid).innerHTML = "<input type='text' id='newFilename' value='"+this.name+"' style=\"z-index:999;\"/ onkeypress=\"renameKeyPress(event, "+this.dbid+");\">";
	document.getElementById('newFilename').focus();
}


function File_setName(enteredName) {
	if (enteredName==null || enteredName.length==0) {
		document.getElementById("fileLabel-"+this.dbid).innerText = this.name;
		globalDragLock = false;
		alert('Cannot set an empty name');
	} else {
		var url = "/file/"+this.dbid+"/rename";
		//console.log("AJAX: "+url);
		var thiss = this;
		jajax(url, 'post', 'info', function() {
			thiss.name = enteredName;
			document.getElementById("fileLabel-"+thiss.dbid).innerHTML = thiss.name;
			globalDragLock = false;
		}, "name="+enteredName);
	}
}



function renameKeyPress(e, dbid) {
	var file = allFiles[dbid];
	//updateInfo("key press in file "+file.dbid+" with name = "+file.name);
	var characterCode; // literal character code will be stored in this variable
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		//e = event; //what was this supposed to be? says event is undefined
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	if(characterCode == 13){ // if generated character code is equal to ascii 13 (i.e enter key)
		var newValue = document.getElementById('newFilename').value;
		if (newValue.indexOf("/") != -1 || newValue.indexOf("\\") != -1) {
			alert("The name may not contain a slash.");
		} else {
			file.setName(newValue); //submit the form
		}
		return false; 
	} else {
		return true;
	}
}



//stuff
var IE = document.all?true:false;

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		var result = new Object();
		result.left = curleft;
		result.top = curtop;
		//return [curleft,curtop];
		if (curleft && curtop) return result;
		else return null;
	}
}

function moveTo(elementId, x, y) {
	document.getElementById(elementId).style.top = y+'px';
	document.getElementById(elementId).style.left = x+'px';
}


function animateReturningFile(elementId, xFrom, yFrom) {
	var TIME = 400;
	var FPS = 30;
	
	var dx = -xFrom; /* total distance to travel */
	var dy = -yFrom;
	var startx = parseInt(document.getElementById(elementId).style.left);
	var starty = parseInt(document.getElementById(elementId).style.top);

	var frames = FPS*TIME/1000.0;
	for (var i=0; i<=frames; i++) {
		var newx = startx + (i/frames)*dx;
		var newy = starty + (i/frames)*dy;
		var command = "moveTo('"+elementId+"', "+parseInt(newx)+", "+parseInt(newy)+")";
		setTimeout(command, i*(1000.0/FPS));
	}
}


function areCoordsOverElement(x, y, element) {
	var pos = findPos(element);
	var width = element.offsetWidth;
	var height = element.offsetHeight;
	if (!pos || !width || !height) return false;
	return (x>pos.left && x<pos.left+width
			&& y>pos.top && y<pos.top+height);
}


/* for storing the mouse location all the time */
//var mouseX = 0;
//var mouseY = 0;
//document.onmousemove=getMouseCoordinates;
//function getMouseCoordinates(event) {
//	ev = event || window.event;
//	mouseX = ev.pageX;
//	mouseY = ev.pageY;
//}






//The Drag Function, oh yeah
var DragHandler = { //http://www.webtoolkit.info/
    // private copy of the element
    _oElem : null,
    // public method wot attaches drag handler to an element.
    attach : function(oElem) {
        oElem.onmousedown = DragHandler._dragBegin;
        // callbacks
        oElem.dragBeginHook = new Function();
        oElem.dragHook = new Function();
        oElem.dragEndHook = new Function();
        return oElem;
    },
    // private method. Begin drag process.
    _dragBegin : function(e) {
    	var oElem = DragHandler._oElem = this;
        if (oElem.shouldDrag(oElem, x, y)) {
	        if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
	        if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
	        var x = parseInt(oElem.style.left);
	        var y = parseInt(oElem.style.top);
	        e = e ? e : window.event;
	        oElem.mouseX = e.clientX;
	        oElem.mouseY = e.clientY;
	        oElem.dragBeginHook(oElem, x, y);
	        document.onmousemove = DragHandler._drag;
	        document.onmouseup = DragHandler._dragEnd;
	        return false;
        } else {    
	        return true;
	    }
    },
    // actually move element's position in the style bit.
    _drag : function(e) {
        var oElem = DragHandler._oElem;
        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);
		/* put here reccement... test - keeps the item inside the board */
		//x = xApplyDragLimit(x);
		//y = yApplyDragLimit(y);		
        e = e ? e : window.event;
        oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
        oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';
        oElem.mouseX = e.clientX;
        oElem.mouseY = e.clientY;
        oElem.dragHook(oElem, x, y);
        return false;
    },
    // remove drag handler.
    _dragEnd : function() {
        var oElem = DragHandler._oElem;
        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);
        oElem.dragEndHook(oElem, x, y);
        document.onmousemove = null;
        document.onmouseup = null;
        DragHandler._oElem = null;
    }
}

