// an _ error ok ?
var cutters_wheel = cutters_wheel ? cutters_wheel : new Object();
cutters_wheel.tools = function() {
    // do NOT access DOM from here; elements don't exist yet
 
    // private variables
    var onReadyMethods = [];

    // public space
    return {
        // public properties, e.g. strings to translate
		
		third_tier_updates: [],

		operator_sets: [],
		
		select_sets: [],

		custom_sets: [],

		thirdTierUpdate: function(which, data) {
			cutters_wheel.tools.third_tier_updates[which](data);
		},

		changeFilter: function(wheel, filter_label ) {

			// $.jGrowl('whl: ' + wheel + ". lbl: " + filter_label);

			var op_set = this.operator_sets[wheel][filter_label];
			var sel_set = this.select_sets[wheel][filter_label];
			var custom_entry = this.custom_sets[wheel][filter_label];
			
			var op_container = '#' + wheel + '_new_filter_operator_container';
			var val_container = '#' + wheel + '_new_filter_value_container';

			var op_select = wheel + '_new_filter_operator';
			var val_select = wheel + '_new_filter_value';

			var select_tag = '';
			var options = [];

			if (op_set != undefined && op_set != null) {
				select_tag = '<select style="display: none;" id="' + op_select + '" name="' + op_select + '">' + "\n";
				options = [];
				for (var i = op_set.length - 1; i >= 0; --i ) {
					options.unshift('<option value="' + op_set[i][0] + '">' + op_set[i][1] + '</option>');
				}
				$(op_container).html(select_tag + options.join("\n") + '</select>');
				// $('#' + op_select).linkselect();
				$('#' + op_select).slideDown('fast');
			}
			
			if (sel_set != undefined && sel_set != null) {
				select_tag = '<select style="display: none;" id="' + val_select +'" name="' + val_select +'">' + "\n"
				options = [];
				for (var i = sel_set.length - 1; i >= 0; --i ) {
					options.unshift('<option value="' + sel_set[i][0] + '">' + sel_set[i][1] + '</option>');
				}
				//$(val_container).removeClass('cw_space_reset');
				$(val_container).html(select_tag + options.join("\n") + '</select>');
				// $('#' + val_select).linkselect();
				$('#' + val_select).slideDown('fast');

			} else {
				if (custom_entry != undefined && custom_entry != null) {
					if (custom_entry == "date_time") {
						$(val_container).addClass('cw_space_reset');
						$(val_container).html('<input style="display: none;" name="' + val_select + '" id="' + val_select + '" type="text" onkeypress="enter_key_pressed(event)" />');
						$('#' + val_select).datepicker({changeMonth: true, changeYear: true, dateFormat:'yy-mm-dd', yearRange: '-20:+1'});
						$('#' + val_select).slideDown('fast');
					}
				} else {
					// check if textbox is showing
					$(val_container).addClass('cw_space_reset');
					$(val_container).html('<input style="display: none;" name="' + val_select_name + '" id="' + val_select + '" type="text" onkeypress="enter_key_pressed(event)" />');
					$('#' + val_select).slideDown('fast');		
				}
			}	
		},
		
		quickAdd: function(model, id) {
			var type_to_add = $('#quick_add_button').val();
			if (type_to_add != "---") {
				window.location.href = "/" + type_to_add + "/new?for=" + model + "_" + id;
			}
		},
		
		addToOnReadyQueue: function(method) {		
			onReadyMethods.push(method);
		},
		
        runQueue: function() {
			for ( i = 0; i < onReadyMethods.length; i++ ) onReadyMethods[i].call();
		},
		
		refreshComponentPanel: function(component_id) {
			if ((component_id == "")) { return false; }
			id = '#' + component_id;
			//TODO: need to dig one level deeper as well and look for ondemand shizzles (to support the panel setting :visually_embed)
			if ($(id).attr("ondemand") != undefined) {
				dest = $(id).attr("ondemand");
				if (dest.length > 0) {
					mdata = null;
					if ($(id).attr("mode") != undefined) {
						mdata = "pmode=" + $(id).attr("mode");
					}
					$.ajax({
						dataType: 'script',
						type: 'post',
						data: mdata,
						url: dest
					});					
				}
			} else {
				
				
			}
		},
		
		exclusiveEdit: function(update_container) {
			
			
		},
		
		reflector: function(action_name, other_info) {
			if (action_name == "toggle") {
				$('#reflector').dialog('open');
 			} else if (action_name == "xxx") {
	
			}
		},
		
		select_all: function(wheel_name, other_info) {
			$('input.' + wheel_name + '_selector').attr('checked', true);
		},
		
		invert_all: function(wheel_name, other_info) {
			$('input.' + wheel_name + '_selector').each(function() {
				if ($(this).is(':checked')) {
					$(this).attr('checked', false);
				} else {
					$(this).attr('checked', true);					
				}
			});
		},
		
		action: function(element, action_name, other_info, embedded) {
			
			if (embedded == undefined) { embedded = false; }
			if (action_name == "jump") {

				return true;
 			} else if (action_name == "confirmed_delete") {
				var path = other_info["path"] + "/" + other_info["id"] + "?emb=" + embedded + '&wheel=' + other_info["wheel"] + '&authenticity_token=' + $('input[name=authenticity_token]').val(); //+ "/delete/" + other_info["id"] + "?emb=" + embedded;
				$.ajax({
					dataType: 'script',
					type: 'DELETE',
					url: path
				});
				// return false;
				
 			} else if (action_name == "delete") {
				var dialog_div = "delete_" + other_info["type"] + "_" + other_info["id"];
           		$("#" + dialog_div).dialog('open');
				
 			} else if (action_name == "new") {
				controller_div = $(element).parents("div:first");
				$(controller_div).siblings(".cw_component_panel").filter(function() {
					return $(this).attr("id").match(/.+_mini_form$/);
				}).each(function() {
					
					var for_model = other_info['for'];
					var destination = $(this).attr("id");
					var params = "for=" + for_model + "&" + "dest=" + destination;
					var url = other_info['url'];
					var method = 'get';

					$.ajax({
						data: params,
						dataType: 'script',
						type: method,
						url: url
					}); 
						
				});
	
 			} else if (action_name == "load") {
				var notifications_sent = 0;
				$(element).parents("div").filter(function (index) {
					return $(this).attr("notifies") != undefined;
	            }).each(function() {
					var parts = $(this).attr("notifies").split(':');
					var ctype = parts[0];
					var other_div = '#' + parts[1];

					if (($(other_div).attr("notifyme") != undefined) && ($(other_div).attr("for-parent") != undefined)) {
						var to_parts = $(other_div).attr("notifyme").split(':');
						var to_action = to_parts[0];
						var to_controller = to_parts[1];
						var params = "for=" + $(other_div).attr("for-parent") + "&" + "dest=" + $(other_div).attr("id");

						var url = "";
						var method = 'get';
						if ((to_action == "edit") || (other_info["for_edit"] == true)) {
							url = to_controller + "/" + other_info["id"] + "/edit";
						} else {
							
							url = to_controller + "/" + other_info["id"];
						}

						$.ajax({
							data: params,
							dataType: 'script',
							type: method,
							url: url
						}); 
						notifications_sent += 1;
					}
				});
				
				if (notifications_sent < 1) {
					return true;
				}

			} else if (action_name == "modal_submit") {
				// NOTE: only support 3rd tier new operations from embedded linky type forms (eg person_relationships)
				var path_parts = other_info["path"].split('/');
				var controller = path_parts[1];
				var id = path_parts[2];
				var form_div_and_field_prefix_name = "edit_" + string_helpers.singularize(controller) + "_" + id;
				tb_remove();
				$(other_info["form_id"]).ajaxSubmit({'dataType' : 'script'});

			} else if (action_name == "submit") {
				if (other_info["for"] != undefined) {
					embedded = true;
				}

				var path_parts = other_info["path"].split('/');
				var controller = path_parts[1];
				var id = path_parts[2];
				var form_div_and_field_prefix_name = "edit_" + string_helpers.singularize(controller) + "_" + id;
				
				if (embedded) {
					$(other_info["form_id"]).ajaxSubmit({'dataType' : 'script'});					
				} else {
					$(other_info["form_id"]).submit();
				}
			} else if (action_name == "wf_update") {
				if ($('#rec_wf_confirm').val().toLowerCase() == "yes") {					
					var options = { dataType: 'script', type: 'post' }
					$("#wf_update_form").ajaxSubmit(options);
				} else {
					$.jGrowl("Must confirm by typing 'yes' in the dialog!");
				}
				
			} else if (action_name == "cancel") {
				$(element).parents("div").filter(function (index) {
					return $(this).attr("notifies") != undefined;
	            }).each(function() {
					$.jGrowl('Edit/new action cancelled');
					$('#' + $(this).attr("id") + "_controller").show('blind');
					$(this).hide();
					
				});				
			}
			return false;
		}
		
    };

}(); // end of app

