/**
 * Multi Media Manager admin javascript
 *
 * $LastChangedDate:2007-10-29 11:54:19 -0800 (Mon, 29 Oct 2007) $
 * $LastChangedRevision:439 $
 * $LastChangedBy:jjacob $
 *
 * 
 * @author Dallas Vogels
 * @author Jeff Jacob
 * @copyright 2007 Point One Media
 */
 
 
 
 /**
 removed a mult media file with ajax
  */
 function mm_remove(name,filename,mm_id,onDelete,onDeleteParam)
 {
 	var answer = confirm("You are about to remove the file "+filename+".\n\nAre you sure you want to delete this file?");
 	
 	if (answer) // delete file
 	{
 			$.getJSON(SERVER_PATH+"ajax/mm/mm_delete.php", { mm_id: mm_id},
			  function(data){
			    //alert("Data Loaded: " + data);
			    if (data.status == true)
			    {
	     			if (typeof onDelete == "function")
			 		{
			 			onDelete(onDeleteParam);
			 		}
			 		if (typeof name == "string")
			 		{
			 			 	$("#mm_preview_"+name).fadeOut('slow',function() {
					 				$("#mm_form_"+name).fadeIn('slow');
						 		}
						 	);
			 		}

			    } 
			    else
			    {
			    	alert("We where unable to remove that content, the error was:"+data.errors);
			    }
			  });
 	}
 	return false;
 }

function mm_box_remove(filename,mm_id)
{
	mm_remove(String(mm_id),filename,mm_id,remove_media_content,filename);
}

/**
  will scan the current selected tinymce box and remove any tag that references filename
*/
function remove_media_content(filename)
{
	//clean up the editor
	//var contents = tinyMCE.getContent();
	var contents = tinyMCE.activeEditor.getContent();
	$('<div id="remove_med_tmp" style="display:none">'+contents+'</div>').appendTo('body');
	$("div#remove_med_tmp img[src$='"+filename+"']").remove();
	$("div#remove_med_tmp a[href$='"+filename+"']").remove();
	contents = $("div#remove_med_tmp").html();
	//tinyMCE.setContent(contents);
	tinyMCE.execCommand('mceSetContent',false,contents);
}
 
/**
mm_upload_ajax

name: unique identifier for boxes
onUpload: a function that is called after a sucessfull upload
onUploadParam: The option
onDelete , onDeleteparam : after an image is uploaded the default return value is a preview and a delete button that will have this callback action
passdata, if this is true the onUpload will also be called with a second parameter of data returned and the default action will not be taken.
*/
file_upload_in_progress = false;

function mm_AjaxFileUpload(name,onUpload,onUploadParam,onDelete,onDeleteParam,output_option,multiple_upload)
	{
		if (file_upload_in_progress == true)
		{
			return; // stop if a file upload is already in progress and just ignore this action, 
			//this can happen if a person double clicks upload or something.
		}
		
		if (($("input#mm_desc_"+name).val() == "")) // if there is not a description
		{
			$("#mm_desc_"+name).focus(); // move cursor to desc box and end
			return; //escape empty value 
		}
		if (($("input#"+name).val() == "") ) // if there is not a file set
		{
			$("#"+name).focus(); // move to file box 
			return; //escape empty value 
		}
		//$('#mm_uploadbutton_'+name).attr("disabled", "disabled");
		file_upload_in_progress = true;
		$("#mm_form_"+name)
		.ajaxStart(function(){
			$(this).hide();
		})
		.ajaxError(function(){
			$(this).show().unbind('ajaxStart').unbind('ajaxError').unbind('ajaxComplete');
		})
		.ajaxComplete(function(){
			$(this).unbind('ajaxStart').unbind('ajaxError').unbind('ajaxComplete');
		});
		
	if (multiple_upload)
	{
		$("#mm_form_"+name).ajaxComplete(function(){
			$(this).show().unbind('ajaxStart').unbind('ajaxComplete');
		})
	}
	$("#mm_loading_"+name)
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide().unbind('ajaxStart').unbind('ajaxComplete');
		});
		$.ajaxFileUpload
		(
			{
				url:SERVER_PATH+'ajax/mm/mm_upload.php',
				secureuri:false,
				fileElementId:name,
				onDelete:onDelete,
				onDeleteParam:onDeleteParam,
				dataType: 'json',
				success: function (data, status)
				{
					file_upload_in_progress = false;
				  	//$("#mm_loading_"+name).unbind('ajaxStart').unbind('ajaxComplete');
				   // $("#mm_form_"+name).unbind('ajaxStart').unbind('ajaxComplete');
					//handle success
					//success may mean an error this is just ajax success
					if (data.status == true)
					{
						//this measn the file was really uploaded
						//because of IE we can't return HTML from a file upload so we have to do a second request.
						//The reason for this is that IE likes to either ignore HTML or parse it and destroy the JSON data
						//mm_data = mm_get_data_by_id(data.mm_id,'thumb')
						if (multiple_upload)
						{
							var	options = 'thumb';
						}
						else
						{
							var options  = '';
						}
						$.getJSON(SERVER_PATH+"ajax/mm/mm_cache.php", { mm_id: data.mm_id, options: options,action: 'mm_get_data_by_id' },
						  function(data){

						    if (data.status == true)
						    {
								if (typeof onUpload == "function")
								{
									if (output_option == 'return_all')
									{
										onUpload(onUploadParam,data);
									}
									else
									{
										onUpload(onUploadParam);
									}
								}
								if (multiple_upload)
								{
									$("#mm_preview_"+name).html("").hide();
								}
								else
								{
									
									$("#mm_preview_"+name).html(mm_upload_single_html(name,data,onDelete,onDeleteParam)).show();
									
									tb_init("#mm_preview_"+name+" a.thickbox");//re init the thickbox
								}
						    } 
						    else
						    {
						    	alert("Unable to fetch information on media file:"+data.errors);
						    }
						  });
						
					}
					else
					{
						$("#mm_form_"+name).show();	
						$("#mm_preview_"+name).html("<strong class=\"error\">"+data.errors+"</strong>").show();
					}
					
				},
				error: function (data, status, e)
				{
					file_upload_in_progress = false;
					$("#mm_loading_"+name).unbind('ajaxStart').unbind('ajaxComplete');
				    $("#mm_form_"+name).unbind('ajaxStart').unbind('ajaxComplete');
					//
					// error handling
				    alert("File Upload Error: " + e);
				}
			}
		);
		return false;

}

