
/**
* This is our campaign class.  It is for working with the campaign form.
*/
function PromoCampaign() {
}


/**
* Our main function that is called to intialize the class.
*
* @param string root This is the root directory of the Moviedollars
*	installation.  Used for loading other scripts via AJAX.
*
* @param string action This is set to non-null when a search or
*	some other action is being performed.
*
* @param boolean using_campaign Set to true if a campaign is being used,
*	false otherwise.
*
*/
PromoCampaign.prototype.init = function(root, action, using_campaign) {

	this.debug = {};
	//
	// Debugging custtings for loading custom theaters
	//
	//this.debug["loadCT less"] = 1;
	//this.debug["loadCT show URL"] = 1;
	//this.debug["loadCT explain"] = 1;
	//this.debug["show using_campaign"] = 1;

	//
	// Immediately bring up the editing form.
	//
	//this.debug["click edit"] = 1;

	this.root = root;
	this.action = action;
	this.using_campaign = using_campaign;
	this.category_id = category_id;
	this.category_search_type = category_search_type;
	this.studio_id = studio_id;
	this.theater_id = theater_id;

	//
	// Set this to an empty array by default.  Later it can be filled
	// with campaign data.
	//
	this.campaign_data = {};

	//
	// Store our old program from a past run
	//
	//var old_program = '';

	//
	// Set a static variable that points to our object.  This is so that
	// code exeucted from a jQuery handler can interact with object methods.
	//
	PromoCampaign.prototype.obj = this;

    //
    // If we have a campign form/page, then call the initCampaign() function.
    //
    var callback_function2 = this.initCampaign;
	callback_function2(root);
    //$("#campaign_list_form").each(function() {
	//	callback_function2(root);
	//});

} // End of init()


