var currentPage = 2;
var investmentMidpoint = 0;  //Mid-point taken from total initial investment and used to ensure user does not request income exceeding specific amounts.
var recurringIncome = 0;
var Pur = {}

function gotoPage(nextPage) {

    var missing = [];
    var currentSection = document.getElementById('section' + currentPage);
    
    //Only validate page fields when going foward in the wizard.
    if(currentPage<nextPage) {
        switch(currentPage) {
            case 1:
                //Nothing to do here. Navigating from intro page.
                break;
            case 2:
	            missing = validateWhatIKnow();
	            break;
            case 3:
                missing = validateWhatIHave();
                break;
            case 4:
                missing = validateWhatIWant();
                break;
            case 5:
                missing = validateWhenIWant();
                break;
            case 6:
                missing = validateHowBadlyIWantIt();
                break;
        }
    }

    if(missing!=null && missing.length==0) {
        if(nextPage==7) {
            //submit form rather than hide/show pages
            compileProfileData();
            document.getElementById('JSON').value = Pur.toJSONString();
            document.forms[0].submit();
        } else {
            //hide current, show next
            if(currentPage!=1) {
                toggleErrorContainer("", currentPage);
            }
    	    var nextSection = document.getElementById('section' + nextPage);
	        new Effect.Fade(currentSection);
    	    new Effect.Appear(nextSection,{duration:0,delay:0});
    	    currentPage = nextPage;
    	}
    } else {
        //Show errors.
        var msg = "";
        if(missing.length==1) {
            msg = "Question ";
        } else {
            msg = "Questions ";
        }

        var separator = "";
        var and = "";
        for(var i=0; i<missing.length; ++i) {
            msg += separator + and + missing[i];
            separator = ", ";
            if(missing.length==2) {
                separator = " and ";
            } else if (i==(missing.length-2)) {
                separator = ", and ";
            }
        }
        msg += " must be completed before continuing.";
        toggleErrorContainer(msg, currentPage);
       
    }  
}

function toggleErrorContainer(errorMessage, id) {

    var errorContainer = document.getElementById('error' + id);
    if(errorMessage==null || errorMessage=="") {
        errorContainer.className = "hiddenErrorContainer";        
        errorMessage = "";
    } else {
        errorContainer.className = "errorContainer";        
    }

    if(document.all) {
         errorContainer.innerText = errorMessage;
    } else {
        errorContainer.textContent = errorMessage;
    }

}

function validateWhatIKnow() {

    var missing = [];

    ensureSelectionHasBeenMade(missing, 'residence', 4, 1);
    ensureSelectionHasBeenMade(missing, 'investmentknowledge', 4, 2);
    ensureSelectionHasBeenMade(missing, 'investstyle', 4, 4);

    return missing;
}

function validateWhatIHave() {
   var missing = [];
    
    ensureSelectionHasBeenMade(missing, 'networth', 6, 1);
    ensureSelectionHasBeenMade(missing, 'income', 6, 2);
    ensureSelectionHasBeenMade(missing, 'initialinvestment', 6, 3);
    ensureSelectionHasBeenMade(missing, 'homeowner', 4, 4);
    ensureSelectionHasBeenMade(missing, 'homeequity', 4, 5);
    ensureSelectionHasBeenMade(missing, 'netinvestment', 3, 6);
    
    if(missing.length==0) {
        //Determine the average initial investment which will be used to display a warning when 
        //clients request periodic income larger than the average initial investment.
        var found = false;
        investmentMidpoint = 0;
        recurringIncome  = 0;
        for(var i=1; i<=6 && !found; ++i) {
            var e = document.getElementById('initialinvestment' + i);
            found = e.checked;
            if(found) {
                switch(i) {
                    case 1:
                        investmentMidpoint = 25000;
                        break;
                    case 2:
                        investmentMidpoint = 75000;
                        break;
                    case 3:
                        investmentMidpoint = 175000;
                        break;
                    case 4:
                        investmentMidpoint = 500000;
                        break;
                    case 5:
                        investmentMidpoint = 1125000;
                        break;
                    case 6:
                        investmentMidpoint = -1;
                        break;
                }
                if(investmentMidpoint>0) {
                    recurringIncome = investmentMidpoint * 0.04; //4% of total investment
                }
            }
        }
    }
    
    return missing;
}

