관리-도구
편집 파일: jqueryFileTree.js
// jQuery File Tree Plugin - Customized version for CrushFTP // Customized by Vipul Limbachiya http://vipullimbachiya.com for CrushFTP // // Version 1.01 // // Cory S.N. LaViska // A Beautiful Site (http://abeautifulsite.net/) // 24 March 2008 // // Visit http://abeautifulsite.net/notebook.php?article=58 for more information // // Usage: $('.fileTreeDemo').fileTree( options, callback ) // // History: // // 1.01 - updated to work with foreign characters in directory/file names (12 // April 2008) // 1.00 - released (24 March 2008) // // TERMS OF USE // // This plugin is dual-licensed under the GNU General Public License and the MIT // License and // is copyright 2008 A Beautiful Site, LLC. // // Customized by Vipul Limbachiya(http://vipullimbachiya.com) for CrushFTP // FTP WebInterface Localization options var localizations = {}; //WebInterface localizations.FilterText = "Filter:"; localizations.ClearFilterLinkText = "Clear"; localizations.FileCounterItemsText = "Items"; localizations.FileCounterFoldersText = "Folders"; localizations.FileCounterFilesText = "Files"; localizations.FileCounterHiddenItemsText = "Hidden Items"; localizations.ThumbnailViewLinkText = "Thumbnail View"; localizations.TreeViewLinkText = "Tree View"; localizations.BackToTopLinkText = "Back to top"; //Sharing Window localizations.ShareWindowHeaderText = "Share"; localizations.ShareWindowFilesSharingLabelText = "Sharing :"; localizations.ShareWindowShareTypeLabelText = "Share type :"; localizations.ShareWindowSendEmailLabelText = "Send Email :"; localizations.ShareWindowExpiresLabelText = "Expires :"; localizations.ShareWindowFromLabelText = "From : "; localizations.ShareWindowToLabelText = "To : "; localizations.ShareWindowCCLabelText = "CC : "; localizations.ShareWindowBCCLabelText = "BCC : "; localizations.ShareWindowSubjectLabelText = "Subject : "; localizations.ShareWindowBodyLabelText = "Body : "; localizations.ShareWindowAdvancedLabelText = "Advanced"; localizations.ShareWindowAttachThumbsLabelText = "Attach Thumbnail"; localizations.ShareWindowAccessLabelText = "Full Access (read, write, delete) "; localizations.ShareWindowSendButtonText = "Send"; localizations.ShareWindowCancelButtonText = "Cancel"; localizations.ShareActionCompleteUsernameText = "Username: "; localizations.ShareActionCompletePasswordText = "Password: "; localizations.ShareActionCompleteLinkText = "Link"; localizations.ShareActionCompleteOkButtonText = "Ok"; //Copy direct link window localizations.CopyLinkWindowHeaderText = "Copy direct link."; //Create folder window localizations.CreateFolderWindowHeaderText = "Create new folder."; localizations.CreateFolderInputDefaultFolderName = "New Folder"; localizations.CreateFolderWindowNavigateToFolderCheckboxText = "Navigate to the folder after creation "; localizations.CreateFolderButtonText = "Create"; //Browser uploader window localizations.BrowserUploaderWindowHeaderText = "Upload file"; localizations.BrowserUploaderUploadDetailsTabHeaderText = "Upload Details"; localizations.BrowserUploaderUploadFilesTabHeaderText = "Upload Files"; localizations.BrowserUploaderAdvancedBrowseButtonText = "Advanced Browse.."; localizations.BrowserUploaderStartUploadingLinkText = "Start Uploading"; localizations.BrowserUploaderClearCompletedLinkText = "Clear Completed"; localizations.BrowserUploaderResumeCheckboxText = "Resume"; localizations.BrowserUploaderFormResetButtonText = "Reset"; localizations.BrowserUploaderFormNextButtonText = "Next"; localizations.BrowserUploaderFileAddedAlreadyText = "This file has already been added."; localizations.BrowserUploaderFileAddedAlreadyDetailsText = "{0} has already been added."; localizations.BrowserUploaderMultiFileAddedAlreadyText = "These files are already added."; localizations.BrowserUploaderMultiFileAddedAlreadyDetailsText = "{0} are already added."; localizations.BrowserUploaderSelectedFilesGroupText = "File Group : "; localizations.BrowserUploaderSelectedFileRemoveLinkText = "Remove"; localizations.BrowserUploaderSelectedFileWillBeUploadedText = "Will be uploaded to"; localizations.BrowserUploaderSelectedFileOverwriteText = "Overwrite"; localizations.BrowserUploaderSelectedFileWillBeOverwrittenText = "will be overwritten"; localizations.BrowserUploaderSelectedFileExistsText = "File exist"; localizations.BrowserUploaderSelectedFileAttentionRequiredText = "Attention Required"; localizations.BrowserUploaderSelectedFileIgnoreLinkText = "Ignore"; localizations.BrowserUploaderSelectedFileDoneText = "Done"; localizations.BrowserUploaderSelectedFileUploadedText = "Uploaded to"; localizations.BrowserUploaderSelectedFileReUploadLinkText = "re-upload"; localizations.BrowserUploaderSelectedFileDismissLinkText = "Dismiss"; localizations.BrowserUploaderSelectedFileCancelLinkText = "Cancel"; localizations.BrowserUploaderSelectedFilePauseLinkText = "Pause"; localizations.BrowserUploaderSelectedFilePausedStatusText = "Paused"; localizations.BrowserUploaderSelectedFileResumeLinkText = "Resume"; localizations.BrowserUploaderAdvancedUploadingFilesText = "Total {0} File(s)"; localizations.BrowserUploaderAdvancedUploadingFilesStatusText = "{0} of {1} item(s) "; localizations.BrowserUploaderAdvancedUploadingFilesToText = "Uploading to : "; localizations.BrowserUploaderAdvancedUploadingSpeedText = "Speed : "; localizations.BrowserUploaderAdvancedUploadingTimeText = "<div class='time'> Time: Elapsed: <span class='elapsed'>{0}</span> <span class='remained'>, Remaining : {1}</span></div>"; //Search window localizations.SearchWindowHeaderText = "Search"; localizations.SearchWindowKeywordsLabelText = "Keywords :"; localizations.SearchWindowExactLabelText = "Exact?"; localizations.SearchWindowByClassModifiedLabelText = "Modified"; localizations.SearchWindowByClassDateFormatLabelText = "(mm/dd/yyyy) "; localizations.SearchWindowSizeLabelText = "Size is "; localizations.SearchWindowTypeLabelText = "Type is a"; localizations.SearchWindowSizeLabelText = "Size is "; localizations.SearchWindowSizeUnitLabelText = "(Kilobytes)"; localizations.SearchWindowSearchButtonText = "Start Search"; localizations.SearchWindowCancelButtonText = "Cancel"; localizations.SearchResultDisplayText = "Search Result:"; localizations.SearchResultClearLinkText = "(Clear Search Filter)"; localizations.SearchFormModifiedOptionAfterText = "After"; localizations.SearchFormModifiedOptionBeforeText = "Before"; localizations.SearchFormSizeOptionBiggerThanText = "Bigger Than"; localizations.SearchFormSizeOptionSmallerThanText = "Smaller Than"; localizations.SearchFormItemTypeOptionFileText = "File"; localizations.SearchFormItemTypeOptionFolderText = "Folder"; //User options window localizations.UserOptionsWindowHeaderText = "Preferences"; localizations.UserOptionsWindowHideItemsStartWithDotLabelText = "Hide '.' Items "; localizations.UserOptionsWindowHideCheckboxLabelText = "Hide Checkbox Column "; localizations.UserOptionsWindowHideFilterLabelText = "Hide Filter Section "; localizations.UserOptionsWindowAutostartUploadLabelText = "When choosing file to upload, auto start upload. "; localizations.UserOptionsWindowLoadJavaAppletLabelText = "When loading the interface, load the Java applet."; localizations.UserOptionsWindowDisableCompressionLabelText = "Disable compression on the Java applet. "; localizations.UserOptionsWindowChangePasswordHeaderText = "Change your password "; localizations.UserOptionsWindowChangePasswordCurPassLabelText = "Current Password: "; localizations.UserOptionsWindowChangePasswordNewPassLabelText = "New Password: "; localizations.UserOptionsWindowChangePasswordConfirmPassLabelText = "Confirm Password:"; localizations.UserOptionsWindowChangePasswordButtonText = "Change Password"; localizations.UserOptionsWindowChangePasswordGenerateRandomButtonText = "Generate random password"; localizations.UserOptionsWindowChangePasswordGenerateRandomUseItLinkText = "Use this"; localizations.UserOptionsWindowChangePasswordGenerateRandomCancelLinkText = "Cancel"; //Main checkbox context menu options localizations.MainCheckboxContextMenuToggleText = "Toggle"; localizations.MainCheckboxContextMenuCheckAllText = "Check All"; localizations.MainCheckboxContextMenuUncheckAllText = "Un-check All"; //Keywords window localizations.KeywordsWindowHeaderText = "Keywords"; localizations.KeywordsWindowUpdateLinkText = "Update"; localizations.KeywordsWindowCancelLinkText = "Cancel"; //File basket localizations.BasketHeaderText = "Files in the Basket"; localizations.BasketClearAllLinkText = "Clear all"; localizations.BasketDownloadLinkText = "Download Basket"; localizations.BasketDownloadAdvancedLinkText = "Download Basket Advanced"; localizations.BasketNoFilesAvailableText = "No Files Available"; localizations.BasketRemoveLinkText = "Remove"; localizations.BasketTotalItemText = "Total {0} item(s)"; localizations.BasketFileAddedAlreadyText = "File added already to the basket"; localizations.BasketFileAddedAlreadyDetailsText = "Selected file is already available in the basket"; localizations.BasketNothingSelectedToAddText = "Nothing selected to add to basket"; localizations.BasketNothingSelectedToAddDetailsText = " "; //Paste form panel localizations.PasteFormHeaderText = "Paste"; localizations.PasteFormResetButtonText = "Reset"; localizations.PasteFormPasteButtonText = "Paste"; localizations.PasteFormErrorHeaderText = "Problem while pasting"; localizations.PasteFormErrorDetailsText = "There was a problem while pasting items.<br />Error : {0}"; localizations.PasteFormErrorNothingToPasteText = "There is nothing to paste"; //Welcome form panel localizations.WelcomeFormHeaderText = "Welcome"; localizations.WelcomeFormOkButtonText = "OK"; //Slideshow popup localizations.SlideshowPopupHeaderText = "Slideshow"; //Manage Share window localizations.ManageShareWindowHeaderText = "Manage Shares"; localizations.ManageShareWindowRefreshLinkText = "Refresh"; localizations.ManageShareWindowDeleteSelectedLinkText = "Delete Selected Items"; localizations.ManageShareWindowGridToLabelText = "To"; localizations.ManageShareWindowGridCCLabelText = "CC"; localizations.ManageShareWindowGridCreatedLabelText = "Created"; localizations.ManageShareWindowGridExpiresLabelText = "Expires"; localizations.ManageShareWindowGridSharedItemsLabelText = "Shared Items"; localizations.ManageShareWindowGridDownloadsLabelText = "Downloads"; //Rename widndow and panel localizations.RenameWindowHeaderText = "Rename"; localizations.RenamePanelSaveLinkText = "Save"; localizations.RenamePanelCancelLinkText = "Cancel"; //Tooltip info localizations.TooltipNameLabelText = "Name"; localizations.TooltipSizeLabelText = "Size"; localizations.TooltipModifiedLabelText = "Modified"; localizations.TooltipKeywordsLabelText = "Keywords"; //Form alerts and notifications localizations.FormValidationFailText = "One or more required items are not entered or not entered properly. Enter proper value for the items with * in below form"; localizations.DeleteConfirmationMessageText = "Total {0} folder(s) and {1} file(s) will be deleted.\n\nItems: {2} Once deleted it can not revert back"; localizations.CopyActionGrowlText = "Total {0} folder(s) and {1} file(s) copied."; localizations.CutActionGrowlText = "Total {0} folder(s) and {1} file(s) cut."; //Treeview header items localizations.TreeviewHeaderNameText = "Name"; localizations.TreeviewHeaderSizeText = "Size"; localizations.TreeviewHeaderModifiedText = "Modified"; localizations.TreeviewHeaderKeywordsText = "Keywords"; //Selection menu items localizations.SelectItemOptionLinkText = "Select" localizations.SelectCheckboxContextMenuToggleText = "Toggle"; localizations.SelectCheckboxContextMenuCheckAllText = "All items"; localizations.SelectCheckboxContextMenuUncheckAllText = "None"; localizations.SelectCheckboxContextMenuCheckAllFilesText = "All files"; localizations.SelectCheckboxContextMenuCheckAllFoldersText = "All folders"; localizations.SelectCheckboxContextMenuCheckItemsWithDotText = "Items starting with \".\""; localizations.SelectCheckboxContextMenuCheckTodayText = "Modified today"; localizations.SelectCheckboxContextMenuCheckWeekText = "Modified this week"; localizations.SelectCheckboxContextMenuCheckMonthText = "Modified this month"; localizations.SelectCheckboxContextMenuCheck2MonthsText = "Modified in last 60 days"; localizations.SelectCheckboxContextMenuCheck3MonthsText = "Modified in last 90 days"; // Page size selection menu item. localizations.PageSizeSelectionLinkText = "Show {0} items on page" //Webinterface labels localizations.CopyrightText = "© 2010 <a target=\"_blank\" href=\"http://www.CrushFTP.com/\">CrushFTP</a>"; localizations.PoweredByText = "Powered by <a target=\"_blank\" href=\"http://www.crushftp.com/\">CrushFTP</a>"; /*Tracking mouse movement*/ $(document).ready(function () { $(document).data("localizations",localizations); if(!window.forSlideshow) { delayInterval = 50; $.idleTimer(2000); $(document).bind("idle.idleTimer", function () { // function you want to fire when the user goes idle if (delayInterval != 500) { delayInterval = 500; clearInterval(window.hashListnerIntervalID); window.hashListnerIntervalID = window.setInterval(function () { try{hashListener.check();}catch(e){} }, delayInterval); } }); $(document).bind("active.idleTimer", function () { // function you want to fire when the user becomes active again if (delayInterval != 50) { delayInterval = 50; clearInterval(window.hashListnerIntervalID); window.hashListnerIntervalID = window.setInterval(function () { try{hashListener.check();}catch(e){} }, delayInterval); } }); clearInterval(window.hashListnerIntervalID); window.hashListnerIntervalID = window.setInterval(function () { try{hashListener.check();}catch(e){} }, delayInterval); } }); if (jQuery)(function ($) { $.extend($.fn, { fileTree: function (o, h) { // Defaults if (!o) var o = {}; if (o.root == undefined) o.root = '/'; if (o.script == undefined) o.script = 'jqueryFileTree.php'; if (o.folderEvent == undefined) o.folderEvent = 'click'; if (o.thumbFolderEvent == undefined) o.thumbFolderEvent = 'dblclick'; if (o.expandSpeed == undefined) o.expandSpeed = 500; if (o.collapseSpeed == undefined) o.collapseSpeed = 500; if (o.expandEasing == undefined) o.expandEasing = null; if (o.collapseEasing == undefined) o.collapseEasing = null; if (o.multiFolder == undefined) o.multiFolder = true; if (o.loadMessage == undefined) o.loadMessage = 'Loading...'; if (o.signupPage == undefined) o.signupPage = false; //All options below this added by Vipul for CrushFTP //Static Values $(document).data("crushftpVariables", o); o.proxy = "/WebInterface/"; o.proxy = o.proxy.substring(("/Web"+"Interface").length); o.ajaxCallURL = "/WebInterface/function/"; o.uploadURL = "/WebInterface/function/"; o.downloadURL = "/WebInterface/function/"; o.ImageFilePath = "/WebInterface/jQuery/images/"; o.FileExtensionImageFilePath = o.ImageFilePath + "fileExtensions/"; o.FilePath = "/WebInterface/jQuery/"; o.fileLarge = o.FileExtensionImageFilePath + "file"; o.fileFolder = o.ImageFilePath + "folderLarge.png"; o.fileFolder1 = o.ImageFilePath + "folderLarge1.png"; o.fileFolder2 = o.ImageFilePath + "folderLarge2.png"; o.fileFolder3 = o.ImageFilePath + "folderLarge3.png"; o.spinerImage = o.ImageFilePath + "spinner.gif"; o.PreviewIconThumbnailStyle = "border:0px;"; o.ViewCookieName = "__WEBINTERFACE_FILE_LIST_VIEW"; o.CookieHideItemStartingWithDot = "__WEBINTERFACE_HIDE_ITEMS_STARTING_WITH_DOT"; o.CookieHideCheckBoxColumn = "__WEBINTERFACE_HIDE_CHECKBOX_COLUMN"; o.CookieHideFilter = "__WEBINTERFACE_HIDE_FILTER"; o.CookieAutoUploadFlag = "__WEBINTERFACE_FILE_AUTOUPLOAD"; o.CookieAutoAppletFlag = "__WEBINTERFACE_AUTOAPPLET"; o.CookieNoCompressionFlag = "__WEBINTERFACE_NOCOMPRESSION"; o.CookieWelcomeNote = "__WEBINTERFACE_WELCOMENOTE"; o.CookieCopiedFiles = "__WEBINTERFACE_FILES_COPIED"; o.CookiePageSize = "__WEBINTERFACE_PAGE_SIZE"; o.MaximumLengthAllowedForKeywordsString = 25; o.MaximumLengthAllowedForSharingPopupHeaderString = 50; o.thumbnailTextCharsLimit = 14; o.FileListingElement = $("#filesListing"); o.FilesNotAvailableMessage = "No files available"; o.CopyNoFilesSelectedMessage = "Please select files/folders to copy"; o.DeleteNoFilesSelectedMessage = "Please select files/folders to delete"; o.CutNoFilesSelectedMessage = "Please select files/folders to cut"; o.ZipNoFilesSelectedMessage = "Please select files/folders to zip"; o.CookieLimitReachedMessage = "Cookie limit reached, copied to the document. Refreshing the page will remove items from clipboard"; o.MaxSimultaneousUploadAllowed = 1; o.GrowlTimeout = 2000; // If growl has close button (next option) it will be set to 0 o.GrowlWithCloseButton = true; o.BasketDataKey = "__WEBINTERFACE_FILES_IN_BASKET"; o.lowestThumbnailBoxWidth = 110; o.lowestThumbnailBoxHeight = 140; o.buggyBrowser = $.browser.msie && $.browser.version <= 8; o.keywordsCharLimit = 1000; o.availableFileExtensionImages = ["ai","avi","bak","bat","bin","bmp","cab","cmd","css","csv","cue","dat","dic","divx","dll","dmg","doc","docx","dvd","dwg","exe","file","fla","gif","html","ifo","ini","iso","jpeg","jpg","js","m4a","mmf","mov","mp3","mp4","mpeg","mpg","otf","pdf","php","png","pps","ppt","pptx","psd","rar","rtf","swf","sys","tiff","ttf","txt","vob","wma","wmv","xls","xlsx","xml","xmp","zip","sitx","idml","indd","sit"]; /*Pagination options*/ o.defaultPageSize = 100; o.pagingNumDisplayEntries = 10; o.pagingCurrentPage = 0; o.pagingNumEdgeEntries = 5; o.pagingPrevText = "Prev"; o.pagingNextText = "Next"; o.pagingEllipseText = "..."; o.pagingControlsShowAlways = false; /*End :: Pagination options*/ if (o.GrowlWithCloseButton) { o.GrowlTimeout = 0; } //Column model for files XML o.colModel = [{ name: 'type', index: 'type', sorttype: "text" }, { name: 'dateFormatted', index: 'dateFormatted', sorttype: "date" }, { name: 'date', index: 'date', sorttype: "date" }, { name: 'modified', index: 'modified', sorttype: "date" }, { name: 'size', index: 'size', sorttype: "number" }, { name: 'sizeFormatted', index: 'sizeFormatted', sorttype: "text" }, { name: 'name', index: 'name', sorttype: "text" }, { name: 'href_path', index: 'href_path', sorttype: "text" }, { name: 'keywords', index: 'keywords', sorttype: "text" }, { name: 'root_dir', index: 'root_dir', sorttype: "text" }, { name: 'preview', index: 'preview', sorttype: "text" }, { name: 'privs', index: 'privs', sorttype: "text" }]; if (o.customData == undefined) o.customData = false; if (o.overrideFromHash == undefined) //It will load items for particular folder as on hash location o.overrideFromHash = true; if (o.setHashLocation == undefined) //Enable or disable to set hash location on folder change o.setHashLocation = true; if (o.expandedImageURL == undefined) //Path to expanded image - displayed against expanded folder in a grid o.expandedImageURL = o.ImageFilePath + "expanded.png"; if (o.collapsedImageURL == undefined) //Path to collapsed image - displayed against expanded folder in a grid o.collapsedImageURL = o.ImageFilePath + "collapsed.png"; if (o.refreshImageURL == undefined) //Path to refresj image - displayed against current folder name in a breadcrumbs o.refreshImageURL = o.ImageFilePath + "refresh.png"; $(this).each(function () { //Template for a header for Grid view var headerTemplate = "<thead><tr><td class='thSelect theader'><input type='checkBox' class='chkBoxAll' /></td><td colName='name' class='thName theader'>"+getLocalizationKey("TreeviewHeaderNameText")+"</td><td colName='size' class='thSize theader'>"+getLocalizationKey("TreeviewHeaderSizeText")+"</td><td colName='modified' class='thModified theader'>"+getLocalizationKey("TreeviewHeaderModifiedText")+"</td><td colName='keywords' class='thKeywords theader'>"+getLocalizationKey("TreeviewHeaderKeywordsText")+"</td></tr></thead>"; //Template for thumbnail view item var thumbnailItemTemplate = '<li class="vtip fileBox #CLASS#" index="#INDEX#" name="#NAME#" title="#TITLE#" privs="#PRIVS#" size="#SIZE#" fulldate="#FULLDATE#" Date="#DATE#" Keywords="#KEYWORDS#" preview="#PREVIEW#"><span class="fileSelectionMark"></span><div>' + ' <div class="imgBox"><div class="imgWrapper">' + ' <table cellspacing="0" cellpadding="0" align="center">' + ' <tbody>' + ' <tr>' + ' <td valign="middle" align="center">' + ' <a class="imgLink" rel="#REL#" href="#HREF#">' + ' <img alt="#NAME#" title="#NAME#" style="border: 0px none;" src="#SRC#">' + ' </a>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table></div>' + ' </div>' + ' </div>' + ' <div class="imgTitle">' + ' <a rel="#PATHREL#" href="#HREF#">#NAME#</a>' + ' </div>' + '</li>'; /* * Shows tree to particular elemenet. First parameter is * parent element, t is a path. Locatefolder in treeview * replaces all content with items in the folder specified. * Usehash is a boolean, which overrides any path supplied * and uses hash from location as a path */ if(o.signupPage) { function GetCurrentPageName() { var sPath = window.location.pathname; var sPage = sPath.substring(sPath.lastIndexOf("/") + 1); return sPage; } var customFormName = GetCurrentPageName(); customFormName = customFormName.replace(".html",""); getCustomForm(customFormName, function (data, hasForm, formName, showAlways) { if(hasForm) { $("#panelSignup").html("<form id='frmSignup'>" + data + "</form>").find("table").css("text-align","left"); $("button#resetPasteForm","#panelSignup").unbind().click(function (event) { $("#panelSignup").clearForm(); event.stopPropagation(); event.preventDefault(); }); function displayError(msg) { var form = $("#panelSignup"); if (form.prev().hasClass("attention")) { form.prev().remove(); } form.before("<div class='attention'>"+msg+"</div>"); form.prev().css("float", "none"); } function validateForm(target, form) { form = form || $("table.customForm","#divUploadPanel"); var validated = true; form.find(".required_true").each( function () { if($(this).hasClass("chkbox")) { if (!$(this).is(":checked") && $(this).closest("td").find("input:checked").length == 0) { $(this).parent().addClass("validationFail").focus(); validated = false; } else { $(this).parent().removeClass("validationFail"); } } else { if ($.trim($(this).val()).length == 0) { $(this).addClass("validationFail").focus(); validated = false; } else { $(this).removeClass("validationFail"); } } }); if (form.prev().hasClass("attention")) { form.prev().remove(); } if (!validated) { form.before("<div class='attention'>"+getLocalizationKey("FormValidationFailText")+"</div>"); } return validated; } $("button.submitForm").unbind().click(function (event){ event.stopPropagation(); event.preventDefault(); if(!validateForm("", $("#panelSignup"))) { return; } var messageForm = $("#panelSignup"); var formClone = messageForm.find("form"); messageForm = serializeForm(formClone[0]); if(messageForm.length==0) { return; } messageForm += "&command=selfRegistration&random="+Math.random(); var obj = messageForm; $("#panelSignup").addClass("spinner"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { displayError("Error : " + errorThrown); }, success: function (msg) { $("#panelSignup").removeClass("spinner"); var responseText = msg; var response = msg.getElementsByTagName("response"); response = IE(response[0]).textContent; if(response.toLowerCase() == "success") { $("#panelSignup").hide(); } displayError(response); } }); return false; }); } }, "Sign up"); return; } function showTree(parentElement, path, locateFolder, useHash) { /*Shows spinner*/ var c = parentElement; var t = path; c.addClass('wait'); /* Remove initial element */ $("#searchResultNotification").hide(); $(".jqueryFileTree.start").remove(); /* If to use custom data - Specific to CrushFTP */ if (o.customData) { /* Conditions if overrid location to use from location hash*/ if ((!$(this).data("initialized") && o.overrideFromHash) || useHash) { $(this).data("initialized", true); var hashLocation = getHash().replace("#", ""); if (hashLocation) { t = hashLocation; } else { t = "/"; } } if (locateFolder) { blockFileListingUI(true); } /* If nothing specified use root directory */ if (t.length == 0 || t == 'null') t = "/"; /* Data to POST to receive file listing */ var obj = { command: "getXMLListing", format: "JSON", path: encodeURIComponent(unescape(unescape(t))), random: Math.random() }; /* Make a call and receive list */ $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (msg) { renderListing(c, t, locateFolder, useHash, msg); if(msg) { var privs = msg.getElementsByTagName("privs"); privs = IE(privs[0]).textContent; $(document).data("curDirPrivs", privs); applyPrivs(); //its a reference to a file and not a folder, so do a download of it. if (currentView() == "Thumbnail") { if (!$(c).hasClass("directory") && $(c).find("a.imgLink[href='"+escape(unescape(t))+"']")[0] && $(c).find("a.imgLink[href='"+escape(unescape(t))+"']").length == 1) { downloadItems(false,$(c).find("a[rel='"+escape(unescape(t))+"']").closest("td")); renderListing(c, t, locateFolder, useHash, null);//empty the listing. } } else { if (!$(c).is("table#filesContainer") && !$(c).hasClass("directory") && $(c).find("a[rel='"+escape(unescape(t))+"']")[0] && $(c).find("a[rel='"+escape(unescape(t))+"']").length == 1) { downloadItems(false,$(c).find("a[rel='"+escape(unescape(t))+"']").closest("td")); renderListing(c, t, locateFolder, useHash, null);//empty the listing. } } } }, error: function (XMLHttpRequest, textStatus, errorThrown) { //its a reference to a file or folder as zip, so start a zip on demand of it. if (t.lastIndexOf(".zip") == t.length-4) { t = t.substring(0,t.lastIndexOf(".zip")); submitAction({ '#command': "downloadAsZip", '#path': encodeURIComponent("/"), '#paths': encodeURIComponent(unescape(t)), '#random': Math.random() }); } else $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); renderListing(c, t, locateFolder, useHash, null);//empty the listing. } }); } else { $.post(o.script, { dir: t }, function (data) { $(c).find('.start').html(''); $(c).removeClass('wait').append(data); blockFileListingUI(false); $(c).find('TR:hidden').show(); bindTree(c); }); } } function applyPrivs() { var privs = $(document).data("curDirPrivs"); var _delete = privs.indexOf("(delete)")>=0; var _write = privs.indexOf("(write)")>=0; var _resume = privs.indexOf("(resume)")>=0; var _share = privs.indexOf("(share)")>=0; var _slideshow = privs.indexOf("(slideshow)")>=0; var _rename = privs.indexOf("(rename)")>=0; var _makedir = privs.indexOf("(makedir)")>=0; var _deleteDir = privs.indexOf("(deletedir)")>=0; var _download = privs.indexOf("(read)")>=0; var myMenu = $("#mainNavigation"); if(!_delete){ myMenu.find("a[href='javascript:delete_items();']").hide(); } if(!_makedir){ myMenu.find("a[href='javascript:performAction('createFolder');']").hide(); } if(!_slideshow){ myMenu.find("a[href='javascript:performAction('slideshowDiv');']").hide(); } } function scrollToFileListing() { if(!o.buggyBrowser) { if($('html,body').scrollTop() > $("#mainContent").offset().top) { $('html,body').animate({ scrollTop: $("#mainContent").offset().top }, 0, false); } } } var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); function sortListing(column, dir, rebuild) { if(!column) { if(window.listingSortColumn) { column = window.listingSortColumn; } } window.listingSortDirection = dir; window.listingSortColumn = column; var inverse = window.listingSortDirection; function IsNumeric(input) { return !((input - 0) == input && input.length > 0); } function applySorting(x, y) { var a = x[window.listingSortColumn].toLowerCase(); var b = y[window.listingSortColumn].toLowerCase(); return (IsNumeric(a) || IsNumeric(b) ? a > b : +a > +b) ? inverse ? -1 : 1 : inverse ? 1 : -1; } if(window.filteredItems) { if(rebuild) { reBuildListing(window.matchedItems.sort(applySorting)); } } else { l = l.sort(applySorting); if(rebuild) { reBuildListing(); } } } function renderListing(c, t, locateFolder, useHash, msg, searchResult) { $("#filter").val(""); if (searchResult) { $("#searchResultNotification").show(); } if(!$("#filter").data("eventAdded")) { $("#filter").unbind("keyup").keyup(function (evt) { var evt = (evt) ? evt : ((event) ? event : null); var val = this.value; function startFilter() { if(window.last_search_item && window.last_search_item === val){ return false; } $("#itemCount").prepend("<span style='margin-right:15px;color:#777;'>(Applying filter...)</span>"); setTimeout(function(){ filterItem(val); },10); } if (evt.keyCode == 13) { startFilter(); } else { delay(function(){ startFilter(); }, 1000); } bindCountOfFiles(); }).data("eventAdded",true); } $("#cluetip").remove(); //If current view is thumbnail if (currentView() == "Thumbnail") { //This will provide HTML for thumbnails var data = mapXmlToTable(msg, true); $(c).html(data); //Bind various events prepareDataRow($(c).find("li")); bindTree(); bindAllEventsForThumbnailView($(c), data); $("#slider").show(); scrollToFileListing(); } else { /* If its tree view */ if(!$("table#filesContainer").data("columnsAdded")) { $("table#filesContainer").find('.start').html(''); $("table#filesContainer").removeClass('wait').append("<tbody></tbody>").prepend(headerTemplate); $("table#filesContainer").data("columnsAdded",true); } if (searchResult) { scrollToFileListing(); //Get the html after XML parsing for treeview var data = mapXmlToTable(msg, true); //Remove old items $(c).find(".headerSortDown").removeClass("headerSortDown"); $(c).find(".headerSortUp").removeClass("headerSortUp"); $(c).find("tbody").html(''); //Remove spinner and add HTML $(c).find("tbody").append(data); //Display new items blockFileListingUI(false); var elems = $(c).find('TR:hidden:not(.hiddenFile)').show().addClass("subdirectory"); /* Bind various events */ //prepareDataRow($(c).find("td.fileTR,td.directory")); bindTree(elems); //Apply proper padding and make it look like Tree var nameColumns = $(elems).find('.columnName'); nameColumns.addClass("subdirectory"); nameColumns.last().parent().addClass("subdirectoryLast"); var relLink = $("a[rel='" + $(nameColumns).first().parent().attr("rel") + "']"); var dirCheckBox = $(relLink).closest("tr").find(".chkBox:visible"); /* Handle checkboxes */ checkUnCheckDirectory(dirCheckBox.parent(), dirCheckBox.is(":checked")); toggleMainCheckbox(dirCheckBox.closest("table")); var padLeft = 0; if (relLink.parent().css("padding-left")) { try { padLeft = parseInt(relLink.parent().css("padding-left").replace("px", "")); } catch (ex) {} } else { padLeft = 20; } if (padLeft != NaN) { if (padLeft >= 20) { padLeft += 20; var padicon = padLeft; var padTree = padicon - 20; nameColumns.attr("style", "padding-left:" + padLeft + "px !important; background-position:" + padicon + "px !important;"); } } bindAllEventsForTreeviewGrid($(c), false); } else if (!locateFolder && $(c).hasClass('directory')) { //If to show folder items under tree //Get the html after XML parsing for treeview var data = mapXmlToTable(msg, true, true, c); //Remove old items var $parent = $(c).closest('table') || $parent; $parent.find(".headerSortDown").removeClass("headerSortDown"); $parent.find(".headerSortUp").removeClass("headerSortUp"); $parent.find("tbody").empty(); $parent.append(data).find('TR:hidden').show(); var expandedFolder = $(c).find("a").attr("rel"); if(!o.buggyBrowser) { var spanTop = $("span[rel='"+expandedFolder+"']:first").offset().top; if($('html,body').scrollTop() < spanTop) { $('html,body').animate({ scrollTop: spanTop }, 0, false); } } bindTree($parent); bindAllEventsForTreeviewGrid($parent, true, data); $parent.find("tr.subdirectory").each(function(){ var relLink = $("a[rel='" + $(this).attr("rel") + "']"); var rootdir = escape($(this).attr("rootdir")); var dirSpan = $parent.find("span[rel='"+rootdir+"']"); $(dirSpan).parent().removeClass('collapsed').addClass('expanded'); $(dirSpan).find("img").attr("src", o.expandedImageURL); var padLeft = 0; if (relLink.parent().css("padding-left")) { try { padLeft = parseInt(relLink.parent().css("padding-left").replace("px", "")); } catch (ex) {} } else { padLeft = 20; } if (padLeft != NaN) { if (padLeft >= 20) { padLeft += 20; var padicon = padLeft; var padTree = padicon - 20; $(this).find("td.columnName").attr("style", "padding-left:" + padLeft + "px !important; background-position:" + padTree + "px 4px !important;"); } } }); } else if (locateFolder) { scrollToFileListing(); //If to show folder items only //Get the html after XML parsing for treeview var data = mapXmlToTable(msg); //Replace all existing items with new items and show them var $parent = $(c).closest('table') || $parent; $parent.find(".headerSortDown").removeClass("headerSortDown"); $parent.find(".headerSortUp").removeClass("headerSortUp"); $parent.find("tbody").empty(); $parent.append(data).find('TR:hidden').show(); //prepareDataRow($(c).find("td.fileTR,td.directory")); bindTree($parent); bindAllEventsForTreeviewGrid($(c).closest('table'), true, data); } else { //If its called for first time. Get the html after XML parsing for treeview var data = mapXmlToTable(msg); //Replace all existing items with new items and show them $(c).find("tbody").append(data); blockFileListingUI(false); var currentViewType = $.cookie(o.ViewCookieName);//prepareDataRow($(c).find("td.fileTR,td.directory")); bindTree(c);//TODO 584ms for 1200 items $(c).closest('table').find("tr").attr("style", "background-position:40px 3px !important;"); bindAllEventsForTreeviewGrid($(c).closest('table'), true, data); } } bindCountOfFiles(); try{ window.cancelDrop(); }catch(ex) {} if(msg && msg.getElementsByTagName("quota") && msg.getElementsByTagName("quota").length>0) { window.quota = IE(msg.getElementsByTagName("quota")[0]).textContent; if ( $("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'> "+window.quota+" available.</span>"); } $("a.clearFilterLink").unbind("click").click( function (e) { e.preventDefault(); if ($("#filter").val().length > 0) { $("#filter").val("").keyup(); } selectDeselectAllItems(false); return false; }); } function bindCountOfFiles() { if (currentView() == "Thumbnail") { var totalItems = $("li", "#filesContainerDiv").length; var totalVisibleItems = $("li:visible", "#filesContainerDiv").length; var totalDirs = $("li.directoryThumb:visible", "#filesContainerDiv").length; var totalFiles = totalVisibleItems - totalDirs; var hiddenItems = $("li", "#filesContainerDiv").length - $("li:visible", "#filesContainerDiv").length; var msg = totalVisibleItems + " " + getLocalizationKey("FileCounterItemsText") + " ("; if (totalDirs > 0) { msg += totalDirs + " " + getLocalizationKey("FileCounterFoldersText") + ", "; } msg += totalFiles + " " + getLocalizationKey("FileCounterFilesText") + ") " if (hiddenItems > 0) { msg += hiddenItems + " " + getLocalizationKey("FileCounterHiddenItemsText") } if (l && totalItems + hiddenItems < l.length) { msg += " (Total items in directory " + l.length + ")"; } $("div.itemCount").html(msg); if ( $("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'> "+window.quota+" available.</span>"); if(window.filteredItems && window.filteredItems.filesCount && $("#filter").val().length>0) { var files = window.filteredItems.filesCount; var dirs = window.filteredItems.dirsCount; var totalItems = files + dirs; var itemCount = "(Items with phrase \""+ $("#filter").val() +"\" : " + totalItems + " , Folders:"+dirs+" Files: " + files + ")"; $("#itemCount").prepend("<span style='margin-right:15px;color:#777;'>"+itemCount+"</span>"); } } else { var totalItems = $("tr", "#filesContainer>tbody").length; var totalVisibleItems = $("tr:visible", "#filesContainer>tbody").length; var totalDirs = $("td.directory:visible", "#filesContainer>tbody").length; var totalFiles = totalVisibleItems - totalDirs; var hiddenItems = $("tr", "#filesContainer>tbody").length - $("tr:visible", "#filesContainer>tbody").length; var msg = totalVisibleItems + " "+getLocalizationKey("FileCounterItemsText")+" ("; if (totalDirs > 0) { msg += totalDirs + " "+getLocalizationKey("FileCounterFoldersText")+", "; } msg += totalFiles + " "+getLocalizationKey("FileCounterFilesText")+") " if (hiddenItems > 0) { msg += hiddenItems + " " + getLocalizationKey("FileCounterHiddenItemsText") } if (l && totalItems + hiddenItems < l.length) { msg += " (Total items in directory " + l.length + ")"; } $("div.itemCount").html(msg); if ( $("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'> "+window.quota+" available.</span>"); if(window.filteredItems && window.filteredItems.filesCount && $("#filter").val().length>0) { var files = window.filteredItems.filesCount; var dirs = window.filteredItems.dirsCount; var totalItems = files + dirs; var itemCount = "(Items with phrase \""+ $("#filter").val() +"\" : " + totalItems + " , Folders:"+dirs+" Files: " + files + ")"; $("#itemCount").prepend("<span style='margin-right:15px;color:#777;'>"+itemCount+"</span>"); } } } function bindSelectionMenu() { if($("a.selectionLink") && $("a.selectionLink").contextMenu) { $("a.selectionLink").contextMenu({ menu: 'selectionMenu' }, function (action, el, pos, command) { handleCheckBoxContextMenuEvents(action, el, pos, command); }).click(function(evt){ evt.stopPropagation(); evt.preventDefault(); $(this).trigger("mousedown").trigger("mouseup"); return false; }); } } function bindPagingSizeMenu() { if($("a.pageSizeSelectionLink") && $("a.pageSizeSelectionLink").contextMenu) { $("a.pageSizeSelectionLink").contextMenu({ menu: 'pagingSizeMenu' }, function (action, el, pos, command) { handlePageSizeContextMenuEvents(action, el, pos, command); }).click(function(evt){ evt.stopPropagation(); evt.preventDefault(); $(this).trigger("mousedown").trigger("mouseup"); return false; }); } } function bindAllEventsForThumbnailView(parentElement, data) { bindBreadcrumbs(); showButtonsBasedOnPriviledge(); //Enable context menu var ok = true; try{if (noMenus) ok=false;}catch(e){} if (ok) { $(".fileBox").contextMenu({ menu: 'myMenu' }, function (action, el, pos, command) { handleContextMenuEvents(action, el, pos, command); }); } bindGoToFolderEvents($(parentElement), o); //Remove spinner $('.wait').removeClass('wait'); blockFileListingUI(false); // Set item title text to fit width setTitleText(); // Set icons to proper zoom as selection zoomInOutView(zoomSlider.slider("value")); checkFilesAvailable(data); refreshView(); bindCountOfFiles(); loadDirectoryPreview(); } function refreshView() { var hideItemsStartingWithDot = $.cookie(o.CookieHideItemStartingWithDot); hideItemsStartingWithDot = hideItemsStartingWithDot == "true"; if(hideItemsStartingWithDot) { $("#SelectCheckboxContextMenuCheckItemsWithDotText").parent().hide(); } else{ $("#SelectCheckboxContextMenuCheckItemsWithDotText").parent().show(); } var hideFilter = $.cookie(o.CookieHideFilter); hideFilter = hideFilter == "true"; if (hideFilter) { $(".filterPanel").hide(); } else { $(".filterPanel").show(); } var hideCheckBoxColumn = $.cookie(o.CookieHideCheckBoxColumn); if(hideCheckBoxColumn && hideCheckBoxColumn != "true") { hideCheckBoxColumn = $(document).data("disableCheckCol"); if(hideCheckBoxColumn == "true") { $("#hideCheckBoxColumn").attr("disabled","disabled"); } } hideCheckBoxColumn = hideCheckBoxColumn == "true"; var disableNameCol = $(document).data("disableNameCol"); disableNameCol = disableNameCol == "true"; var disableSizeCol = $(document).data("disableSizeCol"); disableSizeCol = disableSizeCol == "true"; var disableModifiedCol = $(document).data("disableModifiedCol"); disableModifiedCol = disableModifiedCol == "true"; var disableKeywordsCol = $(document).data("disableKeywordsCol"); disableKeywordsCol = disableKeywordsCol == "true"; if (currentView() == "Thumbnail") { if (hideItemsStartingWithDot) { $("div.imgTitle").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { $(this).closest("li").hide().addClass("hiddenFile"); } }); } else { $("div.imgTitle").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { $(this).closest("li").show().removeClass("hiddenFile"); } }); } } else { if (hideCheckBoxColumn) { $("#filesContainer").find("td.columnSelect").hide(); $("#filesContainer").find("thead > tr > td:first").hide(); } else { $("#filesContainer").find("td.columnSelect").show(); $("#filesContainer").find("thead > tr > td:first").show(); } if (disableNameCol) { $("#filesContainer").find("td.columnName,td.thName").hide(); } else { $("#filesContainer").find("td.columnName").show(); } if (disableSizeCol) { $("#filesContainer").find("td.columnSize,td.thSize").hide(); } else { $("#filesContainer").find("td.columnSize").show(); } if (disableModifiedCol) { $("#filesContainer").find("td.columnModified").hide(); } else { $("#filesContainer").find("td.columnModified").show(); } if (disableKeywordsCol) { $("#filesContainer").find("td.columnKeywords,td.thKeywords").hide(); } else { $("#filesContainer").find("td.columnKeywords").show(); } if (hideItemsStartingWithDot) { $(".jqueryFileTree").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { var el = $(this).closest("td"); if ($(el).hasClass("directory")) { hideDirectoryFromTree($(el).closest("table").find('TR[rel="' + escape($(el).find("a").attr('rel')) + '"]'), true); } $(this).closest("tr").hide().addClass("hiddenFile"); } }); } else { $(".jqueryFileTree").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { var el = $(this).closest("td"); if ($(el).hasClass("directory")) { hideDirectoryFromTree($(el).closest("table").find('TR[rel="' + escape($(el).find("a").attr('rel')) + '"]'), false); } $(this).closest("tr").show().removeClass("hiddenFile"); } }); } } bindCountOfFiles(); } function bindAllEventsForTreeviewGrid(element, checkForFiles, data) { var dtime = new Date(); $(element).find("tr:even").addClass("jqueryFileTreeAlt"); howerEffect(); bindCheckboxEvents(); bindBreadcrumbs(); showButtonsBasedOnPriviledge(); blockFileListingUI(false); if (checkForFiles) { checkFilesAvailable(data); } var itemCount = 0; if (currentView() == "Thumbnail") { itemCount = $("li", "#filesContainerDiv").length; } else { itemCount = $("tr", "#filesContainer>tbody").length; bindSortingToTreeviewGrid(); } if (navigator.appName.indexOf("Explorer") < 0 || (navigator.appName.indexOf("Explorer") >= 0 && itemCount < 200)) { bindContextMenu(element); //no context menu on explorer...jsut too slow! } bindGoToFolderEvents(element, o); refreshView(); $(".chkBoxAll").removeAttr("checked"); loadDirectoryPreview(); } function bindSortingToTreeviewGrid() { var th = jQuery('#filesContainer').find('thead > tr > td').addClass("header"), inverse = true; window.listingSortDirection = $(document).data("listDefaultSortDirection") || "up"; window.listingSortColumn = $(document).data("listDefaultSortColumnIndex") || 1; if($("thead","table#filesContainer").find("td").eq(window.listingSortColumn)) { window.listingSortColumn = $("thead","table#filesContainer").find("td").eq(window.listingSortColumn).attr("colName"); window.listingSortColumn = window.listingSortColumn || "name"; } else { window.listingSortColumn = "name"; } if(window.listingSortColumn) { if(window.listingSortDirection == "up") { inverse = false; } } if(!inverse) { $("thead","table#filesContainer").find("td[colName='"+window.listingSortColumn+"']").addClass("headerSortUp"); } else { $("thead","table#filesContainer").find("td[colName='"+window.listingSortColumn+"']").addClass("headerSortDown"); } if (!$("#filesContainer").data("sortingAdded")) { $(".chkBoxAll").click(function (event) { var chkBox = $(this); toggleCheckBoxesAll($(this).closest("table"), chkBox.is(":checked")); }); th.click(function () { if ($(this).hasClass("thSelect")) { return; } inverse = !inverse; sortListing($(this).attr("colName"), inverse, true); $(th).parent().find(".headerSortDown").removeClass("headerSortDown"); $(th).parent().find(".headerSortUp").removeClass("headerSortUp"); if (!inverse) { $(this).removeClass("headerSortDown").addClass("headerSortUp"); } else { $(this).removeClass("headerSortUp").addClass("headerSortDown"); } }); $("#filesContainer").data("sortingAdded", true); sortListing(window.listingSortColumn, inverse, true); } } function bindContextMenu(elems) { var ok = true; try{if (noMenus) ok=false;}catch(e){} if (ok) { var $filesContainer = elems || $("#filesContainer"); $filesContainer.find("td.fileTR, td.directory, td.file").contextMenu({ menu: 'myMenu', addHoverClass:true }, function (action, el, pos, command) { handleContextMenuEvents(action, el, pos, command); }); } $(".chkBoxAll").contextMenu({ menu: 'checkBoxMenu' }, function (action, el, pos, command) { handleCheckBoxContextMenuEvents(action, el, pos, command); }); } function checkFilesAvailable(fileList) { if (fileList.length == 0) { o.FileListingElement.block({ message: o.FilesNotAvailableMessage, css: { border: 'none', padding: '5px', backgroundColor: '#fff', color: '#000', width: '200px', 'margin-left': '-100px', top: '40px', left: '50%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', 'text-align': 'center', 'font-size': '11px' } }); } else { o.FileListingElement.unblock(); } } function prepareDataRow(elems) { $(elems).each(function () { var keywords = $(this).attr("keywords"); if (keywords.length >= o.keywordsCharLimit) { keywords = keywords.substr( 0, o.keywordsCharLimit) + "..."; } var data = { name: $(this).attr("name"), size: $(this).attr("size"), date: $(this).attr("date"), fulldate: $(this).attr("fulldate"), keywords: keywords, preview: $(this).attr("preview"), privs: $(this).attr("privs") }; $(this).data("dataRow", data); $(this).removeAttr("name").removeAttr("size").removeAttr("date").removeAttr("preview").removeAttr("privs").removeAttr("fulldate"); }); } var regexpCache = {}; function wbr(str, num) { if (!regexpCache[num]) { regexpCache[num] = RegExp("(\[^\s-].{" + num + "})(?=\[^\s-].)", "g"); } return str.replace(regexpCache[num], "$1<br>"); } function setTitleText(elem, chars) { elem = elem || $(".imgTitle").find("a"); chars = chars || o.thumbnailTextCharsLimit; elem.addClass("wordwrap"); if ($.browser.msie && parseInt(jQuery.browser.version) == 8) { elem.each(function () { try{ var title = $(this).closest("li").data("dataRow").name; $(this).html(wbr($(this).text(), chars)); }catch(ex){} }); } } function loadIconPreview(size, force, elem) { var genericIconTree = $(document).data("genericIconTree"); var genericIconThumbnail = $(document).data("genericIconThumbnail"); if (currentView() == "Thumbnail") { var zoomValue = parseInt(window.zoomSlider.slider("value")); size = size || 2; var iconSize = 48; if(zoomValue<3) { $("li.directoryThumb").find("a.imgLink").find("img").attr("src",o.fileFolder); iconSize = 48; } else if(zoomValue<6) { $("li.directoryThumb").find("a.imgLink").find("img").attr("src",o.fileFolder1); iconSize = 128; } else if(zoomValue<10) { $("li.directoryThumb").find("a.imgLink").find("img").attr("src",o.fileFolder2); iconSize = 256; } else { $("li.directoryThumb").find("a.imgLink").find("img").attr("src",o.fileFolder3); iconSize = 512; } var disableHover = false; if ($(document).data("disableThumbnailHover") && $(document).data("disableThumbnailHover") == "true") disableHover = true; if(!disableHover) { disableHover = zoomValue >= 13; } if(disableHover) { $("li.directoryThumb").each(function () { var $curElem = $(this); var item = $curElem.closest("li").addClass("vtipDisabled"); if(item.attr("title")) { $(item).attr("_title",$(item).attr("title")); $(item).removeAttr("title"); } }); } else { $("li.directoryThumb").each(function () { var $curElem = $(this); var item = $curElem.closest("li").removeClass("vtipDisabled"); if(item.attr("_title")) { $(item).attr("title",$(item).attr("_title")); $(item).removeAttr("_title"); } }); } if (elem && elem.hasClass("directoryThumb")) { return; } var opt = false; if (force) { if (elem) { opt = $(elem).data("dataRow"); elem = elem.closest("li") || elem; if (elem.hasClass("vtip")) { elem.attr("title", "<strong>Name : </strong>" + elem.find("div.imgTitle>a").text() + "<br /><strong>Size : </strong>" + opt.size + "<br /><strong>Modified : </strong>" + opt.date + "<br /><strong>Keywords : </strong>" + opt.keywords); } elem = elem.find("a.imgLink").find("img"); elem.removeClass("loadedPreview").attr("src", o.spinerImage); } else { $("img.loadedPreview").removeClass("loadedPreview").attr("src", o.spinerImage); } } if ($.browser.msie && parseInt(jQuery.browser.version) <8) { var loc = window.location.toString().replace(hashListener.getHash().toString(), ""); loc = loc.substring(0,loc.length - 1); elem = elem || $("img[src='" + loc + o.spinerImage + "']"); } else { elem = elem || $("img[src='" + o.spinerImage + "']"); } elem.each(function () { var $curElem = $(this); if(disableHover) { var item = $curElem.closest("li").addClass("vtipDisabled"); if(item.attr("title")) { $(item).attr("_title",$(item).attr("title")); $(item).removeAttr("title"); } } else { var item = $curElem.closest("li").removeClass("vtipDisabled"); if(item.attr("_title")) { $(item).attr("title",$(item).attr("_title")); $(item).removeAttr("_title"); } } $curElem.unbind().bind("load", function (e) { var parentElem = $(this).closest("li") || parentElem; var relLink = parentElem.find("a:first"); var $this = $(this); $(this).removeAttr("width") .removeAttr("height") .css({ width: "", height: "" }); var pic_real_width = this.width; var pic_real_height = this.height; if(pic_real_width < $this.closest("div").width() && pic_real_height < $this.closest("div").height()) { $this.css("height","auto"); $this.css("width","auto"); } else if(pic_real_width > pic_real_height) { $this.css("height","auto"); $this.css("width",$this.closest("div").width()); } else { $this.css("width","auto"); $this.css("height",$this.closest("div").height()); } }); var genericIcon = true; opt = $curElem.closest("li").data("dataRow"); if (opt && opt.preview == "true") { if(!genericIconThumbnail) { $curElem.attr("src", o.ajaxCallURL + "?command=getPreview&size=" + size + "&path=" + encodeURIComponent(unescape($curElem.parent().attr("rel")))).attr("style", o.PreviewIconThumbnailStyle); genericIcon = false; } var parentElem = $curElem.closest("li") || $curElem; var relLink = parentElem.find("a:first"); var title = $(parentElem).attr("title") || $(parentElem).attr("original-title"); if (title && title.indexOf("getPreview") < 0) { $(parentElem).attr("title", "<img src=\"" + o.ajaxCallURL + "?command=getPreview&size=3&path=" + encodeURIComponent(unescape(relLink.attr("rel"))) + "\" border=\"0\" /> <br />" + $(parentElem).attr("title")); } } if(genericIcon) { var ext = getFileExtension($(this).parent().attr("href")); if(o.availableFileExtensionImages.has(ext)) { $(this).attr("src", o.FileExtensionImageFilePath + getFileExtension($(this).parent().attr("href")) + "_" + iconSize + ".png"); } else { $(this).attr("src", o.fileLarge + "_" + iconSize + ".png").attr("style", o.PreviewIconThumbnailStyle); } } var src = $(this).attr("src"); $(this).attr("src",""); $(this).attr("src",src).addClass("loadedPreview"); }); } else { size = size || 1; elem = elem || $("td.fileTR"); var disableHover = false; if ($(document).data("disableTreeviewHover") && $(document).data("disableTreeviewHover") == "true") disableHover = true; elem.each(function () { var $curElem = $(this); var newImg = $("<img />"); $curElem.find(".previewIcon").remove(); $curElem.prepend("<span class=\"previewIcon\"></span>"); $curElem.find(".previewIcon").append(newImg); if ($curElem.attr("preview") == "true" && !genericIconTree) { newImg = $curElem.find("img"); newImg.attr("src", o.ajaxCallURL + "?command=getPreview&size=" + size + "&path=" + encodeURIComponent(unescape($curElem.find("a").attr("rel")))); var relLink = $curElem.find("a").addClass("iconPreviewLink"); $curElem.removeClass("fileItem"); if(!disableHover) { $curElem = $curElem.find("a").addClass("vtip"); $curElem.attr("title", "<img src=\"" + o.ajaxCallURL + "?command=getPreview&size=3&path=" + encodeURIComponent(unescape(relLink.attr("rel"))) + "\" border=\"0\" />"); vtip($curElem); } } else { newImg = $curElem.find("img"); var ext = getFileExtension($(newImg).parent().next().attr("rel")); if(o.availableFileExtensionImages.has(ext)) { newImg.attr("src", o.FileExtensionImageFilePath + getFileExtension($(newImg).parent().next().attr("rel")) + "_16.png"); } else { newImg.attr("src", o.fileLarge + "_16.png").attr("style", o.PreviewIconThumbnailStyle); } if ($curElem.attr("preview") == "true") { var relLink = $curElem.find("a").addClass("iconPreviewLink"); $curElem.removeClass("fileItem"); if(!disableHover) { $curElem = $curElem.find("a").addClass("vtip"); $curElem.attr("title", "<img src=\"" + o.ajaxCallURL + "?command=getPreview&size=3&path=" + encodeURIComponent(unescape(relLink.attr("rel"))) + "\" border=\"0\" />"); vtip($curElem); } } } }); } } function bindEventsToViewChanger() { $(".thumbnailViewLink,.treeViewLink").unbind("click"); $(".thumbnailViewLink,.treeViewLink").click( function (evt) { if ($(this).attr("rel") != currentView()) { $(this).parent().find("a").animate({ opacity: 1 }, 0); $(this).animate({ opacity: 0.3 }, 500); changeView($(this).attr("rel"), true); } $(this).blur(); evt.preventDefault(); return false; }); if (!$("#slider").attr("added")) { window.zoomSlider = $("#slider").slider({ min: 0, max: 30, change: function (event, ui) { zoomInOutView(ui.value); } }); } } bindEventsToViewChanger(); window.zoomInOutView = function(val) { if (val > 0) { $.cssRule({ ".fileBox": [ ["width", o.lowestThumbnailBoxWidth + (val * 30) + "px"], ["height", o.lowestThumbnailBoxHeight + (val * 20) + "px"] ]}); $.cssRule({ ".fileBox .imgBox": [ ["height", o.lowestThumbnailBoxHeight + (val * 20) - 50 + "px"] ]}); $.cssRule({ ".imgWrapper": [ ["height", o.lowestThumbnailBoxHeight + (val * 20) - 52 + "px"] ]}); if (val >= 5) { loadIconPreview(3, true); } else { loadIconPreview(2, true); } } else { $.cssRule({ ".fileBox": [ ["width", o.lowestThumbnailBoxWidth + "px"], ["height", o.lowestThumbnailBoxHeight + "px"] ]}); $.cssRule({ ".fileBox .imgBox": [ ["height", o.lowestThumbnailBoxHeight - 50 + "px"] ]}); $.cssRule({ ".imgWrapper": [ ["height", o.lowestThumbnailBoxHeight - 52 + "px"] ]}); loadIconPreview(2, true); } if ($.browser.msie && parseInt(jQuery.browser.version) == 8) { var charlimit = o.thumbnailTextCharsLimit + (val * 4); setTitleText(false, charlimit); } } function openNewWindow(path) { window.open(path); } function bindGoToFolderEvents(t, o) { if (currentView() == "Thumbnail") { $(t).find('a','LI.fileBox').unbind("click").click(function(evt){ var curitem = $(this).closest("li.fileBox"); curitem.attr("shift",evt.shiftKey); curitem.trigger("click"); $(this).blur(); return false; }); $(t).find('LI.fileBox').unbind("click").click(function(evt){ var curitem = $(this); var shift = evt.shiftKey || curitem.attr("shift") == "true"; curitem.removeAttr("shift"); if(shift) { if(window.lastSelectedItem) { var lastItem = window.lastSelectedItem; window.lastSelectedItem = false; if(lastItem != curitem) { var lastItemIndex = parseInt($(lastItem).attr("index")); var curItemIndex = parseInt($(curitem).attr("index")); if(lastItemIndex > curItemIndex) { for(var i = curItemIndex; i <= lastItemIndex;i++) { if($($(t).find("li").get(i)).is(":visible")) { $($(t).find("li").get(i)).addClass("fileBoxSelected"); } } } if(curItemIndex > lastItemIndex) { for(var i = lastItemIndex; i <= curItemIndex;i++) { if($($(t).find("li").get(i)).is(":visible")) { $($(t).find("li").get(i)).addClass("fileBoxSelected"); } } } } } } else { if(curitem.hasClass("fileBoxSelected")) { curitem.removeClass("fileBoxSelected"); window.lastSelectedItem = false; } else { curitem.addClass("fileBoxSelected"); window.lastSelectedItem = curitem; } } if(window.getSelection) { var selection = window.getSelection(); if(selection.removeAllRanges) { selection.removeAllRanges(); } } if(document.getSelection) { var selection = document.getSelection(); if(selection.removeAllRanges) { selection.removeAllRanges(); } } $(this).blur(); return false; }); $(t).find('LI.fileBox').unbind(o.thumbFolderEvent); $(t).find('LI.fileBox').bind(o.thumbFolderEvent, function () { $(".cluetip-default").remove(); if ($(this).hasClass("directoryThumb")) { window.current_page = o.pagingCurrentPage = 0; $(document).removeData("searchData"); var loc = $(this).find("a.imgLink").attr('rel').match(/.*\//); if (loc) { blockFileListingUI(true); setHashLocation(loc); $(".cluetip-default").remove(); } } else { var extsToOpen = $(document).data("OPEN_NEW_WINDOW_EXTENSIONS"); var fileName = $(this).find("a:first").attr("rel"); var fileExt = "." + getFileExtension(fileName); if(extsToOpen && extsToOpen.length>0 && fileExt.length>0 && extsToOpen.has(fileExt)) { window.open(fileName); } else { downloadItems(false,$(this)); } } $(this).blur(); return false; }); } else { $(t).find('TD A').unbind(o.folderEvent); $(t).find('TD A').bind(o.folderEvent, function (evt) { $("#cluetip").hide(); if(evt.ctrlKey) { evt.stopPropagation(); evt.preventDefault(); return false; } if ($(this).parent().hasClass("directory")) { window.current_page = o.pagingCurrentPage = 0; $(document).removeData("searchData"); var loc = $(this).prev().attr('rel').match(/.*\//); if (loc) { setHashLocation(loc); } } else { var extsToOpen = $(document).data("OPEN_NEW_WINDOW_EXTENSIONS"); var fileName = $(this).closest("td").find("a:first").attr("rel"); var fileExt = "." + getFileExtension(fileName); if(extsToOpen && extsToOpen.length>0 && fileExt.length>0 && extsToOpen.has(fileExt)) { window.open(fileName); } else { downloadItems(false,$(this).closest("td")); } } $(this).blur(); return false; }); } } function bindCheckboxEvents() { $("tr.jqueryFileTree").not(".file").find(".chkBox").unbind("click"); $("tr.jqueryFileTree").not(".file").find(".chkBox").click(function () { checkUnCheckDirectory($(this).parent(), $(this).is(":checked")); toggleMainCheckbox($(this).closest("table")); }); } function bindTree(t) { if (currentView() != "Thumbnail") { $(t).find('span.expandButton').unbind(o.folderEvent); var ok = true; try{if (noMenus) ok=false;}catch(e){} if (!ok) { $(t).find('span.expandButton').hide(); } if (ok) { $(t).find('span.expandButton').bind(o.folderEvent, function () { if ($(this).parent().hasClass('collapsed')) { // Expand showTree($(this).parent(), escape($(this).attr('rel').match(/.*\//))); $(this).parent().removeClass('collapsed').addClass('expanded'); $(this).parent().find("span.expandButton").find("img").attr("src", o.expandedImageURL); } else { // Collapse removeDirectoryFromTree($(this).closest("table").find('TR[rel="' + $(this).attr('rel') + '"]')); var expandedFolder = $(this).attr('rel'); reBuildListing(window.curTreeItems); if(!o.buggyBrowser) { var spanTop = $("span[rel='"+expandedFolder+"']:first").offset().top; if($('html,body').scrollTop() < spanTop) { $('html,body').animate({ scrollTop: spanTop }, 0, false); } } } $(this).blur(); return false; }); } bindGoToFolderEvents(t, o); } // Prevent A from triggering the # on non-click events if (o.folderEvent.toLowerCase != 'click') $(t).find('TD A').bind('click', function () { return false; }); $(".cluetip-default").remove(); /* Load icon previews for images if available */ loadIconPreview(); /* Enable tooltips */ vtip(); } function removeDirectoryFromTree(trElems) { var rel = $(trElems.get(0)).attr("rel"); var newItems = []; for(var i=0;i < window.curTreeItems.length;i++) { var curItem = window.curTreeItems[i]; if(escape(curItem.root_dir).indexOf(rel)!=0) { newItems.push(curItem); } } window.curTreeItems = newItems; } function hideDirectoryFromTree(trElems, flag) { $(trElems).each(function () { $(this).find("td.directory").each(function () { hideDirectoryFromTree($(this).closest("table").find('TR[rel="' + $(this).find('a').attr('rel')) + '"]'); }); if (flag) { $(this).hide(); } else { $(this).show(); } }); } function moveElementOnTreeAfterSorting(trElems) { $(trElems).each(function () { var parentTR = $(this); $(this).closest("table").find("tr[rel='" + $(this).find("a").attr("rel") + "']").each(function () { if ($(this).find("td.directory").length > 0) { $(parentTR).closest("tr").after($(this)); moveElementOnTreeAfterSorting($(this).find("td.directory")); } else { $(parentTR).closest("tr").after($(this)); } }); }); } function getPageSize() { var CookiePageSize = $.cookie(o.CookiePageSize); if(!CookiePageSize) { var options = { path: '/', expires: 365 }; $.cookie(o.CookiePageSize, o.defaultPageSize, options); CookiePageSize = o.defaultPageSize; } if(CookiePageSize == 0) { return "all"; } else { return CookiePageSize } } function reBuildListing(customData) { var data = generateListing(customData); if(currentView() == "Thumbnail") { var c = $("#filesContainerDiv"); $(c).html(data); //Bind various events prepareDataRow($(c).find("li")); bindTree(); bindAllEventsForThumbnailView($(c), data); $("#slider").show(); scrollToFileListing(); } else { var c = $("#filesContainer"); $(c).find("tbody").empty().append(data); blockFileListingUI(false); bindTree(c); $(c).closest('table').find("tr").attr("style", "background-position:40px 3px !important;"); bindAllEventsForTreeviewGrid($(c).closest('table'), true, data); c.find("tr.subdirectory").each(function(){ var relLink = $("a[rel='" + $(this).attr("rel") + "']"); var rootdir = escape($(this).attr("rootdir")); var dirSpan = c.find("span[rel='"+rootdir+"']"); $(dirSpan).parent().removeClass('collapsed').addClass('expanded'); $(dirSpan).find("img").attr("src", o.expandedImageURL); var padLeft = 0; if (relLink.parent().css("padding-left")) { try { padLeft = parseInt(relLink.parent().css("padding-left").replace("px", "")); } catch (ex) {} } else { padLeft = 20; } if (padLeft != NaN) { if (padLeft >= 20) { padLeft += 20; var padicon = padLeft; var padTree = padicon - 20; $(this).find("td.columnName").attr("style", "padding-left:" + padLeft + "px !important; background-position:" + padTree + "px 4px !important;"); } } }); } } function updatePageSizeOnLayout(refresh, customItem) { var CookiePageSize = getPageSize(); o.defaultPageSize = CookiePageSize; var pageText = getLocalizationKey("PageSizeSelectionLinkText").replace("{0}", CookiePageSize); $("#PageSizeSelectionLinkText").html(pageText).show(); if(refresh) { reBuildListing(customItem); } } function changePagerSize(pageSize) { var options = { path: '/', expires: 365 }; $.cookie(o.CookiePageSize, pageSize, options); window.current_page = o.pagingCurrentPage = 0; updatePageSizeOnLayout(true); } function handlePageSizeContextMenuEvents(action, el, pos, command) { $("#cluetip").hide(); action = action == "all" ? 0 : action;changePagerSize(action); return false; } function handleCheckBoxContextMenuEvents(action, el, pos, command) { $("#cluetip").hide(); switch (action) { case 'checkall': selectDeselectAllItems(true); break; case 'uncheckall': selectDeselectAllItems(false); break; case 'toggle': selectDeselectAllItems(false, true); break; case 'checkallfiles': if(currentView() == "Thumbnail") { $("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected"); $("#filesContainerDiv").find("li.fileThumb:visible").addClass("fileBoxSelected"); } else { $("#filesContainer").find(".chkBox:visible:checked").removeAttr("checked"); $("#filesContainer").find("td.fileTR").each(function(){ $(this).parent().find("input.chkBox").attr("checked","checked"); }); if(isChecked($("#filesContainer"))) { $("#filesContainer").find("input.chkBoxAll").attr("checked","checked"); } else { $("#filesContainer").find("input.chkBoxAll").removeAttr("checked"); } } break; case 'checkallfolders': if(currentView() == "Thumbnail") { $("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected"); $("#filesContainerDiv").find("li.directoryThumb:visible").addClass("fileBoxSelected"); } else { $("#filesContainer").find(".chkBox:visible:checked").removeAttr("checked"); $("#filesContainer").find("td.directory").each(function(){ $(this).parent().find("input.chkBox").attr("checked","checked"); }); if(isChecked($("#filesContainer"))) { $("#filesContainer").find("input.chkBoxAll").attr("checked","checked"); } else { $("#filesContainer").find("input.chkBoxAll").removeAttr("checked"); } } break; case 'checkitemswithdot': if (currentView() == "Thumbnail") { $("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected"); $("div.imgTitle:visible").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { $(this).closest("li").addClass("fileBoxSelected"); } }); } else { $("#filesContainer").find(".chkBox:visible:checked").removeAttr("checked"); $(".jqueryFileTree").find("a").each( function () { if ($.trim($(this).text()).charAt(0) == ".") { $(this).closest("tr").find("input.chkBox").attr("checked","checked"); } }); if(isChecked($("#filesContainer"))) { $("#filesContainer").find("input.chkBoxAll").attr("checked","checked"); } else { $("#filesContainer").find("input.chkBoxAll").removeAttr("checked"); } } break; case 'checktoday': checkModifiedItemsByDay(1); break; case 'checkweek': checkModifiedItemsByDay(7); break; case 'checkmonth': checkModifiedItemsByDay(30); break; case 'check2months': checkModifiedItemsByDay(60); break; case 'check3months': checkModifiedItemsByDay(90); break; } } function checkModifiedItemsByDay(day) { day = day || 1; if (currentView() == "Thumbnail") { $("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected"); $("div.imgTitle:visible").find("a").each( function () { var data = $(this).closest("li").data("dataRow"); if(data) { var fileDateMills = data.fulldate; if ((fileDateMills*1) > new Date().getTime()-(1000*60*60*24*day)) { $(this).closest("li").addClass("fileBoxSelected"); } } }); } else { $("#filesContainer").find(".chkBox:visible:checked").removeAttr("checked"); $(".jqueryFileTree").find("a").each( function () { var fileDateMills = $(this).closest("tr").attr("modified"); if ((fileDateMills*1) > new Date().getTime()-(1000*60*60*24*day)) { $(this).closest("tr").find("input.chkBox").attr("checked","checked"); } }); if(isChecked($("#filesContainer"))) { $("#filesContainer").find("input.chkBoxAll").attr("checked","checked"); } else { $("#filesContainer").find("input.chkBoxAll").removeAttr("checked"); } } } function handleContextMenuEvents(action, el, pos, command) { $("#cluetip").hide(); if(command) { $(document).data("currentContext",{'action':action ,'elem':el}); command = decodeURIComponent(command); eval(command); clearContext(); } return false; } Array.prototype.has = function (value) { var i; for (var i = 0, loopCnt = this.length; i < loopCnt; i++) { if (this[i] === value) { return true; } } return false; }; if(!Array.prototype.indexOf) { Array.prototype.indexOf = function (value) { var i; for (var i = 0, loopCnt = this.length; i < loopCnt; i++) { if (this[i] === value) { return i; } } return -1; }; } // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function (from, to) { if(this.slice) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); } else { return this; } } function addToBasket(context) { var elem = false; var exist = false; if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } var filePath = ""; var items = []; if(elem) { var parentElem = $(elem); filePath = parentElem.find("a").attr("rel"); filePath = unescape(filePath.replace("//", "/")); } if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } var ItemsInTheBasket = $(document).data(o.BasketDataKey); var selectedFiles = {}; if(currentView() == "Thumbnail") { selectedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } else { selectedFiles = $("#filesContainer").find(".chkBox:visible:checked"); } if (selectedFiles.length > 0) { selectedFiles.each(function (index) { var file = ""; if(currentView() == "Thumbnail") { file = unescape($(this).find("a:first").attr("rel")); } else { file = unescape($(this).closest("tr").find("a:first").attr("rel")); } if (!ItemsInTheBasket.has(file)) { ItemsInTheBasket.push(file); items.push(file); } $(this).click(); }); } if (!ItemsInTheBasket.has(filePath) && filePath.length>0) { ItemsInTheBasket.push(decodeURIComponent(unescape(filePath))); items.push(filePath); } exist = ItemsInTheBasket.has(filePath); if(items.length>0) { $(document).data(o.BasketDataKey, ItemsInTheBasket); var msgToShow = "\"" + items.join("<br />") + "\" added to the basket"; rebuildBasket(msgToShow); if (currentView() != "Thumbnail") { var tbl = $("#filesListing").find("table"); toggleCheckBoxesAll(tbl, false); toggleMainCheckbox(tbl, false); } } else if(exist) { $.growlUI(getLocalizationKey("BasketFileAddedAlreadyText"), getLocalizationKey("BasketFileAddedAlreadyDetailsText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } else { $.growlUI(getLocalizationKey("BasketNothingSelectedToAddText"), getLocalizationKey("BasketNothingSelectedToAddDetailsText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } } function rebuildBasket(msg, isWarning) { if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } var ItemsInTheBasket = $(document).data(o.BasketDataKey); $("ul.filesSelectedInBasket").empty(); if (isWarning) { $("ul.filesSelectedInBasket").before("<div class='notificationMsg' style='line-height:19px;padding:5px;padding-left:19px;background-position:0px 7px;'>" + msg + "</div>"); var msgPanel = $("ul.filesSelectedInBasket").prev(); msgPanel.addClass("attention2"); setTimeout(function () { msgPanel.fadeOut(1000, function () { msgPanel.remove(); }) }, 5000); } for (var i = 0; i < ItemsInTheBasket.length; i++) { $("ul.filesSelectedInBasket").prepend('<li><label>' + ItemsInTheBasket[i] + '</label> <span>[<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BasketRemoveLinkText") +'</a>]</span></li>').find("a.error").unbind().click(function () { if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } var _ItemsInTheBasket = $(document).data(o.BasketDataKey); var key = $(this).closest("li").find("label").html(); if (_ItemsInTheBasket.indexOf(key) >= 0) { _ItemsInTheBasket.remove(_ItemsInTheBasket.indexOf(key)); $(document).data(o.BasketDataKey, _ItemsInTheBasket); showDownloadBasket(_ItemsInTheBasket); } var parElem = $(this).parent().parent(); parElem.fadeOut(500, function () { parElem.remove(); }); return true; }); } showDownloadBasket(ItemsInTheBasket); $("#submitActionBasket").find(".clearCompleted").unbind().click(function () { $(this).blur(); if (confirm("Are you sure you wish to clear all selected files in Basket?")) { $(document).data(o.BasketDataKey, new Array()); rebuildBasket(); } }); $("#submitActionBasket").find(".download").unbind().click(function () { $(this).blur(); if ($(this).hasClass("advanced")) { downloadBasket(null, "applet"); } else { downloadBasket(null, ""); } }); } function showDownloadBasket(ItemsInTheBasket) { if (!ItemsInTheBasket) { if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } ItemsInTheBasket = $(document).data(o.BasketDataKey); } $("ul.filesSelectedInBasket").parent().find(".notificationMsg,div.totalItemCount").remove(); if (ItemsInTheBasket) { if (!ItemsInTheBasket.length || ItemsInTheBasket.length == 0) { $("ul.filesSelectedInBasket").before("<div class='notificationMsg' style='line-height:19px;padding:5px;padding-left:19px;background-position:0px 7px;'>"+ getLocalizationKey("BasketNoFilesAvailableText") +"</div>"); $("#submitActionBasket").find(".download").hide(); } else { var BasketTotalItemText = getLocalizationKey("BasketTotalItemText"); BasketTotalItemText = BasketTotalItemText.replace("{0}",ItemsInTheBasket.length); $("#submitActionBasket").find(".download").show(); $("ul.filesSelectedInBasket").before("<div class='totalItemCount'>" + BasketTotalItemText + "</div>"); } } else { $("ul.filesSelectedInBasket").before("<div class='notificationMsg' style='line-height:19px;padding:5px;padding-left:19px;background-position:0px 7px;'>"+ getLocalizationKey("BasketNoFilesAvailableText") +"</div>"); $("#submitActionBasket").find(".download").hide(); } var $elem = $("div#filesBasket"); if (!$elem.is(":visible")) { $.blockUI({ message: $elem, showOverlay: false, centerY: false, css: { border: 'none', width: '460px', padding: '15px', color: '#000', 'border': '1px solid '+ getPopupColor(), 'background-color':getPopupColor(true), 'margin-left': '-510px', left: '100%', position: 'absolute', top: '5px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, '-webkit-box-shadow': '2px 5px 5px #888', '-moz-box-shadow': '2px 5px 5px #888' } }); $elem.parent().draggable({handle:"h2"}); } } function downloadBasket(elem, opt) { if (opt == "") { var stringToCopy = ""; if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } var ItemsInTheBasket = $(document).data(o.BasketDataKey); for (var i = 0; i < ItemsInTheBasket.length; i++) { var filePath = ItemsInTheBasket[i]; if (stringToCopy.length > 0) { stringToCopy += ":" + filePath; } else { stringToCopy = filePath; } }; submitAction({ '#command': "downloadAsZip", '#path': encodeURIComponent("/"), '#paths': encodeURIComponent(unescape(stringToCopy)), '#random': Math.random() }); } else { //advanced if (!$(document).data("appletLoaded")) $(document).data("appletLoaded", false); if (!$(document).data("appletLoaded")) { loadApplet(true, function () { handleAppletBrowse(true); }); } else { handleAppletBrowse(true); } } } function validateEmail(email) { //return new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$").test(email); //does not handle all email characters properly. extra dots, dashes, underscores, etc. return email.indexOf("@") > 0 && email.lastIndexOf(".") > email.indexOf("@"); } function validateShareForm() { var validated = true; $("#shareOptionDiv").find(".required").each(function () { var $elm = $(this); $elm.parent().find("span.requiredField").remove(); if ($elm.val().length == 0) { if (validated) { $elm[0].focus(); } $elm.after(" <span class='requiredField'>*</span>"); validated = false; } }); $("#shareOptionDiv").find(".email").not(".required").each(function () { var $elm = $(this); $elm.parent().find("span.requiredField").remove(); if ($elm.val().length > 0 && !validateEmail($elm.val())) { if (validated) { $elm[0].focus(); } $elm.after(" <span class='requiredField'>*</span>"); validated = false; } }); $("#shareOptionDiv").find(".validationFail").remove(); if (!validated) { $("table", "#shareOptionDiv").before("<div style='padding:5px;margin:5px 0px; color:red;' class='validationFail'>"+getLocalizationKey("FormValidationFailText")+"</div>"); } return validated; } function shareFile(context) { var el = false; if(context) { el = currentContext(); } $("#shareOptionDiv").html($("#shareOptionDiv").data("html")); applyShareCustomizations(); $("#txtTime", "#shareOptionDiv").setMask("29:59").keypress(function () { var currentMask = $(this).data('mask').mask; var newMask = $(this).val().match(/^2.*/) ? "23:59" : "29:59"; if (newMask != currentMask) { $(this).setMask(newMask); } }); $("#txtdays", "#shareOptionDiv").setMask("999").keyup(function () { var days = parseInt($(this).val()); if (days == NaN) days = 0; if (days > 0) { var myDate = new Date(); myDate.setDate(myDate.getDate() + days); var prettyDate = (myDate.getMonth() + 1) + '/' + myDate.getDate() + '/' + myDate.getFullYear(); $("#txtDate", "#shareOptionDiv").val(prettyDate); } }); var days = parseInt($("#txtdays", "#shareOptionDiv").val()); if (days == NaN) days = 0; var myDate = new Date(); myDate.setDate(myDate.getDate() + days); var prettyDate = (myDate.getMonth() + 1) + '/' + myDate.getDate() + '/' + myDate.getFullYear(); var _nowDate = new Date(); _nowDate.setDate(_nowDate.getDate() + 1); $("#txtDate", "#shareOptionDiv").val(prettyDate).datepicker({ dateFormat: 'mm/dd/yy', showOn: 'both', buttonImage: '/WebInterface/jQuery/images/calendar.png', buttonImageOnly: true, minDate: _nowDate }).change(function(){ var selectedDate = $(this).datepicker("getDate" ).getTime(); var nowDate = new Date(); nowDate.setDate(nowDate.getDate() - 1); nowDate = nowDate.getTime(); var diff = new Date(); diff.setTime(Math.abs(selectedDate - nowDate)); var timediff = diff.getTime(); var days = Math.floor(timediff / (1000 * 60 * 60 * 24)); $("#txtdays", "#shareOptionDiv").val(days); }); if ($("input#advanced", "#shareOptionDiv").is(":checked")) { $(".advanced", "#shareOptionDiv").show(); } else { $(".advanced", "#shareOptionDiv").hide(); } $("input#advanced", "#shareOptionDiv").click(function () { if ($(this).is(":checked")) { $(".advanced", "#shareOptionDiv").show(); } else { $(".advanced", "#shareOptionDiv").hide(); } }); var _fileName = ""; if (el) { _fileName = unescape($(el).find("a:first").attr("rel")); } var fileName = _fileName; var fileNameOnly = _fileName.substring(_fileName.lastIndexOf("/",_fileName.length-2)+1) + "\r\n"; var multipleFiles = false; var selectedFiles = []; if (currentView() != "Thumbnail") { selectedFiles = $("#filesContainer").find(".chkBox:visible:checked"); } else { selectedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } var itemList = []; if (selectedFiles.length > 0) { fileName = _fileName + "\r\n"; selectedFiles.each(function (index) { var file = ""; if (currentView() != "Thumbnail") { file = unescape($(this).closest("tr").find("a:first").attr("rel")); } else{ file = unescape($(this).find("a:first").attr("rel")); } if(file!=_fileName && !itemList.has(file)) { itemList.push(file); fileName += file; fileNameOnly += file.substring(file.lastIndexOf("/",file.length-2)+1) + "\r\n"; if (index + 1 < selectedFiles.length) { fileName += "\r\n"; } } }); if (selectedFiles.length > 1) { multipleFiles = true; } } var destinationPath = window.location.toString().replace(hashListener.getHash().toString(), ""); //destinationPath = (destinationPath + "#" + fileName + "/"); if(fileName.length==0) { $.growlUI("Nothing selected to share", "No items selected", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } performAction("shareOptionDiv"); $("#emailBody").html($("#emailBody").html().replace("#FILENAME#", fileNameOnly)); if (multipleFiles) { $("legend", "#shareOptionDiv").html("Sharing Files"); } else { if (fileName.length >= o.MaximumLengthAllowedForSharingPopupHeaderString) { $("legend", "#shareOptionDiv").html(fileName.substr(0, o.MaximumLengthAllowedForSharingPopupHeaderString) + "..."); } else{ $("legend", "#shareOptionDiv").html(fileName); } } $("#txtFilesToShare").html(fileName); $("#btnSubmitShareAction", "#shareOptionDiv").click(function () { performShareFormSubmit(destinationPath, fileName);return false; }); var shareThumbnail = $(document).data("shareThumbnail"); if(shareThumbnail) { if(shareThumbnail=="true") { $("#shareOptionDiv").find("input#attach").attr("checked","checked"); } else { $("#shareOptionDiv").find("input#attach").removeAttr("checked"); } } var shareAllowUploads = $(document).data("shareAllowUploads"); if(shareAllowUploads) { if(shareAllowUploads=="true") { $("#shareOptionDiv").find("input#fullaccess").attr("checked","checked"); $("#shareOptionDiv").find("input#advanced").attr("checked","checked").click(); $("#shareOptionDiv").find("input#advanced").attr("checked","checked"); } } var shareAdvanced = $(document).data("shareAdvanced"); if(shareAdvanced) { if(shareAdvanced=="true") { $("#shareOptionDiv").find("input#advanced").attr("checked","checked").click(); $("#shareOptionDiv").find("input#advanced").attr("checked","checked"); } else { $("#shareOptionDiv").find("input#advanced").removeAttr("checked").click(); $("#shareOptionDiv").find("input#advanced").removeAttr("checked"); } } var defaultShareMethod = $(document).data("defaultShareMethod"); if(defaultShareMethod) { defaultShareMethod = defaultShareMethod.toLowerCase(); if(defaultShareMethod=="copy") { $("#shareOptionDiv").find("input#chkCopy").attr("checked","checked"); } else if(defaultShareMethod=="reference") { $("#shareOptionDiv").find("input#chkReference").attr("checked","checked"); } else if(defaultShareMethod=="move") { $("#shareOptionDiv").find("input#chkMove").attr("checked","checked"); } } selectDeselectAllItems(false); } function performShareFormSubmit(destinationPath, fileName) { if (!validateShareForm()) { return false; } $("table", "#shareOptionDiv").hide() $("table", "#shareOptionDiv").after("<div class='wait' style='background-position: 0px -1px;margin:10px 0px;'>Please wait..</div>"); $("#shareOptionDiv").find(".closeButton").hide(500); var baseURL = document.location.href+""; if (baseURL.indexOf("#") >= 0) baseURL = baseURL.substring(0,baseURL.indexOf("#")); var obj = { command: "publish", allowUploads: $("input#fullaccess", "#shareOptionDiv").is(":checked"), attach: $("input#attach", "#shareOptionDiv").is(":checked"), baseUrl: encodeURIComponent(baseURL), emailBcc: $("input#emailBcc", "#shareOptionDiv").val(), emailBody: encodeURIComponent($("textarea#emailBody", "#shareOptionDiv").val()), emailCc: $("input#emailCc", "#shareOptionDiv").val(), emailFrom: $("input#emailFrom", "#shareOptionDiv").val(), emailSubject: encodeURIComponent($("input#emailSubject", "#shareOptionDiv").val()), emailTo: $("input#emailTo", "#shareOptionDiv").val(), expire: $("input#txtDate", "#shareOptionDiv").val() + " " + $("input#txtTime", "#shareOptionDiv").val(), paths: encodeURIComponent(fileName), publishType: $("input:checked", ".publishType").val(), sendEmail: $("input#sendEmail", "#shareOptionDiv").is(":checked"), w: 4 }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = LoadXMLString(response); var username = '', password = '', message = '', url = ''; try { var msgs = responseText.getElementsByTagName("commandResult"); for (var x = 0; x < msgs.length; x++) { username += IE(msgs[x].getElementsByTagName("username")[0]).textContent; password += IE(msgs[x].getElementsByTagName("password")[0]).textContent; message += IE(msgs[x].getElementsByTagName("message")[0]).textContent; url += unescape(IE(msgs[x].getElementsByTagName("url")[0]).textContent); } } catch (ex) { } $("div.wait", "#shareOptionDiv").remove(); $("#shareOptionDiv").parent().find(".closeButton").show(500); if (message.indexOf("ERROR:") == 0) { $("table", "#shareOptionDiv").after("<div style='margin:10px 0px;line-height:25px;'>" + message + "<br/><br/><input style='float:right;margin-bottom:10px;padding:2px 20px;' type=\"submit\" value=\"OK\" onclick=\"$.unblockUI(); return false;\" />" + "</div>"); } else { $("table", "#shareOptionDiv").after("<div style='margin:10px 0px;line-height:25px;'>" + message + "<br/>" + getLocalizationKey("ShareActionCompleteUsernameText") + username + "<br/>" + getLocalizationKey("ShareActionCompletePasswordText") + password + "<br/> " + getLocalizationKey("ShareActionCompleteLinkText") + " <a href='" + url + "'>" + url + "</a><br/><br/><input style='float:right;margin-bottom:10px;padding:2px 20px;' type=\"submit\" value=\""+getLocalizationKey("ShareActionCompleteOkButtonText")+"\" onclick=\"$.unblockUI(); return false;\" />" + "</div>"); } }, error: function () { $.growlUI("Problem while sharing", "There was a problem while sharing a file. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); } function copypath(context) { var el = false; if(context) { el = currentContext(); } if(el) { var $curElem = $(el); var fileName = $curElem.find("a:first").attr("rel"); var destinationPath = location.protocol + "//" + location.host; if($curElem.hasClass("fileTR") || $curElem.hasClass("fileThumb")) { destinationPath = (destinationPath + fileName); } else { destinationPath = (destinationPath + "/#" + fileName); } performAction("copyDirectLinkDiv"); $("#txtDirectLink").val(destinationPath)[0].select(); $("#txtDirectLink")[0].focus(); } else { $.growlUI("Nothing selected", "Right click on item and click on copy direct link", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } } function updateKeywords(context) { function updateKeywordAlert(msg, color, timeout) { $popup.find(".errorNote").remove(); timeout = timeout || 2000; var curElem = $("textarea",$("#keywordsDiv")); curElem.after("<span class='errorNote' style='cursor:pointer;float:left;margin-left: 7px;font-size: 11px;line-height: 25px;color:"+color+";'>"+msg+"</span>"); curElem.next().click(function(){ $(this).fadeOut(1000, function(){$(this).remove()}); }); } var _fileName = ""; var elem = false; if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } var checkedFiles = {}; if(currentView() == "Thumbnail") { checkedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } else { checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); } if (checkedFiles.length == 0 && !elem) { $.growlUI("Nothing selected", "Right click on item and click on update keywords", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } var stringToCopy = _fileName; var totalFiles = elem.length; checkedFiles.each(function () { var parentElem = $(this); if(currentView() != "Thumbnail") { parentElem = $(this).closest("tr"); } var filePath = unescape(parentElem.find("a").attr("rel")); filePath = unescape(filePath.replace("//", "/")); if(_fileName != filePath) { if (stringToCopy.length > 0) { stringToCopy += "\r\n"; } stringToCopy += (filePath); totalFiles += 1; } }); var $curElem = checkedFiles; if(context) { $curElem = elem; } $("#KeywordsWindowHeaderText").find("span").remove(); $("#KeywordsWindowHeaderText").append("<span> : Updating total : "+totalFiles+" item(s)</span>"); var keywords = $($curElem[0]).attr("keywords"); performAction("keywordsDiv"); var $popup = $("#keywordsDiv"); $("#txtKeywords",$popup).val(keywords)[0].focus(); $popup.find(".errorNote").remove(); $("a.update",$popup).unbind().click(function(){ $(this).blur(); var newKeywords = $("#txtKeywords",$popup).val(); var obj = { command: "editKeywords", keywords: encodeURIComponent(unescape(newKeywords)), names: encodeURIComponent(unescape(stringToCopy)), random: Math.random() }; $popup.find(".buttonPanel").addClass("wait"); $popup.find(".errorNote").remove(); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); $popup.find(".buttonPanel").removeClass("wait"); responseText = $.trim(responseText); if(responseText.indexOf("Keywords Edited.")>=0) { $.unblockUI(); if (currentView() != "Thumbnail") { checkedFiles.each(function () { $(this).attr("keywords",newKeywords); $(this).attr("keywords",newKeywords); var $curElem = $(this).closest("TR"); $curElem.find(".columnKeywords").attr("title",newKeywords); if (newKeywords.length >= o.MaximumLengthAllowedForKeywordsString) { newKeywords = newKeywords.substr( 0, o.MaximumLengthAllowedForKeywordsString) + "..."; } $curElem.find(".columnKeywords").html(newKeywords); $($curElem).animate({ "background-color": "#FFFFCC" }, 500, function () { $($curElem).animate({ "background-color": "#FFFFFF" }, 500); }); }); if(context) { $(elem).attr("keywords",newKeywords); $(elem).attr("keywords",newKeywords); var $curElem = $(elem).closest("TR"); $curElem.find(".columnKeywords").attr("title",newKeywords); if (newKeywords.length >= o.MaximumLengthAllowedForKeywordsString) { newKeywords = newKeywords.substr( 0, o.MaximumLengthAllowedForKeywordsString) + "..."; } $curElem.find(".columnKeywords").html(newKeywords); $($curElem).animate({ "background-color": "#FFFFCC" }, 500, function () { $($curElem).animate({ "background-color": "#FFFFFF" }, 500); }); } } } else { updateKeywordAlert("(Error : " + responseText + ")", "red"); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { updateKeywordAlert("(Error : " + errorThrown + ")", "red"); $popup.find(".buttonPanel").removeClass("wait"); } }); }); $("a.cancel",$popup).unbind().click(function(){ $.unblockUI(); }); } function submitAction(opt) { var uniqueIFrameID = "i"+Math.random(); var uniqueIFrame = $("<iframe id=\""+uniqueIFrameID+"\" name=\""+uniqueIFrameID+"\" src=\"javascript:false;\" style=\"display:none;\"></iframe>"); $("body").append(uniqueIFrame); $("#crushftp_action").remove(); $("body").append('<form id="crushftp_action" style=\"display:none;\" name="crushftp_action" enctype="multipart/form-data" method="post">' + '<input type="text" id="command" name="command" value="">' + '<input type="text" id="path" name="path" value="">' + '<input type="text" id="paths" name="paths" value="">' + '<input type="text" id="random" name="random" value="">' + '</form>'); var formToSubmit = $("#crushftp_action"); formToSubmit.attr("action", o.downloadURL).attr("target", uniqueIFrameID); formToSubmit.find("input").val(""); for (var key in opt) { if (opt.hasOwnProperty(key)) { formToSubmit.find(key).attr("value", opt[key]); } } formToSubmit.submit(); } window.downloadItems = function(context, el) { el = el || false; if($(document).data("slideShowOnly")) { var fileName = encodeURIComponent(unescape(el)); submitAction({ '#command': "download", '#path': fileName, '#random': Math.random() }); } else { if(context) { el = currentContext(); } var count = 0; var stringToCopy = ""; if(el) { var $curElem = $(el); stringToCopy = $curElem.find("a:first").attr("rel"); count++; } var checkedFiles = {}; if(currentView() == "Thumbnail") { checkedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } else { checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); } checkedFiles.each(function () { var parentElem = $(this); if(currentView() != "Thumbnail") { parentElem = $(this).closest("tr"); } var filePath = parentElem.find("a").attr("rel"); filePath = filePath.replace("//", "/"); stringToCopy += ":" + filePath; count++; }); if (count > 1) //multiple selected, do zip { downloadAsZip(el); return; } else { if(currentView() == "Thumbnail") { if(!el) { el = $(checkedFiles[0]); } if(el.hasClass("directoryThumb")) { downloadAsZip(el, true); return; } } else { if(!el) { el = $(checkedFiles[0]); if(el) { el = el.closest("td"); } } if(el.hasClass("directory")) { downloadAsZip(el, true); return; } } } submitAction({ '#command': "download", '#path': encodeURIComponent(unescape(stringToCopy)), '#random': Math.random() }); } } function performRenameAction(context) { var el = false; if(context) { el = currentContext(); } if (currentView() != "Thumbnail") { if (!el) { var checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); if(checkedFiles && checkedFiles.length >0) { el = $(checkedFiles[0]).closest("tr").find(".columnName"); } } if(!el || el.length==0) { $.growlUI("Nothing selected", "Nothing selected to rename", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } var $curElem = $(el); var renameTemplate = "<div class='renamePanel'><input type='text' class='renameField' /><div class='saveButton'>"+ getLocalizationKey("RenamePanelSaveLinkText") +"</div><div class='cancelButton'>"+ getLocalizationKey("RenamePanelCancelLinkText") +"</div></div>"; $curElem.disableContextMenu(); $curElem.find("span,a").hide(); $curElem.append(renameTemplate); $curElem.find(".renameField").val($curElem.find("a").text())[0].select(); $curElem.find(".renameField")[0].focus(); $curElem.removeAttr("title"); $curElem.find(".cancelButton").click(function () { $curElem.find("div.renamePanel").remove(); $curElem.find("span,a").show(); $curElem.enableContextMenu(); bindContextMenu($curElem); }); $curElem.find(".renameField").keyup(function (evt) { var evt = (evt) ? evt : ((event) ? event : null); if (evt.keyCode == 13) { $curElem.find(".saveButton").click(); return false; } else if (evt.keyCode == 27) { $curElem.find(".cancelButton").click(); return false; } }); $curElem.find(".saveButton").click(function () { var newName = $curElem.find(".renameField").val(); var oldName = $curElem.find("a").text(); var pathName = $(el).parent().attr("rel"); var obj = { command: "rename", path: encodeURIComponent(unescape(pathName)), name1: encodeURIComponent(unescape(oldName)), name2: encodeURIComponent(unescape(newName)), random: Math.random() }; $curElem.addClass("wait"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); var loadPreview = false; if (responseText.length > 0) { $.growlUI("Problem while renaming", "There was a problem while renaming. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { if ($curElem.hasClass("directory")) { var link = $curElem.find("a"); link.text(newName).attr("href", $curElem.closest("tr").attr("rel") + newName + "/").attr("rel", $curElem.closest("tr").attr("rel") + newName + "/").prev().attr("rel", $curElem.closest("tr").attr("rel") + newName + "/"); $curElem.find("div.renamePanel").remove(); $curElem.find("span,a").show(); } else if ($curElem.hasClass("fileItem") || $curElem.hasClass("fileTR")) { var FileExtension = getFileExtension($curElem.find("a").text()); var link = $curElem.find("a").text(newName); link.attr("href", $curElem.closest("tr").attr("rel") + newName); link.attr("rel", link.attr("href")); FileExtension = getFileExtension(newName); $curElem.removeAttr("title"); $curElem.find("div.renamePanel").remove(); $curElem.find("span,a").show(); if(!$curElem.closest("tr").data("menuOn")) { $curElem.closest("tr").removeClass("rowHoverFixed") .removeClass("rowHover"); } loadPreview = true; } $curElem.enableContextMenu(); $($curElem).closest("TR").animate({ "background-color": "#FFFFCC" }, 500, function () { $($curElem).closest("TR").animate({ "background-color": "#FFFFFF" }, 500, function () { if (loadPreview) { loadIconPreview( 1, true, $($curElem)); } bindContextMenu($curElem); }); }); } }, complete: function () { $curElem.removeClass("wait"); }, error: function () { $.growlUI("Problem while renaming", "There was a problem while renaming. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); }); } else { if(!el) { $.growlUI("Nothing selected", "Nothing selected to rename", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } if ($("#thumbRenamePanel").length == 0) { var renameTemplate = "<div class='renamePanel'><h2>"+ getLocalizationKey("RenameWindowHeaderText") +"</h2><input type='text' class='renameField' /><div class='saveButton'>"+ getLocalizationKey("RenamePanelSaveLinkText") +"</div> <div class='cancelButton'>"+ getLocalizationKey("RenamePanelCancelLinkText") +"</div></div>"; $("body").append("<div id='thumbRenamePanel'>" + renameTemplate + "</div>"); $("#thumbRenamePanel").hide(); } var $renameBox = $('#thumbRenamePanel'); var toTop = (window.screen.availHeight / 2) - ($renameBox.height() * 2); $.blockUI({ message: $renameBox, css: { padding: '10px 10px 20px 30px', 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor(), '-webkit-border-radius': '10px', '-moz-border-radius': '10px', color: '#000', opacity: 0.9, top: toTop + 'px', left: '40%', width: '305px' } }); $renameBox.find(".renameField").val($(el).find("div.imgTitle").find("a").text()).focus(); $renameBox.find(".cancelButton").unbind().click( function () { $.unblockUI(); $("#thumbRenamePanel").remove(); $renameBox.find("input").removeClass("wait"); }); $renameBox.find(".renameField").unbind().keyup( function (evt) { var evt = (evt) ? evt : ((event) ? event : null); if (evt.keyCode == 13) { $renameBox.find(".saveButton").click(); return false; } else if (evt.keyCode == 27) { $renameBox.find(".cancelButton").click(); return false; } }); $renameBox.find(".saveButton").unbind().click( function () { var newName = $renameBox.find(".renameField").val(); var oldName = $(el).find("div.imgTitle").find("a").text(); var pathName = $(el).find("div.imgTitle").find("a").attr("rel"); var obj = { command: "rename", path: encodeURIComponent(unescape(pathName)), name1: encodeURIComponent(unescape(oldName)), name2: encodeURIComponent(unescape(newName)), random: Math.random() }; $renameBox.find("input").addClass("wait"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { $.growlUI("Problem while renaming", "There was a problem while renaming. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { var link = $(el).find("div.imgTitle").find("a"); if($(el).hasClass("directoryThumb")) { link.text(newName).attr("href", link.attr("rel") + newName + "/"); } else { link.text(newName).attr("href", link.attr("rel") + newName); } setTitleText(link); var imglink = $(el).find("a.imgLink"); if($(el).hasClass("directoryThumb")) { imglink.attr("rel", link.attr("rel") + newName + "/"); } else { imglink.attr("rel", link.attr("rel") + newName); } imglink.attr("href", link.attr("href")); $renameBox.find(".cancelButton").click(); $(el).removeAttr("title"); $(el).find(".vtip").removeAttr("title"); $($(el)).animate({ "background-color": "#FFFFCC" }, 500, function () { $($(el)).animate({ "background-color": "#FFFFFF" }, 500, function () { loadIconPreview(1, true, $(el)); bindContextMenu($(el)); }); }); } }, complete: function () { $renameBox.find("input").removeClass("wait"); }, error: function () { $.growlUI("Problem while renaming", "There was a problem while renaming. Please retry.", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); }); } } function getActionResponseText(msg) { var responseText = ''; try { var msgs = msg.getElementsByTagName("commandResult"); for (var x = 0; x < msgs.length; x++) { responseText += IE(msgs[x].getElementsByTagName("response")[0]).textContent; } } catch (ex) {} return responseText; } function getDataOfElemFromPrivs(currentPrivs,val) { var comment = false; if(currentPrivs && val && val.length>0) { val = "(" + val; var commentIndex = currentPrivs.indexOf(val); if(commentIndex>=0) { comment = currentPrivs.substring(commentIndex, currentPrivs.length); comment = comment.substring(val.length,comment.indexOf(")")); } } return comment; } function LoadXMLString(xmlString) { return xmlString; } //does nothing now function bindBackToTop() { $(".backToTop").click(function () { if(!o.buggyBrowser) { $('html,body').animate({ scrollTop: 0 }, 500, false); } }); } function renderButtons() { if($(document).data("uploadOnly")) { return; } $("div.mainNavigation").find("a[href!='javascript:doLogout();']").parent().remove(); var currentPrivs = $(document).data("folderPrivs"); var comment = getDataOfElemFromPrivs(currentPrivs,"comment"); if(comment) { comment = unescape(comment); $("#comments").empty().append(comment).show(); } else { $("#comments").hide(); } var menuList = $(document).data("menuList"); var mainNav = $("#mainNavigation").hide(); if(menuList) { var mainMenu = $(".mainNavigation").find("ul"); mainMenu.empty(); for (var i = 0; i < menuList.length; i++) { var text = menuList[i].name.toString(); text = text.substring(text.indexOf(":") + 1, text.length); if (!currentPrivs || !menuList[i].requiredPriv || currentPrivs.indexOf(menuList[i].requiredPriv) >= 0) mainMenu.append("<li><a href=\"" + menuList[i].text + "\">" + text + "</a></li>"); mainNav.hide(); } } highlightPasteButton(); if(window.slideshowOnly) { $("div.mainNavigation").find("a[href!='javascript:doLogout();']").parent().remove(); } var menuListContextMenu = $(document).data("menuListContextMenu"); if(menuListContextMenu) { var mainMenu = $("#myMenu"); mainMenu.empty(); for (var i = 0; i < menuListContextMenu.length; i++) { var text = menuListContextMenu[i].name.toString(); text = text.substring(text.indexOf(":") + 1, text.length); var command = menuListContextMenu[i].text; if(command.indexOf("()")>=0) { command = command.replace(")","true)"); } else { command = command.replace(")",",true)"); } command = encodeURIComponent(command); mainMenu.append('<li class="'+text.toLowerCase().replace(/ /g,"")+'"><a href="javascript:void(0);" command="'+command+'">' + text + '</a></li>'); } } if ($(document).data("username") == "anonymous") { $("ul.topnav,#myMenu").find("a:contains('Logout')").parent().remove(); } else { $("ul.topnav,#myMenu").find("a:contains('Login')").parent().remove(); } applyCustomizations(); $("#browserFileUpload").find("input#chkUploadResume").bind("click",function(){ if($(this).is(":checked")) { $("ul.filesSelected").find("li.appletUploadItem").each(function(){ if($(this).find("a.errorOverwrite").length>0) { $(this).find("a.errorOverwrite").click(); $(this).find("span.popupNote").remove(); } }); } }); mainNav.show(); } window.clearContext = function() { $(document).removeData("currentContext"); } window.currentContext = function() { var curElem = $(document).data("currentContext"); clearContext(); if(curElem) { return curElem.elem; } else { return false; } } window.initManageShares = function(elem) { var manageSharePanel = $('#manageShareTable'); $(".cancelButton",manageSharePanel.parent()).hide(); function getTextValue(item, text) { if(item && item.length>0 && item[0] && item[0].text) { return item[0].text; } else { return text || ""; } } function bindSorting() { var th = manageSharePanel.find('th'), inverse = true; manageSharePanel.find(".thTO").addClass("headerSortUp"); th.click(function () { if ($(this).hasClass("thSelectBox")||$(this).hasClass("thDelete")) { return; } $(th).parent().find(".headerSortDown").removeClass("headerSortDown"); $(th).parent().find(".headerSortUp").removeClass("headerSortUp"); var header = $(this), index = header.index(); header.closest('table').find('td').filter( function () { return $(this).index() === index; }).sort(function (a, b) { if (header.hasClass("thCreated")) { a = $(a).attr("createdMillis").toLowerCase(); b = $(b).attr("createdMillis").toLowerCase(); } else if (header.hasClass("thExpires")) { a = $(a).attr("expireMillis").toLowerCase(); b = $(b).attr("expireMillis").toLowerCase(); } else { a = $(a).text().toLowerCase(); b = $(b).text().toLowerCase(); } try { return (isNaN(a) || isNaN(b) ? a > b : +a > +b) ? inverse ? -1 : 1 : inverse ? 1 : -1; } catch (ex) { return 1; } }, function () { return this.parentNode; }); inverse = !inverse; if (inverse) { $(this).removeClass("headerSortDown").addClass("headerSortUp"); } else { $(this).removeClass("headerSortUp").addClass("headerSortDown"); } }); } function attachCheckboxEvents() { $("input[type='checkbox']",manageSharePanel).unbind().click(function(event){ if($(this).is(".chkBoxAllManageShares")) { if($(this).is(":checked")) { manageSharePanel.find("input[type='checkbox']").attr("checked","checked"); } else { manageSharePanel.find("input[type='checkbox']").removeAttr("checked"); } } else { var allChecked = true; $("input[type='checkbox']",manageSharePanel).each(function(){ if(!$(this).is(":checked")) { if(!$(this).is(".chkBoxAllManageShares")) { allChecked = false; } } }); if(allChecked) { $("input.chkBoxAllManageShares",manageSharePanel).attr("checked","checked"); } else { $("input.chkBoxAllManageShares",manageSharePanel).removeAttr("checked"); } } }); $("input[type='checkbox']",manageSharePanel).removeAttr("checked"); } function manageShareAlert(msg, color, timeout) { timeout = timeout || 1000; var curElem = $("#topCancelButton",manageSharePanel.parent()); curElem.after("<span style='float:left;margin-left: 7px;font-size: 11px;line-height: 25px;color:"+color+";'>"+msg+"</span>"); setTimeout(function(){ curElem.next().fadeOut(1000, function(){curElem.next().remove()})},timeout); } function replace_str(master_str,find_str,replace_str) { var i = 0; var result = ""; while (master_str.indexOf(find_str,i) != -1) { result += master_str.substring(i,master_str.indexOf(find_str,i)) + replace_str; i = (master_str.indexOf(find_str,i) + find_str.length); } result += master_str.substring(i,master_str.length); return result; } $(".cancelButton",manageSharePanel.parent()).hide(); elem.find("tbody").empty(); elem.find("tbody").append("<tr><td style='padding:18px;background-position:0px 17px;' colspan='8' class='wait'>Loading...</td></tr> "); var obj = { command: "getTempAccounts", random: Math.random() }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); elem.find("tbody").empty(); elem.find("tbody").append("<tr><td colspan='8'>Nothing to display</td></tr> "); $(".cancelButton",manageSharePanel.parent()).hide(); }, success: function (msg) { var items = $.xml2json(msg, true); if(items["listingInfo_subitem"]) { var manageItems = items["listingInfo_subitem"]; elem.find("tbody").empty(); for(var i=0;i<manageItems.length;i++) { var curItem = manageItems[i]; var itemHTML = "<tr class='shareItem' tempUsername='"+getTextValue(curItem.username,"")+"'>" +"<td class=\"columnSelect\"><input class=\"chkBox\" type=\"checkbox\" /></td>" +"<td><div class='wordwrap' style='width:150px !important;text-align:left;'>"+getTextValue(curItem.emailTo," - ")+"</div></td>" +"<td><div class='wordwrap' style='width:150px !important;text-align:left;'>"+getTextValue(curItem.emailCc," - ")+"</div></td>" +"<td expireMillis='"+getTextValue(curItem.expireMillis,0)+"'>"+getTextValue(curItem.created," - ")+"</td>" +"<td createdMillis='"+getTextValue(curItem.createdMillis,0)+"'>"+getTextValue(curItem.expire," - ")+"</td>" +"<td><div class='wordwrap' style='text-align:left;' class='manageSharePaths'>"+unescape(getTextValue(curItem.paths,""))+"</div></td>" +"<td>"+getTextValue(curItem.downloads," - ")+"</td>" +"<td style='border-right:0px;' class=\"columnDelete\"><a href='javascript:void(0);' class='cancelButton' style='margin:0px' tempUsername='"+getTextValue(curItem.username,"")+"'>Delete</a></td>" +"</tr>" +"<tr class='itemDetails' style='display:none;'>" +"<td colspan='8' style='padding:0px; border:0px !important;'>" + "<a style='float:right;margin:3px;' href='javascript:void(0);'>Hide</a>" +"<table border='0' cellpadding='2' cellspacing='2' width='100%'>" +"<tr class='shareItemDetails'>" +"<td style='padding:5px !important; border:0px !important;width:50%;'>" //+ "<div class='shareItemDetails'>" //+ " <div class='pane11'>" //+ " <div><label>Emailed?</label><span>"+(getTextValue(curItem.sendEmail,""))+"</span></div>" + " <div><label>Link:</label><span>"+(getTextValue(curItem.web_link,""))+"</span></div>" + " <div><label>From:</label><span>"+(getTextValue(curItem.emailFrom,""))+"</span></div>" + " <div><label>To:</label><span class='wordwrap' style='width:250px !important;text-align:left;'>"+(getTextValue(curItem.emailTo,""))+"</span></div>" + " <div><label>CC:</label><span class='wordwrap' style='width:250px !important;text-align:left;'>"+(getTextValue(curItem.emailCc,""))+"</span></div>" + " <div><label>BCC:</label><span>"+(getTextValue(curItem.emailBcc,""))+"</span></div>" + " <div><label>Subject:</label><span>"+unescape(getTextValue(curItem.emailSubject,""))+"</span></div>" + " <div class='wordwrap'><label>Body:</label><span><br/>"+unescape(getTextValue(curItem.emailBody,"").replace(/%0A/g,"<br/>").replace(/%3E/g,">").replace(/%3C/g,"<"))+"</span></div>" + " </td>" + " <td style='padding:5px !important; border:0px;border-left:1px solid #eee !important;width:50%;'>" + " <div><label>Share Type:</label><span>"+(getTextValue(curItem.publishType,""))+"</span></div>" //+ " <div><label>Downloads:</label><span>"+(getTextValue(curItem.downloads,""))+"</span></div>" //+ " <div><label>Created:</label><span>"+(getTextValue(curItem.created,""))+"</span></div>" //+ " <div><label>Expire:</label><span>"+(getTextValue(curItem.expire,""))+"</span></div>" + " <div><label>Username:</label><span>"+(getTextValue(curItem.username,""))+"</span></div>" + " <div><label>Password:</label><span>"+(getTextValue(curItem.password,""))+"</span></div>" + " <div><label>Attached in Email?:</label><span>"+(getTextValue(curItem.attach,""))+"</span></div>" + " <div><label>Upload Allowed?</label><span>"+(getTextValue(curItem.allowUploads,""))+"</span></div>" + " <div class='wordwrap'><label>Paths:</label><span><br/>"+unescape(getTextValue(curItem.paths,""))+"</span></div>" + " </div>" + "</td>" +"</tr>" +"</table>" +"</td>" +"</tr>"; elem.find("tbody.mainTbl").append(itemHTML); } if(manageItems.length>0) { $(".cancelButton",manageSharePanel.parent()).show(); } bindSorting(); attachCheckboxEvents(); } else { elem.find("tbody").empty(); elem.find("tbody").append("<tr><td colspan='8' style='text-align:center;'>Nothing to display</td></tr> "); $(".cancelButton",manageSharePanel.parent()).hide(); } elem.find(".shareItemDetails div").unbind().hover(function () { $(this).addClass("highlight"); }, function () { $(this).removeClass("highlight"); }); elem.find("tr.shareItem").unbind().hover(function () { if(!$(this).is(".rowHoverFixed")) { $(this).addClass("rowHover2"); } }, function () { $(this).removeClass("rowHover2"); }); elem.find("tr.itemDetails").find("a").unbind().click( function() { $(this).closest("tr").hide().prev().removeClass("rowHoverFixed"); } ); elem.find("tr.shareItem").click(function () { if(!$(this).is(".rowHoverFixed")) { elem.find("tr.rowHoverFixed").removeClass("rowHoverFixed"); $(this).addClass("rowHoverFixed").removeClass("rowHover2"); elem.find("tr.itemDetails:visible").hide(); moveToElement($(this)); $(this).next().show(); } else { $(this).next().hide().prev().removeClass("rowHoverFixed"); } }); $(".refreshBtn",manageSharePanel.parent()).unbind().click(function(){ $(this).blur(); initManageShares(elem); }); $(".cancelButton",manageSharePanel.parent()).unbind().click(function(event){ $(this).blur(); var curElem = $(this); var userName = ""; var totalItems = 0; if(curElem.attr("tempUsername") && $(this).attr("tempUsername").length>0) { userName = curElem.attr("tempUsername"); totalItems += 1; } else { elem.find("tr").each(function(){ if($(this).find("input[type='checkbox']").is(":checked") && $(this).attr("tempUsername") && $(this).attr("tempUsername").length>0) { userName += $(this).attr("tempUsername") + ";"; totalItems += 1; } }); } if(totalItems>0) { if(confirm("Are you sure you wish to delete selected "+totalItems+" account(s) ?")) { /*command deleteTempAccount tempUsername m8GF*/ var obj = { command: "deleteTempAccount", tempUsername: userName, random: Math.random() }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { manageShareAlert("(Error : " + errorThrown + ")", "red"); }, success: function (msg) { var items = $.xml2json(msg, true); if(items["tempUsername"]&&items["tempUsername"].length>0) { var curItem = items["tempUsername"][0]; manageShareAlert("(User : " + curItem.text + " deleted)", "green",3000); } initManageShares(elem); } }); } } else { manageShareAlert("(Nothing selected to delete)", "red"); } return false; }); } } ); } function userLoginStatusCheckThread() { if(!$(document).data("loginStatusThreadRunning") && !window.loginStatusThreadInterval) { window.loginStatusThreadInterval = setInterval( function() { bindUserName(false,function(response, username){ if(response=="failure") { window.location = window.location; } }); },600000); } } function bindUserName(isInit,callBack) { /* Data to POST to receive file listing */ var obj = { command: "getUsername", random: Math.random() }; /* Make a call and receive list */ $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); }, success: function (msg) { var responseText = LoadXMLString(msg); var username = "anonymous"; try{ var response = msg.getElementsByTagName("response"); response = IE(response[0]).textContent; if (response == "success") { username = msg.getElementsByTagName("username"); username = IE(username[0]).textContent; } if (username == "anonymous" || username == "") { $(document).data("username","anonymous"); } else { $(document).data("username",username); } } catch(ex){ if(callBack) { callBack("failure",username); return false; } } if(isInit) { renderButtons(); } else { if(callBack) { callBack(response,username); } } } }); } function generateRandomPassword(length){ length = length || 8; var randomId = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < length; i++ ) randomId += possible.charAt(Math.floor(Math.random() * possible.length)); return randomId; } function bindUserCustomizationInfo() { var mainNav = $("#mainNavigation").hide(); var obj = { command: "getUserInfo", path: encodeURIComponent(hashListener.getHash().toString().replace("#", "")), random: Math.random() }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); }, success: function (msg) { var responseText = LoadXMLString(msg); var buttons = msg.getElementsByTagName("buttons_subitem"); var user_priv_options = IE(msg.getElementsByTagName("user_priv_options")[0]).textContent; $(document).data("user_priv_options", user_priv_options); if(user_priv_options.indexOf("(SITE_PASS)")>=0) { $("#changepasswordPanel").show(); $("#new_password1").val(""); $("#changepasswordPanel").find("#btnGeneratePassword").unbind().click(function(){ $("#generated_password").val(generateRandomPassword(8)); $("#passwordGeneratePanel").show(); }); $("#passwordGeneratePanel").hide(); $("#changepasswordPanel").find("a.usePassword").unbind().click(function(){ $("#new_password1").val($("#generated_password").val()); $("#new_password2").focus(); }); $("#changepasswordPanel").find("a.cancelPassword").unbind().click(function(){ $("#generated_password").val(""); $("#passwordGeneratePanel").hide(); }); } else { $("#changepasswordPanel").hide(); } var menuListBar = []; var menuListContextMenu = []; for (var x = 0; x < buttons.length; x++) { var opt = {}; opt.name = IE(buttons[x].getElementsByTagName("key")[0]).textContent; opt.text = IE(buttons[x].getElementsByTagName("value")[0]).textContent; opt.requiredPriv = IE(buttons[x].getElementsByTagName("requiredPriv")[0]).textContent; if(IE(buttons[x].getElementsByTagName("forMenu")[0]).textContent=="true") { menuListBar.push(opt); } if(IE(buttons[x].getElementsByTagName("forContextMenu")[0]).textContent=="true") { menuListContextMenu.push(opt); } } $(document).data("menuList", menuListBar); $(document).data("menuListContextMenu", menuListContextMenu); var customizationItems = msg.getElementsByTagName("customizations_subitem"); var customizations = []; for (var x = 0; x < customizationItems.length; x++) { var opt = {}; opt.key = IE(customizationItems[x].getElementsByTagName("key")[0]).textContent; opt.value = "";try{opt.value=IE(customizationItems[x].getElementsByTagName("value")[0]).textContent;}catch(e){}//value may not exist. customizations.push(opt); } $(document).data("customizations", customizations); applyCustomizations(); if(!$(document).data("slideShowOnly") && !$(document).data("uploadOnly")) { displayWelcomeNote(); if (currentView() == "Thumbnail") showTree($("#filesContainerDiv"), encodeURIComponent(o.root), false); else showTree($("#filesContainer"), encodeURIComponent(o.root), false); } } }); } function serializeForm(form) { if (!form || form.nodeName !== "FORM") { return ""; } var i, j, q = []; for (i = form.elements.length - 1; i >= 0; i = i - 1) { if (form.elements[i].name === "") { continue; } switch (form.elements[i].nodeName.toUpperCase()) { case 'INPUT': switch (form.elements[i].type.toLowerCase()) { case 'text': case 'hidden': case 'password': case 'button': case 'reset': case 'submit': q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); break; case 'checkbox': case 'radio': if (form.elements[i].checked && form.elements[i].value) { q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); } break; case 'file': break; } break; case 'TEXTAREA': q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); break; case 'SELECT': switch (form.elements[i].type) { case 'select-one': q.push(form.elements[i].name + "=" + encodeURIComponent( $("#"+form.elements[i].id).val() )); break; case 'select-multiple': for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) { if (form.elements[i].options[j].selected) { q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value)); } } break; } break; case 'BUTTON': switch (form.elements[i].type) { case 'reset': case 'submit': case 'button': q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); break; } break; } } return q.join("&"); } function displayWelcomeNote() { var $elem = $("div#welcomeFormPanel"); var userName = $(document).data("username"); var buttonText = getLocalizationKey("WelcomeFormOkButtonText"); getCustomForm("messageForm",function (data, hasForm, formName, showAlways) { if(hasForm) { if(!showAlways) { var formShown = $.cookie(o.CookieWelcomeNote + "_" + userName + "_" + formName); if(formShown && formShown.length>0) return false; } $("div.welcomeForm","#welcomeFormPanel").html("<form id='frmWelcome'>" + data + "</form>").find("table").css("text-align","left"); $("button#resetPasteForm","#welcomeFormPanel").unbind().click(function (event) { $("#welcomeFormPanel").clearForm(); event.stopPropagation(); event.preventDefault(); }); function displayError(msg) { var form = $("table.customForm","#welcomeFormPanel"); if (form.prev().hasClass("attention")) { form.prev().remove(); } form.before("<div class='attention'>"+msg+"</div>"); form.prev().css("float", "none"); } $("button.submitForm","#welcomeFormPanel").unbind().click(function (event){ event.stopPropagation(); event.preventDefault(); if(!validateForm("", $("div.welcomeForm","#welcomeFormPanel"))) { return; } var messageForm = $("div.welcomeForm","#welcomeFormPanel"); var formClone = messageForm.find("form"); //formClone.wrap("<form></form>"); messageForm = serializeForm(formClone[0]); if(messageForm.length==0) { $.unblockUI(); return; } messageForm += "&command=messageForm&random="+Math.random(); var obj = messageForm; $("#welcomeFormPanel").find("h2").addClass("spinner"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { displayError("Error : " + errorThrown); }, success: function (msg) { $("#welcomeFormPanel").find("h2").removeClass("spinner"); var responseText = LoadXMLString(msg); var response = msg.getElementsByTagName("response"); response = IE(response[0]).textContent; if (response == "success") { if(!showAlways) { var options = { path: '/', expires: 365 }; $.cookie(o.CookieWelcomeNote + "_" + userName + "_" + formName, true, options); } $.unblockUI(); } else { displayError("Error: Problem while saving data"); } } }); return false; }); //TODO welcome note, show or not $.blockUI({ message: $elem, css: { border: 'none', width: '600px', padding: '15px', color: '#000', 'border': '1px solid ' + getPopupColor(), 'background-color':getPopupColor(true), 'margin-left': '-300px', left: '50%', position: 'fixed', top: '20%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, '-webkit-box-shadow': '2px 5px 5px #373434', '-moz-box-shadow': '2px 5px 5px #373434' } }); } }, buttonText); } function loadDirectoryPreview() { var destinationPath = encodeURIComponent(hashListener.getHash().toString().replace("#", "")); destinationPath = destinationPath || "/"; $("div.directoryPreview").hide(); var ok = true; if (!$(document).data("disableDirectoryLogo")) $("div.directoryPreview").empty().append("<img id='directoryPreviewImg' src='"+destinationPath+".logo.png' />"); $('#directoryPreviewImg').load(function() { $('div.directoryPreview').show(); }); } function getLocalizationKey(key) { var _loc = $(document).data("localizations"); var defaultText = localizations[key]; if(_loc && _loc[key]) { defaultText = _loc[key]; } return defaultText; } window.applyLocalizations = function() { var _loc = $(document).data("localizations"); if(_loc) { for(var i in _loc) { if(i) { var key = i.toString(); var val = _loc[i].toString(); if(key && (val || val == "")) { if(key.toLowerCase().indexOf("button")>=0 || key.toLowerCase().indexOf("input")>=0) { $("."+key).val(val); } else if(key.toLowerCase().indexOf("byclass")>=0|| key.toLowerCase().indexOf("multiple")>=0) { $("."+key).html(val); } else { $("#"+key).html(val); } } } } var date1 = $("select#date1_action","div#searchDiv"); date1.find("option[value='after']").text(getLocalizationKey("SearchFormModifiedOptionAfterText")); date1.find("option[value='before']").text(getLocalizationKey("SearchFormModifiedOptionBeforeText")); var date2 = $("select#date2_action","div#searchDiv"); date2.find("option[value='after']").text(getLocalizationKey("SearchFormModifiedOptionAfterText")); date2.find("option[value='before']").text(getLocalizationKey("SearchFormModifiedOptionBeforeText")); var sizeDropdown = $("select#size1_action","div#searchDiv"); sizeDropdown.find("option[value='bigger than']").text(getLocalizationKey("SearchFormSizeOptionBiggerThanText")); sizeDropdown.find("option[value='smaller than']").text(getLocalizationKey("SearchFormSizeOptionSmallerThanText")); var typeDropdown = $("select#type1_action","div#searchDiv"); typeDropdown.find("option[value='file']").text(getLocalizationKey("SearchFormItemTypeOptionFileText")); typeDropdown.find("option[value='folder']").text(getLocalizationKey("SearchFormItemTypeOptionFolderText")); $("#filesContainer").find("td.thName").html(getLocalizationKey("TreeviewHeaderNameText")); $("#filesContainer").find("td.thSize").html(getLocalizationKey("TreeviewHeaderSizeText")); $("#filesContainer").find("td.thModified").html(getLocalizationKey("TreeviewHeaderModifiedText")); $("#filesContainer").find("td.thKeywords").html(getLocalizationKey("TreeviewHeaderKeywordsText")); updatePageSizeOnLayout(); } } function applyCustomizations() { var customizations = $(document).data("customizations"); if(!customizations)return; for(var item in customizations) { var custItem = customizations[item]; switch (custItem.key) { case "logo": $("div.logo","#header").empty().append("<img src='/WebInterface/images/"+custItem.value+"' />"); var link = $(document).data("logoURL"); if(link) { if(!$("div.logo").find("img").parent().attr("href")) { $("div.logo").find("img").wrap("<a href='"+link+"'></a>"); } else { $("div.logo").find("img").parent().attr("href",link); } $("div.logo").find("img").css("border","none"); } break; case "logoAlign": if(custItem.value == "middle") { $("div.logo").css("float","none").addClass("logoCenter").parent().css("text-align","center"); } else if(custItem.value == "right") { $("div.logo").css("float","right").addClass("logoCenter").parent().css("text-align","right"); } else { $("div.logo").css("float","left").removeClass("logoCenter").parent().css("text-align","left"); } break; case "title": document.title = custItem.value; break; case "header": $("div.headerContent").html(custItem.value); break; case "headerTextColor": $("#header").css("color",custItem.value); break; case "headerTextSize": $("#header").css("font-size",custItem.value); break; case "headerTextStyle": if(custItem.value.indexOf("bold")>=0) { $("#header").css("font-weight",custItem.value); } else { $("#header").css("font-style",custItem.value); } break; case "headerTextAlign": $("#header").css("text-align",custItem.value); break; case "headerBackgroundColor": $("#header").css("background-color",custItem.value); break; case "footer": $("div.footerContent").html(custItem.value); break; case "footerTextColor": $.cssRule({ "div.footerContent": [ ["color",custItem.value] ]}); break; case "footerTextSize": $.cssRule({ "div.footerContent": [ ["font-size",custItem.value] ]}); break; case "footerTextStyle": if(custItem.value.indexOf("bold")>=0) { $.cssRule({ "div.footerContent": [ ["font-weight",custItem.value] ]}); } else { $.cssRule({ "div.footerContent": [ ["font-style",custItem.value] ]}); } break; case "footerTextAlign": $.cssRule({ "div.footerContent": [ ["text-align",custItem.value] ]}); break; case "footerBackgroundColor": $.cssRule({ "div.footerContent": [ ["background-color",custItem.value] ]}); break; case "uploadOnly": if(custItem.value.toLowerCase() == "true") { makeItUploadOnly(); } break; case "slideShowOnly": if(custItem.value.toLowerCase() == "true") { if(!window.forSlideshow) { makeItSlideShowOnly(); } } break; case "popupBackgroundColor": $(document).data("popupBackgroundColor", custItem.value); break; case "popupBorderColor": $(document).data("popupBorderColor", custItem.value); break; case "mainBackgroundColor": $.cssRule({ "body": [ ["background-color", custItem.value] ]}); break; case "mainBackgroundImage": $.cssRule({ "body": [ ["background-image", "url("+custItem.value+")"], ["background-repeat", "no-repeat"] ]}); break; case "mainBorderColor": $.cssRule({ "body": [ ["border", "1px solid " +custItem.value] ]}); break; case "buttonFontColor": $.cssRule({ "ul.topnav li a": [ ["color", custItem.value] ]}); break; case "buttonHoverFontColor": $.cssRule({ "ul.topnav li a:hover": [ ["color", custItem.value] ]}); break; case "buttonBackgroundColor": $.cssRule({ "ul.topnav li a,.mainNavigation": [ ["background-color", custItem.value] ]}); $.cssRule({ "ul.topnav": [ ["background-color", custItem.value] ]}); break; case "buttonHoverColor": $.cssRule({ "ul.topnav li a:hover": [ ["background-color", custItem.value] ]}); break; case "buttonBackgroundImage": $.cssRule({ "ul.topnav li a": [ ["background-image", "url("+custItem.value+")"], ["background-repeat", "no-repeat"] ]}); break; case "buttonHoverImage": $.cssRule({ "ul.topnav li a:hover": [ ["background-image", "url("+custItem.value+")"], ["background-repeat", "no-repeat"] ]}); break; case "listBackgroundColor": $.cssRule({ "#filesListing": [ ["background-color", custItem.value] ]}); break; case "listTextColor": $.cssRule({ "#filesListing": [ ["color", custItem.value] ]}); $.cssRule({ "#filesListing a": [ ["color", custItem.value] ]}); break; case "listTextSize": $.cssRule({ "#filesListing,tr.jqueryFileTree, #filesListing a": [ ["font-size", custItem.value] ]}); break; case "listTextStyle": if(custItem.value.indexOf("bold")>=0) { $.cssRule({ "#filesListing,tr.jqueryFileTree, #filesListing a": [ ["font-weight", custItem.value] ]}); } else { $.cssRule({ "#filesListing,tr.jqueryFileTree, #filesListing a": [ ["font-style", custItem.value] ]}); } break; case "listHeaderTextColor": $.cssRule({ "#filesListing th": [ ["color", custItem.value] ]}); break; case "listHeaderTextSize": $.cssRule({ "#filesListing th": [ ["font-size", custItem.value] ]}); break; case "listHeaderTextStyle": if(custItem.value.indexOf("bold")>=0) { $.cssRule({ "#filesListing th": [ ["font-weight", custItem.value] ]}); } else { $.cssRule({ "#filesListing th": [ ["font-style", custItem.value] ]}); } break; case "listDefaultSortColumnIndex": $(document).data("listDefaultSortColumnIndex", custItem.value); break; case "listDefaultSortDirection": $(document).data("listDefaultSortDirection", custItem.value); break; case "listAlternateColor": $.cssRule({ ".jqueryFileTreeAlt" :[ ["background-color", custItem.value + ""] ]}); break; case "listHoverColor": $.cssRule({ ".rowHover": [ ["color", custItem.value + ""] ]}); break; case "tooltipBackgroundColor": $.cssRule({ ".tipsy-inner": [ ["background-color", custItem.value] ]}); break; case "tooltipTextColor": $.cssRule({ ".tipsy-inner": [ ["color", custItem.value] ]}); break; case "tooltipTextColor": $.cssRule({ ".tipsy-inner": [ ["color", custItem.value] ]}); break; case "CHECK_COL": $(document).data("disableCheckCol", custItem.value); break; case "NAME_COL": $(document).data("disableNameCol", custItem.value); break; case "SIZE_COL": $(document).data("disableSizeCol", custItem.value); break; case "MODIFIED_COL": $(document).data("disableModifiedCol", custItem.value); break; case "KEYWORDS_COL": $(document).data("disableKeywordsCol", custItem.value); break; /*case "NAME_COL_TEXT": $("#filesContainer").find("td.thName").html(custItem.value); break; case "SIZE_COL_TEXT": $("#filesContainer").find("td.thSize").html(custItem.value); break; case "MODIFIED_COL_TEXT": $("#filesContainer").find("td.thModified").html(custItem.value); break;*/ case "BROWSER_UPLOAD_START_TEXT": $("#browserFileUpload").find("#submitAction").find("a.upload").text(custItem.value); break; case "shareThumbnail": $(document).data("shareThumbnail", custItem.value); break; case "defaultShareMethod": $(document).data("defaultShareMethod", custItem.value); break; case "shareAdvanced": $(document).data("shareAdvanced", custItem.value); break; case "shareAllowUploads": $(document).data("shareAllowUploads", custItem.value); break; case "disableThumbnailHover": $(document).data("disableThumbnailHover", custItem.value); break; case "disableTreeviewHover": $(document).data("disableTreeviewHover", custItem.value); break; case "autoAppletFlag": if (!$.cookie(o.CookieAutoAppletFlag)) window.autoAppletFlagSet(custItem.value); if (custItem.value == "true") $("#autoAppletFlag").attr("checked", "checked"); break; case "showResume": if(custItem.value=="false") { $("#browserFileUpload").find("label[for='chkUploadResume']").hide(); } else { $("#browserFileUpload").find("label[for='chkUploadResume']").show(); } break; case "pathBackgroundColor": $.cssRule({ "#crumbs": [ ["background-color", custItem.value] ]}); break; case "pathTextColor": $.cssRule({ "#crumbs li,#crumbs li a, #crumbs li a:visited": [ ["color", custItem.value] ]}); break; case "pathTextSize": $.cssRule({ "#crumbs": [ ["font-size", custItem.value] ]}); break; case "quotaTextColor": $.cssRule({ ".quotaText": [ ["color", custItem.value] ]}); break; case "quotaTextSize": $.cssRule({ ".quotaText": [ ["font-size", custItem.value] ]}); break; case "quotaTextStyle": if(custItem.value.indexOf("bold")>=0) { $.cssRule({ ".quotaText": [ ["font-weight", custItem.value] ]}); } else { $.cssRule({ ".quotaText": [ ["font-style", custItem.value] ]}); } break; case "quotaTextAlign": $.cssRule({ ".quotaText": [ ["text-align", custItem.value] ]}); break; case "quotaBackgroundColor": $.cssRule({ ".quotaText": [ ["background-color", custItem.value] ]}); break; case "commentsTextColor": $.cssRule({ ".comments": [ ["color", custItem.value] ]}); break; case "commentsTextSize": $.cssRule({ ".comments": [ ["font-size", custItem.value] ]}); break; case "commentsTextStyle": if(custItem.value.indexOf("bold")>=0) { $.cssRule({ ".comments": [ ["font-weight", custItem.value] ]}); } else { $.cssRule({ ".comments": [ ["font-style", custItem.value] ]}); } break; case "commentsTextAlign": $.cssRule({ ".comments": [ ["text-align", custItem.value] ]}); break; case "commentsBackgroundColor": $.cssRule({ ".comments": [ ["background-color", custItem.value] ]}); break; case "OPEN_NEW_WINDOW_EXTENSIONS": var exts = custItem.value.split(","); if(exts && exts.length>0) { $(document).data("OPEN_NEW_WINDOW_EXTENSIONS", exts); } else { $(document).removeData("OPEN_NEW_WINDOW_EXTENSIONS"); } break; case "genericIconTree": if(custItem.value && custItem.value.length>0 && custItem.value == "true") { $(document).data("genericIconTree",true); } break; case "genericIconThumbnail": if(custItem.value && custItem.value.length>0 && custItem.value == "true") { $(document).data("genericIconThumbnail",true); } break; default : break; } } var destinationPath = hashListener.getHash().toString().replace("#", ""); if (destinationPath.indexOf("/IMPULSEUpload/") > 0) { makeItUploadOnly(); } } function getPopupColor(bg) { if(bg) { return $(document).data("popupBackgroundColor") || "#FFF"; } else { return $(document).data("popupBorderColor") || "#CCC"; } } function applyShareCustomizations() { var customizations = $(document).data("customizations"); if(!customizations)return; for(var item in customizations) { var custItem = customizations[item]; switch (custItem.key) { case "EXPIREDAYS": $("#txtdays", "#shareOptionDiv").val(custItem.value); break; case "EMAILFROM": $("#emailFrom").val(custItem.value); break; case "EMAILTO": $("#emailTo").val(custItem.value); break; case "EMAILCC": $("#emailCc").val(custItem.value); break; case "EMAILBCC": $("#emailBcc").val(custItem.value); break; case "EMAILSUBJECT": $("#emailSubject").val(custItem.value); break; case "EMAILBODY": custItem.value = custItem.value.replace(/\\r/g, '\r'); $("textarea#emailBody", "#shareOptionDiv").val(custItem.value); $("textarea#emailBody", "#shareOptionDiv").html(custItem.value.replace(/>/g,">").replace(/</g,"<")); break; default : break; } } } function makeItSlideShowOnly() { $("#mainContent").hide(); $(document).data("slideShowOnly",true); window.slideshowOnly = true; doSlideshow(true); } function makeItUploadOnly() { browserUploader(); var $elem = $("div#browserFileUpload").parent(); $("#mainContent").hide().after($elem); $elem.css({ 'position':'relative', 'margin-left':'-230px', 'left':'50%' }); $("#hideUploadPanel").hide(); $("#mainContent").before($("div.mainNavigation")); $("div.mainNavigation").find("a[href!='javascript:doLogout();']").parent().remove(); $(document).data("uploadOnly",true); } function bindMainMenuEvents() { var browserTemplate = '<div class="uploadFormPanel" id="uploadDiv##">' + '<form id="META_uploadForm##" name="META_uploadForm##" action="'+o.uploadURL+'" enctype="multipart/form-data" method="post" target="iframeUploadSingle##">' + '<input id="uploadPath##" type="hidden" name="uploadPath" value="#DEST_PATH#" />' + '<input id="theName##" type="hidden" name="the_action" value="STOR" />' + '<input id="file_##_SINGLE_FILE_POST" type="file" multiple="" name="file_##_SINGLE_FILE_POST" />' + '</form>' + '<iframe name="iframeUploadSingle##" id="iframeUploadSingle##" src="javascript:false;" width="1" height="1" style="left:-5000px;display:none;">' + '</iframe>' + '</div>'; window.doSlideshow = function(_slideshowOnly, _popup) { var path = document.location.hash; if (path == "") path = "/"; if (path.indexOf("#") == 0) path = path.substring(1); if($(document).data("slideShowOnly")) { $("#mainContent").before($('div.slideshow')); $('div.slideshow').before($("div.mainNavigation")); } var h = window.innerHeight ? window.innerHeight : $(window).height(); h = h * 0.92; var destinationPath = "#" + path; $('div.slideshow').empty().append('<iframe frameborder="0" scrolling="auto" style="width: 100%; height:'+ h +'px;background-color: #000000;" name="cftp_iframeSS" id="cftp_iframeSS" src="/WebInterface/jQuery/ssindex.html'+destinationPath+'" hspace="0" allowtransparency="false"></iframe>'); $(window).bind("resize",function(){ resetSlideShowDimensions(); }); } window.quickView = function() { var _html = []; var _itemHTML="<p><a href=\"HREF\" fileName=\"FILENAME\" rel=\"QUICKVIEW\" title=\"TITLE\">TITLE</a></p>"; var _fileName = false; var elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = unescape($curElem.find("a:first").attr("rel")); } var files = new Array(); for(var item = 0;item<l.length;item++) { var curItem = l[item]; if(curItem.name) { var inValidImg = (curItem.privs.search(/slideshow/i) == -1 || curItem.preview == 'false'); if(!inValidImg) { var row = new Object(); row['enabled'] = true; row['imageSrc'] = o.ajaxCallURL + '?command=getPreview&size=3&path=' + curItem['href_path']; row["fileName"] = curItem['href_path']; files.push(row); } } } for(var item = 0;item<files.length;item++) { var curItem = files[item]; var _generatedHTML = _itemHTML _generatedHTML = _generatedHTML.replace(/HREF/g, curItem.imageSrc); _generatedHTML = _generatedHTML.replace(/TITLE/g, curItem.name); _generatedHTML = _generatedHTML.replace(/FILENAME/g, curItem.fileName); _html.push(_generatedHTML); } $("#quickViewItems").remove(); var quickViewItems = $("<div id='quickViewItems'></div>"); quickViewItems.empty().append(_html.join("")); if(_fileName && $("a[fileName='"+_fileName+"']",quickViewItems).length>0) { var curPic = $("a[fileName='"+_fileName+"']",quickViewItems).parent(); quickViewItems.prepend(curPic.nextAll()); quickViewItems.prepend(curPic); } if(_html.length>0) { $("body").append(quickViewItems); quickViewItems.hide(); $("a[rel='QUICKVIEW']",quickViewItems).colorbox({ onClosed: function(){ $("#quickViewItems").remove(); }, photo:true, open: true, current : "Item {current} of {total}" }); } else { $.growlUI("Error : Nothing to show in quick view", "No items available", o.GrowlTimeout, "", o.GrowlWithCloseButton); } } window.performAction = function (elem, context) { var onBlockFn = null; if (elem == "upload") { window.browserUploader(context); return; } else if (elem == "quickView") { quickView(context); return; } else if (elem == "delete") { window.delete_items(context); return; } else if (elem == "rename") { performRenameAction(context); return; } else if (elem == "cut") { doCopy(context, true); return; } else if (elem == "copy") { doCopy(context); return; } else if (elem == "paste") { doPaste(context); return; } else if (elem == "zip") { downloadAsZip(context); return; } else if (elem == "download") { downloadItems(context); return; } else if (elem == "share") { shareFile(context); return; } else if (elem == "addToBasket") { addToBasket(context); return } else if (elem == "showBasket") { showDownloadBasket(context); return; } else if (elem == "copyDirectLink") { copypath(context); return; } else if (elem == "updateKeywords") { updateKeywords(context); return; } else if (elem == "logout") { doLogout(context); return; } else if (elem == "search") { var $elem = $("#searchDiv"); $.blockUI({ message: $elem, css: { width: '600px', padding: '15px', 'margin-left': '-300px', left: '50%', position: 'absolute', top: '27%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: onBlockFn }); } else if (elem == "shareOptionDiv") { var $elem = $("#shareOptionDiv"); $.blockUI({ message: $elem, css: { width: '600px', padding: '15px', 'margin-left': '-300px', left: '50%', position: 'absolute', top: '55px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: function () { try { $("input#emailTo", "#shareOptionDiv")[0].focus(); $("input#emailTo", "#shareOptionDiv")[0].select(); $elem.parent().draggable({handle:"h2"}); } catch (ex) {} } }); } else if (elem == "slideshow") { var $elem = $("#slideshowDiv"); var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); var viewportWidth = $(window).width(); viewportHeight = viewportHeight - (viewportHeight * 0.2); viewportWidth = viewportWidth - (viewportWidth * 0.1); $elem.find(".content").append($('div.slideshow')); $.blockUI({ message: $elem, css: { width: viewportWidth + 'px', padding: '15px', 'margin-left': '-'+(viewportWidth/2) - 15+'px', left: '50%', position: 'absolute', top: '5px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: function() { var h = window.innerHeight ? window.innerHeight : $(window).height(); h = h * 0.92; $("div.blockUI").css({"background-color":"black","color":"white"}); var destinationPath = unescape(hashListener.getHash().toString()); $elem.find("div.content").empty().append('<iframe frameborder="0" scrolling="auto" style="width: 100%; height:'+ h +'px;background-color: #000000;" name="cftp_iframeSS" id="cftp_iframeSS" src="/WebInterface/jQuery/ssindex.html'+destinationPath+'" hspace="0" allowtransparency="false"></iframe>'); $(window).bind("resize",function(){ resetSlideShowDimensions(); }); }, onUnblock: function() { $elem.find("div.content").empty(); } }); } else if (elem == "manageShares") { var $elem = $("#manageShares"); $.blockUI({ message: $elem, css: { width: '950px', padding: '15px', 'margin-left': '-460px', left: '50%', position: 'absolute', top: '5%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: function() { initManageShares($elem); $elem.parent().draggable({handle:"h2"}); } }); } else if (elem == "keywordsDiv") { var $elem = $("#keywordsDiv"); $.blockUI({ message: $elem, css: { width: '600px', padding: '15px', 'margin-left': '-310px', left: '50%', position: 'absolute', top: '15%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: function() { $elem.parent().draggable({handle:"h2"}); } }); } else { $elem = $("#"+elem); $.blockUI({ message: $elem, css: { width: '350px', padding: '15px', 'margin-left': '-175px', left: '50%', position: 'absolute', top: '25%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1, 'background-color':getPopupColor(true), 'border':"1px solid " + getPopupColor() }, onBlock: onBlockFn }); } try { $(".blockUI ").find("input[type='text']")[0].focus(); $(".blockUI ").find("input[type='text']")[0].select(); } catch (ex) {} } window.moveToElement = function($target) { if ($target.length) { var targetOffset = $target.offset().top; $('html,body').animate({scrollTop: targetOffset}, 500,false); return false; } } window.resetSlideShowDimensions = function(_height) { if(_height) { $("div.slideshow").find("iframe").css("height",_height+"px"); } else { var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); var viewportWidth = $(window).width(); viewportHeight = viewportHeight - (viewportHeight * 0.2); viewportWidth = viewportWidth - (viewportWidth * 0.1); $("div.blockUI.blockPage").css( { width:viewportWidth+'px', 'margin-left': '-'+(viewportWidth/2) - 15+'px', left: '50%' }); } } window.closeSlideshow = function() { $('#slideshowDiv').find('div.content').empty(); $(window).unbind('resize'); $.unblockUI(); } window.hideItemsStartingWithDot = function (flag) { var options = { path: '/', expires: 365 }; $.cookie(o.CookieHideItemStartingWithDot, flag, options); refreshView(); } window.hideCheckBoxColumn = function (flag) { var options = { path: '/', expires: 365 }; $.cookie(o.CookieHideCheckBoxColumn, flag, options); refreshView(); } window.hideFilter = function (flag) { var options = { path: '/', expires: 365 }; $.cookie(o.CookieHideFilter, flag, options); refreshView(); } window.autoUploadFlagSet = function (flag) { var options = {path: '/',expires: 365}; $.cookie(o.CookieAutoUploadFlag, flag, options); } window.autoAppletFlagSet = function (flag) { var options = {path: '/',expires: 365}; $.cookie(o.CookieAutoAppletFlag, flag, options); } window.noCompressionFlagSet = function (flag) { var options = {path: '/',expires: 365}; $.cookie(o.CookieNoCompressionFlag, flag, options); } window.startTunnel = function () { o.uploadURL = "http://127.0.0.1:55555/WebInterface/function/?CrushAuth="+$.cookie("CrushAuth"); o.downloadURL = "http://127.0.0.1:55555/WebInterface/function/?CrushAuth="+$.cookie("CrushAuth"); if (!$(document).data("appletLoadedU")) $(document).data("appletLoadedU", false); if (!$(document).data("appletLoadedU")) { loadApplet(false, function () { runAppletCommand(false,"COMMAND=TUNNEL:::ACTION=START:::URL="+window.location.toString(), false); }); } else { runAppletCommand(false,"COMMAND=TUNNEL:::ACTION=START:::URL="+window.location.toString(), false); } bindMainMenuEvents(); } window.stopTunnel = function () { o.uploadURL = "/WebInterface/function/"; o.downloadURL = "/WebInterface/function/"; if ($(document).data("appletLoadedU")) { runAppletCommand(false,"COMMAND=TUNNEL:::ACTION=STOP", false); } bindMainMenuEvents(); } window.doLogout = function (elem) { $.ajax({ type: "POST", url: o.ajaxCallURL, data: { command: "logout", random: Math.random() }, error: function (XMLHttpRequest, textStatus, errorThrown) { $.cookie("CrushAuth", "", { path: '/', expires: -1 }); document.location = "/WebInterface/login.html"; }, success: function (msg) { $.cookie("CrushAuth", "", { path: '/', expires: -1 }); document.location = "/WebInterface/login.html"; } }); } window.changePassword = function (elem) { if ($("#new_password1")[0].value != $("#new_password2")[0].value) { alert("New passwords don't match."); } else if ($("#new_password1")[0].value.length < 4) { alert("Password must be more complex."); } else { $.ajax({type: "POST",url: "/WebInterface/function/",data: {command: "changePassword",current_password: $("#current_password")[0].value,new_password1: $("#new_password1")[0].value,new_password2: $("#new_password2")[0].value}, success: function (response) { var s = getActionResponseText(LoadXMLString(response)); if (s.toUpperCase().indexOf("PASSWORD CHANGED") >= 0) { alert("Password changed. Please login using the new password.") doLogout(); } else alert(s); } }); } return false; } window.startSearch = function () { $("#searchDiv").block({ message: 'Processing... <a id="cancelAjax" href="#" style="color:#FFF;font-size:10px;">Cancel</a>', css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', color: '#fff', top: '40%' } }); var destinationPath = encodeURIComponent(hashListener.getHash().toString().replace("#", "")); destinationPath = destinationPath || "/"; var $_Request = $.ajax({ type: "POST", url: o.ajaxCallURL, data: "path=" + destinationPath + "&" + $("#searchForm").serialize().toString().replace(/=on/g, '=true'), success: function (response) { $(document).data("searchData", response); $("#searchDiv").unblock(); if (currentView() == "Thumbnail") { renderListing($("#filesContainerDiv"), "", false, false, response, true); } else { renderListing($("#filesContainer"), "", false, false, response, true); } $.unblockUI(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); } }); $("#cancelAjax").unbind().click( function () { $("#searchDiv").unblock(); $_Request.abort(); return false; }); return false; } window.validateForm = function (target, form) { form = form || $("table.customForm","#divUploadPanel"); var validated = true; form.find(".required_true").each( function () { if($(this).hasClass("chkbox")) { if (!$(this).is(":checked") && $(this).closest("td").find("input:checked").length == 0) { $(this).parent().addClass("validationFail").focus(); validated = false; } else { $(this).parent().removeClass("validationFail"); } } else { if ($.trim($(this).val()).length == 0) { $(this).addClass("validationFail").focus(); validated = false; } else { $(this).removeClass("validationFail"); } } }); if (form.prev().hasClass("attention")) { form.prev().remove(); } if (validated) { $(target).removeClass("disabledClick"); } else { $(target).addClass("disabledClick"); form.before("<div class='attention'>"+getLocalizationKey("FormValidationFailText")+"</div>"); form.prev().css("float", "none"); } return validated; } window.onbeforeunload = confirmExit; window.browserUploader = function () { window.showDrop(); if (!$(document).data("uploadWindowHidden")) { $(document).data("uploadWindowHidden", false); } if (!$(document).data("uploaderCss")) { $(document).data("uploaderCss",{ border: 'none', width: '460px', padding: '15px', color: '#000', 'border': '1px solid #ccc', backgroundColor: '#fff', 'margin-left': '-230px', left: '50%', position: 'absolute', top: '25px', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', '-webkit-box-shadow': '2px 5px 5px #888', '-moz-box-shadow': '2px 5px 5px #888', opacity: 1 }); } var isWindowHidden = $(document).data("uploadWindowHidden"); var $elem = $("div#browserFileUpload"); if (($.cookie(o.CookieAutoAppletFlag)+"") == "true" && !$(document).data("appletLoaded")) { loadApplet(true, function () { if ($("table.customForm","#divUploadPanel").length == 0 && navigator.appName.indexOf("Explorer") >= 0) { window.showDrop(); $(window).bind("resize",function(){ window.showDrop(); }); } }); //make the applet auto initialize when the upload panel is opened. } if (isWindowHidden) { $("#browserFileUpload").parent().show(); $("ul.topnav").find("a[href='javascript:performAction('upload');']").removeClass("bouncing_loader"); if ($("table.customForm","#divUploadPanel").length > 0) { $("#uploadDetailsTabAnchor").click(); } if(o.buggyBrowser) { $elem.parent().find("h2").css("cursor","text"); } else { $elem.parent().draggable({handle:"h2"}); } $(document).data("uploadWindowHidden", false); setTimeout(findAppletDroppedFiles, 500); if ($("table.customForm","#divUploadPanel").length == 0 && navigator.appName.indexOf("Explorer") >= 0) { window.showDrop(); $(window).bind("resize",function(){ window.showDrop(); }); } return; } if($("div.popupWindow").length>0) { return; } if ($("#customUploadForm").length > 0) { getUploadForm(function (data) { $("#customUploadForm").replaceWith(data); $("button#resetUploadForm").unbind().click(function (event) { $("#divUploadPanel").clearForm(); event.stopPropagation(); event.preventDefault(); }); $("a.nextButton").unbind().click(function () { if(validateForm()) { $(".customtabs").find("a").not(".active").removeClass("disabledClick").click(); if (navigator.appName.indexOf("Explorer") >= 0) { window.showDrop(); $(window).bind("resize",function(){ window.showDrop(); }); } } }); }); } if ($("table.customForm","#divUploadPanel").length > 0) { $("#uploadDetailsTabAnchor").click(); } $elem.find("#hideUploadPanel").unbind().click(function () { $("#browserFileUpload").parent().fadeOut(1000); if ($("#browserFileUpload").find("h2").hasClass("spinner")) { $("ul.topnav").find("a[href='javascript:performAction('upload');']").addClass("bouncing_loader"); } $(document).data("uploadWindowHidden", true); window.cancelDrop(); }); $("div#browserFileUpload").find("a.upload").unbind().click(function () { startUploading(); $(this).blur(); return false; }); $("div#browserFileUpload").find("a.clearCompleted").unbind().click(function () { $("a.completed", "ul.filesSelected").each(function () { $(this).closest("li").remove(); }); $(this).blur(); return false; }); $("div#browserFileUpload").find(".advancedBrowse").unbind().click(function () { if (!$(document).data("appletLoaded")) $(document).data("appletLoaded", false); if (!$(document).data("appletLoaded")) loadApplet(true,function () { if (navigator.appName.indexOf("Explorer") >= 0) { window.showDrop(); $(window).bind("resize",function(){ window.showDrop(); }); } handleAppletBrowse(); }); //initializes the applet, then calls the browse function else handleAppletBrowse(); $(this).blur(); return false; }); if ($("li", "ul.filesSelected").length == 0) { var htmlForm = browserTemplate.replace(/##/g, "1"); var destinationPath = encodeURIComponent(hashListener.getHash().toString().replace("#", "")); destinationPath = destinationPath || "/"; var htmlForm = htmlForm.replace(/#DEST_PATH#/g, destinationPath); $elem.find("ul.filesSelected").html(""); $elem.find("div#uploadPanel").html("").append(htmlForm).find("input[type='file']").unbind().change(function () { fileSelect($(this),browserTemplate); }); } if($("div.popupWindow").length==0) { $("#mainContent").append("<div class='popupWindow'></div>"); var popup = $("div.popupWindow"); popup.css($(document).data("uploaderCss")); popup.append($elem); } showHideUploadBtn(); if(o.buggyBrowser) { $elem.parent().find("h2").css("cursor","text"); } else { $elem.parent().draggable({handle:"h2"}); } setTimeout(findAppletDroppedFiles, 500); if(!$(document).data("slideShowOnly")) setupDND(); } window.uploadTabOK = function(o) { var r = validateForm(o); if (r && navigator.appName.indexOf("Explorer") >= 0) setTimeout(window.showDrop,500); return r; } function findAppletDroppedFiles() { var s = runAppletCommand(true,"COMMAND=DND:::"); if (s && s != "") { handleFileSelectToUpload(s, true); while (s != "") { s = runAppletCommand(true,"COMMAND=DND:::"); handleFileSelectToUpload(s, true); } startAutoUploadAfterDrop(); } if (new Date() - $(document).data("dndActiveAt") > 5000) window.cancelDrop(true); if (!$(document).data("uploadWindowHidden")) setTimeout(findAppletDroppedFiles, 500); else window.cancelDrop(true); } window.fileSelect = function(obj){ var notSupportedBrowser = true; //some browsers can handle multi select from the form. So support it here by iterating through the selected files and list their names try { if ($(obj)[0].files.length > 1) { notSupportedBrowser = false; $(obj)[0].name = $(obj)[0].name+"_MULTI"; //the "name" of this field cannot end with SINGLE_FILE_POST or Crush will not be able to distinguish multiple files var files = $(obj)[0].files; var v = $(obj).val(); var filesSelected = getLocalizationKey("BrowserUploaderSelectedFilesGroupText") + " <ul class='groupedItems'>"; var allFiles = []; var destinationPath = hashListener.getHash().toString().replace("#", ""); destinationPath = destinationPath || "/"; //some browsers can handle multi select from the form. So support it here by iterating through the selected files and list their names for (var x=0; x<files.length; x++) { v+=files[x].name+","; filesSelected += "<li class='groupItem' dest='"+destinationPath+"' rel='"+files[x].name+"'>" + files[x].name + "</li>"; allFiles.push(files[x].name); } v = v.substring(0,v.length-1); filesSelected += "</ul>"; performFileSelect(obj, browserTemplate, filesSelected, allFiles); } else { notSupportedBrowser = true; } } catch(e) //not all browsers support multi select { } if(notSupportedBrowser) { performFileSelect(obj, browserTemplate); } } window.doPaste = function (context) { var $elem = $("div#pasteFormPanel"); var elem = false; if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } if (!$(document).data(o.CookieCopiedFiles)) { $.growlUI(getLocalizationKey("PasteFormPasteButtonText"), getLocalizationKey("PasteFormErrorNothingToPasteText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return false; } function pasteFiles(hasForm) { if(!validateForm(elem, $("div.pasteForm","#pasteFormPanel"))) { return false; } $("#pasteFormPanel").find(".closeButton").click(); var action = "Paste"; var destinationPath = undefined; if (elem && !$(elem).hasClass("fileItem") && !$(elem).hasClass("fileThumb")) { if (currentView() != "Thumbnail") { destinationPath = encodeURIComponent(unescape($(elem).find("a:first").attr("rel"))); } else { destinationPath = $(elem).find("a:first").attr("rel"); } } else if($(elem).hasClass("directoryThumb") || $(elem).hasClass("directory")) { destinationPath = encodeURIComponent(unescape(hashListener.getHash().toString().replace("#", ""))); destinationPath = destinationPath || "/"; destinationPath += $(elem).find("a").text(); } else { destinationPath = encodeURIComponent(unescape(hashListener.getHash().toString().replace("#", ""))); destinationPath = destinationPath || "/"; } if (destinationPath) { var copiedItems = $(document).data(o.CookieCopiedFiles); if (copiedItems) { var items = copiedItems.split("\r\n"); var curAction = items[0].toLowerCase(); action = items[0].toLowerCase() + "_paste"; var fileNames = ""; for (var i = 1; i < items.length; i++) { if (fileNames.length > 0) { fileNames += "\r\n"; } fileNames += encodeURIComponent(unescape(items[i])); } var obj = { command: action, names: fileNames, destPath: destinationPath, random: Math.random() }; if(hasForm) { var pasteForm = $("div.pasteForm","#pasteFormPanel"); var formClone = pasteForm.find("form"); pasteForm = serializeForm(formClone[0]); pasteForm += "&command="+action+"&names="+fileNames+"&destPath="+destinationPath+"&random="+Math.random(); obj = pasteForm; } if (currentView() != "Thumbnail") { $("#filesListing").find("table").addClass("wait"); } else { $("#filesListing").find("ul").addClass("wait"); } $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, error: function (XMLHttpRequest, textStatus, errorThrown) { $.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton); }, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { if (responseText.toString().toLowerCase() == "ok") { if (curAction == "cut") { $(document).removeData(o.CookieCopiedFiles); } highlightPasteButton(); var curDestinationPath = encodeURIComponent(unescape(hashListener.getHash().toString().replace("#", ""))); curDestinationPath = curDestinationPath || "/"; if(curDestinationPath != destinationPath) { setHashLocation(destinationPath); } else { $(".refreshButton").click(); } } else { $.growlUI(getLocalizationKey("PasteFormErrorHeaderText"), getLocalizationKey("PasteFormErrorDetailsText").replace("{0}",responseText), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); $(".refreshButton").click(); } } else { if (curAction == "cut") { $(document).removeData(o.CookieCopiedFiles); } highlightPasteButton(); $(".refreshButton").click(); } if (currentView() != "Thumbnail") { $("#filesListing").find("table").removeClass("wait"); } else { $("#filesListing").find("ul").removeClass("wait"); } }, error: function () { $.growlUI(getLocalizationKey("PasteFormErrorHeaderText"), getLocalizationKey("PasteFormErrorDetailsText").replace("{0}","Probelm while executing paste command on server"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); $(".refreshButton").click(); if (currentView() != "Thumbnail") { $("#filesListing").find("table").removeClass("wait"); } else { $("#filesListing").find("ul").removeClass("wait"); } } }); } else { $.growlUI(getLocalizationKey("PasteFormPasteButtonText"), getLocalizationKey("PasteFormErrorNothingToPasteText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } return false; } } if ($("#pasteFormPanel").length > 0) { getCustomForm("pasteForm",function (data, hasForm, formName) { if(hasForm) { $("div.pasteForm","#pasteFormPanel").html("<form id='frmPasteForm'>" + data + "</form>").find("table").css("text-align","left"); $("button#resetPasteForm","#pasteFormPanel").unbind().click(function (event) { $("#pasteFormPanel").clearForm(); event.stopPropagation(); event.preventDefault(); }).val(getLocalizationKey("PasteFormResetButtonText")).text(getLocalizationKey("PasteFormResetButtonText")); $("button.submitForm","#pasteFormPanel").unbind().click(function (event){ event.stopPropagation(); event.preventDefault(); pasteFiles(true); return false; }); $.blockUI({ message: $elem, css: { border: 'none', width: '470px', padding: '15px', 'border': '1px solid ' + getPopupColor(), 'background-color':getPopupColor(true), 'margin-left': '-235px', left: '50%', position: 'absolute', top: '10%', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: 1 } }); } else { pasteFiles(); } }, getLocalizationKey("PasteFormPasteButtonText")); } } window.downloadAsZip = function (context, isFolder) { var action = "Zip"; var _fileName = ""; var elem = {}; var checkedFiles = {}; if(!isFolder) { if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } if(currentView() != "Thumbnail") { checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); } else { checkedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } if(_fileName.length>0) { checkedFiles.push($(elem)); } } else { checkedFiles = context; } var stringToCopy = ""; var ItemsToDownload = []; checkedFiles.each(function () { if(currentView() != "Thumbnail") { var parentElem = $(this).closest("tr"); var filePath = parentElem.find("a").attr("rel"); var dirContext = parentElem.attr("rel"); var dirPath = parentElem.parent().find("a[rel='"+dirContext+"']"); if(dirPath) { dirPath = dirPath.closest("tr"); if(dirPath && dirPath.find("input.chkBox").is(":checked")) { return; } } filePath = filePath.replace("//", "/"); if (!ItemsToDownload.has(filePath)) { ItemsToDownload.push(filePath); stringToCopy += ":" + filePath; } } else { var parentElem = $(this); var filePath = parentElem.find("a").attr("rel"); var dirContext = parentElem.attr("rel"); var dirPath = parentElem.parent().find("a[rel='"+dirContext+"']"); if(dirPath) { if(dirPath && dirPath.hasClass("fileBoxSelected")) { return; } } filePath = filePath.replace("//", "/"); if (!ItemsToDownload.has(filePath)) { ItemsToDownload.push(filePath); stringToCopy += ":" + filePath; } } }); if (stringToCopy.length == 0) { $.growlUI(action, "Nothing selected", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { submitAction({ '#command': "downloadAsZip", '#path': encodeURIComponent("/"), '#paths': encodeURIComponent(unescape(stringToCopy)), '#random': Math.random() }); selectDeselectAllItems(false); } } window.delete_items = function (context) { var action = "delete"; var _fileName = ""; var elem = false; if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } { var checkedFiles = {}; if(currentView() == "Thumbnail") { checkedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } else { checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); } if (checkedFiles.length == 0 && !elem) { $.growlUI("Nothing Selected", o.DeleteNoFilesSelectedMessage, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } var filesCopied = 0; var directoriesCopied = 0; var stringToCopy = _fileName; var _strMsg = stringToCopy; if(elem){ var $curElem = $(elem); if($curElem.hasClass("fileTR") || $curElem.hasClass("fileThumb") || $curElem.hasClass("fileThumb")){ filesCopied+=1; } else { directoriesCopied+=1; } } var notDisplayed = 0; checkedFiles.each(function () { var parentElem = $(this); if(currentView() != "Thumbnail") { parentElem = $(this).closest("tr"); } var filePath = unescape(parentElem.find("a").attr("rel")); filePath = unescape(filePath.replace("//", "/")); if(_fileName != filePath) { if (stringToCopy.length > 0) { stringToCopy += "\r\n"; } stringToCopy += (filePath); if(directoriesCopied + filesCopied <5) { if (_strMsg.length > 0) { _strMsg += "\r\n"; } _strMsg += filePath; } else { notDisplayed += 1; } if(currentView() != "Thumbnail") { if (parentElem.find(".directory").length > 0) { directoriesCopied += 1; } else { filesCopied += 1; } } else { if (parentElem.hasClass("directoryThumb")) { directoriesCopied += 1; } else { filesCopied += 1; } } } }); _strMsg = unescape(_strMsg); if(notDisplayed>0) { _strMsg += "\n\nand " + notDisplayed + " other item(s)"; } var msgToShow = getLocalizationKey("DeleteConfirmationMessageText"); msgToShow = msgToShow.replace("{0}",directoriesCopied); msgToShow = msgToShow.replace("{1}",filesCopied); msgToShow = msgToShow.replace("{2}", '\n' + _strMsg + '\n\n'); /* if (filesCopied > 0 && directoriesCopied > 0) { msgToShow = "Total " + directoriesCopied + " folder(s) and " + filesCopied + " file(s) will be deleted.\n\nItems:" + _strMsg; } else if (filesCopied > 0) { msgToShow = "Total " + filesCopied + " file(s) will be deleted.\n\nItems:\n\n" + _strMsg + "\n"; } else { msgToShow = "Total " + directoriesCopied + " folder(s) will be deleted.\n\nItems:" + _strMsg + "\n"; }*/ if (confirm(msgToShow)) { var fileName = stringToCopy; var obj = { command: "delete", names: encodeURIComponent(unescape(fileName)), random: Math.random() }; //$("#filesListing").addClass("wait"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); //$("#filesListing").removeClass("wait"); if (responseText.length > 0) { $.growlUI("Problem while deleting", "There was a problem while deleting. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); $(".refreshButton").click(); } else { $("#filesContainer").find("input.chkBoxAll").removeAttr("checked"); $(".refreshButton").click(); } }, error: function () { $.growlUI("Problem while deleting", "There was a problem while deleting. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); $(".refreshButton").click(); } }); } selectDeselectAllItems(false); } } window.makedir = function (fileName) { fileName = fileName || $("#txtNewFolder").val(); if (fileName.toString().length == 0) { return; } var filePath = unescape(hashListener.getHash().toString().replace("#", "")); if (filePath.length == 0) { filePath = "/"; } if($("#createFolder").data("parameter")){ var param = $("#createFolder").data("parameter"); filePath = param.find("a").attr("rel"); } var newFolderName = encodeURIComponent(filePath + fileName + "/"); var obj = { command: "makedir", path: newFolderName, random: Math.random() }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { if (responseText.toString().toLowerCase() == "ok") { $(".refreshButton").click(); } else { $.growlUI("Problem while creating new folder", "There was a problem while creating new folder. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } } else { $.unblockUI(); if($("#chkNavigateAfterMkdir").is(":checked")) { setHashLocation(newFolderName); } else { $(".refreshButton").click(); } } }, error: function () { $.growlUI("Problem while creating new folder", "There was a problem while trying to create new folder. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); } window.doCopy = function (context, flag) { var action = "Copy"; if (flag) action = "Cut"; var _fileName = ""; var elem = false; if(context) { elem = currentContext(); if(elem) { var $curElem = $(elem); _fileName = $curElem.find("a:first").attr("rel"); } } var checkedFiles = {}; if(currentView() == "Thumbnail") { checkedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible"); } else { checkedFiles = $("#filesListing").find("input.chkBox:visible:checked"); } if (checkedFiles.length == 0 && !elem) { if (flag) { $.growlUI("Nothing selected", o.CutNoFilesSelectedMessage, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { $.growlUI("Nothing selected", o.CopyNoFilesSelectedMessage, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } return; } var filesCopied = 0; var directoriesCopied = 0; var stringToCopy = action.toLowerCase(); stringToCopy += "\r\n" + _fileName; if(elem){ var $curElem = $(elem); if($curElem.hasClass("fileTR") || $curElem.hasClass("fileThumb")){ filesCopied+=1; } else { directoriesCopied+=1; } } checkedFiles.each(function () { var parentElem = $(this); if(currentView() != "Thumbnail") { parentElem = $(this).closest("tr"); } var filePath = parentElem.find("a").attr("rel"); filePath = filePath.replace("//", "/"); if(_fileName != filePath) { stringToCopy += "\r\n" + filePath; if(currentView() == "Thumbnail") { if (parentElem.hasClass("directoryThumb")) { directoriesCopied += 1; } else { filesCopied += 1; } } else { if (parentElem.find(".directory").length > 0) { directoriesCopied += 1; } else { filesCopied += 1; } } } }); var options = { path: '/', expires: 365 }; $(document).data(o.CookieCopiedFiles, stringToCopy); var msgToShow = getLocalizationKey("CopyActionGrowlText"); if(flag) { msgToShow = getLocalizationKey("CutActionGrowlText"); } msgToShow = msgToShow.replace("{0}",directoriesCopied); msgToShow = msgToShow.replace("{1}",filesCopied); /*if (filesCopied > 0 && directoriesCopied > 0) { if (flag) msgToShow = "Total " + directoriesCopied + " folder(s) and " + filesCopied + " file(s) cut"; else msgToShow = "Total " + directoriesCopied + " folder(s) and " + filesCopied + " file(s) copied"; } else if (filesCopied > 0) { if (flag) msgToShow = "Total " + filesCopied + " file(s) cut"; else msgToShow = "Total " + filesCopied + " file(s) copied"; } else { if (flag) msgToShow = "Total " + directoriesCopied + " folder(s) cut"; else msgToShow = "Total " + directoriesCopied + " folder(s) copied"; }*/ $.growlUI(action, msgToShow); highlightPasteButton(); selectDeselectAllItems(false); } } function getUploadForm(callback) { var $_Request = $.ajax({ type: "POST", url: o.ajaxCallURL, data: "command=getCustomForm&form=uploadForm", error: function (XMLHttpRequest, textStatus, errorThrown) { //$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, textStatus,o.GrowlWithCloseButton); $("#uploadDetailsTabAnchor").hide().next().click(); }, success: function (response) { var items = $.xml2json(response, true); var html = ''; if (items.entries) { $("div.customtabs","#browserFileUpload").find("a#uploadDetailsTabAnchor").show(); var fields = items.entries[0].entries_subitem; html = '<table class="customForm" cellpadding="0" cellspacing="0">'; html += '<tr style="display:none;"><td colspan="2"><input type="hidden" id="meta_UploadFormId" name="meta_UploadFormId" value="' + XMLValue(items.id[0]) + '"/><input type="hidden" id="meta_UploadFormName" name="meta_UploadFormName" value="' + XMLValue(items.name[0]) + '"/></td></tr>'; for (var item in fields) { html += generateFormField(fields[item]); } html += '<tr>' + '<td colspan="2" style="border:0px;text-align:right;padding-right:10px;"><a href="javascript:void(0);" class="nextButton">'+ getLocalizationKey("BrowserUploaderFormNextButtonText")+'</a><button value="'+ getLocalizationKey("BrowserUploaderFormResetButtonText")+'" id="resetUploadForm">'+ getLocalizationKey("BrowserUploaderFormResetButtonText")+'</button></td>' + '<tr>'; html += '</table>'; } else { $("div.customtabs","#browserFileUpload").find("a#uploadDetailsTabAnchor").hide().next().click(); } callback(html); }, complete: function () { callback(""); } }); return false; } function getCustomForm(type, callback, typeName) { var $_Request = $.ajax({ type: "POST", url: o.ajaxCallURL, data: "command=getCustomForm&form=" + type, success: function (response) { var items = $.xml2json(response, true); var html = ''; var alwaysFlag = false; if(items.always && items.always[0] && items.always[0].text) { alwaysFlag = items.always[0].text == "true"; } var formName = ""; if(items.name && items.name[0] && items.name[0].text) { formName = items.name[0].text; } if (items.entries) { var fields = items.entries[0].entries_subitem; html = '<table class="customForm" cellpadding="0" cellspacing="0">'; for (var item in fields) { html += generateFormField(fields[item]); } html += '<tr><td colspan="2" style="text-align:right;padding-right:10px;border:0px;">'; if(type!="messageForm") { html += '<button value="Reset" id="resetPasteForm">Reset</button>  '; } html += '<button class="submitForm" value="'+typeName+'" id="submit'+typeName+'Form">'+typeName+'</button> </td>' + '<tr>'; html += '</table>'; callback(html,true, formName,alwaysFlag); } else { callback(html, false, formName,alwaysFlag); } } }); return false; } function generateFormField(data) { var html = ''; var randomId = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) randomId += possible.charAt(Math.floor(Math.random() * possible.length)); var requiredField = (data.required && XMLValue(data.required[0]) == "true") ? "<span class='requiredField'>*</span>" : ""; if (!data.type) { return ""; } switch (data.type[0].text) { case "label": html = '<tr>' + '<td>' + XMLValue(data.label[0]) + ' ' + requiredField + '</td>' + '<td><label>' + XMLValue(data.value[0]) + '</label></td>' + '<tr>'; break; case "text": var size = parseInt(XMLValue(data.size[0])); if (size > 52) size = 52; html = '<tr>' + '<td><label for="' + XMLValue("meta_" + data.name[0]) + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td><input type="text" id="' + "meta_" + XMLValue(data.name[0]) + randomId + '" name="' + "meta_" + XMLValue(data.name[0]) + '" value="' + XMLValue(data.value[0]) + '" size="' + size + '" class="required_' + XMLValue(data.required[0]) + '" /></td>' + '<tr>'; break; case "textarea": var cols = parseInt(XMLValue(data.cols[0])); if (cols > 40) cols = 40; html = '<tr>' + '<td><label for="' + "meta_" + XMLValue(data.name[0]) + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td><textarea id="' + "meta_" + XMLValue(data.name[0]) + randomId + '" name="' + "meta_" + XMLValue(data.name[0]) + '" cols="' + cols + '" rows="' + XMLValue(data.rows[0]) + '" class="required_' + XMLValue(data.required[0]) + '">' + XMLValue(data.value[0]) + '</textarea></td>' + '<tr>'; break; case "combo": var options = ''; var opts = data.options[0].options_subitem; var item = 0; for (var item in opts) { if (opts[item].text) { var selected = item == 0 ? "selected" : ""; var nameValuePair = opts[item].text.split(":"); options += '<option '+selected+' value="' + extractValString(nameValuePair,1,extractValString(nameValuePair,0)) + '">' + nameValuePair[0] + '</option>'; item++; } } html = '<tr>' + '<td><label for="' + "meta_" + XMLValue(data.name[0]) + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td><select id="' + "meta_" + XMLValue(data.name[0]) + randomId + '" name="' + "meta_" + XMLValue(data.name[0]) + '" class="required_' + XMLValue(data.required[0]) + '">' + options + '</select></td>' + '<tr>'; break; case "checkbox": var options = ''; var opts = data.options[0].options_subitem; var item = 1; //I'll change this later for (var item in opts) { if (opts[item].text) { var selected = ""; //item == 0 ? "checked" : ""; var nameValuePair = opts[item].text.split(":"); options += '<span class="chkBoxPanel"><input class="chkbox required_' + XMLValue(data.required[0]) + '" type="checkbox" id="' + "meta_" + XMLValue(data.name[0]) + '" ' + selected + ' name="' + "meta_" + XMLValue(data.name[0]) + '" value="' + extractValString(nameValuePair,1,extractValString(nameValuePair,0)) + '">' + nameValuePair[0] + '</input></span>'; item++; } } html = '<tr>' + '<td><label for="' + "meta_" + XMLValue(data.name[0]) + randomId + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td>' + options + '</td>' + '<tr>'; break; case "radio": var options = ''; var opts = data.options[0].options_subitem; var item = 0; for (var item in opts) { if (opts[item].text) { var selected = item == 0 ? "checked" : ""; var nameValuePair = opts[item].text.split(":"); options += '<input type="radio" id="' + "meta_" + XMLValue(data.name[0]) + randomId + '" '+selected+' name="' + "meta_" + XMLValue(data.name[0]) + '" value="' + extractValString(nameValuePair,1,extractValString(nameValuePair,0)) + '">' + nameValuePair[0] + '</input>'; item++; } } html = '<tr>' + '<td><label for="' + "meta_" + XMLValue(data.name[0]) + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td>' + options + '</td>' + '<tr>'; break; default: break; } return html; } function extractValString(item,index,rep) { if(item.length>=index && item[index] && item[index].toString()!="undefined") { return item[index]; } else { return rep || ""; } } function XMLValue(val) { if (val && val.text) { return val.text; } else { return ""; } } function showHideUploadBtn() { if ($.cookie(o.CookieAutoUploadFlag)+"" != "true") { var uploadPopup = $("div#browserFileUpload"); var forms = uploadPopup.find("form[rel!='processed']"); if (forms.length > 0) { $("div#browserFileUpload").find("a.upload").show(); } else { $("div#browserFileUpload").find("a.upload").hide(); } } if ($("#browserFileUpload").find("a.errorOverwrite").length == 0) { $("#browserFileUpload").removeClass("attention2"); $("#browserFileUpload").find("div.attention").hide(); $(document).data("appletItemRequiresAttention", false); } } function performAutoUpload() { if ($.cookie(o.CookieAutoUploadFlag)+"" == "true") { startUploading(true); $("div#browserFileUpload").find("a.upload").fadeOut(1000); } else { $("div#browserFileUpload").find("a.upload").fadeIn(1000); return; } } function startUploading(auto, reUpload, itemsToReUpload) { if (!$(document).data("filesInProgress")) { $(document).data("filesInProgress", 0); } var filesInProgress = $(document).data("filesInProgress"); if (filesInProgress == 0) { var uploadPopup = $("div#browserFileUpload"); if ($(document).data("appletUploadItems") || reUpload) { var items = itemsToReUpload || $(document).data("appletUploadItems"); if (items.length > 0 && !$(document).data("appletItemRequiresAttention")) { var destinationPath = items[0].destinationPath; var uploadItems = ""; var allPaths = ""; var pathsAddedToUpload = []; var itemCount = 0; for (var x = 0; x < items.length; x++) { if (!pathsAddedToUpload.has(items[x].path)) { pathsAddedToUpload.push(items[x].path); uploadItems += "P" + (itemCount + 1) + "=" + items[x].path + ":::"; itemCount++; } } var targetUrl = window.location.toString().replace(hashListener.getHash().toString(), ""); targetUrl += destinationPath.substring(1); //remove first / as the baseUrl already has it $(document).data("appletUploadItems", false); //clear out the previous ones as the applet has taken them now. //TO*DO :: Completed 17/09/2010 Vipul //need to consolidate all the "file list items" into one element since the java applet uploads //everything in a combined manner. It has a status it reports of the current item. var _strMsg = ""; if(itemsToReUpload) { for(var i=0; i<itemsToReUpload.length;i++) { var filePath = unescape(itemsToReUpload[i].name); filePath = unescape(filePath.replace("//", "/")); if(_strMsg.length>0) { _strMsg += "<br />"; } _strMsg += filePath; } } else { uploadPopup.find("ul").find("li.appletUploadItem").each(function () { if($(this).hasClass("ignored"))return; var filePath = unescape($(this).find("label").text()); filePath = unescape(filePath.replace("//", "/")); if(_strMsg.length>0) { _strMsg += "<br />"; } _strMsg += filePath; }); } _strMsg = unescape(_strMsg); uploadPopup.find("ul").find("li.appletUploadItem").remove(); if(items.length>1) { _strMsg = getLocalizationKey("BrowserUploaderAdvancedUploadingFilesText").replace('{0}',items.length) +' <br />' + _strMsg; } var filelist = $('<li><label>'+ _strMsg +' <br /> </label><span></span></li>'); filelist.data("filesData", items); uploadPopup.find("ul").prepend(filelist); filelist.find("span").replaceWith("<div class='progressBar'></div>"); var progressBar = filelist.find("div.progressBar"); progressBar.progressbar({ value: 0 }).before("<div class='appletActionButtons'><a href='javascript:void(0);' class='pause'>"+ getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText") +"</a> <a href='javascript:void(0);' class='uploadCancel stop'>"+ getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") +"</a></div>"); progressBar.after("<div class='uploadPath'>"+getLocalizationKey("BrowserUploaderAdvancedUploadingFilesToText")+ decodeURIComponent(unescape(destinationPath)) + "</div>"); filelist.find(".uploadCancel").unbind().click(function () { runAppletCommand(true,"COMMAND=ACTION:::TYPE=UPLOAD:::ACTION=CANCEL"); var curElm = $(this); reportFileCompleted(progressBar, curElm.closest("li").find("label").text(), function () { //$(".refreshButton").click(); }, true); }); filelist.find(".pause").unbind().click(function (event) { event.stopPropagation(); event.preventDefault(); var curElm = $(this); if (curElm.hasClass("pause")) { runAppletCommand(true,"COMMAND=ACTION:::TYPE=UPLOAD:::ACTION=PAUSE"); curElm.removeClass("pause").addClass("resume").html(getLocalizationKey("BrowserUploaderSelectedFileResumeLinkText")); progressBar.parent().find(".time,.speed").remove(); progressBar.parent().find(".uploadPath").hide(); progressBar.addClass("paused").parent().find(".status").html(getLocalizationKey("BrowserUploaderSelectedFilePausedStatusText")); } else if (curElm.hasClass("resume")) { runAppletCommand(true,"COMMAND=ACTION:::TYPE=UPLOAD:::ACTION=RESUME"); curElm.removeClass("resume").addClass("pause").html(getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText")); progressBar.parent().find(".uploadPath").show(); progressBar.parent().find(".status").html("Resuming..."); progressBar.removeClass("paused"); } curElm.blur(); }); var $custForm = $("table.customForm","#divUploadPanel");//.clone(true); //$("body").append($custForm); if($custForm.parent().attr("id") != "custFormApplet") { $custForm.wrap("<form id='custFormApplet'></form>"); } var formItems = serializeForm($("#custFormApplet")[0]).replace(/&/g, ':::').replace(/&/g, ':::'); //$("#custFormApplet").remove(); if (!$(document).data("appletUploadsInProgress")) $(document).data("appletUploadsInProgress",0); $(document).data("appletUploadsInProgress",$(document).data("appletUploadsInProgress")+1); var resumeUpload = ":::RESUME=" + $("#chkUploadResume").is(":checked"); var compressionUpload = ":::NOCOMPRESSION=" + ($.cookie(o.CookieNoCompressionFlag) == "true");destinationPath = unescape(destinationPath); submitApplet(true,"COMMAND=UPLOAD:::URL=" + targetUrl + ":::UPLOADPATH=" + destinationPath + ":::" + uploadItems + ":::" + formItems + resumeUpload + compressionUpload, destinationPath, progressBar, function () { $(document).data("appletUploadsInProgress",$(document).data("appletUploadsInProgress")-1); try{uploadsComplete();}catch(e){} $(".refreshButton").click(); }); } else { return false; } } var forms = uploadPopup.find("form[rel!='processed']"); if (forms.length > 0) { $(forms).each(function () { var filelist = uploadPopup.find("li[rel='" + $(this).attr("id") + "']"); if (filelist) { filelist.find(".uploadCancel,.progressBar").remove(); filelist.find("span").replaceWith("<div class='progressBar'></div><span class='waiting'>[Waiting...]</span>"); filelist.find("span").after("<a href='javascript:void(0);' class='uploadCancel'>"+ getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") +"</a>").show(); var $form = $(this); var progressBar = filelist.find("div.progressBar"); filelist.find(".uploadCancel").click(function () { $form.attr("rel", "processed"); filelist.find(".waiting").remove(); reportFileCompleted(progressBar, filelist.find("label").text(), function () {}, true, true); }); } }); if (auto) { if (!$(document).data("filesInProgress")) { $(document).data("filesInProgress", 0); } var filesInProgress = $(document).data("filesInProgress"); var remainedFiles = o.MaxSimultaneousUploadAllowed - filesInProgress; if (remainedFiles > 0) { for (var i = 0; i < remainedFiles; i++) { submitForm(uploadPopup, forms, i, auto); } } } else { submitForm(uploadPopup, forms, 0); } } } } function submitApplet(signed, command, destinationPath, progressBar, callback) { runAppletCommand(signed,"COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth")); runAppletCommand(signed,command); if(progressBar) { appletProgress(progressBar, "", callback); } } function appletProgress(progressBar, fileName, callback) { var operationType = "UPLOAD"; if(progressBar.attr("rel")) { operationType = progressBar.attr("rel"); } var result = runAppletCommand(true,"COMMAND=ACTION:::TYPE="+operationType+":::ACTION=STATUS"); var o = parseJavaProps(result); if (!o || !o.status || o.status.toUpperCase().indexOf("CANCELLED:") == 0) return; updateProgressBar(o.transferedBytes * 1, o.totalBytes * 1, progressBar, fileName, callback, appletProgress); if ($(progressBar).hasClass("paused") == false) { var $buttons = $(progressBar).parent().find(".appletActionButtons"); $buttons.find(".filesProcessed").remove(); var statusText = progressBar.attr("type") && progressBar.attr("type") == ("download") ? " downloaded" : " uploaded"; var uploadingFilesStatusText = getLocalizationKey("BrowserUploaderAdvancedUploadingFilesStatusText"); uploadingFilesStatusText = uploadingFilesStatusText.replace("{0}",o.transferedItems); uploadingFilesStatusText = uploadingFilesStatusText.replace("{1}",o.totalItems); $buttons.prepend("<div class='filesProcessed'>" + uploadingFilesStatusText + " " + statusText +".</div>"); $(progressBar).after("<div class='status'>" + o.status + "</div>"); //information from the applet, current status } } function submitForm(uploadPopup, forms, i, auto) { if (forms.length > i) { var $form = $(forms[i]); var filelist = uploadPopup.find("li[rel='" + $(forms[i]).attr("id") + "']"); if (filelist.length > 0 && $form.attr("rel") != "processed") { filelist.find(".uploadCancel,.progressBar,.appletActionButtons").remove(); filelist.find("span").replaceWith("<div class='progressBar'></div>"); var progressBar = filelist.find("div.progressBar"); var destinationPath = unescape(filelist.data("fileDetails").path); $form.find("input[name='uploadPath']").val(destinationPath); progressBar.progressbar({ value: 0 }).after("<a href='javascript:void(0);' class='uploadCancel'>"+ getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") +"</a>"); progressBar.after("<div class='uploadPath'>" + getLocalizationKey("BrowserUploaderAdvancedUploadingFilesToText") + decodeURIComponent(unescape(destinationPath)) + "</div>"); filelist.find(".uploadCancel").unbind().click(function () { $("#" + $form.attr("target")).attr("src", "javascript:false;"); reportFileCompleted(progressBar, filelist.find("label").text(), function () {}, true); }); $form.prepend($("table.customForm","#divUploadPanel")); var table = $form.find("table"); $form.submit(); $("#divUploadPanel").append(table); $form.attr("rel", "processed"); if (!$(document).data("filesInProgress")) { $(document).data("filesInProgress", 0); } var filesInProgress = $(document).data("filesInProgress"); $(document).data("filesInProgress", filesInProgress + 1); $("#browserFileUpload").find("h2").addClass("spinner"); if (!$("#browserFileUpload").is(":visible")) { $("ul.topnav").find("a[href='javascript:performAction('upload');']").addClass("bouncing_loader"); } $("div.customtabs").find("a[rel='divUploadPanel']").addClass("disabledClick").addClass("padlock"); setTimeout(function () { if (auto) { checkProgress(filelist.find("div.progressBar"), $form.find("input[type='file']").attr("name"), function () { startUploading(true); }); } else { checkProgress(filelist.find("div.progressBar"), $form.find("input[type='file']").attr("name"), function () { submitForm(uploadPopup, forms, i + 1); }); } }, 500); } else { submitForm(uploadPopup, forms, i + 1); } } else { /*if (!auto) { uploadPopup.find(".closeButton").show(); $.unblockUI(); $.growlUI("Upload", "File upload completed", 1000, undefined, function() { $(".refreshButton").click(); }); }*/ //all items in the list are done uploading. try{uploadsComplete();}catch(e){} $(".refreshButton").click(); return false; } } function updateProgressBar(part1, part2, progressBar, fileName, callback, nextCheckFunction) { var now = new Date().getTime(); if (!$(progressBar).data("history")) $(progressBar).data("history",new Array()); //calculate speeds using a rolling 10 interval window. This provides a smoother speed calculation that doesn't bounce around so much to make the user concerned var h = $(progressBar).data("history"); //while (h.length > 10) h.shift(); h.push({now:now,bytes:part1}); if (h.length > 1 && $(progressBar).hasClass("paused") == false) { var elapsed = now - h[0].now; var bytes = part1 - h[0].bytes;//starting byte amount; var speed = formatBytes((bytes / elapsed) * 1024.0); var secs = ((((part2 - part1) / (bytes / elapsed)) / 1000) + 1) + ""; var remaining = formatTime(secs); var percentDone = (part1 / part2) * 100.0; var rElapsed = formatTime((elapsed / 1000) + 1 + ""); var uploadedSize = formatBytes(part1); var originalSize = formatBytes(part2); $(progressBar).data("originalSize",originalSize); $(progressBar).parent().find(".time,.speed,.status,.uploadStatusLabel").remove(); $(progressBar).prepend('<span class="uploadStatusLabel">' + uploadedSize + ' of ' + originalSize + '</span>'); var timeStampLabel = getLocalizationKey("BrowserUploaderAdvancedUploadingTimeText"); timeStampLabel = timeStampLabel.replace("{0}",rElapsed); timeStampLabel = timeStampLabel.replace("{1}",remaining); $(progressBar).after(timeStampLabel); $(progressBar).after("<div class='speed'>" + getLocalizationKey("BrowserUploaderAdvancedUploadingSpeedText") + speed + "/s</div>"); $(progressBar).progressbar("option", "value", percentDone); } if (part1 < part2) setTimeout(function () { nextCheckFunction(progressBar, fileName, callback); }, 1000); else { reportFileCompleted(progressBar, fileName, callback); } } function checkProgress(progressBar, fileName, callback) { if(!progressBar.parent()) {return;} $.ajax({ type: "POST", url: o.ajaxCallURL, data: "command=getUploadStatus&itemName=" + encodeURIComponent(fileName), success: function (response) { var responseData = response; if (responseData == null) responseData = ""; responseData = getActionResponseText(LoadXMLString(responseData)); responseData = jQuery.trim(responseData.toString()); if (responseData.indexOf("PROGRESS:") >= 0) { part1 = responseData.substring("PROGRESS:".length, responseData.indexOf("/")); part2 = responseData.substring(responseData.indexOf("/") + 1, responseData.indexOf(";")); part1 = part1 * 1; part2 = part2 * 1; //var currentFileBeingReceived = responseData.substring(responseData.indexOf(";")+1); updateProgressBar(part1, part2, progressBar, fileName, callback, checkProgress); } else if (responseData.indexOf("DONE:") >= 0) { reportFileCompleted(progressBar, fileName, callback); } else if (responseData == "null" || responseData == "") { //too quick, upload hasn't started up yet. updateProgressBar(0, 1, progressBar, fileName, callback, checkProgress); } else if (responseData.indexOf("ERROR:") >= 0) { reportFileCompleted(progressBar, fileName, callback, false, false, true, responseData); } else { reportFileCompleted(progressBar, fileName, callback, false, false, true, "ERROR:"+responseData); } }, complete: function (responseData) {}, error: function (XMLHttpRequest, textStatus, errorThrown) { $(progressBar).parent().find(".time,.speed").remove(); progressBar.replaceWith("[<span class='error'>Problem while uploading</span>]"); reportFileCompleted(progressBar, fileName, callback, false, true, true); } }); } function reportFileCompleted(progressBar, fileName, callback, cancelled, wasInWaiting, error, errorMsg) { var wasNotInWaiting = (!wasInWaiting); if (!$(document).data("filesInProgress")) { $(document).data("filesInProgress", 0); } var filesInProgress = $(document).data("filesInProgress"); if (filesInProgress > 0 && wasNotInWaiting) { $(document).data("filesInProgress", filesInProgress - 1); } if (filesInProgress == 1) { $("#browserFileUpload").find("h2").removeClass("spinner"); $("ul.topnav").find("a[href='javascript:performAction('upload');']").removeClass("bouncing_loader"); //$(".refreshButton").click(); $("div.customtabs").find("a[rel='divUploadPanel']").removeClass("disabledClick").removeClass("padlock"); } var originalSize = $(progressBar).data("originalSize"); originalSize = originalSize || ""; originalSize += " "; var parentElm = $(progressBar).parent(); var elapsed = progressBar.parent().find(".elapsed").text(); parentElm.find(".uploadPath").each(function () { if (cancelled) { $(this).text($(this).text().replace(/Uploading/g, "Cancelled uploading")); progressBar.parent().find(".time,.speed,.status").remove(); } else if(error) { $(this).text(errorMsg); } else { $(this).text($(this).text().replace(/Uploading/g, originalSize + "Uploaded")); elapsed = elapsed || "0 secs"; $(this).append(" in " + elapsed); } }); parentElm.find(".uploadCancel,.appletActionButtons").remove(); if($(progressBar).attr("rel")) { if (cancelled) { $(progressBar).replaceWith("[Download Cancelled] <a class='uploadCancel completed' href='javascript:void(0);'>"+ getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") +"</a>"); parentElm.find("a.uploadCancel").wrap("<div class='appletActionButtons'></div>").parent(); parentElm.find(".status").remove(); } else { $(progressBar).replaceWith("[Download Completed] " + originalSize + "Downloaded to: "+$(progressBar).attr("path")+" <a class='uploadCancel completed' href='javascript:void(0);'>"+ getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") +"</a>"); parentElm.find("a.uploadCancel").wrap("<div class='appletActionButtons'></div>").parent(); } } else { if (cancelled) { $(progressBar).replaceWith("[Cancelled] <a class='uploadCancel completed' href='javascript:void(0);'>"+ getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") +"</a>"); } else if (error) { $(progressBar).replaceWith("[ERROR] <a class='uploadCancel completed' href='javascript:void(0);'>"+ getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") +"</a>"); } else { $(progressBar).parent().find(".status").html(""); $(progressBar).replaceWith("["+ getLocalizationKey("BrowserUploaderSelectedFileDoneText") +"] <a class='uploadCancel completed' href='javascript:void(0);'>"+ getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") +"</a>"); } parentElm.find("a.uploadCancel").wrap("<div class='appletActionButtons'></div>").parent().prepend("<a href='javascript:void(0);' class='reupload'>"+ getLocalizationKey("BrowserUploaderSelectedFileReUploadLinkText") +"</a>"); parentElm.find("a.reupload").click(function () { var listItem = $(this).closest("li"); var itemsToReUpload = listItem.data("filesData"); if (itemsToReUpload) { listItem.remove(); startUploading(true, true, itemsToReUpload); } else { $("#" + listItem.attr("rel")).removeAttr("rel"); var dataOfFile = listItem.data("fileDetails"); var $parentElem = listItem.parent(); listItem.replaceWith('<li rel="' + listItem.attr("rel") + '"><label>' + dataOfFile.filename + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") +' " ' + dataOfFile.path + '" <span>[<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>').find("a.error").unbind().click(function () { $(this).parent().parent().remove(); showHideUploadBtn(); return true; }); listItem = $parentElem.find("li[rel='" + listItem.attr("rel") + "']"); listItem.data("fileDetails", dataOfFile); startUploading(); } }); } parentElm.find(".uploadPath").after(parentElm.find("div.appletActionButtons")); parentElm.find("a.uploadCancel").click(function () { $(this).closest("li").remove(); showHideUploadBtn(); }); parentElm.addClass("uploaded"); parentElm.find(".speed,.remained").remove(); if (callback) { callback(); } showHideUploadBtn(); performAutoUpload(); } function formatBytes(bytes) { if ((bytes / 1024).toFixed(0) == 0) return bytes + " bytes"; else if ((bytes / 1024 / 1024).toFixed(0) == 0) return (bytes / 1024).toFixed(1) + " KB"; else if ((bytes / 1024 / 1024 / 1024).toFixed(0) == 0) return (bytes / 1024 / 1024).toFixed(1) + " MB"; else if ((bytes / 1024 / 1024 / 1024 / 1024).toFixed(0) == 0) return (bytes / 1024 / 1024 / 1024).toFixed(1) + " GB"; else if ((bytes / 1024 / 1024 / 1024 / 1024 / 1024).toFixed(0) == 0) return (bytes / 1024 / 1024 / 1024 / 1024).toFixed(1) + " TB"; } function formatTime(secs) { var remaining = ""; secs = secs.substring(0, secs.indexOf(".")) * 1; var mins = (secs / 60) + ""; mins = mins.substring(0, mins.indexOf(".")) * 1; if (mins > 0) { secs -= (mins * 60); remaining = mins + " min, " + secs + " secs"; } else { if (secs < 0) { remaining = "calculating"; } else { remaining = secs + " secs"; } } return remaining; } function parseJavaProps(s) { var o = {}; if (s) { var item_props = s.split(":::"); for (var xx = 0; xx < item_props.length; xx++) { o[item_props[xx].substring(0, item_props[xx].indexOf("="))] = item_props[xx].substring(item_props[xx].indexOf("=") + 1); //set the key, and value on the o object } } return o; } function confirmExit() { if (!$(document).data("filesInProgress")) { $(document).data("filesInProgress", 0); } var filesInProgress = $(document).data("filesInProgress"); if (filesInProgress > 0) { if (filesInProgress > 1) return "Your " + filesInProgress + " files are currently uploading. If you navigate away from this page you will lose them. Are you sure you want to exit this page?"; else return filesInProgress + " file is currently uploading. If you navigate away from this page you will lose it. Are you sure you want to exit this page?"; } } function performFileSelect(obj, browserTemplate, fileName, allFiles) { var parentElem = $(obj).closest("div"); var nextCount = $("div#browserFileUpload").find("div.uploadFormPanel").length + 1; var destinationPath = hashListener.getHash().toString().replace("#", ""); destinationPath = destinationPath || "/"; var htmlForm = browserTemplate.replace(/##/g, nextCount); htmlForm = htmlForm.replace(/#DEST_PATH#/g, destinationPath); parentElem.after(htmlForm); $("#uploadDiv" + nextCount).find("input[type='file']").unbind().change(function () { fileSelect($(this), browserTemplate); }); parentElem.hide(); var v = $(obj).val(); var filesSelected = ""; if(fileName) { v = fileName; } else { v = v.match(/[^\/\\]+$/gi); } v = v.toString(); if(filesSelected.length == 0 && v.length>0) { filesSelected = v; } if (v != '') { if(allFiles) { var filesAvailableOnDir = []; var filesAvailableOnList = []; for(var i=0;i<allFiles.length;i++) { var fileName = allFiles[i]; if(checkFileAvailalble(fileName)) { filesAvailableOnDir.push(fileName) } if(checkFileAvailalbleInSelectedList(fileName, destinationPath)) { filesAvailableOnList.push(fileName) } } var curItem = $('<li rel="' + parentElem.find("form").attr("id") + '"><label>' + filesSelected + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") +' " ' + unescape(destinationPath) + '" <span>[<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>'); $("ul.filesSelected").prepend(curItem).find("a.error").unbind().click(function () { $(this).parent().parent().remove(); parentElem.hide(); showHideUploadBtn(); return true; }).closest("li").data("fileDetails", { "filename": v, "path": destinationPath }); var groupItem = curItem.find("ul.groupedItems"); if(filesAvailableOnDir.length>0) { var fileAvailableInDir = false; for(var item in filesAvailableOnDir) { var curFile = filesAvailableOnDir[item]; if($.type(curFile) === "string") { groupItem.find("li[rel='"+curFile+"']").append(" <label> | "+ getLocalizationKey("BrowserUploaderSelectedFileExistsText") +" : <a class=\"errorOverwrite\" href=\"javascript:void(0);\">"+ getLocalizationKey("BrowserUploaderSelectedFileIgnoreLinkText") +"</a></label>").find(".errorOverwrite").unbind().click(function () { $("#" + $(this).closest("li").attr("rel")).removeAttr("rel"); $(this).parent().replaceWith("<label class='popupNote'>"+ getLocalizationKey("BrowserUploaderSelectedFileWillBeOverwrittenText") +"</label>"); if (groupItem.find("a.errorOverwrite").length == 0) { $("#" + parentElem.find("form").attr("id")).removeAttr("rel"); } if ($("#browserFileUpload").find("a.errorOverwrite").length == 0) { $("#browserFileUpload").removeClass("attention2"); $("#browserFileUpload").find("div.attention").hide(); } performAutoUpload(); return false; }); fileAvailableInDir = true; } } if(fileAvailableInDir) { $("#browserFileUpload").addClass("attention2"); $("#browserFileUpload").find("div.attention").show(); $("#" + parentElem.find("form").attr("id")).attr("rel", "processed"); } } if(filesAvailableOnList.length>0) { var fileAvailableInList = []; for(var item in filesAvailableOnList) { var curFile = filesAvailableOnList[item]; if($.type(curFile) === "string") { groupItem.find("li[rel='"+curFile+"']").remove(); fileAvailableInList.push(curFile); } } if(fileAvailableInList.length>0) { if(fileAvailableInList.length>1) { $.growlUI(getLocalizationKey("BrowserUploaderMultiFileAddedAlreadyText"), getLocalizationKey("BrowserUploaderMultiFileAddedAlreadyDetailsText").replace("{0}",fileAvailableInList.join(",<br/>") ), o.GrowlTimeout, "growlError", true); } else { $.growlUI(getLocalizationKey("BrowserUploaderFileAddedAlreadyText"), getLocalizationKey("BrowserUploaderFileAddedAlreadyDetailsText").replace("{0}",fileAvailableInList.join("<br/>") + "<br />"), o.GrowlTimeout, "growlError", true); } } } if(groupItem.find("li").length==0) { groupItem.parent().remove(); } showHideUploadBtn(); performAutoUpload(); } else { if (checkFileAvailalbleInSelectedList(v, destinationPath)) { $.growlUI(getLocalizationKey("BrowserUploaderFileAddedAlreadyText"), getLocalizationKey("BrowserUploaderFileAddedAlreadyDetailsText").replace("{0}",v), o.GrowlTimeout, "growlError", true); $("#" + parentElem.find("form").attr("id")).attr("rel", "processed"); return false; } else if (checkFileAvailalble(v)) { $("#browserFileUpload").addClass("attention2"); $("#browserFileUpload").find("div.attention").show(); $("ul.filesSelected").prepend('<li rel="' + parentElem.find("form").attr("id") + '"><label>' + filesSelected + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") +' " ' + unescape(destinationPath) + '" <span><span> | '+ getLocalizationKey("BrowserUploaderSelectedFileExistsText") +' : <a class="errorOverwrite" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileOverwriteText") +'</a></span> [<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>').find("a.error").unbind().click(function () { $(this).parent().parent().remove(); parentElem.hide(); showHideUploadBtn(); if ($("#browserFileUpload").find("a.errorOverwrite").length == 0) { $("#browserFileUpload").removeClass("attention2"); $("#browserFileUpload").find("div.attention").hide(); } return true; }).closest("li").data("fileDetails", { "filename": v, "path": destinationPath }); var recentlyAdded = $("ul.filesSelected").find("li:first"); recentlyAdded.effect("highlight", {color:"red"}, 2000); $("#" + parentElem.find("form").attr("id")).attr("rel", "processed"); $("ul.filesSelected").find(".errorOverwrite").unbind().click(function () { $("#" + $(this).closest("li").attr("rel")).removeAttr("rel"); $(this).parent().replaceWith("<span class='popupNote'>"+ getLocalizationKey("BrowserUploaderSelectedFileWillBeOverwrittenText") +"</span>"); if ($("#browserFileUpload").find("a.errorOverwrite").length == 0) { $("#browserFileUpload").removeClass("attention2"); $("#browserFileUpload").find("div.attention").hide(); } performAutoUpload(); return false; }); return false; } else { $("ul.filesSelected").prepend('<li rel="' + parentElem.find("form").attr("id") + '"><label>' + filesSelected + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") +' " ' + unescape(destinationPath) + '" <span>[<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>').find("a.error").unbind().click(function () { $(this).parent().parent().remove(); parentElem.hide(); showHideUploadBtn(); return true; }).closest("li").data("fileDetails", { "filename": v, "path": destinationPath }); } } showHideUploadBtn(); performAutoUpload(); } }; function checkFileAvailalble(name, isFolder) { name = name.toLowerCase(); var fileData = $(document).data("filesList"); for (var file in fileData) { if (isFolder) { if (fileData[file][0] == "DIR" && fileData[file][1].toLowerCase() == name) return true; } else { if (fileData[file][0] == "FILE" && fileData[file][1].toLowerCase() == name) return true; } } return false; } function checkFileAvailalbleInSelectedList(name, path) { name = name.toLowerCase(); path = path.toLowerCase(); var fileData = $("li", "ul.filesSelected"); var fileAdded = false; fileData.each(function () { if($(this).hasClass("groupItem")) { if($(this).hasClass("uploaded") || $(this).hasClass("ignored"))return false; $(this).data("fileDetails",{ filename:$(this).attr("rel"), path:$(this).attr("dest") }); var curData = $(this).data("fileDetails"); if (curData && curData.filename.toLowerCase() == name && curData.path.toLowerCase() == path) { fileAdded = true; } } else { if($(this).hasClass("uploaded")|| $(this).hasClass("ignored"))return false; var curData = $(this).data("fileDetails"); if (curData && curData.filename.toLowerCase() == name.toLowerCase() && curData.path.toLowerCase() == path.toLowerCase()) { fileAdded = true; } } }); return fileAdded; } function handleBrowseComplete(forDownload) { var result = {}; if($("#javaApplet").length>0) result = $("#javaApplet")[0].getASyncResult(window.command_id); else { alert("Applet failed while uploading"); return false; } if (result) { if (forDownload) { handleFileSelectToDownload(result); } else { handleFileSelectToUpload(result); } } else { setTimeout(function () { handleBrowseComplete(forDownload); }, 200); } } function handleFileSelectToDownload(result) { result = result + ""; //need to conver this JavaRuntimeObject to a String var destinationPath = hashListener.getHash().toString().replace("#", "") || "/"; var itemList = parseJavaProps(result.split(";;;")[0]); itemList.destinationPath = destinationPath; var targetUrl = window.location.toString().replace(hashListener.getHash().toString(), ""); var stringToCopy = ""; if (!$(document).data(o.BasketDataKey)) { $(document).data(o.BasketDataKey, new Array()); } var ItemsInTheBasket = $(document).data(o.BasketDataKey); for (var i = 0; i < ItemsInTheBasket.length; i++) { var j = i+1; stringToCopy += "P"+j+"=" +ItemsInTheBasket[i]+":::"; }; $(document).data(o.BasketDataKey, new Array()); rebuildBasket(""); if (stringToCopy.length > 0) { stringToCopy = stringToCopy.substring(0,stringToCopy.length-3); } var progressBar = $("<li><div class='progressBar'></div></li>"); $("ul.filesSelectedInBasket").prepend(progressBar); progressBar = progressBar.find("div"); progressBar.attr("type","download"); progressBar.before("<div class='appletActionButtons'><a href='javascript:void(0);' class='pause'>"+ getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText") +"</a> <a href='javascript:void(0);' class='uploadCancel stop'>"+ getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") +"</a></div>"); progressBar.parent().find(".uploadCancel").unbind().click(function () { runAppletCommand(true,"COMMAND=ACTION:::TYPE=DOWNLOAD:::ACTION=CANCEL"); var curElm = $(this); reportFileCompleted(progressBar, itemList.path, function () { }, true); curElm.blur(); }); progressBar.parent().find(".pause").unbind().click(function () { var curElm = $(this); if (curElm.hasClass("pause")) { runAppletCommand(true,"COMMAND=ACTION:::TYPE=DOWNLOAD:::ACTION=PAUSE"); curElm.removeClass("pause").addClass("resume").html(getLocalizationKey("BrowserUploaderSelectedFileResumeLinkText")); progressBar.parent().find(".time,.speed").remove(); progressBar.parent().find(".uploadPath").hide(); progressBar.addClass("paused").parent().find(".status").html(getLocalizationKey("BrowserUploaderSelectedFilePausedStatusText")); } else if (curElm.hasClass("resume")) { runAppletCommand(true,"COMMAND=ACTION:::TYPE=DOWNLOAD:::ACTION=RESUME"); curElm.removeClass("resume").addClass("pause").html(getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText")); progressBar.parent().find(".uploadPath").show(); progressBar.parent().find(".status").html("Resuming..."); progressBar.removeClass("paused"); } curElm.blur(); }); runAppletCommand(true,"COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth")); progressBar.progressbar({ value: 0 }).attr("rel","DOWNLOAD").attr("path",itemList.path); $("#submitActionBasket").find(".clearCompleted").hide(); var compressionUpload = ":::NOCOMPRESSION=" + ($.cookie(o.CookieNoCompressionFlag) == "true"); submitApplet(true,"COMMAND=DOWNLOAD:::URL=" + targetUrl + ":::PATH=" + itemList.path + ":::" + stringToCopy + compressionUpload, itemList.destinationPath, progressBar, function(){ $("#submitActionBasket").find(".clearCompleted").show(); }); } function setupDND() { if (!$(document).data("dndConfigured")) { $("#javaAppletDivHolder").css({'position':'absolute','visibility':'hidden'}); $("ul.filesSelected","#FileUploadSummary").css("height","170px"); $(document).data("dndConfigured", true); addEvent($(document), "dragenter", function (e) { $(document).data("dndActiveAt",new Date()*1); if (e.preventDefault) e.preventDefault(); if (!$(document).data("appletLoaded")) { $.growlUI("Java Applet Not Loaded", "You must first click the 'Advanced Browse...' button before drag and drop will be enabled.", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return false; } window.showDrop(); return false; }); addEvent($(document), "dragover", function cancel(e) { $(document).data("dndActiveAt",new Date()*1); if (e.preventDefault) e.preventDefault();return false; }); addEvent($(document), "drop", function (e) { if (e.preventDefault) e.preventDefault(); window.cancelDrop(true); return false; }); } } function getX(oElement) { var iReturnValue = 0; while( oElement != null ) { iReturnValue += oElement.offsetLeft; oElement = oElement.offsetParent; } return iReturnValue; } function getY(oElement) { var iReturnValue = 0; while( oElement != null ) { iReturnValue += oElement.offsetTop; oElement = oElement.offsetParent; } return iReturnValue; } window.showDrop = function() { if (!$(document).data("appletLoaded")) return false; if($.browser.msie) { $("#javaAppletDivHolder").css({'position':'relative','visibility':'visible'}); $("ul.filesSelected","#FileUploadSummary").css("height","170px"); $("#javaAppletDiv").addClass('dragOver'); $("#javaAppletDiv").css({ "position":"absolute", "margin":"0px", "padding":"0px" }); $("#javaAppletDiv").css("width",$("#javaAppletDivHolder")[0].offsetWidth); $("#javaAppletDiv").css("left",getX($("#javaAppletDivHolder")[0])); $("#javaAppletDiv").css("top",getY($("#javaAppletDivHolder")[0]) + 10); } else { $("#javaAppletDivHolder").css({'position':'relative','visibility':'visible'}); $("ul.filesSelected","#FileUploadSummary").css("height","170px"); $("#javaAppletDiv").addClass('dragOver'); $("#javaAppletDiv").css("width",$("#javaAppletDivHolder")[0].offsetWidth); $("#javaAppletDiv").css("left",getX($("#javaAppletDivHolder")[0])); $("#javaAppletDiv").css("top",getY($("#javaAppletDivHolder")[0])); } } window.cancelDrop = function (skipIfIE) { if (skipIfIE && navigator.appName.indexOf("Explorer") >= 0) return false; if (navigator.appName.indexOf("Explorer")<0 || $(document).data("uploadWindowHidden")) { $("#javaAppletDiv").removeClass("dragOver"); $("#javaAppletDivHolder").css({'position':'absolute','visibility':'hidden'}); $("ul.filesSelected","#FileUploadSummary").css("height","230px"); $("#javaAppletDiv").css("left","-5000px"); } } window.handleFileSelectToUpload = function (result, dropped) { result = result + ""; //need to conver this JavaRuntimeObject to a String var destinationPath = hashListener.getHash().toString().replace("#", "") || "/"; var itemList = new Array(); var items = result.split(";;;"); for (var x = 0; x < items.length; x++) { var o = parseJavaProps(items[x]); o.destinationPath = destinationPath; itemList[itemList.length] = o; } if (itemList.length > 0) { if (!$(document).data("appletUploadItems")) { $(document).data("appletUploadItems", []); } var fileAvailableInList = []; for (var i = 0; i < itemList.length; i++) { if (itemList[i].name) { var v = itemList[i].name; var itemId = itemList[i].path; var isResume = $("#chkUploadResume").is(":checked"); if (checkFileAvailalbleInSelectedList(v, destinationPath)) { fileAvailableInList.push(v); } else if (checkFileAvailalble(v) && !isResume) { $("#browserFileUpload").addClass("attention2"); $("#browserFileUpload").find("div.attention").show(); var recentlyAdded = $('<li class="appletUploadItem" rel="' + itemId + '"><label>' + v + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") +' " ' + unescape(destinationPath) + '" <span><span> | '+ getLocalizationKey("BrowserUploaderSelectedFileExistsText") +' : <a class="errorOverwrite" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileOverwriteText") +'</a></span> [<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>'); $("ul.filesSelected").prepend(recentlyAdded); recentlyAdded.data("appletItems",itemList[i]).find("a.error").unbind().click(function () { var appletUploadItems = $(document).data("appletUploadItems"); var key = $(this).closest("li").data("appletItems"); if (appletUploadItems.indexOf(key) >= 0) { appletUploadItems.remove(appletUploadItems.indexOf(key)); $(document).data("appletUploadItems", appletUploadItems); } $(this).parent().parent().remove(); showHideUploadBtn(); return false; }).closest("li").data("fileDetails", { "filename": v, "path": destinationPath }); $(document).data("appletItemRequiresAttention", true); var curItem = itemList[i]; recentlyAdded.find(".errorOverwrite").unbind().click(function () { $(document).data("appletUploadItems")[$(document).data("appletUploadItems").length] = curItem; $(this).parent().replaceWith("<span class='popupNote'>"+ getLocalizationKey("BrowserUploaderSelectedFileWillBeOverwrittenText") +"</span>"); showHideUploadBtn(); performAutoUpload(); return false; }); } else { var recentlyAdded = $('<li class="appletUploadItem" rel="' + itemId + '"><label>' + v + '</label> | '+ getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span>[<a class="error" href="javascript:void(0);">'+ getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") +'</a>]</span></li>'); $("ul.filesSelected").prepend(recentlyAdded); recentlyAdded.data("appletItems",itemList[i]).find("a.error").unbind().click(function () { var appletUploadItems = $(document).data("appletUploadItems"); var key = $(this).closest("li").data("appletItems"); if (appletUploadItems.indexOf(key) >= 0) { appletUploadItems.remove(appletUploadItems.indexOf(key)); $(document).data("appletUploadItems", appletUploadItems); } $(this).parent().parent().remove(); showHideUploadBtn(); performAutoUpload(); return false; }).closest("li").data("fileDetails", { "filename": v, "path": destinationPath }); $(document).data("appletUploadItems")[$(document).data("appletUploadItems").length] = itemList[i]; } } } if(fileAvailableInList.length>0) { if(fileAvailableInList.length>1) { $.growlUI(getLocalizationKey("BrowserUploaderMultiFileAddedAlreadyText"), getLocalizationKey("BrowserUploaderMultiFileAddedAlreadyDetailsText").replace("{0}",fileAvailableInList.join("<br/>")), o.GrowlTimeout, "growlError", true); } else { $.growlUI(getLocalizationKey("BrowserUploaderFileAddedAlreadyText"), getLocalizationKey("BrowserUploaderFileAddedAlreadyDetailsText").replace("{0}",fileAvailableInList.join("<br/>")), o.GrowlTimeout, "growlError", true); } } if(!dropped) { performAutoUpload(); }/* else { if(!$("#javaAppletDiv").hasClass("dragOver")) { performAutoUpload(); } else { startAutoUploadAfterDrop() } }*/ return false; } } function startAutoUploadAfterDrop() { if (!$("#javaAppletDiv").hasClass("dragOver")) { setTimeout(startAutoUploadAfterDrop, 500); } else { performAutoUpload(); } } function handleAppletBrowse(forDownload) { if (forDownload) { runAppletCommand(true,"COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth")); window.command_id = runAppletCommand(true,"COMMAND=BROWSE:::DIRECTORIES_ONLY=true", true); } else { window.command_id = runAppletCommand(true,"COMMAND=BROWSE", true); } handleBrowseComplete(forDownload); } function runAppletCommand(signed, command, async) { try { if (async) { return document.getElementById("javaApplet"+(signed?"":"U")).doCommandASync(command) + ""; } else { return document.getElementById("javaApplet"+(signed?"":"U")).doCommandSync(command) + ""; // +"" is needed to convert form the Java object type to a JavaScript string type } } catch (e) { } } function loadApplet(signed,callback) { if (!navigator.javaEnabled()) { $.growlUI("Java Required", "Java must be installed for the advanced functions to work.<br/><br/>Please go to: <a target=\"_blank\" href=\"http://www.java.com/\" class=\"whiteError\">http://www.java.com/</a>", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); return; } var s = "<div id='dragdropAppletDiv' style='background-color:#F0F7CD;margin:0px;'>"+ "<object name=\"javaApplet"+(signed?"":"U")+"\" id=\"javaApplet"+(signed?"":"U")+"\" type=\"application/x-java-applet\" code=\"com.crushftp.tunnel.Applet.class\" archive=\"/WebInterface/CrushTunnel"+(signed?"":"U")+".jar\" width=\"98%\" height=\"96\" background=\"F0F7CD\"> <param name=\"background-color\" value=\"#F0F7CD\"></object></div>"; if (signed) { $("div#browserFileUpload").find(".advancedBrowse").after("<span class='spinner' style='display:inline-block;padding-left:18px;margin-left:3px;'>Loading...</span>"); $("div#submitActionBasket").find(".advanced").addClass("spinner").addClass("spinnerAdvanced"); } isAppletReady(signed,callback); setTimeout(function () { $("#javaAppletDiv"+(signed?"":"U")).html(s); }, 100); } function isAppletReady(signed, callback) { try { if (document.getElementById("javaApplet"+(signed?"":"U")).test() == "OK") { $(document).data("appletLoaded"+(signed?"":"U"), true); if (signed) { $("div#browserFileUpload").find(".advancedBrowse").next().remove(); $("div#submitActionBasket").find(".advanced").removeClass("spinner").removeClass("spinnerAdvanced"); $("#advancedBrowseOptions").show(1000); } runAppletCommand(signed,"COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth")); if (callback) callback(); } else setTimeout(function () { isAppletReady(signed,callback); }, 100); } catch (e) { setTimeout(function () { isAppletReady(signed,callback); }, 1000); } } function highlightPasteButton() { if (($(document).data(o.CookieCopiedFiles) && $(document).data(o.CookieCopiedFiles).length > 0)) { $("div.mainNavigation").find("a:contains('Paste')").addClass("starredMenu"); } else { $("div.mainNavigation").find("a:contains('Paste')").removeClass("starredMenu"); } } function loadPopupContent() { /* Data to POST to receive file listing */ $("#popupContent").find("input#txtNewFolder").keyup(function (evt) { var evt = (evt) ? evt : ((event) ? event : null); if (evt.keyCode == 13) { makedir(); return false; } else if (evt.keyCode == 27) { $.unblockUI(); return false; } }); var varHideItemsStartingWithDot = $.cookie(o.CookieHideItemStartingWithDot); varHideItemsStartingWithDot = varHideItemsStartingWithDot == "true"; if (varHideItemsStartingWithDot) { $("#hideItemsStartingWithDot").attr("checked", "checked"); } else { $("#hideItemsStartingWithDot").removeAttr("checked"); } var varHideCheckBoxColumn = $.cookie(o.CookieHideCheckBoxColumn); varHideCheckBoxColumn = varHideCheckBoxColumn == "true"; if (varHideCheckBoxColumn) { $("#hideCheckBoxColumn").attr("checked", "checked"); } else { $("#hideCheckBoxColumn").removeAttr("checked"); } var varHideFilter = $.cookie(o.CookieHideFilter); varHideFilter = varHideFilter == "true"; if (varHideFilter) { $("#hideFilter").attr("checked", "checked"); } else { $("#hideFilter").removeAttr("checked"); } if ($.cookie(o.CookieAutoUploadFlag)+"" == "true") { $("#autoUploadFlag").attr("checked", "checked"); } else { $("#autoUploadFlag").removeAttr("checked"); } if ($.cookie(o.CookieAutoAppletFlag)+"" == "true") { $("#autoAppletFlag").attr("checked", "checked"); } else { $("#autoAppletFlag").removeAttr("checked"); } if ($.cookie(o.CookieNoCompressionFlag)+"" == "true") { $("#noCompressionFlag").attr("checked", "checked"); } else { $("#noCompressionFlag").removeAttr("checked"); } initTabs(); $("#shareOptionDiv").data("html", $("#shareOptionDiv").html()); } window.performDeleteAction = function(el,callback) { if($(document).data("slideShowOnly")) { var fileName = encodeURIComponent(el); var obj = { command: "delete", names: fileName, random: Math.random() }; $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { $.growlUI("Problem while deleting", "There was a problem while deleting. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); if(callback)callback(false); } else{ if(callback)callback(true); } }, error: function () { $.growlUI("Problem while deleting", "There was a problem while trying to delete this file. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); } else if (currentView() == "Thumbnail") { var $curElem = $(el); var fileName = encodeURIComponent($curElem.find("a:first").attr("rel")); var obj = { command: "delete", names: fileName, random: Math.random() }; $curElem.addClass("wait"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { $.growlUI("Problem while deleting", "There was a problem while deleting. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { $curElem.remove(); } }, complete: function () { $curElem.removeClass("wait"); }, error: function () { $.growlUI("Problem while deleting", "There was a problem while trying to delete this file. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); } else { var $curElem = $(el); var fileName = encodeURIComponent($curElem.find("a").attr("rel")); var obj = { command: "delete", names: fileName, random: Math.random() }; $curElem.addClass("wait"); $.ajax({ type: "POST", url: o.ajaxCallURL, data: obj, success: function (response) { var responseText = getActionResponseText(LoadXMLString(response)); if (responseText.length > 0) { $.growlUI("Problem while deleting", "There was a problem while deleting. Error : " + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } else { if ($curElem.hasClass("directory")) { removeDirectoryFromTree($curElem.closest("tr")); reBuildListing(window.curTreeItems); } else if ($curElem.hasClass("fileItem") || $curElem.hasClass("fileTR")) { $curElem.closest("tr").remove(); } } }, complete: function () { $curElem.removeClass("wait"); }, error: function () { $.growlUI("Problem while deleting", "There was a problem while trying to delete this file. Please retry", o.GrowlTimeout, "growlError", o.GrowlWithCloseButton); } }); } } function blockFileListingUI(flag) { if (flag) { /* o.FileListingElement.block({ message: 'Processing...', css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', color: '#fff' } });*/ $(".mainProcessIndicator").show(); } else { //o.FileListingElement.unblock(); $(".mainProcessIndicator").fadeOut(500); } } function toggleCheckBoxes(el, val) { if (val == 1) { var chkBox = $(el); chkBox.attr("checked", "checked"); toggleCheckBoxesAll($(el).closest("table"), chkBox.is(":checked")); toggleMainCheckbox(chkBox.closest("table")); } else if (val == 0) { var chkBox = $(el); chkBox.removeAttr("checked"); toggleCheckBoxesAll($(el).closest("table"), chkBox.is(":checked")); toggleMainCheckbox(chkBox.closest("table")); } else { var chkBox = $(el); chkBox.removeAttr("checked"); toggleCheckBoxesAll($(el).closest("table"), chkBox.is(":checked"), true); toggleMainCheckbox(chkBox.closest("table")); } } function toggleCheckBoxesAll(elem, status, toggle) { checkUnCheckDirectory( $(elem).find("TR.jqueryFileTree"), status, true, toggle); } function selectDeselectAllItems(flag, toggle) { if (currentView() != "Thumbnail") { var tbl = $("#filesListing").find("table"); toggleCheckBoxesAll(tbl, flag, toggle); toggleMainCheckbox(tbl, flag, toggle); } else { if(toggle) { $("#filesContainerDiv").find("li:visible").each(function(){ if($(this).hasClass("fileBoxSelected")) { $(this).removeClass("fileBoxSelected"); } else { $(this).addClass("fileBoxSelected"); } }); } else { if(flag) { $("#filesContainerDiv").find("li:visible").addClass("fileBoxSelected"); } else { $("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected"); } } } } function isChecked(elem) { var allChecked = true; $(elem).find("TR.jqueryFileTree:visible").each(function () { if (!$(this).find("input.chkBox:visible").is(":checked")){ allChecked = false; } }); return allChecked; } function toggleMainCheckbox(elem, status) { status = status || isChecked(elem); if (status) { $(elem).find("input.chkBoxAll").attr("checked", "checked"); } else { $(elem).find("input.chkBoxAll").removeAttr("checked"); } } function checkUnCheckDirectory(trElems, check, rootDir, toggle) { $(trElems).each(function () { if (rootDir) { $(this).find("td.directory").each(function () { checkUnCheckDirectory( $(this).closest("table").find('TR[rel="' + $(this).find('a').attr('rel') + '"]').find(".chkBox:visible").parent(), check, undefined, toggle); }); } else { $(this).parent().find("td.directory").each( function () { checkUnCheckDirectory( $(this).closest("table").find('TR[rel="' + $(this).find('a').attr('rel') + '"]').find(".chkBox:visible").parent(), check, undefined, toggle); }); } if (toggle) { var checkedElems = $(this).find(".chkBox:visible:checked"); var unCheckedElems = $(this).find(".chkBox:visible").not(":checked"); checkedElems.removeAttr("checked"); unCheckedElems.attr("checked", "checked"); } else { if (check) { $(this).find(".chkBox:visible").attr("checked", "checked"); } else { $(this).find(".chkBox:visible").removeAttr("checked"); } } }); } function currentView() { if(!$("body").data("currentView")) { var currentViewType = $.cookie(o.ViewCookieName); if (currentViewType && currentViewType == "Thumbnail") { $("body").data("currentView", currentViewType); } else { $("body").data("currentView", "Tree"); } } return $("body").data("currentView"); } function changeView(type, refresh) { $("body").data("currentView", type); var options = { path: '/', expires: 10 }; $.cookie(o.ViewCookieName, type, options); if (type == "Thumbnail") { $("#filesContainer").hide(); $("#filesContainerDiv").show(); $("#slider").show(); } else { $("#filesContainerDiv").hide(); $("#filesContainer").show(); $("#slider").hide(); } if (refresh) { blockFileListingUI(true); if ($(document).data("searchData")) { if (currentView() == "Thumbnail") { renderListing($("#filesContainerDiv"), "", false, false, $(document).data("searchData"), true); } else { renderListing($("#filesContainer"), "", false, false, $(document).data("searchData"), true); } } else { if (type == "Thumbnail") { showTree($("#filesContainerDiv"), "", true, true); } else { showTree($("#filesContainer"), "", true, true); } } } } function mapXmlToTable(msg, table, disablePrivsSet, folderExpand) { if (msg && msg.childNodes && msg.childNodes.length > 0) { var rows = msg.getElementsByTagName("listing"); var items = IE(rows[0]).textContent; eval(items); window.curTreeItems = window.curTreeItems ? window.curTreeItems : window.l ? window.l : {}; if(!disablePrivsSet) { $(document).data("folderPrivs", false); var rowsPriv = msg.getElementsByTagName("privs"); if(rowsPriv && rowsPriv.length>0) { var privs = IE(rowsPriv[0]).textContent; if(privs) { $(document).data("folderPrivs", privs); } } } if(folderExpand) { var rel = folderExpand.find("a").attr("rel"); for(var i=0;i<curTreeItems.length;i++) { var curItem = curTreeItems[i]; if(escape(curItem.href_path + "/") == rel) { for(var j= l.length-1; j>=0;j--) { var subItem = l[j]; subItem.ItemType = "subDir"; curTreeItems.splice(i+1, 0, subItem); } i = curTreeItems.length; } } return generateListing(curTreeItems); } else { curTreeItems = l; return generateListing(); } } else { return ""; } } function filterItem(phrase) { if(window.last_search_item && window.last_search_item === phrase){ return false; } var files = 0; var dirs = 0; window.last_search_item = phrase; var curListItems = l; if (currentView() != "Thumbnail") { curListItems = window.curTreeItems; } var matchedItems = []; var hasWords = function (str, words) { if(!str || !words || str.length == 0 || words.length == 0) return false; var text = str.toLowerCase(); for (var i = 0; i < words.length; i++) { if (text.indexOf(words[i]) === -1) return false; } return true; } if(curListItems && curListItems.length>0) { for(var i = 0; i <= curListItems.length; i++) { var opt = curListItems[i]; if(opt) { if (currentView() == "Thumbnail") { var words = phrase.toLowerCase().split(" "); if(hasWords(opt.name, words)) { matchedItems.push(opt); if(opt.type == "FILE") { files += 1; } else { dirs += 1; } } } else { var words = phrase.toLowerCase().split(" "); if(hasWords(opt.name, words)) { matchedItems.push(opt); if(opt.type == "FILE") { files += 1; } else { dirs += 1; } } else if(hasWords(opt.keywords, words)) { matchedItems.push(opt); if(opt.type == "FILE") { files += 1; } else { dirs += 1; } } } } } } window.current_page = o.pagingCurrentPage = 0; if(phrase.length>0) { window.filteredItems = { filesCount :files, dirsCount: dirs }; } else { window.filteredItems = false; } window.matchedItems = matchedItems; reBuildListing(window.matchedItems); $.unblockUI(); } function generateListing(customItem) { var curDirItems = customItem ? customItem : l; if (currentView() != "Thumbnail") { curDirItems = customItem ? customItem : window.curTreeItems; } var CookiePageSize = getPageSize(); var currentPage = o.pagingCurrentPage; var cookiePageSizeIsValid = (CookiePageSize - 0) == CookiePageSize && CookiePageSize.length > 0; if(curDirItems && curDirItems.length>0) { var fileList = []; var maxEntries = curDirItems.length; var start = 0; if(cookiePageSizeIsValid) { CookiePageSize -= 1; var page = currentPage == 0 ? 0 : currentPage; if(page>0) { maxEntries = CookiePageSize * (page+1); start = CookiePageSize * page; } else { maxEntries = CookiePageSize; } } for(var i = start; i <= maxEntries; i++) { var x = i; var opt = curDirItems[i]; if(opt) { var keywords = opt.keywords; if (keywords.length >= o.keywordsCharLimit) { keywords = keywords.substr( 0, o.keywordsCharLimit) + "..."; } if (currentView() == "Thumbnail") { if (opt.type === 'DIR') { var dirTemplate = '<li class="vtip fileBox directoryThumb" index="'+x+'" name="'+opt.name+'" title="<div class=\'tooltip-content\'><strong>' + getLocalizationKey('TooltipNameLabelText') + ' : </strong>'+ opt.name + '<br /><strong>' + getLocalizationKey('TooltipModifiedLabelText') + ' : </strong>' + opt.dateFormatted + '<br /><strong>' + getLocalizationKey('TooltipKeywordsLabelText') + ' : </strong>' + keywords + '</div>" privs="'+opt.privs+'" size="'+opt.sizeFormatted+'" fulldate="'+opt.modified+'" Date="'+opt.dateFormatted+'" Keywords="'+keywords+'" preview="'+opt.preview+'"><span class="fileSelectionMark"></span><div>' + '<div class="imgBox"><div class="imgWrapper">' + '<table cellspacing="0" cellpadding="0" align="center">' + '<tbody>' + '<tr>' + '<td valign="middle" align="center">' + '<a class="imgLink" rel="'+ escape(opt.href_path) + "/"+'" href="'+opt.href_path+'">' + '<img alt="'+opt.name+'" title="'+opt.name+'" style="border: 0px none;" src="'+o.fileFolder+'">' + '</a>' + '</td>' + '</tr>' + '</tbody>' + '</table></div>' + '</div>' + '</div>' + '<div class="imgTitle">' + '<a rel="'+opt.root_dir+'" href="'+opt.href_path+'">'+opt.name+'</a>' + '</div>' + '</li>'; fileList.push(dirTemplate); } else if (opt.type === 'FILE') { var fileTemplate = '<li class="vtip fileBox fileThumb" index="'+x+'" name="'+opt.name+'" title="<div class=\'tooltip-content\'><strong>' + getLocalizationKey('TooltipNameLabelText') + ' : </strong>' + opt.name + '<br /><strong>' + getLocalizationKey('TooltipSizeLabelText') + ' : </strong>' + opt.sizeFormatted + '<br /><strong>' + getLocalizationKey('TooltipModifiedLabelText') + ' : </strong>' + opt.dateFormatted + '<br /><strong>' + getLocalizationKey('TooltipKeywordsLabelText') + ' : </strong>' + keywords + '</div>" privs="'+opt.privs+'" size="'+opt.sizeFormatted+'" fulldate="'+opt.modified+'" Date="'+opt.dateFormatted+'" Keywords="'+keywords+'" preview="'+opt.preview+'"><span class="fileSelectionMark"></span><div>' + '<div class="imgBox"><div class="imgWrapper">' + '<table cellspacing="0" cellpadding="0" align="center">' + '<tbody>' + '<tr>' + '<td valign="middle" align="center">' + '<a class="imgLink" rel="'+escape(opt.href_path)+'" href="'+opt.href_path+'">' + '<img alt="'+opt.name+'" title="'+opt.name+'" style="border: 0px none;" src="'+o.spinerImage+'">' + '</a>' + '</td>' + '</tr>' + '</tbody>' + '</table></div>' + '</div>' + '</div>' + '<div class="imgTitle">' + '<a rel="'+opt.root_dir+'" href="'+opt.href_path+'">'+opt.name+'</a>' + '</div>' + '</li>'; fileList.push(fileTemplate); } } else { var subdirClass = opt.ItemType == "subDir" ? "subdirectory" : ""; var attrs = "name='"+opt.name+"' size='"+opt.sizeFormatted+"' date='"+opt.dateFormatted+"' keywords='"+keywords+"' preview='"+opt.preview+"' privs='"+opt.privs+"'"; if (opt.type === 'DIR') { if (keywords.length >= o.MaximumLengthAllowedForKeywordsString) { keywords = keywords.substr( 0, o.MaximumLengthAllowedForKeywordsString) + "..."; } fileList.push('<tr rootdir="'+opt.root_dir+'" modified="'+opt.modified+'" style="display:none;" privs="' + opt.privs + '" rel="' + escape(unescape(opt.root_dir)) + '" class="jqueryFileTree '+subdirClass+'"><td class="columnSelect"><input class="chkBox" type="checkbox"/></td><td preview="' + opt.preview + '" '+attrs+' class="directory collapsed columnName"><span class="expandButton" rel="' + escape(unescape(opt.href_path)) + '/"><img src="' + o.collapsedImageURL + '" /></span><a href="' + opt.href_path + '" rel="' + escape(unescape(opt.href_path)) + '/">' + opt.name + '</a></td><td class="columnSize" size="0"></td><td class="columnModified" modified="'+opt.modified+'">' + opt.dateFormatted +'</td><td class="columnKeywords" title="' + keywords + '">' + keywords + '</td></tr>'); } else if (opt.type === 'FILE') { if (keywords.length >= o.MaximumLengthAllowedForKeywordsString) { keywords = keywords.substr( 0, o.MaximumLengthAllowedForKeywordsString) + "..."; } fileList.push('<tr rootdir="'+opt.root_dir+'" style="display:none;" modified="'+opt.modified+'" privs="' + opt.privs + '" rel="' + escape(unescape(opt.root_dir)) + '" class="jqueryFileTree '+subdirClass+'"><td class="columnSelect"><input class="chkBox" type="checkbox"/></td><td preview="' + opt.preview + '" '+attrs+' class="fileTR columnName fileItem"><a href="' + opt.href_path + '" rel="' + escape(unescape(opt.href_path)) + '">' + opt.name + '</a></td><td class="columnSize" fulldate="'+opt.date+'" size="' + opt.size + '">' + opt.sizeFormatted + '</td><td class="columnModified" modified="'+opt.modified+'">' + opt.dateFormatted + '</td><td class="columnKeywords" title="' + keywords + '">' + keywords + '</td></tr>'); } } } } drawLinks(curDirItems); return fileList.join(""); } else { drawLinks(curDirItems); return ""; } } function getFileExtension(filename) { var ext = /^.+\.([^.]+)$/.exec(filename); return ext == null ? "" : ext[1].toLowerCase(); } function IE(obj) { if(window.ActiveXObject) { var obj2 = {}; try { obj2.textContent = obj.text; } catch (ex) {} return obj2; } else { return obj; } } function howerEffect() { $(".jqueryFileTree").unbind(); $(".jqueryFileTree").hover(function () { $(this).addClass("rowHover"); }, function () { $(this).removeClass("rowHover"); }); } function setHashLocation(s) { if (o.setHashLocation) { if (s.toString().length > 0) { hashListener.setHash(s); } } } function getHash() { return document.location.hash; } function showButtonsBasedOnPriviledge() { renderButtons(); } /*Pagination methods*/ window.current_page = o.pagingCurrentPage; var panel = $(".pagination"); function numPages(customItem) { var curDirItems = customItem ? customItem : l; var maxentries = curDirItems.length; return Math.ceil(maxentries/o.defaultPageSize); } function getInterval(customItem) { var ne_half = Math.ceil(o.pagingNumDisplayEntries/2); var np = numPages(customItem); var upper_limit = np-o.pagingNumDisplayEntries; var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0; var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(o.pagingNumDisplayEntries, np); return [start,end]; } function pageSelected(page_id, evt, customItem){ $(".pagination").prepend("<span style='margin-right:5px;color:#777;'>(Loading...)</span>"); setTimeout(function(){ var curDirItems = customItem ? customItem : l; current_page = page_id; o.pagingCurrentPage = current_page; drawLinks(); updatePageSizeOnLayout(true, customItem); },50); } function selectPage(page_id){ pageSelected(page_id);} function prevPage(){ if (current_page > 0) { pageSelected(current_page - 1); return true; } else { return false; } } function drawLinks(customItem) { var curDirItems = customItem ? customItem : l; panel.empty(); var interval = getInterval(customItem); var np = numPages(curDirItems); if(np>1 || o.pagingControlsShowAlways) { panel.show(); var getClickHandler = function(page_id) { return function(evt){ return pageSelected(page_id,evt,curDirItems); } } var appendItem = function(page_id, appendopts){ page_id = page_id<0?0:(page_id<np?page_id:np-1); appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{}); if(page_id == current_page){ var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>"); } else { var lnk = jQuery("<a>"+(appendopts.text)+"</a>") .bind("click", getClickHandler(page_id)) .attr('href', "javascript:void(0);"); } if(appendopts.classes){lnk.addClass(appendopts.classes);} panel.append(lnk); } if(o.pagingPrevText){ appendItem(current_page-1,{text:o.pagingPrevText, classes:"prev"}); } if (interval[0] > 0 && o.pagingNumEdgeEntries > 0) { var end = Math.min(o.pagingNumEdgeEntries, interval[0]); for(var i=0; i<end; i++) { appendItem(i); } if(o.pagingNumEdgeEntries < interval[0] && o.pagingEllipseText) { jQuery("<span>"+o.pagingEllipseText+"</span>").appendTo(panel); } } for(var i=interval[0]; i<interval[1]; i++) { appendItem(i); } if (interval[1] < np && o.pagingNumEdgeEntries > 0) { if(np-o.pagingNumEdgeEntries > interval[1]&& o.pagingEllipseText) { jQuery("<span>"+o.pagingEllipseText+"</span>").appendTo(panel); } var begin = Math.max(np-o.pagingNumEdgeEntries, interval[1]); for(var i=begin; i<np; i++) { appendItem(i); } } if(o.pagingNextText){ appendItem(current_page+1,{text:o.pagingNextText, classes:"next"}); } } else { panel.hide(); } } /*End :: Pagination methods*/ function bindBreadcrumbs() { var hashLoc = unescape(hashListener.getHash().toString().replace("#", "")); var dirs = hashLoc.split("/"); var crumbs = ""; var items = 0; function getLocation(num) { var newLoc = ""; for (var i = 0; i < num; i++) { newLoc += dirs[i] + "/"; } return decodeURIComponent(newLoc); } for (var i = dirs.length - 1; i > 0; i--) { if (i < dirs.length - 2) { crumbs = "<li><a href='#" + escape(getLocation(i+1)) + "'>" + dirs[i] + "</a></li>" + crumbs; } else { crumbs = "<li>" + dirs[i] + "</li>" + crumbs; } items += 1; } crumbs = "<li class='home'><a href='#/'>"+$(document).data("username")+"</a></li>" + crumbs; /*if (items == 0) { crumbs += "<li><span class='refreshButton' rel='" + hashLoc + "'><img src='" + o.refreshImageURL + "' /></span></li>"; }*/ $("#crumbs").parent().find("span.refreshButton").remove(); $("#crumbs").html(crumbs).append("<span class='refreshButton' rel='" + hashLoc + "'><img src='" + o.refreshImageURL + "' /></span>"); $(".refreshButton").unbind().click(function () { window.current_page = o.pagingCurrentPage = 0; if (currentView() == "Thumbnail") { showTree($("#filesContainerDiv"), encodeURIComponent($(this).attr("rel")), true, true); } else { showTree($("#filesContainer"), encodeURIComponent($(this).attr("rel")), true, true); } }); } /** * Vertigo Tip by www.vertigo-project.com Requires jQuery */ var border_right = $(window).width(); var vtip = function (el) { var lOffset = currentView() == "Thumbnail" ? 20 : 40; var tOffset = currentView() == "Thumbnail" ? 0 : 0; el = el || $(".vtip"); $(el).cluetip({ splitTitle: '^', showTitle:false, width:'auto', cluetipClass:'default', arrows:true, tracking: currentView() == "Thumbnail", positionBy:'mouse', mouseOutClose:true, dropShadowSteps:0, leftOffset:lOffset, topOffset:tOffset, dynamicLeftOffset : currentView() != "Thumbnail" }); /* $(el).tipsy({ live: false, gravity: $.fn.tipsy.autoNS, html: true });*/ }; window.hashListener = { ie: /MSIE/.test(navigator.userAgent), ieSupportBack: true, hash: document.location.hash, check: function () { var h = document.location.hash; if (h != this.hash) { this.hash = h; this.onHashChanged(); } }, init: function () { if (this.ie && this.ieSupportBack) { var frame = document.createElement("iframe"); frame.id = "state-frame"; frame.style.display = "none"; if (document.body) { document.body.appendChild(frame); this.writeFrame(""); } } var self = this; if ("onpropertychange" in document && "attachEvent" in document) { document.attachEvent("onpropertychange", function () { if (event.propertyName == "location") { self.check(); } }); } }, setHash: function (s) { if (this.ie && this.ieSupportBack) { this.writeFrame(s); } document.location.hash = s; if (document.location.hash != ("#"+s)) document.location.hash = encodeURIComponent(s);//fix for Firefox refusing some strings...umlauts }, getHash: function () { return document.location.hash; }, writeFrame: function (s) { /*var f = document.getElementById("state-frame"); if (f) { var d = f.contentDocument || f.contentWindow.document; d.open(); d.write("<script>window._hash = '" + s + "'; window.onload = parent.hashListener.syncHash;<\/script>"); d.close(); }*/ }, syncHash: function () { var s = this._hash; if (s != document.location.hash) { document.location.hash = s; } }, onHashChanged: function () { var t = encodeURIComponent(this.getHash().replace("#", "")); window.current_page = o.pagingCurrentPage = 0; if (currentView() == "Thumbnail") { showTree($("#filesContainerDiv"), t, true); } else { showTree($("#filesContainer"), t, true); } } }; hashListener.init(); function initDropdownMenu() { $("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*) $("ul.topnav li span").unbind(); $("ul.topnav li span").hover(function () { //When trigger is clicked... //Following events are applied to the subnav itself (moving subnav up and down) $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click $(this).parent().hover(function () {}, function () { $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up }); //Following events are applied to the trigger (Hover events for the trigger) }).hover(function () { $(this).addClass("subhover"); //On hover over, add class "subhover" }, function () { //On Hover Out $(this).removeClass("subhover"); //On hover out, remove class "subhover" }); } // Loading message $(this).html('<table cellpadding="0" cellspacing="0" class="jqueryFileTree start"></table>'); blockFileListingUI(true); // Get the initial file list var currentViewType = $.cookie(o.ViewCookieName); if (currentViewType && currentViewType == "Thumbnail") { $(".thumbnailViewLink").animate({ opacity: 0.3 }, 500); } else { $(".treeViewLink").animate({ opacity: 0.3 }, 500); } bindUserName(true); userLoginStatusCheckThread(); bindUserCustomizationInfo(); applyLocalizations(); updatePageSizeOnLayout(); loadPopupContent(); bindMainMenuEvents(); bindPagingSizeMenu(); bindSelectionMenu(); $("#searchForm").attr("action", o.ajaxCallURL); bindBackToTop(); $("#searchResultNotification").find("a").click(function () { $(document).removeData("searchData"); $(".refreshButton").click(); }); initDropdownMenu(); }); } }); })(jQuery); /* jslint browser: true */ /* global jQuery: true */ /** * jQuery Cookie plugin * * Copyright (c) 2010 Klaus Hartl (stilbuero.de) Dual licensed under the MIT and * GPL licenses: http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ jQuery.cookie = function (key, value, options) { // key and value given, set cookie... if (arguments.length > 1 && (value === null || typeof value !== "object")) { options = jQuery.extend({}, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : ''].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; }; function initTabs() { $('.customtabs').each(function () { $(this).siblings('div').children('div:gt(0)').hide(); $(this).children('a:first').addClass('active'); $(this).find('a').click(function () { setTabByHandler(this); return false; }); }); } function setTabByHandler(elm) { if (elm && !$(elm).hasClass("disabledClick")) { var current_content_div = '#' + $(elm).attr('rel'); $(elm).siblings().removeClass('active'); $(elm).addClass('active'); $(current_content_div).siblings().hide(); $(current_content_div).show(); } $(elm).blur(); return false; } function setTabToElem(elm) { setTabByHandler($("a[rel='" + elm + "']:first")); } $.fn.clearForm = function () { return this.each(function () { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form' || tag == 'div') return $(':input', this).clearForm(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); };