////////////////////////////////////////////////////////////////////////////////
//   Wizard Library
////////////////////////////////////////////////////////////////////////////////

// <script language="javascript">
// Copyright (c) Home Automation, Inc. All rights reserved.          
// Copyright (c) HomeRun Software Systems LLC. All rights reserved.

////////////////////////////////////////////////////////////////////////////////
// Globals
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Connection: Saves the Connection Page Data
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Connection
(
	szConnection
)
{
	// Save the connection data
	Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/CURRENT", szConnection);
	
	// Navigate to the next page
	switch (szConnection)
	{
		case "Network":
		case "Remote":
			ShowPage(PAGE_CTRLR_WIZ_ADDRESS_PORT);
			break;
		case "Serial":
			ShowPage(PAGE_CTRLR_WIZ_SERIAL);
			break;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_IP_Port: Saves the IP Address and Port Page Data
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_IP_Port
(
	IP1,
	IP2,
	IP3,
	IP4,
	szPort
)
{
	// Explicit string conversion
	IP1 += "";
	IP2 += "";
	IP3 += "";
	IP4 += "";
	szPort += "";

	// Validate IP Address
	if ( !isValidIPAddress(IP1 + "." + IP2 + "." + IP3 + "." + IP4) )
	{
		ErrorHandler(null, ERR_INVALID_IP);
		return;
	}
	
	// Validate Port
	if ( (parseInt(szPort) > 99999) || (szPort.length == 0) )
	{
		ErrorHandler(null, ERR_INVALID_PORT);
		return;
	}
	
	// Save data and navigate to the next page
	var nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/COMMHANDLERS/CURRENT");
	var szConn = new String(nodeResult.childNodes(0).text);

	switch (szConn.toUpperCase())
	{
		case "NETWORK":
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/IP1", IP1);
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/IP2", IP2);
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/IP3", IP3);
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/IP4", IP4);
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/ADDRESS", IP1 + "." + IP2 + "." + IP3 + "." + IP4);
			Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/PORT", szPort+"");
			ShowPage(PAGE_CTRLR_WIZ_NWRK_ENCRYPT);
			break;
		case "REMOTE":
			//ShowPage(PAGE_CTRLR_WIZ_ADDRESS_PORT);
			break;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Serial: Saves the Serial Page Data
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Serial()
{
	// Save the Comm Port data
	Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Serial']/PORT", (g_oSpinner[0].SelectedIndex+1));
	
	// Save the Baud Rate data
	Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Serial']/BAUDRATE", g_oSpinner[1].Value);
	
	// Navigate to the next page
	ShowPage(PAGE_CTRLR_WIZ_CODE);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Code: Saves the Code Page Data
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Code
(
	szCode
)
{
	// Explicit string conversion
	szCode += "";

	// Validate Port
	if ( (parseInt(szCode) > 9999) || (szCode.length == 0) )
	{
		ErrorHandler(null, ERR_INVALID_ACCESS_CODE);
		return;
	}
	
	// Save data and navigate to the next page
	Wizard_UpdateNode("CONTROLLER/ACCESSCODE", szCode);
	ShowPage(PAGE_CTRLR_WIZ_FINISH);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Encrypt: Saves the Encryption key
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Encrypt
(
	szEncrypt1,
	szEncrypt2
)
{
	// Explicit string conversion
	szEncrypt1 += "";
	szEncrypt2 += "";

	// Verify proper format
	var aryEncrypt1 = szEncrypt1.split("-");
	if (aryEncrypt1.length != 8)
	{
		ErrorHandler(null, ERR_INVALID_ENCRYPTION_KEY);
		Encrypt1.focus();
		return;
	}

	var aryEncrypt2 = szEncrypt2.split("-");
	if (aryEncrypt2.length != 8)
	{
		ErrorHandler(null, ERR_INVALID_ENCRYPTION_KEY);
		Encrypt2.focus();
		return;
	}
	
	// Verify proper length
	if (szEncrypt1.length != 23)
	{
		ErrorHandler(null, ERR_INVALID_ENCRYPTION_KEY);
		Encrypt1.focus();
		return;
	}

	if (szEncrypt2.length != 23)
	{
		ErrorHandler(null, ERR_INVALID_ENCRYPTION_KEY);
		Encrypt2.focus();
		return;
	}
		
	// Save data and navigate to the next page
	Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/PRIVATEKEY1", szEncrypt1);
	Wizard_UpdateNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']/PRIVATEKEY2", szEncrypt2);

	ShowPage(PAGE_CTRLR_WIZ_FINISH);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Test_Connection: Establish and Test Connection
////////////////////////////////////////////////////////////////////////////////
function Wizard_Test_Connection()
{
	// If in demo mode then bail
	if (DEMO_MODE)
	{
		ErrorHandler(null, ERR_DEMO_COMMANDS);
		CancelWizard();
		return;
	}

	MessageHandler(MSG_TEST_CONNECTION);

	// Disconnect event handlers
	KillEventHandlers();
	
	// Stop the Server
	ConnectionTestResults.innerHTML = "Stopping Communications Server...";
	g_oHAI.Stop();

	// Start timer to check status
	window.refreshTimerCtrlr = window.setInterval("Wizard_CheckCtrlrStatus()", 3000);

	// Save the wizard settings 
	SaveCtrlrWizardData();
	
	// Start the Server
	ConnectionTestResults.innerHTML = "Starting Communications Server...";
	g_oHAI.Start();
	
	// Initialize event handlers
	InitEventHandlers();
	
	// Enable Finish Button
	spnWizardNext.filters(0).src = AIButtonItem["WizardBtn"].Deselect.src;
	AIButtonSelect(spnWizardNext, "WizardBtn");
}

////////////////////////////////////////////////////////////////////////////////
// CancelWizard: Cancels the Wizard
////////////////////////////////////////////////////////////////////////////////
function CancelWizard()
{
	var aryPageInfo;
	var iPage = null;
	
	while (iPage != PAGE_SETTINGS_CONTROLLER)
	{
		// Remove the current page from the history and discard it
		aryPageInfo = g_NavHistory.pop();
		iPage = aryPageInfo[0];
	}
	
	ShowPage(PAGE_SETTINGS_CONTROLLER);
}

////////////////////////////////////////////////////////////////////////////////
// CancelRuleWizard: Cancels the Rule Wizard
////////////////////////////////////////////////////////////////////////////////
function CancelRuleWizard()
{
	var aryPageInfo;
	var iPage = null;
	
	while (iPage != PAGE_RULES_LIST)
	{
		// Remove the current page from the history and discard it
		aryPageInfo = g_NavHistory.pop();
		iPage = aryPageInfo[0];
	}
	
	ShowPage(PAGE_RULES_LIST);
}

////////////////////////////////////////////////////////////////////////////////
// FinishWizard: Finish the Wizard
////////////////////////////////////////////////////////////////////////////////
function FinishWizard()
{
	// If button was disabled then return without processing
	if ( (spnWizardNext.filters(0).src == AIButtonItem["WizardBtn"].Disable.src) ||
		 (spnWizardNext.filters(0).src == AIButtonItem["WizardBtn"].DisableSelect.src) )
	{
		MessageHandler(MSG_CHOOSE_TEST_CONNECTION);
		return;
	}
	
	// Remove wizard pages from Navigation History and goto Welcome Page
	g_NavHistory = new Array();
	ShowPage(PAGE_WELCOME);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_UpdateNode: Updates the node with the given value
////////////////////////////////////////////////////////////////////////////////
function Wizard_UpdateNode
(
	szNode,
	szValue
)
{
	try
	{
		// Select the node to be updated
		var nodeResult = oXMLDoc.selectSingleNode(szNode);

		if (null != nodeResult)
		{
			// Create the new node
			var textNode = oXMLDoc.createTextNode(szValue);

			// Replace the old node with the new one
			nodeResult.replaceChild(textNode, nodeResult.childNodes.item(0));
		}
		else
		{
			// The node doesn't exist so we need to create a new one
			// Get the parent node
			var iNodeStart = szNode.lastIndexOf("/") + 1;
			var szParentNode = szNode.substr(0, iNodeStart-1);
			var nodeParent = oXMLDoc.documentElement.selectSingleNode(szParentNode);
			
			// Create new node
			var nodeItem = oXMLDoc.createElement(szNode.substr(iNodeStart));
			var textNode = oXMLDoc.createTextNode(szValue);
			nodeItem.appendChild(textNode);
			nodeParent.appendChild(nodeItem);
		}
	}
	catch(oError)
	{
		ErrorHandler(oError);
	}
}

////////////////////////////////////////////////////////////////////////////////
// SaveCtrlrWizardData: Save Wizard Data
////////////////////////////////////////////////////////////////////////////////
function SaveCtrlrWizardData()
{
	// Set Connection Type
	var nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/COMMHANDLERS/CURRENT");
	var szCurrentConnection = nodeResult.childNodes(0).text;
	
	// Get the index of the selected connection type
	nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = '" + szCurrentConnection + "']");
	var iCommHandlerIndex = nodeResult.childNodes(1).text -0;
	
	// Get Access Code
	nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/ACCESSCODE");
	g_oHAI.AccessCode = nodeResult.childNodes(0).text;	// Access Code

	// Configure Comm Handler
	var oCommHandler = g_oHAI.CommHandlers.Item(szCurrentConnection);

	switch (szCurrentConnection)
	{
		case "Network":
			// Get Network Settings
			nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Network']");
			
			oCommHandler.Address    = nodeResult.childNodes(2).text ;	// IP Address
			oCommHandler.Port       = nodeResult.childNodes(7).text;	// Port
			oCommHandler.PrivateKey = nodeResult.childNodes(8).text + "-" + nodeResult.childNodes(9).text;
			break;
		
		case "Serial":
			// Get Serial Settings
			nodeResult = oXMLDoc.selectSingleNode("CONTROLLER/COMMHANDLERS/COMMHANDLER[NAME = 'Serial']");
			oCommHandler.BaudRate = nodeResult.childNodes(2).text;	// BaudRate
			oCommHandler.Port = nodeResult.childNodes(3).text;	// Port
			break;
	}

	// Set the new comm handler	
	g_oHAI.CommunicationsHandler = oCommHandler;

	// Save the settings within HAICommSrv
	g_oHAI.SaveSetup();
	
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_CheckCtrlrStatus: Check the controller startup status
////////////////////////////////////////////////////////////////////////////////
function Wizard_CheckCtrlrStatus()
{
	var iStatus  = g_oHAI.Status;
	var szStatus = "";
	
	switch (iStatus)
	{
		case ssStarting:
			szStatus = "Controller is starting...";
			break;
		case ssLoadingSetup:
			szStatus = "Loading Setup information...";
			break;
		case ssLoadingNames:
			szStatus = "Loading Names information...";
			break;
		case ssInteractive:
			szStatus = "Success! Choose 'Finish' now.";
			window.clearInterval(window.refreshTimerCtrlr);
			break;
		case ssStopping:
			szStatus = "Controller is stopping...";
			break;
		case ssFailure:
			szStatus = "Failure! Choose 'Back' to verify proper settings and try again.";
			window.clearInterval(window.refreshTimerCtrlr);
			break;
	}
	
	ConnectionTestResults.innerHTML = szStatus;
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Condition: Save the Rule condition
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Condition
(
	iCondition
)
{
	switch (iCondition)
	{
		case EC_ALARM:
			iNextPage = PAGE_RULES_ALARM;
			break;
		case EC_UNIT:
			iNextPage = PAGE_RULES_UNIT;
			break;
		case EC_SECURITY:
			iNextPage = PAGE_RULES_SECURITY;
			break;
		case EC_ZONE:
			iNextPage = PAGE_RULES_ZONE;
			break;
		default:
			return;
	}

	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/EVENT/EVENT_TYPE", iCondition);

	// Determine next page
	ShowPage(iNextPage);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Unit: Save the Unit
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Unit
(
	szUnitName,
	iUnitID,
	iState
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/EVENT/UNITNAME", szUnitName);
	Wizard_UpdateNode("/RULE/EVENT/UNIT", iUnitID);
	Wizard_UpdateNode("/RULE/EVENT/UNITID", iUnitID);
	Wizard_UpdateNode("/RULE/EVENT/STATE", iState);
	Wizard_UpdateNode("/RULE/EVENT/STATEID", iState);

	// Show Next Page
	ShowPage(PAGE_RULES_VIDEO_PROPERTIES);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Alarm: Save the Alarm
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Alarm
(
	szAreaName,
	iAreaID,
	iAlarm
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/EVENT/AREANAME", szAreaName);
	Wizard_UpdateNode("/RULE/EVENT/AREA", iAreaID);
	Wizard_UpdateNode("/RULE/EVENT/AREAID", iAreaID);
	Wizard_UpdateNode("/RULE/EVENT/ALARMTYPE", iAlarm);
	Wizard_UpdateNode("/RULE/EVENT/ALARMTYPEID", iAlarm);

	// Show Next Page
	ShowPage(PAGE_RULES_VIDEO_PROPERTIES);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Security: Save the Security
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Security
(
	szAreaName,
	iAreaID,
	iMode,
	iUser
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/EVENT/AREANAME", szAreaName);
	Wizard_UpdateNode("/RULE/EVENT/AREA", iAreaID);
	Wizard_UpdateNode("/RULE/EVENT/AREAID", iAreaID);
	Wizard_UpdateNode("/RULE/EVENT/SECURITYMODE", iMode);
	Wizard_UpdateNode("/RULE/EVENT/SECURITYMODEID", iMode);
	Wizard_UpdateNode("/RULE/EVENT/SECURITYCODE", iUser);

	// Show Next Page
	ShowPage(PAGE_RULES_VIDEO_PROPERTIES);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Video_Properties: Save the Video Record Properties
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Video_Properties
(
	iChannel,
	iDuration,
	bGuaranteedRecording
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/NOTIFICATION/CHANNEL", iChannel);
	Wizard_UpdateNode("/RULE/NOTIFICATION/RECORDDURATION", iDuration);
	Wizard_UpdateNode("/RULE/NOTIFICATION/GUARANTEEDRECORDING", bGuaranteedRecording);

	// Show Next Page
	ShowPage(PAGE_RULES_NAME);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Name: Save the Rule Name & Create Rule
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Name
(
	szName,
	bEnabled
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/NAME", szName);
	Wizard_UpdateNode("/RULE/STATUS", bEnabled);

	// Save the rule
	SaveVideoRule();
	
	// Return back to rules list
	CancelRuleWizard();
}

////////////////////////////////////////////////////////////////////////////////
// CancelRuleWizard: Cancels the Rule Wizard
////////////////////////////////////////////////////////////////////////////////
function CancelRuleWizard()
{
	var aryPageInfo;
	var iPage = null;
	
	while (iPage != PAGE_RULES_LIST)
	{
		// Remove the current page from the history and discard it
		aryPageInfo = g_NavHistory.pop();
		iPage = aryPageInfo[0];
	}
	
	ShowPage(PAGE_RULES_LIST);
}

////////////////////////////////////////////////////////////////////////////////
// Wizard_Save_Rule_Zone: Save the Zone
////////////////////////////////////////////////////////////////////////////////
function Wizard_Save_Rule_Zone
(
	szZoneName,
	iZoneID,
	iState
)
{
	// Save data and navigate to the next page
	Wizard_UpdateNode("/RULE/EVENT/ZONENAME", szZoneName);
	Wizard_UpdateNode("/RULE/EVENT/ZONE", iZoneID);
	Wizard_UpdateNode("/RULE/EVENT/ZONEID", iZoneID);
	Wizard_UpdateNode("/RULE/EVENT/STATE", iState);
	Wizard_UpdateNode("/RULE/EVENT/STATEID", iState);

	// Show Next Page
	ShowPage(PAGE_RULES_VIDEO_PROPERTIES);
}

