/**
 * Open the file browser to select or upload a file
 * 
 * This library depends on the colorbox library which you can find at
 * http://colorpowered.com/colorbox/
 * 
 * @param where obj
 * @return bool
 */
function launchFileBrowser(where) {
	try {
		
		var fieldId = $(where).parent().parent().find('input').attr('id');
		var fieldHref = 'index.php/settings/files/select?rid=' + rid + '&rtype=' + rtype + '&sendTo=' + fieldId + '';
		
		$.fn.colorbox({	width:"605px", 
						height:"475px", 
						iframe:true, 
						transition: 'elastic',
						href:fieldHref,
						scrolling: false,
						// title: 'Filebrowser'
					});

	} catch (e) {
		alert('Something went wrong while loading the filebrowser, please refresh the page and try again.');
	}
	
	return false; // always return false to invalidate links
}

/**
 * Remove a file
 * @param where jquery objet
 * @return bool
 */
function removeFile(where) {
	var fieldId = where.parent().parent().find('input').attr('id');

	$('input#' + fieldId).attr('value',0);
	$('input#' + fieldId).parent().find('div').remove();
	$('input#' + fieldId).parent().append(showNoFileSelected());
	
	return false;
}

/**
 * Show pretty HTML when no file is selected
 * @return string
 */
function showNoFileSelected() {
	var html = '<div class="filebrowser">';
	html 	+= '<a class="upload" href="#" onclick="return launchFileBrowser( $(this) );">Upload or select</a>';
	html 	+= '</div>';
	return html;
}

/**
 * Show pretty loading while fetching file info
 * @return string
 */
function showFileLoading() {
	var html = '<div class="filebrowser">';
	html 	+= '<div class="loading">Loading...</span>';
	html 	+= '</div>';
	return html;
}

/**
 * Show the file information
 * 
 * @param location Path to file
 * @param name File name
 * @param type File type
 * @return html
 */
function showFileSelected(location, name, type) {

	var html = '<div class="filebrowser">';
	html += '<a class="preview ' + type + '" href="' + location + '" target="_blank">' + name + '</a>';
	html += '<a class="upload" href="#" onclick="return launchFileBrowser( $(this) );">edit</a>';
	html += '<a class="remove" href="#" onclick="return removeFile( $(this) );">remove</a>';
	html += '</div>';

	return html;
	
}

/**
 * From our overlay, show the file once selected
 * @param field
 * @param id
 * @param location
 * @param name
 * @param type
 * @return
 */
function showFileSelectedRemote(field, id, location, name, type) {
	
	var where = 'input#' + field;
	 
	// console.log(where);
	$(document).find(where).attr('value',id);
	
	var html = showFileSelected( location, name, type );
	$(document).find(where).parent().find('div').remove(); // remove filebrowser html	
	$(document).find(where).parent().append( html ); 
	
	$.fn.colorbox.close();
	
}

var workingFile = 0;

$(document).ready(function() {
	
	$('input.filefield').each(function() {
			
		$(this).hide(); // toggle visibility

		var fileId = $(this).attr('value');
		var fieldId = $(this).attr('id');
		
		if(fileId < 1 || !fileId) {
			// no file has been selected
			$(this).parent().find('div').remove(); // remove filebrowser html
			$(this).parent().append(showNoFileSelected());
		} else {
			// valid file found, now try to get the information using ajax
			$.ajax({
				   url: "index.php/settings/files/ajax/" + fileId,
				   dataType: "json",
				   success: function(data){
						
						$('input#'+fieldId).parent().find('div').remove();
						if(data.error) { // file probably not found, ignore it in silence
							$('input#'+fieldId).parent().append( showNoFileSelected() ); 
						} else {	
							$('input#'+fieldId).parent().append( showFileSelected(data.location,data.name,data.type) ); 
						}
				   },
				   beforeSend: function() {
					   $('input#'+fieldId).parent().find('div').remove();
					   $('input#'+fieldId).parent().append(showFileLoading());
				   },
				   error: function (XMLHttpRequest, textStatus, errorThrown) {
						$('input#'+fieldId).parent().find('div').remove();
						$('input#'+fieldId).parent().append( showNoFileSelected() ); 
				  }  
			}); 
		}
		
	});
	
	
	$('#upload').hide();
	$('#uploadprogress').hide();
	
	// show filemanager
	$('a.view').click(function() {
		$('#files').show();
		$('#upload').hide();
		return false;
	});

	// show upload form
	$('a.upload').click(function() {
		$('#files').hide();
		$('#upload').show();
		return false;
	});

	// show filemanager
	$('input#usecancel').click(function() {
		$('#files').show();
		$('#upload').hide();
		return false;
	});

	// show upload progress
	$('div#upload form').submit(function() {
		$('#upload').hide();
		$('#uploadprogress').show();
	});
	
	$('div.thumbnail').each(function() {
		
		$(this).find('div.options').hide();
		
		$(this).mouseover(function() {
			$(this).find('div.options').show();
		});
		$(this).mouseout(function() {
			$(this).find('div.options').hide();
		});
		
		$(this).find('a.add').click(function() {
			 if(confirm("Are you sure you want to use this file?")) {
				 window.parent.showFileSelectedRemote(sendTo, $(this).parent().parent().find('span.id').text(), $(this).parent().parent().find('span.location').text(), $(this).parent().parent().find('span.name').text(), $(this).parent().parent().find('span.type').text() );
			 }
			 return false;
		});
		
	});

});