// Copyright (c) 2008. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

if (!MM.CSXS) MM.CSXS = {};

// Set this to be true for debug messages in the Site Reports Window
MM.CSXS.DEBUG_BUILD = false;

//--------------------------------------------------------------------
// FUNCTION:
//   MM.CSXS.GetHousingPlugIn
//
// DESCRIPTION:
//	returns creates a single instance (singleton) of housing plugin
//	
// ARGUMENTS:
//	none
//
// RETURNS:
//   returns the housing plugin object 
//--------------------------------------------------------------------
MM.CSXS.GetHousingPlugIn = function()
{
	if (MM._housingPlugIn == null)
	{
		MM._housingPlugIn = new DWHousingPlugIn();
		MM._housingPlugIn.initSetUp();
	}
	return MM._housingPlugIn;
}

//--------------------------------------------------------------------
// FUNCTION:
//   MM.CSXS.GetHousingPlugInIfExist
//
// DESCRIPTION:
//	returns current instance (singleton) of housing plugin.
//  Don't create a new instance if it does not exist.
//	
// ARGUMENTS:
//	none
//
// RETURNS:
//   returns the housing plugin object or null.
//--------------------------------------------------------------------
MM.CSXS.GetHousingPlugInIfExist = function()
{
	return MM._housingPlugIn;
}


//--------------------------------------------------------------------
// CLASS:
//   DWHousingPlugIn (single instance)
//
// DESCRIPTION:
//	 housing plug-in to communicate between PlugPlug (CSI) and host application
//	 also maintains a list of csxs services
//--------------------------------------------------------------------
function DWHousingPlugIn()
{
	this._services = new Array(); //list of services
	this._bCalledSetup = false;
    this._bCalledTerminate = false;
}


