/*
  CLASS LIST:

	* LIApi
	* LIContentRegistry
*/

/*############################################################
	Liquid Intelligence:
	 Api Class
 ############################################################*/

/*==========================
 Constructor
 ==========================*/ 
function LIApi(n_liApplication)
{
	LIApi.prototype.Application = n_liApplication;
	LIApi.prototype.ContentRegistry = new LIContentRegistry(n_liApplication);
}

/*==========================
 Call
 ==========================*/
function LIApi_Call(n_apiName, n_requestXml)
{
	//Quick parameter check
	if (n_apiName == null || n_requestXml == null){ this.Application.ShowInformation("A parameter was not defined"); return; }

	//Make sure our root tag is <request>
	var requestXml;
	var root = n_requestXml.documentElement

	//Get the time zone offset to add to the XML request
	var now = new Date();
	var timeZoneOffset = now.getTimezoneOffset();

	if (root == null || root.nodeName != "request")
	{
		requestXml = this.Application.Xml.NewMSDom();
		requestXml.loadXML( "<request>" +
							"<client_context>" +
							"	<time_zone_offset>" + timeZoneOffset + "</time_zone_offset>" +
							"	<ui_context>" + this.Application.GlobalClientContext + "</ui_context>" +
							"</client_context>" +
								n_requestXml.xml +
							"</request>");
	}
	else
	{	
		var node = n_requestXml.createElement("client_context");
		root.appendChild(node);
		
		var subNode = n_requestXml.createElement("time_zone_offset");
		node.appendChild(subNode);
		subNode.text = timeZoneOffset;
		
		subNode = n_requestXml.createElement("ui_context");
		node.appendChild(subNode);
		subNode.text = this.Application.GlobalClientContext;

		requestXml = n_requestXml;
	}

	Application.Debug.WriteMessage("Call()","Calling remote API: <font color='gray'>" + n_apiName + "</font>");
	
	if (Application.Debug.DebugLevel == "DETAILED")
		Application.Debug.WriteTextMessage("RequestXML","Request XML: " + requestXml.xml);

	//Call the API
	var apiUrl = Application.ResolveUrl("~/callapi.ashx?api=" + n_apiName);

	var responseXML = this.Application.Xml.RemoteXmlCall(apiUrl, requestXml);
	
	if (Application.Debug.DebugLevel == "DETAILED")
		Application.Debug.WriteTextMessage("ResponseXML","Response XML: " + responseXML.ToString());

	return responseXML
}
LIApi.prototype.Call = LIApi_Call;


/*############################################################
	Liquid Intelligence:
	 Content Registry Class
 ############################################################*/
/*==========================
 Constructor
 ==========================*/ 
function LIContentRegistry(n_liApplication)
{ 
	LIContentRegistry.prototype.Application = n_liApplication;
	
	LIContentRegistry.prototype.CLASS_LI_FILE = "0DD2F31D-FD46-4E7C-8B65-6756C615CDB4";
	LIContentRegistry.prototype.CLASS_LI_FOLDER = "72F3AC9C-CDF9-4063-AADB-DAD75F53EC9B";
}

/*==========================
 DoAction
 ==========================*/ 
function LIContentRegistry_DoAction( contentGuid, action, comment )
{
	var req = this.Application.Xml.NewDom();
	req.SetRootName("<request>");
	
	req.Add("<content_registries>+");
		req.Add("<content_registry>+","@guid", contentGuid);
			req.Add("<action>", action);
			req.Add("<comment>", comment);
	
	var xmlResponse = Application.Api.Call( "ContentRegistry.DoAction", req.Dom );
	if ( !xmlResponse.IsValidResponse() ) {	xmlResponse.ShowErrorDialog(); return null; }

	return xmlResponse;
}
LIContentRegistry.prototype.DoAction = LIContentRegistry_DoAction;

/*==========================
 CreateContent
 ==========================*/ 
function LIContentRegistry_CreateContent( n_contentName, n_classGuid, n_comment, n_parentContentGuid, n_relationshipType )
{
	var req = this.Application.Xml.NewDom();
	req.SetRootName("<request>");
	
	req.Add("<content_registries>+");
		req.Add("<content_registry>+","@guid", this.Application.NULL_GUID);
			req.Add("<action>", "create");
			req.Add("<comment>", n_comment);
	
			req.Add("<created_content>+");
			
				req.Add("<content_registry>+");
					req.Add("<class_guid>", n_classGuid);
					req.Add("<name>", n_contentName);
				
				req.Add("-<content_registry_association>+");
					req.Add("<parent_content_registry_guid>", n_parentContentGuid);
					req.Add("<relationship_type>", n_relationshipType);

	var xmlResponse = Application.Api.Call( "ContentRegistry.DoAction", req.Dom );
	if ( !xmlResponse.IsValidResponse() ) {	xmlResponse.ShowErrorDialog(); return null; }

	return xmlResponse;
}
LIContentRegistry.prototype.CreateContent = LIContentRegistry_CreateContent;

//==============================
// ShowCreationUI
//==============================
function LIContentRegistry_ShowCreationUI(n_window, n_classGuid, n_parentGuid, n_arguments)
{
	//Hard code the create, the class is passed as the content guid
	return this.ShowActionUI(n_window, "create", n_classGuid, n_parentGuid, n_arguments);
}
LIContentRegistry.prototype.ShowCreationUI = LIContentRegistry_ShowCreationUI;


