/*!
***********************************************************************
@file WizardPayload.js

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

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

function WizardPayload(inWizardPayloadSelect, inInstallerPayload)
{
	this.wizardSelect = inWizardPayloadSelect;
	this.session = this.wizardSelect.session;
	this.payload = inInstallerPayload;

	// A mode for deciding what checked and unchecked means
	this.mode = this.wizardSelect.mode;

	// A place to put errors
	this.errorbox = this.wizardSelect.wizardError;

	// Get the scoop on the payload
	this.checkbox = null;

	// Size may change depending on selection.
	this.OperationSize = new AdobeProperty(this.payload.OperationSize(true).totalBytes);

	// Fabricate the UI
	this.DOM = this._CreateDOM();
	this.UIMessage = "";
	this.hasUIChild = false;
	this.payload.wp = this;
}

WizardPayload.prototype._CreateDOM = function()
{
	var thisCB = this;
	// Name
	this.nameSpanElement = document.createElement("span");
	this.nameSpanElement.className = "productnametext";
	var nameText = this.payload.GetUIProductName(this.session);
	this.nameSpanElement.innerHTML = nameText;

	// Annotation
	this.disclosureTriangleContent = document.createElement("span");
	this.disclosureTriangleContent.className = "disclosureTriangleContent";

	// Size
	this.sizeSpanElement = document.createElement("span");
	this.sizeSpanElement.className = "componentsizetext";
	this.OperationSize.Bind(this.sizeSpanElement, bytesToText);

	
	// Final Container assembly
	// Tabbing this section to visualize the nesting of the table elements
	
	var table0 = document.createElement("table");
	table0.className = "t0";

        var t0_tbody = document.createElement("tbody");
        t0_tbody.className = "t0_tbody";
        table0.appendChild(t0_tbody);
        
            var t0_tr1 = document.createElement("tr");
            t0_tr1.className = "t0_tr1";
            t0_tbody.appendChild(t0_tr1);
            
                var t0_tr1_td1 = document.createElement("td");
                t0_tr1_td1.className = "t0_tr1_td1";
                t0_tr1.appendChild(t0_tr1_td1);
            	
                    var table1 = document.createElement("table");
	                table1.className = "t1";
                    t0_tr1_td1.appendChild(table1);
                    
                        var table1_tbody = document.createElement("tbody");
                        table1_tbody.className = "table1_tbody";
                        table1.appendChild(table1_tbody);
                        
                            var t1_tr1 = document.createElement("tr");
                            t1_tr1.className = "t1_tr1";
                            table1_tbody.appendChild(t1_tr1);
                            
                                var t1_tr1_td1 = document.createElement("td");
                            	t1_tr1_td1.className = "td_payload_checkBox";
                                t1_tr1.appendChild(t1_tr1_td1);
                                
									// The check box
	                                this.checkbox = new WizardCheckBox1("", "productCheckBox", t1_tr1_td1, true, function(){thisCB.SetCheckBox();});

                                var t1_tr1_td2 = document.createElement("td");
                            	t1_tr1_td2.className = "td_payload_icon";
                                t1_tr1.appendChild(t1_tr1_td2);
                                
	                                // The payload icon
	                                var productIconPath = this.payload.GetProductIcon(this.session);
	                                if (productIconPath == null)
	                                    productIconPath = kImgDefaultProductIcon;
                                    var productIconImg = new WizardImage1(productIconPath, "", "payloadIcon", t1_tr1_td2);
	                                //t1_tr1_td2.appendChild(productIconImg);

                                var t1_tr1_td3 = document.createElement("td");
                            	t1_tr1_td3.className = "td_payload_disclosure";
                                t1_tr1.appendChild(t1_tr1_td3);
                                
	                                // The disclosure triangle
	                                if(gSession.languagertl)
	                                {
                                        this.disclosureTriangleImg = new WizardImage1(kImgSupportingCompClosedTriangleRTL, "", "payloadDisclosureTriangle", t1_tr1_td3, function() { thisCB.handleDisclosureTriangleToggling(thisCB.disclosureTriangleImg); });
                                    }
                                    else
                                    {
                                        this.disclosureTriangleImg = new WizardImage1(kImgSupportingCompClosedTriangle, "", "payloadDisclosureTriangle", t1_tr1_td3, function() { thisCB.handleDisclosureTriangleToggling(thisCB.disclosureTriangleImg); });
                                    }
                                    
                var t0_tr1_td2 = document.createElement("td");
                t0_tr1_td2.className = "t0_tr1_td2";
                t0_tr1.appendChild(t0_tr1_td2);
            	
                    var table2 = document.createElement("table");
	                table2.className = "t2";
                    t0_tr1_td2.appendChild(table2);
                    
                        var table2_tbody = document.createElement("tbody");
                        table2_tbody.className = "table2_tbody";
                        table2.appendChild(table2_tbody);
                        
                            var t2_tr1 = document.createElement("tr");
                            t2_tr1.className = "t2_tr1";
                            table2_tbody.appendChild(t2_tr1);
                            
                                var t2_tr1_td1 = document.createElement("td");
                                t2_tr1_td1.className = "t2_tr1_td1";
                                t2_tr1.appendChild(t2_tr1_td1);
                                
                                    
	                                // The product name and payloadNote and UIMessage
	                                t2_tr1_td1.appendChild(this.nameSpanElement);

                                var t2_tr1_td2 = document.createElement("td");
                                t2_tr1_td2.className = "t2_tr1_td2";
                                t2_tr1.appendChild(t2_tr1_td2);
                                
	                                // The payload size
	                                t2_tr1_td2.appendChild(this.sizeSpanElement);

            var t0_tr2 = document.createElement("tr");
            t0_tr2.className = "disclosureContent";
            t0_tbody.appendChild(t0_tr2);

                var t0_tr2_td1 = document.createElement("td");
                t0_tr2_td1.className = "t0_tr2_td1";
                t0_tr2_td1.innerHTML = "&nbsp;"
                t0_tr2.appendChild(t0_tr2_td1);
                
                var t0_tr2_td2 = document.createElement("td");
                t0_tr2_td2.className = "t0_tr2_td2";
                t0_tr2_td2.innerHTML = "&nbsp;"
                t0_tr2.appendChild(t0_tr2_td2);
            
	            t0_tr2.style.display = "none";
            
            var t0_tr3 = document.createElement("tr");
            t0_tr3.className = "productdivider";
            t0_tbody.appendChild(t0_tr3);

                var t0_tr3_td1 = document.createElement("td");
                t0_tr3_td1.className = "productdivider";
                t0_tr3_td1.innerHTML = "&nbsp;"
                t0_tr3.appendChild(t0_tr3_td1);
                
                var t0_tr3_td2 = document.createElement("td");
                t0_tr3_td2.className = "productdivider";
                t0_tr3_td2.innerHTML = "&nbsp;"
                t0_tr3.appendChild(t0_tr3_td2);
            
                    var hr_divider = document.createElement("span");
                    hr_divider.className = "hrlight275";
                    t0_tr3_td2.appendChild(hr_divider);
                    //TODO: Move this code back up
                    var listDivider = new WizardImage1(kImgPanelDivider, "", "hr_divider", hr_divider);
        
	return table0;
}

WizardPayload.prototype.handleDisclosureTriangleToggling = function(triangle)
{
    var disclosureTriangleContent = this.DOM.rows[1];

	if (disclosureTriangleContent.style.display != "none")
	{
	    disclosureTriangleContent.style.display = "none";
	    if(gSession.languagertl)
	    {
	    	triangle.SetSrc(kImgSupportingCompClosedTriangleRTL);
	    }
	    else
 	    {
		triangle.SetSrc(kImgSupportingCompClosedTriangle);
	    }
	}
	else
	{
	    var systemInfo = this.session.systemInfo;
	    var currentPlatform = systemInfo.Macintosh ? "Mac" : "Win";
	    
	    if(currentPlatform=="Mac")
	    {
	        disclosureTriangleContent.style.display = "table-row";
	    }
	    else
	    {
	        disclosureTriangleContent.style.display = "block";
	    }
	    triangle.SetSrc(kImgSupportingCompOpenTriangle);
	}
	if (this.session.systemInfo.Macintosh) {
		this.session.UIShowWindow(1); // On Safari 3.1.1 elements are not drawn, this will force frameview to be redrawn Bug 1782889, 1800816
	}
}


WizardPayload.prototype.SetCheckBox = function()
{
	this.checkbox.toggleC();
	this.actionMap = this.payload.GetUISelectionAction(this.session, this.checkbox.GetChecked());
	if (this.payload.policyNode && (this.actionMap.checkedState == this.checkbox.GetChecked()))
	{
		this.payload.policyNode.SetAffinity();
	}
	this.wizardSelect.OnChecked(this, this.wizardSelect.Refresh());
}


/**
Make the UI view match the InstallerPayload model.
*/
WizardPayload.prototype.Refresh = function()
{
	this.actionMap = this.payload.GetUISelectionAction(this.session);
	if (this.actionMap.visible)
	{
		if (this.actionMap.selectable)
		{
			this.checkbox.Enable();
			this.DOM.className = "t0";
		}
		else
		{
			this.checkbox.Disable();
			this.DOM.className = "t0_disabled";
		    if((this.payload._payloadType == kTopLevelPayload && this.payload.policyNode.installedOrUpdated && !(this.payload.policyNode.installedForThisSession)) || this.payload.policyNode.installedAsDriverElseWhere || (this.payload.policyNode.constraintClass == kPolicyClass.Intrinsic && this.payload.policyNode.constraintCode == kIntrinsicPolicyCode.Conflict))
			{
				this.nameSpanElement.className = "productnametextdisabled";
				this.sizeSpanElement.innerText="---";
			}
		}
	}
	else
	{
		this.checkbox.Disable();
		this.DOM.className = "t0_hidden";
	}

	this.checkbox.SetChecked(this.actionMap.checkedState);
	if (this.errorbox)
	{
		if (this.checkbox.GetChecked() && !this.checkbox.IsDisabled())
		{
			this.errorbox.ClearError("atleastone");
		}
	}
	
	// In PP mode, we should not show the payload dependencies note
	if(!(gSession.IsSuiteMode()))
	{
		if(!(this.payload.IsDriverForSession(gSession)))
	    {
	        if(!(this.payload.policyNode.alreadyInstalledPayloadNote && this.payload.policyNode.alreadyInstalledPayloadNote!= ""))
	        {
	            this.actionMap.payloadNote = "";
	        }
	    }
	}
	    

	// Set the payload annotation
	if (this.actionMap.payloadNote && this.actionMap.payloadNote != "")
	{
	    this.ClearPayloadNoteDOM();
	    this.AddPayloadNoteToDOM(this.actionMap.payloadNote);
	}
	
	// Hide the triangle if there is no payload note and no UIChild
	if ((!(this.actionMap.payloadNote && this.actionMap.payloadNote != "")) && (this.hasUIChild == false))
	{
		this.disclosureTriangleImg.Hide();
	}
	
	// Register any errors/warnings from the InstallerPayload
	if (this.actionMap.visible && this.errorbox && this.actionMap.payloadError)
	{
		var errors = null;
		if (this.actionMap.payloadError.id && this.actionMap.payloadError.text)
		{
			errors = new Object();
			errors[this.actionMap.payloadError.id] = this.actionMap.payloadError;
		}
		else
		{
			errors = this.actionMap.payloadError;
		}
		for (var errorId in errors)
		{
			var errorObj = errors[errorId];
			this.errorbox.AddError(errorId, errorObj.className,  errorObj.text);
		}
	}

	return this.actionMap.selectable ? 1 : 0;
}



