﻿var isInitialized = false;
var hasCompletedWizard = false;
var progressBarUpdater = null;
var stepHistory = null;

// UI variables and settings
var splashDiv;
var blackoutDiv;
var visibleStepDiv;
var hiddenStepDiv;
var isSwapAllowed=true;

    function initialize(bypassSplash)
    {
		if (typeof(advisor)=="undefined")
		{
			alert("Advisor does not exist.");
			return;
		}
		
        var startButton = getElement("advisorBeginButton");
		setText(getElement("advisorTitle"), advisor.name);		
	
	    if(advisor.specVersion != "")
        {
	        setText(getElement("advisorSpecVersion"), " v" + advisor.specVersion );
    	}		
		
        setText(getElement("advisorDisclaimerText"), advisor.disclaimer);
        if (advisor.advisorSkinType == "Blue" || advisor.advisorSkinType == "SilverBlack")
            setText(startButton, WizardMessages.StartButton_Text + " " + advisor.name);
        else if(advisor.advisorSkinType == "GreenPrint")
            startButton.Text =setText(startButton,"CONTINUE");
        else        
            startButton.Text =  setText(startButton,WizardMessages.StartAdvisorButton_Text);
            
        visibleStepDiv = getElement('StepA');
        hiddenStepDiv = getElement('StepB');
        
        // initialize stepHistoryTracker
		stepHistory = new StepHistoryTracker(advisor);

		// attempt to restore state of advisor if user hit the back button
		var postData = advisor.getElement("pageState").value;
		if (postData.length > 0)
		{
			advisor.restoreFromPostData(postData);
			advisor.overrideInitialStep = "summary";
		}

		hasCompletedWizard = location.search.toLowerCase().indexOf("advisorrequestid")!=-1;
		if (location.hash.length > 1) {
			var initialStepId = location.hash.substr(1);
			if (window[initialStepId] || initialStepId=="summary")
				advisor.overrideInitialStep = initialStepId;
		}
		
	    if (advisor.advisorSkinType == "SilverMini")
	        bypassSplash = true;
		
		if (advisor.overrideInitialStep || hasCompletedWizard || bypassSplash)
			showWizard();
		else
			showSplash();
    }
    

    function preFetchObjects()
    {
		new Ajax.Request("CacheObject.aspx?action=advisor&advisor=" + advisor.id + ";" + advisor.version + "&cs=" + advisor.customerSet);
		new Ajax.Request("CacheObject.aspx?action=config&advisor="  + advisor.id + ";" + advisor.version + "&cs=" + advisor.customerSet);
		new Ajax.Request("CacheObject.aspx?action=runtime&advisor=" + advisor.id + ";" + advisor.version + "&cs=" + advisor.customerSet);
    }
    
    function showSplash()
    {
		getElement("advisorDisclaimer").style.display = "";
		getElement("StepBack").style.display = "none";
    }
    
    function showWizard()
    {
		if (!WizardUtils.stepExists(advisor.initialStep))
		{
			alert('Advisor error:\rAdvisor.InitialStep ("' + advisor.initialStep + '") does not exist.');
			return;
		}
		getElement("advisorDisclaimer").style.display = "none";
		getElement("StepBack").style.display = "";
		setOpacity(hiddenStepDiv, 100);
        openStep(advisor.initialStep);
        progressBarUpdater = new ProgressBarUpdater(document.getElementById("progressBar"), stepHistory);
		progressBarUpdater.update();
		if (advisor.overrideInitialStep)
			jumpToStep(advisor.overrideInitialStep);
		// loading of css background images (buttons, step indicator, etc.) will be delayed if preFetchObjects is called initialize
		// we call it here to allow the background images to be loaded
		setTimeout("preFetchObjects()", 1500);
    }

    function showSummary()
    {
    // Format of summary is:
    // foreach step:
    //   {QuestionShortText (link)} {AnswerValue} {AhswerShortText}, {AnswerValue} {AhswerShortText}...
		document.getElementById("progressBar").style.display = "";
		showLastSelection(false); // hide lastSelection
		showMoreInfo();// hide moreInfo

		var lastStepId = stepHistory.stepList[stepHistory.stepList.length-1];
		currentStep = null;
		var html = "";

		if (advisor.advisorSkinType == "Silver" ) {

		    html += "<div class='stepSummary'>";
		    html += "<div class='summaryHeader'>"+ WizardMessages.AdvisorSummary_Text.escapeHTML() +"</div>";
		    html += "<div class='stepQuestion'>";
		    html += "<table width=100% cellpadding=1 border=0>";
		    html += "<tr bgcolor='#CCCCCC'><td colspan=2>";
		    html += "<b><font color=black>"+WizardMessages.SelectionSummary_Text.escapeHTML()+"</font></b>";
		    html += "</td></tr><tr><td colspan=2>&nbsp;</td></tr>";
	        html += "<tr><td align='center' colspan='2'>";
	        html += "<div class='solutionLink'>";
	        html += "<a href='javascript:showAdvisorResults();'>" + WizardMessages.ViewSolutionButton_Text.escapeHTML() + "</a>";
	        html += "<span>&nbsp;&nbsp;</span>";
	        html += "</td></tr><tr><td colspan=2>&nbsp;</td></tr>";
		    html += "<tr><td>";
		    html += "<div id='summaryStepListContainer' style='height:250px;padding:0 0 20px 0;overflow-y: auto;overflow-x;hidden:auto;postion:relative'>";
		        html += "<br><table class='summaryTable' cellpadding='0' cellspacing='0'>";
		        for (var i=0; i<stepHistory.stepList.length; i++)
		        {
			        var thisStep = window[ stepHistory.stepList[i] ];
			        html += "<tr>";
			        html += "<td style='border-width:1px;border-style:solid;border-color:lightgrey;' align='center'>"+(i+1)+"</td>";
			        html += thisStep.getNewSummaryHtml("openStep('{0}',true)");
			        html += "</tr>";
		        }
		        html += "</table>"
		    html += "</div>";
		    html += "</td></tr>";
    		
    	    html += "<tr><td colspan=2>&nbsp;</td></tr>";
		    html += "<tr><td align='center' colspan='2'>";
		    html += "<div class='solutionLink'>";
		    html += "<a href='javascript:showAdvisorResults();'>" + WizardMessages.ViewSolutionButton_Text.escapeHTML() + "</a>";
		    html += "<span>&nbsp;&nbsp;</span>";
		    html += "</div>";
		    html += "</td></tr>";
		    html += "</table>";
		    html += "</div>";
		    html += "</div>";
		    html += "<br />";
		} else {
		    
		    html = "<div class='step'>";
    	    html += "<div class='stepQuestion'>";
		    html += WizardMessages.SelectionSummary_Text.escapeHTML();
		    html += "</div>";
		    html += "<div id='summaryStepListContainer'>";
		    html += "<ol class='selectionSummary'>";

		    for (var i=0; i<stepHistory.stepList.length; i++)
		    {
			    var thisStep = window[ stepHistory.stepList[i] ];
			    html += "<li>";
			    html += thisStep.getSummaryHtml("openStep('{0}',true)");
			    html += "</li>";

		    }
		    html += "</ol>";
		    html += "</div>";
		    html += "</div>";
		    html += "<br />";
		    html += "<a class='previousStepLink' href='javascript:openStep(\"" + lastStepId + "\", true);'>" + WizardMessages.GoBackButton_Text.escapeHTML() + "</a> ";
		   
		   
		   
		    if (advisor.advisorSkinType == "SilverMini") {
		        html += "<div class='solutionLink'>";
		        html += "<a href='javascript:showAdvisorResults();'><span>" + WizardMessages.UpdateSolution_Text.escapeHTML() + "</span></a>";
		    }
		    else {
    		 
    		    html += "<div class='continueLink'>";
		        html += "<a href='javascript:showAdvisorResults();'><span>" + WizardMessages.ViewSolutionButton_Text.escapeHTML() + "</span></a>";
		     }
		       
		    html += "<span>&nbsp;&nbsp;</span>";
		    html += "</div>";
		}
		
		hiddenStepDiv.innerHTML = html;
		swapStepAandB();	
		  
	    // add scrolling if needed
	    	    
	    if (advisor.advisorSkinType != "Silver" ) {
			var maxHeight = 300;
			if (advisor.advisorSkinType == "SilverBlack")
				maxHeight = 240;
    	    var tooTall = $('summaryStepListContainer').getHeight() > maxHeight;
	        $('summaryStepListContainer').setStyle( {
		        overflow : tooTall ? "auto"  : "",
		        height   : tooTall ? maxHeight + "px" : ""
	        } );
        }		

		hasCompletedWizard = true;
		progressBarUpdater.update();
		
    }
    
    function getWizardType()
    {
		var pathname = window.location.pathname.toLowerCase();
		if (pathname.indexOf("/dellstarwizard.aspx") != -1)
			return "dsWiz";
		else if (pathname.indexOf("/premieradvisor.aspx") != -1)
			return "premierWiz";
		else
			return "stdWiz";
    }
    
    function showAdvisorResults()
    {
		// persist state to hidden input field.  browser persists state
		// when navigating forward and back, so we'll store state from
		// this field if user clicks back button on solution page.
		advisor.getElement("pageState").value = advisor.getPostData();

		document.getElementById("progressBar").style.display = "none";
		var params = location.search.toQueryParams();
		var postData = "";
		if (getWizardType()=="dsWiz")
			// disable background solution creation
			postData += "action=Evaluate,CreateSolutionSync&createdInDellStar=true";
		else if (advisor.advisorType=="SMBSelector")
			postData += "action=Evaluate";
		else
			postData += "action=Evaluate,CreateSolutionAsync";

		if (params["cust"])
			postData += "&cust=" + escape(params["cust"]);
		if (params["name"])
			postData += "&name=" + escape(params["name"]);
		if (params["usr"])
			postData += "&usr=" + escape(params["usr"]);
		if (params["soln"])
		    postData += "&soln=" + escape(params["soln"]);
		if (params["oc"])
			postData += "&oc=" + escape(params["oc"]);
			
		postData += "&stepOrder=" + escape(stepHistory.stepList.join(","));
		postData += "&" + advisor.getPostData();//stepHistory.stepList);
		
		if (advisor.name == "SMB Virtualization Advisor") {
            window.location = "http://" + window.location.hostname + "/dellstaronline/Summary.aspx?c=us&l=en&cs=g_5&Solution=20735";
            return;
        }

		new Ajax.Request(createSolutionUrl, {
			method: 'post',
			postBody: postData,
			onSuccess: function(transport){
				var o = {};
				try {
					eval("o = " + transport.responseText);
				} catch (e) {
					o.error = "Error (" + e.message + ") processing callBackFunction with:\n\n" + transport.responseText;
				}
				var params = location.search.toQueryParams();
				if (o.error) {
					alert("Error: " + o.error);
					if (o.trace && o.advisorRequestId)
						addTraceLink(o.advisorRequestId);
					if(advisor.advisorSkinType != "GreenPrint")
					    showSummary();
					else
					{
					    document.getElementById("progressBar").style.display = "";
					    openStep(advisor.initialStep,true);
					    progressBarUpdater = new ProgressBarUpdater(document.getElementById("progressBar"),stepHistory);
                        progressBarUpdater.update();
					}
				} else if (o.advisorRequestId) {
					var sourceWizard = getWizardType();
					var url = "";
					if (sourceWizard=="dsWiz")
						url += "DellStarSolution.htm";
					else if (sourceWizard=="premierWiz")
						url += "PremierSolution.aspx";
					else if (advisor.advisorSkinType == "SilverMini")
					    url += "MiniSolution.aspx";
					else{
		                url += "Solution.aspx";
		            }
					url += "?Advisor=" + o.advisor;
					url += "&AdvisorRequestId=" + o.advisorRequestId;
					if (params["cs"] != null)
						url += "&cs=" + advisor.customerSet;
				    if (params["oc"] != null)
                        url += "&oc=" + escape(params["oc"]);
					if (sourceWizard=="dsWiz")
					{
						url += "&solutions=";
						for(var i=0; i<o.solutions.length; i++)
						{
							if (i>0)
								url += ",";
							url += o.solutions[i].id + "." + o.solutions[i].version;
						}
						
						if (o.noValidSolutions)
						{
							alert("A solution that satisfies your request could cannot be created.  Please change one or more of your responses and try again.");//TODO: localize
							if(advisor.advisorSkinType != "GreenPrint")
							    showSummary();
							else
		                    {
		                        openStep(advisor.initialStep,true);
		                        progressBarUpdater = new ProgressBarUpdater(document.getElementById("progressBar"));					                                    progressBarUpdater.update();
		                    }
							return;
						}
					}
					window.location = url;
				}
			},
			onFailure: function() {
			if(advisor.advisorSkinType != "GreenPrint")
			{
				showSummary();
		    }
		    else
		    {
		        openStep(advisor.initialStep,true);
		        progressBarUpdater = new ProgressBarUpdater(document.getElementById("progressBar"));					                                    progressBarUpdater.update();
		    }	
			}
		} );

		hiddenStepDiv.innerHTML = '<div class="ajax">' + WizardMessages.PleaseWait_Text + '</div>';
		swapStepAandB();
    }
    
    var somethingFading = false;
    
    function showMoreInfo(helpText)
    {
		if (somethingFading)
			return; // actually delay

		// change logic to this:
		// - if nothing shown, display until it's visible and ignore mouseout
		// - if coming from another element, work as before
		if (typeof(helpText)=="string" && helpText.length>0) {
			somethingFading = true;
			getElement("moreInfoText").innerHTML = helpText;
			expandTerms();
			getElement("moreInfo").style.display='block';
			FadeElement("moreInfo", 90, function() {
				somethingFading = false;
			}, 0.3, null, true, null, []);
		} else {
			var delay = helpText;
			var td = getElement("termDiv");
			if (td!=null)
				td.style.display='none';
			FadeElement("moreInfo", 0, function() {
				getElement("moreInfo").style.display='none';
				somethingFading = false;
			}, 0.3, null, false, delay, []);
		}
    }
    
    function keepMoreInfo()
    {
		var ele = getElement("moreInfo");
		if (getOpacity(ele) > 50)
		{
			getElement("moreInfo").style.display='block';
			FadeElement("moreInfo", 90, function() {
				somethingFading = false;
			}, 0.3, null, true, null, []);
		}
    }
    
    function expandTerms()
    {
		// find all elements having popupText='advisormessagekey';
		$('moreInfo').descendants().each( function(ele) {
			var defTxt = ele.readAttribute("definitionText");
			var defId = ele.readAttribute("definitionId");
			if (defTxt != null || defId != null)
			{
				ele.addClassName("popupMessage");
				Event.observe(ele, "mouseover", function(evnt) {
					showTerm(evnt);
				} );
			}
		});		
    }
    
    function showTerm(evnt)
    {
		var termDiv = $(verifyTermDiv());
		var ele = Event.element(evnt);
		var pos = ele.cumulativeOffset();
		var defTxt = ele.readAttribute("definitionText");
		var defId = ele.readAttribute("definitionId");
		var message = "";
		
		if (defTxt != null)
			message = defTxt;
		else if (defId != null)
			message = advisor.messages[defId];

		var termDivText = getElement('termDivText');
		termDivText.innerHTML = message;
		termDiv.style.left = (pos.left - termDiv.getWidth() - 2) + "px";
		termDiv.style.top = (pos.top - termDiv.getHeight() + 9 )+ "px";
		termDiv.style.display='';
    }
    
    function verifyTermDiv()
    {
		var termDiv = getElement('termDiv');
		if (termDiv==null)
		{
			termDiv = document.createElement("div");
			termDiv.id = "termDiv";
			termDiv.innerHTML = "<div id='termDivText'></div><div id='termDivFooter'></div>";
			document.body.appendChild(termDiv);
		}
		return termDiv;
    }
    
    function showMoreInfoPopup(helpText, answerText)
    {
        if (typeof(helpText)=="string" && helpText.length>0) {
            setText(getElement("moreInfoPopupMessageHeader"), answerText);
		    getElement("moreInfoPopupMessageBody").innerHTML = helpText;
		    getElement("moreInfoPopupContainer").style.display = "";
		    getElement("popUpMessageButton").focus();
		}
    }
    
    function setMoreInfo(selectEle)
    {
		var attr = selectEle.options[selectEle.selectedIndex].attributes["answerHelpText"];
		var moreInfoEle = getElement(selectEle.id + "MoreInfo");
		if (moreInfoEle!=null) {
			var moreInfoAttr = moreInfoEle.attributes["answerHelpText"]
			moreInfoAttr.value = attr==null ? "" : attr.value;
			moreInfoEle.style.visibility = moreInfoAttr.value=="" ? "hidden" : "visible";
		}
    }
    
    function selectAll(obj) {
        if (obj.checked) {
            for (var i = 0; i < currentStep.answers.length; i++) {
                var a = document.getElementById(currentStep.id + "." + currentStep.answers[i].id);
                if (currentStep.answers[i].id == "DontKnow")
                    a.checked = false;
                else
                    a.checked = true;
            }
        }
        else {
            for (var i = 0; i < currentStep.answers.length; i++) {
                var a = document.getElementById(currentStep.id + "." + currentStep.answers[i].id);
                a.checked = false;
            }
        }
    }    
    
    function showLastSelection(show)
    {
		if (show) {
			var previousStep = window[currentStep.previousStepId];
			if (typeof(previousStep)=="undefined")
				return;
			var html = "";
			var res = [];
			html += previousStep.questionShortText.escapeHTML();
			html += ": ";
			for(var i=0; i<previousStep.answers.length; i++)
			{
				var thisAns = previousStep[previousStep.answers[i].id];
				var shortText = thisAns.shortText.length == 0 ? thisAns.longText : thisAns.shortText;
				if (typeof(thisAns.isSelected)!="undefined")
				{
					if (thisAns.isSelected)
						res.push(shortText);
				}
				else
				{
					res.push(thisAns.value + " " + shortText);
				}
			}
			html += " " + res.join(", ");
			if(advisor.advisorSkinType != "GreenPrint")
			    getElement("lastSelectionText").innerHTML = html;
			FadeElement("lastSelection", 100, null, 0.3, null, false);
		} else {
			FadeElement("lastSelection", 0, null, 0.3, null, false);
		}
    }

    function swapStepAandB(showValidationSummary)
    {
		var callback = function() { onStepVisible(showValidationSummary); };

        if(isInitialized)
        {
			var previousStepId = currentStep != null && currentStep.previousStepId != null ? currentStep.previousStepId : null;
			var previousStep = window[previousStepId] || null;
			var previousStepWasSection = previousStep != null && previousStep.answers.length==0;

        	hiddenStepDiv.style.display = '';
			if (previousStepWasSection) // if prev step had flash, hide now to prevent any issues with fade-out
        		visibleStepDiv.style.display = 'none';

        	onStepPreVisible();

			FadeElement(hiddenStepDiv.id, 100, callback, 1.0, null, false, null,
				[ { elementId : visibleStepDiv.id, factor: -1, offset: 100 /* factor=-1 and offset=100 will make visibleStepDiv's opacity of the complement of hiddenStepDiv */ } ] );
        }
        else
        {
        	onStepPreVisible();
    		var sb = jQuery('#StepBack');
			if (advisor.advisorSkinType != "GreenPrint" && advisor.advisorSkinType != "SilverBlack") // slide&fade-in initial step
			{
        		var targetLeft = parseInt(sb.css('left'));
        		var startLeft = parseInt(jQuery('.wizard').css('width'));
        		sb.css('left', startLeft);
        		scrollInitialDivLeft(sb[0], targetLeft);
        	}
        	else // just show initial step
        	{
				setOpacity(sb[0], 100);
        	}
    		callback();
    		isInitialized = true;
        }
    }


    function onStepVisible(showValidationSummary)
    {
        swapHiddenAndVisibleDivVariables();
        visibleStepDiv.style.display = '';
        hiddenStepDiv.style.display = 'none';
        if (currentStep!=null)
        {
        	showLastSelection(true);
        	currentStep.onMadeVisible();
			if (showValidationSummary)
			{
				WizardUtils.showValidationSummary();
			}
		}
	}
	
	function onStepPreVisible()
    {
		var thisStepDiv = hiddenStepDiv;
		try
		{
    		// get elements
    		var stepDiv = jQuery(thisStepDiv).find('.step');
    		var qDiv = stepDiv.find('.stepQuestion');
    		var aDiv = stepDiv.find('.scroll');
    		
    		// save defaults
    		var defaults = { overflow: aDiv.css('overflow'), height: aDiv.css('height') };

    		// adjust css and measure
    		aDiv
    			.css('overflow', 'visible')
    			.css('height', 'auto');

    		var availHeight = stepDiv.height() - (aDiv.offset().top - stepDiv.offset().top);
    		var ansHeight = aDiv.outerHeight({ margin: true });

    		// set css
    		aDiv
    			.css('overflow', defaults.overflow)
    			.css('height', ansHeight > availHeight ? availHeight : defaults.height);
    	}
    	catch(e)
    	{
    	}
        // currentStep will return null on last step
        if(currentStep !=null)
        {
		    var isSection = currentStep.answers.length==0;
		    if (isSection)
			    jQuery('#StepBackImageLayer').hide();
		    else
			    jQuery('#StepBackImageLayer').show();
		}
    }
    
    function swapHiddenAndVisibleDivVariables()
    {
        var tempDiv = visibleStepDiv;
        visibleStepDiv = hiddenStepDiv;
        hiddenStepDiv = tempDiv;           
    }
    
    function scrollInitialDivLeft(ele, targetLeft, startLeft)
    {
    	var left = getLeft(ele);
        if (startLeft==null)
        	startLeft = left;

        var distTot = startLeft - targetLeft;
        var distRemain = left - targetLeft;

        if (distTot > 0 && distRemain > 1) {
    		distRemain = Math.max(distRemain * 0.8 - 5, 0);
    		var factor = 1 - distRemain / distTot;

    		left = targetLeft + distRemain;
    		setLeft(ele, left);
    		setOpacity(ele, factor * 100);

    		setTimeout( function() { scrollInitialDivLeft(ele, targetLeft, startLeft); } , 20);
    		return;
    	}

        setLeft(ele, targetLeft);
        setOpacity(ele, 100);
    }
    
    function clearSplash()
    {
        document.body.removeChild(getElement('splash'));
    }

    function toggleCheckOrRadio(answer)
    {
        if(answer.element)
        {
            answer.element.checked = !answer.element.checked;
        }
    }

