/*!
**********************************************************************
@file personalization.js

Copyright 2003-2006 Adobe Systems Incorporated.                     
All Rights Reserved.                                                
                                                                    
NOTICE: All information contained herein is the property of Adobe   
Systems Incorporated.                                                                                                                    

***********************************************************************
*/

/**
Implement a Wizard Page in three easy steps:

 1. Subclass WizardPage
 2. Extend with page-specific method overrides
 3. Return the WizardPage subclass name

*/

/***********************************************************************
1. Subclass WizardPage
*/
function personalization_wp(inController)
{
	this.SetController(inController);
	
	this.PayloadsToCheck = new Array();
	this.mustProvideSerial = false;
	
	this.radioState = "serial";
	this.serialNumberValid = "0";
	this.serialNumberOutput = "";
	this.serialNumber = "";	
	
	this.serialIcon = null;
	
	this.arrSNElements = new Array("personalization_SN1", "personalization_SN2", "personalization_SN3", "personalization_SN4", "personalization_SN5", "personalization_SN6");
}

personalization_wp.prototype = new WizardPage("personalization");

/***********************************************************************
2. Extend/override with page-specific logic
*/
personalization_wp.prototype.GetDisplayName = function()
{
	return this.localization.GetString("locNavTitle", "Personalization");
}

personalization_wp.prototype.isActive = function()
{
	var validResults = null;
	var requiresResult = false;
	this.PayloadsToCheck = new Array();

	for (var pay in this.wizardControl.session.sessionPayloads)
	{
		validResults = this.wizardControl.session.GetStreamsForAdobeCode(pay);

		if (validResults && validResults["Streams"]) 
		{
			if (validResults["Streams"][0]) 
			{
				for (var i = 0; i < validResults["Streams"].length; i++) 
				{
					if (validResults["Streams"][i]["name"] == "SIF")
					{
						requiresResult = true;
						this.PayloadsToCheck.push(pay);
						
						if (this.wizardControl.session.GetDriverPayload() && this.wizardControl.session.GetDriverPayload().AdobeCode && (pay == this.wizardControl.session.GetDriverPayload().AdobeCode))
						{
							gSession.LogInfo("Driver payload includes a serial check: defined \"serialNumber\" property required to install/repair");
							gSession.LogInfo("No trial option available for this install");
							this.mustProvideSerial = true;
						}
					}
				}
			}	
		}
	}
	
	return (true == requiresResult); 
}


personalization_wp.prototype.onSwitchTo = function()
{
	return this.isActive();
}


personalization_wp.prototype.onResourcesLoaded = function()
{
	var thisCB = this;
	for (var i = 0; i < this.arrSNElements.length; i++) 
	{
		this.getElementById(this.arrSNElements[i]).onkeyup = function() { thisCB.autoTab(this, 4, event); };
		this.getElementById(this.arrSNElements[i]).onkeydown = function() { thisCB.numericWatch(this, 4, event); };
		this.getElementById(this.arrSNElements[i]).onchange = function() { thisCB.onFieldChange(); };
		this.getElementById(this.arrSNElements[i]).onblur = function() { thisCB.onFieldChange(); };
	}
	
	this.getElementById(this.arrSNElements[0]).onbeforepaste = function() { thisCB.serialBeforePaste(); };
	this.getElementById(this.arrSNElements[0]).onpaste = function() { thisCB.distributePaste(this, 4); }; 
	
	if (this.getElementById("serialRadio"))
		this.getElementById("serialRadio").onclick = function() { thisCB.handleSerialRadio(); };
	if (this.getElementById("trialRadio"))
		this.getElementById("trialRadio").onclick = function() { thisCB.handleTrialRadio(); }; 
	
	this.serialIcon = this.getElementById("serialIcon");
}


personalization_wp.prototype.handleSerialRadio = function()
{
	var doClearWhenDone = false;
	
	if (this.radioState == "trial")
		doClearWhenDone = true;
	
	this.radioState = "serial";
	this.wizardControl.nextButton.button.disabled = true;
	
	for (var i=0; i < this.arrSNElements.length; i++)
		this.getElementById(this.arrSNElements[i]).disabled = false;
	
	// Check number and set serial output
	this.updateSerialCheckStatus();
	
	if(this.radioState == "serial" && this.serialNumber.length == 24)
		this.wizardControl.nextButton.button.disabled = false;
	
	if (doClearWhenDone)
	{
		this.errorbox.Clear();
		this.errorbox.ShowHide();
	}
}