/**
Interface to add a payload note for a given Wizard Payload.
*/
WizardPayload.prototype.AddPayloadNoteToDOM = function(payloadNote)
{
	if(this.DOM.rows && this.DOM.rows[1])
	{
		var pn = null;
	    var payloadNoteContentParent = this.DOM.rows[1].cells[1];
		var allChildren = payloadNoteContentParent.children;
		for (var i = 0; i < allChildren.length; i++)
		{
			if(allChildren[i] && (allChildren[i].className == "payloadNote"))
			{
				pn = allChildren[i];
				break;
			}
		}
		if(!pn)
		{
			pn = document.createElement("span");
		}
		pn.className = "payloadNote";
		pn.innerHTML = payloadNote;

		if(payloadNoteContentParent)
		{
			payloadNoteContentParent.insertBefore(pn,payloadNoteContentParent.firstChild);
		}
	}
}

/**
Interface to clear all payload notes for a given Wizard Payload.
*/
WizardPayload.prototype.ClearPayloadNoteDOM = function()
{
	if(this.DOM.rows && this.DOM.rows[1])
	{
    var payloadNoteContentParent = this.DOM.rows[1].cells[1];
	if (payloadNoteContentParent)
	{
			var allChildren = payloadNoteContentParent.children;
			for (var i = 0; i < allChildren.length; i++)
			{
				if(allChildren[i] && (allChildren[i].className == "payloadNote"))
				{
					allChildren[i].innerHTML="";
				}
			}

		   // payloadNoteContentParent.innerHTML = "";
		}	
	}
}