function validateWhatIWant() {

    var missing = [];

    for(var i=1; i<=3; ++i) {
        var e = document.getElementById('goal' + i);
        var w = document.getElementById('goal' + i + 'wrapper');
        var goal = null;
        var ok = false;
        
        if(e.value != null && e.value != "") {
            try {
                goal = parseFloat(e.value);
                if(goal == eval(e.value)) {
                    ok = true;
                }
            } catch(ex) {
                alert(ex);
            }
        }
        
        if(!ok)
            missing.push('Goal ' + i);
            
        toggleBackground(ok, 'goal' + i);
            
    }

    var cashFlows = ['shortTermAmount', 'midTermAmount', 'longTermAmount'];
    var warningIDs = ['shortTermWarning', 'midTermWarning', 'longTermWarning'];
    var performComparisonToInitialInvestment = (recurringIncome > 0);
    
    var pauseRequired = false;
    
    for(var i=0; i<cashFlows.length; ++i) {
        var e = document.getElementById(cashFlows[i]);
        var w = document.getElementById(cashFlows[i] + 'Wrapper');

        //warning large amount
        var wla = document.getElementById(warningIDs[i]);
        wla.innerHTML = '';

        if(e.value!='') {
            var amount = null;

            try {
                amount = parseInt(e.value);
                if(performComparisonToInitialInvestment && amount>=investmentMidpoint) {
                    wla.innerHTML = "<span style='color:red;font-weight:bold'>This amount exceeds your total investment and may not be attainable.</span>";
                    pauseRequired = true;
                }
            } catch(ex) {
            }
            
            if(isNaN(amount)) {
                missing.push(w);
            } else if(eval(e.value)!=amount) {
                missing.push(w);
            }
                
        }
    }

    if(pauseRequired && missing.length==0) {
        pauseForWarning(1500);
    }

    return missing;
}

function validateWhenIWant() {
    var missing = [];
    var found = null;
    var performComparisonToInitialInvestment = (recurringIncome > 0);
    var pauseRequired = false;
    
    ensureSelectionHasBeenMade(missing, 'investmenthorizon', 5, 1);
    ensureSelectionHasBeenMade(missing, 'incomehorizon', 5, 2);
        
    var e = document.getElementById('oneYearAmount');
    var we = document.getElementById('oneYearWarning');
    we.innerHTML = "";

    var amount = 0;
    if(e.value!='') {
        try {
            amount = parseInt(e.value);
            if(performComparisonToInitialInvestment && (amount>recurringIncome)) {
                we.innerHTML = "<span style='color:red;font-weight:bold'>This amount is significant relative to your total investment and may not be attainable.</span>";
                pauseRequired = true;
            }
        } catch(ex) {
        }
    }
    if(isNaN(amount)) {
        missing.push(document.getElementById('oneyearwrapper'));        
    }

    if(pauseRequired && missing.length==0) {
        pauseForWarning(1500);
    }


    
    return missing;
}

function validateHowBadlyIWantIt() {

    var missing = [];
    var found = null;

    ensureSelectionHasBeenMade(missing, 'riskmeans', 5, 1);

    if(document.getElementById('maxdownside').value=='') {
        toggleBackground(false, 'riskchart');         
        missing.push(2);
    } else {
        toggleBackground(true, 'riskchart'); 
    }
    
    ensureSelectionHasBeenMade(missing, 'downsideall', 6, 3);
    ensureSelectionHasBeenMade(missing, 'basicneeds', 4, 4);
    ensureSelectionHasBeenMade(missing, 'maxloss', 4, 5);

    return missing;
}