DWHousingPlugIn.prototype =
{
    initSetUp: function() {
        if (!this._bCalledSetup) {
            var appLanguage = dw.getAppLanguage(); //'en_US'

            this.data = [];
            this.data[0] = 'DRWV';    /**app name**/
            this.data[1] = '11';    /**app version**/
            this.data[2] = appLanguage;    /**app locale**/
            this.data[7] = "unknown";    /**apeVersion**/
            this.data[8] = appLanguage;    /**userinterface locale**/

            this.data[9] = 'MM.CSXS.DisposePlayer';
            this.data[10] = 'MM.CSXS.AllocatePlayer';
            this.data[11] = 'MM.CSXS.RegisterExtension';
            this.data[12] = 'MM.CSXS.ExtensionEvent';
            this.data[13] = 'MM.CSXS.SetMenu';
            this.data[14] = 'MM.CSXS.RequestStateChange';
            this.data[15] = 'MM.CSXS.AllocateEvalScript';
            this.data[16] = 'MM.CSXS.DisposeEvalScript';
            this.data[17] = 'MM.CSXS.EvalScript';
            this.data[19] = 'MM.CSXS.ChangeConnectionsHomeIcon';
            this.data[20] = 'MM.CSXS.AMTRequest';

            this.data[21] = true;    /**PlugPlugPanelWindow**/
            this.data[22] = true;    /**PlugPlugModalDialogWindow**/
            this.data[23] = true;    /**PlugPlugModelessWindow**/
            this.data[24] = true;    /**PlugPlugTooltipWindow**/
            this.data[25] = true;    /**PlugPlugToolbarWindow**/

            this.data[31] = false;    /**offline**/
            this.data[33] = null;
            this.data[41] = 10;    /**font size**/

            if (dw.appVersion && dw.appVersion.indexOf('zh') != -1) 
            {
                // Include Adobe Heidi font to display GB18030 characters in Simplified Chinese version.
                this.data[42] = "Adobe \u9ED1\u4F53 Std R, Adobe Heiti Std R, Arial";
            }
            else
            {
                this.data[42] = dw.getSystemFontName(); // /**font family**/
                //alert("lucia_42 >"+this.data[42]+"<");
            }

            //app-bar color values
            this.data[43] = "PlugPlugColorType_RGB";  /** app bar rgb value**/
            this.data[44] = "PlugPlugAntialiasLevel_None";  /**app bar anti alias level **/
            //**app bar rgb color values - nested array of r,g,b,a**/
            var appBarColorArray = dw.getAppBarColor();
            this.data[45] = [appBarColorArray[0], appBarColorArray[1], appBarColorArray[2], appBarColorArray[3]];
            //panel color values
            this.data[46] = "PlugPlugColorType_RGB";  /** panel rgb value**/
            this.data[47] = "PlugPlugAntialiasLevel_None";  /**panel anti alias level **/
            //**panel rgb color values  - nested array of r,g,b,a **/
            var panelColorArray = dw.getPanelColor();
            this.data[48] = [panelColorArray[0], panelColorArray[1], panelColorArray[2], panelColorArray[3]];

            if (PlugPlug) {
                var retCode = PlugPlug.Setup(this.data);
                this.writeToLog("PlugPlug.Setup retCode..." + retCode, true);

                var ppVersion = PlugPlug.GetVersion();
                var ppVersionStr = ppVersion.major + "." + ppVersion.minor + "." + ppVersion.patch;
                this.writeToLog("PlugPlug version: " + ppVersionStr, true);
            }
            this._bCalledSetup = true;
        }

    },
    LoadStageManager: function() {
        var housingPlugIn = MM.CSXS.GetHousingPlugIn();
        if (housingPlugIn) {
            var extensionId = "STAGEMANAGER";
            var aServiceExtension = housingPlugIn.findExtension(extensionId);
            if (aServiceExtension) {
                aServiceExtension.loadExtension();
            }
        }
    },
    CreateAPEPlayerInstance: function(isDebugMode) {
        var housingPlugIn = MM.CSXS.GetHousingPlugIn();
        if (housingPlugIn) {
            housingPlugIn.writeToLog("CreateAPEPlayerInstance");
            var extensionID = "STAGEMANAGER";
            var controlType = "APEStageWindow";
            var extensionStyle = "PlugPlug";

            var result = dw.flash.createAPEInstance(extensionID, controlType, extensionStyle, isDebugMode);
            housingPlugIn.writeToLog("CreateAPEPlayerInstance - result = >" + result + "<");
        }
    },
    getServices: function() {
        return this._services;
    },
    findExtension: function(extensionId) {
        var retService = null;
        for (var i = 0; i < this._services.length; i++) {
            var aService = this._services[i];
            if (aService.getExtensionId() == extensionId) {
                retService = aService;
                break;
            }
        }
        return retService;
    },
    removeExtension: function(extensionId) {
        var bRemoved = false;
        for (var i = 0; i < this._services.length; i++) {
            var aService = this._services[i];
            if (aService.getExtensionId() == extensionId) {
                this._services.splice(i, 1);
                bRemoved = true;
                break;
            }
        }
        return bRemoved;
    },
    registerExtension: function(extensionId, serviceType, extInfo) {
        //remove an extension if existing
        this.removeExtension(extensionId);

        //register the extension
        var aServiceExtension = new CSXSService(extensionId, serviceType, extInfo);

        this._services.push(aServiceExtension);
        this.writeToLog("after registering service:: " + extensionId);
    },

    handleExtensionCall: function(extensionId, inXMLCallString) {
        this.writeToLog("handleExtensionCall:" + extensionId + " xmlString:" + inXMLCallString);
        var retValue = PlugPlug.ExtensionCall(extensionId, inXMLCallString, MM.CSXS);
        if (retValue && retValue.value) {
            this.writeToLog("response: " + retValue.value);
        }
        else {
            var dumpStr = "";
            this.dumpObj(retValue, dumpStr);
            this.writeToLog("response: " + dumpStr);
            retValue = null;
        }
        return retValue;
    },
	
    handleNotifyStateChange: function(extensionId, inEvent, eventData) {
        this.writeToLog("handleNotifyStateChange:" + extensionId + " xmlString:" + inEvent);
        var retValue = PlugPlug.NotifyStateChange(extensionId, inEvent, eventData);
        this.writeToLog("response: " + retValue);
        return retValue;
    },
    handleMenuCall: function(extensionId, inMenuID) {
        this.writeToLog("handleMenuCall:" + extensionId + " inMenuID:" + inMenuID);
        var retValue = PlugPlug.MenuCall(extensionId, inMenuID);
        this.writeToLog("response: " + retValue);
        return retValue;
    },
    executeScriptCall: function(extensionId, inScript) {
        this.writeToLog("executeScriptCall:" + extensionId + " inScript:" + inScript);
        var retValue = eval(inScript);
        this.writeToLog("response: " + retValue);
        return retValue;
    },
    handleTerminate: function() {
        if (!this._bCalledTerminate) {
            //call unload all the service extension
            for (var i=0; i < this._services.length; i++)
            {
            var aService = this._services[i];
            //unload the service
            PlugPlug.UnloadExtension(aService.getExtensionId());
            }
            //terminate on PlugPlug
            PlugPlug.Terminate();
            this._bCalledTerminate = true;
        }
    },
    writeToLog: function(message, forceCreate) {
        var fileURL = "DWHousingPlugIn";
        if (!MM.CSXS.DEBUG_BUILD)
            return;

        if (forceCreate) {
            dw.resultsPalette.siteReports.addResultItem(this, fileURL, 5, fileURL, message, 0, 0, 0, 0, true);
        }
        else {
            //to work around a bug when shutdown the app - we can create a panel for logging...
            dw.resultsPalette.siteReports.addResultItem(this, fileURL, 5, fileURL, message, 0, 0, 0, 0, false);
        }
    },
    dumpObj: function(anObj, dumpStr) {
        for (var aProp in anObj) {
            typeof (aProp);
            if (typeof (anObj[aProp]) == "object") {
                dumpStr = dumpObjProps(anObj[aProp], dumpStr);
            }
            else {
                dumpStr += aProp;
                dumpStr += ":";
                dumpStr += anObj[aProp];
                dumpStr += "\r\n";
            }
        }
        return dumpStr;
    }
};


