(function() {

	var glow;

	gloader.load(
	 ["glow", "1", "glow.dom", "glow.events"],
	 {
		async: false,
		onLoad: function(fetchedGlow) {
			//write glow back to the variable we defined above
			glow = fetchedGlow;
			//call the init function when ready
			glow.ready(init);
		}
	 }
	);
	
function init() {
	inf_init();
}
	
	
var linedata3 = new Array();
var linedata4 = new Array();
var myValues = new Array();
var myAnnValues = new Array();

//* = derived values
myAnnValues[0] = ['A1'];//mortgage interest payments*
myAnnValues[1] = ['B1'];//rent
myAnnValues[2] = ['C1'];//food
myAnnValues[3] = ['D1'];//meals out
myAnnValues[4] = ['E1'];//alcohol
myAnnValues[5] = ['F1'];//tobacco
myAnnValues[6] = ['G1'];//phone charges
myAnnValues[7] = ['H1'];//clothing and footwear
myAnnValues[8] = ['I1'];//fuel for transport
myAnnValues[9] = ['S1'];//heating and lighting
myAnnValues[10] = ['J1'];//rail and bus fares
myAnnValues[11] = ['K1'];//child care services
myAnnValues[12] = ['L1'];//chemists goods
myAnnValues[13] = ['M1'];//council tax
myAnnValues[14] = ['N1'];//other expenditure
myAnnValues[15] = ['O1'];//water charges
myAnnValues[16] = ['T1'];//housing repairs, maintenance and diy
myAnnValues[17] = ['U1'];//vehicle repair/maintenance
myAnnValues[18] = ['Q1'];//vehcile tax and insurance
myAnnValues[19] = ['P1'];//uk and foreign holidays and other airfares
myAnnValues[20] = ['R1'];//furnishings and electrical goods
myAnnValues[21] = ['A2'];//est. annual house depreciation*
myAnnValues[22] = ['I2'];//estimated car expenditure*

var cw1 = new Array();
var cw2 = new Array();
var cw3 = new Array();
var cw4 = new Array();
//blank for calculated category weights from sw[1..4]



function inf_init(){
	PreLoad();
	CheckForm(1);
}

//calculates rpi category weights from section-level data
function PreLoad()	{

	// hiding the results before calculation
	
	glow.dom.get("p.preText").css("display", "none");

	for (k=0;k<catID.length;k++)	{
		myCat = catID[k];
		var total1 = 0;
		var total2 = 0;
		var total3 = 0;
		var total4 = 0;
		for (m=0;m<sectionID.length;m++)	{
			mySectionCat = sectionCat[m];
			if (mySectionCat == myCat)	{
				total1 = total1+eval(sw1)[m];
				total2 = total2+eval(sw2)[m];
				total3 = total3+eval(sw3)[m];
				total4 = total4+eval(sw4)[m];
			}
		}
		cw1[k] = total1;
		cw2[k] = total2;
		cw3[k] = total3;
		cw4[k] = total4;
	}
	
	glow.events.addListener(
	 glow.dom.get("a#infla_submitBtn"),
	 'click',
	 function() {
		CheckForm(2);
	 }
	);
}

//READS FORM VALUES TO ARRAY AND CALLS FUNCTION TO CALCULATE USER RATES
function CheckForm(t)	{
	//cycles through form and assigns values to inflation calculator categories.  Then re-runs calculation
	
	// deprecating this
	/*for (i=0;i<23;i++)	{
		var myBox = document.userInput.elements[i].value;
		myValues[i]=parseInt(myBox);
		
	}*/
	
	// added param "t" for differentiating between init call and button press call
	
	// including BBC Glow for DOM manipulation
	
	for (var i = 0; i < 23; i++) {
		myValues[i] = parseInt(glow.dom.get("#box"+i+" input").val());
	}
	
	CalcValues();
	
	// DEPR document.getElementById('resultsText').firstChild.data=linedata3[linedata3.length-1]+"%";
	if(linedata3[linedata3.length-1] > 0) {
		glow.dom.get("#resultsText").text("+" + linedata3[linedata3.length-1]+"%");
	} else {
		glow.dom.get("#resultsText").text(linedata3[linedata3.length-1]+"%");
	}
	
	
	/*
	p.preText {
		display: table;
	}

	p.preText#infla_comparison {
		display: block;
	}

	p.preText span {
		display: table-cell;
	}
	*/
	
	if (t == 2) {
		glow.dom.get("p.preText#infla_comparison").css("display", "block");
		glow.dom.get("p.preText").css("display", "inline");
		glow.dom.get("p.preText span").css("display", "inline");
		glow.dom.get("div.infla_addon_disabled").removeClass("infla_addon_disabled");
		//rangeOfRates only affects the big coloured number output at the bottom
		var rangeOfRates = [-4,-2,0,2];
		var correspondingColor = ["#6cc", "#369", "#fdeb03", "#969", "#f33"];
		for (var i = 0; i < rangeOfRates.length; i++) {
			if (linedata3[linedata3.length-1] > rangeOfRates[3]) {
				glow.dom.get(
				 "#resultsText"
				).css("color", correspondingColor[4]);
				break;
			} else if (linedata3[linedata3.length-1] < rangeOfRates[i]) {
				glow.dom.get(
				 "#resultsText"
				).css("color", correspondingColor[i]);
				break;
			} else {
				continue;
			}
		}
		putMarker(linedata3[linedata3.length-1]);
                var range = Math.floor((linedata3[linedata3.length-1])/2) + 1;
                if(range < 1){
                     range = 1;
                } else if (range > 5){
                     range = 5;
                }
                var mapFormLink = "/1/hi/business/7733901.stm?range=" + range;
                glow.dom.get("#islider p.mapformlink a").attr("href", mapFormLink);
	} else {
		// do nothing if called via init
	}
}

function putMarker(number) {
		//change the + value for alignment to move the scale around
       var alignment = (number * 40) + 228;
       if(alignment < -11){
              alignment = -11;
       } else if(alignment > 389) {
              alignment = 389;
       }
       glow.dom.get("div.infla_addon_enabled div#indicator_top").css("left", alignment + "px");
}


// Adding two new functions to help make life better for the fingers

function getBoxVal(ind) {
	boxVal = parseInt(glow.dom.get("#box"+ind+" input").val());
	return boxVal;
}

function putBoxVal(box, value) {
	glow.dom.get("#box"+box+" input").val(value);
}



//CALCULATES USER INFLATION RATES
function CalcValues()	{
	//estimates mortgage interest payments
	
	// DEPR myMortgage = parseInt(document.userInput.box24.value)*avgAnnualPay/avgMortgageVal;
	myMortgage = getBoxVal(24)*avgAnnualPay/avgMortgageVal;
	// DEPR document.userInput.box0.value=Math.round(myMortgage);
	putBoxVal(0, myMortgage);
	
	myValues[0]=myMortgage;
	myAnnValues[0][1]=myValues[0];//mortgage interest
	
	//calculates annual from  expenditure items on form
	for (i=1;i<13;i++) {
		myAnnValues[i][1]=(myValues[i]*12);
	}
	myAnnValues[13][1]=myValues[13];//Council Tax
	myAnnValues[14][1]=(myValues[14]*12);//other monthly expenditure
	for (i=15;i<20;i++) {
		myAnnValues[i][1]=myValues[i];
	}
	myAnnValues[20][1]=myValues[20];//big tag spedning

	//estimates house depreciation
	
	// DEPR var myAvgHousePrice=houseseries[document.userInput.list1.selectedIndex];
	var myAvgHousePrice = houseseries[glow.dom.get("#list1").val()];
	
	// DEPR myAnnValues[21][1] = parseInt(document.userInput.box23.value)*avgAnnualDep/myAvgHousePrice;
	myAnnValues[21][1] = getBoxVal(23)*avgAnnualDep/myAvgHousePrice;
	
	// DEPR document.userInput.box21.value=Math.round(myAnnValues[21][1]);
	putBoxVal(21,Math.round(myAnnValues[21][1]));
	

	//calculates monthly spend = needed for car expenditure estimation
	var myMonthlySpend = 0;
	for(i=2;i<13;i++) {
		myMonthlySpend=myMonthlySpend+myValues[i];
	}
	myMonthlySpend=myMonthlySpend+myValues[14];
	var myCar = ((myMonthlySpend+myValues[1])*12+myValues[0]+myAnnValues[21][1]+myValues[13]+myValues[15]+myValues[16]+myValues[17]+myValues[18]+myValues[19]+myValues[20])*((sw3[70]/(1000-sw3[70]))/(propHHCar/100));
	
	//estimates amortised car purchase expenditure
	if (myValues[8]>0) {
		myValues[22] = myCar;
		myAnnValues[22][1] = myCar;
		
		// DEPR document.userInput.box22.value=Math.round(myCar);
		putBoxVal(22,Math.round(myCar));
		
	} else {
		myValues[22] = 0;
		myAnnValues[22][1] = 0;
		
		//DEPR document.userInput.box22.value=0;
		putBoxVal(22,0);
	}

	//calculates annual expenditure
	var AnnTotal = 0;
	for (i=0;i<23;i++) {
		AnnTotal = AnnTotal+myAnnValues[i][1];
	}
	
	//calculates proportion of Annual total for each RPI cat
	for (j=0;j<23;j++) {
		myAnnValues[j][2] = 1000*myAnnValues[j][1]/AnnTotal;
	}
	
	for (t=0;t<23;t++) {
		ucw1[t] = myAnnValues[t][2]/cw1[t];
		ucw2[t] = myAnnValues[t][2]/cw2[t];
		ucw3[t] = myAnnValues[t][2]/cw3[t];
		ucw4[t] = myAnnValues[t][2]/cw4[t];
	}
	var psw1 = new Array();
	var psw2 = new Array();
	var psw3 = new Array();
	var psw4 = new Array();
	for (i=0;i<sectionID.length;i++) {
		var mySW1 = sw1[i];
		var mySW2 = sw2[i];
		var mySW3 = sw3[i];
		var mySW4 = sw4[i];
		
		myCat = sectionCat[i];
		for (v=0;v<23;v++) {
			var testCat = catID[v];
			if (testCat==myCat) {
				myMatch = v;
			}
		}
		
		psw1[i] = ucw1[myMatch]*sw1[i];
		psw2[i] = ucw2[myMatch]*sw2[i];
		psw3[i] = ucw3[myMatch]*sw3[i];
		psw4[i] = ucw4[myMatch]*sw4[i];
	}
	var personalIndex = new Array();
	for (x=0;x<indexYear.length;x++) {
		var sectionProduct = new Array();
		for (y=0;y<sectionID.length;y++) {
			var currYear = indexYear[x];//sets current year - for weightings
			var mySection = sectionID[y];
			var myWeighting = eval('psw'+currYear)[y];
			var mySectionValue = eval('index'+mySection)[x];
			sectionProduct[y] = myWeighting*mySectionValue;
		}
			
		var tot1 = 0;
		var tot2 = 0;
		for (z=0;z<sectionID.length;z++) {
			tot1=tot1+sectionProduct[z];
			var myWeighting = eval('psw'+currYear)[z];
			tot2=tot2+myWeighting;
		}
		personalIndex[x]=tot1/tot2;
	}
	var personalChainedIndex = new Array();
	personalChainedIndex[0] = personalIndex[0];
	for (i=1;i<indexYear.length;i++) {
		if (i==12 || i==24 || i==36 || i==48) {
			personalChainedIndex[i] = personalChainedIndex[i-1]*personalIndex[i]/100;
		} else {
			personalChainedIndex[i] = personalChainedIndex[i-1]*personalIndex[i]/personalIndex[i-1];
		}
	}
	var personalRate = new Array();
	personalRate[0] = (personalChainedIndex[11]/100-1)*100;
	for (i=12;i<indexYear.length;i++) {
		personalRate[i-11] = (personalChainedIndex[i]/personalChainedIndex[i-12]-1)*100;
	}
	for (k=0;k<indexYear.length-11;k++) {
			var rawvalue1  = Math.round(personalRate[k]*10)/10;
			if (isNaN(rawvalue1)) {
				linedata3[k] = 0;//zeros introduced here - due to not a number being returned
			} else {
			linedata3[k] = rawvalue1;
			}
	}

//linedata3 is personal inflation rate series
//linedata1 is national inflation rate series based on rpi
}


})();