function mm_upload_single_html(name,data,onDelete,onDeleteParam)
{
	var filename = data.filename;
	var imbed = data.imbed; // the imbeddable display
	var mm_id = data.mm_id;
	// if I just uploaded this image then it won't have any unique tags
	var insertable = '';
	if (data.type == 'image')
	{
		insertable = insertable+'<a href="/app/portal/mm/'+filename+'" title="'+data.desc+'" class="thickbox">';
	}
	else
	{
		insertable = insertable+'<a href="/app/portal/mm/'+filename+'" title="'+data.desc+'" target="_blank">';
	}
	insertable = insertable+imbed+'</a></div><a href="javascript:void(0);" onClick="mm_remove(\''+name+'\',\''+filename+'\','+mm_id+'';
	if (onDelete != "void")
	{
		insertable = insertable+','+onDelete+',\''+onDeleteParam+'\'';
	}
	insertable = insertable+');"><img src="'+SERVER_PATH+'resources/images/icons/delete_32.gif" title="Delete" alt="Delete"/></a>'+
	'<a href="'+SERVER_PATH+'ajax/mm/mm_edit.php?height=60&width=500&mm_id='+mm_id+
		'" title="Make changes and click save" class="thickbox">'+
	'<img src="'+SERVER_PATH+'resources/images/icons/edit_32.gif" title="Edit Description" alt="Edit Description"/></a>'+
	'</div>';
	return insertable;
	
}


function mm_get_data_by_id(id,options)
{
		var ret;
		
		return ret;
}

function mm_box_onupload(box_name,data)
{
	$("#mm_desc_"+box_name).val('');	
	$("#"+box_name).val('');	
	$("#mm_form_"+box_name).show();	
	var filename = data.filename;
	var imbed = data.imbed; // the imbeddable display
	//alert(imbed);
	var mm_id = data.mm_id;
	// if I just uploaded this image then it won't have any unique tags
	var insertable = '<div class="mm_spot" id="mm_preview_'+mm_id+'"><div class="mm_image_preview">';
	if (data.type == 'image')
	{
		insertable = insertable+'<a href="/app/portal/mm/'+filename+'" title="'+data.desc+'" class="thickbox">';
	}
	else
	{
		insertable = insertable+'<a href="/app/portal/mm/'+filename+'" title="'+data.desc+'" target="_blank">';
	}
	insertable = insertable+imbed+'</a>'+
	'</div><a href="javascript:void(0);" onClick="mm_box_remove(\''+filename+'\','+mm_id+');return false;">'+
	'<img src="'+SERVER_PATH+'resources/images/icons/no.png" title="Delete" alt="Delete" style="padding: 5px; float: left;"/></a>'+
	'<a href="'+SERVER_PATH+'ajax/mm/mm_edit.php?height=500&width=700&mm_id='+mm_id+
		'" title="Select a size and press insert" class="thickbox">'+
	'<img src="'+SERVER_PATH+'resources/images/icons/edit_32.gif" title="Edit Description" alt="Edit Description" style="padding: 5px; float: left;"/></a>'+
	'<a href="'+SERVER_PATH+'ajax/mm/mm_insert.php?height=460&width=480&mm_id='+mm_id+
		'" title="Select a size and press insert" class="thickbox">'+
	'<img src="'+SERVER_PATH+'resources/images/icons/add.png" alt="Insert" title="Insert" style="padding: 5px; float: right;"/></a>'+ 
	'</div>';
	//alert(insertable);
	$("#box_"+box_name).append(insertable);
	tb_init("#mm_preview_"+mm_id+" a.thickbox");//re init the thickbox
}