function compileProfileData() {

    var e = null;
    var found = false;
    var elements = null;

    //
    // What I Know
    //
    Pur.Resident = "";
    found = false;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('residence' + i);
        found = e.checked;
        if(found) {
            Pur.Resident = e.value; 
        }
    }
    
    Pur.InvestmentKnowledge = 0;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('investmentknowledge' + i);
        found = e.checked;
        if(found) {
            Pur.InvestmentKnowledge = eval(e.value);
        }
    }
    
    Pur.InvestedIn = {};
    for(var i=1; i<=4; ++i) {
        e = document.getElementById('investedin' + i);
        switch(i) {
            case 1:
                Pur.InvestedIn.GIC = e.checked;
                break;
            case 2:
                Pur.InvestedIn.MutualFunds = e.checked;
                break;
            case 3:
                Pur.InvestedIn.StocksBonds = e.checked;
                break;
            case 4:
                Pur.InvestedIn.OptionsFutures = e.checked;
                break;
        }
    }
    
    Pur.InvestmentStyle = "";
    found = false;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('investstyle' + i);
        found = e.checked;
        if(found) {
            Pur.InvestmentStyle = e.value; 
        }
    }
    
    //
    // What I Have
    //
    elements = ['networth', 'income', 'initialinvestment'];
    for(var c=0; c<3; ++c) {
        found = false;
        for(var i=1; i<=6 && !found; ++i) {
            e = document.getElementById(elements[c] + i);
            found = e.checked;
            if(found) {
                switch(c) {
                    case 0:
                        Pur.NetWorth = eval(e.value);
                        break;
                    case 1:
                        Pur.Income = eval(e.value);
                        break;
                    case 2:
                        Pur.InitialInvestment = eval(e.value);
                        break;
                }
            }
        }    
    }

    found = false;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('homeequity' + i);
        found = e.checked;
        if(found) {
            Pur.HomeEquity = eval(e.value); 
        }
    }

    found = false;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('homeowner' + i);
        found = e.checked;
        if(found) {
            Pur.HomeOwner = eval(e.value); 
        }
    }



    found = false;
    for(var i=1; i<=6 && !found; ++i) {
        e = document.getElementById('netinvestment' + i);
        found = e.checked;
        if(found) {
            Pur.NetInvestment = eval(e.value); 
        }
    }

    e = document.getElementById('registeredweight');
    Pur.TaxShelteredInvestment = eval(e.options[e.selectedIndex].value);

    e = document.getElementById('taxableweight');
    Pur.TaxableInvestment = eval(e.options[e.selectedIndex].value);
    
    //
    // What I Want
    //

    for(var i=1; i<=3; ++i) {
        e = document.getElementById('goal' + i);
        switch(i) {
            case 1:
                Pur.Goal1 = eval(e.value);
                break;
            case 2:
                Pur.Goal2 = eval(e.value);
                break;
            case 3:
                Pur.Goal3 = eval(e.value);
                break;
        }
    }



    elements = ['shortTerm', 'midTerm', 'longTerm'];
    Pur.CashFlows = {};
    for(var c=0; c<elements.length; ++c) {
        var eAmount = document.getElementById(elements[c] + 'Amount');
        var eCurrency = document.getElementById(elements[c] + 'Currency');
        var amount = parseInt(eAmount.value);
        if(amount==null || isNaN(amount)) {
            amount = 0;
        }
        
        var currency = eCurrency.options[eCurrency.selectedIndex].value;
        switch(c) {
            case 0:
                Pur.CashFlows.ShortTerm = {};
                Pur.CashFlows.ShortTerm.Amount = amount;
                Pur.CashFlows.ShortTerm.Currency = currency;
                break;
            case 1:
                Pur.CashFlows.MidTerm = {};
                Pur.CashFlows.MidTerm.Amount = amount;
                Pur.CashFlows.MidTerm.Currency = currency;
                break;
            case 2:
                Pur.CashFlows.LongTerm = {};
                Pur.CashFlows.LongTerm.Amount = amount;
                Pur.CashFlows.LongTerm.Currency = currency;
                break;
        }
    }

    //
    // When I Want It
    //
    found = false;
    Pur.InvestmentHorizon = 0;
    for(var i=1; i<=5 && !found; ++i) {
        e = document.getElementById('investmenthorizon' + i);
        found = e.checked;
        if(found) {
            Pur.InvestmentHorizon = eval(e.value); 
        }
    }

    found = false;
    Pur.IncomeHorizon = 0;
    for(var i=1; i<=5 && !found; ++i) {
        e = document.getElementById('incomehorizon' + i);
        found = e.checked;
        if(found) {
            Pur.IncomeHorizon = eval(e.value); 
        }
    }

    Pur.CashFlows.OneYearIncome = {};
    var eAmount = document.getElementById('oneYearAmount');
    var eCurrency = document.getElementById('oneYearCurrency');
    var amount = parseInt(eAmount.value);
    if(amount==null || isNaN(amount)) {
        Pur.CashFlows.OneYearIncome.Amount = 0;
    } else {
        Pur.CashFlows.OneYearIncome.Amount = amount;
    }
    Pur.CashFlows.OneYearIncome.Currency = eCurrency.options[eCurrency.selectedIndex].value;

    //
    // How Badly I Want It
    //
    found = false;
    Pur.RiskMeans = 0;
    for(var i=1; i<=5 && !found; ++i) {
        e = document.getElementById('riskmeans' + i);
        found = e.checked;
        if(found) {
            Pur.RiskMeans = eval(e.value); 
        }
    }

    found = false;
    Pur.DownSideAll = 0;
    for(var i=1; i<=5 && !found; ++i) {
        e = document.getElementById('downsideall' + i);
        found = e.checked;
        if(found) {
            Pur.DownSideAll = eval(e.value); 
        }
    }

    found = false;
    Pur.BasicNeeds = 0;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('basicneeds' + i);
        found = e.checked;
        if(found) {
            Pur.BasicNeeds = eval(e.value); 
        }
    }

    found = false;
    Pur.MaxLoss = 0;
    for(var i=1; i<=4 && !found; ++i) {
        e = document.getElementById('maxloss' + i);
        found = e.checked;
        if(found) {
            Pur.MaxLoss = eval(e.value); 
        }
    }





}