/**
* This function is caled if we actually have campaign
*/
PromoCampaign.prototype.initCampaign = function(root) {

	/**
	* Check the Campaign Id when switched.
	*/
	$("select[id='campaign[campaign_id]']").change(function() {

		$(this).loadingWidget("Campaign");
		var data = {};
		data["campaign_id"] = $("[id='campaign[campaign_id]']").val();
		data["action"] = "";

		if (data["campaign_id"] == 0) {
			$("#using_campaign").val(false);
		} else {
			$("#using_campaign").val(true);
		}

		//
		// Create a callback to hide the please wait graphic.
		//
		var element = $(this);
		var callback2 = function() {
			element.loadingWidget();
		}

		PromoCampaign.prototype.getObj().loadCampaign(data["campaign_id"], callback2);

		});


	//
	// Handle a click on our "Edit/Add Campaign" button.
	//
	$("[id='campaign[button_campaign_edit]']").click(function() {
		PromoCampaign.prototype.getObj().campaignEdit($(this));
		});

	$("[id='campaign[button_campaign_new]']").click(function() {
		PromoCampaign.prototype.getObj().campaignEdit($(this));
		});

	if (PromoCampaign.prototype.getObj().debug["click edit"]) {
		$("[id='campaign[button_campaign_edit]']").click(); // Debugging
	}

	//
	// Whenever the Program or Genre is changed, search for categories.
	//
	$("[id='search[RefAVCProgramId]']").change(function() {
		PromoCampaign.prototype.getObj().loadCategories("search");
		PromoCampaign.prototype.getObj().loadStudios("search");
		PromoCampaign.prototype.getObj().loadCustomTheaters("search");

		//
		// Cancel any current campaign
		//
		$("[id='campaign[campaign_id]']").val(0);
		$("#using_campaign").val(false);
		});

	$("[id='search[RefVODContentTypeId]']").change(function() {
		PromoCampaign.prototype.getObj().loadCategories("search");
		PromoCampaign.prototype.getObj().loadStudios("search");
		PromoCampaign.prototype.getObj().loadCustomTheaters("search");

		//
		// Cancel any current campaign
		//
		$("[id='campaign[campaign_id]']").val(0);
		$("#using_campaign").val(false);
		});

	//
	// Part of the "drill down", changing a category will cause studios
	// to be searched for.
	//
	$("[id='search[CategoryIds]']").change(function() {
		PromoCampaign.prototype.getObj().loadStudios("search");
		//
		// Cancel any current campaign
		//
		$("[id='campaign[campaign_id]']").val(0);
		$("#using_campaign").val(false);
		});

	$("[id='search[StudioId]']").change(function() {
		//
		// Cancel any current campaign
		//
		$("[id='campaign[campaign_id]']").val(0);
		$("#using_campaign").val(false);
		});

	$("[id='search[RefVODTheaterId]']").change(function() {
		//
		// Cancel any current campaign
		//
		$("[id='campaign[campaign_id]']").val(0);
		$("#using_campaign").val(false);
		});

	//
	//
	// Start of main code, end of handlers.
	//
	//
	PromoCampaign.prototype.getObj().setButtonLabel();
	$("select[id='campaign[campaign_id]']").attr("disabled", false);

	if (PromoCampaign.prototype.getObj().action) {
		//
		// If we are doing a search, check to see if we are using a campign.
		// If not, reset the campaign dropdown.
		//
		//
		// This form was submitted, check our using_campaign value 
		// and reset the campaign dropdown if we're not using a campaign.
		//
		var using_campaign = PromoCampaign.prototype.getObj().using_campaign;
		if (PromoCampaign.prototype.getObj().debug["show using_campaign"]) {
			alert(using_campaign);
		}

		//
		// Set this in the form in case we search again from here.
		//
		$("#using_campaign").val(using_campaign);

		if (!using_campaign || using_campaign == "false") {
			//
			// We're not using a campaign.  Set the current campaign to zero.
			//
			$("select[id='campaign[campaign_id]']").val(0);

		} else {
			//
			// We are using a campaign.  Set the value of the dropdown and 
			// use that campaign.
			//
			var id = $("[id='campaign[campaign_id]']").val();
			PromoCampaign.prototype.getObj().loadCampaign(id);

		}

		//
		// Load our categories based on whatever other criteria were selected.
		//
		PromoCampaign.prototype.getObj().loadCategories("search");

	} else {
		//
		// Initial page load, check our default ID.
		//
		if ($("[id='campaign[campaign_id]']").val() == 0) {
			$("#using_campaign").val(false);
		} else {
			$("#using_campaign").val(true);
		}

		//
		// Load our campaign.  That will set the Program and Genre.
		//
		var id = $("[id='campaign[campaign_id]']").val();
		PromoCampaign.prototype.getObj().loadCampaign(id);
	}

	//
	// Only load custom theaters for the search Prefix if we have the
	// actual search form.
	//
	if ($("[id='search[RefAVCProgramId]']").length) {
		PromoCampaign.prototype.getObj().loadCustomTheaters("search");
	}

} // End of initCampaigns()


/**
* This function is called whenever we click the "new campaign" or 
*	"edit campaign" button.
*
* @param e jQuery object of the button that was clicked.
*/
PromoCampaign.prototype.campaignEdit = function(e) {

	//
	// If we are creating a new campaign, reset our campaign dropdown
	//
	if (e.attr("id") == "campaign[button_campaign_new]") {
		$("[id='campaign[campaign_id]']").val(0);
	}

	$("[id='campaign[campaign_id]']").attr("disabled", true);
	$("[id='campaign[button_campaign_edit]']").attr("disabled", true);

	var data = {};
	data["campaign_id"] = $("[id='campaign[campaign_id]']").val();
	//PromoCampaign.prototype.getObj().loadCampaign(data["campaign_id"]);

	var callback_function = PromoCampaign.prototype.getObj().callbackCampaignEdit;
	var url = root + "promo/campaigns/ajax_edit.php";
	$.get(url, {}, function(data) {
		$("#campaign_form").html(data);
        callback_function(root);
		//$("[id='campaign[button_save]']").click(); // Debugging
		//$(".prompt_ok").click(); //Debugging

		//
		// If we are creating a new campaign, reset the Program and Genre.
		//
		if (e.attr("id") == "campaign[button_campaign_new]") {
			$("[id='campaign[RefAVCProgramId]']").val(0);
			$("[id='campaign[RefVODContentTypeId]']").val(0);
			//
			// TODO: Reset the studio and categories?
			//
		}

		//
		// Hide our other forms that we're not using while we edit the 
		// campaign.
		//
		$("#banner_search_form").hide();
		$("#campaign_list_form").hide();

		}); //End of $.get()

} // End of campaignEdit()


