/***   The data comes from an as yet unpublished survey by Branco Milanovic and expresses
*   world incomes from 2002 in '2005 international dollars'. This means that if you enter a salary earned in the US
*   in 2005, it would work perfectly to tell you where you ranked then in terms of perchasing power parity (PPP).*   I have adjusted for inflation since 2005 (10.3%) which provides a rough translation of a 2009 income.*   It is still not quite correct as it is still using the 2002 distribution (today's is probably more skewed)*   so richness percentages for high earners are really slightly lower than indicated and for low earners are higher
*   than indicated. Also, while the currency is converted at today's market rates to 2009 US dollars*   (then via the 1.103 factor into 2005 US dollars), it should also factor in which country you are living in,
*   as this is needed for a true PPP calculation (dollars go further in Egypt than in the USA or UK), but it works fine
*   now for the richest countries, which are where most of the site users will come from.
**   Based on a script by Poke ( http://www.pokelondon.com/ ) at http://www.globalrichlist.com/
*   but improved by allowing for exchange rates, household size, inflation, an updated data-set (2002 rather than 1993),
*   and using the income at each centile rather than the income-share of the range between the listed centiles
*   (which gives the wrong answers...).*/// declare variablesvar strInput;var strOutput;var income;
var percentPoorer;var percentRicher;var minDollarToCalc = 231;var maxDollarToCalc = 35386;var conversionTo2005 = 1.103; // i.e. 10.3% inflation from 2005 to 2009: http://inflationdata.com/inflation/Inflation_Rate/CurrentInflation.aspvar medianIncome = 999;// Setup relationship between money and populationcentileArray = new Array( 0,     5,    10,    15,    20,    25,    30,    35,    40,    45,     50,     55,     60,     65,     70,     75,     80,     85,     90,      95,      98,      99);incomeArray  = new Array(50,   231,   305,   370,   417,   483,   551,   631,   731,   852,    999,   1199,   1405,   1710,   2247,   2834,   4249,   7022,  11217,   17001,   25601,   35386); //old       = new Array( 0,     5,    10,    15,    20,    25,    30,    35,    40,    45,     50,     55,     60,     65,     70,     75,     80,     85,     90,      95,      99,  99.5,  99.8, 99.85);
//old       = new Array(50, 238.1, 318.1, 372.9, 432.1, 495.8, 586.0, 657.7, 741.9, 883.2, 1044.1, 1164.9, 1505.0, 1856.8, 2326.8, 3005.6, 4508.1, 6563.3, 9109.8, 13240.7, 24447.1, 39434, 60947, 71700); 
// returns array with//  [0] = SLOPE, m//  [1] = y-int, b//  [2] = Rfunction calcTrendRSquare (arrX, arrY) {        var n = arrX.length;        var sumX = 0;    var sumY = 0;    var sumXY = 0;    var sumX2 = 0;    var sumY2 = 0;            for (var i = 0; i < arrX.length; i++){        sumX += arrX[i];        sumY += arrY[i];        sumXY += arrX[i] * arrY[i];        sumX2 += Math.pow(arrX[i],2);        sumY2 += Math.pow(arrY[i],2);    }        var sumX2_2 = Math.pow(sumX,2);     var sumY2_2 = Math.pow(sumY,2);        var slope_m = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX2_2);    var yInt_b  = (sumY - slope_m * sumX) / n;    var r       = (n * sumXY - sumX * sumY) / Math.sqrt((n * sumX2 - sumX2_2) * (n * sumY2 - sumY2_2));        var returnArray = new Array(slope_m, yInt_b, r);     return returnArray;}                          function getPercentPoorer(bIndex, income) {                // get the R-square Trend        var people = new Array(centileArray[bIndex], centileArray[bIndex+1]);        var money  = new Array(incomeArray[bIndex], incomeArray[bIndex+1]);                var rSquare = calcTrendRSquare(people, money);                var percentPoorer = ((income + (rSquare[1]*-1)) / rSquare[0]);		        return percentPoorer;}    // if submittedfunction howRich() {	//  reset the output	document.howRichCalculator.richPercentage.value = "";	// error check	if (document.howRichCalculator.annualIncome.value == "") {		return false;	}	// error check	if (document.howRichCalculator.householdSize.value == "") {		document.howRichCalculator.householdSize.value = "1";	}	if (document.howRichCalculator.householdSize.value == "0") {		document.howRichCalculator.householdSize.value = "1";	}		// the input	strInput = document.howRichCalculator.annualIncome.value;	currency = document.howRichCalculator.annualIncomeCurrency.value;	householdSize = document.howRichCalculator.householdSize.value;		// remove thousands separators	strInput = strInput.replace(",","");	strInput = strInput.replace(",","");	strInput = strInput.replace(",","");	strInput = strInput.replace(" ","");	strInput = strInput.replace(" ","");	strInput = strInput.replace(" ","");		// convert to a number	income = strInput * 1; 		// divide by the number of people	income = income / householdSize; 		// convert currency so we can calculate with US dollars.	income = income * getCurrencyFactor(currency);		// convert currency from current US dollars to 2005 US dollars.	income = income / conversionTo2005;		// validate input		if (isNaN(income)) {		// if not valid		document.howRichCalculator.richPercentage.value = "";		document.howRichCalculator.richPercentage2.value = "";
		document.howRichCalculator.richFactor.value = "";
		document.howRichCalculator.richFactor2.value = "";
			}
	else {		        // get the index to play with		var blockIndex = 0;        for (var i = 0; i < incomeArray.length; i++) {            if(income < incomeArray[i]) {                blockIndex = i-1;                break;            }        }		percentPoorer = getPercentPoorer(blockIndex, income);					// calculate percentage			percentageRicher = 100 - percentPoorer;						strOutput = percentageRicher.toPrecision(2);				if (income <= minDollarToCalc)		{ // no output if income too low            strOutput = "******";		} 		else if (income >= maxDollarToCalc )		{  // roughened output if income too high			strOutput = "< 1.0";		}						document.howRichCalculator.richPercentage.value = strOutput;		richFactor = income / medianIncome;		if (richFactor < 10)		{			strFactor = richFactor.toFixed(1);		}		else		{			strFactor = richFactor.toFixed(0);		}				document.howRichCalculator.richFactor.value = strFactor;
		
		//********************************************
		// repeat the above with 90% of your income...
		
		income = income * 0.9;
		
        // get the index to play with
		blockIndex = 0;
        for (i = 0; i < incomeArray.length; i++) {
            if(income < incomeArray[i]) {
                blockIndex = i-1;
                break;
            }
        }

		percentPoorer = getPercentPoorer(blockIndex, income);
			
		// calculate percentage	
		percentageRicher = 100 - percentPoorer;
				
		strOutput = percentageRicher.toPrecision(2);
		
		if (income <= minDollarToCalc)
		{ // no output if income too low
            strOutput = "******";
		} 
		else if (income >= maxDollarToCalc )
		{  // roughened output if income too high
			strOutput = "< 1.0";
		}		
		
		document.howRichCalculator.richPercentage2.value = strOutput;

		richFactor = income / medianIncome;
		if (richFactor < 10)
		{
			strFactor = richFactor.toFixed(1);
		}
		else
		{
			strFactor = richFactor.toFixed(0);
		}
		
		document.howRichCalculator.richFactor2.value = strFactor;
	}}