//--------------------------------------------------------------------
// CLASS:
//   CSXSServiceMenuItem
//
// DESCRIPTION:
//	 a menu item class for each CSXSService
//--------------------------------------------------------------------
function CSXSServiceMenuItem(menuItemId, menuName, menuPosition)
{
	this._menuItemId = menuItemId,
	this._menuName = menuName;
	this._menuPosition = menuPosition;
}
CSXSServiceMenuItem.prototype = 
{
	getMenuItemId : function()
	{
		return this._menuItemId;
	},
	getMenuName : function()
	{
		return this._menuName;
	},
	getMenuPosition : function()
	{
		return this._menuPosition;
	}
};



//--------------------------------------------------------------------
// CLASS:
//   CSXSService
//
// DESCRIPTION:
//	 a class for csxs service
//--------------------------------------------------------------------
function CSXSService(extensionId, serviceType, obj)
{
/*
    // ensure that min size and max size is set to the values of the default geometry
    obj.minSize.width = obj.defaultGeometry.width;
    obj.minSize.height = obj.defaultGeometry.height;
    obj.maxSize.width = obj.defaultGeometry.width;
    obj.maxSize.height = obj.defaultGeometry.height;
*/
	this._extensionId = extensionId;
	this._serviceType = serviceType;
	this._obj = obj;

	//the list of menu items (fly-out-menu items)
	this._menuItems = new Array();

	//the list of menu items (app-level menu items)
	this._appMenuItems = new Array();
}

function mapPlugPlugType(inType)
{
  var RegEx = new RegExp("PlugPlug(.*)");
  myArray = RegEx.exec(inType);
  if (myArray.length == 2)
    return myArray[1];
  else
    return inType;
}