personalization_wp.prototype.handleTrialRadio = function()
{
	this.radioState = "trial";
	this.wizardControl.nextButton.button.disabled = false;
	
	// Clear serial output
	this.serialNumberOutput = "";
	this.serialNumber = "";	
	this.serialNumberValid = "0";
	this.serialIcon.style.display = 'none';
	this.getElementById("pers_EPIC_SERIAL").value = "";
	
	if (this.wizardControl.session.properties["pers_EPIC_SERIAL"])
		delete this.wizardControl.session.properties["pers_EPIC_SERIAL"];
	
	for (var i=0; i < this.arrSNElements.length; i++)
		this.getElementById(this.arrSNElements[i]).disabled = true;	
	
	this.errorbox.Clear();
	this.errorbox.ShowHide();
}


personalization_wp.prototype.onShow = function()
{	
	this.setWindowTitle();	
	this.wizardControl.session.UISetCloseBoxEnabled(1);	
	
	// Decide where to set the focus
	var sRadio = this.getElementById("serialRadio");
	var tRadio = this.getElementById("trialRadio");
	if (this.serialNumberValid == "1" || this.radioState == "trial" || this.mustProvideSerial)
	{
		this.wizardControl.nextButton.button.focus();
		this.wizardControl.nextButton.SetFocus(this.wizardControl.nextButton.button);
	}
	else if (sRadio)
	{
		if (this.radioState == "serial")
			sRadio.focus();
		else if (tRadio)
			tRadio.focus();
	} 
	
	if (sRadio && this.radioState == "serial")
		sRadio.checked = true;
	else if (tRadio && this.radioState == "trial")
		tRadio.checked = true;
	
	// Place correct icon next to the SN fields
	if (this.serialNumberValid == "1" && this.radioState != "trial")
	{
		this.serialIcon.style.display = 'inline';
		this.serialIcon.src = './media/img/bulletCheck.png';
	}
	else if (this.serialNumberValid != "1" && this.radioState != "trial" && this.serialNumber.length == 24)
	{
		this.serialIcon.style.display = 'inline';
		this.serialIcon.src = './media/img/bulletCritical.png';		
	}
	else
	{
		this.serialIcon.style.display = 'none';
	}
	
	// Remove unwanted screen text
	if(this.mustProvideSerial)
	{
		var trialRadioDiv = this.getElementById("trialRadioDiv");
		if (trialRadioDiv)
		{
			if (trialRadioDiv.firstChild) trialRadioDiv.removeChild(trialRadioDiv.firstChild);
			if (trialRadioDiv.firstChild) trialRadioDiv.removeChild(trialRadioDiv.firstChild);
		}
		
		var trialTextDiv = this.getElementById("trialTextDiv");
		if (trialTextDiv && trialTextDiv.firstChild)
			trialTextDiv.removeChild(trialTextDiv.firstChild);

		var serialRadioDiv = this.getElementById("serialRadioDiv");
		if (serialRadioDiv)
		{
			if (serialRadioDiv.firstChild) serialRadioDiv.removeChild(serialRadioDiv.firstChild);
			if (serialRadioDiv.firstChild) serialRadioDiv.removeChild(serialRadioDiv.firstChild);
		}
		
		var serialHeaderDiv = this.getElementById("serialHeader");
		if (serialHeaderDiv)
			if (serialHeaderDiv.firstChild) serialHeaderDiv.removeChild(serialHeaderDiv.firstChild);
	}	
	else
	{
		var serialHeaderAltDiv = this.getElementById("serialHeaderAlt");
		if (serialHeaderAltDiv && serialHeaderAltDiv.firstChild)
			serialHeaderAltDiv.removeChild(serialHeaderAltDiv.firstChild);	
	}

	// Deal with enable state on the Next button
	if (this.serialNumber.length != 24 && this.radioState != "trial")
		this.wizardControl.nextButton.button.disabled = true;
	else
		this.wizardControl.nextButton.button.disabled = false;

	this.wizardControl.nextButton.SetAccessKey("n");
	this.wizardControl.backButton.SetAccessKey("b");
	
	this.wizardControl.nextButton.SetTabIndex(101);
	this.wizardControl.quitButton.SetTabIndex(103);	

	return true;
}