/**
Interface to add a sub-payload (parent-child / 64 bit) for a given Wizard Payload.
*/
WizardPayload.prototype.AddSubPayloadDOM = function(inWP)
{
	var thisCB = this;
	if(this.DOM.rows && this.DOM.rows[1])
	{
		var subPayloadParent = this.DOM.rows[1].cells[1];
		if(subPayloadParent)
		{
			var nameSpanElement = document.createElement("span");
			nameSpanElement.className = "smalltext";
			nameSpanElement.innerHTML = inWP.nameSpanElement.innerHTML;

			var sizeSpanElement = document.createElement("span");
			sizeSpanElement.className = "componentsizetextsmall";
			sizeSpanElement.innerHTML = inWP.sizeSpanElement.innerHTML;
			inWP.OperationSize.Bind(sizeSpanElement, bytesToText);

			var subtable0 = document.createElement("table");
			subtable0.className = "subPayload_t0";
			//Setting the class does not appear to work for the table
			subtable0.style.width = "260px";

				var t0_tbody = document.createElement("tbody");
				t0_tbody.className = "t0_tbody_subPayload";
				subtable0.appendChild(t0_tbody);
				
				    var t0_tr1 = document.createElement("tr");
				    t0_tr1.className = "t0_tr1_subPayload";
				    t0_tbody.appendChild(t0_tr1);
				    
				        var t0_tr1_td1 = document.createElement("td");
				        t0_tr1_td1.className = "t0_tr1_td1_subPayload";
				        t0_tr1.appendChild(t0_tr1_td1);
	                    inWP.checkbox = new WizardCheckBox1("", "productCheckBox", t0_tr1_td1, inWP.checkbox.GetChecked(), function(){inWP.SetCheckBox();});
				    	
				        var t0_tr1_td2 = document.createElement("td");
				        t0_tr1_td2.className = "t0_tr1_td2_subPayload";
				        t0_tr1_td2.appendChild(nameSpanElement);
				        t0_tr1.appendChild(t0_tr1_td2);
				    	
				        var t0_tr1_td3 = document.createElement("td");
				        t0_tr1_td3.className = "t0_tr1_td3_subPayload";
				        t0_tr1_td3.appendChild(sizeSpanElement);
				        t0_tr1.appendChild(t0_tr1_td3);

			this.payload.policyNode.payloadNote="";
			subPayloadParent.appendChild(subtable0);
			this.handleDisclosureTriangleToggling(this.disclosureTriangleImg);
			this.hasUIChild = true;
			return subtable0;
		}
	}
}

/**
Return the DOM for the user interface to show/select this payload.
*/
WizardPayload.prototype.GetUIDOM = function()
{
	return this.DOM;
}