function noenter() {
  return !(window.event && window.event.keyCode == 13);
}

function cw_repopulate_from_components() {
	$("textarea.codepress").each(function (i) {
		this.updateTextarea();
	});
	// return true;
}

function cw_browse_link(link, session) {
	$.ajax({
		dataType: 'script',
		type: 'get',
		url: link.href
	});
	return false;
}

function cw_browse(form, target) {
	var options = { dataType: 'script', type: 'get' }
    $('#' + form).ajaxSubmit(options);
	return false;
}

function cw_toggle_collapsible_section(section, item_name, item_id) {
  var entity_parts = section.split('_');
  var id = entity_parts[1];
  if ($("#collapsible_section_for_" + section).is(":hidden")) {
    if (cw_collapsible_sections_loaded[section]) {
		$("#collapsible_section_for_" + section).slideDown("fast");
		$("#data_row_" + item_name + "_" + 	item_id).addClass("cw_tabbed_row");
		$("#toggle_image_for_" + item_name + "_" + item_id).attr({src : "/images/cutters_wheel/collapse.png"});
		$.scrollTo("#toggle_image_for_" + item_name + "_" + item_id, { duration: 600 })

    } else {
      var on_demand = $("#" + section).attr("on_demand");
      if (on_demand) {
		$("#toggle_image_for_" + item_name + "_" + item_id).attr({src : "/images/cutters_wheel/spinner_small.gif"});
		var params = "for=" + item_name + "_" + item_id + "&dest=collapsible_section_for_" + section
		$.ajax({
			success: function() { 
				cw_collapsible_sections_loaded[section] = true;
				cw_toggle_collapsible_section(section, item_name, item_id); 
				$("#toggle_image_for_" + item_name + "_" + item_id).attr({src : "/images/cutters_wheel/collapse.png"});
			},
			data: params,
			dataType: 'script',
			type: 'post',
			url: on_demand
		}); 
		
      } else {
        cw_collapsible_sections_loaded[section] = true;
        cw_toggle_collapsible_section(section);
      }
    }
	$("#" + section).addClass("cw_tabbed");

  } else {
    $("#collapsible_section_for_" + section).slideUp("fast");
	$("#" + section).removeClass("cw_tabbed");
	$("#data_row_" + item_name + "_" + 	item_id).removeClass("cw_tabbed_row");
	$("#toggle_image_for_" + item_name + "_" + 	item_id).attr({src : "/images/cutters_wheel/expand.png"});	
  }
}

