/***************************************************************************************
 * jQuery File Commander v0.5 (initial public release)
 * 
 * Copyright 2010, Miroslaw Niepokoj 
 * e-mail: miroslaw.niepokoj@gmail.com
 * http://niepokoj.com/
 * 
 * license: http://www.opensource.org/licenses/mit-license.php The MIT License
 * 
 * Description
 * TotalCommander clone for better web files management...
 * 
 * If you want to use it then make one thing for me :)
 * All I want from you is to put somewhere on your site a link to http://niepokoj.com 
 * That's all! Thanks! 
 */

// Array.indexOf throws errors in IE8 so fix'em 
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  }
}

var FCCache = {
	cache: [],
	
	normalizePath: function(path) {
		path = path.replace(/\//g, "|");
		path = path.replace(/\\/g, "|");
		
		var pathArray = path.split("|");		
		var newPathArray = [ ];
		for(p in pathArray) {

			p = pathArray[p];
			
			// CLEANING VALUE
//			p = $.trim(p);
			if(p == "")
				continue;
			
			// DOTS ARE REMOVING
			if (p == '..') {
				newPathArray.pop();
				continue;
			}
			newPathArray.push(p);
		}

		var newPath = "";
		for (p in newPathArray)
			newPath += ('|'+newPathArray[p]);
		return newPath;
	},
	setPath: function(path, data) {
		path = this.normalizePath(path);
		this.cache[path] = data;
	},
	getPath: function(path) {
		path = this.normalizePath(path);
		if(this.cache[path])
			return this.cache[path];
		return false; 
	},
	removePath: function(path) {
		path = this.normalizePath(path);
		if(this.cache[path])
			this.cache[path] = false;		
	}
};

var FCCookie = {
	getCookie : function(cookieName) { 
		if (document.cookie.length > 0) { 
			var begin = document.cookie.indexOf(cookieName+"="); 
			if (begin != -1) { 
				begin += cookieName.length+1;
				var end = document.cookie.indexOf(";", begin);
				if (end == -1) end = document.cookie.length;
				return unescape(document.cookie.substring(begin, end)); 
			}
		}
		return null; 
	},

	setCookie : function(cookieName, value, expiredays) { 
		var expireDate = new Date ();
		expireDate.setTime(expireDate.getTime() + (expiredays * 24 * 3600 * 1000));
		document.cookie = cookieName + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + expireDate.toGMTString());
	},

	delCookie : function(cookieName) {
		if (getCookie(cookieName)) {
			document.cookie = cookieName + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
		}
	}
};

/* 
 * folder view
 * 
 * 'path': path to display files from  
 * 'FCPanelView': FCPanelView parent instance
 * 'name': tab name
 * 'paths': url paths for actions and images
 */
function FCFolderView(params) {
	this.create(params);
};