WizardPayloadSelect.prototype.GetPayloadsByFilter = function(level_branding, installed_type)
{
	var systemInfo = this.session.systemInfo;
	var currentPlatform = systemInfo.Macintosh ? "Mac" : "Win";
	
	var payloadsFiltered = new Array();
	var filterFunction1;
	var filterFunction2;
	var filterFunction3;
	if(level_branding=="top")//top => branded automatically, there are no top unbranded level components for now
	{
		filterFunction1 = function (aPayload)
		{
			var payloadSatisfies = aPayload.GetSatisfiedArray();
			if ((payloadSatisfies.length == null) || (payloadSatisfies.length <= 0))
			{
			    aPayload._payloadType = kTopLevelPayload;
				return true;
			}
			return false;
		};
	}
	else if(level_branding=="brandedshared" || level_branding=="sharedbranded")
	{
		filterFunction1 = function (aPayload)
		{
			var payloadSatisfies = aPayload.GetSatisfiedArray();
			if (payloadSatisfies.length && (payloadSatisfies.length > 0) && (aPayload.GetProductIcon() != null))
			{
				aPayload._payloadType = kBrandedSharedCompPayload;
				return true;
			}
			return false;
		};
	}
	else if(level_branding=="unbrandedshared" || level_branding=="sharedunbranded")
	{
		filterFunction1 = function (aPayload)
		{
			var payloadSatisfies = aPayload.GetSatisfiedArray();
			if (payloadSatisfies.length && payloadSatisfies.length > 0 && (aPayload.GetProductIcon() == null))
			{
				aPayload._payloadType = kUnbrandedSharedCompPayload;
				return true;
			}
			return false;
		};
	}
	else if(level_branding=="wontmatter" || level_branding=="any" || level_branding=="all")
	{
		filterFunction1 = function (aPayload)
		{
			return true;
		};
	}
	else
	{
		filterFunction1 = function (aPayload)
		{
			alert("unknown filter for level_branding:: "+level_branding+" has been requested! write a new filter function to filter payloads all properly!");
			return true;
		};
	}
	
	//formulate filter function for second parameter
	if(installed_type=="installed")
	{
		filterFunction2 = function (aPayload)
		{
			var rvalue = (aPayload.GetInstallStateForCollection(aPayload.policyNode.session.sessionCollection) == kCapsInstallStateInstalled);
			if (aPayload.wp.wizardSelect.mode != kWorkflowModeUninstall && (currentPlatform=="Mac") && aPayload._sessionData.Satisfies && (aPayload._sessionData.Satisfies.family != "NonAdobePayload"))
			{
				var actuallyExists = aPayload.policyNode.session.IfRIBSPayloadInstallationActuallyExists(aPayload._adobeCode);
				var payloadExists = (actuallyExists != null) && (actuallyExists.isSuccessful == 1) && (actuallyExists["installDir"] != null);
				var driver = aPayload.policyNode.session.GetDriverPayload();
				var isDriverAdobeCode = driver && (driver.AdobeCode == aPayload._adobeCode);

				// Test if any payload other than driver has moved
				if (payloadExists && !isDriverAdobeCode && !_equalPaths(actuallyExists["installDir"] , gSession.properties["INSTALLDIR"])) 
				{
					gSession.IsAnySubPayloadMoved = true;
				}
				rvalue = rvalue && payloadExists;
			}
			return rvalue;
		};
	}
	else if(installed_type=="notinstalled")
	{
		filterFunction2 = function (aPayload)
		{
			var rvalue = (aPayload.GetInstallStateForCollection(aPayload.policyNode.session.sessionCollection) != kCapsInstallStateInstalled);
			if(currentPlatform=="Mac") {
				var actuallyExists = null;
				// If it not third party payload then check whether it is actually installed.
				if (!aPayload.GetSessionData().ThirdPartyCapabilities)
					actuallyExists = aPayload.policyNode.session.IfRIBSPayloadInstallationActuallyExists(aPayload._adobeCode);
				rvalue = rvalue || ((actuallyExists != null) && (actuallyExists.isSuccessful != 1));
			}

			// Override if the payload has been installed or upgraded in another session
			if(aPayload.wp.wizardSelect.mode == kWorkflowModeMaintenance)
			{
				if((aPayload._payloadType == kTopLevelPayload && aPayload.policyNode.installedOrUpdated && !(aPayload.policyNode.installedForThisSession)) || aPayload.policyNode.installedAsDriverElseWhere)
				rvalue = false;
			}
			return rvalue;
		};
	}
	else if(installed_type=="wontmatter" || installed_type=="any" || installed_type=="all")
	{
		filterFunction2 = function (aPayload)
		{
			return true;
		};
	}
	else
	{
		filterFunction2 = function (aPayload)
		{
			alert("unknown filter for installed_type:: "+installed_type+" has been requested! write a new filter function to filter payloads all properly!");
			return true;
		};
	}
	
	filterFunction3 = function(aPayload)
	{
	    if(aPayload.isExtensionPayload())
	    {
	        aPayload._payloadType = kPayloadTypeExtension;
			return false;	
	    }
		return true;
	}
	
	var driver = this.session.GetDriverPayload();
	for (var p in this.payloads)
	{
	    var aPayload = this.payloads[p];
		var wp = aPayload.wp;
		if (wp)
		{		    
		    if (filterFunction1(aPayload) && filterFunction2(aPayload) && filterFunction3(aPayload))
		    {
		        payloadsFiltered.push(wp);
		    }
		}
	}
	return payloadsFiltered;
}

WizardPayloadSelect.prototype.CreateAllWizardPayloads = function()
{
	var driver = this.session.GetDriverPayload();
	if(!this.session.WizardPaylodsCreated)
	{
		for (var p in this.payloads)
		{
			var wp = new WizardPayload(this, this.payloads[p]);
			if (wp)
			{
				this.wizardPayloads.push(wp);
			}
		}
	}
	this.session.WizardPaylodsCreated=true;
}

WizardPayloadSelect.prototype.PluginSecondaryPayloads = function()
{
	for (var p in this.payloads)
	{
        if(this.payloads[p].hasUIParent())
        {
            var uiParentPayload = this.payloads[p].uiParentPayload;
            if(uiParentPayload)
            {
				if(this.payloads[p].GetInstallStateForCollection(this.payloads[p].policyNode.session.sessionCollection) == uiParentPayload.GetInstallStateForCollection(uiParentPayload.policyNode.session.sessionCollection))
				{
					this.session.LogDebug("WizardPayloadSelect.PluginSecondaryPayloads: " + this.payloads[p].LogID() + "has been added to its UI parent payload " + uiParentPayload.LogID());
					var newDOM = uiParentPayload.wp.AddSubPayloadDOM(this.payloads[p].wp);
					this.payloads[p].wp.DOM = null;
					this.payloads[p].wp.DOM = newDOM;
				}
				else
				{
					this.session.LogDebug("WizardPayloadSelect.PluginSecondaryPayloads: " + this.payloads[p].LogID() + "has not been added to its UI parent payload " + uiParentPayload.LogID() + " since both installer actions are not the same");
				}
            }
            else
            {
			    this.session.LogDebug("WizardPayloadSelect.PluginSecondaryPayloads: " + this.payloads[p].LogID() + "has UI parent payload, but it does not exist");
            }
        }

	}
}