//==============================
// ShowActionUI
// - launches appropriate creation editor based on class of item
//- action can be string verb or actionUI object
//==============================
function LIContentRegistry_ShowActionUI(n_window, n_action, n_inputGuid, n_parentGuid, n_arguments)
{

	if ( n_window == null || n_window.self == null)
	{
		Application.ShowInformation("You must supply a Parent Window for Show Action UI to work");
		return;
	}

	//get handler details and make sure valid
	var actionUI;

	if (typeof(n_action._sysType) != "undefined" && n_action._sysType == "ACTION_UI") { actionUI = n_action; } else { actionUI = this.GetActionUI(n_inputGuid, n_action); }

	Application.Debug.WriteMessage("ShowActionUI()","Requesting UI for action: " + actionUI.Action + " and ContentGuid: " + n_inputGuid);

	if ( !actionUI.FoundUI )
	{
		Application.ShowInformation("Information\n\nThere is no user interface or action\ndefined for this item.");
		return;
	}
	if ( !actionUI.RawResponse.IsValidResponse() ) { actionUI.RawResponse.ShowErrorDialog(); return; }

	var url = Application.ResolveUrl( actionUI.UIHandler );
	url = url + ( ( actionUI.UIHandler.indexOf( "?" ) < 0 ) ? "?" : "&" );
	url = url + ( (actionUI.Action.toUpperCase() == "CREATE") ? "CLASS_GUID=" : "CR_GUID=") + n_inputGuid;
	url = url + "&PARENT_CR_GUID=" + n_parentGuid;
	url = url + "&ACTION=" + actionUI.Action;
	url = url + "&globalClientContext=" + Application.GlobalClientContext;

	//MG: special recognized flag that indicated that
	//the content for which we're going to show action UI
	//has just been created - the flag will be passed on
	//to server side renderer as part of the URL.
	if ("object" == typeof(n_arguments) && null != n_arguments)
	{
		if (true == n_arguments.Created)
		{
			url += "&Created=true";
		}
	}

	//Generate a unique name 
	//if we don't have a creg guid, use the class as a basis for the window name
	var formName = ( n_inputGuid != "" ) ? (n_action + "_" + n_inputGuid.substring(0,8)) : (n_action + "_handler");

	//check to see if a window mode has been specified, set to dialog style for default
	if (actionUI.WindowType == "") { actionUI.WindowType = "WINDOW" };
	
	//----------------
	//Open Window
	//----------------
		switch ( actionUI.WindowType.toUpperCase() )
		{
			case "MODAL":
				if (actionUI.Parameters == "") {
					actionUI.Parameters = "scroll: no; help: no; status: no; resizable: yes;"
				}
				
				var arguments = (n_arguments == null ? new Object() : n_arguments);
				arguments.Window = n_window;
				var result = this.Application.ShowModalDialog( n_window, url, arguments, actionUI.Parameters );
				arguments = null;
				n_window = null;
				CollectGarbage();
				return result;
				break;

			case  "WINDOW":
 			default:

 			 //Check to see if window style has been defined - use defaults if not
 
				var intAvailWidth, intAvailHeight;
				var intLeft, intTop, intWidth, intHeight;
				 
				if (actionUI.Parameters == "")
				{
					intWidth = 800;
					intHeight = 600;

					//----------------
					//Center Form
					//----------------
					intAvailWidth = window.screen.availWidth;
					intAvailHeight = window.screen.availHeight;
					intLeft = (intAvailWidth-intWidth) / 4;
					intTop = ((intAvailHeight-intHeight) / 3);

					//----------------
					//Setup Options
					//----------------
					actionUI.Parameters="top=" + intTop +
								",left=" + intLeft +
								",width=" + intWidth +
								",height=" + intHeight +
								",channelmode=no" +
								",directories=no" +
								",fullscreen=no" +
								",location=no" +
								",menubar=no" +
								",resizable=yes" +
								",scrollbars=yes" +
								",status=yes" +
								",titlebar=yes" +
								",toolbar=no";
				}
 			
				n_window.open(url, "", actionUI.Parameters);
				break;
		}

}
LIContentRegistry.prototype.ShowActionUI = LIContentRegistry_ShowActionUI;


//==============================
// GetActionUI
//==============================
function LIContentRegistry_GetActionUI(n_inputGuid, n_action)
{
  //Call the API to acquire a UI  
	var xd = this.Application.Xml.NewDom();

	xd.SetRootName("<request>");
	
	if( n_action.toUpperCase() == "CREATE")	{
		xd.Add("<class>", "@guid", n_inputGuid);
	} 
	else{
		xd.Add("<content_registry>", "@guid", n_inputGuid);
	}
	
		xd.Add("<action>", n_action);
		xd.Add("<platform>", this.Application.PLATFORM);


	var response = this.Application.Api.Call("ContentRegistry.GetActionUIHandler", xd.Dom);

  //check to see if viewer has been defined for class
	var actionUI = new Object();
	actionUI._sysType = "ACTION_UI";
	actionUI.FoundUI = false;
	actionUI.RawResponse = response;

	if(	!response.IsValidResponse() ) {return actionUI;}

	var action = response.GetNodeValue("/response/data/action","");
 
	if (action.toUpperCase() != n_action.toUpperCase()) {return actionUI; }

	actionUI.FoundUI = true;
	actionUI.Action = action;
	actionUI.ContentGuid = n_inputGuid;
	actionUI.UIHandler = response.GetNodeValue("/response/data/ui_handler","");
	actionUI.Parameters = response.GetNodeValue("/response/data/parameters","");
	actionUI.WindowType = response.GetNodeValue("/response/data/window_type","");
	
	return actionUI;
}
LIContentRegistry.prototype.GetActionUI = LIContentRegistry_GetActionUI;