| /* webfan (C) Till Wehowski, Webfan.de - All rights reserved. */
(function(){
	
	
	
  	
 
	
 var webkitWebfanShim = function( ){
 	
 var loaded = false;
 
 var filer = null;
 var filerTemp = null;
 var _fs = null;
 
 var errorFn = console.warn;
 	
	
//view-source:http://html5-demos.appspot.com/static/filesystem/idb.filesystem.js/demos/basic/js/app.js
window.requestFileSystem = window.requestFileSystem ||
                           window.webkitRequestFileSystem;
window.URL = window.URL || window.webkitURL;
try{
  window.TEMPORARY=0;
  window.PERSISTENT = 1;
	
}catch(err){
	
}
//var openFSButton = document.querySelector('#openFSButton');
var preview = document.createElement('DIV');
var logger = console;
var fs = null;
var cwd = null;
var html = [];
var entries = document.createElement('DIV');
function fsDump() {
 return {
    fs : fs,
    cwd : cwd,
    
    extra : {
    	preview : preview,
    	entries : entries,
        html : html    
    }     
 };
}    
function onError(e) {
  console.error('Error.Shim.Filesystem: ' + e.code + ' - ' + e.name);
}
function clearFS() {
  fs.root.createReader().readEntries(function(results) {
    [].forEach.call(results, function(entry) {
      if (entry.isDirectory) {
        entry.removeRecursively(function() {}, onError);
      } else {
        entry.remove(function() {}, onError);
      }
    });
    getAllEntries(fs.root);
  }, onError);
  // idb.drop(function(e) {
  //   logger.log('<p>Database deleted!</p>');
  // }, onError);
}
function openFS(type, cb, size) {
  window.requestFileSystem(type, size || (1024*1024), function(myFs) {
 //   fs = myFs;
    cwd = myFs.root.toURL();
    //openFSButton.disabled = true;
    logger.log('Opened ' + cwd/* myFs.name, + */ +'');
   // getAllEntries(fs.root);
    cb(myFs, cwd, html);
  }, function(e) {
    logger.log(e);
  });
}
function writeFile(file, i) {
  cwd.getFile(file.name, {create: true, exclusive: false}, function(fileEntry) {
    fileEntry.createWriter(function(fileWriter) {
      fileWriter.onwritestart = function() {
        console.log('WRITE START');
      };
      fileWriter.onwriteend = function() {
        console.log('WRITE END');
      };
      fileWriter.write(file);
    }, onError);
    getAllEntries(cwd);
  }, onError);
}
function getAllEntries(dirEntry) {
  dirEntry.createReader().readEntries(function(results) {
    html = [];
    // var paths = results.map(function(el) { return el.fullPath.substring(1); });
    // renderFromPathObj(buildFromPathList(paths));
    // document.querySelector('#entries2').innerHTML = html.join('');
    var frag = document.createDocumentFragment();
    // Native readEntries() returns an EntryArray, which doesn't have forEach.
    [].forEach.call(results, function(entry) {
      var li = document.createElement('li');
      li.dataset.type = entry.isFile ? 'file' : 'folder';
      
      var deleteLink = document.createElement('a');
      deleteLink.href = '';
      deleteLink.innerHTML = '<img src="images/icons/delete.svg" alt="Delete this" title="Delete this">';
      deleteLink.classList.add('delete');
      deleteLink.onclick = function(e) {
        e.preventDefault();
        if (entry.isDirectory) {
          entry.removeRecursively(function() {
          logger.log('<p>Removed ' + entry.name + '</p>');
          getAllEntries(window.cwd);
        });
        } else {
          entry.remove(function() {
          logger.log('<p>Removed ' + entry.name + '</p>');
          getAllEntries(window.cwd);
        });
        }
        return false;
      };
      var span = document.createElement('span');
      span.appendChild(deleteLink);
      if (entry.isFile) {
        entry.file(function(f) {
          var size = Math.round(f.size * 100 / (1024 * 1024)) / 100;
          span.title = size + 'MB';
          if (size < 1) {
            size = Math.round(f.size * 100 / 1024) / 100;
            span.title = size + 'KB';
          }
          span.title += ', last modified: ' +
                        f.lastModifiedDate.toLocaleDateString();
          if (f.type.match('audio/') || f.type.match('video/ogg')) {
            var audio = new Audio();
            if (audio.canPlayType(f.type)) {
              audio.src = window.URL.createObjectURL(f);
              //audio.type = f.type;
              //audio.controls = true;
              audio.onended = function(e) {
                window.URL.revokeObjectURL(this.src);
              };
              var a = document.createElement('a');
              a.href = '';
              a.dataset.fullPath = entry.fullPath;
              a.textContent = entry.fullPath;
              a.appendChild(audio);
              a.onclick = playPauseAudio;
              span.appendChild(a);
            } else {
              span.appendChild(document.createTextNode(entry.fullPath + " (can't play)"));
            }
          } else {
            var a = document.createElement('a');
            a.href = '';
            a.textContent = entry.fullPath;
            a.onclick = function(e) {
              e.preventDefault();
              var iframe = preview.querySelector('iframe');
              if (!iframe) {
                iframe = document.createElement('iframe');
              } else {
                window.URL.revokeObjectURL(iframe.src);
              }
              preview.innerHTML = '';
              if (this.classList.contains('active')) {
                this.classList.remove('active');
                return;
              } else {
                this.classList.add('active');
              }
              iframe.src = window.URL.createObjectURL(f);
              preview.innerHTML = '';
              preview.appendChild(iframe);
              return false;
            };
            span.appendChild(a)
          }
          /*var img = document.createElement('img');
          img.src = 'images/icons/file.png';
          img.title = 'This item is a file';
          img.alt = img.title;
          span.appendChild(img);*/
          li.appendChild(span);
        }, onError);
      } else {
        var span2 = document.createElement('span');
        var folderLink = document.createElement('a');
        folderLink.textContent = entry.fullPath;
        folderLink.href = '';
        folderLink.onclick = function(e) {
          e.preventDefault();
          cwd.getDirectory(this.textContent, {}, function(dirEntry) {
            window.cwd = dirEntry; // TODO: not sure why we need to use window.cwd here.
            getAllEntries(dirEntry);
          }, onError);
          return false;
        };
        span2.appendChild(folderLink);
        span.appendChild(span2);
        span.classList.add('bold');
        var img = document.createElement('img');
        img.src = 'images/icons/folder.png';
        img.alt = 'This item is a folder';
        img.title = img.alt;
        span.title = img.alt;
        span.appendChild(img);
        li.appendChild(span);
      }
      frag.appendChild(li);
    });
    entries.innerHTML = '<ul></ul>';
    entries.appendChild(frag);
  }, onError);
}
function create(filePath, cb) {
  cwd.getFile(filePath, {create: true, exclusive: true}, function(fileEntry) {
    logger.log('<p>Created empty file <em>' + fileEntry.fullPath, + '</em></p>');
 //   getAllEntries(cwd);
     if('function'===typeof cb)cb(fileEntry);
  }, onError);
}
function mkdir(path, cb) {
	
console.log('mkdir>'+path);
	
  cwd.getDirectory(path, {create: true, exclusive: true}, function(dirEntry) {
    console.log('Created folder ' + dirEntry.fullPath, + '');
    /*getAllEntries(cwd);*/
    if('function'===typeof cb)cb(dirEntry);
  }, onError);
}
function buildFromPathList(paths) {
  var tree = {};
  for (var i = 0, path; path = paths[i]; ++i) {
    var pathParts = path.split('/');
    var subObj = tree;
    for (var j = 0, folderName; folderName = pathParts[j]; ++j) {
      if (!subObj[folderName]) {
        subObj[folderName] = j < pathParts.length - 1 ? {} : null;
      }
      subObj = subObj[folderName];
    }
  }
  return tree;
}
function renderFromPathObj(object) {
  for (var folder in object) {
    if (!object[folder]) { // file's will have a null value
      html.push('<li>', folder, '</li>');
    } else {
      html.push('<li>', folder);
      html.push('<ul>');
      renderFromPathObj(object[folder]);
      html.push('</ul>');
    }
  }
}
function playPauseAudio(e) {
  var a = e.target;
  var audio = a.querySelector('audio');
  if (audio.paused) {
    audio.play();
    a.classList.add('active');
  } else {
    audio.pause();
    a.classList.remove('active');
  }
  e.preventDefault();
}
function DnDFileController(selector, onDropCallback) {
  var el_ = document.querySelector(selector);
  this.dragenter = function(e) {
    e.stopPropagation();
    e.preventDefault();
    el_.classList.add('dropping');
  };
  this.dragover = function(e) {
    e.stopPropagation();
    e.preventDefault();
  };
  this.dragleave = function(e) {
    e.stopPropagation();
    e.preventDefault();
    //el_.classList.remove('dropping');
  };
  this.drop = function(e) {
    e.stopPropagation();
    e.preventDefault();
    el_.classList.remove('dropping');
    onDropCallback(e.dataTransfer.files)
  };
  el_.addEventListener('dragenter', this.dragenter, false);
  el_.addEventListener('dragover', this.dragover, false);
  el_.addEventListener('dragleave', this.dragleave, false);
  el_.addEventListener('drop', this.drop, false);
}
   function loadFiler(){
       
	          
	                   
        webfan.plug('chdir', function(){
        	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	  
      	    if('string' !==typeof _Arguments[1] ){
				  process.chdir(_Arguments[0]);
			}else if('fs' === _Arguments[1]){
				filer.cd(_Arguments[0], function(dirEntry) {
                   if('function'===typeof _Arguments[2])_Arguments[2](dirEntry);
                }, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);
			}else if('temp' === _Arguments[1]){
				filerTemp.cd(_Arguments[0], function(dirEntry) {
                   if('function'===typeof _Arguments[2])_Arguments[2](dirEntry);
                }, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);			
			} 
        });                  
           
           
           	 
   try{
   	 openFS(window.TEMPORARY, function(myFs, cwd, html){
	    	
	    	console.log('open>'+cwd);
	 
	         filer =   new window.frdlFiler();
	         filerTemp =  new window.frdlFiler();
	         filerTemp.init({persistent: false, size: 1024 * 1024}, function(fs) {
                   
                
                   _fs = fs;
 
	         if(null !== frdl.$q('link[type="application\/manifest+json"]', false)){
          	     filer.init({persistent: true, size: window.frdlFiler.DEFAULT_FS_SIZE}, function(fs) {
          	     	
                     _fs = fs;
                 
                    openFS(window.PERSISTENT, function(myFs, cwd, html){   
                       loaded=true; 
                       
                       	console.log('open>'+cwd);
                       
                    });   
                 }, errorFn);
             }else{
		      	filer=filerTemp;
		      	 loaded=true; 
		     }
                       
                   
                   
           }, errorFn);
   }, window.frdlFiler.DEFAULT_FS_SIZE);
  }catch(err){
 	console.warn(err);
  } 	   
   
 }
 /* end loadFiler() */
 
 try{
 	loadFiler();
 }catch(err){
 	console.warn(err);
 } 	
   	 
      
	
 	   	 var shim = {
	 	 '$win open' : function(){
		 	  return window.open(arguments[0][0]);
		 },
		 
		 '$win close' : function(){
		 	  return window.close();
		 },
		 
		 '$fs --local' : function(){
		 		if('temp' === arguments[0])return filerTemp;
		 	  return filer;
		 },
		 
		 'path.exec' : function(){
		 	 /* return document.base || window.location.href; */
		 	 try{
			 	 return webfan['$fs --local']().fs.root.toURL();
			 }catch(err){
			 	 return document.base || window.location.href; 
			 }
		 	
		 },
		 
		 '$path' : function(){
		 	  return require('path');
		 }
	 };
     
  var suggested = (true === navigator['-webkit-webfan'] )
   	             ? navigator.webfan 
   	             : shim;
    		 
      window.DIRECTORY_SEPARATOR = (true === navigator['-webkit-webfan'] )
   	             ? require('path').sep
   	             : '/'; 
   	             
   	             
      webfan.plug('$fs.ready', function(){
      	    return true;
      });           
      webfan.plug('app://', function(){
      	try{
			if('temp' === arguments[0])return webfan['$fs --local']('temp').fs.root.toURL();
			return webfan['$fs --local']().fs.root.toURL();
		}catch(err){
			return window.location.href;
		}
      	   
      });
      
                  
      webfan.plug('tmpdir', function(){
      	  return (true === navigator['-webkit-webfan'] ) ? require('os').tmpdir()  : webfan['path.exec']() + 'tmp/';
      });
               
                   
      webfan.plug('path.exec', function(){
      	  return suggested['path.exec']()/* + DIRECTORY_SEPARATOR */;
      });
               	  
               	             
      webfan.plug('$fs --local', function(){
      	
      	if(true === navigator['-webkit-webfan']){
			return navigator.webfan['$fs --local']();
		}
      	
      	    if('local' === arguments[0])return filer;
      	    if('temp' === arguments[0])return filerTemp;
      	    return suggested['$fs --local']();
      });
      
     	             
      webfan.plug('$fs --local root', function(){
         return suggested['path.exec']() /* + DIRECTORY_SEPARATOR */;	   
      });
         
      webfan.plug('file://', function(){
      	    return suggested['path.exec']() /* + DIRECTORY_SEPARATOR */;
      });
                
                     
                
   	 
   	           
   	   setTimeout(function(){
   	 	 
		  	fs = webfan['$fs --local']();
       },1000);            
    
     fs = webfan['$fs --local']();
  
  
  
  
  
  
  
        
         		 
       
                   	  	             
      webfan.plug('$import webkitWebfanShim', function(){
      	    return webkitWebfanShim;
      });
      
      webfan.plug('$win open', function(){
      	    return suggested['$win open'](arguments);
      });
      
    	             
   	             
      webfan.plug('$win close', function(){
      	    return suggested['$win close'](arguments);
      });
      
      
  
  
      
      
       webfan.plug('file://ls', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	   if(true === navigator['-webkit-webfan'] ){
		   	 	return webfan['$fs --local']().readdir(_Arguments[0],  function(err, files) {
                      if (err) {
                      	errorFn(err + ' : ' +_Arguments[0]);
                        return;
                      }
                      _Arguments[1](files);
                     /* webfan['$fs --local']().close(); */
                }
		   	 	
		   	 	);   
		   }else{
		   	    return webfan['$fs --local']().ls(_Arguments[0], function(entries) {
                    _Arguments[1](entries);
                }, errorFn);
		   }
      });
       webfan.plug('temp://ls', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	      return webfan['$fs --local']('temp').ls(_Arguments[0], function(entries) {
                    _Arguments[1](entries);
                }, errorFn);
      });
            
      
      
      
        webfan.plug('file://chdir', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	   if(true === navigator['-webkit-webfan']){
		   	 	process.chdir(_Arguments[0]);   
		   }else{
		   	     webfan['$fs --local']().cd(_Arguments[0], function(dirEntry) {
                      if('function'===typeof _Arguments[2])_Arguments[2](dirEntry);
                }, ('function'===typeof _Arguments[1]) ? _Arguments[1] : errorFn);
		   }
      });     
      
      
      
      
      
       webfan.plug('file://write -f', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	   if(true === navigator['-webkit-webfan'] ){
		   	 	 webfan['$fs --local']().writeFile(_Arguments[0],_Arguments[1],  function(err) {
                      if (err) {
                      	(('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn)(err);
                        return;
                      }
                       if('function'===typeof _Arguments[2])_Arguments[2](_Arguments[0]);
                      webfan['$fs --local']().close();
                });   
		   }else{
		   	     webfan['$fs --local']().write(_Arguments[0], {data:_Arguments[1]},function(fileEntry, fileWriter) {
                    if('function'===typeof _Arguments[2])_Arguments[2](_Arguments[0], fileEntry, fileWriter);
                }, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);
		   }
      });
       webfan.plug('temp://write -f', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	 	     webfan['$fs --local']('temp').write(_Arguments[0], {data:_Arguments[1]},function(fileEntry, fileWriter) {
                    if('function'===typeof _Arguments[2]) _Arguments[2](_Arguments[0], fileEntry, fileWriter);
                }, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);
      });          
      
      
      
      
      
      
      
      
       webfan.plug('file://mkdir', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
       	
      	   if(true === navigator['-webkit-webfan'] ){
		   	 	return webfan['$fs --local']().mkdir(_Arguments[0],
		   	 	                                     ('undefined'!==typeof _Arguments[1] && 'function'!==typeof _Arguments[1]) 
		   	 	                                          ? _Arguments[1] 
		   	 	                                          :parseInt('0755', 8),
		   	 	                                     function(err) {
		   	 	                                     	
		   	 	                            	
		   	 	                                     	
		   	 	                                     	
                      if (err) {
                      	('function'===typeof _Arguments[3]) ? _Arguments[3](err) : errorFn(err);
                        return;
                      }
              
                  /*  if('function'===typeof _Arguments[2]){
						webfan['file://ls'](_Arguments[0], function(files){
							_Arguments[2](files);
						}, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);
					}
					*/
                }
		   	 	
		   	 	);   
		   }else{
		   	
		   	
		   	    return webfan['$fs --local']().mkdir(_Arguments[0],  (true=== _Arguments[1] || false=== _Arguments[1]) 
		   	                                     ? _Arguments[1] 
		   	                                     : false , 
		   	                                     function(dirEntry) {
                     if('function'===typeof _Arguments[2])_Arguments[2](dirEntry); 
    
                    
                }, ('function'===typeof _Arguments[3]) ? _Arguments[3] : errorFn);
		   }
      });
      
      
       webfan.plug('temp://mkdir', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
      	   webfan['$fs --local']('temp').mkdir(_Arguments[0], false, function(dirEntry) {
                     
                    _Arguments[1]( _Arguments[0], dirEntry);
                }, ('function'===typeof _Arguments[2]) ? _Arguments[2] : errorFn);	
    
      });      
      
      
      
      
      
      
      
      
      
      
       webfan.plug('file://read -f', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
       	var eFn = function(err, path){
       		if('string' !== typeof path)path = _Arguments[0];
		   console.warn(err + ' : ' + path);	
		};
       	
          if(true === navigator['-webkit-webfan'] ){
		     	 webfan['$fs --local']().readFile(_Arguments[0], function(err, data) {
                      if (err) {
                      	if('function'===typeof _Arguments[2]){
							_Arguments[2](err  + ' : ' +_Arguments[0]);
						}else{
							eFn(err, _Arguments[0]);
						}
                        return;
                      }
                       _Arguments[1](data );
                  });   
		      }else{
		  
		  
		  	   webfan['$fs --local']().open(_Arguments[0], function(file) {
                   var reader = new FileReader();
                   reader.onload = function(ev) {
                         _Arguments[1](ev.target.result.toString());
                   };
                    reader.readAsBinaryString(file);
                }, ('function'===typeof _Arguments[2]) ? _Arguments[2] : eFn);
		  
		       }      	
      });
      
      
      
      
       webfan.plug('temp://read -f', function(){
       	var _Arguments = Array.prototype.slice.call(arguments)[0];
	/* webfan['$fs --local']().*/ webfan['$fs --local']().fs.root.getFile(_Arguments[0], {create: false}, function(fileEntry) {
  	
	    fileEntry.file(function(file) {
            var reader = new FileReader();
           reader.onloadend = function(ev) {
                _Arguments[1](ev.target.result );
          };
             reader.readAsBinaryString(file);
       }, ('function'===typeof _Arguments[2]) ? _Arguments[2] : errorFn);  	
	  	
      }, ('function'===typeof _Arguments[2]) ? _Arguments[2] : errorFn);     	
      });
                
                
                
          
          
 };
 	
 	
 	
 	
            
 
 
  
  
  exports  = module.exports = webkitWebfanShim;    
      
}());
 |