var work_folders = work_folders ? work_folders : new Object();
work_folders.tools = function() {
    // do NOT access DOM from here; elements don't exist yet
    // public space
    return {
		action_stack: {},
		update_running: false,
		
		find_pos: function(obj) {
			var curleft = curtop = 0;
			if (obj.offsetParent) {
				do {
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				} while (obj = obj.offsetParent);
			}
			return [curleft,curtop];
		},
		

		toggle_scroller: function(folder_div) {
			var pos = work_folders.tools.find_pos($('#' + folder_div+ '_box'));
			var lf = pos[0];
			var tp = pos[1];
			$.jGrowl('grr ' + lf + 'x' + tp);

			$('#'+folder_div+'_scroller').css({ left: lf + 'px', top: tp + 'px'});
			$('#'+folder_div+'_scroller').show('blind');
			$('#' + folder_div+ '_box').highlight();
		},
		
		add_action: function(selected) {
			if ($("#folder_active_actions").children().filter('.folder_action_' + selected).length > 0) {
				$.jGrowl('Already have an action by that type');
			} else {
				$('#templates .folder_action_' + selected).clone().appendTo("#folder_active_actions").attr({action:selected});
				$('#folder_active_actions .folder_action_' + selected).show("slow");
				$("#action_invocation").show("slow");
				
				$("#folder_action_help").hide("slow");
				$("#folder_action_help").html("");
				$('#templates .folder_action_' + selected + '_help').clone().appendTo("#folder_action_help");
				$("#folder_action_help").show("slow");
			}
		},
	
		remove_action: function(ele) {
			$(ele).parent().hide("slow", function() {
				$(this).remove();
				if ($("#folder_active_actions").children().length == 0) {
					$("#action_invocation").hide("fast");
				}
			});
		},
			
		run_actions: function(wheel, folder) {
			// if (update_running == true) { 
			// 	alert('fe');
			// 	return false;
			// }
			// update_running = true;
			var apply_to_selected = $('input[name=filter_actions_apply_to]:checked').val();
			var all_actions = {};
			var summary = [];
			var checked_items = [];
			var action_count = 0;
			
			$('#items_items input:checked').each(function(element) {
				checked_items.push($(this).attr('value'))
			});
			switch(apply_to_selected) {
				// case "folder":
				// 	all_actions['apply_to'] = 'folder';
				// 	all_actions['apply_to_data'] = folder;
				// 	$('#folder_apply_summary').html('Actions will be applied to EVERY item in the folder');
				// 	break;
				case "wheel":
					all_actions['apply_to'] = 'wheel';
					all_actions['apply_to_data'] = $('#items_items .this_wheel').html();
					apply_to = { to: 'folder', data: wheel }
					$('#folder_apply_summary').html('Actions will be applied to the items in the RESULT set below');
					break;
				case "selected":
					if (checked_items.length > 0) {
						all_actions['apply_to'] = 'selected';
						all_actions['apply_to_data'] = checked_items.join(':');
						$('#folder_apply_summary').html('Actions will be applied to ' + checked_items.length + ' SELECTED items')
					} else {
						$.jGrowl('You need to select some items in the list in order to "Apply to SELECTED..."');
						return false;
					}
					break;
				default:
					$.jGrowl('Unknown apply rule!');
					return false
			}
						
			$("#folder_active_actions .folder_action_container").each(function(){
				// var action = this.id.split('_')[2];
				var action = $(this).attr('action');
				action_count++;
				switch(action) {
					case "stage":
						all_actions['stage'] = $('#folder_change_stage').val();
						summary.push("Change workflow Stage to <em>" + all_actions['stage'] + "</em>");
						break;
					case "audit":
						all_actions['audit'] = $('#folder_change_audit').val();
						summary.push("Change workflow Audit to <em>" + all_actions['audit'] + "</em>");
						break;
					case "notes":
						var todo = $('#folder_change_notes').val();
						var notes = $('#folder_notes_content').attr('value').replace(/\n111\n111/, '');
						if (todo == "clear") {
							all_actions['notes_action'] = 'clear';
							all_actions['notes'] = '';
							summary.push("CLEAR workflow Notes");
						} else if (todo == "replace") {
							all_actions['notes_action'] = 'replace';
							all_actions['notes'] = notes;
							summary.push("REPLACE workflow Notes with: " + notes);
						} else {
							all_actions['notes_action'] = 'append';							
							all_actions['notes'] = notes;
							summary.push("APPEND to workflow Notes: " + notes);
						}
						break;
					case "assets":
						all_actions['assets'] = true;
						summary.push("(re)Generate assets");
						break;
					case "reindex":
						all_actions['reindex'] = true;
						summary.push("Re-Index manuscripts");
						break;
					case "indexassoc":
						all_actions['reindex'] = true;
						summary.push("Re-Index associated manuscripts");
						break;
					case "assign":
						all_actions['assign'] = $('#folder_assign').val();
						summary.push("Assign folder to user " + $("#folder_assign option:selected:first").html());
						break;
					case "changeowner":
						all_actions['changeowner'] = $('#folder_items_change_owner').val();
						if (all_actions['assign'] != undefined) {
							summary.push("<strike>Change ownership of items to user " + all_actions['changeowner'] + "</strike> (Assign action above overrides change of ownership)" );
						} else {
							summary.push("Change ownership of items to user " + all_actions['changeowner']);
						}
						break;
					case "copy":
						all_actions['copy'] = $('#folder_copy').val();
						summary.push("Copy items to folder " + $("#folder_copy option:selected:first").html());
						//all_actions['copy'];
						break;
					case "remove":
						all_actions['remove'] = true;
						if ((all_actions['reindex'] != undefined) || (all_actions['assets'] != undefined) || (all_actions['assign'] != undefined) || (all_actions['changeowner'] != undefined)) {
							summary.push("<strike>Remove items from folder</strike> (Cant remove items that are involved in reindexing, asset generation or change of ownership)");
						} else {
							summary.push("Remove items from folder");
						}
						break;
					case "derive":
						all_actions['derive'] = $('#folder_derive').val();
						summary.push("Derive new folder of " + all_actions['derive'] + ' related to the records in this folder');
						break;
					default:
						action_count--;
				}
			});
			
			if (action_count < 1) {
				$.jGrowl('You need to select at least one action to apply to the folder!');
				return false
			}
			
			var list_eles = "";
			for (var c in summary) {
				list_eles += "<li>" + summary[c] + "</li>\n";
			}
			var form_eles = "";
			for (var n in all_actions) {
				form_eles += "<input type=\"hidden\" name=\"" + n + "\" id=\"" + n + "\" value=\"" + all_actions[n] + "\" />\n";
			}
			$('#folder_action_summary').html(list_eles);
			$('form#folder_action_form').html(form_eles)
			$('#folder_action_summary_dialog').dialog('open');
		},
		drop_add: function(event, ui, folder_div_id) {
			var destination_folder = folder_div_id.split('_')[2];
			var type_bits = ui.draggable.attr("id").split('_');
			var controller = type_bits[1];
			var id = type_bits[2];
			$.ajax({
				dataType: 'script',
				type: 'POST',
				url: "/" + controller + "/" + id + "/add_to_folder/" + destination_folder
			}); 
			
		},
		add: function(controller, wheel) {
			
			$('#folder_selection_for_' + wheel + '_container').block({ message: "Adding..."});
			
			if ($("#folder_selection_for_" + wheel).val() == "new") {
				if ($('#folder_name_for_' + wheel).val().length < 1) {
					$("#folder_name_for_" + wheel + "_container").toggle('blind');
					$("#folder_selection_for_" + wheel + "_container").toggle('blind');
					$("#folder_name_for_" + wheel).focus();
					return false;
				} else {
					$('#add_to_folder_button_for_' + wheel).remove();				
				}
			} else {
				$('#add_to_folder_button_for_' + wheel).remove();
				$('#folder_name_for_' + wheel).val($("#folder_selection_for_" + wheel).val());
			}

			var folder_selected = $('#folder_name_for_' + wheel).val();
			var selected = [];
			$("input[type='checkbox']." + wheel + '_selector').each(function() {
				if (this.checked) {
					selected.push(this.value);
				}
			});
			var data = "";
			var url = "/" + controller + "/add_to_folder/" + folder_selected
	
			if (selected.length > 0) {
				data = "ids=" + selected.join(':') + "&";
			}
			data += "wheel=" + wheel;
	
			$.ajax({
				data: data,
				dataType: 'script',
				type: 'POST',
				url: url
			}); 
			
			return false;
		}
    };

}(); // end of app