function openStep(stepId, isStepBackwards, skipSwap)
{	
	
	showLastSelection(false); // hide lastSelection
	showMoreInfo();// hide moreInfo
	if (currentStep && isStepBackwards) // save state, but don't validate
		currentStep.updateStateFromForm();
	// keep history of forward steps
	var previousStepId = currentStep==null ? null : currentStep.id;
    currentStep = window[stepId];    
    if (!isStepBackwards)
		currentStep.previousStepId = previousStepId;
	Debug.Print("openStep(" + stepId + "), previousStepId=" + previousStepId + ", isStepBackwards=" + isStepBackwards);
	if (!isStepBackwards)
		stepHistory.trackStep(previousStepId, currentStep.id);
    hiddenStepDiv.innerHTML = this.currentStep.HTML;
    Debug.Print(stepId + ".onLoad()");
    currentStep.onLoad();
    Debug.Print(stepId + ".bindToForm()");
    //currentStep.bindToForm();
    if (!skipSwap)
    {
		swapStepAandB();
	}
	currentStep.bindToForm();
	Debug.Print("openStep(" + stepId + "), progressBarUpdater=" + progressBarUpdater);
	if (progressBarUpdater)
		progressBarUpdater.update();
	var jumpToSummaryLink = document.getElementById('jumpToSummaryLink' + currentStep.id);
	if (jumpToSummaryLink)
		jumpToSummaryLink.style.display = hasCompletedWizard ? "" : "none"; 
		
	// change the flash only when there is a change in section
	if(advisor.advisorSkinType == "GreenPrint") // Change the flash after the step is open
	{

	    // forward and backward flash files are saved as ; separated values. Extract them here
	    var nextStep = window[currentStep.nextStepId];
	    var flashToBeLoaded;
	    if (nextStep != null && nextStep.answers != null)
	        var previousStepWasSection = nextStep.answers.length == 0 && isStepBackwards;

	    if ((currentStep.answers.length == 0) || previousStepWasSection)
	       {
	            //var previousFlash = document.getElementById("flashSource") == null ? "" : document.getElementById("flashSource").getAttribute("src");		
                //if((previousFlash != currentStep.flashFilePath) && (currentStep.flashFilePath !='') && (currentStep.flashFilePath != null)) 
                //{
                
                //check if this is the initial question
                if(isStepBackwards && currentStep.answers.length ==0)
                    flashToBeLoaded = currentStep.flashFilePath.substring(currentStep.flashFilePath.lastIndexOf(';') + 1, currentStep.flashFilePath.length);
                // check if the backward navigation from section question
                else if (isStepBackwards && nextStep.answers.length == 0)                
                    flashToBeLoaded = nextStep.flashFilePath.substring(0, nextStep.flashFilePath.lastIndexOf(';'));	            
	            else  	    
	            // forward navigation
	                flashToBeLoaded = currentStep.flashFilePath.substring(currentStep.flashFilePath.lastIndexOf(';') + 1, currentStep.flashFilePath.length);
    	        
            var html = '';
            if (jQuery.browser.msie && jQuery.browser.version == "6.0")
            {
                html += "<object class='startUpFlashDiv' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codeBase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0'>";
            }
            else
                html += "<object class='startUpFlashDiv' >";
                    html += "<param id='movieName' name='movie' value='" + flashToBeLoaded + "'/>";
            html += "<param name='wmode' value='transparent' />";
			html += "<param name='height' value='100%' />";
			html += "<param name='width' value='100%' />";
                    html += "<embed id='flashSource' src='" + flashToBeLoaded + "'";
            html += "width='100%' height='100%' wmode='transparent' class='startUpFlashDiv'></embed>";
            html += "</object>";
            if (document.getElementById("flashContainer") != null)
                document.getElementById("flashContainer").innerHTML = html;
                //}
        }
       
    }      
}