personalization_wp.prototype.updateSerialNumber = function()
{
	this.serialNumber = "";
	
	for (var i=0; i < this.arrSNElements.length; i++)
		this.serialNumber += this.getElementById(this.arrSNElements[i]).value;
}

personalization_wp.prototype.updateSerialCheckStatus = function()
{
	this.updateSerialNumber();
	this.serialNumberValid = "0";

	if (this.serialNumber.length == 24)
	{	
		var serialResults = null;
		
		if (this.PayloadsToCheck && this.PayloadsToCheck[0])
		{
			for (var i = 0; i < this.PayloadsToCheck.length; i++)
			{
				serialResults = null;
				serialResults = this.wizardControl.session.IsValidSerialNumberForAdobeCode(this.PayloadsToCheck[i], this.serialNumber);

				if (!(serialResults && serialResults["isValid"] && serialResults["isValid"] == "1"))
					break;
			}			
		}

		if (serialResults) {
			if (null == serialResults["_error"] || "0" == serialResults["_error"]) {
				this.serialNumberOutput = serialResults["serialOutput"];
				this.serialNumberValid = serialResults["isValid"];
			}
		}
		
		this.wizardControl.nextButton.button.disabled = false;
	} 
	else
	{
		this.serialIcon.style.display = 'none';
		this.wizardControl.nextButton.button.disabled = true;
	}
	
	var selected_pe = this.getElementById("pers_EPIC_SERIAL");
	
	if (("1" == this.serialNumberValid) && (this.radioState == "serial")) {
		selected_pe.value = this.serialNumberOutput;
		this.wizardControl.session.properties["pers_EPIC_SERIAL"] = this.serialNumberOutput;
		
		this.serialIcon.style.display = 'inline';
		this.serialIcon.src = './media/img/bulletCheck.png';
		this.errorbox.Clear();
		this.errorbox.ShowHide();
	}
	else if ((this.mustProvideSerial || (this.serialNumber.length > 0)) && (this.radioState == "serial"))
	{
		if (this.serialNumber.length == 24)
		{
			this.serialIcon.style.display = 'inline';
			this.serialIcon.src = './media/img/bulletCritical.png';
		}
		else
		{
			this.serialIcon.style.display = 'none';
		}
		selected_pe.value = "";
		if (this.wizardControl.session.properties["pers_EPIC_SERIAL"])
			delete this.wizardControl.session.properties["pers_EPIC_SERIAL"];
		this.errorbox.Clear();
		this.errorbox.AddError("critical", this.localization.GetString("locPerError", "You have entered an invalid serial number.  Please re-enter a valid serial number and try again."));
	} 
	else
	{
		selected_pe.value = "";
		if (this.wizardControl.session.properties["pers_EPIC_SERIAL"])
			delete this.wizardControl.session.properties["pers_EPIC_SERIAL"];
	}
	
	// Serialiation is a dynamic intrinsic constraint so re-compute those now.
	this.wizardControl.session.PayloadPolicyRefresh();
}

personalization_wp.prototype.onNext = function()
{		
	this.updateSerialCheckStatus();
	
	return (("1" == this.serialNumberValid) || (this.radioState == "trial"));
}


personalization_wp.prototype.onFieldChange = function()
{
	this.updateSerialNumber();
	
	if (this.serialNumber.length >= 24)
	{
		this.updateSerialCheckStatus();
	}
	else
	{
		this.serialIcon.style.display = 'none';
		this.wizardControl.nextButton.button.disabled = true;
		this.errorbox.Clear();
		this.errorbox.ShowHide();
	}
}


/**
 Change the serial number field focus when a field is full
*/
personalization_wp.prototype.autoTab = function (input, len, e) 
{	
	var keyCode = e.keyCode; 
	var strKey = String.fromCharCode(e.keyCode);
	
	var reKeyboardChars = /[\x00\x03\x08\x09\x10\x0D\x16\x18\x1A\x2E\x25\x26\x27\x28]/;

	this.onFieldChange();

	if(input.value.length >= len && !reKeyboardChars.test(strKey)) 
	{
		input.value = input.value.slice(0, len);

		if((this.getIndex(input) != this.getIndex(document.getElementById("personalization_SN6")))) 
		{
			input.form[(this.getIndex(input)+1) % input.form.length].focus();
			input.form[(this.getIndex(input)+1) % input.form.length].select();
		} 
		else if (this.serialNumberValid == "1")
		{
			this.serialIcon.style.display = 'inline';
			this.serialIcon.src = './media/img/bulletCheck.png';
			this.wizardControl.nextButton.button.disabled = false;
			this.wizardControl.nextButton.button.focus();
			this.wizardControl.nextButton.SetFocus(this.wizardControl.nextButton.button);
		} 
	} 	

	return true;
} 