CSXSService.prototype =
{
    getExtensionId: function() {
        return this._extensionId;
    },
    getServiceType: function() {
        return this._serviceType;
    },
    getPlayerType: function() {
        return this._obj.playerType;
    },
    getSWFPath: function() {
        return this._obj.swfUTF8Path;
    },
    getIconPathNormal: function() {
        return this._obj.iconPathNormal;
    },
    getIconPathRollOver: function() {
        return this._obj.iconPathRollOver;
    },
    getIconPathDisable: function() {
        return this._obj.iconPathDisable;
    },
    getWindowType: function() {
        return this._obj.windowType;
    },
    showWindowOnCreate: function() {
        return this._obj.showWindowOnCreate;
    },
    getGeometry: function() {
        return this._obj.defaultGeometry;
    },
    getTopLeftX: function() {
        return this._obj.defaultGeometry.topleftx;
    },
    getTopLeftY: function() {
        return this._obj.defaultGeometry.toplefty;
    },
    getWidth: function() {
        return this._obj.defaultGeometry.width;
    },
    getHeight: function() {
        return this._obj.defaultGeometry.height;
    },
    getMinSize: function() {
        return this._obj.minSize;
    },
    getMaxSize: function() {
        return this._obj.maxSize;
    },
    addMenuItem: function(aMenuItem) {
        this._menuItems.push(aMenuItem);
        //log the menu items
        var housingPlugIn = MM.CSXS.GetHousingPlugIn();
        if (housingPlugIn) {
            housingPlugIn.writeToLog("Extension Id::" + this._extensionId + "::Menu Item name::" + aMenuItem._menuName);
        }
    },
    addAppMenuItem: function(aMenuItem) {
        this._appMenuItems.push(aMenuItem);
    },
    getMenuItems: function() {
        return this._menuItems;
    },
    getAppMenuItems: function() {
        return this._appMenuItems;
    },
    isOpen: function() {
        return this._isOpen;
    },
    setOpen: function(isOpen) {
        this._isOpen = isOpen;
    },
    setLoaded: function(isLoaded) {
        this._isLoaded = isLoaded;
    },
    createNewExtensionStage: function() {
        var c_Type = mapPlugPlugType(this._obj.windowType);
        if (c_Type == "ModelessWindow" || this._extensionId == "com.adobe.rc.operationalmessages") {
            c_Type = "PanelWindow";
        }
        if(this._extensionId == "SRHP")
        {
            c_Type = "ToolbarWindow";
        }
		else
			if(this._extensionId == "FRIO")
			{
				c_Type = "TooltipWindow";
			}

        var result = dw.flash.newControl(this._extensionId, c_Type, this._obj, "PlugPlug");

		this.setOpen(true);  // set the open status to be true so we have a checkmark
		this.setLoaded(true);

        // I am not getting the RequestStateChange callback from PlugPlug so I am going to do it below manually
        if( (c_Type == "PanelWindow") || (c_Type == "TooltipWindow") ) {
            var myObject = {};
            var requestResult = dw.flash.requestStateChange(this._extensionId, "Open", myObject); //actually creates the panel and loads the swf inside the panel		 
        }
    },
    loadExtension: function() {
        //load the extension
        //create the corresponding UI (floater, dialog, etc) based on UI Type	
        var housingPlugIn = MM.CSXS.GetHousingPlugIn();
        housingPlugIn.writeToLog("loadExtension: " + this._extensionId);
        var retValue = "PlugPlugErrorCode_success";

        if (this._extensionId != "STAGEMANAGER") {
            retValue = PlugPlug.LoadExtension(this._extensionId);
        }
        else {
            //create a floater object
            controlType = mapPlugPlugType(this._obj.windowType);

            //HACK for SRHR and for CH(until we implement the TooltipWindow)
			/*
            if (controlType == "TooltipWindow") {
                controlType = "PanelWindow";
            }
			*/

            //set the name of the extension - to the corresponding top level menu item
            if (this._appMenuItems.length) {
                var extensionName = this._appMenuItems[0].getMenuName();
                if (extensionName && extensionName.length) {
                    //trim the ...
                    var ellipsisIndex = extensionName.indexOf("...");
                    if (ellipsisIndex != -1) {
                        extensionName = extensionName.substring(0, ellipsisIndex);
                    }

                    this._obj.name = extensionName;
                }
            }

            housingPlugIn.writeToLog("dw.flash.newControl - control Type " + controlType);
            var result = dw.flash.newControl(this._extensionId, controlType, this._obj, "PlugPlug");
            housingPlugIn.writeToLog("dw.flash.newControl - result= " + result);

            // I am not getting the RequestStateChange callback from PlugPlug so I am going to do it below manually
            if (controlType == "PanelWindow") {
                housingPlugIn.writeToLog("loadExtension PanelWindow - extensionID = " + this._extensionId);
                var myObject = {};
                var requestResult = dw.flash.requestStateChange(this._extensionId, "Open", myObject); //actually creates the panel and loads the swf inside the panel		 
                this.setOpen(true);  // set the open status to be true so we have a checkmark
                housingPlugIn.writeToLog("loadExtension - result: " + requestResult);
            }

            if (controlType != "ModalDialogWindow") {
                // notify plug plug that we have opened the panel
                housingPlugIn.writeToLog("PlugPlug.NotifyStateChange - id: " + this._extensionId + ", PlugPlugOpen");
                var windowGeometry = [];
                windowGeometry[0] = this.getTopLeftX(); // topleftx
                windowGeometry[1] = this.getTopLeftY(); // toplefty
                windowGeometry[2] = this.getWidth(); // width
                windowGeometry[3] = this.getHeight(); // height
                PlugPlug.NotifyStateChange(this._extensionId, "PlugPlugOpen", windowGeometry);
            }

            this.setLoaded(true);

            // we don't want to show the stage manager
            var requestResult = dw.flash.requestStateChange(this._extensionId, "Hide", myObject);
        }
		
		return( retValue );
    },
    isLoaded: function() {
        return this._isLoaded;
    },
    closeExtension: function() {
        MM.CSXS.RequestStateChange(this._extensionId, "PlugPlugClose", null);
    },
    openExtension: function() {
        MM.CSXS.RequestStateChange(this._extensionId, "PlugPlugOpen", null);
    },
    hideExtension: function() {
        MM.CSXS.RequestStateChange(this._extensionId, "PlugPlugHide", null);
    },
    showExtension: function() {
        MM.CSXS.RequestStateChange(this._extensionId, "PlugPlugShow", null);
    },
    terminateExtension: function() {
        PlugPlug.UnloadExtension(this._extensionId);
		this.setOpen(false);
        this.setLoaded(false);
    },
    reInitExtension: function() {
        //reload the extension to inform PlugPlug that is open
        if (PlugPlug.LoadExtension(this._extensionId) == "PlugPlugErrorCode_success") {
            var housingPlugIn = MM.CSXS.GetHousingPlugIn();

            //log
            housingPlugIn.writeToLog("PlugPlug.Re-Initialize Extension - id: " + this._extensionId);

            //re-init the control/player widget
            controlType = mapPlugPlugType(this._obj.windowType);
            var result = dw.flash.reInitControl(this._extensionId, controlType, this._obj, "PlugPlug");

            // notify plug plug that we have opened the panel
            housingPlugIn.writeToLog("PlugPlug.NotifyStateChange - id: " + this._extensionId + ", PlugPlugOpen");
            var windowGeometry = [];
            windowGeometry[0] = this.getTopLeftX(); // topleftx
            windowGeometry[1] = this.getTopLeftY(); // toplefty
            windowGeometry[2] = this.getWidth(); // width
            windowGeometry[3] = this.getHeight(); // height
            PlugPlug.NotifyStateChange(this._extensionId, "PlugPlugOpen", windowGeometry);
			
            this.setOpen(true);   // need to place check mark next to the menu item for Extensions in the Windows, Extensions menu
            this.setLoaded(true);
        }
    }
};