function jumpToStep(targetStepId)
{
	if (currentStep == null || typeof(currentStep)!="object")
		return;
	Debug.Print("jumpToStep(" + targetStepId + ")");
	isUserInputValid = true;
	var beginningStepId = currentStep==null ? null : currentStep.id;
	while (isUserInputValid && currentStep.id!=targetStepId) {
		currentStep.updateStateFromForm();
		currentStep.validateInput();

		if (currentStep.validationInfo.errors.length==0) // is valid
		{
			currentStep.onNext();
			if (currentStep.validationInfo.errors.length==0) // is still valid
			{
				var openStepId = overrideNextStep == '' ? currentStep.nextStepId : overrideNextStep;
				if (!WizardUtils.stepExists(openStepId))
				{
					stepHistory.trackStep(currentStep.id, null);
					if(advisor.advisorSkinType != "GreenPrint")
					    showSummary();
					else
					{
					    showAdvisorResults();
					    
					}
					return;
				}
				openStep(openStepId, false, true);
				overrideNextStep = '';
			}
			else
			{
				isUserInputValid = false;
			}
		}
		else
		{
			isUserInputValid = false;
		}
	}

	if (beginningStepId != currentStep.id) { // if current step is not shown, show it.
		if(targetStepId != currentStep.id) { // if we encountered a validation error before getting to target step, show validation error
			swapStepAandB(true);
		} else {
			swapStepAandB();
		}
		progressBarUpdater.update();
	} else if (!isUserInputValid) {
		WizardUtils.showValidationSummary();
	}
}