/**
* Set the label on our button accordingly.
*/
PromoCampaign.prototype.setButtonLabel = function() {

	var id = $("[id='campaign[campaign_id]']").val();
	var button = $("[id='campaign[button_campaign_edit]']");

	$("[id='campaign[button_campaign_edit]']").attr("value", "Edit Campaign");
	$("[id='campaign[button_campaign_new]']").attr("value", "Create New");

	//
	// Show/hide our buttons accordingly.
	//
	if (id == 0) {
		$("[id='campaign[button_campaign_edit]']").hide();
		$("[id='campaign[button_campaign_new]']").show();
		
	} else {
		$("[id='campaign[button_campaign_edit]']").show();
		$("[id='campaign[button_campaign_new]']").show();

	}

} // End of setButtonLabel()


/**
* This function loads a specific campaign by ID, and then
* sets the current search form elements to that campaign.
*/
PromoCampaign.prototype.loadCampaign = function(id, callback) {

	//
	// Create our data array here, since we're only retrieving
	// data and not setting anything.
	//
	var data = {};
	data["campaign_id"] = id;

	var url = this.root + 'promo/campaigns/ajax.php';

	$.getJSON(url, data, function(data) {
	//$.getJSONDebug(url, data, function(data) {

		//
		// Update the same attributes in the video search form.
		//
		if (typeof(data["RefAVCProgramId"]) != "undef") {
			$("[id='search[RefAVCProgramId]']").val(
				data["RefAVCProgramId"]);
		}

		if (typeof(data["RefVODContentTypeId"]) != "undef") {
			$("[id='search[RefVODContentTypeId]']").val(
				data["RefVODContentTypeId"]);
		}

		if (typeof(data["RefVODTheaterId"]) != "undef"
			&& data["RefVODTheaterId"] != "") {
			$("[id='search[RefVODTheaterId]']").val(
				data["RefVODTheaterId"]);
		} else {
			$("[id='search[RefVODTheaterId]']").val(0);

		}

		//
		// Split up our category list into an an array, then
		// turn that array into an associative array.
		//
		if (typeof(data["CategoryIds"]) != "undef") {
			tmp = data["CategoryIds"].split(",");
			data["CategoryIds"] = {};
			for (key in tmp) {
				var category_id = tmp[key];
				data["CategoryIds"][category_id] = category_id;
			}
		}

		if (typeof(data["CategorySearchType"]) != "undef") {
			$("[name='search[CategorySearchType]']"
				+ "[value='" + data["CategorySearchType"] + "']").attr(
					"checked", "checked");
		}

		PromoCampaign.prototype.getObj().campaign_data = data;

		//
		// Load our categories and studios, and set them.
		//
		if ($("[id='search[RefAVCProgramId]']").length) {
			PromoCampaign.prototype.getObj().loadCategories("search");

		} else if ($("[id='attrib[RefVODVideoId]']").length) {
			//
			// This is run when we're in the "add new video" screen.
			//
			PromoCampaign.prototype.getObj().loadCategories("attrib");

		}

		//
		// Load custom theaters
		//
		PromoCampaign.prototype.getObj().loadCustomTheaters("search");

		//PromoCampaign.prototype.getObj().campaign_data = data;
		PromoCampaign.prototype.getObj().setButtonLabel();

		if (callback) {
			callback();
		}

		});

} // End of loadCampaign()