function WizardPayloadSelect(inSession, inMode, inListElement, inWizardError, inOptContainer)
{
	// Stash our input.
	this.session = inSession;
	this.mode = inMode;
	this.listElement = inListElement;
	this.wizardError = inWizardError;
	this.container = inOptContainer;
	this.session.WizardPaylodsCreated = false;

	// Get the payload list. This is a set of InstallerPayloads.
	this.payloads = PayloadUISort(inSession.sessionPayloads, inSession);
	
	// Keep track of how much space we need and is available.
	this.totalSize = new AdobeProperty();
	this.availableSpace = new AdobeProperty();
	
	// Keep track of whether or not all selectable options are selected.
	this.allSelected = new AdobeProperty(false);
	
	// Assemble the WizardPayload objects. This consists of all the payloads in the session. It is further categorized into top level, branded , etc
	this.wizardPayloads = new Array();

	// Setup elemnt set for storing checkboxes and disclosure triangle
	this.wamElementSet = new Array();
	
	this.CreateAllWizardPayloads();//this.wizardPayloads is populated during this function

	this.PluginSecondaryPayloads();
	
	if(this.mode == kWorkflowModeInstall)
    {
	    /** Listing of all top level payloads **/
	    this.topLevelPayloads  = this.GetPayloadsByFilter("top","wontmatter");

	    /** Listing of all branded shared component payloads **/
	    this.brandedSharedCompPayloads  = this.GetPayloadsByFilter("brandedshared","wontmatter");

	    /** Listing of all unbranded shared component payloads **/
	    this.unbrandedSharedCompPayloads  = this.GetPayloadsByFilter("unbrandedshared","wontmatter");

		var topCount =this.topLevelPayloads.length;

        for(var adobeCode in this.session.sessionPayloads)
        {
	        //Decrement the top count for each protected content
            var payload = this.session.sessionPayloads[adobeCode];
            if(payload.policyNode && payload.policyNode.IsProtected(adobeCode))
            {
                --topCount;
                continue;
            }

			//Decrement the top count for each third party payload
			var payloadSessionData = payload.GetSessionData();
			if (payload._payloadType == kTopLevelPayload && payloadSessionData.ThirdPartyCapabilities)
			{
				--topCount;
				continue;
			}
        }
        
		// Remember if we are in Suite mode (more than one top level payload)
		if(topCount > 1)
		    this.session._suiteMode = true; 
					
    }
    else if(this.mode == kWorkflowModeMaintenance)
    {
	    /** Listing of installed top level payloads **/
	    this.installedtopLevelPayloads  = this.GetPayloadsByFilter("top","installed");

	    /** Listing of installed branded shared component payloads **/
	    this.installedbrandedSharedCompPayloads  = this.GetPayloadsByFilter("brandedshared","installed");

	    /** Listing of installed unbranded shared component payloads **/
	    this.installedunbrandedSharedCompPayloads  = this.GetPayloadsByFilter("unbrandedshared","installed");
	    
	    /** Listing of notinstalled top level payloads **/
	    this.notinstalledtopLevelPayloads  = this.GetPayloadsByFilter("top","notinstalled");

	    /** Listing of notinstalled branded shared component payloads **/
	    this.notinstalledbrandedSharedCompPayloads  = this.GetPayloadsByFilter("brandedshared","notinstalled");

	    /** Listing of notinstalled unbranded shared component payloads **/
	    this.notinstalledunbrandedSharedCompPayloads  = this.GetPayloadsByFilter("unbrandedshared","notinstalled");

        var topCount = this.installedtopLevelPayloads.length + this.notinstalledtopLevelPayloads.length;

        for(var adobeCode in this.session.sessionPayloads)
        {
	        //Decrement the top count for each protected content
            var payload = this.session.sessionPayloads[adobeCode];
            if(payload.policyNode && payload.policyNode.IsProtected(adobeCode))
            {
                --topCount;
                continue;
            }

			//Decrement the top count for each third party payload
			var payloadSessionData = payload.GetSessionData();
			if (payload._payloadType == kTopLevelPayload && payloadSessionData.ThirdPartyCapabilities)
			{
				--topCount;
				continue;
			}
        }
        
		// Remember if we are in Suite mode (more than one top level payload)
		if(topCount > 1)
		    this.session._suiteMode = true; 
					
    }
    else if(this.mode == kWorkflowModeUninstall)
    {
	    /** Listing of installed top level payloads **/
	    this.topLevelPayloads  = this.GetPayloadsByFilter("top","installed");
	    
	    /** Listing of installed branded shared component payloads **/
	    this.brandedSharedCompPayloads  = this.GetPayloadsByFilter("brandedshared","installed");

	    /** Listing of installed unbranded shared component payloads **/
	    this.unbrandedSharedCompPayloads  = this.GetPayloadsByFilter("unbrandedshared","installed");

	    /** Listing of notinstalled top level payloads  - only required to determine if we are running in Suite mode **/
	    this.notinstalledtopLevelPayloads  = this.GetPayloadsByFilter("top","notinstalled");

        var topCount = this.topLevelPayloads.length + this.notinstalledtopLevelPayloads.length;

        for(var adobeCode in this.session.sessionPayloads)
        {
			//Decrement the top count for each protected content
            var payload = this.session.sessionPayloads[adobeCode];
            if(payload.policyNode && payload.policyNode.IsProtected(adobeCode))
            {
                --topCount;
                continue;
            }

			//Decrement the top count for each third party payload
			var payloadSessionData = payload.GetSessionData();
			if (payload._payloadType == kTopLevelPayload && payloadSessionData.ThirdPartyCapabilities)
            {
                --topCount;
                continue;
            }
        }

		// Remember if we are in Suite mode (more than one top level payload)
		if(topCount > 1)
		    this.session._suiteMode = true; 
						
    }
    
    var driver = this.session.GetDriverPayload();
	
	// Update visibility and selectability.
	var count = this.Refresh();

	// We may be passed a function so the client can redirect
	// where a WizardPayload appears in the DOM on a payload
	// by payload basis.
	var GetListElement = function(inPayload)
	{
		if ("function" == typeof inListElement)
		{
			return inListElement(inPayload);
		}
		return inListElement;
	};
	var GetElementByID = function(elementID)
	{
		var elementQ = new Array();
		var elementNode = null;
		elementQ.push(GetListElement(null));
		do {
			var node = elementQ.pop();
			for (var n = 0; n < node.childNodes.length; n++) {
				if (node.childNodes[n].id == elementID) {
					elementNode = node.childNodes[n];
					break;
				}
				elementQ.push(node.childNodes[n]);
			}
		} while (elementQ.length > 0 && elementNode == null);
		while (elementQ.length > 0) // Rmove remaining elements
			elementQ.pop();
		delete elementQ;

		return elementNode;
	};

	var GetPayloadListElement = function(listElementIdP,divElementIdP)
	{
		var payloadsPList = new Array();

		if (!divElementIdP) {
			payloadsPList[0] = GetElementByID(listElementIdP);
		}
		else {
			var payloadsPDiv = GetElementByID(divElementIdP);

			// Javascript not standardized across Win and Mac
			if (navigator.appVersion.indexOf("Win")!=-1)
				payloadsPList[0] = payloadsPDiv.rows[1].cells[1].childNodes[0];
			else
				payloadsPList[0] = payloadsPDiv.rows[1].cells[1].childNodes[1];
			payloadsPList[1] = payloadsPDiv;
		}

		return payloadsPList;
	};

	var setupdomCrossPlatform = function(payloadsP,listElementIdP,divElementIdP)//document.getElementById() is working only for win, mac is screwed up!
	{
		var payloadsPList = GetPayloadListElement(listElementIdP ,divElementIdP)[0];

		if(!divElementIdP)
		{
			if ( payloadsP.length > 0 )
			{
				for (var pIndex = 0; pIndex < payloadsP.length; pIndex++)
				{
					var dom = payloadsP[pIndex].GetUIDOM();
					if (dom)
					{
					    if(!(payloadsP[pIndex].payload.hasUIParent() && payloadsP[pIndex].payload.uiParentPayload && (payloadsP[pIndex].payload.GetInstallStateForCollection(payloadsP[pIndex].payload.policyNode.session.sessionCollection) == payloadsP[pIndex].payload.uiParentPayload.GetInstallStateForCollection(payloadsP[pIndex].payload.uiParentPayload.policyNode.session.sessionCollection))))
					    {
						    payloadsPList.appendChild(dom);
					    }
				    }
			    }
		    }
		}
		else	//payloadsP,listElementIdP,divElementIdP, for maintenance mode, divElementIdP or listElementIdP element is two levels below
		{
			if ( payloadsP.length > 0 )
			{
				for (var pIndex = 0; pIndex < payloadsP.length; pIndex++)
				{
					var dom = payloadsP[pIndex].GetUIDOM();
					if (dom)
					{
					    if(!(payloadsP[pIndex].payload.hasUIParent() && payloadsP[pIndex].payload.uiParentPayload && (payloadsP[pIndex].payload.GetInstallStateForCollection(payloadsP[pIndex].payload.policyNode.session.sessionCollection) == payloadsP[pIndex].payload.uiParentPayload.GetInstallStateForCollection(payloadsP[pIndex].payload.uiParentPayload.policyNode.session.sessionCollection))))
					    {
						    payloadsPList.appendChild(dom);
					    }
				    }
			    }
		    }
		}
	};

	var CanHideElement = function(payloadList)
	{
		var bHide = true;

		for (var i in payloadList) {
			if (payloadList[i].actionMap.visible) {
				bHide = false;
				break;
			}
		}

		return bHide;
	};

	var HideElementList = function(bHide, listElementIdP, divElementIdP)
	{
		if (bHide == true) {
			var display = "none";
			var payloadsPList = GetPayloadListElement(listElementIdP ,divElementIdP);
			var payloadHeaderNode = GetElementByID(listElementIdP + "Header"); // Get the header container

			payloadsPList[0].style.display = display;
			if (payloadsPList[1]) // divElementIdP is valid?
				payloadsPList[1].style.display = display;
			if (payloadHeaderNode)
				payloadHeaderNode.style.display = display;
		}
	};

	var HidePayloadList = function(payloadsArray, preFixString)
	{
		var bHideUnBrandedShared = CanHideElement(payloadsArray[2]);
		var bHideBrandedShared = CanHideElement(payloadsArray[1]);

		HideElementList(bHideUnBrandedShared,
			preFixString+"unbrandedSharedCompList", preFixString+"unbrandedSharedCompOuterDiv");
		HideElementList(bHideBrandedShared,
			preFixString+"brandedSharedCompList", null);
		HideElementList(payloadsArray[0].length == 0
				&& bHideUnBrandedShared
				&& bHideUnBrandedShared,
				preFixString+"topLevelPayloadsList", null);
	};

	var SetupTabOrderOnPayloads = function(payloadList)
	{
		if (payloadList.length > 0) {
			var wamElementSet = payloadList[0].wizardSelect.wamElementSet;
			for (var i in payloadList) {
				wamElementSet.push({element:payloadList[i].checkbox.GetDisplayElement(),virtualtype:'CheckBox',jawslabel:"Check box for "+payloadList[i].nameSpanElement.innerText});
				wamElementSet.push({element:payloadList[i].disclosureTriangleImg.GetDisplayElement(),virtualtype:'DisclosureTriangle',jawslabel:"Disclosure Triangle for "+payloadList[i].nameSpanElement.innerText});
				wamElementSet.push({element:payloadList[i].nameSpanElement,virtualtype:'ReadableText'});
				wamElementSet.push({element:payloadList[i].sizeSpanElement,virtualtype:'ReadableText'});
				wamElementSet.push({element:payloadList[i].DOM.rows[1],virtualtype:'ReadableText'});
			}
		}
	};

	//for install and uninstall modes, there are only three groups top, shared and supporting, but for maintenance, there are six groups in ui, installed top, installed shared and installed supporting, notinstalled top, notinstalled shared and notinstalled supporting
	if(this.session.getWorkflowMode() == kWorkflowModeInstall || this.session.getWorkflowMode() == kWorkflowModeUninstall)
	{
		// Assemble the UI.
		// RemoveAllChildren(GetListElement(null));
			
		// Top level payloads
		setupdomCrossPlatform(this.topLevelPayloads,"topLevelPayloadsList",null);
		
		// Branded shared components
		setupdomCrossPlatform(this.brandedSharedCompPayloads,"brandedSharedCompList",null);
		
		// Unbranded shared components
		setupdomCrossPlatform(this.unbrandedSharedCompPayloads,"unbrandedSharedCompList","unbrandedSharedCompOuterDiv");

		// Make things hidden if nothing is there to display
		HidePayloadList(new Array(this.topLevelPayloads, this.brandedSharedCompPayloads, this.unbrandedSharedCompPayloads), "");
		// Set up the tab order
		SetupTabOrderOnPayloads(this.topLevelPayloads);
		this.wamElementSet.push({element:GetElementByID("brandedSharedCompListHeaderID"),virtualtype:'ReadableText'}); // Shared Component
		SetupTabOrderOnPayloads(this.brandedSharedCompPayloads);
		this.wamElementSet.push({element:GetElementByID("unbrandedSharedCompListHeaderID"),virtualtype:'ReadableText'}); // Supporting Component
		SetupTabOrderOnPayloads(this.unbrandedSharedCompPayloads);
	}
	else if(this.session.getWorkflowMode() == kWorkflowModeMaintenance)
	{
		// Top level payloads
		setupdomCrossPlatform(this.installedtopLevelPayloads,"installedtopLevelPayloadsList",null);
					
		// Branded shared components
		setupdomCrossPlatform(this.installedbrandedSharedCompPayloads,"installedbrandedSharedCompList",null);
		
		// Unbranded shared components
		setupdomCrossPlatform(this.installedunbrandedSharedCompPayloads,"installedunbrandedSharedCompList","installedunbrandedSharedCompOuterDiv");

		// Make things hidden if nothing is there to display
		HidePayloadList(new Array(this.installedtopLevelPayloads, this.installedbrandedSharedCompPayloads, this.installedunbrandedSharedCompPayloads), "installed");
		// Set up the tab order
		this.wamElementSet.push({element:GetElementByID("ciheading"),virtualtype:'ReadableText'}); // Top level installed products
		SetupTabOrderOnPayloads(this.installedtopLevelPayloads);
		this.wamElementSet.push({element:GetElementByID("installedbrandedSharedCompListHeaderID"),virtualtype:'ReadableText'}); // Installed Shared Component
		SetupTabOrderOnPayloads(this.installedbrandedSharedCompPayloads);
		this.wamElementSet.push({element:GetElementByID("installedSupportingCompTitleTextID"),virtualtype:'ReadableText'}); // Installed Supporting Component
		SetupTabOrderOnPayloads(this.installedunbrandedSharedCompPayloads);

		// PART NOT INSTALLED
		// Top level payloads
		setupdomCrossPlatform(this.notinstalledtopLevelPayloads,"notinstalledtopLevelPayloadsList",null);
					
		// Branded shared components
		setupdomCrossPlatform(this.notinstalledbrandedSharedCompPayloads,"notinstalledbrandedSharedCompList",null);
		
		// Unbranded shared components
		setupdomCrossPlatform(this.notinstalledunbrandedSharedCompPayloads,"notinstalledunbrandedSharedCompList","notinstalledunbrandedSharedCompOuterDiv");

		// Make things hidden if nothing is there to display
		HidePayloadList(new Array(this.notinstalledtopLevelPayloads, this.notinstalledbrandedSharedCompPayloads, this.notinstalledunbrandedSharedCompPayloads), "notinstalled");
		// Set up the tab order
		this.wamElementSet.push({element:GetElementByID("cniheading"),virtualtype:'ReadableText'}); // Top level Available Products
		SetupTabOrderOnPayloads(this.notinstalledtopLevelPayloads);
		this.wamElementSet.push({element:GetElementByID("notinstalledbrandedSharedCompListHeaderID"),virtualtype:'ReadableText'}); // Not Installed Shared Component
		SetupTabOrderOnPayloads(this.notinstalledbrandedSharedCompPayloads);
		this.wamElementSet.push({element:GetElementByID("notinstalledSupportingCompTitleTextID"),virtualtype:'ReadableText'}); // Not Installed Supporting Component
		SetupTabOrderOnPayloads(this.notinstalledunbrandedSharedCompPayloads);
	}
		
	// Make sure everything is in order.
	//this.ValidateSelections();
}