function wizardNavClick(target)
{
	if (currentStep == null || typeof(currentStep)!="object")
		return;

	Debug.Print("wizardNavClick(" + target + ")");
	if (target==-1)
	{
		openStep(currentStep.previousStepId, true); // go back.
	}
	else
	{
		isUserInputValid = true;
		currentStep.updateStateFromForm();
		
		currentStep.validateInput();
		if (currentStep.validationInfo.errors.length==0) // is valid
		{
			currentStep.onNext();
			if (currentStep.validationInfo.errors.length==0) // is still valid
			{
				if (target=="summary")
				{
					stepHistory.trackStep(currentStep.id, null);
                    if(advisor.advisorSkinType != "GreenPrint")					
					showSummary();
					else
					    showAdvisorResults();
				} else {
					var openStepId = overrideNextStep == '' ? currentStep.nextStepId : overrideNextStep;
					if (!WizardUtils.stepExists(openStepId))
					{
						stepHistory.trackStep(currentStep.id, null);
						if(advisor.advisorSkinType != "GreenPrint")
						showSummary();
						else
						    showAdvisorResults();
						return;
					}
					openStep(openStepId);
					overrideNextStep = '';
				}
			}
			else
			{
				WizardUtils.showValidationSummary();
			}
		}
		else
		{
			WizardUtils.showValidationSummary();
		}
	}
}