/**
* This function is called when a campaign editing form is loaded.
*/
PromoCampaign.prototype.callbackCampaignEdit = function() {

	var campaign_data = PromoCampaign.prototype.getObj().campaign_data;

	//
	// The clickable link in every legend tag should toggle the
	// contents of that fieldset.
	//
	$("fieldset").find("legend").find("a").click(function() {
		var e = $(this).parent().parent().find(".fields");
		e.toggle();
		return(false);
		});

	//
	// Hook the submit() event on this form so that pressing "enter"
	// when saving a campaign doesn't cause any problems.
	//
	$("#campaign_form_filter").submit(function() {
		return(false);
		});

	//
	// Set the search type
	//
	$("[name='campaign[CategorySearchType]']"
		+ "[value='" + campaign_data["CategorySearchType"] + "']").attr(
			"checked", "checked");

	//
	// Load custom theaters and put a hook on the Program dropdown so that 
	// any change causes the function to be called again.
	//
	PromoCampaign.prototype.getObj().loadCustomTheaters("campaign");
	$("[id='campaign[RefAVCProgramId]']").change(function() {
		//
		// Load our custom threaters again, since we may have changed to
		// the clips Program.
		//
		PromoCampaign.prototype.getObj().loadCategories("campaign");
		PromoCampaign.prototype.getObj().loadStudios("campaign");
		PromoCampaign.prototype.getObj().loadCustomTheaters("campaign");

		});

	//
	// Changing genre causes custom theeaters to be reloaded too.
	//
	$("[id='campaign[RefVODContentTypeId]']").change(function() {
		PromoCampaign.prototype.getObj().loadCategories("campaign");
		PromoCampaign.prototype.getObj().loadStudios("campaign");
		PromoCampaign.prototype.getObj().loadCustomTheaters("campaign");
		});

	$("[id='campaign[CategoryIds]']").change(function() {
		PromoCampaign.prototype.getObj().loadStudios("campaign");
		});

	//
	// Cancel editing our campaign.
	//
	$("[id='campaign[button_cancel]']").click(function() {
		$("#campaign_form").empty();
		$("[id='campaign[campaign_id]']").attr("disabled", false);
		$("[id='campaign[button_campaign_edit]']").attr("disabled", false);
		//
		// Show our other forms again.
		//
		$("#banner_search_form").show();
		$("#campaign_list_form").show();

		//
		// Rerun the hook for our fieldsets since hiding the forms which surround the fieldsets seems to break the hooks.
		// See Bug #1525 for more info.
		//
		Promo.prototype.obj.hookFieldsets();

		});

	//
	// Create a default campaign name if we are adding a campaign
	//
	var campaign_id = $("[id='campaign[campaign_id]']").val();
	if (campaign_id == 0) {
		$("[id='campaign[name]']").val("(Untitled Campaign)");
		//
		// Clicking on this new campaign name will cause it to be erased.
		//
		$("[id='campaign[name]']").click(function() {
			$("[id='campaign[name]']").val("");
			});

	}

	//
	// Key handler for the name text box.  Handles enter (submit).
	//
	$("[id='campaign[name]']").keyup(function(e) {

		if (e.keyCode == 13 || e.keyCode == 10) {
			$("[id='campaign[button_save]']").click();
		}

		});

	//
	// Clicking the save button on the campaign editing screen
	//
	$("[id='campaign[button_save]']").click(function() {
		$("[id='campaign[campaign_id]']").attr("disabled", false);
		PromoCampaign.prototype.getObj().saveCampaign(
			PromoCampaign.prototype.getObj().saveCampaignUi);
		//
		// Show our other forms again.
		//
		$("#banner_search_form").show();
		$("#campaign_list_form").show();

		//
		// Rerun the hook for our fieldsets since hiding the forms which surround the fieldsets seems to break the hooks.
		// See Bug #1525 for more info.
		//
		Promo.prototype.obj.hookFieldsets();

		});


	//
	// Initial load of categories.
	//
	PromoCampaign.prototype.getObj().loadCategories("campaign");

} // End of callbackCampaignEdit()