function setValue(n) {

    var e1 = document.getElementById("goal1");
    var e2 = document.getElementById("goal2");
    var e3 = document.getElementById("goal3");

    var g1 = getNumber(e1.value);
    var g2 = getNumber(e2.value);
    var g3 = getNumber(e3.value);

    switch(n) {
        case 1:
            if(g1>100) {
                g1 = 100; 
                g2 = 0; 
                g3 = 0;
            } else {
                var rem = 100-g1;
                g2 = rem * 0.6;
                g3 = rem * 0.4;
            }
            break;

        case 2:
            if(g2>100) {
                g2 = 100;
                g1 = 0;
                g3 = 0;
            } else {
                var rem = 100-g2;
                if(rem<g1) {
                    g1 = rem;
                    g3 = 0;
                } else {
                    g3 = 100 - (g1 + g2);
                }
            }
            break;
            
        case 3:
            if(g3>=100) {
            	g3 = 100;
                g2 = 0;
                g1 = 0;
            } else {
                var rem = 100-g3;
                g2 = rem / 2;
                g1 = rem - g2;
            }
            break;
    }

    g1 = Math.round(g1*10)/10;
    g2 = Math.round(g2*10)/10;
    g3 = Math.round(g3*10)/10;
    
    e1.value = g1;
    e2.value = g2;
    e3.value = g3;
    
    return true;
    
}

function getNumber(text) {
    
    var s = "";
    var alreadyHaveDecimal = false;
    for(var i=0; i<text.length; ++i) {
        var c = text.substring(i,i+1);
        if("0"<=c && c<="9") {
            s += c;
        } else if(c=="." && !alreadyHaveDecimal) {
            s += c;
            alreadyHaveDecimal = true;
        }
    }
    
    if(isNaN(s)) {
        s=0;
    }

    return parseFloat(s);
}

//This function is called when loading completed profile.
function updateState(n) {
    validateWhatIKnow();
    validateWhatIHave();
    validateWhatIWant();
    validateWhenIWant();
    validateHowBadlyIWantIt();
    selectPortfolio(n);
}



function ensureSelectionHasBeenMade(missing, cName, max, question) {

    var found = false;    
    for(var i=1; i<=max && !found; ++i) {
        var e = document.getElementById(cName + i);
        found = e.checked;
    }

    if(!found) {
        missing.push(question);
    }
    toggleBackground(found, cName);
}