// WizardUtils instance
var WizardUtils = {
	stepExists : function(stepId) {
		return typeof(window[stepId]) == "object";
	},
	showMessage : function(txt) {
		setText(getElement("popUpMessageBody"), txt);
		getElement("popUpMessageContainer").style.display = "";
		getElement("popUpMessageButton").focus();
	},
	showValidationSummary : function() {
		if(currentStep.validationInfo != null && currentStep.validationInfo.errors.length>0)
			WizardUtils.showMessage(currentStep.validationInfo.errors.join("\r"));
	}
};


// Class to track step history
function StepHistoryTracker(advisorObject)
{
	this.advisorObject = advisorObject;
	this.stepList = [];
	this.stepVisitedList = {};
	this.stepPath = {};
	this.getCompleteStepPath = function() {
		var completeStepPath = {};
		for(var stepIndex = 0; stepIndex < this.advisorObject.steps.length; stepIndex++)
		{
			var currStep = this.advisorObject.steps[stepIndex];
			if (stepIndex==0)
				this._track(completeStepPath, null, currStep.id);
			this._track(completeStepPath, currStep.id, currStep.nextStepId);
		}
		return completeStepPath;
	}
	this._track = function(obj, step1id, step2id) {
		if (step1id==null)
			step1id = "0";
		if (!WizardUtils.stepExists(step2id))
			step2id = null;
		obj[step1id] =
		{
			stepId : step1id,
			nextStepId : step2id
		};
	}
	this.trackStep = function(previousStepId, newStepId) {
		Debug.Print("trackStep: " + previousStepId + " -> " + newStepId);
		this._track(this.stepPath, previousStepId, newStepId);
		
		// rebuild the stepList
		this.stepList = [];
		this.stepVisitedList = [];

		// get the complete path
		var completeStepPath = this.getCompleteStepPath();
		
		// build that path that got us here
		for (var stepEntry = this.stepPath["0"]; stepEntry != null; stepEntry = this.stepPath[stepEntry.nextStepId])
		{
			Debug.Print("trackStep: building path: stepEntry={stepId:" + stepEntry.stepId + ", nextStepId:" + stepEntry.nextStepId + "}");

			if (stepEntry.nextStepId==null)
				break;

			// if entry is already in stepVisitedList, we looped; quit now
			if (this.stepVisitedList[stepEntry.nextStepId])
				break;
			
			this.stepList.push(stepEntry.nextStepId);
			this.stepVisitedList[stepEntry.nextStepId] = true;
			
			if (stepEntry.stepId == null)
				break;
		}
		Debug.Print("trackStep: building path: done; stepList=" + this.stepList.join(','));

		// add the path that takes us to the end
		for (var stepEntry = completeStepPath[newStepId]; stepEntry != null; stepEntry = completeStepPath[stepEntry.nextStepId])
			if (!this.stepVisitedList[stepEntry.stepId])
				this.stepList.push(stepEntry.stepId);
		Debug.Print("- stepList=" + this.stepList.join(","));
	}
}

