/*
Author: Andrew Masri 
Ajax file management functions
*/







//open the File Manager app in a new window in order allow the user to upload/select an image
var fileBrowserWindow = false;
function launchFileBrowser() {

	jQuery.cookie('fileBrowserEnabled', 'enabled', { path: '/' });
	jQuery.cookie('clipboardReturnUrl', window.location.href, { path: '/' });
	
	if(!fileBrowserWindow || fileBrowserWindow.closed) {
		fileBrowserWindow = window.open(base_url, 'FileBrowser', 'width=1000, height=600, alwaysRaised=1, location=0, status=0, scrollbars=1');
		jQuery(window).unload( function () { quitFileBrowser(); } );	//if the user navigates away from or closes the edited page then also close the file browser 

		//don't let the filemanger get lost behind the parent window
		jQuery(window).bind('focus click', function() { 
			fileBrowserWindow.focus();
		});	

	} else {
		fileBrowserWindow.focus();
	}
}







//if the image clipboard is active then enable image selection on the page 
function initFileBrowser() {

	if (jQuery.cookie('fileBrowserEnabled') != 'enabled' || !window.opener || window.opener.closed) { return; }	//don't activate the file browser/selector unless it's been enabled and there's a parent/opener window
	
	var $hoverBox = jQuery('<div id="hoverBox" style="position:absolute; padding:10px; background-color:#fff; border:1px solid #443; top:30px; left:40%; z-index:1000"><img src="'+base_url+'img/'+site+'/closeButton.png" style="width:20px; margin:-18px; float:right; cursor:pointer" onclick="quitFileBrowser();" title="Close Clipoard"/><span style="color:#554">Select an Image</span></div>').appendTo('body');
	$hoverBox.effect("pulsate", { times:3 }, 2000);
	
	jQuery('img:not(#hoverBox img)').bind('mouseover', function(event) {
		switch (event.type) {
			case 'mouseover':
				var buttonName = (event.target.src.indexOf('_mime.jpg') == -1) ? 'Copy this image' : 'Copy this file';
			 	$hoverBox.html('<img src="'+base_url+'img/closeButton.png" style="width:20px; margin:-18px; float:right; cursor:pointer" onclick="quitFileBrowser();" title="Close Clipoard"/><input type="button" onclick="selectFile(\''+event.target.src+'\');" value="'+buttonName+'" style="position:absolute"/><img style="width:120px; margin-top:23px" src="'+event.target.src+'"/>').stop(true, true).css('opacity', 1);
				
				//position the box so it's entirely visible		 		
		 		if (jQuery(window).width() < (event.pageX + $hoverBox.width() + 20)) {
			 		$hoverBox.css({
						left: (event.pageX - 30 - $hoverBox.width())
					});
		 		} else {
			 		$hoverBox.css({
						left: event.pageX + 5
					});
		 		}

		 		if (jQuery(window).height() < (event.pageY + $hoverBox.height() + 20)) {
			 		$hoverBox.css({
						top: (event.pageY - 20 - $hoverBox.height())
					});
		 		} else {
			 		$hoverBox.css({
						top: event.pageY + 5
					});
		 		}
				break;
		}
	});
}



//disables the clipboard
function quitFileBrowser() {
	jQuery.cookie('fileBrowserEnabled', 'disabled', { path: '/' });
	jQuery('#hoverBox').remove();
	if (window.opener) {
		window.close(); 	//this window is the file browser window (because there's a parent window);
	} else {
		fileBrowserWindow.close(); //close any file browser window
	} 
}


//selects the image or mime image (representing a file)
function selectFile(url) {
	if (window.opener && !window.opener.closed) {
		window.opener.copyFile(url);
		quitFileBrowser();
	} else {
	//this should not actually be possible since closing the parent window should also close the child window	
		alert("Whoops. Did you close the main window? You're going to have to start over.");
		jQuery.cookie('fileBrowserEnabled', 'disabled', { path: '/' });	//stop image browsing
		window.open(jQuery.cookie('clipboardReturnUrl'), '_self');	//use the file browser window to return to the parent page
	}
}




function copyFile(url) {
//	alert('copy '+url+ ' to '+uploadPath);
	Post.Send('sourceUrl='+url+'&uploadPath='+uploadPath, base_url+'filemanager/copy');
}




var fileRef = false;	//this is used to pass data between these 2 functions

//called by File Manager app to save the selected image (or file)
function saveImage(url) {
	//if a ckeditor window isn't open to accept the file then save it directly to server  
	if (typeof ckeditorInsertImage != 'function' || !ckeditorInsertImage(url)) {
		//if fileRef is defined then send the image to the server 
		if ((typeof fileRef != 'undefined' && fileRef) && (typeof pageId != 'undefined' && pageId) && (typeof url != 'undefined' && url)) {
			//standlone filemanager mode - save directly to the server
			if (url.indexOf('&') != -1) {
				alert('web file names may not contain "&". Please rename the file.');
				return;
			}
			url = replaceThumbnail(url)
			Post.Send('pageRef=' + fileRef + '&pageId=' + pageId + '&url=' + encodeURI(url), base_url + 'dataserver/ajaxInsertImage');
		} else {
			//uploaded subconsulting attachments don't need saving in the images table so fileRef and pageId aren't necessary
//			alert('System Error: missing parameter in saveImage(). please notify your web developer.')
//			alert('pageRef=' + fileRef + '&pageId=' + pageId + '&url=' + encodeURI(url))
//			return;
		}
	}
	setTimeout("closePopupDialogs()", 1000);		//close any open dialogs
}







