/**
 * +-------------------------------------------------------------------+
 * |                        7t-File Manager                            |
 * |                                                                   |
 * | Copyright Ankur Sharma               http://www.7tech.co.in       |
 * |                                                                   |
 * +-------------------------------------------------------------------+
 * | The file is a part of 7T-FileManager plugin script.               |
 * +-------------------------------------------------------------------+
 */
 

function resize_textbox(){
	h=jQuery(window).height();
	jQuery("#left-col,#right-col").height(h-90);				
}
jQuery(document).ready(function(){
	resize_textbox(); 
	jQuery(window).resize(function(){ setTimeout('resize_textbox()',500); }); 

	current_working_dir=new Array();
	if(jQuery("#left-col .selected-folder")!=undefined)
	{
		main=jQuery("#left-col .selected-folder");
		element=main.parent().parent();
		while(element.hasClass('folder-wrapper') || element.hasClass('sub-folder-wrapper'))
		{
			if(element.hasClass('folder-wrapper'))
			{
				current_working_dir.push(element.find(".folder-name").html());
			}
			element=element.parent().parent();
		}
	}
	current_working_dir.reverse();
	jQuery(".folder-link").live("click",function(){
		if(jQuery(this).hasClass('folder-open')){
			jQuery(this).removeClass('folder-open').addClass('folder-close').parent().parent().find('.sub-folder-wrapper:first').hide();
		} else if(jQuery(this).hasClass('folder-close')){
			if(jQuery(this).parent().parent().find('.sub-folder-wrapper:first').html()!=""){
				jQuery(this).removeClass('folder-close').addClass('folder-open').parent().parent().find('.sub-folder-wrapper:first').show();
			} else{
				main=jQuery(this);
				element=jQuery(this).parent().parent();
				folder=new Array();
				while(element.hasClass('folder-wrapper') || element.hasClass('sub-folder-wrapper'))
				{
					if(element.hasClass('folder-wrapper'))
					{
						folder.push(element.find(".folder-name").html());
					}
					element=element.parent().parent();
				}
			
				jQuery.post(document.URL, {'ajax_request':1, "get_left_col_sub_dir":folder.reverse()}, function(result) {
					if(result.success==1)
					{
						main.removeClass('folder-close').addClass('folder-open').parent().parent().find('.sub-folder-wrapper:first').html(result.data).show();
					}else{
						alert("ERROR: "+result.error);
					}
				},"json");				
			}
		}
		
		return false;
	});
	
	jQuery(".folder-name").live("click",function(){
		main=jQuery(this);
		folder=new Array();
		element=jQuery(this).parent().parent();
		while(element.hasClass('folder-wrapper') || element.hasClass('sub-folder-wrapper'))
		{
			if(element.hasClass('folder-wrapper'))
			{
				folder.push(element.find(".folder-name").html());
			}
			element=element.parent().parent();
		}
		postdata={'ajax_request':1,"get_right_col_sub_dir":folder.reverse()};
		if(jQuery(this).parent().parent().find('.sub-folder-wrapper:first').html()=="" && main.parent().find(".folder-link").hasClass('folder-close')){
			postdata["get_left_sub_dir_too"]=1;
		}
		jQuery.post(document.URL,postdata,function(result){
			if(result.success==1){
				jQuery("#left-col .selected-folder").removeClass('selected-folder');		
				main.addClass('selected-folder');
				current_working_dir=folder.slice(0);
				jQuery("#right-col").html(result.data);
				if(result.left_sub_dir!=undefined){
					main.parent().parent().find('.sub-folder-wrapper:first').html(result.left_sub_dir)
					main.parent().find(".folder-link").removeClass("folder-close").addClass("folder-open");
				}
			}else{
				alert("ERROR: "+result.error);
			}
		},"json");
	});
	jQuery(".folder-type").live("dblclick",function(){
		folder=new Array();
		folder=current_working_dir.slice(0);
		foldername=jQuery(this).find(".file-name").html();
		folder.push(foldername);
		newsel=jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper .folder-name").filter(function(){ return jQuery(this).html()==foldername;  });
		postdata={'ajax_request':1,"get_right_col_sub_dir":folder};
		if(newsel.parent().find(".folder-link").hasClass("folder-close") && newsel.parent().parent().find('.sub-folder-wrapper:first').html()==""){
			postdata["get_left_sub_dir_too"]=1;
		}
		jQuery.post(document.URL,postdata,function(result){	
			if(result.success==1){
				if(newsel.hasClass("folder-name")){
					jQuery("#left-col .selected-folder").removeClass("selected-folder");
					newsel.addClass("selected-folder");
					if(result.left_sub_dir!=undefined){
						newsel.parent().parent().find('.sub-folder-wrapper:first').html(result.left_sub_dir)
						newsel.parent().find(".folder-link").removeClass("folder-close").addClass("folder-open");
					}
				}
				current_working_dir=folder;
				jQuery("#right-col").html(result.data);
			}else{
				alert("ERROR: "+result.error);
			}
		},"json");
	});
	jQuery("#refresh_btn").click(function(){
		folder=current_working_dir.slice(0);
		jQuery.post(document.URL,{'ajax_request':1,"get_right_col_sub_dir":folder},function(result){
			if(result.success==1){
				jQuery("#right-col").html(result.data);
			}else{
				alert("ERROR: "+result.error);
			}
		},"json");
	});
	jQuery("#up_btn").click(function(){
		folder=new Array();
		folder=current_working_dir.slice(0);
		if(folder.length>1)
		{
			folder.pop();
			jQuery.post(document.URL,{'ajax_request':1,"get_right_col_sub_dir":folder},function(result){
				if(result.success==1){
					newsel=jQuery("#left-col .selected-folder").parents(".folder-wrapper").find(".folder-name").filter(function(){ return jQuery(this).html()==folder[folder.length-1];  });
					if(newsel.hasClass("folder-name"))
					{
						jQuery("#left-col .selected-folder").removeClass("selected-folder");
						newsel.addClass("selected-folder");
					}
					current_working_dir=folder;
					jQuery("#right-col").html(result.data);
				}else{
					alert("ERROR: "+result.error);
				}
			},"json");
		}
	});
	jQuery("#newfile_btn").click(function(){
		jQuery("#data_container").html('<div id="the-popup">New File Name:<br><input id="filename-textbox" type="text" value=""  /><br><br>Current Path where file will be created:<br><span>/'+current_working_dir.join('/')+'/</span><br><br><div><input id="createfile" type="button" value="Create" /><input class="r-float" onclick="tb_remove()" type="button" value="Cancel" /><div class="clear"></div></div></div>');
		tb_show('Create New File','#TB_inline?height=150&width=400&inlineId=data_container');
		jQuery("#data_container").html('');
		jQuery("#createfile").click(function(){
			if(jQuery("#filename-textbox").val()!=""){
				folder=current_working_dir.slice(0);
				jQuery.post(document.URL,{'ajax_request':1,"create_new_file":jQuery("#filename-textbox").val(),"path":folder},function(result){
						if(result.success==1){
							jQuery("#right-col").html(result.data);
						}else{
							alert("ERROR: "+result.error);
						}
				},"json");
				tb_remove();
			}else{
					alert("Please enter a file name.");
			}
		});
	});
	jQuery("#rename_btn").click(function(){
		if(jQuery("#right-col .ui-selected .file-name").length==0){
			alert("Please select a file to rename.");
		}else if(jQuery("#right-col .ui-selected .file-name").length==1){
			jQuery("#data_container").html('<div id="the-popup">New Name<span>(Enter only name)</span>:<br><input id="filename-textbox" type="text" value=""  /><br><br>Old file name with complete path:<br><span>/'+current_working_dir.join('/')+'/'+jQuery("#right-col .ui-selected .file-name").html()+'</span><br><br><div><input id="renamefile" type="button" value="Rename" /><input class="r-float" onclick="tb_remove()" type="button" value="Cancel" /><div class="clear"></div></div></div>');
			tb_show('Rename a File','#TB_inline?height=150&width=400&inlineId=data_container');
			jQuery("#data_container").html('');			
			jQuery("#renamefile").click(function(){
				if(jQuery("#filename-textbox").val()!=""){
					folder=current_working_dir.slice(0);
					jQuery.post(document.URL,{'ajax_request':1,"new_name":jQuery("#filename-textbox").val(),"path":folder,"old_name":jQuery("#right-col .ui-selected .file-name").html()},function(result){
							if(result.success==1){
								jQuery("#right-col").html(result.data);
								if(jQuery("#left-col .selected-folder").html()== folder.pop()){
								jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
							}
							}else{
								alert("ERROR: "+result.error);
							}
					},"json");
					tb_remove();
				}else{
					alert("Please enter a file name.");
				}
			});
		} else {
			alert("Please select only single file.");
		}
	});
	jQuery("#newfolder_btn").click(function(){
		jQuery("#data_container").html('<div id="the-popup">New Folder Name:<br><input id="filename-textbox" type="text" value=""  /><br><br>Current Path where folder will be created:<br><span>/'+current_working_dir.join('/')+'/</span><br><br><div><input id="createfolder" type="button" value="Create" /><input class="r-float" onclick="tb_remove();" type="button" value="Cancel" /><div class="clear"></div></div></div>');
		tb_show('Create New Folder','#TB_inline?height=150&width=400&inlineId=data_container');
		jQuery("#data_container").html('');
		jQuery("#createfolder").click(function(){
			if(jQuery("#filename-textbox").val()!=""){
				folder=current_working_dir.slice(0);
				jQuery.post(document.URL,{'ajax_request':1,"create_new_folder":jQuery("#filename-textbox").val(),"path":folder},function(result){
						if(result.success==1){
							jQuery("#right-col").html(result.data);
							if(jQuery("#left-col .selected-folder").html()== folder.pop()){
								jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
							}
						}else{
							alert("ERROR: "+result.error);
						}
				},"json");
				tb_remove();
			} else {
				alert("Please select only single file.");
			}
		});
	});
	jQuery("#download_btn").click(function(){
		if(jQuery("#right-col .ui-selected.folder-type").length==0)
		{
			url=document.URL.split("#");
			folder=current_working_dir.slice(0);
			url[0]+=url[0].contains("?")?"&":"?";
			url[0]+="download_file_path="+folder.join("/")+"&ajax_request=1&download_file=";
			jQuery("#right-col .ui-selected .file-name").each(function(i,v){
				jQuery("body").append('<iframe class="downloadiframe" src="'+url[0]+jQuery(v).html()+'"></iframe>');
			});
		}else{
			alert('Select files only.');
		}
	});
	jQuery("#edit_btn,#codeedit_btn").click(function(){
			allowedExt=['','basic', 'brainfuck' ,'c','coldfusion','cpp','css','html','java','js','pas','perl' ,'php','python','robotstxt', 'ruby','sql','tsql', 'vb', 'xml', 'txt'];
		if(jQuery("#right-col .ui-selected").length==1 && jQuery("#right-col .ui-selected.file-type").length==1 && allowedExt.indexOf(jQuery("#right-col .ui-selected").attr('ext'))>-1)
		{
			url=document.URL.split("#");
			folder=current_working_dir.slice(0);
			url[0]+=url[0].contains("?")?"&":"?";
			url[0]+="filepath_for_edit="+folder.join("/")+"&filename="+jQuery("#right-col .ui-selected .file-name").html()+"&ajax_request=1&codeedit="+(jQuery(this).attr("id")=="codeedit_btn"?1:0);
			window.open(url[0]);
		}
	});
	jQuery("#permission_btn").click(function(){
		files_selected=new Array();
		jQuery("#right-col .ui-selected .file-name").each(function(i,v){ files_selected.push(jQuery(v).html()); });
		if(files_selected.length>0)
		{
			jQuery("#data_container").html('<div id="the-popup">Selected Files:<br><span>/'+current_working_dir.join("/")+"/"+files_selected.join("<br>/"+current_working_dir.join("/")+"/")+'</span><br><br><div>File Permission:<input type="text" id="file-permission-textbox" value="'+jQuery("#right-col .ui-selected .file-permission").last().html()+'" size="3" maxlength="3" /><br><br><input id="changepermission" type="button" value="Change" /><input class="r-float" onclick="tb_remove();" type="button" value="Cancel" /><div class="clear"></div></div></div>');
			tb_show('Change Permissions','#TB_inline?height=300&width=420&inlineId=data_container');
			jQuery("#data_container").html('');
			jQuery("#changepermission").click(function(){
				per_value=jQuery("#file-permission-textbox").val();
				if(per_value.length==3 && !isNaN(per_value) && per_value[0]<8 && per_value[1]<8 && per_value[2]<8){
					folder=current_working_dir.slice(0);
					jQuery.post(document.URL,{'ajax_request':1,"change_permission":files_selected,"path":folder,"permission_val":'0'+per_value},function(result){
							if(result.success==1){
								jQuery("#right-col").html(result.data);
							}else{
								alert("ERROR: "+result.error);
							}
					},"json");
					tb_remove();
				}else{
					alert('Wrong file permission format');
				}			
			});
		}
	});
	jQuery("#delete_btn").click(function(){
		files_selected=new Array();
		jQuery("#right-col .ui-selected .file-name").each(function(i,v){ files_selected.push(jQuery(v).html());});
		if(files_selected.length>0)
		{
			jQuery("#data_container").html('<div id="the-popup">You are about to delete:<br><span>/'+current_working_dir.join("/")+"/"+files_selected.join("<br>/"+current_working_dir.join("/")+"/")+'</span><br><br><div><input id="deletefiles" type="button" value="Delete" /><input class="r-float" onclick="tb_remove();" type="button" value="Cancel" /><div class="clear"></div></div></div>');
			tb_show('Delete File/Folder','#TB_inline?height=300&width=420&inlineId=data_container');
			jQuery("#data_container").html('');			
			jQuery("#deletefiles").click(function(){
				folder=current_working_dir.slice(0);
				jQuery.post(document.URL,{'ajax_request':1,"delete_files":files_selected,"path":folder},function(result){
						if(result.success==1){
							jQuery("#right-col").html(result.data);
							if(jQuery("#left-col .selected-folder").html()== folder.pop()){
								jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
								if(jQuery("#right-col .folder-type").length==0){ jQuery("#left-col .selected-folder").parent().find(".folder-link").removeClass("folder-open folder-close").addClass("folder-line"); }
							}
						}else{
							if(result.data!=undefined){
								jQuery("#right-col").html(result.data);
								if(jQuery("#left-col .selected-folder").html()== folder.pop()){
									jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
								}
							}
							alert("ERROR: "+result.error);
						}
				},"json");
				tb_remove();
			});
		}
	});
	jQuery(".folder-type,.file-type").live("click",function(e){
	    if(jQuery(this).hasClass("ui-selected")){
	   	 jQuery(this).removeClass("ui-selected");
	   }
	    else{
	    	if(!e.ctrlKey){jQuery(".ui-selected").removeClass("ui-selected");}
		jQuery(this).addClass("ui-selected");
	   }
	});
	jQuery("#upload_btn").click(function(){
		var uploader = new plupload.Uploader({
			runtimes : "html5,silverlight,flash,html4",
			browse_button : 'uploadfiles',
			container : 'the-popup',
			multipart_params : {upload_files_path:current_working_dir.join("/"),ajax_request:1},
			url : '',
			flash_swf_url : jQuery('#total_wrapper').attr('plg_path')+'/other/plupload.flash.swf',
			silverlight_xap_url : jQuery('#total_wrapper').attr('plg_path')+'/other/plupload.silverlight.xap'
		});
		jQuery("#data_container").html('<div id="the-popup" class="the-popup2">Files will be uploaded at:<br><span>/'+current_working_dir.join("/")+'/</span><br><br><div><input id="uploadfiles" type="file" value="Select" /><input class="r-float" onclick="tb_remove();" type="button" value="Cancel" /><div class="clear"></div></div><div id="filelist"></div></div>');
		tb_show('Upload Files','#TB_inline?height=350&width=580&inlineId=data_container');
		jQuery("#data_container").html('');
			
		uploader.init();
		uploader.bind('FilesAdded', function(up, files) {
			jQuery.each(files, function(i, file) {
				jQuery('#filelist').append(
					'<div id="' + file.id + '">' +
					file.name + ' <span class="filesize">(' + plupload.formatSize(file.size) + ')</span><span2><span class="progressbar_container"><span class="progressbar">&nbsp;</span></span> <b></b></span2>' +
				'<div class="clear"></div></div>');
			});	
			up.refresh(); // Reposition Flash/Silverlight
			uploader.start();
		});
	
		uploader.bind('UploadProgress', function(up, file) {
			jQuery('#' + file.id + " b").html(file.percent + "%");
			jQuery('#' + file.id + " .progressbar").css("width",(file.percent*2)+"px");
		});
	
		uploader.bind('Error', function(up, err) {
			jQuery('#filelist').append("<div>Error: " + err.code +
				", Message: " + err.message +
				(err.file ? ", File: " + err.file.name : "") +
				"</div>"
			);	
			up.refresh(); // Reposition Flash/Silverlight
		});
	
		uploader.bind('FileUploaded', function(up, file) {
			jQuery('#' + file.id + " b").html("100%");
			jQuery('#' + file.id + " .progressbar").css("width","200px");
		});
		uploader.bind('UploadComplete', function(up, file) {
			folder=current_working_dir.slice(0);
			jQuery.post(document.URL,{'ajax_request':1,"get_right_col_sub_dir":folder},function(result){
				if(result.success==1){
					jQuery("#right-col").html(result.data);
				}else{
					alert("ERROR: "+result.error);
				}
			},"json");
		});
	});
		
	jQuery("#copy_btn").click(function(){
		files_selected=new Array();
		jQuery("#right-col .ui-selected .file-name").each(function(i,v){ files_selected.push(jQuery(v).html());});
		if(files_selected.length>0)
		{
			jQuery("#data_container").html('<div id="the-popup">You are copying following files:<br><span>/'+current_working_dir.join("/")+"/"+files_selected.join("<br>/"+current_working_dir.join("/")+"/")+'</span><br><br>Enter the path where you want to copy these files:<br><input id="copy-path-textbox" type="text" value="/'+current_working_dir.join('/')+'"  /><br><br><div><input id="copyfiles" type="button" value="Copy" /><input class="r-float" onclick="tb_remove();" type="button" value="Cancel" /><div class="clear"></div></div></div>');
			tb_show('Copy Files','#TB_inline?height=350&width=420&inlineId=data_container');
			jQuery("#data_container").html('');
			jQuery("#copyfiles").click(function(){
				folder=current_working_dir.slice(0);
				destination_path=new Array();
				jQuery("#copy-path-textbox").val().replace('\\','/').split("/").forEach(function(e){if(jQuery.trim(e)!=""){destination_path.push(e);}});
				
				if( compare_array(destination_path,folder) || (destination_path.length > folder.length  && compare_array(destination_path.slice(0,folder.length),folder) && files_selected.indexOf(destination_path[folder.length+1])> -1)){
					alert('Can not copy to the same path');
					return true;
				}
				
				jQuery.post(document.URL,{'ajax_request':1,"destination_path_for_copy":jQuery("#copy-path-textbox").val(),"path":folder, "files":files_selected},function(result){
						if(result.success==1){
						
							jQuery("#right-col").html(result.data);
							/*if(jQuery("#left-col .selected-folder").html()== folder.pop()){
								jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
							}*/
						}else{
							if(result.data!=undefined){
								jQuery("#right-col").html(result.data);
								/*if(jQuery("#left-col .selected-folder").html()== folder.pop()){
									jQuery("#left-col .selected-folder").parent().parent().find(".sub-folder-wrapper").html(result.left_sub_dir);
								}*/
							}
							alert("ERROR: "+result.error);
						}
				},"json");
				tb_remove();
			});
		}
	});
	jQuery( "#right-col" ).selectable({delay:100,filter:'.folder-type,.file-type'});
	
	

	function compare_array(x, y) {
	    if(x.length!=y.length) return false;
            for (key in x) {
                if (x[key] != y[key]) {
                    return false;
                }
            }
            return true;
        }


			

});