function calcPreTax(threshold, incomeLevels, taxPercents, maxIncomeLevel) {        var incomeLevel;    var nextIncomeLevel;	var taxPercent;	var preTaxSoFar = 0;	var postTaxSoFar = 0;      for (var i = 0; ; i++){        incomeLevel = incomeLevels[i];        nextIncomeLevel = incomeLevels[i+1];		taxPercent = taxPercents[i];		if ( (incomeLevel == maxIncomeLevel) || ((nextIncomeLevel - incomeLevel) * (100 - taxPercent) / 100 + postTaxSoFar > threshold) )		{			preTaxSoFar += (threshold - postTaxSoFar) / (100 - taxPercent) * 100;			break;		}		else		{			postTaxSoFar += (nextIncomeLevel - incomeLevel) * (100 - taxPercent) / 100;			preTaxSoFar += (nextIncomeLevel - incomeLevel);		}    }		return preTaxSoFar;    }// Need to take into account the US restrictions of charitable donationsfunction goldPledge(){var currentAge = numval(document.goldCalculator.currentAge.value);var retirementAge = numval(document.goldCalculator.retirementAge.value);var currency = document.goldCalculator.currency.value;var averageIncome = numval(document.goldCalculator.averageIncome.value);var threshold = numval(document.goldCalculator.threshold.value);var taxCountry = document.goldCalculator.taxCountry.value;var annualDonation = 0;var totalEarnings = 0;
var totalDonation = 0;
var livesSaved = 0;
var dalys = 0;
var schoolYears = 0;// Set up tax brackets

// for 2009-10 tax yearincomeLevelsAU = new Array(0, 6000, 35000, 80000, 180000, -1, -1, -1);taxPercentsAU  = new Array(0,   15,    30,    38,     45, -1, -1, -1);maxIncomeLevelAU = 95000;

// for 2010 tax year, using 2009 personal exemption (3650) and 2009 standard deduction (5700)
incomeBaseUS = 3650+5700;incomeLevelsUS = new Array(0, incomeBaseUS+0,	incomeBaseUS+8375, incomeBaseUS+34000, incomeBaseUS+82400, incomeBaseUS+171850, incomeBaseUS+373650, -1);taxPercentsUS  = new Array(0,             10,                  15,                 25,                 28,                  33,                  35, -1);maxIncomeLevelUS = incomeBaseUS+373650;

