// 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";
localizations.FilesNotAvailableMessage = "No files available";
localizations.CopyNoFilesSelectedMessage = "Please select files/folders to copy";
localizations.DeleteNoFilesSelectedMessage = "Please select files/folders to delete";
localizations.CutNoFilesSelectedMessage = "Please select files/folders to cut";
localizations.pagingPrevText = "Prev";
localizations.pagingNextText = "Next";
localizations.pagingEllipseText = "...";
localizations.FilterItemCountText = "(Items with phrase \"{filterVal}\" : {totalItems} , Folders: {folders} Files: {files})";
localizations.TotalItemsInDirMsgText = "(Total items in directory {count})";
localizations.ThumbnailsTooltipText = "<strong>Name : </strong>{text}<br /><strong>Size : </strong>{size}<br /><strong>Modified : </strong>{date}<br /><strong>Keywords : </strong> {keywords}";
localizations.WelcomeNoteSubmitFormFailureMsgText = "Error: Problem while saving data";
localizations.TreeviewSpecificActionMsgTitleText = "For tree view only";
localizations.TreeviewSpecificActionMsgDescText = "This is specific to tree view only";
localizations.PasswordExpiringMsgText = "Password Expiring Soon<br/>Use User Options button to change.";
localizations.PasswordNotMatchingMsgText = "New passwords don't match.";
localizations.PasswordMustBeComplexMsgText = "Password must be more complex.";
localizations.PasswordChangedMsgText = "Password changed.  Please login using the new password.";
localizations.AppletLoadingFailedMsgText = "Applet failed while uploading";
localizations.DownloadStartedAlertTitleText = "Download has started";
localizations.DownloadStartedAlertDescText = "Please select location to save your file(s) to proceed";
//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";
localizations.ShareActionEmailValidationFailureHelpToolTip = "Please enter valid email address. You can enter multiple email addresses at once separated by comma. ie. <strong>bob@email.com, john@email.com,...</strong>";
//Copy direct link window
localizations.CopyLinkWindowHeaderText = "Copy direct link.";
localizations.CopyLinkText = "Copy 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.BrowserUploaderSelectedFileReDownloadLinkText = "re-download";
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 = "Current Speed : ";
localizations.BrowserUploaderAdvancedUploadingAverageSpeedText = "Avg. Speed : ";
localizations.BrowserUploaderAdvancedUploadingTimeText = "<div class='time'> Time: Elapsed: <span class='elapsed'>{0}</span> <span class='remained'>, Remaining : {1}</span></div>";
localizations.BatchCompleteText = "Result";
localizations.BatchComplete = "Transfers Acknowledged.";
localizations.BrowserUploaderSpeedTimeCalculatingText = "Calculating..";
localizations.BrowserUploaderProblemWhileTransferMsgText = "Problem while transferring";
localizations.BrowserUploaderCancelledUploadMsgText = "Cancelled uploading";
localizations.BrowserUploaderAlertWhileNavigatingAwayMultipleFilesMsgText = "Your {count} files are currently uploading.  If you navigate away from this page you will lose them.  Are you sure you want to exit this page?";
localizations.BrowserUploaderAlertWhileNavigatingAwaySingleFileMsgText = "{count} file is currently uploading.  If you navigate away from this page you will lose it.  Are you sure you want to exit this page?";
localizations.BrowserDownloadAlertWhileNavigatingAwayMsgText = "Your files are currently downloading. If you navigate away from this page you will lose them.  Are you sure you want to exit this page?";
//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";
localizations.SearchProcessNotificationText = "Processing... ";
localizations.SearchProcessCancelText = "Cancel";
//Multiple file selection options
localizations.ItemsSelectionDisplayText = "All <strong>{count}</strong> items on this page are selected.";
localizations.ItemsSelectionSelectAllItemsInDir = "Select all <strong>{total_items}</strong> items in <strong>{list_type}</strong> (including hidden items)</span>";
localizations.ItemsSelectionSelectedAllItemsInDir = "All <strong>{total_items}</strong> items in <strong>{list_type}</strong> (including hidden items) are selected";
localizations.ItemsSelectionClearSelection = "Clear selection";
localizations.ItemsSelectionShowingFolderText = "Current Folder";
localizations.ItemsSelectionShowingFilteredItemsText = "Current filtered list";
localizations.ItemsSelectionShowingSearchedItemsText = "Search result";
//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 = " ";
localizations.BasketClearAllConfirmMessage = "Are you sure you wish to clear all selected files in Basket?";
//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";
localizations.ManageShareWindowNothingToShowMessageText = "Nothing to display";
localizations.ManageShareWindowNothingSelectedToDeleteMessageText = "(Nothing selected to delete)";
localizations.ManageShareWindowDeleteAccountConfirmationText= "Are you sure you wish to delete selected {count} account(s) ?";
localizations.ManageShareWindowUserDeletedMessageText = "(User : {name} deleted)";
//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.DeleteConfirmationMessageRemoveAllItemsInDirText = "All items in folder \"{folder_name}\" will be deleted.\n\nTotal {count} items will be deleted.\n\nOnce 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.";
localizations.NothingSelectedGrowlText = "Nothing selected";
localizations.ShareNothingSelectedGrowlText = "Nothing selected to share";
localizations.DownloadNothingSelectedGrowlText = "Nothing selected to download";
localizations.RenameNothingSelectedGrowlText = "Nothing selected to rename";
localizations.ProblemWhileRenamingGrowlText = "Problem while renaming";
localizations.ProblemWhileRenamingDescGrowlText = "There was a problem while renaming. Please retry. Error : ";
localizations.ProblemWhileSharingGrowlText = "Problem while sharing";
localizations.ProblemWhileSharingDescGrowlText = "There was a problem while sharing a file. Please retry";
localizations.DirectLinkDescGrowlText = "Right click on item and click on copy direct link";
localizations.UpdateKeywordDescGrowlText = "Right click on item and click on update keywords";
localizations.QuickViewNothingToShowGrowlText = "Error : Nothing to show in quick view";
localizations.QuickViewNoItemsAvailableGrowlText = "No items available";
localizations.ProblemWhileDeletingGrowlText = "Problem while deleting";
localizations.ProblemWhileDeletingDescGrowlText = "There was a problem while deleting. Please retry. Error : ";
localizations.ProblemWhileCreatingFolderGrowlText = "Problem while creating new folder";
localizations.ProblemWhileCreatingFolderDescGrowlText = "There was a problem while creating new folder. Please retry. Error : ";
localizations.JavaRequiredGrowlText = "Java Required";
localizations.JavaRequiredDescGrowlText = "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>";
localizations.JavaAppletNotLoadedGrowlText = "Java Applet Not Loaded";
localizations.JavaAppletNotLoadedDescGrowlText = "You must first click the 'Advanced Browse...' button before drag and drop will be enabled.";
localizations.NoFilesFoundGrowlTitle = "No data found";
localizations.NoFilesFoundGrowlText = "Error : Not data found for ";
//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 = "&copy; 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>";
// Applet browse window title options
localizations.advancedUploadItemsSelectionWindowTitle = "Choose items to upload..";
localizations.advancedDownloadPathSelectionWindowTitle = "Choose path where to download.."; /*Tracking mouse movement*/

localizations.maxAllowedDownloadSizeReached = "Download size exceeded the maximum allowed size"; //Header of growl to display when download reaches maximum allowed size
localizations.maxAllowedDownloadSizeReachedText = "Maximum size allowed to download : {size}. <br />Use the advanced downloader, or add to basket instead."; //Text of growl to display when download reaches maximum allowed size

// Change icon window items
localizations.ChangeIconWindowHeaderText = "Change icon ";
localizations.ChangeIconWindowInstructionsText = "Choose a small image to set as the icon for selected item:";
localizations.ChangeIconWindowSelectedFilesLabelText = "Selected file : ";
localizations.ChangeIconWindowCancelLinkText = "Cancel";
localizations.ChangeIconWindowUpdateLinkText = "Save";
localizations.ChangeIconFileSelectAlertText = "Please select image file to continue.";

