
/**
* Our categories widget.  This plugin handles loading of category lists, 
*	as well as setting the current selected category, if there is one.
*
* @param object categories Object of the element that holds the list of 
*	categories.
*
* @param object select Object of the element that holds the selected list 
*	of categories
*
* @param object obj The PromoCampaign object
* 
* @param string prefix Prefix of the form element we are working with
*
* @author Douglas Muth <dmuth@guesswho.com>
*/
jQuery.fn.categoriesWidget = function(categories, selected, obj, prefix) {

	return(this.each(function() {

		jQuery.fn.categoriesWidget.category_id_group = "";

		var category_group = jQuery(this);
    	var program = $("[id='" + prefix + "[RefAVCProgramId]']").val();
	    var genre = $("[id='" + prefix + "[RefVODContentTypeId]']").val();

    	var url = root + "promo/videos/ajax.php";
	    var data = {};
	    data["action"] = "getCategories";
	    data["program"] = program;
	    data["genre"] = genre;

	    categories.loadingWidget("Categories");
	    categories.attr("disabled", true);

		var callback = jQuery.fn.categoriesWidget.callback;

		//
		// Our regexp is set once per invocation to be a little more efficient
		//
		jQuery.fn.categoriesWidget.space_regexp = /[ ]+$/;

	    //
	    // Clear our the select lists first.
	    //
		category_group.empty();
	    categories.empty();
	    categories.append("<option value=\"\">Any</option>");
		selected.empty();


	    //
    	// Loop through our array and populate the select list
	    //
    	$.getJSON(url, data, function(data) {
    	//$.getJSONDebug(url, data, function(data) { // Debugging

			jQuery.fn.categoriesWidget.setHandlers(obj, data, category_group, 
				categories, selected, prefix);

	        //
	        // Fire our callback to hide the loading widget
    	    //
        	callback(categories, obj, prefix);

	    	});

		//
		// If a category search type was specified, set the form element 
		// accordingly.
		//
		if (obj.category_search_type) {
			var element = $("input[name='" + prefix + "[CategorySearchType]']"
				+ "[value='" + obj.category_search_type + "']");
			element.attr("checked", "checked");
		}

		})); //End of this.each()

} // End of categoriesWidget()


/**
* Turn our array of categories into a multi-dimensional array.
*/
jQuery.fn.categoriesWidget.getCategoryData = function(obj, data, selected) {

	var retval = {};

	//
	// Clear out the selected list of categories.
	//
	selected.empty();

	for (k in data) {

		var category_id = k;
		var category = data[k];
		var num_videos = category["num_videos"];

		var tmp = jQuery.fn.categoriesWidget.parseCategory(category["title"]);
		var group = tmp["group"];
		var title = tmp["category"];
		if (title == "") {
			title = group;
		}
		var category_string = title + " (" + num_videos + " video clips)";

		if (!retval[group]) {
			retval[group] = [];
		}

		retval[group][category_id] = category_string;

		//
		// If the current category ID was searched on, add it to the list 
		// of selected categories.
		//
		if (obj.category_id[category_id]
			) {
			selected.append("<option value=\"" + category_id + "\">"
				+ category_string + "</option>");

		} else if (
			obj.campaign_data["CategoryIds"]
			&& obj.campaign_data["CategoryIds"][category_id]
			) {
			selected.append("<option value=\"" + category_id + "\">"
				+ category_string + "</option>");

		}
	}

	return(retval);

} // End of getCategoryData()