//opens the image finder dialog
function launchFileFinder(title, uploadPath, ref) {
	fileRef = ref;

	busyStart('launchFileFinder('+title+')'); 
	
	if (jQuery('#fileFinderDialog').length == 0) {
		jQuery('body').append('<div id="fileFinderDialog" title="'+title+'"></div>');	
	}

	//load the specified url content via ajax call into the dialog placeholder
	jQuery('#fileFinderDialog').load(site_url('filemanager/fileFinder/'+uploadPath), function() {

		//initialise the fancy file uploader over the upload button
		if (typeof window.initAjaxUpload == 'function') {
			if (typeof uploadPath == 'string') {
				initAjaxUpload(uploadPath);	
			} else {
				alert('Error: no upload path specified');
			}
		} else {
			alert('Error: Missing javascript function initAjaxUpload()');
		}

		//hide the drag 'n' drop icon in the file list if ckeditor not open
		if (typeof editorInstance == 'undefined' || !editorInstance) {
			jQuery('#fileListForSave').css('background-image', 'none'); 
		}

		//if a file list area exists outside the dialog box then hide the dialog box file list 
		if (jQuery('#fileList-'+uploadPath.replace(/\//g, '-')).length) {
			jQuery('#fileList').css('display', 'none'); 
		}

		//hide fileListForSave (used as a launchpad to drag/drop/save file) if there's a download file list on the page
		if (jQuery('#fileListForDownload').length != 0) {
			jQuery('#fileListForSave').css('display', 'none');
		}

		popupDialog('#fileFinderDialog');
		jQuery('#fileFinderDialog').dialog( "option", "title", title );	//change the title - necessary in the case of recycling the dialog container
		
		busyStop();
	});
}




//This function is called to insert the successfully uploaded/copied file into the file list and the ckeditor or bgImage database
function insertFile(url) {
	var src = replaceThumbnail(url);
	var filename = src.split('/');
	filename = filename[filename.length-1];

	if (url.indexOf('_mime.jpg') != -1) {
		var htmlForSave = '<img class="linkThumbnail thumbnail" ondblclick="saveImage(src);" src="'+url+'" title="'+filename+'" onmouseover="hoverThumbnail(this)"/>';	
	} else {
		var htmlForSave = '<img class="replaceThumbnail thumbnail" ondblclick="saveImage(src);" src="'+url+'" title="'+filename+'" onmouseover="hoverThumbnail(this)"/>'; 				
	}
	var htmlForDownload = '<a href="'+src+'" title="'+filename+'"><img class="thumbnail" src="'+url+'" onmouseover="hoverThumbnail(this)"/></a>';	

	jQuery('#removeFileButton').css('display', 'none');			

	var fileListId = '#fileList-'+uploadPathFromUrl(url);	//we can't just use the page uploadPath because there may be multiple filelists and upload paths on the same page eg. contract and invoice files

	//append the thumbnail to the fileFinder
	jQuery('#fileFinder .fileListForSave').prepend(htmlForSave);
	jQuery('#fileFinder .fileListForSave img:not(#removeFileButton)').first().fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(1000);	//perform visual effect on uploaded image 

	//append the thumbnail to the selected file list
	jQuery(fileListId+'.fileListForSave').prepend(htmlForSave);
	jQuery(fileListId+'.fileListForSave img:not(#removeFileButton)').first().fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(1000);	//perform visual effect on uploaded image 

	//append the thumbnail to the selected downloadable file list
	jQuery(fileListId+'.fileListForDownload').prepend(htmlForDownload);
	jQuery(fileListId+'.fileListForDownload img:not(#removeFileButton)').first().fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(1000);	//perform visual effect on uploaded image 

	jQuery('#uploadErrors').html('<span class="small success">File uploaded successfully</span>');	//clear any status messages
	if (editorInstance) {              
		jQuery('#ui-dialog-title-fileFinder').text("Drag n' Drop Images"); //possibility to drag images into editor
	}
	saveImage(url);	//insert the image in the ckeditor if open - otherwise save to images table (bgImage)
}



//parses the file url to get the upload path of the file 
function uploadPathFromUrl(url) {
	url = url.split('/uploads/');
	url = url[1].split('/');
	url.shift();	//remove first segment (site name)
	url.pop();	//remove last segment (filename) to leave the upload path
	return url.join('-');
}


	

//converts the specified thumbnail to it's original image counterpart (the system often creates thumbnails of original images) 
function replaceThumbnail(filename) {
	filename = filename.replace('_thumb', '');
	return filename.replace('_mime.jpg', '');
}
	
	