$(document).ready(function () {
	$(document).data("localizations", localizations); //sets localizations to cache
	if (!window.forSlideshow) //If not slideshow only
	{
		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);
			}
		});
		//adds hash change listener
		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.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.signupPage == undefined) o.signupPage = false;
			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;";
			//Various Cookies for layout
			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.MaxSimultaneousUploadAllowed = 1;
			o.GrowlTimeout = 3000; // If growl has close button (next option) it will be set to 0
			o.GrowlWithCloseButton = true;
			o.BasketDataKey = "__WEBINTERFACE_FILES_IN_BASKET";
			o.BasketDataKeyQuickDownload = "__WEBINTERFACE_FILES_IN_BASKET_QUICK_DOWNLOAD";
			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", "htm", "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.pagingControlsShowAlways = false; /*End :: Pagination options*/
			o.folderNameSpecialCharacterSubstitute = "_"; //While creating new folders, it will replace special characters with specified character
			// Template of file select panel
			o.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>';
			//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) // If to display sign-up form
				{
					// function to retrive current page's name

					function GetCurrentPageName() {
						var sPath = window.location.pathname;
						var sPage = sPath.substring(sPath.lastIndexOf("/") + 1);
						return sPage;
					}
					var customFormName = GetCurrentPageName();
					customFormName = customFormName.replace(".html", "");
					// Get custom form from server and display
					getCustomForm(customFormName, function (data, hasForm, formName, showAlways) {
						if (hasForm) {
							var signupPanel = $("#panelSignup");
							signupPanel.html("<form id='frmSignup'>" + data + "</form>").find("table").css("text-align", "left");
							setCustomFormFieldAttributes(signupPanel)
							attachCalendarPopup(signupPanel);
							$("button#resetPasteForm", signupPanel).unbind().click(function (event) {
								signupPanel.clearForm();
								event.stopPropagation();
								event.preventDefault();
							});
							// a method to show error on signup page

							function displayError(msg) {
								var form = signupPanel;
								if (form.prev().hasClass("attention")) {
									form.prev().remove();
								}
								form.before("<div class='attention'>" + msg + "</div>");
								form.prev().css("float", "none");
							}
							// a method to validate signup form

							function validateForm(target, form) {
								form = form || $("table.customForm", "#divUploadPanel");
								var validated = true;
								form.find(".required_true").each(
								function () {
									if($(this).is(":disabled") || $(this).attr("readonly")) return;
									if ($(this).hasClass("chkbox")) {
										if (!$(this).is(":checked") && $(this).closest("td").find("input:checked").length == 0) {
											$(this).parent().addClass("validationFail");
											if (validated) {
												$(this).parent().focus();
											}
											validated = false;
										} else {
											$(this).parent().removeClass("validationFail");
										}
									} else {
										if ($.trim($(this).val()).length == 0) {
											$(this).addClass("validationFail");
											if (validated) {
												$(this).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;
							}
							// signup window submit form
							$("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) {
										errorThrown = errorThrown || messageForm;
										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, callback) {
					parentElement = $(parentElement);
					parentElement.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) {
								path = hashLocation;
							} else {
								path = "/";
							}
						}
						if (locateFolder) {
							blockFileListingUI(true);
						} /* If nothing specified use root directory */
						if (path.length == 0 || path == 'null') path = "/"; /* Data to POST to receive file listing */
						if (window.redirectRoot && path == "/") document.location = window.redirectRoot;
						if(path.lastIndexOf("/")!=path.length-1)
						{
							var ext = getFileExtension(path);
							if(ext && ext.length>0)
							{
								downloadItems(false, false, path);
							}
						}
						$("div.mainNavigation").block({
							message: "",
							css: {
								border: 'none',
								color: '#000'
							}
						});
						var obj = {
							command: "getXMLListing",
							format: "JSON",
							path: encodeURIComponent(unescape(unescape(path))),
							random: Math.random()
						}; /* Make a call and receive list */
						$.ajax({
							type: "POST",
							url: o.ajaxCallURL,
							data: obj,
							success: function (msg) {
								if ($(document).data("uploadOnly")) {
									if (msg && msg.childNodes && msg.childNodes.length > 0) {
										var rows = msg.getElementsByTagName("listing");
										var items = IE(rows[0]).textContent;
										eval(items); // it evals the response, it sets a global variable l to item list.
										window.curTreeItems = window.curTreeItems ? window.curTreeItems : window.l ? window.l : {};
									}
									return false;
								}
								renderListing(parentElement, locateFolder, useHash, msg);
								var inverse = true;
								if (window.listingSortColumn) {
									if (window.listingSortDirection == "up") {
										inverse = false;
									}
								}
								sortListing(window.listingSortColumn, inverse, true);
								if(msg && msg.childNodes && msg.childNodes.length > 0) {
									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 (!parentElement.hasClass("directory") && parentElement.find("a.imgLink[href='" + escape(unescape(path)) + "']")[0] && parentElement.find("a.imgLink[href='" + escape(unescape(path)) + "']").length == 1) {
											downloadItems(false, parentElement.find("a[rel='" + escape(unescape(path)) + "']").closest("td"));
											renderListing(parentElement, locateFolder, useHash, null); //empty the listing.
										}
									} else {
										if (!parentElement.is("table#filesContainer") && !parentElement.hasClass("directory") && parentElement.find("a[rel='" + escape(unescape(path)) + "']")[0] && parentElement.find("a[rel='" + escape(unescape(path)) + "']").length == 1) {
											downloadItems(false, parentElement.find("a[rel='" + escape(unescape(path)) + "']").closest("td"));
											renderListing(parentElement, locateFolder, useHash, null); //empty the listing.
										}
									}
									showItemsBasedOnData(true, obj);
								}
								else
								{
									showItemsBasedOnData(false, obj);
								}
								if (callback) {
									try {
										callback();
									} catch (ex) {}
								}
							},
							error: function (XMLHttpRequest, textStatus, errorThrown) {
								//its a reference to a file or folder as zip, so start a zip on demand of it.
								if (path.lastIndexOf(".zip") == path.length - 4) {
									path = path.substring(0, path.lastIndexOf(".zip"));
									submitAction({
										'#command': "downloadAsZip",
										'#path': encodeURIComponent("/"),
										'#paths': encodeURIComponent(unescape(path)),
										'#random': Math.random()
									});
								} else {
									errorThrown = errorThrown || "getXMLListing failed";
									$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
									showItemsBasedOnData(false, obj);
								}
								if (!$(document).data("uploadOnly")) {
									renderListing(parentElement, locateFolder, useHash, null); //empty the listing.
								} else {
									window.curTreeItems = window.curTreeItems ? window.curTreeItems : window.l ? window.l : {};
								}
							}
						});
					} else {
						$.post(o.script, {
							dir: path
						}, function (data) {
							parentElement.find('.start').html('');
							parentElement.removeClass('wait').append(data);
							blockFileListingUI(false);
							parentElement.find('TR:hidden').show();
							bindTree(parentElement);
							if (callback) {
								try {
									callback();
								} catch (ex) {}
							}
						});
					}
				}

				//Function to manage items on screen based on folder loaded
				function showItemsBasedOnData(folderLoaded, obj)
				{
					if(!folderLoaded)
					{
						$.growlUI(getLocalizationKey("NoFilesFoundGrowlTitle"), "<span class='nodataFoundErrorMsg'></span>" + getLocalizationKey("NoFilesFoundGrowlText") + decodeURIComponent(obj.path), o.GrowlTimeout, "", o.GrowlWithCloseButton);
					}
					else
					{
						$(".nodataFoundErrorMsg").closest("div.blockUI").find("img.closeButton").trigger("click");
					}
				}

				// method shows/hides menu items based on privs of current logged in user.
				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");
					myMenu.find("a[href*='changeIcon']").parent().hide();
					if (!_delete) {
						myMenu.find("a[href='javascript:delete_items();']").remove();
					}
					if(!_write)
					{
						myMenu.find("a[href='javascript:performAction('cut');']").remove();
						myMenu.find("a[href='javascript:performAction('copy');']").remove();
						myMenu.find("a[href='javascript:performAction('paste');']").remove();
						myMenu.find("a[href*='updateKeywords']").parent().hide();
					}
					if (!_makedir) {
						myMenu.find("a[href='javascript:performAction('createFolder');']").remove();
					}
					if (!_slideshow) {
						myMenu.find("a[href='javascript:performAction('slideshowDiv');']").remove();
					}
					if (!_download) {
						myMenu.find("a[href='javascript:performAction('download');']").remove();
						myMenu.find("a[href='javascript:performAction('cut');']").remove();
						myMenu.find("a[href='javascript:performAction('copy');']").remove();
						myMenu.find("a[href='javascript:performAction('paste');']").remove();
					}
				}
				// To preserve location of browser scroll

				function scrollToFileListing() {
					if (!o.buggyBrowser) {
						if ($('html,body').scrollTop() > $("#mainContent").offset().top) {
							$('html,body').animate({
								scrollTop: $("#mainContent").offset().top
							}, 0, false);
						}
					}
				}
				//Back to top link event

				function bindBackToTop() {
					$(".backToTop").click(function () {
						if (!o.buggyBrowser) {
							$('html,body').animate({
								scrollTop: 0
							}, 500, false);
						}
					});
				}
				var delay = (function () {
					var timer = 0;
					return function (callback, ms) {
						clearTimeout(timer);
						timer = setTimeout(callback, ms);
					};
				})();
				// Sorting method for sorting

				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) {
						if(x && x[window.listingSortColumn] && y && y[window.listingSortColumn])
						{
							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;
						}
						else
							return inverse ? 1 : -1;
					}
					if (window.filteredItems) {
						if (rebuild) {
							reBuildListing(window.matchedItems.sort(applySorting));
						}
					} else {
						l = l.sort(applySorting);
						if (rebuild) {
							reBuildListing();
						}
					}
				}
				//Renders list of items

				function renderListing(parentElement, locateFolder, useHash, responseData, searchResult) {
					$("#filter").val(""); // reset user filter
					parentElement = $(parentElement);
					if (searchResult) { // if it is a search result
						$("#searchResultNotification").show();
					}
					if (!$("#filter").data("eventAdded")) // bind event of keyup on filter input to do live filter if event not added already
					{
						$("#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) { // if value is not updated, do nothing
									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);
							}
						}).data("eventAdded", true);
					}
					$("#cluetip").remove(); // remove tooltip shown					
					//If current view is thumbnail
					if (currentView() == "Thumbnail") {
						//This will provide HTML for thumbnails
						var data = mapXmlToTable(responseData, true);						
						parentElement.html(data);
						prepareDataRow(parentElement.find("li"));
						bindTree();
						bindAllEventsForThumbnailView(parentElement, 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) { // Displaying result from search query
							$(document).data("expandedFolders", []);
							scrollToFileListing();
							//Get the html after XML parsing for treeview
							var data = mapXmlToTable(responseData, true);
							//Remove old items
							parentElement.find(".headerSortDown").removeClass("headerSortDown");
							parentElement.find(".headerSortUp").removeClass("headerSortUp");
							parentElement.find("tbody").html('');
							//Remove spinner and add HTML
							parentElement.find("tbody").append(data);
							//Display new items
							blockFileListingUI(false);
							var elems = parentElement.find('TR:hidden:not(.hiddenFile)').show().addClass("subdirectory"); /* Bind various events */
							//prepareDataRow(parentElement.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(parentElement, false);
						} else if (!locateFolder && parentElement.hasClass('directory')) {
							//If  to  show folder items  under  tree
							//Get the html after XML parsing for treeview
							var data = mapXmlToTable(responseData, true, true, parentElement);
							//Remove old items
							var $parent = parentElement.closest('table') || $parent;
							$parent.find(".headerSortDown").removeClass("headerSortDown");
							$parent.find(".headerSortUp").removeClass("headerSortUp");
							$parent.find("tbody").empty();
							$parent.append(data).find('TR:hidden').show();
							//Select and create an array of folders that are expanded
							var expandedFolder = parentElement.find("a").attr("rel");
							var expandedFolders = $(document).data("expandedFolders");
							if (!expandedFolders) {
								expandedFolders = [];
							}
							if (!expandedFolders.has(expandedFolder)) {
								expandedFolders.push(expandedFolder);
							}
							$(document).data("expandedFolders", expandedFolders);
							// Cache it for later use
							if (!o.buggyBrowser && $("span[rel='" + expandedFolder + "']:first").length > 0) {
								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);
							// set proper padding to list items to make it like a tree layout
							$parent.find("tr.subdirectory").each(function () {
								var relLink = $("a[rel='" + $(this).attr("rel") + "']");
								var rootdir = escape(unescape($(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", ""));
										// get current items padding information
									} catch (ex) {}
								} else {
									padLeft = 20;
									// Default padding is 20px
								}
								if (padLeft != NaN) {
									if (padLeft >= 20) {
										padLeft += 20; // add next level padding
										var padicon = padLeft;
										var padTree = padicon - 20;
										$(this).find("td.columnName").attr("style", "padding-left:" + padLeft + "px !important; background-position:" + padTree + "px 4px !important;");
									}
								}
							});
							if (expandedFolders) {
								// loop through expanded folders and set proper icon for expand view
								for (var item in expandedFolders) {
									if (expandedFolders[item].toLowerCase) {
										var rootdir = escape(unescape(expandedFolders[item]));
										var dirSpan = $parent.find("span[rel='" + rootdir + "']");
										$(dirSpan).parent().removeClass('collapsed').addClass('expanded');
										$(dirSpan).find("img").attr("src", o.expandedImageURL);
									}
								}
							}
						} else if (locateFolder) {
							// Its simply showing all content of selected folder
							$(document).data("expandedFolders", []);
							scrollToFileListing();
							//If to  show folder items only
							//Get the html after XML parsing  for treeview
							var data = mapXmlToTable(responseData);
							//Replace all existing items  with new items and show them
							var $parent = parentElement.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(parentElement.find("td.fileTR,td.directory"));
							bindTree($parent);
							bindAllEventsForTreeviewGrid(parentElement.closest('table'), true, data);
						} else {
							// Called for the first time
							$(document).data("expandedFolders", []);
							//If its called for first  time. Get the html after XML parsing for treeview
							var data = mapXmlToTable(responseData);
							//Replace all existing items with new items and show them
							parentElement.find("tbody").append(data);
							blockFileListingUI(false);
							var currentViewType = $.cookie(o.ViewCookieName);
							bindTree(parentElement);
							parentElement.closest('table').find("tr").attr("style", "background-position:40px 3px !important;");
							bindAllEventsForTreeviewGrid(parentElement.closest('table'), true, data);
						}
					}
					// Bind properties of folder loaded
					bindCountOfFiles();
					try {
						window.cancelDrop();
					} catch (ex) {}
					// Select and show quota information for current folder
					if (responseData && responseData.getElementsByTagName("quota") && responseData.getElementsByTagName("quota").length > 0) {
						window.quota = IE(responseData.getElementsByTagName("quota")[0]).textContent;
						if ($("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'>&nbsp;&nbsp;" + window.quota + " available.</span>");
					}
					// clear filter link event
					$("a.clearFilterLink").unbind("click").click(

					function (e) {
						e.preventDefault();
						if ($("#filter").val().length > 0) {
							$("#filter").val("").keyup();
						}
						selectDeselectAllItems(false); //uncheck all items in grid/tree
						return false;
					});
				}
				//Method to show properties of loaded folder

				function bindCountOfFiles() {
					if (!window.listingInfo) window.listingInfo = {};
					var curDir = "/";
					if (hashListener.getHash() && hashListener.getHash().toString() != "") {
						curDir = unescape(hashListener.getHash().toString().replace("#", ""));
					}
					if (currentView() == "Thumbnail") {
						//sets listingInfo variable with various details of loaded folder
						window.listingInfo.totalItems = $("li", "#filesContainerDiv").length;
						window.listingInfo.totalVisibleItems = $("li:visible", "#filesContainerDiv").length;
						window.listingInfo.totalDirs = $("li.directoryThumb:visible", "#filesContainerDiv").length;
						window.listingInfo.totalFiles = window.listingInfo.totalVisibleItems - window.listingInfo.totalDirs;
						window.listingInfo.hiddenItems = $("li", "#filesContainerDiv").length - $("li:visible", "#filesContainerDiv").length;
						window.listingInfo.totalItemsInDir = window.listingInfo.totalItems + window.listingInfo.hiddenItems;
						window.listingInfo.filtered = false;
						if (curDir != window.listingInfo.curDir) {
							window.listingInfo.selectedEverything = false;
						}
						selectDeselectAllItems(window.listingInfo.selectedEverything);
						if (window.listingInfo.selectedEverything) {
							$("#selectionOfItemsOptions").show();
						}
						window.listingInfo.curDir = curDir;
						window.listingInfo.isSearchResult = $("#searchResultNotification").is(":visible");
						var msg = window.listingInfo.totalVisibleItems + " " + getLocalizationKey("FileCounterItemsText") + " (";
						if (window.listingInfo.totalDirs > 0) {
							msg += window.listingInfo.totalDirs + " " + getLocalizationKey("FileCounterFoldersText") + ", ";
						}
						msg += window.listingInfo.totalFiles + " " + getLocalizationKey("FileCounterFilesText") + ") "
						if (window.listingInfo.hiddenItems > 0) {
							msg += window.listingInfo.hiddenItems + " " + getLocalizationKey("FileCounterHiddenItemsText")
						}
						if (l && window.listingInfo.totalItems + window.listingInfo.hiddenItems < l.length) {
							var items = l.length;
							msg += getLocalizationKey("TotalItemsInDirMsgText").replace("{count}", items);
							window.listingInfo.totalItemsInDir = items;
						}
						$("div.itemCount").html(msg);
						if ($("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'>&nbsp;&nbsp;" + window.quota + " available.</span>");
						if (window.filteredItems && window.filteredItems.filesCount && $("#filter").val().length > 0) {
							window.listingInfo.filtered = true;
							var files = window.filteredItems.filesCount;
							var dirs = window.filteredItems.dirsCount;
							window.listingInfo.totalDirs = dirs;
							window.listingInfo.totalFiles = files;
							window.listingInfo.totalItems = files + dirs;
							var FilterItemCountText = getLocalizationKey("FilterItemCountText");
							var itemCount = FilterItemCountText.replace("{filterVal}", $("#filter").val()).replace("{totalItems}", window.listingInfo.totalItems).replace("{folders}", dirs).replace("{files}", files);
							$("#itemCount").prepend("<span style='margin-right:15px;color:#777;'>" + itemCount + "</span>");
						}
					} else {
						window.listingInfo.totalItems = $("tr", "#filesContainer>tbody").length;
						window.listingInfo.totalVisibleItems = $("tr:visible", "#filesContainer>tbody").length;
						window.listingInfo.totalDirs = $("td.directory:visible", "#filesContainer>tbody").length;
						window.listingInfo.totalFiles = window.listingInfo.totalVisibleItems - window.listingInfo.totalDirs;
						window.listingInfo.hiddenItems = $("tr", "#filesContainer>tbody").length - $("tr:visible", "#filesContainer>tbody").length;
						window.listingInfo.totalItemsInDir = window.listingInfo.totalItems + window.listingInfo.hiddenItems;
						window.listingInfo.filtered = false;
						if (curDir != window.listingInfo.curDir) {
							window.listingInfo.selectedEverything = false;
						}
						selectDeselectAllItems(window.listingInfo.selectedEverything);
						if (window.listingInfo.selectedEverything) {
							$("#selectionOfItemsOptions").show();
						}
						window.listingInfo.curDir = curDir;
						window.listingInfo.isSearchResult = $("#searchResultNotification").is(":visible");
						var msg = window.listingInfo.totalVisibleItems + " " + getLocalizationKey("FileCounterItemsText") + " (";
						if (window.listingInfo.totalDirs > 0) {
							msg += window.listingInfo.totalDirs + " " + getLocalizationKey("FileCounterFoldersText") + ", ";
						}
						msg += window.listingInfo.totalFiles + " " + getLocalizationKey("FileCounterFilesText") + ") "
						if (window.listingInfo.hiddenItems > 0) {
							msg += window.listingInfo.hiddenItems + " " + getLocalizationKey("FileCounterHiddenItemsText")
						}
						if (l && window.listingInfo.totalItems + window.listingInfo.hiddenItems < l.length) {
							var items = l.length;
							msg += getLocalizationKey("TotalItemsInDirMsgText").replace("{count}", items);
							window.listingInfo.totalItemsInDir = items;
						}
						$("div.itemCount").html(msg);
						if ($("div.itemCount").find("span.quotaText").length == 0 && window.quota && window.quota.length > 0) $("div.itemCount").append("<span class='quotaText'>&nbsp;&nbsp;" + window.quota + " available.</span>");
						if (window.filteredItems && window.filteredItems.filesCount && $("#filter").val().length > 0) {
							window.listingInfo.filtered = true;
							var files = window.filteredItems.filesCount;
							var dirs = window.filteredItems.dirsCount;
							window.listingInfo.totalDirs = dirs;
							window.listingInfo.totalFiles = files;
							window.listingInfo.totalItems = files + dirs;
							var FilterItemCountText = getLocalizationKey("FilterItemCountText");
							var itemCount = FilterItemCountText.replace("{filterVal}", $("#filter").val()).replace("{totalItems}", window.listingInfo.totalItems).replace("{folders}", dirs).replace("{files}", files);
							$("#itemCount").prepend("<span style='margin-right:15px;color:#777;'>" + itemCount + "</span>");
						}
					}
				}
				// method to bind context menu on selectall checkbox to provide multiple options.

				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;
						});
					}
				}
				// method to bind paging size menu

				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;
						});
					}
				}
				// set of events combined to this method for thumbs view

				function bindAllEventsForThumbnailView(parentElement, data) {
					bindBreadcrumbs(); // breadcrumbs
					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();
					loadDirectoryPreview();
				}
				// set of events combined to this method for tree view

				function bindAllEventsForTreeviewGrid(element, checkForFiles, data) {
					$(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();
					loadDirectoryPreview();
				}
				//refreshes current view

				function refreshView() {
					// If to show items starting with a dot
					var hideItemsStartingWithDot = $.cookie(o.CookieHideItemStartingWithDot);
					hideItemsStartingWithDot = hideItemsStartingWithDot == "true";
					if (hideItemsStartingWithDot) {
						$("#SelectCheckboxContextMenuCheckItemsWithDotText").parent().hide();
					} else {
						$("#SelectCheckboxContextMenuCheckItemsWithDotText").parent().show();
					}
					// If to show filter on screen
					var hideFilter = $.cookie(o.CookieHideFilter);
					hideFilter = hideFilter == "true";
					if (hideFilter) {
						$(".filterPanel").hide();
					} else {
						$(".filterPanel").show();
					}
					// If to show checkbox column in listing
					var hideCheckBoxColumn = $.cookie(o.CookieHideCheckBoxColumn);
					if (hideCheckBoxColumn && hideCheckBoxColumn != "true") {
						hideCheckBoxColumn = $(document).data("disableCheckCol");
						if (hideCheckBoxColumn == "true") {
							$("#hideCheckBoxColumn").attr("disabled", "disabled");
						}
					}
					hideCheckBoxColumn = hideCheckBoxColumn == "true";
					// If to disable name column
					var disableNameCol = $(document).data("disableNameCol");
					disableNameCol = disableNameCol == "true";
					// If to disable size column
					var disableSizeCol = $(document).data("disableSizeCol");
					disableSizeCol = disableSizeCol == "true";
					// If to disable modified column
					var disableModifiedCol = $(document).data("disableModifiedCol");
					disableModifiedCol = disableModifiedCol == "true";
					// If to disable keywords column
					var disableKeywordsCol = $(document).data("disableKeywordsCol");
					disableKeywordsCol = disableKeywordsCol == "true";
					//Shows/hides columns and properties based on customization set
					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");
								}
							});
						}
					}
					// re-bind file count
					bindCountOfFiles();
				}
				// Bind sorting to treeview grid

				function bindSortingToTreeviewGrid() {
					var th = jQuery('#filesContainer').find('thead > tr > td').addClass("header"),
						inverse = true;
					// sort direction
					window.listingSortDirection = $(document).data("listDefaultSortDirection") || "up";
					// column sorted
					window.listingSortColumn = $(document).data("listDefaultSortColumnIndex") || 1;
					// select default column to sort
					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");
					}
					$(".chkBoxAll").unbind().click(function (event) {
						var chkBox = $(this);
						toggleCheckBoxesAll($(this).closest("table"), chkBox.is(":checked"));
					});
					// Add sorting event
					if (!$("#filesContainer").data("sortingAdded")) {
						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);
						// Sort the list with options selected above.
						sortListing(window.listingSortColumn, inverse, true);
					}
				}
				// Context menu events

				function bindContextMenu(elems) {
					var addMenu = true;
					// noMenus is global variable, if it is set to true no context menu should be bound
					try {
						if (noMenus) addMenu = false;
					} catch (e) {}
					if (addMenu) {
						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);
					});
				}
				// sets a message if nothing to display, else clears loading info

				function checkFilesAvailable(fileList) {
					if (fileList.length == 0) {
						o.FileListingElement.block({
							message: getLocalizationKey("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();
					}
				}
				// This method loops through list item and sets data like name, size, privs etc for each item. Which isused later on actions.

				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 = {};
				// Adds line break in title of an item if it exceeds provided length

				function wbr(str, num) {
					if (!regexpCache[num]) {
						regexpCache[num] = RegExp("(\[^\s-].{" + num + "})(?=\[^\s-].)", "g");
					}
					return str.replace(regexpCache[num], "$1<br>");
				}
				// Sets title of an item based on allowed characters length

				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) {}
						});
					}
				}
				//Method to load icon previews, based on size and generic icon

				function loadIconPreview(size, force, elem) {
					var genericIconTree = $(document).data("genericIconTree");
					var genericIconThumbnail = $(document).data("genericIconThumbnail");
					var randomNo = Math.random();
					if (currentView() == "Thumbnail") {
						var zoomValue = parseInt(window.zoomSlider.slider("value")); // Current zoom level
						size = size || 2; // default size is 2
						var iconSize = 48;
						if (zoomValue < 3) {
							iconSize = 48; //Icon size 48 if zoom level is less than 3
						} else if (zoomValue < 6) {
							iconSize = 128; //Icon size 128 if zoom level is less than 6
						} else if (zoomValue < 10) {
							iconSize = 256; //Icon size 256 if zoom level is less than 10
						} else {
							iconSize = 512; //Icon size 512 if zoom level is higher than 10
						}
						var disableHover = false;
						if ($(document).data("disableThumbnailHover") && $(document).data("disableThumbnailHover") == "true") disableHover = true;
						if (!disableHover) {
							disableHover = zoomValue >= 13; // hover info, tooltip should be disabled if zoom level is more than 12
						}
						if (disableHover) {
							//If hover is disabled, it will loop through items and disable tooltip
							$("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 {
							//If hover is enabled, it will loop through items and enable tooltip
							$("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");
								}
							});
						}
						// Not required for directory icon
						if (elem && elem.hasClass("directoryThumb")) {
							return;
						}
						var opt = false;
						if (force) {
							// load icons forcefuly
							if (elem) {
								opt = $(elem).data("dataRow");
								elem = elem.closest("li") || elem;
								if (elem.hasClass("vtip")) {
									elem.attr("title", getLocalizationKey("ThumbnailsTooltipText").replace("{text}", elem.find("div.imgTitle>a").text() ).replace("{size}", opt.size).replace("{date}", opt.date).replace("{keywords}", 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);
							}
						}
						//For MSIE a location of window includes hash, we need only current location
						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 + "']");
						}
						// Loop through items and load preview icons, if icon not available generic icon will be shown
						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");
								}
							}
							// binds images' load event
							$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;
								// Calculate image's real width and height and fix it to fit to the image holder DIV
								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;
							var itemListed = $curElem.closest("li");
							opt = itemListed.data("dataRow");
							if (opt && opt.preview > 0 || itemListed.attr("preview")) {
								//if current item has preview, show preview image as an icon. Generic icon otherwise
								if (!genericIconThumbnail && !itemListed.is(".directoryThumb")) {
									$curElem.attr("src", o.ajaxCallURL + "?command=getPreview&size=" + size + "&path=" + encodeURIComponent(unescape($curElem.parent().attr("rel"))) + "&random="+randomNo+"&frame=1").attr("style", o.PreviewIconThumbnailStyle);
									genericIcon = false;
								}
								var parentElem = itemListed || $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"))) + "&random="+randomNo+"&frame=1" + "\" border=\"0\" /> <br />" + $(parentElem).attr("title"));
								}
							}
							// If generic icon to be shown, set it based on current file's extension. Which will be replaced with common file icon if current icon set does not have an icon for this extension.
							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");
						});
						//Resetting iconSize as this will be used when preview images load
						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;
						}
					} else {
						//for treeview
						size = size || 1; // default size for preview icon is 1 for treeview
						elem = elem || $("td.fileTR");
						var disableHover = false;
						if ($(document).data("disableTreeviewHover") && $(document).data("disableTreeviewHover") == "true") disableHover = true;
						// loop through images and load relevant preview or generic icon
						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 item has preview and no generic icon to show
							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"))) + "&random="+randomNo+"&frame=1");
								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"))) + "&random="+randomNo+"&frame=1" + "\" border=\"0\" />");
									vtip($curElem);
								}
							} else {
								//If generic icon to show
								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"))) + "&random="+randomNo+"&frame=1" + "\" border=\"0\" />");
										vtip($curElem);
									}
								}
							}
						});
					}
				}
				// Bind view changer links events.

				function bindEventsToViewChanger() {
					$(".thumbnailViewLink,.treeViewLink").unbind("click").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();
				//Method which sets elements sizes based on zoom level
				window.zoomInOutView = function (val, elem) {
					elem = elem || false;
					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, elem);
						} else {
							loadIconPreview(2, true, elem);
						}
					} 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, elem);
					}
					if ($.browser.msie && parseInt(jQuery.browser.version) == 8) {
						var charlimit = o.thumbnailTextCharsLimit + (val * 4);
						setTitleText(false, charlimit);
					}
				}
				// Events to bind on items to navigate folders

				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); // If shift is pressed it will allow multiple item selection in thumbs view
							curitem.trigger("click");
							$(this).blur();
							return false;
						});
						$(t).find('LI.fileBox').unbind("click").click(function (evt) {
							window.listingInfo.selectedEverything = false;
							$("#selectionOfItemsOptions").hide();
							var curitem = $(this);
							var shift = evt.shiftKey || curitem.attr("shift") == "true"; // If shift is pressed it will allow multiple item selection in thumbs view
							curitem.removeAttr("shift");
							if (shift) {
								if (window.lastSelectedItem) // Last selected item, if shift is pressed
								{
									var lastItem = window.lastSelectedItem;
									window.lastSelectedItem = false;
									if (lastItem != curitem) //If current and last items are not same
									{
										var lastItemIndex = parseInt($(lastItem).attr("index"));
										var curItemIndex = parseInt($(curitem).attr("index"));
										//loop through items between last selected and current, and apply selection class
										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");
												}
											}
										}
										//reverse loop if below item selected first
										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 only single item selection (without shift)
								if (curitem.hasClass("fileBoxSelected")) // If already selected, unselect. Select otherwise
								{
									curitem.removeClass("fileBoxSelected");
									window.lastSelectedItem = false;
								} else {
									curitem.addClass("fileBoxSelected");
									window.lastSelectedItem = curitem;
								}
							}
							// Remove selection range, it messes up UI as all the text came between selection highlights in native browser selection manner
							if (window.getSelection) // Modern Browsers
							{
								var selection = window.getSelection();
								if (selection.removeAllRanges) {
									selection.removeAllRanges();
								}
							}
							if (document.getSelection) // IE
							{
								var selection = document.getSelection();
								if (selection.removeAllRanges) {
									selection.removeAllRanges();
								}
							}
							//Show selection info bar if items are hidden in paging.
							if ($(t).find("li.fileBoxSelected").length == window.listingInfo.totalVisibleItems) {
								showSelectionInfoBar();
							}
							$(this).blur();
							return false;
						});
						//Event of double click on thumb icon loads that folder, if file selected, downloads that file.

						var hasTouch = false; // Check if application is loaded on touch supported device
						var agent = navigator.userAgent.toLowerCase();
						if (agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0 || agent.indexOf('android') >= 0)
						{
							hasTouch = true;
						}
						function thumbFolderEvent(elem) {
							$(".cluetip-default").remove();
							if ($(elem).hasClass("directoryThumb")) { // If directory
								window.current_page = o.pagingCurrentPage = 0;
								$(document).removeData("searchData");
								var loc = $(elem).find("a.imgLink").attr('rel').match(/.*\//);
								if (loc) {
									blockFileListingUI(true);
									setHashLocation(loc); // Just sets a location, loading of that folder will be done by hash listener.
									$(".cluetip-default").remove();
								}
							} else { // If file
								var extsToOpen = $(document).data("OPEN_NEW_WINDOW_EXTENSIONS"); // Extensions which should open in a window than download, ie. images
								var fileName = $(elem).find("a:first").attr("rel");
								var fileExt = "." + getFileExtension(fileName);
								if (extsToOpen && extsToOpen.length > 0 && fileExt.length > 0 && extsToOpen.has(fileExt)) { // If file to be shown in window
									window.open(fileName);
								} else {
									//Downloads item/file
									downloadItems(false, $(elem));
								}
							}
							$(elem).blur();
							return false;
						}
						if(!hasTouch)
						{
							$(t).find('LI.fileBox').unbind(o.thumbFolderEvent);
							$(t).find('LI.fileBox').bind(o.thumbFolderEvent, function(){
								thumbFolderEvent($(this));
							});
						}
						else
						{
							$(t).find('LI.fileBox').doubletap(function(event, elem){
								thumbFolderEvent(elem);
							});
						}
					} else { //Treeview
						$(t).find('TD A').unbind(o.folderEvent);
						$(t).find('TD A').bind(o.folderEvent, function (evt) { // Binds click to each file name, click on folder shows content of folder, downloads if file
							$("#cluetip").hide();
							if (evt.ctrlKey) // Ctrl + click opens context menu. A hack for laptop users. Stop event if ctrl+click.
							{
								evt.stopPropagation();
								evt.preventDefault();
								return false;
							}
							if ($(this).parent().hasClass("directory")) { // If directory
								window.current_page = o.pagingCurrentPage = 0;
								$(document).removeData("searchData");
								var loc = $(this).prev().attr('rel').match(/.*\//);
								if (loc) {
									setHashLocation(loc); // Just set hash in location bar, everything else done by hash listener
								}
							} else { // If file
								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)) {
									// If the file needs to be shown in window
									window.open(fileName);
								} else {
									// If file has to be downloaded
									downloadItems(false, $(this).closest("td"));
								}
							}
							$(this).blur();
							return false;
						});
					}
				}
				// Checkbox events for treeview

				function bindCheckboxEvents() {
					$("tr.jqueryFileTree").not(".file").find(".chkBox").unbind("click");
					$("tr.jqueryFileTree").not(".file").find(".chkBox").click(function () {
						checkUnCheckDirectory($(this).parent(), $(this).is(":checked")); //Check or uncheck parent directory checkbox if all items beneath are selected/not selected
						toggleMainCheckbox($(this).closest("table")); //Check or uncheck check all checkbox if all items are selected/not selected
						window.listingInfo.selectedEverything = false;
						$("#selectionOfItemsOptions").hide();
						// Show selection info bar if there are items hidden in paging
						if ($("#filesContainer").find(".chkBox:visible:checked").length == window.listingInfo.totalVisibleItems) {
							showSelectionInfoBar();
						}
					});
				}
				// Bind tree of items list

				function bindTree(t) {
					if (currentView() != "Thumbnail") {
						// For tree view only
						$(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) {
							// Expand icon click
							$(t).find('span.expandButton').unbind(o.folderEvent).bind(o.folderEvent, function (event, callback) {
								if ($(this).parent().hasClass('collapsed')) {
									// Expand
									$(this).parent().removeClass('collapsed').addClass('expanded');
									showTree($(this).parent(), escape($(this).attr('rel').match(/.*\//)), false, false, callback);
									$(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');
									var expandedFolders = $(document).data("expandedFolders");
									if (!expandedFolders) {
										expandedFolders = [];
									}
									if (expandedFolders.has(expandedFolder)) {
										expandedFolders.remove(expandedFolders.indexOf(expandedFolder));
									}
									$(document).data("expandedFolders", expandedFolders);
									reBuildListing(window.curTreeItems); // Rebuild items on screen
									// Scroll window to proper location for better user interface. As they dont have to scroll up. Non-IE only
									if (!o.buggyBrowser && $("span[rel='" + expandedFolder + "']:first").length > 0) {
										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();
				}
				// Remove directory and it's sub-elements, used when deleted

				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(escape(unescape(rel))) != 0) {
							newItems.push(curItem);
						}
					}
					window.curTreeItems = newItems;
				}
				//Hide directory and subitems from the list

				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();
						}
					});
				}
				//Move elements on tree when sorting applied, recursive method

				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));
							}
						});
					});
				}
				//Returns current paging size (Items to show on a page)

				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
					}
				}
				//Rebuid listing, rebind events and all other elements. Expects custom data to generate listing. Used in filter and other method when current items are modified ie. delete

				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;");
								}
							}
						});
					}
				}
				// Update page size and refresh layout

				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);
					}
				}
				// Change pager size on selection and refresh layout

				function changePagerSize(pageSize) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookiePageSize, pageSize, options);
					window.current_page = o.pagingCurrentPage = 0;
					updatePageSizeOnLayout(true);
				}
				//Handle pager size menu selection

				function handlePageSizeContextMenuEvents(action, el, pos, command) {
					$("#cluetip").hide();
					action = action == "all" ? 0 : action;
					changePagerSize(action);
					return false;
				}
				//Handle context menu of check boxes and various selection options. ie. select files modified today, this week etc

				function handleCheckBoxContextMenuEvents(action, el, pos, command) {
					$("#cluetip").hide();
					switch (action) {
					case 'checkall':
						selectDeselectAllItems(true); // Select all
						break;
					case 'uncheckall':
						selectDeselectAllItems(false); // Deselect all
						break;
					case 'toggle':
						// Toggle
						selectDeselectAllItems(false, true);
						break;
					case 'checkallfiles':
						//Select all Files
						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':
						// Select all Folders
						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':
						//Select items start with dot
						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':
						//Check items modified in 1 day
						checkModifiedItemsByDay(1);
						break;
					case 'checkweek':
						//Check items modified in 7 days
						checkModifiedItemsByDay(7);
						break;
					case 'checkmonth':
						//Check items modified in 30 days
						checkModifiedItemsByDay(30);
						break;
					case 'check2months':
						//Check items modified in 60 days
						checkModifiedItemsByDay(60);
						break;
					case 'check3months':
						//Check items modified in 90 days
						checkModifiedItemsByDay(90);
						break;
					}
				}
				// Method to check items modified in last n days. For both views

				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");
						}
					}
				}
				//Handle context menu events

				function handleContextMenuEvents(action, el, pos, command) {
					$("#cluetip").hide();
					if (command) {
						$(document).data("currentContext", {
							'action': action,
							'elem': el
						});
						command = decodeURIComponent(command); // Decode command associated with menu and evaluate it
						eval(command);
						clearContext();
					}
					return false;
				}
				// Few prototype entries
				// Add a method "has" to array
				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;
				};
				//Add "indexOf" method to array
				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;
					}
				}

				//Add Filter method in array if not available
				if (!('filter' in Array.prototype)) {
					Array.prototype.filter= function(filter, that /*opt*/) {
						var other= [], v;
						for (var i=0, n= this.length; i<n; i++)
							if (i in this && filter.call(that, v= this[i], i, this))
								other.push(v);
						return other;
					};
				}

				//Array diff operation
				Array.prototype.diff = function(a) {
					return this.filter(function(i) {return !(a.indexOf(i) > -1);});
				};

				//Add item to basket
				function addToBasket(context) {
					var elem = false;
					var exist = false;
					var _fileName = "";
					if (context) // Select context and set filename to add to the basket
					{
						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)) { // If basket not avaiable already, create one in document cache
						$(document).data(o.BasketDataKey, new Array());
					}
					var ItemsInTheBasket = $(document).data(o.BasketDataKey); // Items in the basket
					var selectedFiles = {};
					if (window.listingInfo.selectedEverything) // If all items in the list is selected, loop through them and add to the basket
					{
						var listItems = window.curTreeItems;
						if (window.listingInfo.filtered) {
							listItems = window.matchedItems;
						}
						for (var i = 0; i < listItems.length; i++) {
							var curItem = listItems[i];
							var filePath = unescape(curItem.root_dir) + unescape(curItem.name);
							filePath = filePath.replace("//", "/");
							if (!ItemsInTheBasket.has(filePath)) {
								ItemsInTheBasket.push(filePath);
								items.push(filePath);
							}
						}
					} else {
						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) { // Only if item not available in the basket, add it
							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) {
						// Show message if file exist in the basket
						$.growlUI(getLocalizationKey("BasketFileAddedAlreadyText"), getLocalizationKey("BasketFileAddedAlreadyDetailsText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						return;
					} else {
						// If nothing to add
						$.growlUI(getLocalizationKey("BasketNothingSelectedToAddText"), getLocalizationKey("BasketNothingSelectedToAddDetailsText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						return;
					}
				}
				//Method to rebuild basket

				function rebuildBasket(msg, isWarning) {
					if (!$(document).data(o.BasketDataKey)) {
						$(document).data(o.BasketDataKey, new Array());
					}
					//Items in the basket
					var ItemsInTheBasket = $(document).data(o.BasketDataKey);
					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);
					}
					//Loop through items and build a list, bind events
					for (var i = 0; i < ItemsInTheBasket.length; i++) {
						if ($("ul.filesSelectedInBasket").find("li[rel='" + escape(ItemsInTheBasket[i]) + "']").length == 0) {
							$("ul.filesSelectedInBasket").prepend('<li rel="' + escape(ItemsInTheBasket[i]) + '"><label>' + ItemsInTheBasket[i] + '</label> <span>[<span class="error pointer">' + getLocalizationKey("BasketRemoveLinkText") + '</span>]</span></li>').find("span.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).closest("li");
								parElem.fadeOut(500, function () {
									parElem.remove();
								});
								return true;
							});
						}
					}
					//Show download basket
					showDownloadBasket(ItemsInTheBasket);
					//Clear all completed items link event
					$("#submitActionBasket").find(".clearCompleted").unbind().click(function () {
						$(this).blur();
						if (confirm(getLocalizationKey("BasketClearAllConfirmMessage"))) {
							$(document).data(o.BasketDataKey, new Array());
							$("ul.filesSelectedInBasket").empty();
							rebuildBasket();
						}
					});
					//Download link event
					$("#submitActionBasket").find(".download").unbind().click(function () {
						$(this).blur();
						if ($(this).hasClass("advanced")) {
							downloadBasket(null, "applet");
						} else {
							downloadBasket(null, "");
						}
					});
					//To download quickly using advanced download
					var quickDLList = $(document).data(o.BasketDataKeyQuickDownload);
					if (quickDLList && quickDLList.length > 0) {
						downloadBasket(null, "applet", true);
					}
				}
				//Show download basket

				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"
						});
					}
				}
				//Download basket

				function downloadBasket(elem, opt, quick) {
					if (opt == "") {
						//Download as zip
						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, quick);
							});
						} else {
							handleAppletBrowse(true, quick);
						}
					}
				}
				// Method to download selected items quickly using advanced download (java applet)

				function quickAdvancedDownload(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("//", "/"));
					}
					var selectedFiles = {};
					var ItemsToDownloadQuick = [];
					var CurrentItemsInTheBasket = $(document).data(o.BasketDataKey);
					CurrentItemsInTheBasket = CurrentItemsInTheBasket || [];
					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") {
								try{
									file = decodeURIComponent(unescape($(this).find("a:first").attr("rel")));
								}
								catch(e)
								{
									file = (unescape($(this).find("a:first").attr("rel")));
								}
							} else {
								try{
									file = decodeURIComponent(unescape($(this).closest("tr").find("a:first").attr("rel")));
								}
								catch(e)
								{
									file = (unescape($(this).closest("tr").find("a:first").attr("rel")));
								}
							}
							if (!items.has(file)) {
								items.push(file);
							}
							if (!ItemsToDownloadQuick.has(file)) {
								ItemsToDownloadQuick.push(file);
							}
							if (!CurrentItemsInTheBasket.has(file)) {
								CurrentItemsInTheBasket.push(file);
							}
							$(this).click();
						});
					}
					if (!items.has(filePath) && filePath.length > 0) {
						items.push(filePath);
					}
					if (!ItemsToDownloadQuick.has(filePath) && filePath.length > 0) {
						ItemsToDownloadQuick.push(decodeURIComponent(unescape(filePath)));
					}
					if (!CurrentItemsInTheBasket.has(filePath) && filePath.length > 0) {
						CurrentItemsInTheBasket.push(decodeURIComponent(unescape(filePath)));
					}
					exist = ItemsToDownloadQuick.has(filePath);
					if (items.length > 0) {
						$(document).data(o.BasketDataKeyQuickDownload, ItemsToDownloadQuick);
						$(document).data(o.BasketDataKey, CurrentItemsInTheBasket);
						rebuildBasket();
						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;
					}
				}
				//Strip down emails

				function stripDownEmails(email) {
					var simpleEmails = "";
					if (email.indexOf(";") < 0) email = email.replace(/,/g, ";");
					var emails = email.split(";");
					for (var x = 0; x < emails.length; x++) {
						var s = emails[x];
						if (s.indexOf("<") >= 0 && s.indexOf(">") >= 0) {
							s = s.substring(s.indexOf("<") + 1, s.indexOf(">")); //pull out the email in a pretty formatted version "Spink, Ben <ben@crushftp.com>"
						}
						s = $.trim(s); //remove white space
						if (s == "") continue;
						if (s.indexOf("@") > 0 && s.lastIndexOf(".") > s.indexOf("@")) simpleEmails += s + ",";
					}
					if (simpleEmails != "") simpleEmails = simpleEmails.substring(0, simpleEmails.length - 1);
					return simpleEmails;
				}
				//Validate emails

				function validateEmail(email, strict) {
					if (strict) {
						var emails = email.split(";");
						var ok = true;
						var foundOne = false;
						for (var x = 0; x < emails.length; x++) {
							var s = emails[x];
							if (s == "") continue;
							foundOne = true;
							if (s.indexOf("@") > 0 && s.lastIndexOf(".") > s.indexOf("@")) {
								//good email
							} else ok = false;
						}
						if (!foundOne) ok = false;
						return ok;
					} else {
						return email.indexOf("@") > 0 && email.lastIndexOf(".") > email.indexOf("@");
					}
				}
				//Validate share form

				function validateShareForm() {
					var validated = true;
					//Loop through required fields
					$("#shareOptionDiv").find(".required").each(function () {
						var $elm = $(this);
						$elm.parent().find("span.requiredField").remove();
						if (($elm.is("#emailFrom") || $elm.is("#emailTo")) && !$("#sendEmail").is(":checked")) {
							return;
						}
						if ($elm.val().length == 0) {
							if (validated) {
								$elm[0].focus();
							}
							if ($elm.is(".email")) {
								$elm.after(" <span class='requiredField'>* <img src='" + o.ImageFilePath + "help.png'  alt='help' title='" + getLocalizationKey("ShareActionEmailValidationFailureHelpToolTip") + "' /></span>");
								$elm.next().find("img").cluetip({
									splitTitle: '^',
									showTitle: false,
									width: 300,
									cluetipClass: 'default-ontop',
									positionBy: 'mouse',
									mouseOutClose: true,
									dropShadowSteps: 0,
									onShow: function () {
										$("#cluetip").css("z-index", "9999").css("width", "320px");
										var _offset = $elm.next().find("img").offset();
										var _left = _offset.left;
										if (_left) {
											$("#cluetip").css("left", _left + 20 + "px");
										}
									}
								});
							} else {
								$elm.after(" <span class='requiredField'>*</span>");
							}
							validated = false;
						}
					});
					//Validate emails
					$("#shareOptionDiv").find(".email").each(function () {
						var $elm = $(this);
						if ($elm.parent().find("span.requiredField").length > 0 || (($elm.is("#emailFrom") || $elm.is("#emailTo") || $elm.is("#emailCc") || $elm.is("#emailBcc")) && !$("#sendEmail").is(":checked"))) {
							return;
						}
						var val = $elm.val();
						val = $.trim(val);
						if (val.length > 0) {
							val = stripDownEmails(val);
							if (!validateEmail(val, true)) {
								$elm.after(" <span class='requiredField'>* <img src='" + o.ImageFilePath + "help.png'  alt='help' title='" + getLocalizationKey("ShareActionEmailValidationFailureHelpToolTip") + "' /></span>");
								$elm.next().find("img").cluetip({
									splitTitle: '^',
									showTitle: false,
									width: 300,
									cluetipClass: 'default-ontop',
									positionBy: 'mouse',
									mouseOutClose: true,
									dropShadowSteps: 0,
									onShow: function () {
										$("#cluetip").css("z-index", "9999").css("width", "320px");
										var _offset = $elm.next().find("img").offset();
										var _left = _offset.left;
										if (_left) {
											$("#cluetip").css("left", _left + 20 + "px");
										}
									}
								});
								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;
				}

				//Change icon of selected files
				function changeIcon(context)
				{
					var el = false;
					if (context) {
						el = currentContext();
					}
					var _fileName = "";
					if (el) {
						_fileName = unescape($(el).find("a:first").attr("rel"));
					}
					var $elem = $("#iconChangeDiv");
					$.blockUI({
						message: $elem,
						css: {
							width: '400px',
							padding: '15px',
							'margin-left': '-200px',
							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: function(){
							$elem.find("input.variable").val("");
							var rootPath = "";
							if (currentView() != "Thumbnail") {
								rootPath = $(el).closest("tr").attr("rel");
							}
							else {
								rootPath = $(el).find("div.imgTitle").find("a").attr("rel");
							}
							$elem.find("input#uploadPath").val(rootPath);
							$elem.find("input#changeIconItem").val(_fileName);
							$("#changeIconWindowSelectedFiles", $elem).html("<br />" + _fileName + "<br/>");
						}
					});
					$("a.cancel", $elem).unbind().click(function () {
						$.unblockUI();
					});
					$("a.update", $elem).unbind().click(function () {
						if($elem.find("input[type='file']").val()=="")
						{
							alert(getLocalizationKey("ChangeIconFileSelectAlertText"));
							return false;
						}
						else
						{							
							$("#iframeUploadIcon").unbind().bind("load", function(){
								refreshPreivewIcon(el);
							});
							$elem.find("form").submit();
							$.unblockUI();
							selectDeselectAllItems(false);
						}
					});
				}

				function refreshPreivewIcon(el)
				{
					$(el).attr("preview","true");
					if (currentView() == "Thumbnail") {
						var _title = $(el).attr("title");
						var fileLink = $(el).find("a.imgLink");
						var filePath = fileLink.attr("href");
						if(_title.indexOf("command=getPreview")>=0)
						{
							_title = _title.replace("command=getPreview", "command=getPreview&random=" + Math.random());						
						}
						else
						{
							_title = "<img src=\"" + o.ajaxCallURL + "?command=getPreview&size=3&path=" + encodeURIComponent(unescape(filePath)) + "&random="+Math.random()+"&frame=1" + "\" border=\"0\" />" + _title;
						}
						$(el).attr("title", _title);						
						vtip($(el));
					}
					zoomInOutView(zoomSlider.slider("value"), el);					
				}
				
				//Share files
				function shareFile(context) {
					var el = false;
					if (context) {
						el = currentContext();
					}
					$("#shareOptionDiv").html($("#shareOptionDiv").data("html"));
					//Apply share window customizations
					applyShareCustomizations();
					//Set mask to time field
					$("#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);
						}
					});
					//Set mask to day field
					$("#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).attr("date", prettyDate);
							if (window.Shareyyyymmdd) {
								var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
								prettyDate = myDate.getFullYear() + '/' + monthNames[myDate.getMonth()] + '/' + myDate.getDate();
								$("#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();
					$("#txtDate", "#shareOptionDiv").val(prettyDate).attr("date", prettyDate);
					if (window.Shareyyyymmdd) {
						var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
						prettyDate = myDate.getFullYear() + '/' + monthNames[myDate.getMonth()] + '/' + myDate.getDate();
					}
					var _nowDate = new Date();
					_nowDate.setDate(_nowDate.getDate() + 1);
					var _dateFormat = 'mm/dd/yy';
					if (window.Shareyyyymmdd) {
						_dateFormat = 'yyyy/MM/dd';
					}
					//Date picker
					$("#txtDate", "#shareOptionDiv").val(prettyDate).datepicker({
						dateFormat: _dateFormat,
						showOn: 'both',
						buttonImage: '/WebInterface/jQuery/images/calendar.png',
						buttonImageOnly: true,
						minDate: _nowDate
					}).change(function () {
						//Calculate date and time and show in days field
						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);
						var myDate = new Date();
						myDate.setDate(myDate.getDate() + days);
						var prettyDate = (myDate.getMonth() + 1) + '/' + myDate.getDate() + '/' + myDate.getFullYear();
						$("#txtDate", "#shareOptionDiv").val(prettyDate).attr("date", prettyDate);
						if (window.Shareyyyymmdd) {
							var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
							prettyDate = myDate.getFullYear() + '/' + monthNames[myDate.getMonth()] + '/' + myDate.getDate();
							$("#txtDate", "#shareOptionDiv").val(prettyDate);
						}
					});
					//Default values and show fields based on values
					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 = [];
					var itemList = [];
					//If everything is selecetd, share a folder
					if (window.listingInfo.selectedEverything) {
						var listItems = window.curTreeItems;
						if (window.listingInfo.filtered) {
							listItems = window.matchedItems;
						}
						for (var i = 0; i < listItems.length; i++) {
							var curItem = listItems[i];
							if (!itemList.has(curItem.name)) {
								itemList.push(curItem.name);
								fileName += curItem.name;
								fileNameOnly += curItem.name.substring(curItem.name.lastIndexOf("/", curItem.name.length - 2) + 1) + "\r\n";
								if (i + 1 < listItems.length) {
									fileName += "\r\n";
								}
							}
						}
					} else {
						//Else select chosen items
						if (currentView() != "Thumbnail") {
							selectedFiles = $("#filesContainer").find(".chkBox:visible:checked");
						} else {
							selectedFiles = $("#filesContainerDiv").find("li.fileBoxSelected:visible");
						}
						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(), "");
					if (fileName.length == 0) {
						$.growlUI(getLocalizationKey("ShareNothingSelectedGrowlText"), getLocalizationKey("NothingSelectedGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						return;
					}
					performAction("shareOptionDiv");
					if (!window.shareEmailBody) window.shareEmailBody = $("#emailBody").html();
					if (o.buggyBrowser) {
						window.shareEmailBody = window.shareEmailBody.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1\r$2');
					}
					$("#emailBody").text(window.shareEmailBody.replace(/{files}/g, 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);
				}
				// Share form submit action

				function performShareFormSubmit(destinationPath, fileName) {
					//Validate form first
					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("#"));
					//Build share object and submit
					var obj = {
						command: "publish",
						allowUploads: $("input#fullaccess", "#shareOptionDiv").is(":checked"),
						attach: $("input#attach", "#shareOptionDiv").is(":checked"),
						baseUrl: encodeURIComponent(baseURL),
						emailBcc: stripDownEmails($("input#emailBcc", "#shareOptionDiv").val()),
						emailBody: encodeURIComponent($("textarea#emailBody", "#shareOptionDiv").val()),
						emailCc: stripDownEmails($("input#emailCc", "#shareOptionDiv").val()),
						emailFrom: stripDownEmails($("input#emailFrom", "#shareOptionDiv").val()),
						emailSubject: encodeURIComponent($("input#emailSubject", "#shareOptionDiv").val()),
						emailTo: stripDownEmails($("input#emailTo", "#shareOptionDiv").val()),
						expire: $("input#txtDate", "#shareOptionDiv").attr("date") + " " + $("input#txtTime", "#shareOptionDiv").val(),
						paths: encodeURIComponent(fileName),
						publishType: $("input:checked", ".publishType").val(),
						sendEmail: $("input#sendEmail", "#shareOptionDiv").is(":checked")
					};
					$.ajax({
						type: "POST",
						url: o.ajaxCallURL,
						data: obj,
						success: function (response) {
							var responseText = 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(getLocalizationKey("ProblemWhileSharingGrowlText"), getLocalizationKey("ProblemWhileSharingDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						}
					});
				}
				//Copy item path/link action

				function copypath(context) {
					var el = false;
					if (context) {
						el = currentContext();
					}
					//If context allow, show link in a popup
					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(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("DirectLinkDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
					}
				}
				//Update keyword action

				function updateKeywords(context) {
					//Update keyword alert

					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(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("UpdateKeywordDescGrowlText"), 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(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();
					});
				}
				//Build a form and submit form to server in hidden way using iFrame

				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();
				}
				//Download items
				window.downloadItems = function (context, el, fileToDownload) {
					el = el || false;
					if ($(document).data("slideShowOnly")) { // For slideshow only version
						var fileName = encodeURIComponent(unescape(el));
						submitAction({
							'#command': "download",
							'#path': fileName,
							'#random': Math.random()
						});
					} else {
						if (context) {
							el = currentContext();
						}
						var count = 0;
						var stringToCopy = "";
						var totalSizeToDownload = 0;
						if (el) {
							var $curElem = $(el);
							stringToCopy = $curElem.find("a:first").attr("rel");
							count++;
							if (currentView() != "Thumbnail") {
								totalSizeToDownload += parseFloat(el.closest("tr").find("td.columnName").attr("sizeinbytes"));
							}
							else
							{
								totalSizeToDownload += parseFloat(el.attr("sizeinbytes"));
							}
						}
						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");
								if(el && el.length>0 && el.closest("tr").length>0)
								{
									if(el.closest("tr")[0] != parentElem[0])
									{
										totalSizeToDownload += parseFloat(parentElem.find("td.columnName").attr("sizeinbytes"));
									}
								}
								else
								{
									totalSizeToDownload += parseFloat(parentElem.find("td.columnName").attr("sizeinbytes"));
								}
							}
							else
							{
								if(el && el.length>0)
								{
									if(el[0] != parentElem[0])
									{
										totalSizeToDownload += parseFloat($(this).attr("sizeinbytes"));
									}
								}
								else
								{
									totalSizeToDownload += parseFloat($(this).attr("sizeinbytes"));
								}
							}
							var filePath = parentElem.find("a").attr("rel");
							filePath = filePath.replace("//", "/");
							stringToCopy += ":" + filePath;
							count++;
						});

						var maxAllowedDownloadSize = parseFloat($(document).data("maxAllowedDownloadSize"));

						if(maxAllowedDownloadSize>0 && totalSizeToDownload>maxAllowedDownloadSize)
						{
							$.growlUI(getLocalizationKey("maxAllowedDownloadSizeReached"), getLocalizationKey("maxAllowedDownloadSizeReachedText").replace("{size}",formatBytes(maxAllowedDownloadSize)), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
							return false;
						}

						if(fileToDownload)
						{
							stringToCopy = fileToDownload;
							count++;
						}
						if (count > 0) {
							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").next();
										}
									}
									if (el.hasClass("directory")) {
										downloadAsZip(el, true);
										return;
									}
								}
							}
							submitAction({
								'#command': "download",
								'#path': encodeURIComponent(unescape(stringToCopy)),
								'#random': Math.random()
							});
						} else {
							$.growlUI(getLocalizationKey("DownloadNothingSelectedGrowlText"), getLocalizationKey("NothingSelectedGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
							return;
						}
					}
					$.growlUI(getLocalizationKey("DownloadStartedAlertTitleText"), getLocalizationKey("DownloadStartedAlertDescText"), o.GrowlTimeout);
				}
				//Rename action

				function performRenameAction(context) {
					var el = false;
					if (context) {
						el = currentContext();
					}
					if (currentView() != "Thumbnail") { //Treeview
						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(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("RenameNothingSelectedGrowlText"), 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>";
						//Disable context menu on current item while rename is still not completed
						$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(); // Re-enable context menu
							bindContextMenu($curElem);
						});
						//Enter key press event
						$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();
							newName = newName.replace(/\//g, o.folderNameSpecialCharacterSubstitute).replace(/:/g, o.folderNameSpecialCharacterSubstitute);
							$curElem.find(".renameField").val(newName);
							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(response);
									var loadPreview = false;
									if (responseText.length > 0) {
										$.growlUI(getLocalizationKey("ProblemWhileRenamingGrowlText"), getLocalizationKey("ProblemWhileRenamingDescGrowlText") + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
									} else {
										if ($curElem.hasClass("directory")) {
											var link = $curElem.find("a");
											var nameToChange = link.attr("rel");
											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("span.expandButton").attr("rel", $curElem.closest("tr").attr("rel") + newName + "/");
											$curElem.find("div.renamePanel").remove();
											$curElem.find("span,a").show();
											$curElem.attr("name", newName);
											var filesContainer = $("table#filesContainer");
											//Method to update links of item after rename

											function updateLinks(old, update) {
												old = escape(old);
												update = escape(update);
												filesContainer.find("tr[rel='" + old + "']").each(function () {
													var curItem = $(this);
													if (curItem.find("td.directory").length > 0) {
														updateLinks(old + curItem.find("td.directory").attr("name") + "/", update + curItem.find("td.directory").attr("name") + "/");
													}
													curItem.attr("rel", update).attr("rootdir", update);
													curItem.find("a").attr("rel", update + curItem.find("a").closest("td").attr("name")).attr("href", unescape(update + curItem.find("a").closest("td").attr("name"))).attr("title", "<img src=\"" + o.ajaxCallURL + "?command=getPreview&size=3&path=" + encodeURIComponent(unescape(update + curItem.find("a").closest("td").attr("name"))) + "&random="+Math.random()+"&frame=1" + "\"" + " border='0' />");
												});
											}
											updateLinks(nameToChange, $curElem.closest("tr").attr("rel") + newName + "/");
											var expandedFolder = newName;
											var expandedFolders = $(document).data("expandedFolders");
											if (!expandedFolders) {
												expandedFolders = [];
											}
											if ($curElem.hasClass("expanded")) {
												if (!expandedFolders.has(expandedFolder)) {
													expandedFolders.push(expandedFolder);
												}
											} else {
												if (expandedFolders.has(expandedFolder)) {
													expandedFolders.remove(expandedFolders.indexOf(expandedFolder));
												}
											}
											$(document).data("expandedFolders", expandedFolders);
											//Update names and reference in document cache

											function updateNames(dirItems, _path, _old, _new, sub) {
												if (sub) {
													for (var item in dirItems) {
														if (dirItems[item].root_dir == _path) {
															dirItems[item].root_dir = unescape(_new);
															dirItems[item].href_path = dirItems[item].root_dir + dirItems[item].name;
															if (dirItems[item].type == "DIR") {
																updateNames(dirItems, unescape(_old) + dirItems[item].name + "/", unescape(_old) + dirItems[item].name + "/", unescape(_new) + dirItems[item].name + "/", true);
															}
														}
													}
												} else {
													for (var item in dirItems) {
														if (dirItems[item].name == unescape(_old)) {
															dirItems[item].name = unescape(_new);
															dirItems[item].href_path = dirItems[item].href = dirItems[item].root_dir + unescape(_new);
														}
														if (dirItems[item].root_dir == _path + unescape(_old) + "/") {
															dirItems[item].root_dir = _path + unescape(_new) + "/";
															dirItems[item].href_path = dirItems[item].root_dir + dirItems[item].name;
															if (dirItems[item].type == "DIR") {
																updateNames(dirItems, _path + unescape(_old) + "/" + dirItems[item].name + "/", _path + unescape(_old) + "/" + dirItems[item].name + "/", _path + unescape(_new) + "/" + dirItems[item].name + "/", true);
															}
														}
													}
												}
											}
											if (l && l.length > 0) {
												updateNames(l, pathName, oldName, newName);
											}
											if (window.curTreeItems && window.curTreeItems.length > 0) {
												updateNames(window.curTreeItems, pathName, oldName, newName);
											}
										} 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();
											$curElem.attr("name", newName);
											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(getLocalizationKey("ProblemWhileRenamingGrowlText"), getLocalizationKey("ProblemWhileRenamingDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
								}
							});
						});
					} else { // Thumbs view
						if (!el) {
							$.growlUI(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("RenameNothingSelectedGrowlText"), 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>&nbsp;&nbsp;<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();
							newName = newName.replace(/\//g, o.folderNameSpecialCharacterSubstitute).replace(/:/g, o.folderNameSpecialCharacterSubstitute);
							$renameBox.find(".renameField").val(newName);

							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(response);
									if (responseText.length > 0) {
										$.growlUI(getLocalizationKey("ProblemWhileRenamingGrowlText"), getLocalizationKey("ProblemWhileRenamingDescGrowlText") + 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(getLocalizationKey("ProblemWhileRenamingGrowlText"), getLocalizationKey("ProblemWhileRenamingDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
								}
							});
						});
					}
				}
				//Get action response text from server reply

				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;
				}
				//Get data of elements from privs of elements

				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;
				}
				//Render main navigation buttons and context menu items

				function renderButtons() {
					if ($(document).data("uploadOnly")) { //No buttons for upload only
						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();
						//Loop through menu item and make a button list
						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();
						}
					}
					//Highlight pase button if there are files copied
					highlightPasteButton();
					if (window.slideshowOnly) {
						$("div.mainNavigation").find("a[href!='javascript:doLogout();']").parent().remove();
					}
					//Build context menu
					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();
							var val = text.substring(1, text.indexOf(":") - 1);
							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);
							//command will be added to button's attribute, command will be evaluated on button click
							mainMenu.append('<li class="' + val.toLowerCase().replace(/ /g, "") + '"><a href="javascript:void(0);" command="' + unescape(command) + '">' + text + '</a></li>');
						}
					}
					if ($(document).data("username") == "anonymous") {
						//No logout link for anonymous
						$("ul.topnav,#myMenu").find("a:contains('Logout')").parent().remove();
					} else {
						$("ul.topnav,#myMenu").find("a:contains('Login')").parent().remove();
					}
					//Apply customization options
					applyCustomizations();
					var _loc = $(document).data("localizations");
					if (mainMenu && _loc["CopyLinkText"] && mainMenu.find("li.copydirectlink").length > 0 && mainMenu.find("li.copydirectlink").find("a").length > 0) {
						mainMenu.find("li.copydirectlink").find("a").text(_loc["CopyLinkText"]);
					}
					$("#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();
				}
				//Clear current context
				window.clearContext = function () {
					$(document).removeData("currentContext");
				}
				//Retrive current context
				window.currentContext = function () {
					var curElem = $(document).data("currentContext");
					clearContext();
					if (curElem) {
						return curElem.elem;
					} else {
						return false;
					}
				}
				//Init manage shares
				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 || "";
						}
					}
					//Sorting for manage shares popup

					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");
							}
						});
					}
					//Checkbox events for manage share popup

					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");
					}
					//Alert for manage share

					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);
					}
					//Replace string common method for manage shares popup

					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> ");
					//Select temp accounts and show them in popup
					var obj = {
						command: "getTempAccounts",
						random: Math.random()
					};
					$.ajax({
						type: "POST",
						url: o.ajaxCallURL,
						data: obj,
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							errorThrown = errorThrown || "getTempAccounts failed";
							$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
							elem.find("tbody").empty();
							elem.find("tbody").append("<tr><td colspan='8'>"+ getLocalizationKey("ManageShareWindowNothingToShowMessageText") +"</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();
								//Loop through items, build table and show in popup
								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;width:180px;overflow: hidden;'>" + 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><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, "&gt;").replace(/%3C/g, "&lt;")) + "</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>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 {
								//If nothing to show
								elem.find("tbody").empty();
								elem.find("tbody").append("<tr><td colspan='8' style='text-align:center;'>"+getLocalizationKey("ManageShareWindowNothingToShowMessageText")+"</td></tr> ");
								$(".cancelButton", manageSharePanel.parent()).hide();
							}
							//Hover effects
							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();
									scrollToElement($(this));
									$(this).next().show();
								} else {
									$(this).next().hide().prev().removeClass("rowHoverFixed");
								}
							});
							//Refresh manage shares popup
							$(".refreshBtn", manageSharePanel.parent()).unbind().click(function () {
								$(this).blur();
								initManageShares(elem);
							});
							//Remove shared item event
							$(".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(getLocalizationKey("ManageShareWindowDeleteAccountConfirmationText").replace("{count}", totalItems))) {
/*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) {
												errorThrown = errorThrown || "deleteTempAccount failed";
												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(getLocalizationKey("ManageShareWindowUserDeletedMessageText").replace("{name}", curItem.text), "green", 3000);
												}
												initManageShares(elem);
											}
										});
									}
								} else {
									manageShareAlert(getLocalizationKey("ManageShareWindowNothingSelectedToDeleteMessageText"), "red");
								}
								return false;
							});
						}
					});
				}
				//Login status thread

				function userLoginStatusCheckThread() {
					if (!$(document).data("loginStatusThreadRunning") && !window.loginStatusThreadInterval) {
						window.loginStatusThreadInterval = setInterval(
						function () {
							var targetUrl = window.location.toString().replace(hashListener.getHash().toString(), "");
							bindUserName(false, function (response, username) {
								if (response == "failure") {
									window.location = targetUrl;
								}
							});
						}, 600000);
					}
				}
				//Bind user name

				function bindUserName(isInit, callBack) { /* Data to POST to receive file listing */
					var obj = {
						command: "getUsername",
						random: Math.random()
					}; /* Make a call and receive list */
					var username = "anonymous";
					$.ajax({
						type: "POST",
						url: o.ajaxCallURL,
						data: obj,
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							errorThrown = errorThrown || "getUsername failed";
							$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
							callBack("failure", username);
						},
						success: function (msg) {
							var responseText = msg;
							try {
								var response = msg.getElementsByTagName("response");
								response = IE(response[0]).textContent;
								if (response == "success") {
									username = msg.getElementsByTagName("username");
									username = IE(username[0]).textContent;
								}
								username = username || "";
								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);
								}
							}
						}
					});
				}
				//Generate random password

				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;
				}
				//Bind user customization info

				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) {
							errorThrown = errorThrown || "getUserInfo failed";
							$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
						},
						success: function (msg) {
							var responseText = msg;
							var buttons = msg.getElementsByTagName("buttons_subitem");
							//Go through various customizations option and show items based on customization
							if (msg.getElementsByTagName("expire_password_when")[0]) {
								var expire_password_when = IE(msg.getElementsByTagName("expire_password_when")[0]).textContent;
								if (expire_password_when && expire_password_when.length > 0) $.growlUI(getLocalizationKey("PasswordExpiringMsgText"), expire_password_when, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
							}
							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();
							displayWelcomeNote();
							if (!$(document).data("slideShowOnly")) {
								if (currentView() == "Thumbnail") showTree($("#filesContainerDiv"), encodeURIComponent(o.root), false);
								else showTree($("#filesContainer"), encodeURIComponent(o.root), false);
							}
						}
					});
				}
				//Serialize form
				window.serializeForm = function (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("&");
				}
				//Show welcome note

				function displayWelcomeNote() {
					var $elem = $("div#welcomeFormPanel");
					var userName = $(document).data("username");
					var buttonText = getLocalizationKey("WelcomeFormOkButtonText");
					//Get form from server named messageForm, build form if exist and show to user
					getCustomForm("messageForm", function (data, hasForm, formName, showAlways) {
						if (hasForm) {
							if (!showAlways) //If not to show always and shown already once, do nothing
							{
								var formShown = $.cookie(o.CookieWelcomeNote + "_" + userName + "_" + formName);
								if (formShown && formShown.length > 0) return false;
							}
							//Build form and show in a popup
							var welcomeForm = $("div.welcomeForm", "#welcomeFormPanel");
							welcomeForm.html("<form id='frmWelcome'>" + data + "</form>").find("table").css("text-align", "left");
							setCustomFormFieldAttributes(welcomeForm)
							attachCalendarPopup(welcomeForm);
							$("button#resetPasteForm", welcomeForm).unbind().click(function (event) {
								welcomeForm.clearForm();
								event.stopPropagation();
								event.preventDefault();
							});
							//Display error message for welcome note

							function displayError(msg) {
								var form = $("table.customForm", welcomeForm);
								if (form.prev().hasClass("attention")) {
									form.prev().remove();
								}
								form.before("<div class='attention'>" + msg + "</div>");
								form.prev().css("float", "none");
							}
							//Submit action
							$("button.submitForm", welcomeForm).unbind().click(function (event) {
								event.stopPropagation();
								event.preventDefault();
								if (!validateForm("", welcomeForm)) {
									return;
								}
								var messageForm = welcomeForm;
								var formClone = messageForm.find("form");
								messageForm = serializeForm(formClone[0]);
								if (messageForm.length == 0) {
									$.unblockUI();
									return;
								}
								messageForm += "&command=messageForm&random=" + Math.random();
								var obj = messageForm;
								welcomeForm.find("h2").addClass("spinner");
								$.ajax({
									type: "POST",
									url: o.ajaxCallURL,
									data: obj,
									error: function (XMLHttpRequest, textStatus, errorThrown) {
										errorThrown = errorThrown || "messageForm failed";
										displayError("Error : " + errorThrown);
									},
									success: function (msg) {
										$("#welcomeFormPanel").find("h2").removeClass("spinner");
										var responseText = 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(getLocalizationKey("WelcomeNoteSubmitFormFailureMsgText"));
										}
									}
								});
								return false;
							});
							$.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);
				}
				//Load directory preview in top of window corner

				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();
					});
				}
				//Get localization key

				function getLocalizationKey(key) {
					var _loc = $(document).data("localizations");
					var defaultText = localizations[key];
					if (_loc && _loc[key]) {
						defaultText = _loc[key];
					}
					return defaultText;
				}
				//Apply localizations
				window.applyLocalizations = function () {
					var _loc = $(document).data("localizations"); //All localizations from cache
					if (_loc) {
						for (var i in _loc) //Loop through localizations
						{
							if (i) {
								var key = i.toString();
								var val = _loc[i].toString();
								if (key && (val || val == "")) {
									//If button or input, set value
									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) //If localization is for multiple items, set html
									{
										$("." + key).html(val);
									} else {
										$("#" + key).html(val);
									}
								}
							}
						}
						//Various hard coded localization
						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();
					}
				}
				//Apply customizations

				function applyCustomizations() {
					var customizations = $(document).data("customizations"); //Customizations from cache
					if (!customizations) return;
					for (var item in customizations) //Loop through customizations
					{
						var custItem = customizations[item];
						//Switch from key and apply customization based on key and value
						switch (custItem.key) {
						case "redirectRoot":
							//Redirect root
							window.redirectRoot = custItem.value;
							break;
						case "shareyyyymmdd":
							// If share window to yse yyyymmdd format
							window.Shareyyyymmdd = custItem.value == "true";
							break;
						case "customformyyyymmdd":
							// If custom forms has to use yyyymmdd format for date
							window.CustomFormyyyymmdd = custItem.value == "true";
							break;
						case "logo":
							//Logo to show on layout
							$("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":
							//Allignment of logo on screen
							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
							document.title = custItem.value;
							break;
						case "header":
							//Header on layout
							$("div#headerText").html(custItem.value);
							break;
						case "headerTextColor":
							//Header text color
							$("#headerContent").css("color", custItem.value);
							break;
						case "headerTextSize":
							//Header text size
							$("#headerContent").css("font-size", custItem.value);
							break;
						case "headerTextStyle":
							//Header text style
							if (custItem.value.indexOf("bold") >= 0) {
								$("#headerContent").css("font-weight", custItem.value);
							} else {
								$("#headerContent").css("font-style", custItem.value);
							}
							break;
						case "headerTextAlign":
							//Header text aling
							$("div#headerText").css("float", custItem.value);
							break;
						case "headerBackgroundColor":
							//Header background color
							$("#headerContent").css("background-color", custItem.value);
							break;
						case "footer":
							//Footer html
							$("div.footerContent").html(custItem.value);
							break;
						case "footerTextColor":
							//Footer text color
							$.cssRule({
								"div.footerContent": [
									["color", custItem.value]
									]
							});
							break;
						case "footerTextSize":
							//Footer text size
							$.cssRule({
								"div.footerContent": [
									["font-size", custItem.value]
									]
							});
							break;
						case "footerTextStyle":
							//Footer text style
							if (custItem.value.indexOf("bold") >= 0) {
								$.cssRule({
									"div.footerContent": [
										["font-weight", custItem.value]
										]
								});
							} else {
								$.cssRule({
									"div.footerContent": [
										["font-style", custItem.value]
										]
								});
							}
							break;
						case "footerTextAlign":
							//Footer text alignment
							$.cssRule({
								"div.footerContent": [
									["text-align", custItem.value]
									]
							});
							break;
						case "footerBackgroundColor":
							//Footer background color
							$.cssRule({
								"div.footerContent": [
									["background-color", custItem.value]
									]
							});
							break;
						case "uploadOnly":
							//If layout need to be upload only
							if (custItem.value.toLowerCase() == "true") {
								makeItUploadOnly();
							}
							break;
						case "slideShowOnly":
							//If layout need to be slideshow only
							if (custItem.value.toLowerCase() == "true") {
								if (!window.forSlideshow) {
									makeItSlideShowOnly();
								}
							}
							break;
						case "popupBackgroundColor":
							//Popup background color
							$(document).data("popupBackgroundColor", custItem.value);
							break;
						case "popupBorderColor":
							//Popup border color
							$(document).data("popupBorderColor", custItem.value);
							break;
						case "mainBackgroundColor":
							//Body background color
							$.cssRule({
								"body": [
									["background-color", custItem.value]
									]
							});
							break;
						case "mainBackgroundImage":
							//Body background image, no-repeat
							$.cssRule({
								"body": [
									["background-image", "url(" + custItem.value + ")"],
									["background-repeat", "no-repeat"]
									]
							});
							break;
						case "mainBorderColor":
							//Body border color
							$.cssRule({
								"body": [
									["border", "1px solid " + custItem.value]
									]
							});
							break;
						case "buttonFontColor":
							//Main navigation button font color
							$.cssRule({
								"ul.topnav li a": [
									["color", custItem.value]
									]
							});
							break;
						case "buttonHoverFontColor":
							//Main navigation button font color on hover
							$.cssRule({
								"ul.topnav li a:hover": [
									["color", custItem.value]
									]
							});
							break;
						case "buttonBackgroundColor":
							//Main navigation button font background color
							$.cssRule({
								"ul.topnav li a,.mainNavigation": [
									["background-color", custItem.value]
									]
							});
							$.cssRule({
								"ul.topnav": [
									["background-color", custItem.value]
									]
							});
							break;
						case "buttonHoverColor":
							//Main navigation button background color on hover
							$.cssRule({
								"ul.topnav li a:hover": [
									["background-color", custItem.value]
									]
							});
							break;
						case "buttonBackgroundImage":
							//Main navigation button background image
							$.cssRule({
								"ul.topnav li a": [
									["background-image", "url(" + custItem.value + ")"],
									["background-repeat", "no-repeat"]
									]
							});
							break;
						case "buttonHoverImage":
							//Main navigation button background image on hover
							$.cssRule({
								"ul.topnav li a:hover": [
									["background-image", "url(" + custItem.value + ")"],
									["background-repeat", "no-repeat"]
									]
							});
							break;
						case "listBackgroundColor":
							//Item listing background color
							$.cssRule({
								"#filesListing": [
									["background-color", custItem.value]
									]
							});
							break;
						case "listTextColor":
							//Item listing font/text color
							$.cssRule({
								"#filesListing": [
									["color", custItem.value]
									]
							});
							$.cssRule({
								"#filesListing a": [
									["color", custItem.value]
									]
							});
							break;
						case "listTextSize":
							//Item listing text size
							$.cssRule({
								"#filesListing,tr.jqueryFileTree, #filesListing a": [
									["font-size", custItem.value]
									]
							});
							break;
						case "listTextStyle":
							//Item listing text style ie. bold, italic etc
							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 "listHeaderBackgroundColor":
							//Item listing header background color
							$.cssRule({
								"#filesListing td.header": [
									["background-color", custItem.value]
									]
							});
							break;
						case "listHeaderTextColor":
							//Item listing header text color
							$.cssRule({
								"#filesListing td.header": [
									["color", custItem.value]
									]
							});
							break;
						case "listHeaderTextSize":
							//Item listing header text size
							$.cssRule({
								"#filesListing td.header": [
									["font-size", custItem.value]
									]
							});
							break;
						case "listHeaderTextStyle":
							//Item listing header text style
							if (custItem.value.indexOf("bold") >= 0) {
								$.cssRule({
									"#filesListing td.header": [
										["font-weight", custItem.value]
										]
								});
							} else {
								$.cssRule({
									"#filesListing td.header": [
										["font-style", custItem.value]
										]
								});
							}
							break;
						case "listDefaultSortColumnIndex":
							//Item listing default sorting column
							$(document).data("listDefaultSortColumnIndex", custItem.value);
							break;
						case "listDefaultSortDirection":
							//Item listing default sort direction
							$(document).data("listDefaultSortDirection", custItem.value);
							break;
						case "listAlternateColor":
							//Item listing alternate item row background color
							$.cssRule({
								".jqueryFileTreeAlt": [
									["background-color", custItem.value + ""]
									]
							});
							break;
						case "listHoverColor":
							//Item listing background color on hover
							$.cssRule({
								".rowHover td, .rowHoverFixed td": [
									["background-color", custItem.value + " !important"]
									]
							});
							break;
						case "tooltipBackgroundColor":
							//Tooltip's background color
							$.cssRule({
								".tipsy-inner": [
									["background-color", custItem.value]
									]
							});
							break;
						case "tooltipTextColor":
							//Tooltip's text color
							$.cssRule({
								".tipsy-inner": [
									["color", custItem.value]
									]
							});
							break;
						case "CHECK_COL":
							//Enable/disable checkbox column
							$(document).data("disableCheckCol", custItem.value);
							break;
						case "NAME_COL":
							//Enable/disable name column
							$(document).data("disableNameCol", custItem.value);
							break;
						case "SIZE_COL":
							//Enable/disable size column
							$(document).data("disableSizeCol", custItem.value);
							break;
						case "MODIFIED_COL":
							//Enable/disable modified column
							$(document).data("disableModifiedCol", custItem.value);
							break;
						case "KEYWORDS_COL":
							//Enable/disable keywords column
							$(document).data("disableKeywordsCol", custItem.value);
							break;
						case "BROWSER_UPLOAD_START_TEXT":
							//Browser upload windo "start upload" button text to display
							$("#browserFileUpload").find("#submitAction").find("a.upload").text(custItem.value);
							break;
						case "shareThumbnail":
							//Settings to share thumbnail or not
							$(document).data("shareThumbnail", custItem.value);
							break;
						case "defaultShareMethod":
							//Default method to use while sharing
							$(document).data("defaultShareMethod", custItem.value);
							break;
						case "shareAdvanced":
							//Allow/dis-allow advanced sharing option
							$(document).data("shareAdvanced", custItem.value);
							break;
						case "shareAllowUploads":
							//Allow/dis-allow uploads while sharing
							$(document).data("shareAllowUploads", custItem.value);
							break;
						case "disableThumbnailHover":
							//Enable/disable thumbnail hover info popup setting
							$(document).data("disableThumbnailHover", custItem.value);
							break;
						case "disableTreeviewHover":
							//Enable/disable treeview item hover info popup setting
							$(document).data("disableTreeviewHover", custItem.value);
							break;
						case "autoAppletFlag":
							//Load applet automatically when page loads flag
							if (!$.cookie(o.CookieAutoAppletFlag)) window.autoAppletFlagSet(custItem.value);
							if (custItem.value == "true") $("#autoAppletFlag").attr("checked", "checked");
							break;
						case "showResume":
							//Show an option of resume in browser file upload window flag
							if (custItem.value == "false") {
								$("#browserFileUpload").find("label[for='chkUploadResume']").hide();
							} else {
								$("#browserFileUpload").find("label[for='chkUploadResume']").show();
							}
							break;
						case "pathBackgroundColor":
							// Path/Breadcrumbs background color
							$.cssRule({
								"#crumbs": [
									["background-color", custItem.value]
									]
							});
							break;
						case "pathTextColor":
							// Path/Breadcrumbs font color
							$.cssRule({
								"#crumbs li,#crumbs li a, #crumbs li a:visited": [
									["color", custItem.value]
									]
							});
							break;
						case "pathTextSize":
							// Path/Breadcrumbs text size
							$.cssRule({
								"#crumbs": [
									["font-size", custItem.value]
									]
							});
							break;
						case "quotaTextColor":
							// Quota text color
							$.cssRule({
								".quotaText": [
									["color", custItem.value]
									]
							});
							break;
						case "quotaTextSize":
							// Quota text size
							$.cssRule({
								".quotaText": [
									["font-size", custItem.value]
									]
							});
							break;
						case "quotaTextStyle":
							// Quota text style
							if (custItem.value.indexOf("bold") >= 0) {
								$.cssRule({
									".quotaText": [
										["font-weight", custItem.value]
										]
								});
							} else {
								$.cssRule({
									".quotaText": [
										["font-style", custItem.value]
										]
								});
							}
							break;
						case "quotaTextAlign":
							// Quota text allignment on screen
							$.cssRule({
								".quotaText": [
									["text-align", custItem.value]
									]
							});
							break;
						case "quotaBackgroundColor":
							// Quota text background color
							$.cssRule({
								".quotaText": [
									["background-color", custItem.value]
									]
							});
							break;
						case "commentsTextColor":
							// Comments text color
							$.cssRule({
								".comments": [
									["color", custItem.value]
									]
							});
							break;
						case "commentsTextSize":
							// Comments text size
							$.cssRule({
								".comments": [
									["font-size", custItem.value]
									]
							});
							break;
						case "commentsTextStyle":
							// Comments text style
							if (custItem.value.indexOf("bold") >= 0) {
								$.cssRule({
									".comments": [
										["font-weight", custItem.value]
										]
								});
							} else {
								$.cssRule({
									".comments": [
										["font-style", custItem.value]
										]
								});
							}
							break;
						case "commentsTextAlign":
							// Comments text allignment on screen
							$.cssRule({
								".comments": [
									["text-align", custItem.value]
									]
							});
							break;
						case "commentsBackgroundColor":
							// Comments background color
							$.cssRule({
								".comments": [
									["background-color", custItem.value]
									]
							});
							break;
						case "OPEN_NEW_WINDOW_EXTENSIONS":
							// Extensions to open in new window and void forced download
							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":
							//Generic icon to use in tree, no preview icon
							if (custItem.value && custItem.value.length > 0 && custItem.value == "true") {
								$(document).data("genericIconTree", true);
							}
							break;
						case "genericIconThumbnail":
							//Generic icon to use in thumbnails, no preview icon
							if (custItem.value && custItem.value.length > 0 && custItem.value == "true") {
								$(document).data("genericIconThumbnail", true);
							}
							break;
						case "maxAllowedDownloadSize":
							//Maximum size allowed to download
							if (custItem.value && custItem.value.length>0) {
								$(document).data("maxAllowedDownloadSize", custItem.value);
							}
							break;
						default:
							break;
						}
					}
					var destinationPath = hashListener.getHash().toString().replace("#", "");
					if (destinationPath.indexOf("/IMPULSEUpload/") > 0) //Upload only
					{
						makeItUploadOnly();
					}
				}

				//Get popup color
				function getPopupColor(bg) {
					if (bg) {
						return $(document).data("popupBackgroundColor") || "#FFF";
					} else {
						return $(document).data("popupBorderColor") || "#CCC";
					}
				}

				//Apply share popup customizations
				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');
							custItem.value = custItem.value.replace(/\\n/g, '\n');
							var emailVal = custItem.value;
							window.shareEmailBody = emailVal;
							$("textarea#emailBody", "#shareOptionDiv").html(emailVal);
							break;
						default:
							break;
						}
					}
				}

				//Switch to slideshow only mode
				function makeItSlideShowOnly() {
					$("#mainContent").hide();
					$(document).data("slideShowOnly", true);
					window.slideshowOnly = true;
					doSlideshow(true);
				}

				//Switch to upload only mode
				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);
				}

				//Show slideshow popup, if slideshow only cover whole page with slideshow
				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/slideshowView.html' + destinationPath + '" hspace="0" allowtransparency="false"></iframe>');
					$(window).bind("resize", function () {
						//When window resizes control and slideshow should resize its size
						resetSlideShowDimensions();
					});
				}

				//Quick view on item, allows preview of large image in popup of item (If item has preview, provides next-prev options). Uses colorboc plugin
				window.quickView = function () {
					var _html = [];
					var _itemHTML = "<p><a href=\"HREF\" fileName=\"FILENAME\" rel=\"QUICKVIEW\" title=\"TITLE\">TITLE</a></p>"; // Basic html used in colorbox mode
					var _fileName = false;
					var elem = currentContext();
					if (elem) {
						var $curElem = $(elem);
						_fileName = unescape($curElem.find("a:first").attr("rel")); //filename will be available if initiated using context menu, and will be shown as initial image in quick preview
					}
					var files = new Array();
					//Loop through items in current directory and build html for items which have preview
					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 == 0);
							if (!inValidImg) {
								var row = new Object();
								row['enabled'] = true;
								row['imageSrc'] = o.ajaxCallURL + '?command=getPreview&size=3&path=' + curItem['href_path'] + '&random='+Math.random()+'&frame=1';
								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();
						//Intiate colorbox
						$("a[rel='QUICKVIEW']", quickViewItems).colorbox({
							onClosed: function () {
								$("#quickViewItems").remove();
							},
							photo: true,
							open: true,
							current: "Item {current} of {total}"
						});
					} else {
						$.growlUI(getLocalizationKey("QuickViewNothingToShowGrowlText"), getLocalizationKey("QuickViewNoItemsAvailableGrowlText"), o.GrowlTimeout, "", o.GrowlWithCloseButton);
					}
				}

				//Method to expand all dirs in current listing to the first level
				window.expandDirsFirstLevel = function (expandItemsQueue) {
					var curPath = encodeURIComponent(unescape(hashListener.getHash().toString().replace("#", "")));
					curPath = curPath || "/";
					var expandItems = $("table#filesContainer").find("tr[rootdir='" + decodeURIComponent(curPath) + "']:visible");
					expandItemsQueue = expandItemsQueue || [];
					// Loop through items, find out which are not expanded. Make an array of such items and pass it to expandDir method
					expandItems.each(function () {
						var expandBtn = $(this).find("td.directory");
						if (!expandItemsQueue.has(escape(unescape(expandBtn.find("a").attr("rel")))) && expandBtn && !expandBtn.hasClass("expanded") && expandBtn.find("a").length > 0 && expandBtn.find("a").attr("rel")) {
							expandItemsQueue.push(escape(unescape(expandBtn.find("a").attr("rel"))));
						}
					});
					expandDir(expandItemsQueue); //Expand each items supplied as an array
				}

				//Expands directory passed as an array in parameter
				function expandDir(expandQueue) {
					if (expandQueue.length > 0) {
						var curDir = expandQueue.shift();
						curDir = $("table#filesContainer").find("span.expandButton[rel='" + curDir + "']");
						if (curDir.length > 0) {
							//Finds out relevant list item in listing and triggers expand event, once expand of current item completes it will recall expandDirsFirstLevel with same array passed to this method. Which will not have items that are expanded now in next call.
							curDir.trigger(o.folderEvent, function () {
								expandDirsFirstLevel(expandQueue);
							});
						} else {
							expandDirsFirstLevel(expandQueue);
						}
					} else {
						return;
					}
				}

				//performAction method is generally used in all context menu and main menu item's command
				window.performAction = function (elem, context) {
					var onBlockFn = null;
					if (elem == "expandFirstLevel") {
						//Expand first level of each dirs on list, treeview only
						if (currentView() == "Thumbnail") {
							$.growlUI(getLocalizationKey("TreeviewSpecificActionMsgTitleText"), getLocalizationKey("TreeviewSpecificActionMsgDescText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						} else {
							window.expandDirsFirstLevel(context);
						}
						return;
					} else if (elem == "upload") {
						//Open browser uploader window
						window.browserUploader(context);
						return;
					} else if (elem == "quickView") {
						//Open quick view popup
						quickView(context);
						return;
					} else if (elem == "delete") {
						//Remove selected item
						window.delete_items(context);
						return;
					} else if (elem == "rename") {
						//Rename selected item
						performRenameAction(context);
						return;
					} else if (elem == "cut") {
						//Cut selected item
						doCopy(context, true);
						return;
					} else if (elem == "copy") {
						//Copy selected item
						doCopy(context);
						return;
					} else if (elem == "paste") {
						//Paste copied/cut items
						doPaste(context);
						return;
					} else if (elem == "zip") {
						//Zip selected items and download
						downloadAsZip(context);
						return;
					} else if (elem == "download") {
						//Download selected items
						downloadItems(context);
						return;
					} else if (elem == "share") {
						//Open share window with selected items
						shareFile(context);
						return;
					} else if (elem == "addToBasket") {
						//Add selected items to download basket
						addToBasket(context);
						return
					} else if (elem == "quickAdvancedDownload") {
						//Quickly download selected items using advanced download applet
						quickAdvancedDownload(context);
						return
					} else if (elem == "showBasket") {
						//Show download basket
						showDownloadBasket(context);
						return;
					} else if (elem == "copyDirectLink") {
						//Copy link of selected item, opens popup with link
						copypath(context);
						return;
					} else if (elem == "updateKeywords") {
						//Open popup to update keywords of selected items
						updateKeywords(context);
						return;
					} else if (elem == "batchComplete") {
						//Complete batch
						batchComplete(context);
						return;
					} else if (elem == "logout") {
						//Logout
						doLogout(context);
						return;
					} else if (elem == "search") {
						//Open search window
						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") {
						//Open share option
						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") {
						//Open on page 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/slideshowView.html' + destinationPath + '" hspace="0" allowtransparency="false"></iframe>');
								$(window).bind("resize", function () {
									resetSlideShowDimensions();
								});
							},
							onUnblock: function () {
								$elem.find("div.content").empty();
							}
						});
					} else if (elem == "manageShares") {
						//Open manage shares popup
						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") {
						//Show keywords
						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 if (elem == "changeIcon") {
						//Open icon change window
						changeIcon(context);
					} 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) {}
				}

				//Scroll position of window to target element
				window.scrollToElement = function ($target) {
					if ($target.length) {
						var targetOffset = $target.offset().top;
						$('html,body').animate({
							scrollTop: targetOffset
						}, 500, false);
						return false;
					}
				}

				//Reset slideshow dimensions
				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);

						//Set the width and margin of popup to keep it in center if window resizes based on new viewport dimension
						$("div.blockUI.blockPage").css({
							width: viewportWidth + 'px',
							'margin-left': '-' + (viewportWidth / 2) - 15 + 'px',
							left: '50%'
						});
					}
				}

				//Close slideshow popup
				window.closeSlideshow = function () {
					$('#slideshowDiv').find('div.content').empty();
					$(window).unbind('resize');
					$.unblockUI();
				}

				//Set cookie to show/hide items start with a dot. Refresh view
				window.hideItemsStartingWithDot = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieHideItemStartingWithDot, flag, options);
					refreshView();
				}

				//Set cookie to show/hide checkbox columns. Refresh view
				window.hideCheckBoxColumn = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieHideCheckBoxColumn, flag, options);
					refreshView();
				}

				//Set cookie to show/hide filter box. Refresh view
				window.hideFilter = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieHideFilter, flag, options);
					refreshView();
				}

				//Set cookie to auto upload items as selection completes flag
				window.autoUploadFlagSet = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieAutoUploadFlag, flag, options);
				}

				//Set cookie to auto load applet as page completes loading
				window.autoAppletFlagSet = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieAutoAppletFlag, flag, options);
				}

				//Set cookie to use compression in upload/download flag
				window.noCompressionFlagSet = function (flag) {
					var options = {
						path: '/',
						expires: 365
					};
					$.cookie(o.CookieNoCompressionFlag, flag, options);
				}

				//Command to start tunnel in applet to boost speed
				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);
					}
				}

				//Command to stop tunnel in applet
				window.stopTunnel = function () {
					o.uploadURL = "/WebInterface/function/";
					o.downloadURL = "/WebInterface/function/";
					if ($(document).data("appletLoadedU")) {
						runAppletCommand(false, "COMMAND=TUNNEL:::ACTION=STOP", false);
					}
				}

				//Logout user
				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) {
							//Remove CrushAuth cookie and redirect to login page
							$.cookie("CrushAuth", "", {
								path: '/',
								expires: -1
							});
							document.location = "/WebInterface/login.html";
						}
					});
				}

				//Batch complete method
				window.batchComplete = function (elem) {
					$.ajax({
						type: "POST",
						url: "/WebInterface/function/",
						data: {
							command: "batchComplete"
						},
						success: function (response) {
							var s = getActionResponseText(response);
							if (s.toUpperCase().indexOf("SUCCESS") >= 0) {
								$.growlUI(getLocalizationKey("BatchCompleteText"), getLocalizationKey("BatchComplete"), o.GrowlTimeout, "", o.GrowlWithCloseButton);
							} else $.growlUI(getLocalizationKey("BatchCompleteText"), s, o.GrowlTimeout, "", o.GrowlWithCloseButton);
						}
					});
				}

				//Change password method
				window.changePassword = function (elem) {
					if ($("#new_password1")[0].value != $("#new_password2")[0].value) {
						alert(getLocalizationKey("PasswordNotMatchingMsgText"));
					} /*else if ($("#new_password1")[0].value.length < 4) {
						alert(getLocalizationKey("PasswordMustBeComplexMsgText"));
					} */
					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(response);
								if (s.toUpperCase().indexOf("PASSWORD CHANGED") >= 0) {
									alert(getLocalizationKey("PasswordChangedMsgText"));
									doLogout();
								} else alert(s);
							}
						});
					}
					return false;
				}

				//Perform search in directory, make ajax call based on options selected and show result on screen
				window.startSearch = function () {
					$("#searchDiv").block({
						message:  getLocalizationKey("SearchProcessNotificationText") + ' <a id="cancelAjax" href="#" style="color:#FFF;font-size:10px;">'+ getLocalizationKey("SearchProcessCancelText") +'</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 || "/"; //Path to perform search on
					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) {
							errorThrown = errorThrown || "searching failed";
							$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
						}
					});
					$("#cancelAjax").unbind().click(
						function () {
							$("#searchDiv").unblock();
							$_Request.abort();
							return false;
						}
					);
					return false;
				}

				//Get upload form from  if exist, execute callback
				function getUploadForm(callback) {
					var $_Request = $.ajax({
						type: "POST",
						url: o.ajaxCallURL,
						data: "command=getCustomForm&form=uploadForm",
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							$("#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;
				}

				//Get custom form from server, execute callback
				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 = '<input type="hidden" id="meta_form_name" name="meta_form_name" value="' + formName + '" /><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>&nbsp;&nbsp';
								}
								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;
				}

				//Validate custom forms
				window.validateForm = function (target, form) {
					form = form || $("table.customForm", "#divUploadPanel");
					var validated = true;
					//Loop through required items first
					form.find(".required_true").each(
					function () {
						if($(this).is(":disabled") || $(this).attr("readonly")) return;
						if ($(this).hasClass("chkbox")) { //If it is checkbox
							if (!$(this).is(":checked") && $(this).closest("td").find("input:checked").length == 0) {
								$(this).parent().addClass("validationFail")
								if (validated) {
									$(this).parent().focus();
								}
								validated = false;
							} else {
								$(this).parent().removeClass("validationFail");
							}
						} else { //If another input type
							if ($.trim($(this).val()).length == 0) {
								$(this).addClass("validationFail");
								if (validated) {
									$(this).focus();
								}
								validated = false;
							} else {
								$(this).removeClass("validationFail");
							}
						}
					});
					//Remove attention message, if exists already
					if (form.prev().hasClass("attention")) {
						form.prev().remove();
					}

					if (validated) {//If validated, allow click on submit
						$(target).removeClass("disabledClick");
					} else {
						//Else show proper message, disable submit
						$(target).addClass("disabledClick");
						form.before("<div class='attention'>" + getLocalizationKey("FormValidationFailText") + "</div>");
						form.prev().css("float", "none");
					}
					return validated; //Return result
				}

				//Show browser uploader popup
				window.browserUploader = function () {
					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 to load applet automatically and it has not loaded yet, load applet first
					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();
						setTimeout(findAppletDroppedFiles, 500);
						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);
						//For internet explorer show java applet in drop zone
						if ($("table.customForm", "#divUploadPanel").length == 0 && navigator.appName.indexOf("Explorer") >= 0) {
							window.showDrop();
							$(window).bind("resize", function () {
								window.showDrop();
							});
						}
						return;
					}

					window.showDrop(); //Drag/Drop zone for html5 and java applet

					if ($("div.popupWindow").length > 0) { //If shown already, do nothing
						var popup = $("div.popupWindow").show();
						popup.css($(document).data("uploaderCss"));
						setTimeout(findAppletDroppedFiles, 500);
						return;
					}
					if ($("#customUploadForm").length > 0) {
						//Show upload form if exist, bind events
						getUploadForm(function (data) {
							$("#customUploadForm").replaceWith(data);
							setCustomFormFieldAttributes($("#divUploadPanel"));
							attachCalendarPopup($("#divUploadPanel"));
							$("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();
										});
									}
								}
							});
						});
					}
					//Show form default
					if ($("table.customForm", "#divUploadPanel").length > 0) {
						$("#uploadDetailsTabAnchor").click();
					}

					//Hide upload window event
					$elem.find("#hideUploadPanel").unbind().click(function () {
						$("#browserFileUpload").parent().hide();
						if ($("#browserFileUpload").find("h2").hasClass("spinner")) {
							$("ul.topnav").find("a[href='javascript:browserUploader();'], a[href='javascript:performAction(\'upload\');']").addClass("bouncing_loader");
						}
						$(document).data("uploadWindowHidden", true);
						window.cancelDrop();
					});

					//Start upload
					$("div#browserFileUpload").find("a.upload").unbind().click(function () {
						startUploading();
						$(this).blur();
						return false;
					});

					//Clear items that are completed from the list
					$("div#browserFileUpload").find("a.clearCompleted").unbind().click(function () {
						$("span.completed", "ul.filesSelected").each(function () {
							$(this).closest("li").remove();
						});
						$(this).blur();
						return false;
					});

					//Advanced browse open dialog
					$("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;
					});

					//It uses different file input for each file selected, it is hidden once file is selected. It keeps adding new element as user selectes item
					if ($("li", "ul.filesSelected").length == 0) {
						var htmlForm = o.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));
						});
					}

					if ($("div.popupWindow").length == 0) {
						$("#mainContent").append("<div class='popupWindow'></div>");
						var popup = $("div.popupWindow");
						popup.css($(document).data("uploaderCss"));
						popup.append($elem);
					}

					//If items selected then show upload button
					showHideUploadBtn();

					//Do not allow window to be dragged in buggy browsers
					if (o.buggyBrowser) {
						$elem.parent().find("h2").css("cursor", "text");
					} else {
						$elem.parent().draggable({
							handle: "h2"
						});
					}
					setTimeout(findAppletDroppedFiles, 500);
					if (!$(document).data("slideShowOnly")) setupDND();
				}

				//Validate upload form and keep show drop panel open on screen
				window.uploadTabOK = function (o) {
					var r = validateForm(o);
					if (r && navigator.appName.indexOf("Explorer") >= 0) setTimeout(window.showDrop, 500);
					return r;
				}

				//Listen to files that are dropped and make a list
				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);
				}

				//File selection process, for advanced or native browse this method will make a list and bind various events, like remove selected item etc
				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, filesSelected, allFiles);
						} else {
							notSupportedBrowser = true;
						}
					} catch (e) //not all browsers support multi select
					{}
					if (notSupportedBrowser) {
						performFileSelect(obj);
					}
				}

				//Highlight paste button if files are copied
				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");
					}
					if ($("#browserFileUpload").find("h2").hasClass("spinner")) {
						$("ul.topnav").find("a[href='javascript:browserUploader();'], a[href='javascript:performAction(\'upload\');']").addClass("bouncing_loader");
					}
				}

				//Copy selected items
				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(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("CutNoFilesSelectedMessage"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						} else {
							$.growlUI(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("CopyNoFilesSelectedMessage"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						}
						return;
					}
					var filesCopied = 0;
					var directoriesCopied = 0;
					var stringToCopy = action.toLowerCase();
					stringToCopy += "\r\n" + _fileName;
					if (window.listingInfo.selectedEverything) {
						var listItems = window.curTreeItems;
						if (window.listingInfo.filtered) {
							listItems = window.matchedItems;
						}
						for (var i = 0; i < listItems.length; i++) {
							var curItem = listItems[i];
							if (stringToCopy.length > 0) {
								stringToCopy += "\r\n";
							}
							stringToCopy += unescape(curItem.root_dir) + unescape(curItem.name) + "/";
							if (curItem.type.toLowerCase() == "dir") {
								directoriesCopied += 1;
							} else {
								filesCopied += 1;
							}
						}
					} else {
						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);
					$.growlUI(action, msgToShow);
					highlightPasteButton();
					selectDeselectAllItems(false);
				}

				//Paste copied items to target folder
				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)) { //If nothing copied
						$.growlUI(getLocalizationKey("PasteFormPasteButtonText"), getLocalizationKey("PasteFormErrorNothingToPasteText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						return false;
					}

					//Paste items selected, show form if there's form to show on paste
					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) { //Target exists in context
							var copiedItems = $(document).data(o.CookieCopiedFiles); //Items copied
							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]));
								}
								//Build an object to submit to server
								var obj = {
									command: action,
									names: fileNames,
									destPath: destinationPath,
									random: Math.random()
								};

								//If has form attach form info
								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");
								}
								$(".mainProcessIndicator").show();
								$.ajax({
									type: "POST",
									url: o.ajaxCallURL,
									data: obj,
									error: function (XMLHttpRequest, textStatus, errorThrown) {
										errorThrown = errorThrown || action + " failed";
										$.growlUI("Error : " + errorThrown, errorThrown, o.GrowlTimeout, "", o.GrowlWithCloseButton);
									},
									success: function (response) {
										$(".mainProcessIndicator").hide();
										var responseText = getActionResponseText(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 () {
										$(".mainProcessIndicator").hide();
										$.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) {
						//Get paste from from server, build and show in popup if exists
						getCustomForm("pasteForm", function (data, hasForm, formName) {
							if (hasForm) {
								var pasteForm = $("div.pasteForm", "#pasteFormPanel");
								pasteForm.html("<form id='frmPasteForm'>" + data + "</form>").find("table").css("text-align", "left");
								setCustomFormFieldAttributes(pasteForm);
								attachCalendarPopup(pasteForm);
								$("button#resetPasteForm", pasteForm).unbind().click(function (event) {
									pasteForm.clearForm();
									event.stopPropagation();
									event.preventDefault();
								}).val(getLocalizationKey("PasteFormResetButtonText")).text(getLocalizationKey("PasteFormResetButtonText"));
								$("button.submitForm", pasteForm).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"));
					}
					else {
						pasteFiles();
					}
				}

				//Download selected items as a zip
				window.downloadAsZip = function (context, isFolder) {
					var action = "Zip";
					var _fileName = "";
					var elem = {};
					var checkedFiles = {};
					var stringToCopy = "";
					var ItemsToDownload = [];
					if (window.listingInfo.selectedEverything && !window.listingInfo.isSearchResult && !window.listingInfo.filtered) { //If all items in current directory is selected, pass directory name as a parameter, it will download whole directory as zip. No need to pass every item
						stringToCopy = "/";
						if (hashListener.getHash() && hashListener.getHash().toString() != "") {
							stringToCopy = hashListener.getHash().toString().replace("#", "");
						}
					} else if ((window.listingInfo.selectedEverything && window.listingInfo.isSearchResult) || (window.listingInfo.selectedEverything && window.listingInfo.filtered)) {
						//If not all items selected, loop through items selected and make a list
						var listItems = window.curTreeItems;
						if (window.listingInfo.filtered) {
							listItems = window.matchedItems;
						}
						for (var i = 0; i < listItems.length; i++) {
							var curItem = listItems[i];
							if (stringToCopy.length > 0) {
								stringToCopy += "\r\n";
							}
							var filePath = unescape(curItem.root_dir) + unescape(curItem.name);
							filePath = filePath.replace("//", "/");
							if (!ItemsToDownload.has(filePath)) {
								ItemsToDownload.push(filePath);
								stringToCopy += ":" + filePath;
							}
						}
					} else {
						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;
						}
						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) {//If nothing selected
						$.growlUI(action, getLocalizationKey("NothingSelectedGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
					} else {
						//Submit action
						submitAction({
							'#command': "downloadAsZip",
							'#path': encodeURIComponent("/"),
							'#paths': encodeURIComponent(unescape(stringToCopy)),
							'#random': Math.random()
						});
						selectDeselectAllItems(false);
						$.growlUI(getLocalizationKey("DownloadStartedAlertTitleText"), getLocalizationKey("DownloadStartedAlertDescText"), o.GrowlTimeout);
					}
				}

				//Delete selected items
				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(getLocalizationKey("NothingSelectedGrowlText"), getLocalizationKey("DeleteNoFilesSelectedMessage"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						return;
					}
					var filesCopied = 0;
					var directoriesCopied = 0;
					var stringToCopy = _fileName;
					var _strMsg = stringToCopy;
					var msgToShow = getLocalizationKey("DeleteConfirmationMessageText");
					if (window.listingInfo.selectedEverything) {
						var listItems = window.curTreeItems;
						if (window.listingInfo.filtered) {
							listItems = window.matchedItems;
						}
						for (var i = 0; i < listItems.length; i++) {
							var curItem = listItems[i];
							if (stringToCopy.length > 0) {
								stringToCopy += "\r\n";
							}
							stringToCopy += unescape(curItem.root_dir) + unescape(curItem.name) + "/";
						}
						var curDir = "/";
						if (hashListener.getHash() && hashListener.getHash().toString() != "") {
							curDir = unescape(hashListener.getHash().toString().replace("#", ""));
						}
						msgToShow = getLocalizationKey("DeleteConfirmationMessageRemoveAllItemsInDirText");
						msgToShow = msgToShow.replace("{folder_name}", curDir);
						msgToShow = msgToShow.replace("{count}", listItems.length);
					} else {
						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)";
						}
						msgToShow = msgToShow.replace("{0}", directoriesCopied);
						msgToShow = msgToShow.replace("{1}", filesCopied);
						msgToShow = msgToShow.replace("{2}", '\n' + _strMsg + '\n\n');
					}
					if (confirm(msgToShow)) {
						var fileName = stringToCopy;
						var obj = {
							command: "delete",
							names: encodeURIComponent(unescape(fileName)),
							random: Math.random()
						};
						$.ajax({
							type: "POST",
							url: o.ajaxCallURL,
							data: obj,
							success: function (response) {
								var responseText = getActionResponseText(response);
								if (responseText.length > 0) {
									$.growlUI(getLocalizationKey("ProblemWhileDeletingGrowlText"), getLocalizationKey("ProblemWhileDeletingDescGrowlText") + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
									$(".refreshButton").click();
								} else {
									$("#filesContainer").find("input.chkBoxAll").removeAttr("checked");
									$(".refreshButton").click();
								}
							},
							error: function () {
								$.growlUI(getLocalizationKey("ProblemWhileDeletingGrowlText"), getLocalizationKey("ProblemWhileDeletingDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
								$(".refreshButton").click();
							}
						});
					}
					selectDeselectAllItems(false);
				}

				//Create directory
				window.makedir = function (fileName) {
					fileName = fileName || $("#txtNewFolder").val();
					if (fileName.toString().length == 0) {
						return;
					}
					fileName = fileName.replace(/\//g, o.folderNameSpecialCharacterSubstitute).replace(/:/g, o.folderNameSpecialCharacterSubstitute);
					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(response);
							if (responseText.length > 0) {
								if (responseText.toString().toLowerCase() == "ok") {
									$(".refreshButton").click();
								} else {
									$.growlUI(getLocalizationKey("ProblemWhileCreatingFolderGrowlText"), getLocalizationKey("ProblemWhileCreatingFolderDescGrowlText") + responseText, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
								}
							} else {
								$.unblockUI();
								if ($("#chkNavigateAfterMkdir").is(":checked")) {
									newFolderName = escape(decodeURIComponent(newFolderName));
									setHashLocation(newFolderName);
								} else {
									$(".refreshButton").click();
								}
							}
						},
						error: function () {
							$.growlUI(getLocalizationKey("ProblemWhileCreatingFolderGrowlText"), getLocalizationKey("ProblemWhileCreatingFolderDescGrowlText"), o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						}
					});
				}

				//Disable or hide the fields on custom page based on their name
				function setCustomFormFieldAttributes(panel)
				{
					$(panel).find("*[name$='_disabled']").attr("disabled", "disabled");
					$(panel).find("*[name$='_readonly']").attr("readonly", "readonly");
					$(panel).find("*[name$='_hidden']").each(function(){
						$(this).closest("tr").hide();
					});
				}

				//Attach calendar to date fields
				function attachCalendarPopup(panel) {
					var _nowDate = new Date();
					_nowDate.setDate(_nowDate.getDate() + 1);
					var _dateFormat = 'mm/dd/yy';
					if (window.CustomFormyyyymmdd) { //Choose custom date format
						_dateFormat = 'yy/MM/dd';
					}
					panel.find("input.futureDateField").each(function(){
						if($(this).is(":disabled") || $(this).attr("readonly")) return;
						$(this).datepicker({ //For date fields which accepts future dates
							dateFormat: _dateFormat,
							showOn: 'both',
							buttonImage: '/WebInterface/jQuery/images/calendar.png',
							buttonImageOnly: true,
							minDate: _nowDate
						}).attr("readonly", "readonly");
					});

					panel.find("input.dateField").each(function(){
						if($(this).is(":disabled") || $(this).attr("readonly")) return;
						$(this).datepicker({  //Normal date fields
							dateFormat: _dateFormat,
							showOn: 'both',
							buttonImage: '/WebInterface/jQuery/images/calendar.png',
							buttonImageOnly: true
						}).attr("readonly", "readonly");
					});
				}

				//General form field based on data passed
				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)); //Generate random Id for field
					var requiredField = (data.required && XMLValue(data.required[0]) == "true") ? "<span class='requiredField'>*</span>" : "";
					if (!data.type || (data.type[0].text != 'label' && !data.name)) {
						return "";
					}
					var controlName = "";
					if(data.name)
					{
						controlName = XMLValue(data.name[0]);
					}
					switch (data.type[0].text) {
					case "label":
						//Generate label, with value
						html = '<tr>' + '<td>' + XMLValue(data.label[0]) + ' ' + requiredField + '</td>' + '<td><label>' + XMLValue(data.value[0]) + '</label></td>' + '<tr>';
						break;
					case "text":
						//Generate input text box, with value and applied size
						var size = parseInt(XMLValue(data.size[0]));
						var dateFieldClass = "";
						if (controlName.lastIndexOf("_date1") >= 0) {
							dateFieldClass = "futureDateField";
						} else if (controlName.lastIndexOf("_date") >= 0) {
							dateFieldClass = "dateField";
						}
						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_" + controlName + randomId + '" name="' + "meta_" + controlName + '" value="' + XMLValue(data.value[0]) + '" size="' + size + '" class="required_' + XMLValue(data.required[0]) + ' ' + dateFieldClass + '" /></td>' + '<tr>';
						break;
					case "textarea":
						//Generate textarea, with value, cols provided
						var cols = parseInt(XMLValue(data.cols[0]));
						if (cols > 40) cols = 40;
						html = '<tr>' + '<td><label for="' + "meta_" + controlName + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td><textarea id="' + "meta_" + controlName + randomId + '" name="' + "meta_" + controlName + '" cols="' + cols + '" rows="' + XMLValue(data.rows[0]) + '" class="required_' + XMLValue(data.required[0]) + '">' + XMLValue(data.value[0]) + '</textarea></td>' + '<tr>';
						break;
					case "combo":
						//Generate dropdown list, with options provided, selected option
						var options = '';
						var opts = data.options[0].options_subitem;
						var itemCount = 0;
						for (var item in opts) {
							if (typeof opts[item] == "object" || typeof opts[item] == "string") {
								var selected = itemCount == 0 ? "selected" : "";
								var curValue = typeof opts[item] == "string" ? opts[item] : opts[item].text;
								var nameValuePair = [curValue, curValue];
								if (curValue.indexOf(":") >= 0) {
									nameValuePair = curValue.split(":");
								}
								options += '<option ' + selected + ' value="' + extractValString(nameValuePair, 1, extractValString(nameValuePair, 0)) + '">' + nameValuePair[0] + '</option>';
								itemCount++;
							}
						}
						html = '<tr>' + '<td><label for="' + "meta_" + controlName + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td><select id="' + "meta_" + controlName + randomId + '" name="' + "meta_" + controlName + '" class="required_' + XMLValue(data.required[0]) + '">' + options + '</select></td>' + '<tr>';
						break;
					case "checkbox":
						//Generate checkboxes, with value and default selection
						var options = '';
						var opts = data.options[0].options_subitem;
						for (var item in opts) {
							if (typeof (opts[item]) != "function") {
								var selected = ""; //item == 0 ? "checked" : "";
								var nameValuePair = " : ";
								if (opts[item].text) {
									nameValuePair = opts[item].text.split(":");
								}
								options += '<span class="chkBoxPanel"><input class="chkbox required_' + XMLValue(data.required[0]) + '" type="checkbox" id="' + "meta_" + controlName + '"  ' + selected + ' name="' + "meta_" + controlName + '"  value="' + extractValString(nameValuePair, 1, extractValString(nameValuePair, 0)) + '">' + nameValuePair[0] + '</input></span>';
							}
						}
						html = '<tr>' + '<td><label for="' + "meta_" + controlName + randomId + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td>' + options + '</td>' + '<tr>';
						break;
					case "radio":
						//Generate radio buttons, with value and default selection
						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_" + controlName + randomId + '" ' + selected + ' name="' + "meta_" + controlName + '"  value="' + extractValString(nameValuePair, 1, extractValString(nameValuePair, 0)) + '">' + nameValuePair[0] + '</input>';
								item++;
							}
						}
						html = '<tr>' + '<td><label for="' + "meta_" + controlName + '">' + XMLValue(data.label[0]) + ' ' + requiredField + '</label></td>' + '<td>' + options + '</td>' + '<tr>';
						break;
					default:
						break;
					}
					return html; //Return current field
				}

				//Extract value from XML string
				function extractValString(item, index, rep) {
					if (item.length >= index && item[index] && item[index].toString() != "undefined") {
						return item[index];
					} else {
						return rep || "";
					}
				}

				//Get XML text from an element
				function XMLValue(val) {
					if (val && val.text) {
						return val.text;
					} else {
						return "";
					}
				}

				//Show upload button only if form is validated and has files to upload
				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(".upload").show();
						} else {
							$("div#browserFileUpload").find(".upload").hide();
						}
					}
					if ($("#browserFileUpload").find("span.errorOverwrite").length == 0) {
						$("#browserFileUpload").removeClass("attention2");
						$("#browserFileUpload").find("div.attention").hide();
						$(document).data("appletItemRequiresAttention", false);
					}
				}

				//Perfor auto upload if option set to upload items automatically on selection
				function performAutoUpload() {
					if ($.cookie(o.CookieAutoUploadFlag) + "" == "true") {
						startUploading(true);
						$("div#browserFileUpload").find(".upload").fadeOut(1000);
					} else {
						$("div#browserFileUpload").find(".upload").fadeIn(1000);
						return;
					}
				}

				//Method starts uploading selected files
				function startUploading(auto, reUpload, itemsToReUpload, element) {
					//Check for username, if fails reload window. It will navigate to login page if required
					bindUserName(false, function (response, username) {
						if (response == "failure") {
							window.location = window.location;
						} else {
							if (!$(document).data("filesInProgress")) {
								$(document).data("filesInProgress", 0);
							}
							var filesInProgress = $(document).data("filesInProgress");//Total files currently uploading
							if (filesInProgress == 0) {//If nothing being uploaded currently
								var uploadPopup = $("div#browserFileUpload");
								if ($(document).data("appletUploadItems") || reUpload) {
								//If there are items queued to reupload or applet upload items are in queue, it uploads them first
									var items = itemsToReUpload || $(document).data("appletUploadItems");
									//Items to upload
									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", $(document).data("appletUploadItems") - items.length);

										//Generate a list item of file to upload add to upload window file list
										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);
										if (items.length > 1) {
											_strMsg = getLocalizationKey("BrowserUploaderAdvancedUploadingFilesText").replace('{0}', items.length) + '  <br />' + _strMsg;
										}
										var rel= generateRandomPassword(8);
										var filelist = $('<li rel="'+rel+'"><label>' + _strMsg + ' <br /> </label><div class="progressPanel" rel="'+rel+'"><span></span></div></li>');
										filelist.data("filesData", items);
										if (uploadPopup.find("ul").find("li.appletUploadItem").length > 0) {
											uploadPopup.find("ul").find("li.appletUploadItem").replaceWith(filelist);
										} else {
											if (element) {
												element.replaceWith(filelist);
											} else {
												uploadPopup.find("ul:first").prepend(filelist);
											}
										}
										filelist.find("span").replaceWith("<div class='progressBar'></div>");
										//Add progressbar in list for current file to upload
										var progressBar = filelist.find("div.progressBar");
										progressBar.progressbar({
											value: 0
										}).before("<div class='appletActionButtons'><span class='pause pointer'>" + getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText") + "</span> <span class='uploadCancel stop pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") + "</span></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 () {
												startUploading();
											}, true);
										});
										//Update files in progress count
										$(document).data("filesInProgress", $(document).data("filesInProgress") + 1);
										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");
										if ($custForm.parent().attr("id") != "custFormApplet") {
											$custForm.wrap("<form id='custFormApplet'></form>");
										}
										var formItems = serializeForm($custForm.parent()[0]).replace(/&/g, ':::').replace(/&/g, ':::');

										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);
										$("#browserFileUpload").find("h2").addClass("spinner");
										if (!$("#browserFileUpload").is(":visible")) {
											$("ul.topnav").find("a[href='javascript:browserUploader();'], a[href='javascript:performAction(\'upload\');']").addClass("bouncing_loader");
										}
										//Add a padlock icon in forms tab in upload window
										$("div.customtabs").find("a[rel='divUploadPanel']").addClass("disabledClick").addClass("padlock");
										submitApplet(true, "COMMAND=UPLOAD:::URL=" + targetUrl + ":::UPLOADPATH=" + destinationPath + ":::" + uploadItems + ":::" + formItems + resumeUpload + compressionUpload, destinationPath, progressBar, function () {
											$(document).data("appletUploadsInProgress", $(document).data("appletUploadsInProgress") - 1);
											startUploading();
											try {
												uploadsComplete();
											} catch (e) {}
											$(".refreshButton").click();
										});
									} else {
										return false;
									}
								} else {
									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("<span class='uploadCancel pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") + "</span>").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 to start uploading automatically
											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);//Build form and submit to server, it will upload form and with data in upload form
												}
											}
										} else {
											submitForm(uploadPopup, forms, 0);
										}
									}
								}
							}
						}
					});
				}

				//Perform applet command
				function submitApplet(signed, command, destinationPath, progressBar, callback) {
					runAppletCommand(signed, "COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth"));
					runAppletCommand(signed, command);
					if (progressBar) {
						appletProgress(progressBar, "", callback); //Update progressbar by applet progress
					}
				}

				//Listen progress of applet
				function appletProgress(progressBar, fileName, callback) {
					var operationType = "UPLOAD";
					var key = "";
					if (progressBar.attr("rel")) {
						operationType = progressBar.attr("rel");
						if (operationType == "DOWNLOAD") { //If download
							key = ":::UNIQUE_KEY=" + progressBar.parent().attr("uid");
						}
					}
					var result = runAppletCommand(true, "COMMAND=ACTION:::TYPE=" + operationType + ":::ACTION=STATUS" + key);
					var o = parseJavaProps(result);
					if(typeof o.status == "string" && o.status.length == 0)
					{
						o.status = " ";
					}
					if (!o || !o.status || o.status.toUpperCase().indexOf("CANCELLED:") == 0)
					{
						//If file upload/download is cancelled
						return;
					}
					var transferedItems = parseInt(o.transferedItems);
					var curItems = transferedItems + 1;
					var totalItems = parseInt(o.totalItems);
					if (curItems > totalItems) curItems = totalItems;
					updateProgressBar(o.transferedBytes * 1, o.totalBytes * 1, progressBar, fileName, callback, appletProgress, o.status); //Update progressbar
					if ($(progressBar).hasClass("paused") == false) {
						//If its still under progress ie. not cancelled or paused
						var $buttons = $(progressBar).parent().find(".appletActionButtons");
						$buttons.find(".filesProcessed").remove();
						var statusText = progressBar.attr("type") && progressBar.attr("type") == ("download") ? " Downloading" : " Uploading";
						var uploadingFilesStatusText = getLocalizationKey("BrowserUploaderAdvancedUploadingFilesStatusText");
						uploadingFilesStatusText = uploadingFilesStatusText.replace("{0}", curItems);
						uploadingFilesStatusText = uploadingFilesStatusText.replace("{1}", o.totalItems);
						$buttons.prepend("<div class='filesProcessed'>" + statusText + " " + uploadingFilesStatusText + ".</div>");
						$(progressBar).after("<div class='status'>" + o.status + "</div>"); //information from the applet, current status
					}
				}

				//Submit form to the server, This is only for native file uploads
				function submitForm(uploadPopup, forms, i, auto) {
					if (forms.length > i && $(forms[i]) && $(forms[i]).attr("id")) {
						var $form = $(forms[i]);
						var filelist = uploadPopup.find("li[rel='" + $(forms[i]).attr("id") + "']");
						if (filelist.length > 0 && $form.attr("rel") != "processed") {
							//Build a progressbar and update list item
							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("<span class='uploadCancel pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") + "</span>");
							progressBar.after("<div class='uploadPath'>" + getLocalizationKey("BrowserUploaderAdvancedUploadingFilesToText") + 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");
							var disabled = $form.find(":disabled").removeAttr("disabled");
							$form.submit();
							disabled.attr("disabled", "disabled");
							$("#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:browserUploader();'], 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); //Next item to upload
						}
					} else {
						try {
							uploadsComplete();
						} catch (e) {}
						$(".refreshButton").click();
						return false;
					}
				}

				//Update progressbar based on current file upload/download progress
				function updateProgressBar(part1, part2, progressBar, fileName, callback, nextCheckFunction, status) {
					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 history = $(progressBar).data("history");//Progressbar data history
					var currentSpeed = $(progressBar).data("currentSpeed");//Current upload/download speed
					/*if (history.length > 30) {
						while (history.length > 25) history.pop();
					}*/
					history.push({
						now: now,
						bytes: part1
					});
					if (history.length > 1 && $(progressBar).hasClass("paused") == false) {//Calculation and updating progressbar. Calculation of speed, percentages etc.
						var pivot = 0; //If history is for less than 5 seconds, use data of first second
						if (history.length > 5) {
							pivot = history.length - 5; // Set pivot to be of previous five second
						}
						var elapsed = now - history[0].now; // Time elapsed
						var bytes = part1 - history[pivot].bytes; // Bytes transferred in timeframe
						var lastElapsed = now - history[pivot].now;// Elapsed time for last transfer timeframe
						var originalBytes = part1 - history[0].bytes; // total bytes transferred
						var secs = ((((part2 - part1) / (originalBytes / elapsed)) / 1000) + 1) + ""; // total time remaining
						var remaining = formatTime(secs);//formatted time
						var percentDone = (part1 / part2) * 100.0;// percentages completed
						var rElapsed = formatTime((elapsed / 1000) + 1 + "");// elapsed time formatted
						var speed = "";
						var avgSpeed = formatBytes((originalBytes / elapsed) * 1024.0) + "/s";	 //Average speed
						if ((originalBytes / elapsed) == 0) {// Still Calculating
							speed = getLocalizationKey("BrowserUploaderSpeedTimeCalculatingText");
							remaining = getLocalizationKey("BrowserUploaderSpeedTimeCalculatingText");
							$(progressBar).data("currentSpeed", speed);
						} else {
							speed = formatBytes((bytes / lastElapsed) * 1024.0) + "/s";// Based on data transferred in last timeframe (5 secs)
							$(progressBar).data("currentSpeed", speed);
						}
						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);
						if(elapsed/1000 >= 10)
						{
							$(progressBar).after("<div class='speed'>" + getLocalizationKey("BrowserUploaderAdvancedUploadingAverageSpeedText") + avgSpeed + ", "  + getLocalizationKey("BrowserUploaderAdvancedUploadingSpeedText") + speed + "</div>");
						}
						else
						{
							$(progressBar).after("<div class='speed'>" + getLocalizationKey("BrowserUploaderAdvancedUploadingSpeedText") + speed + "</div>");
						}
						$(progressBar).progressbar("option", "value", percentDone);
						var type = progressBar.attr("type") || "";
						if(type != "download")
						{
							if($(progressBar).closest("#progressPanel").length == 0)
							{
								$("#progressPanel").append($(progressBar).parent());
							}
						}
					}
					if (status && status.indexOf("ERROR:") >= 0) { //If error in transmitting file
						reportFileCompleted(progressBar, fileName, callback, false, false, true, getLocalizationKey("BrowserUploaderProblemWhileTransferMsgText") +" : " + status);
						return false;
					}
					if (part1 < part2)
					{
						setTimeout(function () {//Call next function after a second
							nextCheckFunction(progressBar, fileName, callback);
						}, 1000);
					}
					else {
						if (status && status.indexOf("ERROR") >= 0) {
							//If error while upload/download
							reportFileCompleted(progressBar, fileName, callback, false, false, true, getLocalizationKey("BrowserUploaderProblemWhileTransferMsgText") + " : " + status);
						} else {
							//If file upload/download completed
							reportFileCompleted(progressBar, fileName, callback);
						}
					}
				}

				//Check progress of current file
				function checkProgress(progressBar, fileName, callback) {
					if ((progressBar.parent() && progressBar.parent().length == 0) || !progressBar.parent()) {
						return false;
					}
					//Ajax call to get update of current file
					$.ajax({
						type: "POST",
						url: o.ajaxCallURL,
						data: "command=getUploadStatus&itemName=" + encodeURIComponent(fileName),
						success: function (response) {
							var responseData = response;
							if (responseData == null) responseData = "";
							responseData = getActionResponseText(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;
								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'>"+getLocalizationKey("BrowserUploaderProblemWhileTransferMsgText")+"</span>]");
							reportFileCompleted(progressBar, fileName, callback, false, true, true);
						}
					});
				}

				//Report file completed, update all events and details of current file
				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:browserUploader();'], a[href='javascript:performAction(\'upload\');']").removeClass("bouncing_loader");
						$("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) { //If upload cancelled
							$(this).text($(this).text().replace(/Uploading/g, getLocalizationKey("BrowserUploaderCancelledUploadMsgText")));
							progressBar.parent().find(".time,.speed,.status").remove();
						} else if (error) { //If an error has occured
							$(this).text(errorMsg);
							$.growlUI("Error", errorMsg, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						} else { //else update details
							$(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")) { //Download
						if (cancelled) { //If download cancelled
							parentElm.prepend("[Download Cancelled] <span class='uploadCancel completed pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") + "</span> ");
							parentElm.find("span.uploadCancel").wrap("<div class='appletActionButtons'></div>");
							parentElm.find("span.uploadCancel").before(" <span class='redownload pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileReDownloadLinkText") + "</span> ");
							parentElm.find(".status").remove();
							$(progressBar).hide();
						} else if (error) { //If error has occured
							parentElm.prepend("Error : " + errorMsg);
							$(progressBar).hide();
							$.growlUI("Error", errorMsg, o.GrowlTimeout, "growlError", o.GrowlWithCloseButton);
						} else { //Else update details
							$(progressBar).replaceWith("[Download Completed] " + originalSize + "Downloaded to: " + $(progressBar).attr("path") + " <span class='uploadCancel completed pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") + "</span>");
							parentElm.find("span.uploadCancel").wrap("<div class='appletActionButtons'></div>").parent();
							parentElm.find("span.uploadCancel").before(" <span class='redownload pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileReDownloadLinkText") + "</span> ");
							if (callback) {
								callback();
							}
						}
						//Upload cancel button event
						parentElm.find("span.uploadCancel").click(function () {
							var currentDownloadList = parentElm.data("currentDownloadList");
							$(this).closest("li").remove();
							showHideUploadBtn();
							var dataInBasket = $(document).data(o.BasketDataKey) || [];
							var diff = dataInBasket.diff(currentDownloadList);
							$(document).data(o.BasketDataKey, diff);
							$("ul.filesSelectedInBasket").empty();
							rebuildBasket();
						});
						//re-upload/download link event
						parentElm.find("span.redownload").click(function () {
							handleFileSelectToDownload(false, false, parentElm);
						});
						parentElm.addClass("uploaded");
						parentElm.find(".speed,.remained").remove();
						showHideUploadBtn();
						performAutoUpload();
					} else { //Upload
						if($(progressBar).closest("#progressPanel").length>0)
						{
							$("ul.filesSelected").find('li[rel="' + $(progressBar).parent().attr("rel") + '"]').append($(progressBar).parent());
						}
						if (cancelled) {//If cancelled
							$(progressBar).parent().find(".time,.speed,.status").remove();
							$(progressBar).replaceWith("[Cancelled] <span class='uploadCancel completed pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") + "</span>");
						} else if (error) {//If an error occured
							$(progressBar).replaceWith("[ERROR] <span class='uploadCancel completed pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") + "</span>");
						} else {//Else update status
							$(progressBar).parent().find(".status").html("");
							$(progressBar).replaceWith("[" + getLocalizationKey("BrowserUploaderSelectedFileDoneText") + "] <span class='uploadCancel completed pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileDismissLinkText") + "</span>");
						}
						parentElm.find("span.uploadCancel").wrap("<div class='appletActionButtons'></div>").parent().prepend("<span class='reupload pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileReUploadLinkText") + "</span>");
						//Re-upload link event
						parentElm.find("span.reupload").click(function () {
							var listItem = $(this).closest("li");
							var itemsToReUpload = listItem.data("filesData");
							if (itemsToReUpload) {
								startUploading(true, true, itemsToReUpload, listItem); //Start upload again with items to reupload
							} 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> <div class="progressPanel" rel="' + listItem.attr("rel") + '"> | ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + dataOfFile.path + '" <span>[<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>').find("span.error").unbind().click(function () {
									$(this).closest("li").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("span.uploadCancel").click(function () {
							$(this).closest("li").remove();
							showHideUploadBtn();
						});
						parentElm.addClass("uploaded");
						parentElm.find(".speed,.remained").remove();
						if (!cancelled && !error) {
							if (callback) {
								callback();
							}
						}
						showHideUploadBtn();
						performAutoUpload();
					}
				}

				//Format bytes to make it more readable
				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";
				}

				//Format time to show in upload/download progress
				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 = getLocalizationKey("BrowserUploaderSpeedTimeCalculatingText");
						} else {
							remaining = secs + " secs";
						}
					}
					return remaining;
				}

				//Parse java properties
				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;
				}

				//Event to finre on before unload, that will alert user if any process is running and user tries to navigate away
				window.onbeforeunload = confirmExit;

				function confirmExit() {
					//That will alert user if any process is running and user tries to navigate away
					if (!$(document).data("filesInProgress")) {
						$(document).data("filesInProgress", 0);
					}
					var filesInProgress = $(document).data("filesInProgress");
					if (filesInProgress > 0) {
						if (filesInProgress > 1) return getLocalizationKey("BrowserUploaderAlertWhileNavigatingAwayMultipleFilesMsgText").replace("{count}", filesInProgress);
						else return getLocalizationKey("BrowserUploaderAlertWhileNavigatingAwaySingleFileMsgText").replace("{count}", filesInProgress);
					}
					var downloadFilesInProgress = $("ul.filesSelectedInBasket").find("div.progressBar:visible").length;
					if (downloadFilesInProgress > 0) {
						return getLocalizationKey("BrowserDownloadAlertWhileNavigatingAwayMsgText");
					}
				}

				//Perform file selection, for native and advanced browse both
				function performFileSelect(obj, 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 = o.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));
					});
					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, unescape(destinationPath))) {
									filesAvailableOnDir.push(fileName)
								}
								if (checkFileAvailalbleInSelectedList(fileName, unescape(destinationPath))) {
									filesAvailableOnList.push(fileName)
								}
							}
							var curItem = $('<li rel="' + parentElem.find("form").attr("id") + '"><label>' + filesSelected + '</label> <div class="progressPanel" rel="' + parentElem.find("form").attr("id") + '">| ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span>[<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>');
							$("ul.filesSelected").prepend(curItem).find("span.error").unbind().click(function () {
								$(this).closest("li").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>&nbsp;|&nbsp;" + getLocalizationKey("BrowserUploaderSelectedFileExistsText") + " : <span class=\"errorOverwrite pointer\">" + getLocalizationKey("BrowserUploaderSelectedFileIgnoreLinkText") + "</span></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("span.errorOverwrite").length == 0) {
												$("#" + parentElem.find("form").attr("id")).removeAttr("rel");
											}
											if ($("#browserFileUpload").find("span.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, unescape(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, unescape(destinationPath))) {
								$("#browserFileUpload").addClass("attention2");
								$("#browserFileUpload").find("div.attention").show();
								$("ul.filesSelected").prepend('<li  rel="' + parentElem.find("form").attr("id") + '"><label>' + filesSelected + '</label> <div class="progressPanel" rel="' + parentElem.find("form").attr("id") + '"> | ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span><span>&nbsp;|&nbsp;' + getLocalizationKey("BrowserUploaderSelectedFileExistsText") + ' : <span class="errorOverwrite pointer">' + getLocalizationKey("BrowserUploaderSelectedFileOverwriteText") + '</span></span> [<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>').find("span.error").unbind().click(function () {
									$(this).closest("li").remove();
									parentElem.hide();
									showHideUploadBtn();
									if ($("#browserFileUpload").find("span.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"
								}, o.GrowlTimeout);
								$("#" + 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("span.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> <div class="progressPanel" rel="' + parentElem.find("form").attr("id") + '"> | ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span>[<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>').find("span.error").unbind().click(function () {
									$(this).closest("li").remove();
									parentElem.hide();
									showHideUploadBtn();
									return true;
								}).closest("li").data("fileDetails", {
									"filename": v,
									"path": destinationPath
								});
							}
						}
						showHideUploadBtn();
						performAutoUpload();
					}
				};

				//Method to check if file available in current listed files
				function checkFileAvailalble(name, _path) {
					name = name.toLowerCase();
					_path = _path || "/";
					var fileAvl = false;
					if (window.curTreeItems) {
						$.each(window.curTreeItems, function () {
							if ($.trim($(this)[0].name).toLowerCase() === $.trim(name)) {
								fileAvl = true;
							}
						});
					}
					return fileAvl;
				}

				//Method to check if file available in selected files
				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;
				}

				//Get val type
				function getType(val) {
					if (val === null) return "[object Null]";
					return Object.prototype.toString.call(val);
				}

				//Handle browse complete, advanced browse
				function handleBrowseComplete(forDownload, quick) {
					var result = {};
					if ($("#javaApplet").length > 0) result = $("#javaApplet")[0].getASyncResult(window.command_id);
					else {
						alert(getLocalizationKey("AppletLoadingFailedMsgText"));
						return false;
					}
					if (result) {
						if (forDownload) {
							handleFileSelectToDownload(result, quick);
						} else {
							handleFileSelectToUpload(result);
						}
					} else {
						if (getType(result).toLowerCase().indexOf("string") < 0) {
							setTimeout(function () {
								handleBrowseComplete(forDownload, quick);
							}, 200);
						} else {
							if (quick) {
								$(document).data(o.BasketDataKeyQuickDownload, new Array());
							}
						}
					}
				}

				//File selected to download
				function handleFileSelectToDownload(result, quick, progressBar) {
					bindUserName(false, function (response, username) {
						if (response == "failure") {
							window.location = window.location;
						} else {
							var itemList = [];
							var stringToCopy = "";
							var downloadList = [];
							var downloadInfo = {};
							if (!progressBar) {
								result = result + ""; //need to conver this JavaRuntimeObject to a String
								var destinationPath = hashListener.getHash().toString().replace("#", "") || "/";
								itemList = parseJavaProps(result.split(";;;")[0]);
								itemList.destinationPath = destinationPath;
								var targetUrl = window.location.toString().replace(hashListener.getHash().toString(), "");
								if (!$(document).data(o.BasketDataKey)) {
									$(document).data(o.BasketDataKey, new Array());
								}
								var uniqueId = generateRandomPassword(10);
								var ItemsInTheBasket = $(document).data(o.BasketDataKey);
								if (quick) {
									ItemsInTheBasket = $(document).data(o.BasketDataKeyQuickDownload);
								}
								for (var i = 0; i < ItemsInTheBasket.length; i++) {
									var j = i + 1;
									stringToCopy += "P" + j + "=" + escape(ItemsInTheBasket[i]) + ":::";
								};
								if (quick) {
									$(document).data(o.BasketDataKeyQuickDownload, new Array());
								} else {
									$(document).data(o.BasketDataKey, new Array());
								}
								rebuildBasket("");
								if (stringToCopy.length > 0) {
									stringToCopy = stringToCopy.substring(0, stringToCopy.length - 3);
								}
								progressBar = $("<li uid='" + uniqueId + "'><div class='progressBar'></div></li>");
								$("ul.filesSelectedInBasket").prepend(progressBar);
								$("ul.filesSelectedInBasket").find("li:not(li[uid])").remove();
								progressBar = progressBar.find("div");
								progressBar.attr("type", "download");
								progressBar.parent().data("downloadList", stringToCopy);
								progressBar.parent().data("currentDownloadList", ItemsInTheBasket);
								progressBar.parent().data("progressBar", progressBar);
								downloadInfo = {
									targetUrl: targetUrl,
									path: itemList.path,
									downloadFiles: stringToCopy,
									uniqueId: uniqueId,
									destinationPath: itemList.destinationPath
								}
								progressBar.parent().data("downloadInfo", downloadInfo);
							} else {
								downloadList = progressBar.data("downloadList");
								downloadInfo = progressBar.data("downloadInfo");
								var progressBarHTML = progressBar.data("progressBar");
								progressBar.empty().append(progressBarHTML);
								progressBar.removeClass("uploaded");
								progressBar = progressBar.find("div");
							}
							progressBar.before("<div class='appletActionButtons'><span class='pause pointer'>" + getLocalizationKey("BrowserUploaderSelectedFilePauseLinkText") + "</span> <span class='uploadCancel stop pointer'>" + getLocalizationKey("BrowserUploaderSelectedFileCancelLinkText") + "</span></div>");
							progressBar.parent().find(".uploadCancel").unbind().click(function () {
								runAppletCommand(true, "COMMAND=ACTION:::TYPE=DOWNLOAD:::ACTION=CANCEL:::UNIQUE_KEY=" + downloadInfo.uniqueId);
								var curElm = $(this);
								reportFileCompleted(progressBar, downloadInfo.path, false, 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:::UNIQUE_KEY=" + downloadInfo.uniqueId);
									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:::UNIQUE_KEY=" + downloadInfo.uniqueId);
									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", downloadInfo.path);
							$("#submitActionBasket").find(".clearCompleted").hide();
							var resumeUpload = ":::RESUME=" + $("#chkDownloadResume").is(":checked");
							var compressionUpload = ":::NOCOMPRESSION=" + ($.cookie(o.CookieNoCompressionFlag) == "true");
							submitApplet(true, "COMMAND=DOWNLOAD:::URL=" + downloadInfo.targetUrl + ":::PATH=" + downloadInfo.path + ":::" + downloadInfo.downloadFiles + resumeUpload + compressionUpload + ":::UNIQUE_KEY=" + downloadInfo.uniqueId, downloadInfo.destinationPath, progressBar, function () {
								$("#submitActionBasket").find(".clearCompleted").show();
							});
						}
					});
				}

				//Get x position of an element
				function getX(oElement) {
					var iReturnValue = 0;
					while (oElement != null) {
						iReturnValue += oElement.offsetLeft;
						oElement = oElement.offsetParent;
					}
					return iReturnValue;
				}

				//Get y position of an element
				function getY(oElement) {
					var iReturnValue = 0;
					while (oElement != null) {
						iReturnValue += oElement.offsetTop;
						oElement = oElement.offsetParent;
					}
					return iReturnValue;
				}

				//Setup drag and drop of files for advanced upload.
				function setupDND() {
					if (!$(document).data("dndConfigured")) {
						$("#javaAppletDivHolder").css({
							'position': 'absolute',
							'visibility': 'hidden'
						});
						$("ul.filesSelected", "#FileUploadSummary").css("height", "220px");
						$(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(getLocalizationKey("JavaAppletNotLoadedGrowlText"), getLocalizationKey("JavaAppletNotLoadedDescGrowlText"), 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;
						});
					}
					else
					{
						$(document).data("dndActiveAt", new Date() * 1);
					}
				}

				//Show drop area on upload window
				window.showDrop = function () {
					if (!$(document).data("appletLoaded")) return false;
					if ($.browser.msie) { // For MSIE
						$("#javaAppletDivHolder").css({
							'position': 'relative',
							'visibility': 'visible'
						});
						$("ul.filesSelected", "#FileUploadSummary").css("height", "240px");
						$("div.tab_content", "#browserFileUpload").css("max-height", "550px");
						$("#javaAppletDiv").addClass('dragOver');
						$("#javaAppletDiv").css({
							"position": "absolute",
							"margin": "0px",
							"padding": "0px"
						});
						//Reset location of drop applet div on screen
						$("#javaAppletDiv").css("width", $("#javaAppletDivHolder")[0].offsetWidth);
						$("#javaAppletDiv").css("left", getX($("#javaAppletDivHolder")[0]));
						$("#javaAppletDiv").css("top", getY($("#javaAppletDivHolder")[0]) + 10);
					} else { // For normal browsers
						$("#javaAppletDivHolder").css({
							'position': 'relative',
							'visibility': 'visible'
						});
						$("ul.filesSelected", "#FileUploadSummary").css("height", "240px");
						$("#javaAppletDiv").addClass('dragOver');
						$("#javaAppletDiv").css("width", $("#javaAppletDivHolder")[0].offsetWidth);
						$("#javaAppletDiv").css("left", getX($("#javaAppletDivHolder")[0]));
						$("#javaAppletDiv").css("top", getY($("#javaAppletDivHolder")[0]));
					}
				}

				//Cancel drop action
				window.cancelDrop = function (skipIfIE) {
					if (skipIfIE && navigator.appName.indexOf("Explorer") >= 0) return false; //IE issue fix
					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");
					}
				}

				//Handle file selected to upload
				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, unescape(destinationPath)) && !isResume) {
									$("#browserFileUpload").addClass("attention2");
									$("#browserFileUpload").find("div.attention").show();
									var recentlyAdded = $('<li class="appletUploadItem" rel="' + itemId + '"><label>' + v + '</label> <div class="progressPanel"  rel="' + itemId + '"> | ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span><span>&nbsp;|&nbsp;' + getLocalizationKey("BrowserUploaderSelectedFileExistsText") + ' : <span class="errorOverwrite pointer">' + getLocalizationKey("BrowserUploaderSelectedFileOverwriteText") + '</span></span> [<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>');
									$("ul.filesSelected").prepend(recentlyAdded);
									recentlyAdded.data("appletItems", itemList[i]).find("span.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).closest("li").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> <div class="progressPanel"  rel="' + itemId + '">| ' + getLocalizationKey("BrowserUploaderSelectedFileWillBeUploadedText") + ' " ' + unescape(destinationPath) + '" <span>[<span class="error pointer">' + getLocalizationKey("BrowserUploaderSelectedFileRemoveLinkText") + '</span>]</span></div></li>');
									$("ul.filesSelected").prepend(recentlyAdded);
									recentlyAdded.data("appletItems", itemList[i]).find("span.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).closest("li").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();
						}
						return false;
					}
				}

				//Start auto upload after drop
				function startAutoUploadAfterDrop() {
					if (!$("#javaAppletDiv").hasClass("dragOver")) {
						setTimeout(startAutoUploadAfterDrop, 500);
					} else {
						performAutoUpload();
					}
				}

				//Handle applet browse, open browse window
				function handleAppletBrowse(forDownload, quick) {
					if (forDownload) {
						runAppletCommand(true, "COMMAND=AUTH:::CRUSHAUTH=" + $.cookie("CrushAuth"));
						window.command_id = runAppletCommand(true, "COMMAND=BROWSE:::DIRECTORIES_ONLY=true:::TITLE=" + getLocalizationKey("advancedDownloadPathSelectionWindowTitle"), true);
					} else {
						window.command_id = runAppletCommand(true, "COMMAND=BROWSE:::TITLE=" + getLocalizationKey("advancedUploadItemsSelectionWindowTitle"), true);
					}
					handleBrowseComplete(forDownload, quick);
				}

				//Run applet command
				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) {}
				}

				//Load applet on page, allows callback when applet is ready
				function loadApplet(signed, callback) {
					if (!navigator.javaEnabled()) {
						$.growlUI(getLocalizationKey("JavaRequiredGrowlText"), getLocalizationKey("JavaRequiredDescGrowlText"), 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").before("<span class='spinner' style='display:inline-block;padding-left:18px;float:right;margin: 7px 0px 0px 10px;'>Loading...</span>");
						$("div#submitActionBasket").find(".advanced").addClass("spinner").addClass("spinnerAdvanced");
					}
					setTimeout(function () {
						$("#javaAppletDiv" + (signed ? "" : "U")).html(s);
						isAppletReady(signed, callback);
					}, 100);
				}

				//Method to check if applet is ready
				function isAppletReady(signed, callback) {
					try
					{
						var appletItem = document.getElementById("javaApplet" + (signed ? "" : "U"));
						if (appletItem && appletItem.test() == "OK")
						{
							$(document).data("appletLoaded" + (signed ? "" : "U"), true);
							if (signed) {
								$("div#browserFileUpload").find(".advancedBrowse").prev().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);
					}
				}

				//Load popup content, binds various events
				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());
				}

				//Block/unblock file listing UI
				function blockFileListingUI(flag) {
					if (flag) {
						$(".mainProcessIndicator").show();
					} else {
						$(".mainProcessIndicator").fadeOut(500);
					}
				}

				//Toggle checkboxes
				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"));
					}
				}

				//Toggle all checkboxes
				function toggleCheckBoxesAll(elem, status, toggle) {
					var infoBar = $("#selectionOfItemsOptions").hide();
					checkUnCheckDirectory(
					$(elem).find("TR.jqueryFileTree"), status, true, toggle);
					if (status) {
						showSelectionInfoBar();
					} else {
						window.listingInfo.selectedEverything = false;
					}
				}

				//Show selection info bar. It will be shown when all items in listing are selected and there are more hidden in paging
				function showSelectionInfoBar() {
					var totalCheckedItems = $("TR.jqueryFileTree").find(".chkBox:visible:checked").length;
					if (currentView() == "Thumbnail") {
						totalCheckedItems = $("#filesContainerDiv").find("li.fileBoxSelected:visible").length;
					}
					if ((window.listingInfo.filtered && totalCheckedItems < window.matchedItems.length) || (!window.listingInfo.filtered && totalCheckedItems < window.listingInfo.totalItemsInDir)) { //If all items listed are selected and there are more hidden in paging
						var infoBar = $("#selectionOfItemsOptions").show();
						var listType = getLocalizationKey('ItemsSelectionShowingFolderText');
						if (window.listingInfo.filtered) {
							listType = getLocalizationKey('ItemsSelectionShowingFilteredItemsText');
						} else if (window.listingInfo.isSearchResult) {
							listType = getLocalizationKey('ItemsSelectionShowingSearchedItemsText');
						}
						if (window.listingInfo.selectedEverything) {
							infoBar.find(".options").hide();
							infoBar.find(".actions").show();
							var allItemSelectedText = getLocalizationKey('ItemsSelectionSelectedAllItemsInDir');
							if (window.listingInfo.filtered) {
								allItemSelectedText = allItemSelectedText.replace('{total_items}', window.matchedItems.length);
							} else {
								allItemSelectedText = allItemSelectedText.replace('{total_items}', window.listingInfo.totalItemsInDir);
							}
							allItemSelectedText = allItemSelectedText.replace('{list_type}', listType);
							infoBar.find("#ItemsSelectionSelectedAllItemsInDir").html(allItemSelectedText);
						} else {
							infoBar.find(".options").show();
							infoBar.find(".actions").hide();
							infoBar.find("#ItemsSelectionDisplayText").html(getLocalizationKey('ItemsSelectionDisplayText').replace('{count}', totalCheckedItems));
							var allItemSelectText = getLocalizationKey('ItemsSelectionSelectAllItemsInDir');
							if (window.listingInfo.filtered) {
								allItemSelectText = allItemSelectText.replace('{total_items}', window.matchedItems.length);
							} else {
								allItemSelectText = allItemSelectText.replace('{total_items}', window.listingInfo.totalItemsInDir);
							}
							allItemSelectText = allItemSelectText.replace('{list_type}', listType);
							infoBar.find("#ItemsSelectionSelectAllItemsInDir").html(allItemSelectText);
						}
					}
				}

				//Select/Deselect all items
				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");
								showSelectionInfoBar();
							} else {
								$("#filesContainerDiv").find("li.fileBoxSelected:visible").removeClass("fileBoxSelected");
								window.listingInfo.selectedEverything = false;
								$("#selectionOfItemsOptions").hide();
							}
						}
					}
				}

				//Is all checkboxes in element are selected
				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;
				}

				//Toggle main checkbox, check all
				function toggleMainCheckbox(elem, status) {
					status = status || isChecked(elem);
					if (status) {
						$(elem).find("input.chkBoxAll").attr("checked", "checked");
					} else {
						$(elem).find("input.chkBoxAll").removeAttr("checked");
					}
				}

				//Check/uncheck directory based on files beneath directory
				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");
							}
						}
					});
				}

				//Current view
				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");
				}

				//Method to change current view, refresh after changing view
				function changeView(type, refresh) {
					if (!window.listingInfo.selectedEverything) $("#selectionOfItemsOptions").hide();
					$("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);
							}
						}
					}
				}

				//Map XML to tables, converts XML to an array/json
				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);
						if (folderExpand) window.curTreeItems = window.curTreeItems ? window.curTreeItems : {};
						else 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) {
							if (l && l.length > 0) {
								var rel = folderExpand.find("a").attr("rel");
								for (var i = 0; i < curTreeItems.length; i++) {
									var curItem = curTreeItems[i];
									if (curItem.root_dir + unescape(curItem.name) + "/" == unescape(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 {
						$(document).data("folderPrivs", false);
						l = [];
						return "";
					}
				}

				//Filter listed item quickly as user types
				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;
						$("#selectionOfItemsOptions").hide();
					}
					window.matchedItems = matchedItems;
					window.listingInfo.selectedEverything = false;
					reBuildListing(window.matchedItems); //rebuild listing with filtered items
					bindCountOfFiles();
					$.unblockUI();
				}

				//Generate listing based on custom items
				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;
								start += page;
								maxEntries += page;
							} else {
								maxEntries = CookiePageSize;
							}
						}
						//Loop through items and build HTML for thumbs and tree view
						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 + '" sizeInBytes="' + opt.size + '" 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(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 + '" sizeInBytes="' + opt.size + '" 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 + "' sizeInBytes='" + opt.size + "' size='" + opt.sizeFormatted + "' date='" + opt.dateFormatted + "' keywords='" + keywords + "' preview='" + (opt.preview > 0 ? "true" : "false") + "' 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 > 0 ? "true" : "false") + '" ' + 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 > 0 ? "true" : "false") + '" ' + 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 + '" sizeInBytes="' + opt.size + '" size="' + opt.size + '">' + opt.sizeFormatted + '</td><td class="columnModified" modified="' + opt.modified + '">' + opt.dateFormatted + '</td><td class="columnKeywords" title="' + keywords + '">' + keywords + '</td></tr>');
									}
								}
							}
						}
						//Draw links for current directory
						drawPaginationLinks(curDirItems);
						return fileList.join("");//return html
					} else {
						drawPaginationLinks(curDirItems);
						return "";
					}
				}

				//Get file extension from file name
				function getFileExtension(filename) {
					var ext = /^.+\.([^.]+)$/.exec(filename);
					return ext == null ? "" : ext[1].toLowerCase();
				}

				//If it is an MSIE
				window.IE = function (obj) {
					if (window.ActiveXObject) {
						var obj2 = {};
						try {
							obj2.textContent = obj.text;
						} catch (ex) {}
						return obj2;
					} else {
						return obj;
					}
				}

				//Hover effect of listing row
				function howerEffect() {
					$(".jqueryFileTree").unbind();
					$(".jqueryFileTree").hover(function () {
						$(this).addClass("rowHover");
					}, function () {
						$(this).removeClass("rowHover");
					});
				}

				//Set hash location, its used to load directory
				function setHashLocation(s) {
					if (o.setHashLocation) {
						if (s.toString().length > 0) {
							hashListener.setHash(s);
						}
					}
				}

				//Get current hast location
				function getHash() {
					return document.location.hash;
				}

				//Show buttons based on privs
				function showButtonsBasedOnPriviledge() {
					renderButtons();
					if(!$(document).data("folderPrivs"))
						$("div.mainNavigation").find("a[href!='javascript:doLogout();']").parent().remove();
					$("div.mainNavigation").unblock();
				}

				/*Pagination methods*/
				window.current_page = o.pagingCurrentPage;
				var panel = $(".pagination");

				//Number of pages based on page size
				function numPages(customItem) {
					var curDirItems = customItem ? customItem : l;
					var maxentries = curDirItems.length;
					return Math.ceil(maxentries / o.defaultPageSize);
				}

				//Count interval based on page, page count and page size
				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];
				}

				//Select page, update page size and refresh view
				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;
						drawPaginationLinks();
						updatePageSizeOnLayout(true, customItem);
					}, 50);
				}

				//Select page
				function selectPage(page_id) {
					pageSelected(page_id);
				}

				//Go to prev page
				function prevPage() {
					if (current_page > 0) {
						pageSelected(current_page - 1);
						return true;
					} else {
						return false;
					}
				}

				//Draw pagination links
				function drawPaginationLinks(customItem) {
					panel.each(function () {
						var curPanel = $(this);
						var curDirItems = customItem ? customItem : l;
						curPanel.empty();
						var interval = getInterval(customItem);
						var np = numPages(curDirItems);
						if (np > 1 || o.pagingControlsShowAlways) {
							curPanel.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);
									}
									curPanel.append(lnk);
								}
							if (getLocalizationKey("pagingPrevText")) {
								appendItem(current_page - 1, {
									text: getLocalizationKey("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] && getLocalizationKey("pagingEllipseText")) {
									jQuery("<span>" + getLocalizationKey("pagingEllipseText ")+ "</span>").appendTo(curPanel);
								}
							}
							for (var i = interval[0]; i < interval[1]; i++) {
								appendItem(i);
							}
							if (interval[1] < np && o.pagingNumEdgeEntries > 0) {
								if (np - o.pagingNumEdgeEntries > interval[1] && getLocalizationKey("pagingEllipseText")) {
									jQuery("<span>" + getLocalizationKey("pagingEllipseText") + "</span>").appendTo(curPanel);
								}
								var begin = Math.max(np - o.pagingNumEdgeEntries, interval[1]);
								for (var i = begin; i < np; i++) {
									appendItem(i);
								}
							}
							if (getLocalizationKey("pagingNextText")) {
								appendItem(current_page + 1, {
									text: getLocalizationKey("pagingNextText"),
									classes: "next"
								});
							}
						} else {
							curPanel.hide();
						}
					});
				}
				/*End :: Pagination methods*/

				//Build breadcrumbs
				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;
					}
					var userName = $(document).data("username") || "Home";
					crumbs = "<li class='home'><a href='#/'>" + $(document).data("username") + "</a></li>" + crumbs;
					$("#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"
					});
				};

				//Hash listener plugin
				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) {
					},
					syncHash: function () {
						var s = this._hash;
						if (s != document.location.hash) {
							document.location.hash = s;
						}
					},
					onHashChanged: function () {
						var t = escape(unescape(this.getHash().replace("#", "")));
						var loc = unescape(t);
						if(loc.lastIndexOf("/")!=loc.length-1)
						{
							t = loc + "/";
							setHashLocation(escape(unescape(t)));
							return;
						}
						window.current_page = o.pagingCurrentPage = 0;
						if (currentView() == "Thumbnail") {
							showTree($("#filesContainerDiv"), t, true);
						} else {
							showTree($("#filesContainer"), t, true);
						}
					}
				};

				//All events to initiate on page load
				hashListener.init();
				// 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();
				bindPagingSizeMenu();
				bindSelectionMenu();
				$("#searchForm").attr("action", o.ajaxCallURL);
				bindBackToTop();
				$("#searchResultNotification").find("a").click(function () {
					$(document).removeData("searchData");
					$(".refreshButton").click();
				});
				$("#selectionOfItemsOptions").find("a.options").click(function () {
					window.listingInfo.selectedEverything = true;
					showSelectionInfoBar();
				});
				$("#selectionOfItemsOptions").find("a.actions").click(function () {
					window.listingInfo.selectedEverything = false;
					var tbl = $("#filesListing").find("table");
					toggleCheckBoxesAll(tbl, false);
					toggleMainCheckbox(tbl, false);
					selectDeselectAllItems(false);
				});

				//if(1==1) //Todo add a customization
				{
					$(window).scroll(function () {
						stickyRelocate();
					});
					stickyRelocate();
				}
			});
		}
	});
})(jQuery);

function isScrolledIntoView(elem) {
	if(!elem ||  elem.length ==0) return;
	var docViewTop = $(window).scrollTop();
	var docViewBottom = docViewTop + $(window).height();
	var elemTop = $(elem).offset().top;
	var elemBottom = elemTop + $(elem).height();
	return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

function stickyRelocate() {
	var sticky = $('#mainNavigation');
	if (!isScrolledIntoView($('#mainNav-anchor'))) {
		sticky.addClass('stick');
	}
	else {
		sticky.removeClass('stick');
	}
}

/* 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;
};

//Initialize tabs
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;
		});
	});
}

//Set current tab based on element
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;
}

//Set current tab based on elem name
function setTabToElem(elm) {
	setTabByHandler($("a[rel='" + elm + "']:first"));
}

//Method to clear all items in current form
$.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;
	});
};