/**
* Go through our array of categories, populate select boxes, and set handlers.
*/
jQuery.fn.categoriesWidget.setHandlers = function(obj, data, category_group, 
	categories, selected, prefix) {

	//
	// First, turn our flat data array into a multi-dimensional group/category 
	// array.
	//
	category_data = jQuery.fn.categoriesWidget.getCategoryData(obj, data, selected);

	//
	// Now populate our category group.
	// The reason for the silliness with having an identical value attrib is
	// because some categories end with spaces, and FireFox seems to 
	// automagically chop off trailing spaces.  Putting them in a value attrib
	// causes them to be preserved, however.
	//
	for (k in category_data) {
		category_group.append("<option value=\"" + k + "\">" 
			+ k + "</option>");
	}

	//
	// Clear out current handlers and set up new ones to popular the
	// list of custom theaters when a type is clicked on.
	//
	category_group.unbind();

	category_group.change(function() {

		var val = $(this).val();
		categories.empty();
		var category_list = category_data[val];

		for (key in category_list) {
			var id = key;
			var category = category_list[key];
			categories.append("<option value=\"" + id + "\">"
				+ category + "</option>");

		}

		});

	//
	// Handle adding categories
	//
	$("#button_add_category").unbind();
	$("#button_add_category").click(function() {

		var id = categories.val();
		var name = categories.find(":selected").text();

		if (!id) {
			alert("You must select a category to add!");
			return(false);
		}
		
		selected.append("<option value=\"" + id + "\">"
			+ name + "</option>");

		// 
		// Reset the campaign
		//
		if (prefix == "search") {
			$("[id='campaign[campaign_id]']").val(0);
			$("#using_campaign").val(false);
		}

		//
		// Load our studios based on updated search criteria
		//
		obj.loadStudios(prefix);

		});

	//
	// Handle removing categories
	//
	$("#button_remove_category").unbind();
	$("#button_remove_category").click(function() {

		var beenhere = 0;
		selected.find(":selected").each(function() {
			$(this).remove();
			beenhere = 1;
			});

		if (!beenhere) {
			alert("You must select a category to remove!");
			return(false);
		}

		// 
		// Reset the campaign
		//
		if (prefix == "search") {
			$("[id='campaign[campaign_id]']").val(0);
			$("#using_campaign").val(false);
		}

		//
		// Load our studios based on updated search criteria
		//
		obj.loadStudios(prefix);

		});

	//
	// If the search type is changed, reset the campaign.
	//
	var element = $("input[name='" + prefix + "[CategorySearchType]']");
		element.change(function() {

		obj.loadStudios(prefix);

		if (prefix == "search") {
			$("[id='campaign[campaign_id]']").val(0);
			$("#using_campaign").val(false);
		}
		});


	//
	// If we have a group ID of a selected category, select the group,
	// then select the category.
	//
	if (jQuery.fn.categoriesWidget.category_id_group) {
		category_group.val(jQuery.fn.categoriesWidget.category_id_group);
		category_group.change();
		categories.val(obj.category_id);
	}

	return(category_data);

} // End of setHandlers()


/**
* Parse a category and split it up into the parent category and sub 
*	categories.
*
* @param string title The full name of the category, such as "AGE -> Daddies"
*
* @return array Associative array of the group ("AGE") and category ("Daddies")
*
* In the event that there is a third level category, it is ignored and 
*	grouped in with the second level category, since the UI only supports 
*	2 levels of categories at this time.
*/
jQuery.fn.categoriesWidget.parseCategory = function(title) {

	retval = {};

	var fields = title.split("->");
	retval["group"] = fields[0];
	retval["category"] = "";
	//
	// Remove trailing spaces to prevent duplicates on certain categories 
	// such as "BISEXUAL".
	//
	retval["group"] = retval["group"].replace(
		jQuery.fn.categoriesWidget.space_regexp, "");

	//
	// If we have a category portion, concatente any additional sub 
	// categories onto it.
	//
	if (fields.length > 1) {

		for (var i = 1; i < fields.length; i++) {

			if (retval["category"]) {
				retval["category"] += "->";
			}

			retval["category"] += fields[i];

		}

	}

	return(retval);

} // End of parseCategory()


/**
* Our callback.  This is called after a successful AJAX request.
*/
jQuery.fn.categoriesWidget.callback = function(categories, obj, prefix) {

	categories.attr("disabled", false);

	//
	// If a category ID was set, change the selected category to that ID,
	// then load studios based on that category.
	//
	var campaign_data = obj.campaign_data;

	if (typeof(campaign_data["CategoryIds"]) != "undef") {
		if (campaign_data["CategoryIds"] != 0) {
			categories.val(campaign_data["CategoryIds"]);
		}
	}

	//
	// If not using a campaign, set the ID to whatever our search criteria was
	//
	if (obj.using_campaign == "false") {
		categories.val(obj.category_id);
	}

	obj.loadStudios(prefix);
	categories.loadingWidget();

} // End of callback()


/**
* A join function for debugging.
*/
jQuery.fn.categoriesWidget.join = function (data) {

	retval = "";

	for (key in data) {
		if (retval) {
			retval += ", ";
		}

		retval += key + ": " + data[key];
	}

	return(retval);

} // End of join()


