/*
* File Manager
*
* Copyright (c) 2010 Tom Kay - oridan82@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.*
*
*/

;(function($){
	var optionDefaults = {
		id				: '',
		path			: '',
		upload			: false,
		readonly		: true,
		fixedPath		: false,
		
		baseClass		: 'fmBase',
		folderClass		: 'fmFolder',
		trashClass		: 'fmTrash',
		loadingClass	: 'fmLoading',

		highlightClass	: '',
		hoverClass		: ''
	};
	
	/*
	var hayCarpeta = false;
	var hayFichero = false;
	*/

	$.fn.fileManager = function(settings, pluploadOptions) {
		var mbOptions = $.extend({}, optionDefaults, settings);
		if (!mbOptions.ajaxPath) {
			alert('ajaxPath not specified'); return;
		}

		if (mbOptions.fixedPath) mbOptions.path = ""; //LC
		pluploadOptions = $.extend({url:mbOptions.ajaxPath,runtimes:'html5,html4'}, pluploadOptions);

		var query = $.extend({},{path:mbOptions.path},mbOptions.get);

		this.each(function () { // swap with getJSON so not duplicating ajax
			var $sel = $(this);
			
			$.getJSON(mbOptions.ajaxPath, query, function(data, status) {
				$sel.data('result',data);
				$sel.data('options',mbOptions);
				if (status != "success") {
					var msg = "Sorry but there was an error: "+status;
				}
				// process response
				$sel.empty();

				if (mbOptions.readonly) {
					if (mbOptions.id == "barra1") {
						$sel.append('<div>Informes</div>');
					}	
					if (mbOptions.id == "barra2") {
						$(".caminoMigas").html(data.ruta+"<span id='nombrefichero'></span>");
						//$sel.append("<div class='barra2' >"+data.ruta+"<span id='nombrefichero'></span></div>");
					}	
					//if (data.path && data.path.indexOf("/") > -1) DrawItem($sel,{path:'..',title:'..',type:1});
					//DrawItem($sel,{path:'',title:'',type:2}); //LC quitar papelera
				}
				if ($(data.files).length == 0) {
					$sel.append('<div class="TitularSeccion"><h3>'+NO_DOCUMENTS+'</h3></div>');
				}
				
				//iconos de todas las carpetas
				$(data.files).each(function () {
					DrawItemCarpeta($sel,this);
				});
				
				//lista completa de ficheros de la carpeta seleccionada
				$sel.append('<div class="descarga"><table id="tablaInformes" name="tablaInformes"><tbody></tbody></table></div>');
				
				$(data.files).each(function () {
					DrawItemFichero($sel, this, $("#tablaInformes"));
				});

				$sel.append('<div style="clear:both"></div>');
				
				//if (!mbOptions.readonly)
				//	$sel.append($('<div>New Folder</div>').button().bind('click',NewFolder));
				
				if (mbOptions.upload) {
					var ul = $('<div></div>').hide();
					$sel.append($('<div>Upload Files</div>').button().bind('click',{container:ul},UploadFiles));
					$sel.append(ul);
				}
				
				// end processing
				
				$('.fmItem').bind('click',FileClick); //LC cambiado dblclick por click
				//$('.fmItem').bind('mouseover',showFileName); //LC cambiado dblclick por click
				//$('.fmItem').bind('mouseout',hideFileName); //LC cambiado dblclick por click
				$('.'+mbOptions.folderClass,$sel).bind('click',FolderClick); //LC cambiado dblclick por click
				$('.ruta').bind('click',FolderClickUrl); //LC cambiado dblclick por click
				
				if(typeof irAbajo == 'function') { 
					irAbajo(); 
				}				
				
			});

			function UploadFiles(event) {
				$(event.data.container).toggle();
				if (plupload && pluploadOptions) {
					if (!$(event.data.container).pluploadQueue) {
						$(event.data.container).html('Must install Plupload jquery plugin.'); return;
					}
					var opts = pluploadOptions;
					opts.url = opts.url+ (opts.url.indexOf('?') < 0 ? '?' : '&') +'path='+$sel.data('result').path;
					$(event.data.container).pluploadQueue(opts);
					$(event.data.container).pluploadQueue().bind('FileUploaded',function (uploader,file,response) {
						if (uploader.total.queued == 0) {
							RefreshView($sel);
						}
					});
				} else {
					$(event.data.container).html('Must install Plupload.');
				}
			}
			function NewFolder() {
				var path = prompt('Enter Folder Name:');
				if (!path) return;
				if ($sel.data('result').path) path = $sel.data('result').path + '/' + path;
				ReloadFolder($sel, path);
			}
		});


		function FileDropped(event,ui) {
			var from = $(ui.draggable);
			var to = $(this);

			if ($(this).hasClass(mbOptions.trashClass)) {
				if (confirm('Really delete "'+from.data('item').title+'"?  This cannot be undone')) {
					ajaxData = {path:mbOptions.path, 'delete':from.data('item').path};
					$.ajax({url:mbOptions.ajaxPath, data:ajaxData, dataType:'script', complete:function() {
						RefreshView(from.data('item').target);
					}});
				}
			} else {
				return Rename(from.data('item').target,from.data('item').path,to.data('item').path+'/'+from.data('item').path);
			}
		};
		function Rename(view,from,to) {
			ajaxData = {path:mbOptions.path,mFrom:from,mTo:to};
			$.ajax({url:mbOptions.ajaxPath,data:ajaxData,dataType:'script',complete:function() {
				RefreshView(view);
			}});
		}
		function FolderClick() {
			$("#fileMan").show();
			var item = $(this).data('item');
			if (item.type != ICONTYPE_FOLDER) return;
			var path = item.path;
			if (item.target.data('result').path) path = item.target.data('result').path + '/' + path;
			ReloadFolder($("#fileMan"), path);
		}
		function FolderClickUrl() {
			ReloadFolder($("#fileMan"), this.title);
		}
		function FileClick() {
			//var item = $(this).data('item');
			//var path = item.path;
			//if (item.target.data('result').path) path = item.target.data('result').path + '/' + path;
			location.href="ajax.php?path="+$(this).find("a").attr("href")+"&url=/informes/descargar_informe";
			return false;
		}
		function showFileName() {
			//$("#nombrefichero").html("/ "+this.innerHTML);
			$("#nombrefichero").html("/ "+this.title);
		}
		function hideFileName() {
			$("#nombrefichero").html("");
		}
		function RefreshView(target) {
			ReloadFolder(target,target.data('result').path);
		}
		function ReloadFolder(target,path) {
			target.fileManager($.extend({},mbOptions,{id:'barra2', fixedPath:false, path:path}),pluploadOptions);
		};

		var ICONTYPE_FILE = 0;
		var ICONTYPE_FOLDER = 1;
		var ICONTYPE_TRASH = 2;
		var ICONTYPE_PATRAS = 3;
		
		
		function DrawItemCarpeta(target, item) {
			//if (item.type == ICONTYPE_FOLDER && mbOptions.fixedPath) return;
			if (item.type != ICONTYPE_FOLDER && item.type != ICONTYPE_TRASH)
				return;
			
			item.target = $(target);
			item.fullPath = item.target.data('result').rootPath + item.target.data('result').path + '/' + item.path;
			var icon = $('<div title="'+item.title+'"></div>');
			icon.data('item',item);
			icon.addClass(mbOptions.baseClass);
			
			// set classes
			if (item.type == ICONTYPE_FOLDER){
				if(item.title == "..") icon.addClass(mbOptions.folderClass+" fmPatras");
				if(item.title != "..") icon.addClass(mbOptions.folderClass);
			}	
			else if (item.type == ICONTYPE_TRASH)
				icon.addClass(mbOptions.trashClass);
			else 
				icon.addClass("fmItem");
				
			
			// set draggables
			//if (!mbOptions.readonly) {
			//	if (item.type == ICONTYPE_FOLDER || item.type == ICONTYPE_TRASH)
			//		icon.droppable({tolerance:'intersect',accept:'.'+mbOptions.baseClass,drop:FileDropped,hoverClass:mbOptions.hoverClass,activeClass:mbOptions.highlightClass});
			//	if (item.type != ICONTYPE_TRASH && item.path != '..')
			//		icon.draggable({stack:'files',revert:true,zIndex:1000,opacity:0.5,scroll:false});
			//}
			
			// events
			if (mbOptions.events) {
				$.each(mbOptions.events,function (index,value) {
					icon.bind(index, value);
				});
			}
			icon.data('result',target.data('result'));
			
			target.append(icon);
			if (!item.path) return;

			//if (mbOptions.readonly) return;
				
			var ext = item.path.match(/\.[^.\b]*$/i);
			if (ext) ext = ext[0];
			else ext = '';
			var basename = item.path.replace(ext,'');

			
			var label = $('<div class="label">'+item.title+'</div>')
				.prependTo(icon)//.bind('dblclick',function() {return false;})
				.bind('click',function () {
					if (!mbOptions.readonly) {
						renamebox.show().focus();
						return false;
					}
				});
			
		}
		function DrawItemFichero(target, item, parcial) {
			//if (item.type == ICONTYPE_FOLDER && mbOptions.fixedPath) return;
			if (item.type == ICONTYPE_FOLDER || item.type == ICONTYPE_TRASH)
				return;
			
			item.target = $(target);
			item.fullPath = item.target.data('result').rootPath + item.target.data('result').path + '/' + item.path;
			
			//icon.addClass(mbOptions.baseClass + '2');
			
			var nombreicon = "";
			// set classes
			if (item.fullPath.toUpperCase().indexOf(".PDF") > -1)
				nombreicon = "icono_pdf.png";
			else if (item.fullPath.toUpperCase().indexOf(".DOC") > -1)
				nombreicon = "icono_word.png";
			else if (item.fullPath.toUpperCase().indexOf(".ZIP") > -1)
				nombreicon = "icono_zip.png";
			else if (item.fullPath.toUpperCase().indexOf(".TXT") > -1)
				nombreicon = "icono_txt.png";
			else if (item.fullPath.toUpperCase().indexOf(".XLS") > -1)
				nombreicon = "icono_excel.png";
			else 
				nombreicon = "file64.png";
			
			if (item.type == ICONTYPE_FILE && item.path.search(/.jpeg|.jpg|.png|.gif|.tif|.tiff/i) > -1) {
				nombreicon = "icono_img.png";
			}
			var icon = $('<tr><td class="icono fmItem" title="' + item.title + '"><a href="' + item.fullPath + '"><img src="img/informes/' + nombreicon + '" alt="descargar ' + item.title + '" title="descargar ' + item.title + '" style="width:32px; height:32px;" /></a></td><td class="titulo fmItem" title="' + item.title + '"><a href="' + item.fullPath + '">' + item.title + '</a></td><td class="fmItem" title="' + item.title + '"><a href="' + item.fullPath + '">' + item.fecha + '</a></td><td class="fmItem" title="' + item.title + '"><a href="' + item.fullPath + '">' + item.size + ' Kb.</a></td></tr>');
			icon.data('item',item);
			
			// events
			if (mbOptions.events) {
				$.each(mbOptions.events,function (index,value) {
					icon.bind(index, value);
				});
			}
			icon.data('result',target.data('result'));
			
			parcial.append(icon);
			if (!item.path) return;

			//if (mbOptions.readonly) return;
				
			var ext = item.path.match(/\.[^.\b]*$/i);
			if (ext) ext = ext[0];
			else ext = '';
			var basename = item.path.replace(ext,'');

/*			
			var label = $('<div class="label2">'+item.title+'</div>')
				.prependTo(icon)//.bind('dblclick',function() {return false;})
				.bind('click',function () {
					if (!mbOptions.readonly) {
						renamebox.show().focus();
						return false;
					}
				});
*/			
		}
		
		return $(this);
	};
})(jQuery);