FCFolderView.prototype = {
	availableIcons: ["ai","avi","bmp","cs","doc","dll","doc","exe","fla","gif","htm","html","jpg","js","mdb","mp3","pdf","ppt","rdp","swf",
	                       "swt","txt","vsd","xls","xml","zip","png"],
	currentIndex: 0,
	fileRowHeight: 17,
	path: false,
	name: false,
	FCPanelView: false,
	height: false,
	divFiles: false,
	imgPath: false,
	urlPrefx: false,
	dirSeparator: '\\',
	randomID: Math.random()*10000000000,

	callbacks: {
		'onTabGetFocus'		: false,	// tab get focus
		'onTabLoseFocus'	: false,	// tab lose focus
		'onTabLoad'			: false		// tab files loaded
	},
	
	rowWidth: false, 
	iconWidth: false,
	extWidth: false,
	sizeWidth: false,
	timeWidth: false,
	attrWidth: false,
	nameWidth: false,	

	create: function(params) {

		// SETTING OPTIONS
		for (x in params['FCPanelView']['callbacks'])
			this.callbacks[x] = params['FCPanelView']['callbacks'][x];
		
		this.currentIndex = 0;
		this.fileRowHeight = 17;
		this.name = params['name'];
		path = params['path'];
		if(!path) {
			path = FCCookie.getCookie(this.name);
			if(!path)
				path = this.dirSeparator;
		}
		this.path = path;
		this.lsPath = params['paths']['lsPath'];
		this.imgPath = params['paths']['imgPath'];
		this.FCPanelView = params['FCPanelView'];
		this.urlPrefix = params['paths']['urlPrefix'];

		this.height = (this.FCPanelView.fc.height-50);

		this.calculateColumnsWidth();		

		// creating table with headers
		var tabHead = $('<div>').addClass('fc-folder-headers');
		tabHead.html(
			'<div class="fc-file-header fc-file-icon" style="width: '+this.iconWidth+'px">&nbsp;</div>'+
			'<div class="fc-file-header fc-file-name" style="width: '+this.nameWidth+'px">name</div>'+
			'<div class="fc-file-header fc-file-ext" style="width: '+this.extWidth+'px">ext</div>'+
			'<div class="fc-file-header fc-file-size" style="width: '+this.sizeWidth+'px">size</div>'+
			'<div class="fc-file-header fc-file-time" style="width: '+this.timeWidth+'px">time</div>'+
			'<div class="fc-file-header fc-file-attr" style="width: '+this.attrWidth+'px">attr</div><div class="fc-clear"></div>');
		this.FCPanelView.divFolderPanel.append(tabHead);
	
		// creating table container for files
		this.divFiles = $('<div>').addClass('fc-file-list').css({ 'height':this.height+"px"});
		this.FCPanelView.divFolderPanel.append(this.divFiles);
		this.loadFiles(path);
	},
	
	calculateColumnsWidth: function() {
		this.iconWidth = 16;
		this.extWidth = 35;
		this.sizeWidth = 50;
		this.timeWidth = 110;
		this.attrWidth = 35; 
		this.rowWidth = this.FCPanelView.divFolderPanel.width()-1;
		this.nameWidth = this.rowWidth-this.iconWidth-this.extWidth-this.sizeWidth-this.timeWidth-this.attrWidth;
	},

	showFiles: function(fileList) {
		var tabFiles = $('<div>').addClass('fc-table-file-list');
		var j = 0;
		for(i=0;i<fileList['folders'].length;i++) {
			var f = fileList['folders'][i];
			var tr = $('<div>').addClass('fc-file-row').addClass('fc-folder-row');
			tr.append(
				'<div class="fc-file-icon" style="width: '+this.iconWidth+'px"><img src="'+this.imgPath+'folder.gif" /></div>'+
				'<div class="fc-file-name" style="width: '+this.nameWidth+'px"><span class="fc-file-basename">'+f['base']+'</span></div>'+
				'<div class="fc-file-ext" style="width: '+this.extWidth+'px">'+f['ext']+'&nbsp;</div>'+
				'<div class="fc-file-size" style="width: '+this.sizeWidth+'px">&nbsp;</div>'+
				'<div class="fc-file-time" style="width: '+this.timeWidth+'px">'+f['time']+'</div>'+
				'<div class="fc-file-attr" style="width: '+this.attrWidth+'px">'+f['attr']+'</div>'
			);
			if(j++%2 == 0)
				tr.addClass('fc-alt-row');
			tr.mouseenter(function(){ $(this).addClass('fc-mouse-over'); });
			tr.mouseout(function(){	$(this).removeClass('fc-mouse-over'); });
			tr.data('file', f);
			tabFiles.append(tr);
		}

		var urlPath = this.urlPrefix+"/"+fileList['path'].replace("\\", '/');
		for(i=0;i<fileList['files'].length;i++) {
			var f = fileList['files'][i];
			var ext = this.imgPath+"default";
			if(this.availableIcons.indexOf( f['ext'].toLowerCase() ) >= 0)
				ext = this.imgPath+f['ext'].toLowerCase();

			if(this.urlPrefix)
				var link = "<a target='_blank' href='"+urlPath+f['name']+"'><span class='fc-file-basename'>"+f['base']+"</span></a>";
			else
				link =  "<span class='fc-file-basename'>"+f['base']+"</span>";

			var tr = $('<div>').addClass('fc-file-row');
			tr.append(
				'<div class="fc-file-icon" style="width: '+this.iconWidth+'px"><img src="'+ext+'.gif" /></div>'+
				'<div class="fc-file-name" style="width: '+this.nameWidth+'px">'+link+'</div>'+
				'<div class="fc-file-ext" style="width: '+this.extWidth+'px">'+f['ext']+'&nbsp;</div>'+
				'<div class="fc-file-size" style="width: '+this.sizeWidth+'px">'+f['size']+'&nbsp;</div>'+
				'<div class="fc-file-time" style="width: '+this.timeWidth+'px">'+f['time']+'</div>'+
				'<div class="fc-file-attr" style="width: '+this.attrWidth+'px">'+f['attr']+'</div>'
			);
			if(j++%2 == 0)
				tr.addClass('fc-alt-row');
			tr.mouseenter(function(){ $(this).addClass('fc-mouse-over'); });
			tr.mouseout(function(){	$(this).removeClass('fc-mouse-over'); });
			tr.data('file', f);
			tabFiles.append(tr);
		}

		this.divFiles.html("");
//		var dScrl = $('<div>').addClass('fc-file-list-scroller');
//		dScrl.append(tabFiles);
		this.divFiles.append(tabFiles);
	},

	moveUp: function() {
		if (this.currentIndex == 0)
			return;
		
		this.hideCursor();
		this.currentIndex--;
		this.showCursor();	
		this.setCursorInView();
	},

	moveDown: function() {
		if (this.currentIndex >= this.divFiles.find('div.fc-file-row').length-1)
			return;

		this.hideCursor();
		this.currentIndex++;
		this.showCursor();
		this.setCursorInView();
	},

	movePageUp: function() {
		this.hideCursor();

		this.currentIndex -= Math.round(this.height / this.fileRowHeight);
		if (this.currentIndex < 0)
			this.currentIndex = 0;

		this.showCursor();	
		this.setCursorInView();	
	},

	movePageDown: function() {
		this.hideCursor();

		this.currentIndex += Math.round(this.height / this.fileRowHeight);
		if (this.currentIndex > this.divFiles.find('div.fc-file-row').length-1)
			this.currentIndex = this.divFiles.find('div.fc-file-row').length-1;

		this.showCursor();	
		this.setCursorInView();	
	},
		
	
	moveToBegin: function() {
		if (this.currentIndex == 0)
			return;

		this.hideCursor();
		this.currentIndex = 0;
		this.showCursor();	
		this.setCursorInView();	
	},

	moveToEnd: function() {
		if (this.currentIndex >= this.divFiles.find('div.fc-file-row').length-1)
			return;

		this.hideCursor();
		this.currentIndex = this.divFiles.find('div.fc-file-row').length-1;
		this.showCursor();	
		this.setCursorInView();	
	},
		
	setCursorInView: function() {
		
		// MOVE VIEW TO MAKE CURSOR VISIBLE
		var divHeight = this.height;
		var filesHeight = this.divFiles.find('div.fc-file-row').length * this.fileRowHeight;
		if(divHeight > filesHeight) return;

		// FILE LIST IS HIGHER THAN VIEW
		// TAKING VIEW VERTICAL COORDINATES
		var divPosY1 = this.divFiles.scrollTop();
		var divPosY2 = divPosY1+this.height;

		// CALCULATING CURSOR POSITION
		var cy = this.currentIndex * this.fileRowHeight;
		
		// CHECKING IF CURSOR IS OUTSIDE VIEW
		// IS IT ABOVE?
		if(cy < divPosY1) {
			while(cy < divPosY1) {
				this.divFiles.scrollTop(divPosY1-this.fileRowHeight);
				divPosY1-=this.fileRowHeight;
			}
			return;
		}

		// IS IT BELOW?
		if(cy+this.fileRowHeight > divPosY2)
			while(cy+this.fileRowHeight > divPosY2) {
				divPosY1 += this.fileRowHeight;
				divPosY2 += this.fileRowHeight;
				this.divFiles.scrollTop(divPosY1);
			}
	},

	showCursor: function() {
		this.divFiles.find('div.fc-file-row').eq(this.currentIndex).addClass('fc-file-current-row');
	},

	hideCursor: function() {
		this.divFiles.find('div.fc-file-row').eq(this.currentIndex).removeClass('fc-file-current-row');
	},

	markFile: function() {
		this.divFiles.find('div.fc-file-row').eq(this.currentIndex).toggleClass('fc-file-marked-row');
	},

	getCurrentFile: function() {
		var data = this.divFiles.find('div.fc-file-current-row').data('file');
		return data.name;
	},

	isCurrentFolder: function() {
		return this.divFiles.find('div.fc-file-current-row').hasClass('fc-folder-row');
	},

	isCurrentMarked: function() {
		return this.divFiles.find('div.fc-file-current-row').hasClass('fc-file-marked-row');
	},
	
	doEnter: function(callBack) {
		if (this.isCurrentFolder()) {
			this.loadingFilesCallback = callBack;
			var name = this.getCurrentFile();
			this.path += (name + this.dirSeparator);
			this.loadFiles(this.path);
		}
		else {
			
			// HIT ENTER ON FILE
			if(this.urlPrefix) {
				var name = this.getCurrentFile();
				window.open(this.urlPrefix+'\\'+this['path']+name, "_blank");
			}
			if (callBack) 
				callBack();
		}
	},

	folderUp: function(callBack) {
		this.loadingFilesCallback = callBack;
		this.loadFiles(this.path + ".." + this.dirSeparator);
	},

	cleanMarkedFiles: function() {
		this.divFiles.find('div.fc-file-marked-row').removeClass('fc-file-marked-row');
	},
	
	getMarkedFiles: function() {
		var out = [ ]; 
		this.divFiles.find('div.fc-file-marked-row').each(function(i,b){
			var data = $(b).data('file');
			out.push(data.name);
		});
		return out;
	},

	getCurrentAndMarkedFiles: function() {
		var out = this.getMarkedFiles();
		if(!this.isCurrentMarked()) {
			var fn = this.getCurrentFile();
			if(fn != "")
				out.push(fn);
		}
		return out;
	},

	getCurrentPath: function() {
		var p = $.trim(this.path);
		if(!p) p = this.dirSeparator;
		return p;
	},

	makeBusy: function() {
		this.divFiles.find('div.fc-table-file-list').addClass('fc-table-busy');
	},

	turnOffBusy: function() {
		this.divFiles.find('div.fc-table-file-list').removeClass('fc-table-busy');
	},

	loadingFilesCallback: false, 	
	
	loadFiles: function(path, forceRefresh) {

		// HANDLE CONTEXT
		var _this = this;
		
		var retriveData = function(a) {
			_this.showFiles(a);
			_this.path = a.path;
			_this.FCPanelView.setTitle(_this.dirSeparator + a.path);
			
			// REMEMBER PATH FOR THIS VIEW
			FCCookie.setCookie(_this.name, a.path, 1000);
			_this.currentIndex = 0;
			
			// SHOW CURSOR ONLY IF PANEL IS ACTIVE
			if(_this.FCPanelView.isActive())
				_this.showCursor();
			
			// CALLBACKS
			if(_this.loadingFilesCallback)
				_this.loadingFilesCallback();

			if(_this.callbacks['onTabLoad'])
				_this.callbacks['onTabLoad'](_this);
		};
		

		// CHECKING CACHE 
		if(FCCache.getPath(path) && !forceRefresh) {
			retriveData(FCCache.getPath(path));
			return;
		}
		
		$.post(this.lsPath, {'path':path}, function(a){
			retriveData(a);
			FCCache.setPath(a.path, a);
		}, "json");
	},

	refreshPanel: function(callBack, forceRefresh) {
		this.loadingFilesCallback = callBack;
		this.loadFiles(this.path, forceRefresh);
	},
	
	doResetPath: function(callBack) {
		this.loadingFilesCallback = callBack;
		this.loadFiles(this.dirSeparator);
	},
	
	setInactive: function() {
		this.hideCursor();
	
		// CALLBACK - PANEL LOSE ACTIVE
		if (this.callbacks['onTabLoseFocus']) 
			this.callbacks['onTabLoseFocus'](this);		
	},

	setActive: function() {
		this.showCursor();
		
		// CALLBACK - PANEL LOSE ACTIVE
		if (this.callbacks['onTabGetFocus']) 
			this.callbacks['onTabGetFocus'](this);		
	},
	
	getName: function() {
		return this.name;
	},
	
	getID: function() {
		return this.randomID;
	}	
};