WizardPayloadSelect.prototype.ValidateSelections = function()
{
	var sessionIsValid = true;
	
	// Clear any errors this would generate
	var errorprefix = "WPS.";
	this.wizardError.ClearErrorsMatching("^WPS\..*");

	// Simulate installation and return any conflicts that would occur during that process
	try
	{
		_simulatePayloadOperations(this.session);
		
		// Report the results
		for (var anAdobeCode in this.session.sessionPayloads)
		{
			var aPayload = this.session.sessionPayloads[anAdobeCode];
			this.session.LogDebug("WizardPayloadSelect.ValidateSelections: checking operaiton result for " + aPayload.LogID());
			if (aPayload.GetOperationResult()
				&& aPayload.GetOperationResult().message
				&& aPayload.GetOperationResult().message.simulationResults)
			{
				var simulationResults = aPayload.GetOperationResult().message.simulationResults;
				for (var conflictIndex = 0; conflictIndex < simulationResults.conflicting.length; ++conflictIndex)
				{
					sessionIsValid = false;
					var conflictingAdobeCode = simulationResults.conflicting[conflictIndex];
					var conflictingPayload = this.session.allPayloads[conflictingAdobeCode];
					this.wizardError.AddError(errorprefix + "conflict" + anAdobeCode + conflictingAdobeCode, "critical",
						aPayload.GetUIProductName(this.session)
						+ " cannot be installed alongside "
						+ conflictingPayload.GetUIProductName(this.session));
				}
			}
			else
			{
				this.session.LogDebug("WizardPayloadSelect.ValidateSelections: no operation result message for " + aPayload.LogID());
				this.session.LogDebug(aPayload.GetOperationResult());
			}
		}
	}
	catch (ex)
	{
		this.session.LogError("Simulation exception, skipping additional conflict reporting.");
	}
	
	// Load the template string so we can substitute the values for the entries
	
	
	// Report any payload dependencies that would not be met if the installation were to proceed
	var unsatisfiedDependenciesArray = this.session.AccumulateUnsatisfiedDependencies();
	for (var index = 0; index < unsatisfiedDependenciesArray.length; ++index)
	{
		sessionIsValid = false;
		var curDependency = unsatisfiedDependenciesArray[index];
		
		// We don't block for a recommended payload
		if(curDependency.type == kDependencyTypeRecommended)
		    continue;
		
		var substParams = new Object();
		substParams["payload1"] = curDependency.owningPayload.GetUIProductName(this.session);
		substParams["payload2"] = curDependency.productName;
		
		var dependencyErrorText = this.session.localization.GetString('locRequirePayloadInstalled', curDependency.owningPayload.GetUIProductName(this.session) + " requires " + curDependency.productName + " to be installed.", substParams);
		this.wizardError.AddError(errorprefix + "dependency" + curDependency.owningPayload.GetAdobeCode + curDependency.productName, 
									"critical",
									dependencyErrorText);
	}
	
	// Update the total size
	this.totalSize.Set(this.session.OperationSize().totalBytes);

	return sessionIsValid;
}