function mm_insert_box_insert_image()
{
	var size = $('#mm_insert_select').val();
	var insert_html = $('#mm_insert_image_'+size).html();
	//alert(insert_html);
	//tinyMCE.execCommand('mceInsertContent',false,insert_html);
	//tinyMCE.selectedInstance.execCommand('mceInsertContent',false,insert_html);
	tinyMCE.execCommand('mceInsertContent',false,insert_html);
	tb_remove();
	return false;
}

function mm_insert_box_insert_pdf()
{
	var type = $('#mm_insert_select').val();
	var insert_html = $('#mm_insert_pdf_'+type).html();
	tinyMCE.execCommand('mceInsertContent',false,insert_html);
	tb_remove();
	return false;
}

/**
shows the correct image when an the drop down is changed
**/
function mm_insert_box_show_image()
{
	var size = $('#mm_insert_select').val();
	$('.mm_insert_image').hide();
	$('#mm_insert_image_'+size).show();
}

/**
shows the correct image when an the drop down is changed
**/
function mm_insert_box_show_pdf()
{
	var size = $('#mm_insert_select').val();
	$('.mm_insert_pdf').hide();
	$('#mm_insert_pdf_'+size).show();
}



/**
saves changes to an mm item
*/
function submit_mm_edits(id)
{
	var desc = $('#mm_edit_description').val();
	if (desc.length > 0)
	{
		$.getJSON(SERVER_PATH+"ajax/mm/mm_edit_save.php", { mm_id: id, description: desc },
				  function(data){
				    //alert("Data Loaded: " + data);
				    if (data.status == true)
				    {
	     				tb_remove();
				    } 
				    else
				    {
				    	alert("We where unable to save the changes, the error was:"+data.errors);
				    }
				  });
	}
	else
	{
		alert("Please provide a description");
	}
}



function mm_browse_show(tag_string)
{
	$.getJSON(SERVER_PATH+"ajax/mm/mm_browse.php", { action: 'get_images', tags: tag_string },
	  function(data){
	    //alert("Data Loaded: " + data);
	    if (data.status == true)
	    {
			if (data.html == '')
			{
				$('#mm_browse_right_view').html('<p>This item as no associated media</p>');
			}
			else
			{
				$('#mm_browse_right_view').html(data.html);
			}
			show_only_type($('#mm_browse_right_type').val());	
	    } 
	    else
	    {
	    	alert("An error has ocurred");
	    }
	  });
	  
	  
	
}

function create_insert_data_object(filename,imbed,id)
{
	this.filename = filename;
	this.imbed = imbed;
	this.mm_id = id;
	
}

/** adds this media to the current object and shows insert box */
function mm_browse_insert(filename,id)
{
	var current_tags = $('#current_tags').val();

	$.getJSON(SERVER_PATH+"ajax/mm/mm_browse.php", { action: 'duplicate' ,mm_id: id, tag_string:current_tags },
  function(data){
  	if (!data.already_used)
  	{
	   	var box_name = $('#box_name').val();
		mm_box_onupload(box_name,data);	
	}
		$.get(SERVER_PATH+"ajax/mm/mm_insert.php", { mm_id: data.mm_id },
	  function(datab){
	    $('#mm_browse_right_view').html(datab);	
	  });
  }) ;
//	 var imbed = $('#mm_id_'+id+' .mm_image_preview').html();
//	data = new create_insert_data_object(filename,imbed	,id);


	return false;	
}



function search_trim(box_ident,term,filter)
{
	//	alert(term);
	//set the class of all objects to_hide
	search_trim_rec($(box_ident),term,filter);
	$('.do_not_hide').removeClass('to_hide').removeClass('do_not_hide').show();
	$('.to_hide').removeClass('to_hide').hide();
}

function search_trim_rec(box_ident,term,filter)
{
	box_ident.contents().map(function(index, domElement)
	{		
		$(this).filter("[nodeType=1]").map(function(ii,di)
		{
			$(di).filter(filter).addClass("to_hide");
			search_trim_rec($(di),term,filter);
		}
		);
		$(this).filter("[nodeType=3]").filter('[nodeValue*='+term+']').map( function(fii,dff)
		{
			//show the parrents
			var first_parent_found = false;
			$(this).parents().map(function (ip,dp) 
			{
				$(this).addClass("do_not_hide");
				if ((!first_parent_found) && $(this).is(filter))
				{
					$(this).find(filter).addClass("do_not_hide");
					first_parent_found = true;
				}
			}
			);
		}
		);
	}
	);
}

function show_only_type(type)
{
	if (type == 'all')
	{
		$('.mm_browse_media').show();
	}
	else
	{
		$('.mm_browse_media').not('.mm_browse_type_'+type).fadeOut();
		$('.mm_browse_type_'+type).fadeIn();
	}
}