/**
 Get the index of the current form item
*/
personalization_wp.prototype.getIndex = function (input) {
	
	var index = -1, i = 0, found = false;

	while (i < input.form.length && index == -1)
	{
		if (input.form[i] == input)
			index = i;
		else 
			i++;
	}
	return index;
}


/**
 Block undesired serial number characters while allowing for keyboard-based paste
*/
personalization_wp.prototype.numericWatch = function (input, len, e) 
{
	var blnValidChar = true;

	var reValidChars = /\d/;
	var reKeyboardChars = /[\x00\x03\x08\x09\x0D\x16\x18\x1A\x2E]/;
	var reClipBoardChars = /[\x56\x58\x43\x41]/;
	var reControlChars = /[\x63\x78\x76\x7A]/;
	var reArrowKeys = /[\x25\x26\x27\x28]/;
	var reNumericKeypad = /[\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69]/;
	var strKey, iKeyCode;
 
	iKeyCode = e.keyCode;
	strKey = String.fromCharCode(e.keyCode);
	
	if (/*(e.shiftKey && !e.keyCode == 0) || */
		(!reValidChars.test(strKey) && 
		!reKeyboardChars.test(strKey) &&
		!(e.ctrlKey && reClipBoardChars.test(strKey)) && 
		!(e.metaKey && reClipBoardChars.test(strKey)) && 
		!reControlChars.test(strKey) && 
		!reArrowKeys.test(strKey) && 
		!reNumericKeypad.test(strKey)))
	{
		blnValidChar = false;
	}

	if(!blnValidChar) 
	{
		e.returnValue = false;	
		input.form.focus();		
		return false;
	} 
	else 
	{		
		if (e.metaKey && (e.keyCode == 86)) 
		{
			this.distributePaste(input, len);
		} 
		else if (e.ctrlKey && (e.keyCode == 86)) 
		{
		    this.distributePaste(input, len);
		}		
	
		return true;
	} 
}

/**
 Paste the current text in the clipboard across the serial number fields, removing unwanted dashes
*/
personalization_wp.prototype.distributePaste = function (input, len) 
{
	var storeChopped = "";
	var storeFull = "";
	
	if (input == document.getElementById("personalization_SN1")) {

		var requiresResult = "0";
		var count = 0;
		var loopCount = 0;

		var pasteObject = this.wizardControl.session.UIGetPasteboardValue();
		
		if (null == pasteObject["_error"] || "0" == pasteObject["_error"]) {
			storeFull = pasteObject["value"];
		}		
		
		if (storeFull.length > 0) {
			for(var i=0; i<storeFull.length; i++) {
				if (storeFull.charAt(i) != ' ' && storeFull.charAt(i) != '-') {
					storeChopped += storeFull.charAt(i);
					count++;
				}
			}	
		
			if (storeFull.length > 24) {
				storeFull = storeFull.slice(0, 23);
			}
		
			for(var position = 0; position < storeFull.length; position = position + len) {
				if (position > storeFull.length) {
					position = storeFull.length - 1;
				}
			
				document.getElementById(this.arrSNElements[loopCount]).value = storeChopped.slice(position, position+len);	
				loopCount++;
			}
		
			if (position >= 23) {
				this.wizardControl.nextButton.button.disabled = false;
				this.wizardControl.nextButton.button.focus();
				this.wizardControl.nextButton.SetFocus(this.wizardControl.nextButton.button);
			}	
		}		
	} 
	
	this.onFieldChange();

	return false;
} 


/**
 Callback to help Windows deal with distributed paste
*/
personalization_wp.prototype.serialBeforePaste = function() 
{
	return true;
} 


/***********************************************************************
3. Last, and very important, return the name of the class.
*/
"personalization_wp";