/********************************************************************************************* 
 * panel view  
 *********************************************************************************************/

/** {		
 * 'divPanelContainer' : panel div container (dom node), 
 * 'fc' : instance of FC class
 * 'name' : name of panel
 * 'path' : start path for panel
 * }
 */
function FCPanelView(params) {
	this.create(params);
};

FCPanelView.prototype = {

	container: false,
	fc: false,
	name: false,
	divTitlePanel: false,
	divFolderPanel: false,
	activeIndex: 0,
	panels: [],
	activeFolder: false,
	
	callbacks: {
		'onPanelGetFocus'	: false,	// panel get focus
		'onPanelLoseFocus'	: false		// panel lose focus
	},

	create: function(params) {

		// SETTING PANEL VIEW
		this.container = params['divPanelContainer'];
		this.fc = params['fc'];
		this.name = params['name'];
		
		// SETTING CALLBACKS
		for (x in params['fc']['callbacks'])
			this.callbacks[x] = params['fc']['callbacks'][x];

		this.divTitlePanel = $('<div>').addClass('fc-panel-title').html('tutaj tytuł');
		this.divFolderPanel = $('<div>').addClass('fc-folder-view');
		this.container.append(this.divTitlePanel);
		this.container.append(this.divFolderPanel);
		
		this.activeIndex = 0;
		this.panels = [
			new FCFolderView({
				'path': params['path'],
				'FCPanelView': this,
				'name': this.name+'0',
				'paths': this.fc.paths
			})
		];
		this.activeFolder = this.panels[0];
	},	

	setTitle: function(title) {
		this.divTitlePanel.html(title+" ("+this.name+")");
	},

	getName: function() {
		return this.name;
	},

	removeActive: function() {
		this.divTitlePanel.removeClass('fc-active-panel');
		this.getActiveFolder().setInactive();
		
		// CALLBACK - PANEL LOSE FOCUS
		if (this.callbacks['onPanelLoseFocus']) 
			this.callbacks['onPanelLoseFocus'](this);
	},
	
	setActive: function() {
		this.divTitlePanel.addClass('fc-active-panel');
		this.getActiveFolder().setActive();
		
		// CALLBACK - PANEL BECOME ACTIVE
		if (this.callbacks['onPanelGetFocus']) 
			this.callbacks['onPanelGetFocus'](this);
	},
	
	isActive: function() {
		return this.divTitlePanel.hasClass('fc-active-panel');
	},
	
	movePageDown: function() {
		this.getActiveFolder().movePageDown();
	},

	movePageUp: function() {
		this.getActiveFolder().movePageUp();
	},	
	
	getActiveFolder: function() {
		return this.panels[this.activeIndex];
	},
	
	moveUp: function() {
		this.getActiveFolder().moveUp();
	},

	moveDown: function() {
		this.getActiveFolder().moveDown();
	},

	moveToBegin: function() {
		this.getActiveFolder().moveToBegin();
	},

	moveToEnd: function() {
		this.getActiveFolder().moveToEnd();
	},
	
	markFile: function() {
		this.getActiveFolder().markFile();
	},

	doEnter: function(fun) {
		this.getActiveFolder().doEnter(fun);
	},

	folderUp: function(fun) {
		this.getActiveFolder().folderUp(fun);
	},

	getMarkedFiles: function() {
		return this.getActiveFolder().getMarkedFiles();
	},

	cleanMarkedFiles: function() {
		this.getActiveFolder().cleanMarkedFiles();
	},

	getCurrentPath: function() {
		return this.getActiveFolder().getCurrentPath();
	},

	getCurrentFile: function() {
		return this.getActiveFolder().getCurrentFile();
	},
	
	getCurrentAndMarkedFiles: function() {
		return this.getActiveFolder().getCurrentAndMarkedFiles();
	},

	refreshPanel: function(fun, forceRefresh) {
		this.getActiveFolder().refreshPanel(fun, forceRefresh);
	},

	makeBusy: function() {
		this.getActiveFolder().makeBusy();
	},
	
	turnOffBusy: function() {
		this.getActiveFolder().turnOffBusy();
	},
	
	doResetPath: function(callback) {
		this.getActiveFolder().doResetPath(callback);
	}
};

