﻿
DynamicReportView = Class.create(
{

	// options should have:
	//  ReportID
	//  UniqueID
	//  UsesPrompting
	//  Status
	
	// Optional options include:
	//  DomIDs : a sub-object that can specify DOM ids to use that override default behavior
	//		PromptContainer
	//		DisplayContainer
	
	initialize : function(options)
	{
		this.myData = options;
		
		this.myData.DomIDs 												= this.myData.DomIDs || {};
		this.myData.DomIDs.Loading								= this.myData.UniqueID + "_Loading";
		this.myData.DomIDs.RunLink 								= this.myData.UniqueID + "_RunLink";
		this.myData.DomIDs.PromptsContainerDomID	= this.myData.DomIDs.PromptsContainerDomID || this.myData.UniqueID + "_AllPromptsDiv";
		this.myData.DomIDs.PromptForm 						= this.myData.UniqueID + "_AllPromptsForm";
		this.myData.DomIDs.DisplayContainerDomID	= this.myData.DomIDs.DisplayContainerDomID || this.myData.UniqueID + "_ReportDisplay";
		this.myData.DomIDs.MissingRequiredPromptsErrorMessageDomID = this.myData.UniqueID + "_" + DynamicReportView.MissingRequiredPromptsErrorMessageDomID;
		this.myData.Bound 												= {};
		this.myData.Bound.setLoading							= this.setLoading.bind(this);
		this.myData.Bound.RunClicked							= this.RunClicked.bindAsEventListener(this);
		this.myData.Bound.KeyDownOnPromptInput		= this.KeyDownOnPromptInput.bindAsEventListener(this);
		
		if ($(this.myData.DomIDs.RunLink))
		  $(this.myData.DomIDs.RunLink).observe("click", this.myData.Bound.RunClicked);
		  
		// If we are set to load with the page, then set it up for onLoad
		if (this.myData.Status == DynamicReportView.Status.FrameWithOnload)
			document.observe("dom:loaded", this.myData.Bound.RunClicked);
		  
		DynamicReportView.addView(this);
		
		this.debug("DynamicReportView.initialize(): initialized " + this.getUniqueID());
	},

//---------------------------------------------------------------------------------------------------------------------------
// Property Accessor Methods
	
	getUniqueID : function()
	{
		return this.myData.UniqueID;
	},
	
	getReportID : function()
  {
    return this.myData.ReportID;
  },
  
  getRunLinkDomID : function()
  {
    return this.myData.DomIDs.RunLink;
  },
	
//---------------------------------------------------------------------------------------------------------------------------
// Prompt Methods

	promptsAreLoaded : function()
	{
		return ($(this.myData.DomIDs.PromptForm));
	},
	
	loadPrompts : function()
	{
		var url = DynamicReportView.Page;
		url += "?ReportID=" + this.myData.ReportID;
		url += "&OutputType=Prompts";
		url += "&UniqueID=" + this.myData.UniqueID;
		
		this.setLoading(true, this.myData.DomIDs.PromptsContainerDomID);
		new Ajax.Updater(this.myData.DomIDs.PromptsContainerDomID, url, 
		{	
			onComplete: (function(transport) 
			{ 
				// Perform any initialization on the prompts that have been loaded
				this.initializePrompts();
				// Remove the loading indication
				this.setLoading(false);
			}).bind(this)
		});
	},
	
	initializePrompts : function()
	{
		var inputs = $(this.myData.DomIDs.PromptForm).getInputs('text');
		inputs.each( (function(input)
		{
			input.observe("keyup", this.myData.Bound.KeyDownOnPromptInput);
		}).bind(this) );
		
		if (inputs.length > 0)
		  inputs[0].focus();
	},
	
	serializePrompts : function()
	{
		var params = null;
		if (this.myData.UsesPrompting)
		{
			if (this.myData.AppliedPrompts)
			{
				// There are alreay prompts applied
				params = this.myData.AppliedPrompts;
			}
			else
			{
				if (this.promptsAreLoaded())
					params = $(this.myData.DomIDs.PromptForm).serialize();
				else
					throw("Prompts not loaded!");
			}
		}
		return params;
	},
	
//---------------------------------------------------------------------------------------------------------------------------
// Report Methods

	loadReport : function()
	{
		if(this.validate())
		{
			var url = DynamicReportView.Page;
			url += "?ReportID=" + this.myData.ReportID;
			url += "&OutputType=Report";
			url += "&UniqueID=" + this.myData.UniqueID;
			
			var params = this.serializePrompts();
			
			this.setLoading(true, this.myData.DomIDs.DisplayContainerDomID);
			new Ajax.Updater(this.myData.DomIDs.DisplayContainerDomID, url, { parameters: params, onComplete: (function(transport) { this.setLoading(false); }).bind(this) });
		}
	},
	
//---------------------------------------------------------------------------------------------------------------------------
// Event Handlers
	
	RunClicked : function(event)
	{
		if ( (this.myData.UsesPrompting) && (! this.myData.AppliedPrompts) )
		  this.loadPrompts();
		else
			this.loadReport();
	},
	
	KeyDownOnPromptInput : function(event)
	{
		if (ManoUtilities.KeyStroke.getKey(event) == ManoUtilities.KeyStroke.KEY_ENTER)
			this.loadReport();
	},
	
//---------------------------------------------------------------------------------------------------------------------------
// Utility Methods	
	
	setLoading : function(showLoading, promptOrDisplayDomID)
	{
		var loadingCollection = $$("." + this.myData.DomIDs.Loading);
		if (loadingCollection.length > 0) //We are searching based on the class name because we want dynamic reports to have the option of showing multiple loading graphics
		{								  //ie,FullDisplay_HTML could have multiple <img id="#{UniqueID}_Loading" class="#{UniqueID}_Loading"		
			for (var i = 0; i < loadingCollection.length; i++)
			{
				if (showLoading)
					loadingCollection[i].show();
				else
					loadingCollection[i].hide();
		  }
		}
		
		if (promptOrDisplayDomID) //Empty the the previous content of the report(whether it's showing prompts or report's output)
		{
			if ($(promptOrDisplayDomID))
			{
				  $(promptOrDisplayDomID).update("");
			}
		}
	},
	
	///Validates the required fields of the report
	validate : function()
	{
		var isValid = true;
		for(var i=0;i<this.myData.ExpectedPrompts.length;i++)
		{
			var isValidCriterion = true;
			var expectedPrompt = this.myData.ExpectedPrompts[i];
			if(expectedPrompt.IsRequired)
			{
				var hasPrimary = false;
				var hasSecondary = false;
				
				if($(expectedPrompt.PrimaryElementName))
					var criterionTitleDivElement =  $(expectedPrompt.PrimaryElementName).up('div .CriterionDisplay'); //The element that the css gets applied to when a required prompt is not supplied
				
				if ($(expectedPrompt.PrimaryElementName) && ($F(expectedPrompt.PrimaryElementName)!='') )
					hasPrimary = true;
				
				if ($(expectedPrompt.SecondaryElementName) && ($F(expectedPrompt.SecondaryElementName)!='') )
					hasSecondary = true;
				
				isValidCriterion = hasPrimary || hasSecondary ; //Either one would be enough to run the report
				
				if(!isValidCriterion)
				{
					isValid = false;
					if(criterionTitleDivElement)
						criterionTitleDivElement.addClassName(DynamicReportView.IsRequiredErrorClass);
				}
				else
					if(criterionTitleDivElement)
						criterionTitleDivElement.removeClassName(DynamicReportView.IsRequiredErrorClass);
			}
		}
		
		//Show the generic error if it exists on the page
		if ($(this.myData.DomIDs.MissingRequiredPromptsErrorMessageDomID))
			if(isValid)
				$(this.myData.DomIDs.MissingRequiredPromptsErrorMessageDomID).hide();
			else
				$(this.myData.DomIDs.MissingRequiredPromptsErrorMessageDomID).show();
			
		
		return isValid;
	},
	
	debug : function(msg)
	{
		var queryParams = window.location.toString().toQueryParams();
    if (queryParams.DebugDynamicReportView)
    {
      try { console.info(msg); }
  		catch (Exception) { alert(msg); }
    }
	},
	
	bogus : Prototype.emptyFunction

});

DynamicReportView.Loading = "<div class='AddEditLoadingContainer'><img class='AddEditLoadingDefaultImage' src='/_gfx/icon_sm_loading.gif' /></div>";
DynamicReportView.Page = "/index.aspx";

DynamicReportView.Status = {};
DynamicReportView.Status.Frame = "Frame";
DynamicReportView.Status.FrameWithOnload = "FrameWithOnload";
DynamicReportView.Status.PromptsLoaded = "Prompted";
DynamicReportView.Status.Displayed = "Displayed";
DynamicReportView.IsRequiredErrorClass = 'inputRequired';
DynamicReportView.MissingRequiredPromptsErrorMessageDomID = 'MissingRequiredPromptsErrorMessageElement';

DynamicReportView.Views = new Hash();
DynamicReportView.getView = function(uniqueId)
{
	return DynamicReportView.Views.get(uniqueId);
};
DynamicReportView.addView = function(view)
{
	DynamicReportView.Views.set(view.getUniqueID(), view);

};
DynamicReportView.getReportViewsByReportID = function(reportId) 
{
  matching = [];

  DynamicReportView.Views.each(function(view)
  {
    if (view.value.getReportID() == reportId)
      matching.push(view.value);
  });
 
  return matching;
}