// Class to update progress bar
// Progress bar is a table with (1) row and (number of steps + 2) columns.
// [start] [step 1] [step 2] [step 3] [end]
function ProgressBarUpdater(tableElement, stepHistoryObject)
{
	this.tableElement = tableElement;
	this.stepHistoryObject = stepHistoryObject;
	this.row = tableElement.rows[0];
	this.lastStepCount = 0;
	this.sync = function()
	{
		var uiStepCount = this.row.cells.length - 2;
		    
		var numberOfStepsToAdd = this.stepHistoryObject.stepList.length - uiStepCount;
		
		if (numberOfStepsToAdd > 0)
		{
			for (var i = 0; i < numberOfStepsToAdd; i++)
			{
				var td = this.row.insertCell(this.row.cells.length-1);
				
				if(advisor.advisorSkinType != "GreenPrint")
				{
					td.innerHTML = '<span class="stepPrefix">Step </span>' + (this.row.cells.length-2);
				}
				else
				    td.innerHTML=".";
				
				if(advisor.advisorSkinType != "GreenPrint")
				    td.className = "stepIncompleted";
				else
				    td.className = "stepIncompletedGp";
				    
				
				    
				
			}
		}
		else if (numberOfStepsToAdd < 0)
		{
			for (var i = numberOfStepsToAdd; i < 0; i++)
				this.row.deleteCell(this.row.cells.length-2);
		}
	}
	    
	this.update = function()
	{
		this.sync();
		var isFutureStep = false;
		for(var i=0; i<this.stepHistoryObject.stepList.length; i++)
		{
			var stepId = this.stepHistoryObject.stepList[i];
			var td = this.row.cells[i+1];
			var isLastStep = i == this.stepHistoryObject.stepList.length - 1;
			var isFirstStep = i == 0;
			if (typeof(Debug)=="object" && typeof("Debug.LoggerUrl")=="string")
			{
				td.title = stepId;
			}			
			if (advisor.advisorSkinType == "SilverBlack")
			{
			    // The no. of td are calculated here and the width is set
				td.width = (85 / this.stepHistoryObject.stepList.length) + '%';
			}
			var currentStepId = currentStep==null ? null : currentStep.id;
			if (stepId==currentStepId) {
				if(advisor.advisorSkinType != "GreenPrint")
				    {
				        td.className = "stepCurrent";				        				        
				    }
				else
				    {
				        td.className = "stepCurrentGp";					       		        
				    }
				    
				// if it's current step, clicking does not do
				// anything
				td.onclick= "";
				// mark all following steps as future steps
				isFutureStep = true;
			} else if (this.stepHistoryObject.stepVisitedList[stepId]) {
				if(advisor.advisorSkinType != "GreenPrint")
				{
				    td.className = "stepCompleted";
				}
				else
				{
				    td.className = "stepCompletedGp";				    
				}
				if (!isFutureStep)
					td.className += " stepPrevious";
				if (isFutureStep)
				// if this step has been visited before, but it's
				// after the current step, run jumpToStep (to
				// validate the steps in between)
					td.onclick= new Function("jumpToStep('" + stepId + "')");
				else
				// if this step has been visited before and it's
				// before current step, just open it (since
				// validation is not necessary)
					td.onclick= new Function("openStep('" + stepId + "', true)");
				
			} else {
				if(advisor.advisorSkinType != "GreenPrint")
				{
				    td.className = "stepIncompleted";
				}
				else
				{
				    td.className = "stepIncompletedGp";				    
				}
				// if this step has not been visited before, call
				// jumpToStep (to validate the steps in between)
				td.onclick= new Function("jumpToStep('" + stepId + "')");
			}
			if (isFirstStep)
				td.className += " stepFirst";
			if (isLastStep)
				td.className += " stepLast";
		}
	}
}

function addTraceLink(id)
{
	var a = document.getElementById('traceLink');
	if (a==null)
	{
		a = document.createElement('a');
		a.target = "_blank";
		a.innerHTML = "view trace";
		a.id = "traceLink";

		var div = document.createElement('div');
		div.className = "traceContainer";
		div.style.position = "absolute";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.padding = "3px";
		div.style.backgroundColor = "#eee";
		div.appendChild(a);

		document.body.appendChild(div);
	}
	a.href = "Reports/Trace.aspx?AdvisorRequestId=" + id;
}


    function ChangeFlash(flashPath)
    {
        
        
    }


 