/**
* Save a new/updated campaign.
*/
PromoCampaign.prototype.saveCampaign = function (callback) {

	var url = root + 'promo/campaigns/ajax.php';

	var data = {}
	data["name"] = $("[id='campaign[name]']").val();
	data["campaign_id"] = $("[id='campaign[campaign_id]']").val();
	data["RefAVCProgramId"] = $("[id='campaign[RefAVCProgramId]']").val();
	data["RefVODContentTypeId"] = $("[id='campaign[RefVODContentTypeId]']").val();
	data["CategoryIds"] = "";
	data["CategorySearchType"] = $(
		"input[name='campaign[CategorySearchType]']:checked").val();
	data["StudioId"] = $("[id='campaign[StudioId]']").val();
	data["RefVODTheaterId"] = $("[id='campaign[RefVODTheaterId]']").val();
	data["SubAccount"] = $("[id='campaign[SubAccount]']").val();
	data["action"] = "save";

	//
	// Select all categories for form submission
	//
	$("[id='campaign[CategoryIds][]'] option").attr("selected", "seleted");

	//
	// Turn the array of category IDs into a comma-delimited list.
	//
	$("[id='campaign[CategoryIds][]'] :selected").each(function() {

		var val = $(this).val();

		if (data["CategoryIds"]) {
			data["CategoryIds"] += ",";
		}
		data["CategoryIds"] += val;

		});

	$.getJSON(url, data, function(data) {
	//$.getJSONDebug(url, data, function(data) {

		//
		// Fire the callback if it's present.
		//
		if (callback) {
			callback(data);
		}

		});

} // End of saveCampaign()


/**
* Do UI stuff when a campaign is saved.
*/
PromoCampaign.prototype.saveCampaignUi = function(data) {

	var campaign_id = $("[id='campaign[campaign_id]']").val();
	var campaign_name = $("[id='campaign[name]']").val();

	if (campaign_id == 0) {
		//
		// New campaign. Add it into the campaign dropdown list, too.
		//
		var campaign_id = data["id"];
		var message = "New campaign saved with name '" + campaign_name + "'.";

		$("[id='campaign[campaign_id]']").append(
			"<option value=\"" + campaign_id + "\">" + campaign_name + "</option>");
		$("[id='campaign[campaign_id]']").val(campaign_id);

	} else {
		//
		// Update the campaign name in the dropdown list.
		//
		var message = "Campaign '" + campaign_name + "' updated.";
		var e = $("[id='campaign[campaign_id]']").find("option[value='" 
			+ campaign_id + "']");
		e.text(campaign_name);

	}

	PromoCampaign.prototype.getObj().loadCampaign(campaign_id);

	//$("#filter_message").show();
	$("#filter_message").fadeIn();
	$("#filter_message").text(message);

	//$("[id='campaign[campaign_id]']").attr("disabled", false);

	//
	// Remove the entire campaign form.  We're done here!
	//
	$("#campaign_form").empty();

} // End of saveCampaignUi()


/**
* Fetch our custom theaters via AJAX and load them into our custom 
*	theater dropdown.
*
* @param string prefix The prefix to form element names.  
*	Can be "search" or "campaign".
*/
PromoCampaign.prototype.loadCustomTheaters = function(prefix) {

	//
	// We'll be passing in a reference to our object for now.  
	// Eventually, I hope this will no longer be necessary.
	//
	var obj = this.obj;

	var ctElement = $("[id='" + prefix + "[RefVODTheaterId]']");
	$("#CustomTheaterType").customTheatersWidget(ctElement, obj, prefix);

} // End of loadCustomTheaters()