/**************Register Extension Call back function****************/
MM.CSXS.RegisterExtension = function(extensionId,serviceType,extInfo)
{
	var housingPlugIn = MM.CSXS.GetHousingPlugIn();
	housingPlugIn.writeToLog("RegisterExtension extensionID:" + extensionId);
	housingPlugIn.registerExtension(extensionId,serviceType,extInfo);
	return "PlugPlugErrorCode_success";
}


/********Set Menu call back defined**************/
MM.CSXS.SetMenu = function(serviceID, position, menuArray)
{
	var menuResult = "PlugPlugErrorCode_unknown";
	var housingPlugIn = MM.CSXS.GetHousingPlugIn();
	if (housingPlugIn)
	{	    
		if (serviceID == null)
		{
			for (var i=0; i < menuArray.length; i++)
			{
				//add the menuitem
				var menuItem = menuArray[i];
				//app level menu item
				var aServiceExtension = housingPlugIn.findExtension(menuItem.extensionId);
				if (aServiceExtension)
				{
					var aMenuItem = new CSXSServiceMenuItem(menuItem.menuId, menuItem.nameUtf8, position);		
					housingPlugIn.writeToLog("app menu for extension id:" + menuItem.extensionId + "::" + menuItem.nameUtf8);
 				    aServiceExtension.addAppMenuItem(aMenuItem);
                    menuResult = "PlugPlugErrorCode_success";
				}
			}
		}
		else
		{
			//display the menu item name and next menu item.
			var aServiceExtension = housingPlugIn.findExtension(serviceID);
			if (aServiceExtension)
			{
				for (var i=0; i < menuArray.length; i++)
				{
					//add the menuitem
					var menuItem = menuArray[i];
					//service specific menu item
					var aMenuItem = new CSXSServiceMenuItem(menuItem.menuId, menuItem.nameUtf8, position);		
					aServiceExtension.addMenuItem(aMenuItem);
				}
			}			
			menuResult = dw.flash.setMenu(serviceID,serviceID,menuArray);
		}
	}

	return menuResult;
}


