if(prepend_path == undefined)
	var prepend_path = '';

$.fn.insertAtCaret = function (myValue) {
	return this.each(function(){
		//IE support
		if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
		}
		//MOZILLA / NETSCAPE support
		else if (this.selectionStart || this.selectionStart == '0') {
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
				this.focus();
				this.selectionStart = startPos + myValue.length;
				this.selectionEnd = startPos + myValue.length;
				this.scrollTop = scrollTop;
		} else {
				this.value += myValue;
				this.focus();
		}
	});
};

function empty (mixed_var) { 
    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }
 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}

function insertItem(textarea, selectbox)
{
	$(textarea).insertAtCaret('['+ $(selectbox).val() +']');
}

function insertFile(textarea, selectbox, path)
{
	var files = $(selectbox).val();
	
	for(i in files)
	{
		var file = files[i];
		var info = file.split('.');
		var s = '<img src="'+ path_prepend + path +'/'+ file +'" alt="" />';
		var text2 = textarea;
		
		switch(info[(info.length - 1)])
		{
			case 'jpg':
			case 'jpeg':
			case 'jpe':
			case 'gif':
			case 'png':
				
				tinyMCE.get(textarea).execCommand('mceInsertContent', false, s);
                tinyMCE.get(textarea).execCommand('mceCleanup');
				//$(textarea).insertAtCaret('<img src="'+ path_prepend + path +'/'+ file +'" alt="" />');
				break;
			
			default:
				$(textarea).insertAtCaret('<a href="'+ path_prepend + path + '/'+ file +'">'+ file +'</a>');
				break;
		}
	}
}

function removeFile(selectbox, path, exclusions)
{
	var e = $(selectbox)[0];
	var files = $(selectbox).attr('disabled', true).val();
	
	if(exclusions != null)
	{
		var forbidden = false;
		
		if(files.length > 1)
		{
			selected_files = [];
			
			for(var i in files)
			{
				var include = true;
				
				for(var x in exclusions)
				{
					if($('#'+ exclusions[x]).val() == files[i])
					{
						e.options[i].selected = false;
						include = false;
						forbidden = true;
					}
				}
				
				if(include)
					selected_files[selected_files.length] = files[i];
			}
			
			if(forbidden)
			{
				if(selected_files.length > 0)
				{
					alert('Some of the files you are trying to remove are currently in use and cannot be removed.');
				}
				else
				{
					alert('The files you are trying to remove are currently in use and cannot be removed.');
					$(selectbox).attr('disabled', false);
					return false;
				}
			}
		}
		else
		{
			for(var i in exclusions)
			{
				if($('#'+ exclusions[i]).val() == files[0])
					forbidden = true;
			}
			
			if(forbidden)
			{
				alert('The file you are trying to remove is currently in use and cannot be removed.');
				$(selectbox).attr('disabled', false);
				return false;
			}
			
			selected_files = files;
		}
	}

	var result = confirm('Are you sure you want to remove the selected file?');

	if(!result)
	{
		$(selectbox).attr('disabled', false);
		return false;
	}

	$.post('uploader-remove.html', {
		controller: 'uploader_remove',
		path: path_prepend + path,
		files: selected_files.toString()
	}, function(data) {
		if(data == 'success')
		{
			for(var i = (e.options.length - 1); i >= 0; i--)
			{
				if(e.options[i].selected)
					e.remove(i);
			}
		}
		
		$(selectbox).attr('disabled', false);
	}, 'text');
}

/* Handy handlers */
$(document).ready(function() {
	//Make inputs with default data clear on focus/refill on unfocus when empty
	$('.nice_default').live('focus', function(e) {
		if(!empty($(this).attr('reset_value'))) {
			if($(this).val() == $(this).attr('reset_value')) $(this).val('');
		} else if($(this).val() == $(this).attr('defaultValue')) {
			$(this).val('');
		}
	}).live('blur', function(e) {
		if($(this).val() == '') $(this).val($(this).attr('defaultValue'));
	});
	$('.fancy_default').live('focus', function(e) {
		if($(this).val() == $(this).attr('defaultValue')) {
			$(this).val(''); $(this).css('color', '#000');
		}
	});/*.live('blur', function(e) {
		if($(this).val() == '') {
			$(this).val($(this).attr('defaultValue')); $(this).css('color', '#777');
		}
	});*/
	
	$('a.view_cur_img').live('mouseenter', function(e) {
		var id = '#'+$(this).attr('id').substr(0, $(this).attr('id').indexOf('-')) + '-img';
		$(id).css({
			'top'	: (e.pageY - $(window).scrollTop() + 4)+'px',
			'left'	: (e.pageX + 4)+'px'
		}).fadeIn(250);
	}).live('mouseleave', function(e) {
		var id = '#'+$(this).attr('id').substr(0, $(this).attr('id').indexOf('-')) + '-img';
		$(id).css({
			'top'	: '-9999px',
			'left'	: '-9999px'
		}).fadeOut(250);
	});
});

/* Multicomplete event handlers */
$(document).ready(function() {
	$(".multicomplete-item").live("mouseenter", function() {
		$(this).css("background-color", "#f4f4f4");
	}).live("mouseleave", function() {
		$(this).css("background-color", "#eee");
	});
	$(".multicomplete-remove").live("click", function() {
		var data = $(this).parent().data();
		if(data.hasOwnProperty("content_id"))
		{
			var id = data.content_id;
			var hide = $(this).parents("ul.multicomplete-list").first().data("cont_id");
		}
		if(data.hasOwnProperty("structure_id"))
		{
			id = data.structure_id;
			hide = $(this).parents("ul.multicomplete-list").first().data("struct_field");
		}
		var ids = $("#"+hide).val().split(",");
		var idx = ids.indexOf(id);
		if(idx != -1) ids.splice(idx,1);
		$("#"+hide).val(ids.join()).change();
		$(this).parent().remove();
	}).live("mouseenter", function() {
		$(this).css("color", "#723");
	}).live("mouseleave", function() {
		$(this).css("color", "#000");
	});
	$(".multicomplete-list li input").live("focus", function() {
		$(this).css("background-color", "#fff");
	}).live("blur", function() {
		$(this).css("background-color", "#f9f9f9");
	});
});

$(document).ready(function() {
	$('table.listing > tbody > tr').hover(
		function() { $(this).addClass('admin-highlight'); },
		function() { $(this).removeClass('admin-highlight'); }
	);
});

function ax_lock(lock_id) {
	var locked = $('input[name="ax_locks['+lock_id+'][locked]"]').val() == 'true';
	var src = $('img[id='+lock_id+']').attr('src');
	
	if(locked) {
		var locked_icon = src;
		var unlocked_icon = locked_icon.replace(/\/[^\/]*\/?$/, '')+'/lock_open.png';
		$('input[name="ax_locks['+lock_id+'][locked]"]').val('false');
		$('img[id='+lock_id+']').attr('src', unlocked_icon);
	} else {
		var unlocked_icon = src;
		var locked_icon = unlocked_icon.replace(/\/[^\/]*\/?$/, '')+'/lock.png';
		$('input[name="ax_locks['+lock_id+'][locked]"]').val('true');
		$('img[id='+lock_id+']').attr('src', locked_icon);
	}
}