WizardPayloadSelect.prototype.SelectAll = function(inSelectState)
{
	// Get our session payloads and order them.
	var payloads = PayloadDependencySort(this.payloads, this.mode == kWorkflowModeUninstall || this.allSelected.Get());
	var stateToSet;
	if(inSelectState != null)
		stateToSet = inSelectState;
	else
		stateToSet = !this.allSelected.Get();

	// Select/Deselect appropriately
	for (var p in payloads)
	{
		var actionMap = payloads[p].GetUISelectionAction(this.session);
		if (actionMap.selectable)
		{
			payloads[p].GetUISelectionAction(this.session, stateToSet);
		}
	}
	this.Refresh();
}

WizardPayloadSelect.prototype.ShowAllCheckBoxes = function()
{
	for (var wp in this.wizardPayloads)
	{
	    this.wizardPayloads[wp].checkbox.SetVisibility("visible");
	}
}

WizardPayloadSelect.prototype.HideAllCheckBoxes = function()
{
	for (var wp in this.wizardPayloads)
	{
		if ( (this.wizardPayloads[wp].payload.hasUIParent() != true) || (this.wizardPayloads[wp].payload.uiParentPayload == null) )
			this.wizardPayloads[wp].checkbox.SetVisibility("hidden");
	}
}

WizardPayloadSelect.prototype.AreAllPayloadsSelected = function()
{
	return this.allSelected.Get();
}