/****** Extension Event Call back *************/
MM.CSXS.ExtensionEvent = function(serviceID, xmlStr)
{
  var housingPlugIn = MM.CSXS.GetHousingPlugIn();
  housingPlugIn.writeToLog("ExtensionEvent function :"+serviceID+ "  "+xmlStr);
  outStr = dw.flash.controlEvent(serviceID, xmlStr);
  housingPlugIn.writeToLog("ExtensionEvent result : " + outStr);

  return outStr;
}


/**********Request State Change callback defined**********/

MM.CSXS.RequestStateChange = function(extId, eventType, data)
{
/*
PlugPlugNotifyStateChange
now only provides 'PlugPlugGoOffline', 'PlugPlugGoOnline', 'PlugPlugGetFocus' and 'PlugPlugLoseFocus' (see PlugPlug).
*/

  var housingPlugIn = MM.CSXS.GetHousingPlugIn();

  housingPlugIn.writeToLog("RequestStateChange :"+extId+" event="+eventType+" data="+data);

  eventType = mapPlugPlugType(eventType);    

  
  if (eventType == "Resize" || eventType == "Move")
  {
      housingPlugIn.writeToLog(eventType + ": topleftx= "+data.topleftx+" toplefty= "+data.toplefty+" width= "+data.width+" height="+data.height);
  }
  else if (eventType == "Reskin")
  {
      housingPlugIn.writeToLog("Data :"+data.baseFontSize+" "+data.baseFontFamily+" "+data.backgroundGreyPercentage);
  }
 
  if (data == null)
  {
	//use empty dat value
	data = {};
  }

  //send the request state change event inside DW.
  var stateChangeResult = dw.flash.requestStateChange(extId, eventType, data);

  var aServiceExtension = housingPlugIn.findExtension(extId);
  if (eventType == "Hide")
  { 	
		if (aServiceExtension)
		{ 
		  aServiceExtension.setOpen(false);
		}
		housingPlugIn.writeToLog("Sending Hide Notify StateChange : ");
		//notify plug plug that we close the extension
	  PlugPlug.NotifyStateChange(extId, "PlugPlugHide", null);
  } 
  else if (eventType == "Show") 
  {
	  if (aServiceExtension)
	  {
	    housingPlugIn.writeToLog("Show : "+extId);
	    aServiceExtension.setOpen(true);
	  }
    housingPlugIn.writeToLog("Sending Show Notify StateChange : ");
    PlugPlug.NotifyStateChange(extId, "PlugPlugShow", null);
  } 
  else if (eventType == "Close")  
  {
		if (aServiceExtension)
		{ 
		  housingPlugIn.writeToLog("Close : "+extId);
		  aServiceExtension.setOpen(false);   // #242871 - We are going to treat a close like a hide
		}
		//notify plug plug that we close the extension
	  PlugPlug.NotifyStateChange(extId, "PlugPlugClose", null);
  } 
  else if (eventType == "Open") 
  {
	  if (aServiceExtension)
	  {
	    housingPlugIn.writeToLog("SetOpen : "+extId);
	    aServiceExtension.setOpen(true);
	  }
    housingPlugIn.writeToLog("Sending Open Notify StateChange : ");
    PlugPlug.NotifyStateChange(extId, "PlugPlugOpen", null);
  } 

  return stateChangeResult;
}

