<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
 * Copyright (C) 2003-2009 Frederico Caldeira Knabben
 *
 * == BEGIN LICENSE ==
 *
 * Licensed under the terms of any of the following licenses at your
 * choice:
 *
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 *
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 *
 *  - Mozilla Public License Version 1.1 or later (the "MPL")
 *    http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * == END LICENSE ==
 *
 * This page shows all resources available in a folder in the File Browser.
-->
<html>
<head>
	<title>Resources</title>
	<link href="browser.css" type="text/css" rel="stylesheet">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<script type="text/javascript" src="js/common.js"></script>
    <script type="text/javascript" src="js/language.js"></script>
	<script type="text/javascript" src="js/safeFN_class.js"></script>
	<script type="text/javascript">

var oListManager = new Object() ;
var currentFolderUploadStatus;
var DwikiFNencode = parent.DwikiFNencode;
var isInternalLink = parent.isLocalDwikiBrowser;
var ImagesAllowed = new RegExp(parent.DwikiImageUploadAllowedExtensions);
var isDwikiUrlExtern = parent.isDwikiUrlExtern;
var isDwikiMediaFile = parent.isDwikiMediaFile;
var FCKImageSaveDir = false;
var isDwikiImage = parent.isDwikiImage;
var isInternet_Explorer = false;
 if(navigator.userAgent.indexOf('MSIE') != -1 ||  navigator.userAgent.indexOf('Trident') != -1) {
  isInternet_Explorer = true;
 }

function getFCKSaveDir() {
   //alert(dwikiUTF8_decodeFN(document.cookie,DwikiFNencode)); 
   var allcookies = document.cookie;
   var pos = allcookies.indexOf("FCK_media=");
   if(pos != -1) {
       var start = pos+10;
       var end = allcookies.indexOf(";",start);
       if(end == -1) end = allcookies.length;
       var value = allcookies.substring(start,end);
       value = decodeURIComponent(value);
       return dwikiUTF8_decodeFN(value,DwikiFNencode); 
   }
    return false;
} 

window.onbeforeunload = function() { };
 
oListManager.Clear = function()
{
	document.body.innerHTML = '' ;
}

function ProtectPath(path)
{
	path = path.replace( /\\/g, '\\\\') ;
	path = path.replace( /'/g, '\\\'') ;
	return path ;
}

oListManager.GetFolderRowHtml = function( folderName, folderPath, folder_class, isImage )
{
	
    folderPath = dwikiUTF8_decodeFN(folderPath,DwikiFNencode);
	var sLink = '<a href="#" onclick="OpenFolder(\'' + ProtectPath( folderPath ) + '\');return false;">' ;
    icon = 'images/Folder.gif';
   
    if(folder_class == 'r') icon = 'images/FolderRO.gif';
    var ColSpan = isImage ? 4 : 3;
	return '<tr>' +
			'<td width="16">' +
				sLink +
				'<img alt="" src="' + icon  +'" width="16" height="16" border="0"><\/a>' +
			'<\/td><td nowrap colspan="' + ColSpan +'">&nbsp;' +
				sLink +
				folderName +
				'<\/a>' +
		'<\/td><\/tr>' ;
}