// for 2009-10 and 2010-11 tax years
incomeBaseUK = 6475;incomeLevelsUK = new Array(0, incomeBaseUK,	incomeBaseUK+37400, -1, -1, -1, -1, -1);taxPercentsUK  = new Array(0,           20,                 40, -1, -1, -1, -1, -1);maxIncomeLevelUK = incomeBaseUK+37400;currencyFactor = getCurrencyFactor(currency);if ((currentAge >= 0) && (retirementAge >= currentAge) && (threshold >= 0) && (averageIncome >= threshold))   {   if (taxCountry == "au")   {   		threshold = threshold * currencyFactor / aud; // convert to local currency   		preTaxThreshold = calcPreTax(threshold, incomeLevelsAU, taxPercentsAU, maxIncomeLevelAU);		preTaxThreshold = preTaxThreshold / currencyFactor * aud; // convert to nominated currency   }   else if (taxCountry == "uk")   {    	threshold = threshold * currencyFactor / gbp; // convert to local currency   		preTaxThreshold = calcPreTax(threshold, incomeLevelsUK, taxPercentsUK, maxIncomeLevelUK); 		preTaxThreshold = preTaxThreshold / currencyFactor * gbp; // convert to nominated currency   }   else if (taxCountry == "us")   {    	threshold = threshold * currencyFactor / usd; // convert to local currency   		preTaxThreshold = calcPreTax(threshold, incomeLevelsUS, taxPercentsUS, maxIncomeLevelUS);		preTaxThreshold = preTaxThreshold / currencyFactor * usd; // convert to nominated currency   }   annualDonation = averageIncome - preTaxThreshold;   totalEarnings = averageIncome * (retirementAge - currentAge);
   totalDonation = (averageIncome - preTaxThreshold) * (retirementAge - currentAge);   livesSaved = totalDonation * currencyFactor / pricePerLifeSaved();   dalys = totalDonation * currencyFactor / pricePerDALY();
   schoolYears = totalDonation * currencyFactor / pricePerSchoolYear();
   document.goldCalculator.annualDonation.value = formatNumber(annualDonation,0,0);   document.goldCalculator.totalEarnings.value = formatNumber(totalEarnings,0,0);
   document.goldCalculator.totalDonation.value = formatNumber(totalDonation,0,0);   document.goldCalculator.livesSaved.value = formatNumber(livesSaved,0,0);   document.goldCalculator.dalys.value = formatNumber(dalys,0,0);
   document.goldCalculator.schoolYears.value = formatNumber(schoolYears,0,0);
   }else   {      document.goldCalculator.annualDonation.value = "";      document.goldCalculator.totalEarnings.value = "";
      document.goldCalculator.totalDonation.value = "";
      document.goldCalculator.livesSaved.value = "";
      document.goldCalculator.dalys.value = "";
      document.goldCalculator.schoolYears.value = "";
   }}function silverPledge(){var currentAge = numval(document.silverCalculator.currentAge.value);var retirementAge = numval(document.silverCalculator.retirementAge.value);var currency = document.silverCalculator.currency.value;var averageIncome = numval(document.silverCalculator.averageIncome.value);var percentage = numval(document.silverCalculator.percentage.value);
var totalEarnings;var totalDonation;var livesSaved;var dalys;var schoolYears;var currencyFactor = getCurrencyFactor(currency);if ((currentAge >= 0) && (retirementAge >= currentAge) && (averageIncome >= 0) && (percentage >= 0) && (percentage <= 100))   {
      totalEarnings = (retirementAge - currentAge) * averageIncome;      totalDonation = totalEarnings * percentage / 100;	  	  livesSaved = totalDonation * currencyFactor / pricePerLifeSaved();	  dalys = totalDonation * currencyFactor / pricePerDALY();	  schoolYears = totalDonation * currencyFactor / pricePerSchoolYear();      document.silverCalculator.totalEarnings.value = formatNumber(totalEarnings,0,0);
      document.silverCalculator.totalDonation.value = formatNumber(totalDonation,0,0);      document.silverCalculator.livesSaved.value = formatNumber(livesSaved,0,0);      document.silverCalculator.dalys.value = formatNumber(dalys,0,0);      document.silverCalculator.schoolYears.value = formatNumber(schoolYears,0,0);   }else   {      document.silverCalculator.totalEarnings.value = "";
      document.silverCalculator.totalDonation.value = "";      document.silverCalculator.livesSaved.value = "";      document.silverCalculator.dalys.value = "";
      document.silverCalculator.schoolYears.value = "";
   }}