/*******Allocate Eval Script Call back defined************/
MM.CSXS.AllocateEvalScript = function(engineId)
{
  var housingPlugIn = MM.CSXS.GetHousingPlugIn();
  var retCode = "PlugPlugErrorCode_engineAllocationFailure";

  //using the engine id , get the service id
  if (engineId.search(/([^_]+)_(\w+)_(\w+)/ig) != -1)
  {
	var extensionId = RegExp.$1;
	if (extensionId != null)
	{
		if (dw.flash.allocateScriptDoc(extensionId))
		{
			//successfully allocated a dedicated js engine for extension id
			retCode = "PlugPlugErrorCode_success";
		}
	}
  }  	
  housingPlugIn.writeToLog("AllocateEvalScript :"+engineId);
  return retCode;
}

/*******Dispose Eval Script Call back defined************/
MM.CSXS.DisposeEvalScript = function(engineId)
{
  var housingPlugIn = MM.CSXS.GetHousingPlugIn();
  var retCode = "PlugPlugErrorCode_success";

  //using the engine id , get the service id
  if (engineId.search(/([^_]+)_(\w+)_(\w+)/ig) != -1)
  {
	var extensionId = RegExp.$1;
	if (extensionId != null)
	{
		//de-allocated a js engine for extension id
		dw.flash.deAllocateScriptDoc(extensionId);
	}
  }  	
  housingPlugIn.writeToLog("DisposeEvalScript :"+engineId);
  return retCode;
}

/*******Eval Script Call back defined************/
MM.CSXS.EvalScript = function(engineId, script)
{
  var housingPlugIn = MM.CSXS.GetHousingPlugIn();
  housingPlugIn.writeToLog("EvalScript :"+engineId+"  "+script);
  //using the engine id , get the service id
  if (engineId.search(/([^_]+)_(\w+)_(\w+)/ig) != -1)
  {
	var extensionId = RegExp.$1;
	if (extensionId != null)
	{
		retCode = dw.flash.evalScript(extensionId,script);
	}
  }  	
  return retCode;
}

/*******AMTRequest Call back defined************/
MM.CSXS.AMTRequest = function(buffer, buffersize)
{
    var amtRequestValueArray = dw.flash.handleAMTPlugPlugRequest(buffer, buffersize);

    var returnArray = new Array();
    returnArray[0] = amtRequestValueArray[0];
    returnArray[1] = amtRequestValueArray[1];

    return returnArray;
}
/*******AMTRequest Call back defined************/
MM.CSXS.ChangeConnectionsHomeIcon = function(textUtf8, imageSize, imageData, tooltipUtf8, type)
{
/*
The function must have the following signatue: function(textUtf8, imageSize, imageData, tooltipUtf8, type)
    If a value is not defined than it is set to 'undefined'.
    If imageSize is not defined '-1' is set.
    The imageData is passed as a string that represents the hex values of its charaters e.g. 'ABC' -> '414243'
For more information about the arguments see:
csxs::ch::ConnectionsHomeIcon
*/
    dw.flash.handleChangeConnectionsHomeIcon(textUtf8, imageSize, imageData, tooltipUtf8, type);
}

/*******AllocatePlayer Call back defined************/
MM.CSXS.AllocatePlayer = function(isDebugMode)
{
    var isDebugModeBool = new Boolean(true);

    if(isDebugMode == "false")
        isDebugModeBool = false;

    MM._housingPlugIn.CreateAPEPlayerInstance(isDebugModeBool);

    var apeRefStr = dw.flash.getAPEPlayerRefAsString();

    return apeRefStr;
}

/*******DisposePlayer Call back defined************/
MM.CSXS.DisposePlayer = function(APEPlayerRef)
{
    dw.flash.handleDisposeAPEPlayer(APEPlayerRef);
}