/*********************************************************************************************
 * 
 * @param {Object} element
 * @param {Object} options
 *
 *********************************************************************************************/

function FC(element, options) {
	this.create(element, options);
};

FC.prototype = {

	paths: {
		lsPath: 	"/files/ajax_ls",
		copyPath: 	"/files/ajax_copy",
		movePath: 	"/files/ajax_move",
		delPath: 	"/files/ajax_del",
		renPath: 	"/files/ajax_ren",
		mkdirPath: 	"/files/ajax_mkdir",
		imgPath:	"/img/ico-ext/"
	},

	callbacks: {
		'onPanelGetFocus'	: false,	// panel get focus
		'onPanelLoseFocus'	: false,	// panel lose focus
		'onTabGetFocus'		: false,	// tab get focus
		'onTabLoseFocus'	: false,	// tab lose focus
		'onTabLoad'			: false		// tab files loaded
	},

	height: '300',
	leftPath: false,
	rightPath: false,

	leftDiv: false,
	rightDiv: false,
	rootElement: false,
	leftPanel: false,
	rightPanel: false,
	activePanel: false,
	busy: false,

	create: function(element, options) {
		
		options = options || {};

		// SETTING OPTIONS
		for(x in options)
			this[x] = options[x];

		// PREPARING ELEMENT TO BUILD
		var root = $(element);
		this.rootElement = root;
		root.html("");
		root.addClass('fc-container').css({'height':this.height+'px'});
		
		var root2 = $('<div>').addClass('fc-border');
		root.append(root2);

		// CREATING DIV FOR PANELS
		this.leftDiv = $('<div>').addClass('fc-panel'); //.attr('id', 'fc-left-panel');
		this.rightDiv = $('<div>').addClass('fc-panel'); //.attr('id', 'fc-right-panel');

		// ADDING DIV 
		root2.append(this.leftDiv);
		root2.append(this.rightDiv);

		root2.append( $('<div>').addClass('fc-clear') );

		// CREATING PANEL VIEWS FOR LEFT/RIGHT
		this.leftPanel = new FCPanelView({
			'divPanelContainer' : this.leftDiv, 
			'fc' : this,
			'name' : "left",
			'path' : this.leftPath
		});
		this.rightPanel = new FCPanelView({
			'divPanelContainer' : this.rightDiv, 
			'fc' : this,
			'name' : "right",
			'path' : this.rightPath
		});
		
		this.activePanel = this.leftPanel;
		this.setLeftActive();
	},

	switchActivePanel: function() {
		this.activePanel.removeActive();
		this.activePanel = (this.activePanel == this.leftPanel ? this.rightPanel : this.leftPanel);
		this.activePanel.setActive();
	},

	setLeftActive: function() {
		this.activePanel.removeActive();
		this.activePanel = this.leftPanel;
		this.activePanel.setActive();
	},

	setRightActive: function() {
		this.activePanel.removeActive();
		this.activePanel = this.rightPanel;
		this.activePanel.setActive();
	},
	
	moveDown:  function() {
		this.activePanel.moveDown();
	},

	moveUp: function() {
		this.activePanel.moveUp();
	},

	movePageDown: function() {
		this.activePanel.movePageDown();
	},

	movePageUp: function() {
		this.activePanel.movePageUp();
	},
	
	moveToBegin: function() {
		this.activePanel.moveToBegin();
	},

	moveToEnd: function() {
		this.activePanel.moveToEnd();
	},
	
	markFile: function() {
		this.activePanel.markFile();
	},

	doEnter: function() {
		this.makeBusy();
		var _this = this;
		this.activePanel.doEnter(function(){
			_this.turnOffBusy();			
		});
	},
	
	doResetPath: function() {
		this.makeBusy();
		var _this = this;
		var count = 2;
		var dec = function() {
			count--;
			if(count == 0)
				_this.turnOffBusy();
		};
		this.leftPanel.doResetPath(dec);
		this.rightPanel.doResetPath(dec);
	},

	doCopy: function() {

		// SETTING SOURCE AND DESTINATION PANELS 
		var srcPanel = this.activePanel;
		var dstPanel = (this.activePanel == this.leftPanel ? this.rightPanel : this.leftPanel);

		var files = srcPanel.getCurrentAndMarkedFiles();
		var srcPath = srcPanel.getCurrentPath();
		var dstPath = dstPanel.getCurrentPath();
		
		// CAN'T COPY TO THE SAME FOLDER
		if(srcPath == dstPath) return;

		if(!confirm('Do you want to copy '+files.length+' file(s) to '+dstPath+' ?'))
			return;

		this.makeBusy();
		var _this = this;
		$.post(this.paths.copyPath, {'dstPath':dstPath, 'srcPath':srcPath, 'files':files}, function(a) {
			srcPanel.cleanMarkedFiles();
			_this.doRefresh(_this, true);
			dstPanel.refreshPanel(function(){
				_this.turnOffBusy();
			}, true);
		});
	},

	doMove: function() {

		// SETTING SRC I DESTINATION PANEL 
		var srcPanel = this.activePanel;
		var dstPanel = (this.activePanel == this.leftPanel ? this.rightPanel : this.leftPanel);

		var files = srcPanel.getCurrentAndMarkedFiles();
		var srcPath = srcPanel.getCurrentPath();
		var dstPath = dstPanel.getCurrentPath();

		// CAN'T MOVE TO THE SAME FOLDER
		if(srcPath == dstPath) return;
		
		if(!confirm('Do you want to move '+files.length+' file(s) to '+dstPath+' ?'))
			return;

		this.makeBusy();
		var _this = this;
		$.post(this.paths.movePath, {'dstPath':dstPath, 'srcPath':srcPath, 'files':files}, function(a) {
			_this.doRefresh(_this, true);
		});
	},

	/**
	 * return path which is actually in use (from active panel and its active tab)
	 */
	getCurrentActivePath: function() {
		return this.activePanel.getCurrentPath();
	},

	delFile: function() {
		var srcPath = this.activePanel.getCurrentPath();
		var files = this.activePanel.getCurrentAndMarkedFiles();

		if(!confirm('Do you want to delete '+files.length+' file(s)?'))
			return;
		
		this.makeBusy();
		var _this = this;
		$.post(this.paths.delPath, {'srcPath':srcPath, 'files':files}, function(a) {
			_this.doRefresh(_this);
		});
	},

	doRename: function() {
		var srcPath = this.activePanel.getCurrentPath();
		var file = this.activePanel.getCurrentFile();

		var name = prompt("Please enter new name", file);
		if(name == "" || name == null)
			return;
		
		this.makeBusy();
		var _this = this;
		$.post(this.paths.renPath, {'srcPath':srcPath, 'oldName':file, 'newName':name}, function(a) {
			_this.doRefresh(_this);
		});
	},
	
	doRefresh: function(_this, forceBoth) {

		// CHECKING IF PANELS HAVE SAME VIEW SO BOTH NEED TO BE REFRESH
		if (_this.leftPanel.getCurrentPath() == _this.rightPanel.getCurrentPath() || forceBoth) {
			var count = 2;
			var dec = function(){
				count--;
				if (count == 0) 
					_this.turnOffBusy();
			};
			_this.rightPanel.refreshPanel(dec, true);
			_this.leftPanel.refreshPanel(dec, true);
		}
		else {
			
			// REFRESHING ONLY ONE PANEL
			_this.activePanel.refreshPanel(function(){
				_this.turnOffBusy();
			}, true);
		}		
	},
	
	doReloadCurrentView: function() {
		if(this.busy) return;
		this.makeBusy();
		var _this = this;
		// REFRESHING ONLY ONE PANEL
		this.activePanel.refreshPanel(function(){
			_this.turnOffBusy();
		}, true);
	},
	
	/**
	 * used do refresh cache without reloading view
	 */
	doReloadPath: function(path, callback) {
		// CLEANING CACHE
		FCCache.removePath(path);
		if (this.busy)
			return;
		var _this = this;
		this.makeBusy();
		$.post(this.paths['lsPath'], {'path':path}, function(a){
			FCCache.setPath(a.path, a);
			if(callback)
				callback();
			
			// RELOADS ALL TABS WITH THE SAME PATH
			for(var i=0;i<_this.leftPanel.panels.length;i++)
				if(_this.leftPanel.panels[i].getCurrentPath() == path)
					_this.leftPanel.panels[i].loadFiles(path);
			for(var i=0;i<_this.rightPanel.panels.length;i++)
				if(_this.rightPanel.panels[i].getCurrentPath() == path)
					_this.rightPanel.panels[i].loadFiles(path);

			_this.turnOffBusy();
		}, "json");		
	},
	
	folderUp: function() {
		this.makeBusy();
		var _this = this;
		this.activePanel.folderUp(function(){
			_this.turnOffBusy();
		});
	},

	doNewFolder: function() {
		var srcPath = this.activePanel.getCurrentPath();

		var name = prompt("Please enter folder name", "");
		if(name == "" || name == null)
			return;

		this.makeBusy();
		var _this = this;
		$.post(this.paths.mkdirPath, {'srcPath':srcPath, 'name':name}, function(a) {
			_this.doRefresh(_this);
		});
	},
	
	makeBusy: function() {
		this.leftPanel.makeBusy();
		this.rightPanel.makeBusy(); 
		this.busy = true;
	},

	turnOffBusy: function() {
		this.leftPanel.turnOffBusy();
		this.rightPanel.turnOffBusy();
		this.busy = false; 
	},

	keyDown: function(event) {
		
//		console.log(event.keyCode);
//		event.preventDefault();

		var _keyIndex = [38, 40, 9, 13, 56, 37, 39, 32, 46, 8, 116, 117, 118, 36, 35, 33, 34, 120, 82].indexOf(event.keyCode);
		
		if ( _keyIndex == -1 || _keyIndex == null ) {
			return true;
		}

		event.preventDefault();
//		console.log(event.keyCode);
		
		if(!this.busy) {
			switch(event.keyCode) {
	
			case 32: // SPACE
				this.markFile();
				break;
	
			case 8: // BACKSPACE
				this.folderUp();
				break;

			case 33: // PGUP
				this.movePageUp();
				break;

			case 34: // PGDOWN
				this.movePageDown();
				break;
				
			case 36: // HOME
				this.moveToBegin();
				break;

			case 35: // END
				this.moveToEnd();
				break;
				
			case 38: // UP
				this.moveUp();
				break;
	
			case 40: // DOWN
				this.moveDown();
				break; 
	
			case 37: // LEFT
				this.setLeftActive();
				break;
	
			case 39: // RIGHT
				this.setRightActive();
				break; 
	
			case 9:	// TAB
				this.switchActivePanel();
				break;
	
			case 13: // ENTER
				this.doEnter();
				break;
				
			case 116: // F5
				this.doCopy();
				break;
				
			case 117: // F6
				if ( event.shiftKey )
					this.doRename();
				else
					this.doMove();
				break;
				
			case 46: // DEL
				this.delFile();
				break;

			case 118: // F7
				this.doNewFolder();
				break;

			case 120: // F9
				this.doResetPath();
				break;
			
			case 82: // R
				if ( event.ctrlKey )
					this.doReloadCurrentView();
				break;
			}		
		}
	}
/*
	if (navigator.appVersion.indexOf('MSIE') != -1) {
		event.keyCode = 0; 
		event.returnValue = false;
	}	
*/
};