/**
* This function tells us how many milliseconds have passed since
* the last time it was called.
*
* @param boolean reset If true, the internal counter will be reset.
*
* @return integer The numbre of milliseconds since the last call to 
*	this function.
*/
PromoCampaign.prototype.getTimeOffset = function(reset) {

	var retval = "";
	var obj = PromoCampaign.prototype.getObj();

	//
	// If we have no pre-existing data object or are resetting it, 
	// create a new object-wide date object.
	//
	if (!obj.date_stamp || reset) {
		obj.date_stamp = new Date();
	}

	var date_stamp_new = new Date();
	var time = obj.date_stamp.valueOf();
	var time2 = date_stamp_new.valueOf();
	retval = time2 - time;

	return(retval);

} // End of getTimeOffset()


/**
* Laod categories, based on what the program and genre are.
*
* @param string prefix The prefix to form element names.  
*	Can be "search" or "campaign".
*/
PromoCampaign.prototype.loadCategories = function(prefix) {

	//
	// We'll be passing in a reference to our object for now.  
	// Eventually, I hope this will no longer be necessary.
	//
	var obj = this.obj;
	var categories = $("[id='CategoryName']");
	var selected = $("[id='" + prefix + "[CategoryIds][]']");

	$("#CategoryGroup").categoriesWidget(categories, selected, obj, prefix);

} // End of loadCategories()


/**
* Load studios, based on the program, genre, and category.
*
* @param string prefix The prefix to form element names.  
*	Can be "search" or "campaign".
*/
PromoCampaign.prototype.loadStudios = function(prefix) {

	var obj = PromoCampaign.prototype.getObj();
	var program = $("[id='" + prefix + "[RefAVCProgramId]']").val();
	var genre = $("[id='" + prefix + "[RefVODContentTypeId]']").val();
	var element = $("[id='" + prefix + "[StudioId]']");

	//
	// Grab all category IDs, then turn them into a comma-delimited string
	//
	$("[id='"+ prefix + "[CategoryIds][]'] option").attr("selected", "selected");
	var category_id = $("[id='"+ prefix + "[CategoryIds][]']").val();
	$("[id='"+ prefix + "[CategoryIds][]'] option").attr("selected", "");

	//
	// Turn our list of categoryIDs into a comma-delimieted string.
	//
	if (category_id) {
		category_id = category_id.join(",");
	}

	var url = root + "promo/videos/ajax.php";
	var data = {};
	data["action"] = "getStudios";
	data["program"] = program;
	data["genre"] = genre;
	if (category_id) {
		data["category_id"] = category_id;
	}

	data["CategorySearchType"] = $(
		"input[name='" + prefix + "[CategorySearchType]']:checked").val();

	element.loadingWidget("Studios");
	element.attr("disabled", true);
	var callback = function() {
		element.loadingWidget();
		element.attr("disabled", false);

		//
		// If a studio ID was set, set the currently selected studio to it.
		//
		var campaign_data = PromoCampaign.prototype.getObj().campaign_data;

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

		//
		// If not using a campaign, set the ID to whatever our search criteria was
		//
		if (PromoCampaign.prototype.getObj().using_campaign == "false") {
			element.val(PromoCampaign.prototype.getObj().studio_id);
		}

	}

	//
	// Clear our the select list first.
	//
	element.empty();
	element.append("<option value=\"\">Any</option>");

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

		var count = 0;
		for (k in data) {

			var category_id = k;
			var category = data[k];
			var title = category["title"];
			var num_videos = category["num_videos"];
			var val = title + " (" + num_videos + " video clips)";

			element.append("<option value=\"" + category_id + "\">"
				+ val
				+ "</option>");

			count++;

		}
		//alert("Count: " + count); // Debugging

		//
		// Fire our callback to hide the loading widget
		//
		callback();

	});

} // End of loadStudios()



/**
* Return the current instance of our object.
*/
PromoCampaign.prototype.getObj = function() {
	return(this.obj);
}