var imageDirectoryRegex = new RegExp ('^(.*?ckgedit\\/fckeditor\\/userfiles\\/image\\/)(.*)');
var imageDirectoryRegexFarms = new RegExp ('^(.*?ckgedit\\/fckeditor\\/.*?\\/image\\/)(.*)');
function reviseImgSrc(url) {
 
 var imgUrl =decodeURI(dwikiUTF8_decodeFN(url,DwikiFNencode));
 
 var matches = imgUrl.match(imageDirectoryRegex); 
 if(!matches)  matches = imgUrl.match(imageDirectoryRegexFarms); 
 if(matches && matches.length > 1) {
   if(!matches[1].match(/^\//)) matches[1] = '/'+matches[1];   
    return  matches[1]+ encodeURI(dwikiUTF8_encodeFN(matches[2],DwikiFNencode));
 }
 else { 
   var matches = imgUrl.match(/^http:\/\/(.*)/);
   if(matches) {
      return 'http://' + encodeURI(dwikiUTF8_encodeFN(matches[1],DwikiFNencode));
   }
 }
 return url;
}

function oListImage(fileUrl,width,height) {
    fileUrl = encodeURI(dwikiUTF8_encodeFN(fileUrl,DwikiFNencode));
    this.src = ProtectPath( fileUrl );
 
    this.src = reviseImgSrc(this.src);
   

    this.fileUrl = fileUrl;
    this.width = width;
    this.height = height;
}

function GetUrlParam( paramName )
{
    
	var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
	var oMatch = oRegex.exec( window.top.location.search ) ;
    
	if ( oMatch && oMatch.length > 1 )
		return decodeURIComponent( oMatch[1] ) ;
	else
		return '' ;
}

var imgCount = 0;
var imageArray = new Array();
var KBArray = new Array();
var imgProcessingStack = new Array();

function big_image(id) {
   var elems = id.split('_');
    var oImg = imageArray[elems[1]];


    var height = oImg.height;
    var width =  oImg.width;

   if(elems.length > 1) {
       if(oImg.width > 500) {
            height =  Math.round( oImg.height * ( 500  / oImg.width ) ) ;
            width = 500; 
        }
        if(height > 400) {
       	   width = Math.round( width  * ( 400 / height ) ) ;
           height = 400;  
        }
    }

    var element = '<img border = "0" src = "' + oImg.src + '" width = "' + width + '" height="' + height + '">';     
    element += '<center><br /><button class="bigwin_close_but" onclick="OpenFile(\''+ ProtectPath(oImg.fileUrl) +'\');void 0;">insert into document<\/button><\/center>';
    var big_win = document.getElementById('bigwin_display');
    big_win.innerHTML = element;
    big_win = document.getElementById('big_imagewin');
    big_win.style.display = 'block';
    big_win.scrollIntoView(); 

}

function getImageSize(oImgWidth,oImgHeight) {

   var  width = oImgWidth; var height = oImgHeight;  

    if(oImgWidth > 120) {
        height =  Math.round( oImgHeight * ( 120  / oImgWidth ) ) ;
        width = 120; 
    }
    if(height > 120) {
   	   width = Math.round( width  * ( 120 / height ) ) ;
       height = 120;  
    }

   return width + 'x' + height +'&nbsp;';
}

function showImage(id) { 
    var elems = id.split('_');
    var oImg = imageArray[elems[1]];
    if(!oImg) return id;
 
    var height = oImg.height;
    var width =  oImg.width;

 
    if(oImg.width > 120) {
        height =  Math.round( oImg.height * ( 120  / oImg.width ) ) ;
        width = 120; 
    }
    if(height > 120) {
   	   width = Math.round( width  * ( 120 / height ) ) ;
       height = 120;  
    }

    var sLink = '<a href="#" onclick="OpenFile(\'' + ProtectPath( oImg.src ) + '\');return false;">' ;
    var element = sLink + '<img border = "0" src = "' + oImg.src + '" width = "' + width + '" height="' + height + '"></a>';
    return element;
   // document.getElementById(id).innerHTML = element;

    
}

var foldersDone = { };
oListManager.GetFileRowHtml = function( fileName, fileUrl, fileSize, isImage, fileTime,iLinkTitle )
{
    var c_type = "file";
    if(isImage) {
        
        if(imgCount % 2 == 0) {
         c_type = 'silver';
        }
        else c_type = 'img';
    }
    else if(fileUrl.match(/data\/pages/)) {
        c_type = 'txt';
    }

   fileTime =  new Date(Number(fileTime)*1000);
   fileTime ="&nbsp;&nbsp;&nbsp;&nbsp;" + fileTime.toDateString().replace(/^\w+\s*/,"")  + "&nbsp;" + fileTime.toLocaleTimeString();
   var Unlink,sUnlink,trash,sLink,sTitle;
    if(iLinkTitle) {
     sTitle = ';;' + iLinkTitle;
     fileUrl += sTitle;    
    }
	// Build the link to view the folder.
	var sLink = '<a href="#" onclick="OpenFile(\'' + ProtectPath( fileUrl ) + '\');return false;">' ;

    var trash = 'images/trash.png';    
    var sUnlink = '<td width="20" class="' + c_type +'"><a href="#" onclick="UnlinkFile(event,\'' + fileName + '\');return false;">' ;
            sUnlink += '<img src="' + trash  + '" border="0"></a><\/td>';
    if(c_type == 'txt'){
        sUnlink = ""; //ilink title here
    }
    var imgTD = "";
    var fileSizeSpan="";
    if(isImage) {
         elems = fileSize.split(';;');
         fileSize = elems[0];

        var oImage = new oListImage(fileUrl, elems[1],elems[2]);
        oImage.inserted = false;
        imageArray[imgCount] = oImage;
        var imgId = 'img_' + imgCount;
        var imgTD = '<td width="152" align="center" class="' +c_type +'"><div id="' +	imgId +  '">'
         +  showImage(imgId) + '<\/div>' +
        '<div class="img_buttons"><a href="#" onclick="big_image(\'' + imgId + '\');return false;">' 
         + translateItem('DlgFileBrowserMagnify', 'magnify') +  
        '<\/a><\/div><\/td>';
         fileSizeSpan='<span id="size_'+ imgCount + '">' + elems[1] + 'x' + elems[2] + '&nbsp;</span>';   
         imgCount++;
 

    }

    if(currentFolderUploadStatus != 'd') sUnlink = '&nbsp;';
	// Get the file icon.
	var sIcon = oIcons.GetIcon( fileName ) ;
   	return '<tr>' + sUnlink +
			 '<td width="16" class="' + c_type + '">' +
				sLink +
				'<img alt="" src="images/icons/' + sIcon + '.gif" width="16" height="16" border="0"><\/a>' +
			'<\/td><td class="' + c_type +  '">&nbsp;' +
				sLink +
				fileName +
				'<\/a>' +
			 '<\/td>' + imgTD +
			'<\/td>' + '<td align="right" class="' + c_type + '"nowrap>&nbsp;' + fileSizeSpan +
				fileSize +
				' KB'  +   fileTime +             
		'<\/td><\/tr>' ;
}

function OpenFolder( folderPath )
{

	// Load the resources list for this folder.
	window.parent.frames['frmFolders'].LoadFolders( dwikiUTF8_encodeFN(folderPath,DwikiFNencode) ) ;
}
 
function UnlinkFile(evt,f) {
var evt = (evt) ? evt : ((window.event) ? event : null);

    if(evt && (evt.ctrlKey||evt.metaKey)) {
        move_to = window.prompt('Subdirectory of current directory to which you want to move ' + f, "secure");
        if(move_to) {
            move_to = move_to.replace(/^[\/\s]+/,"");
            move_to = move_to.replace(/[\/\s]+$/,"");
            if(move_to.match(/[\/\\]/)) {
              alert(translateItem('FolderMoveWarning','You can only move files to a folder one level below the current directory'));
              return false;     
            }
            move_to = move_to.toLowerCase(move_to);
            move_to = move_to.replace(/\s/g, '_');
            move_to = encodeURI(dwikiUTF8_encodeFN(move_to,DwikiFNencode));
            f = move_to + '/' +f;
        }
        else return false;  
    }
    else {
       if(!confirm("Delete " + f + "?")) return false;
    }
    
    var id = oConnector.CurrentFolder + ':' + f;
    id = id.replace(/\//g,':');
    id = id.replace('::',':');
    parent.opener.ckged_get_unlink_size(id);
     setTimeout(oConnector.SendCommand( 'UnlinkFile', 'file=' + f, UnlinkFileCallBack ), 7000) ; 
     setTimeout(LoadResources(oConnector.ResourceType, oConnector.CurrentFolder),9000);
    
}


function OpenFile( fileUrl )
{
    if(DwikiFNencode != 'safe') {
    fileUrl = dwikiUTF8_decodeFN(fileUrl,DwikiFNencode);  
    fileUrl =  decodeURI( fileUrl );
    }
	funcNum = GetUrlParam('CKEditorFuncNum') ;
  try {
    
    if(isInternalLink) {
       fileUrl=decodeURI( fileUrl ).replace( '#', '%23' ) ;
    }
    if(isDwikiUrlExtern) {
        fileUrl = window.location.protocol +'//' + window.location.host + '/' + decodeURI( fileUrl ).replace( '#', '%23' ) ;
    }
    if(isDwikiImage) {
      if(DwikiFNencode == 'url')  fileUrl=encodeURI(encodeURI(fileUrl));    
        if(window.top.opener.JSINFO['ckg_canonical'] ) {
            fileUrl = window.location.protocol +'//' + window.location.host + fileUrl;
        }
    }
    window.top.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl);
    if(isInternalLink) { 
        fileUrl = fileUrl.replace(/^.*?\/pages\//,"")          
        window.top.opener.update_ckgeditInternalLink(fileUrl);
    }   
    else if(isDwikiMediaFile) {        
       var url;       
       if(url = fileUrl.match(/userfiles\/(file|image)\/(.*?)$/)) {
            fileUrl = url[2];           
           if(!fileUrl.match(/^\//)) fileUrl = '/' + fileUrl;            
       }
       else if(url = fileUrl.match(/data\/media\/(.*?)$/)) {  // needs tobe updated for non-standard and Windows save dirs
           fileUrl = url[1];
           if(!fileUrl.match(/^\//)) fileUrl = '/' + fileUrl;
       }      
      else {
                   var cookie = ckgEedit_getCookie('FCK_animal') ;
                   if(cookie) {
                        var match = fileUrl.match(cookie+'\/file/(.*)');
                        if(match)  fileUrl = match[1];
                   }
      }
       window.top.opener.update_ckgeditMediaLink(fileUrl);    
    parent.opener.oDokuWiki_FCKEditorInstance.isLocalDwikiBrowser=false;
    }
  
  } 
  catch(e) {   
  }
	window.top.close() ;
	window.top.opener.focus() ;
}
function sortFileList(type) {
     oListManager.Clear();
    oConnector.SortType = type;
    oConnector.SendCommand( 'GetFoldersAndFiles', null, GetFoldersAndFilesCallBack ) ;
}

function findFiles(search){
   oConnector.Search = new RegExp(search);
   sortFileList('search');
}

function reverseListOrder(bool){
   oConnector.reverseOrder = bool;
   if(oConnector.SortType && (oConnector.SortType == 'mtime' || oConnector.SortType=='fsize')) {
       oConnector.SendCommand( 'GetFoldersAndFiles', null, GetFoldersAndFilesCallBack ) ;
   }  
}

function LoadResources( resourceType, folderPath )
{
    
	oListManager.Clear();
	document.body.innerHTML = translateItem('DlgFileBrowserWaitingMsg', 'Loading, please wait.'); //Show waiting message
	oConnector.ResourceType = resourceType ;
	oConnector.CurrentFolder = folderPath ? folderPath : '/';
     parent.opener.window.setTimeout( oConnector.SendCommand( 'GetFoldersAndFiles', null, GetFoldersAndFilesCallBack ), 9000) ;  
	
}

function Refresh()
{
	LoadResources( oConnector.ResourceType, oConnector.CurrentFolder ) ;
}

function GetFoldersAndFilesCallBack( fckXml )
{
   imgCount = 0; 
   imageArray = new Array();
   KBArray = new Array();
   imgProcessingStack = new Array();
   oListManager.Clear();//Clear waiting message

	if ( oConnector.CheckError( fckXml ) != 0 )
		return ;

	// Get the current folder path.
	var oFolderNode = fckXml.SelectSingleNode( 'Connector/CurrentFolder' ) ;
	if ( oFolderNode == null )
	{

        alert(translateItem('FileBrowserError_XML', 'The server didn\'t reply with a proper XML data. Please check your configuration.'));	
		return ;
	}
	var sCurrentFolderPath	= oFolderNode.attributes.getNamedItem('path').value ;
 
	var sCurrentFolderUrl	= oFolderNode.attributes.getNamedItem('url').value ;

	var oHtml = new StringBuilder( '<table id="tableFiles" cellspacing="0" cellpadding="1" width="100%" border="0">' ) ;

	// Add the Folders.
    var isImage = oConnector.ResourceType == 'Image' ? true : false;
	var oNodes ;
	oNodes = fckXml.SelectNodes( 'Connector/Folders/Folder' ) ;
	for ( var i = 0 ; i < oNodes.length ; i++ )
	{

        var sFolderName = dwikiUTF8_decodeFN(oNodes[i].attributes.getNamedItem('name').value,DwikiFNencode);
        var folder_class = oNodes[i].attributes.getNamedItem('class').value ;
        if(sFolderName.match(/__AAAAAAAA__.AAA/)) {
            currentFolderUploadStatus = folder_class;
            continue;
        }
		oHtml.Append( oListManager.GetFolderRowHtml( sFolderName, sCurrentFolderPath + sFolderName + "/", folder_class, isImage ) ) ;
	}

	// Add the Files.
	oNodes = fckXml.SelectNodes( 'Connector/Files/File' ) ;
    if(oConnector.SortType == 'mtime') {
        oNodes.sort(function(a, b) {
            var a_tm = Number(a.attributes.getNamedItem('time').value);
            var b_tm = Number(b.attributes.getNamedItem('time').value);
            if(oConnector.reverseOrder) {
               return b_tm - a_tm;
            }
            return a_tm - b_tm;
         });
     }
     else if(oConnector.SortType == 'fsize') {
        oNodes.sort(function(a, b) {         
            var a_tm = parseInt(a.attributes.getNamedItem('size').value);
            var b_tm = parseInt(b.attributes.getNamedItem('size').value);
            if(oConnector.reverseOrder) {
               return b_tm - a_tm;
            }
            return a_tm - b_tm;
         });
     }
	for ( var j = 0 ; j < oNodes.length ; j++ )
	{
		var oNode = oNodes[j] ;
        var sFileName = dwikiUTF8_decodeFN(oNode.attributes.getNamedItem('name').value,DwikiFNencode);
        if(oConnector.SortType == 'search' && !sFileName.match(oConnector.Search)) continue;
    	var sFileSize = oNode.attributes.getNamedItem('size').value ;
        var sFileTime = oNode.attributes.getNamedItem('time').value;
      
        if(isInternalLink) {
            var sTitle = "";
            sTitle = oNode.attributes.getNamedItem('title').value;
           // if(sTitle) alert(sTitle);             
            if(!sFileName.match(/\.txt$/)) continue;
            sFileName = sFileName.replace(/\.txt$/,"");    
        }
        else if(isImage) {        
          if(!sFileName.match(ImagesAllowed)) {
                continue;
          }
        }


		// Get the optional "url" attribute. If not available, build the url.
		var oFileUrlAtt = oNodes[j].attributes.getNamedItem('url') ;
		var sFileUrl = oFileUrlAtt != null ? oFileUrlAtt.value : sCurrentFolderUrl + sFileName ;

         if(isImage && FCKImageSaveDir) {
           sFileUrl=sFileUrl.replace(/^.*?\/image\//,"");
           sFileUrl = FCKImageSaveDir + sFileUrl;
        }

        if(isImage) {
               sFileUrl = dwikiUTF8_encodeFN(sFileUrl,DwikiFNencode);
       }
		oHtml.Append( oListManager.GetFileRowHtml( sFileName, sFileUrl, sFileSize, isImage, sFileTime, sTitle) ) ;
	}

	oHtml.Append( '<\/table>' ) ;
    var big = '<center><div id="big_imagewin"><div id="bigwin_display"></div>' +
              '<div id="big_iwin_close"><button onclick="close_bigImgwin();"  class="bigwin_close_but">close</button>&nbsp;&nbsp;&nbsp;</div></div></center>';
	document.body.innerHTML = big + oHtml.ToString() ;
    oConnector.Search = new RegExp("");
   
}


function insertImages() {

   for(var i = 0; i<imageArray.length; i++) {
           var imgId = 'img_' + i;
           showImage(imgId);
   }
  
}

function postMessageHandler( event ) {
/*
  console.log("We've got a message!");
  console.log("* Message:", event.data);
  console.log("* Origin:", event.origin);
  console.log("* Source:", event.source);
  */
  Refresh();
}
  
if (window.addEventListener) {
  window.addEventListener("message", postMessageHandler, false);
  } else {
  window.attachEvent("onmessage", postMessageHandler);
}
function UnlinkFileCallBack( fckXml, id )
{   
    if(id) {
       parent.opener.ckged_setmedia(id,true,this);
    }
   GetFoldersAndFilesCallBack( fckXml );
   
}

function close_bigImgwin() {

  document.getElementById('big_imagewin').style.display='none';
}

window.onload = function()
{
	window.top.IsLoadedResourcesList = true ;
        setupLanguage();
       FCKImageSaveDir=getFCKSaveDir() ;       
     //  alert(FCKImageSaveDir);     
  
}
	</script>
</head>
<body class="FileArea">
</body>
</html>