WizardPayloadSelect.prototype.Refresh = function()
{
	var retVal = {
		uiVisible: 0,
		uiSelectable: 0,
		uiSelected: 0   //Payloads that have their check-box enabled, are visble, and are selected
	};
	
	// Clear some errors.
	if (this.wizardError)
	{
		this.wizardError.ClearErrorsMatching("^InstallerPayload\..*");
		this.wizardError.ClearError("WizardPayload.AtLeastOne");
	}

	// Refresh each payload
	for (var pIndex = 0; pIndex < this.wizardPayloads.length; pIndex++)
	{
		this.wizardPayloads[pIndex].Refresh();
	}

	// Figure out totals for selectable and selected
	for (var pIndex = 0; pIndex < this.wizardPayloads.length; pIndex++)
	{
		if (this.wizardPayloads[pIndex].actionMap.visible)
		{
			retVal.uiVisible++;
		}
		if (this.wizardPayloads[pIndex].actionMap.selectable)
		{
			retVal.uiSelectable++;
			if (this.wizardPayloads[pIndex].actionMap.checkedState)
			{
				retVal.uiSelected++;
			}
		}
	}
	
	// Throw up an error if we don't meet the minimim selected threshold.
	if(this.session.IsSuiteMode() && this.mode == kWorkflowModeUninstall)
	    var selectionMinimum = 1;
	else
	    var selectionMinimum = 0;

	if (this.wizardError && retVal.uiVisible > 0 && retVal.uiSelected < selectionMinimum)
	{
		if(this.mode == kWorkflowModeUninstall && retVal.uiSelectable == 0)
		{
			// We have nothing to select in the UI. Allow the user to uninstall
			var driver = this.session.sessionPayloads[this.session.GetSessionData().driverPayloadID];
			if (driver && driver.policyNode)
			{
				driver.policyNode.action.Set(true);
			}
			this.session.LogDebug("WizardPayloadSelect.Refresh: Nothing to select in the UI. Allowing uninstall");
		}
		else
		{
			this.wizardError.AddError("WizardPayload.AtLeastOne", "critical", this.session.localization.GetString("locErrorNoSelections", "At least one component must be selected."));
		}
	}

	// Set the property indicating whether or not everything is selected.  Useful for,
	// say, a Select/Deselect All button whose behavior changes depending on whether or
	// not everything is selected.
	this.allSelected.Set(retVal.uiSelectable == retVal.uiSelected);

	// Update the total size
	this.totalSize.Set(this.session.OperationSize().totalBytes);

	return retVal;
}

WizardPayloadSelect.prototype.SetOnCheckedFuntion = function(onCheckedFn)
{
	this.onChecked = onCheckedFn;
}

WizardPayloadSelect.prototype.OnChecked = function(wp, selectedCount)
{
	if (this.onChecked != null) {
		this.onChecked(wp, selectedCount);
	}
}
/*
LEGACY: Return the number of payloads selected by the user.
*/
WizardPayloadSelect.prototype.SelectCount = function()
{
	return this.Refresh();
}