function toggleBackground(ok, name) {
    document.getElementById(name + 'wrapper').style.backgroundColor  = ok ? "": "#FECFCF";
}


//Enable selection of a radio button from a control containing the radio button.
function selectRadio(id) {
    document.getElementById(id).checked=true;
}

//Toggle the state of a checkbox that is contained within an object
function toggleCheckBox(id) {
    var e=document.getElementById(id);
    e.checked = !e.checked;
}

//Position viewable area
function scrollToElement(el,scrollDiv){
  var selectedPosX = 0;
  var selectedPosY = 0;
  while(el != null){
    selectedPosX += el.offsetLeft;
    selectedPosY += el.offsetTop;
    el = el.offsetParent;
  }
  scrollDiv.scrollTop = selectedPosY-200;
}

function sanitizeTaxableRegisteredLists(lst,list2){
	var tlist = document.getElementById(list2);
	var regamt = lst.options[lst.selectedIndex].value;
	var taxamt = tlist.options[tlist.selectedIndex].value;

	var allowableindex = 9-lst.selectedIndex;
	index = tlist.selectedIndex;
	if(index>allowableindex)
	index = allowableindex;

	tlist.options.length = 0;

	for(var i=0;i<=allowableindex;i++){
	  var option = document.createElement('option');
	  if(i==0){
		  option.text = 'Less than 10%';
		  option.value = 10;
	  }else if(i==9){
		  option.text = 'Greater than 90%';
		  option.value = 100;
	  }else{
	  		var val = parseInt(i*10);
		  option.text = val + '% to ' + (10+val) +'%';
		  option.value = (10+val);
	  }
	  if(index==i)
		  option.selected = true;
	  try {
	    tlist.add(option, null); // standards compliant; doesn't work in IE
	  }catch(ex) {
	    tlist.add(option); // IE only
	  }
	}

}

function selectPortfolio(n) {

    var downSides = [0, -30, -10, -25, -15, -20, -5]; //dummy downside value added at index=0 to bypass subtracting of 1 in other calculations below.
    var selectedPortolio = document.getElementById('checkp' + n);
    
    document.getElementById('maxdownside').value = downSides[n];

    for(var i=1; i<=6; ++i) {
        var e = document.getElementById('checkp' + i);
        if(n==i) {
            e.style.visibility = "visible";
        } else {
            e.style.visibility = "hidden";
        }
    }
    
    Pur.Portfolio = n;
    Pur.MaxDownSide = downSides[n];
    Pur.MaximumAnnualLoss =  downSides[n] / 100;
    
    var pctdrop = document.getElementById('pctdrop');
    pctdrop.innerHTML = '<span style="color:red">The maximum annual paper loss I am willing to accept is <b>' + Pur.MaxDownSide +'%<' + '/b></span>.' ;
    var dropAmount = document.getElementById('dropAmount');
    dropAmount.innerHTML = -Pur.MaxDownSide + "%&#032;";

}


function checkDigit(e){
    var keynum
    var keychar
    var numberRegex

    if(window.event){ // IE
            keynum = e.keyCode
    }else if(e.which){ // Netscape/Firefox/Opera
            keynum = e.which
    }
    //alert("keynum " +keynum +"\n" + "keychar " + keychar);
    return ( (keynum>=96 && keynum<=105) || (keynum>=48 && keynum<=57) || (keynum==8 || keynum==46 || keynum==177 || keynum==110) );
}

function pauseForWarning(ms) {
    var start = new Date();
    
    while(new Date() - start < ms) ;
}


function checkHomeFields(name) {

	if(name.indexOf("homeequity")>-1) {
		if(document.getElementById("homeowner4").checked) {
			document.getElementById("homeequity1").checked = true;
		} else {
			document.getElementById(name).checked = true;
		}
	} else {
		if(name=="homeowner4") {
			document.getElementById("homeequity1").checked = true;
			document.getElementById(name).checked = true;
		} else {
			document.getElementById(name).checked = true;
		}
	}
	
}