calculators_class = function() {
	this.todayJS = new Date();
	this.currentYear = this.todayJS.getFullYear();
	this.cb = new ContentBuffer();
}

calculators_class.prototype.addCommas = function(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

calculators_class.prototype.sliderDataAdj = function(ele,oData) {
	var sliderDataDiv = Element.get("sliderDataInner_"+ele);
	var innerDataSize = Element.getSize("sliderDataInner_"+ele);
	var dataWidth = innerDataSize.width;
	var center = Math.floor(dataWidth/2);
	var offset = oData.offset; //offset from left & right edges to account for minus/plus
	var handleCenter = 3; //split handle in half
	var newPosition;
	
	var nearRightEdge = ((oData.sliderWidth - dataWidth) + center);
	var nearLeftEdge = (dataWidth - center);
	
	if (oData.currentPos > nearRightEdge) {
		newPosition = (oData.sliderWidth - dataWidth);
		if (sliderDataDiv) { Element.setStyle(sliderDataDiv,"text-align:right;"); }
	} else if (oData.currentPos < nearLeftEdge) {
		newPosition = 0;
		if (sliderDataDiv) { Element.setStyle(sliderDataDiv,"text-align:left;"); }
	} else {			
		if (sliderDataDiv) { Element.setStyle(sliderDataDiv,"text-align:center;"); }
		newPosition = (oData.currentPos - center) + handleCenter; //text align center under slider handle
	}
	
	var d = oData.currentValue;
	if (oData.formatType == "accuratepercent") {
		
		d = Math.round(d * 10) / 10; /* format to tenth THIS IS NO BUENO! */
		
		//d = Format(d,"Price"); //price adds comma
		//d = Format(d,"comma");
		
	} else if (oData.formatType == "hidevalue") {
		d = "";
	} else {
		d = Math.round(d);
		d = Format(d,"comma");
	}
	Element.get("slider_"+ele+"_value").innerHTML = d;
	Element.setStyle(sliderDataDiv, "left:"+newPosition+"px;");
}

calculators_class.prototype.boldLabel = function(ele,val) {
	try {	
		val = parseInt(val);
		if (val == 1 || val == 2 || val == 3) {
			Element.get(ele+"1").style.fontWeight = "normal";
			Element.get(ele+"2").style.fontWeight = "normal";
			Element.get(ele+"3").style.fontWeight = "normal";
			var label = Element.get(ele + val);
			Element.setStyle(label,"font-weight:bold;");
			
			this.cb.load({
				url: "retirementBubble.asp",
				data: {investmentStyle:val},
				method: "get",
				contentType: "text/html",
				onload: function(cp){
					results = cp.getResult();
					if (results) {
						this.bubbleContent = results;
						
						//show bubbles for allocation numbers
						switch(val) {
							case 1 :
								this.title = "Conservative";
								pos = "left";
								drift = -70;
								newEl = ele+"1";
								break;
							case 2 :
								this.title = "Moderate";
								newEl = ele+"2";
								break;
								//drift = 0;
							case 3 :
								this.title = "Aggressive";
								newEl = ele+"3";
								pos = "right";
								break;
						}
						if (this.bubbleContent) {
							yellowBubble._bubble.floatDistance = 20;
							yellowBubble._bubble.title = this.title;
							if (val == 1) { 
								yellowBubble._bubble.driftDistance = -85;
							} else if (val == 3) { 
								yellowBubble._bubble.driftDistance = 75;
							} else { 
								yellowBubble._bubble.driftDistance = 0; 
							}
							yellowBubble._bubble.SetContent(this.bubbleContent);
							var pos = Element.getXY(newEl);
							yellowBubble._bubble.MoveBubble(pos.x, pos.y, Element.getSize(newEl), 'y');
							yellowBubble._bubble.BlowBubble();
						}
						
					}
				},
				onerror: function(){ },
				context:this
			});
		}
	} catch(e) { }
}

calculators_class.prototype.sliderDataAdjVertical = function(ele,oData) {
	var sliderDataDiv = Element.get("sliderDataInner_"+ele);
	var innerDataSize = Element.getSize(sliderDataDiv);
	
	var d = oData.currentValue;
	if (oData.formatType == "accuratepercent") {
		d = Format(d,"Price");
	} else {
		d = Math.round(d);
	}
	
	Element.get("slider_"+ele+"_value").innerHTML = "$" + Format(d,"comma");
	Element.setStyle(sliderDataDiv, "top:"+(oData.currentPos-4)+"px;");
	
}

calculators_class.prototype.setButtons = function(update) {
	
	var buttonLI = Element.parseSelector("ul#studentPicker li a");
	
	//clear buttons
	var count = 1;
	for (var b in buttonLI) {
		if (buttonLI[b]) {
			Element.removeClass(buttonLI[b],"on");
			if (this.numOfStudents == count) {
				Element.addClass(buttonLI[b],"on");
			}
			count++;
		}
	}
	
	if (update) {
		try { 
			collegesavings.updateChartTime('numberOfChildren',this.numOfStudents);
		} catch (e) { }
	} else {
		window.location.href = "collegesavings.asp?numberOfChildren=" +this.numOfStudents;
	}
}

calculators_class.prototype.setStudents = function(num) {
	this.numOfStudents = num;	
	this.setButtons(0);
}

calculators_class.prototype.removeStudent = function(which) {
	var paneToRemove = Element.get("student_"+which);
	Element.setStyle(paneToRemove,"display:none;");
	var panesLeft = Element.parseSelector("div.studentPane");
	this.paneCount = 0;
	for (var p in panesLeft) {
		if (panesLeft[p].style.display != "none") {
			this.paneCount++;
		}
		this.linksLeft = Element.parseSelector("a.removeChildLink");
	}
	//don't show "remove" link if only 1 student
	if (this.paneCount && this.paneCount < 2) {
		for (var l in this.linksLeft) {
			this.linksLeft[l].style.display = "none";
		}
	}
	
	if (this.paneCount > 0 && this.paneCount <= 5) {
		this.removeChildRecord(which); //destroy record of child removed
	}
	
}

calculators_class.prototype.removeChildRecord = function(which) {
	this.cb.load({
		url: "removeChildRecord.asp",
		data: {remove:which},
		method: "get",
		contentType: "text/html",
		onload: function(cp){
			results = cp.getResult();
			if (results) {
				this.setStudents(this.paneCount);	
			}
		},
		onerror: function(){ },
		context:this
	});
}

calculators_class.prototype.changeSchoolPriceSlider = function(s,schoolType,publicPrice,privatePrice) {
	if (schoolType!=0) {
		if (s==1) {
			var handle = slider_annualEstimate1_handle;
		} else if (s==2) {
			var handle = slider_annualEstimate2_handle;
		} else if (s==3) {
			var handle = slider_annualEstimate3_handle;
		} else if (s==4) {
			var handle = slider_annualEstimate4_handle;
		} else if (s==5) {
			var handle = slider_annualEstimate5_handle;
		}
		
		if (schoolType=="public") {
			var price = publicPrice;
		} else if (schoolType == "private") {
			var price = privatePrice;
		}
		
		handle.setValue(price);
		var posOfVal = handle.getPositionOfValue(price);
		handle.setPosition(posOfVal);
		handle._updateHandle();
		handle.finalDisplayFromValue(price);
		this.sliderDataAdj("annualEstimate"+s,{formatType:"dollars",currentValue:price,currentPos:handle.getPosition(),sliderWidth:154,offset:18});
	}
}

//set contribution slider to max allowable by law (based on age)
calculators_class.prototype.setMaxContribution = function(el) {

	this.maxIraContribution = 6000; //must be highest regardless of age for initial slider max
	//Starting in 2009, increase contribution limit by $500 per year
	this.AdditionalContrib = 0;
	if (this.currentYear > 2009) {
		var NumYears = (this.currentYear - 2009);
    	this.AdditionalContrib = (500 * NumYears);
	}
	this.maxIraContribution += this.AdditionalContrib;
	
	if (ira) { ira.maxContribution = this.maxIraContribution; }//update IRA object
	
	this.currentAge = slider_currentAge_handle.getValue();
	
	if (this.currentAge < 50) {
		this.contribution = (this.maxIraContribution - 1000);
	} else {
		this.contribution = this.maxIraContribution;
	}
	
	this.userWantsToContributeMax = (Element.get("maxcontributionsYes").checked) ? 1 : 0;
	
	var handle = slider_contribution_handle;//slider instance

	handle.setMaxVal(this.contribution);//change max value of slider
	
	if (this.userWantsToContributeMax || handle.getPosition() == 154 || handle.getValueOfPosition(handle.getPosition()) > this.contribution) {
	
		handle.setValue(this.contribution);//now update handle's value
		handle.setPosition(154);//force handle to right edge
		handle._updateHandle();
		
		//keep this just in case...don't let handle go too far
		if (handle.getPosition() > 154) {
			handle.setPosition(154);
			handle._updateHandle();
		}
		
		//move/adjust slider value label
		this.sliderDataAdj("contribution",{formatType:"dollars",currentValue:this.contribution,currentPos:handle.getPosition(),sliderWidth:164,offset:18});
	}
	
	var existingContributionValue = handle.getValue();
	
	//finally
	if (el!="currentAge") { 
		updateChart("contribution",existingContributionValue);
	}	
}

calculators_class.prototype.checkPosition = function() {
	
	var handle = slider_contribution_handle;//slider instance
	//keep this just in case...don't let handle go too far
	if (handle.getPosition() > 154) {

		var handleVal = handle.getValue();
		var posOfVal = handle.getPositionOfValue(handleVal);
			posOfVal = (182 - parseInt(posOfVal));
		var newPosition = 154 - posOfVal;
		handle.setPosition(newPosition);
		handle._updateHandle();
		this.sliderDataAdj("contribution",{formatType:"dollars",currentValue:handleVal,currentPos:handle.getPosition(),sliderWidth:164,offset:18});
	}
}


calculators_class.prototype.setMaxIRAContribution = function() {

	this.setMaxContribution();
	var slider = slider_contribution;
	var handle = slider_contribution_handle;
	
	if (this.contribution && !isNaN(this.contribution)) {
		handle.finalDisplayFromValue(this.contribution);
		this.sliderDataAdj("contribution",{formatType:"dollars",currentValue:this.contribution,currentPos:handle.getPosition(),sliderWidth:164,offset:18});
		//don't use timer, update immediately
		ira.id = 'contribution';
		ira.currentValue = this.contribution;
		ira.updateChart();
	}
}

calculators_class.prototype.setMaxContributionRadios = function() {
	
	var handle = slider_contribution_handle;
	if (handle.getPosition() == 154) {
		Element.get("maxcontributionsNo").checked = false;
		Element.get("maxcontributionsYes").checked = true;
	} else {
		Element.get("maxcontributionsNo").checked = true;
		Element.get("maxcontributionsYes").checked = false;
	}
}


calculators_class.prototype.showLoading = function(container,gifPos) {
	var size = Element.getSize(container);
	var pos = Element.getXY(container);
	//We can position the loading gif (0=center,1=top,2=bottom)
	if(gifPos==1) {
		var topPosOfImg = 60; //show the gif near the top
	}
	else if(gifPos==2) {
		var topPosOfImg = (parseInt(size.height - 30)); //show the gif near the bottom
	}
	else {
		var topPosOfImg = (parseInt(size.height / 2 - 16)); //center loading gif
	}
	var leftPos = (parseInt(size.width / 2 - 16)); //centered
	//create new transparent div and attach to DOM
	var indicator = Element.create('div',{id:'loading_'+container,'class': 'loadingIndicator',style:'top:'+pos.y+'px;left:'+pos.x+'px;height:'+size.height+'px;width:'+size.width+'px'},'', document.body);
	//create new loading gif and attach to new div
	var graphic = Element.create('img', {src:'/scottrade/research/calculators/images/purple-loading.gif', style:'position:absolute;top:'+topPosOfImg+'px;left:'+leftPos+'px;'}, '', indicator);
}

calculators_class.prototype.hideLoading = function(container) {
	Element.remove('loading_'+container);
}

calculators_class.prototype.hideZoomLine = function() {
	var z = Element.get("zoomline");
	if(z) { Element.setStyle(z,"visibility:hidden;"); }
}

calculators_class.prototype.showDefinition = function(newEl) {
	var definition = "The annual rate at which you expect your investment to grow expressed as a percent.  Typically, the higher the percentage, the more risk you are willing to take with your investment.";
	if (yellowBubble) {
		yellowBubble._bubble.floatDistance = 0;
		if (rollover.currentCalculator == "ira") {
			yellowBubble._bubble.driftDistance = -70;
		} else {
			yellowBubble._bubble.driftDistance = 0;
		}
		yellowBubble._bubble.SetPoint("center");
		yellowBubble._bubble.title = "Expected Rate of Return";
		yellowBubble._bubble.SetContent(definition);
		var pos = Element.getXY(newEl);
		yellowBubble._bubble.MoveBubble(pos.x, pos.y, Element.getSize(newEl), 'y');
		yellowBubble._bubble.BlowBubble();
	}
}

calculators_class.prototype.hideDefinition = function() {
	if (yellowBubble) { yellowBubble._bubble.PopBubble(); }
}

calculators = new calculators_class();

rollover_class = function() {
	this.currentMenu = null;
	this.mousePos = null;
	this.currentCalculator = (cc) ? cc : "";
	this.isPrivateUser = (pvt==1) ? 1 : 0;
	this.mouseX = 0;
	this.mouseY = 0;
}


rollover_class.prototype.mouseMove = function(event){
    
    var $mousedOver = $(event.target);
  	this.offset = 0;
  	
  	switch(this.currentCalculator) {
  		case "retirement" :
  			this.chart = "rCht";
  			this.$chart = $("#retirementChart");
  			this.offset = 0;
	  		break;
		case "costofwaiting" :
  			this.chart = "cht";
  			this.$chart = $("#costofwaitingChart");
  			this.offset = 0;
	  		break;	
	  	case "ira" :
  			this.chart = "iraCht";
  			this.$chart = $("#iraChart");
  			this.offset = 1;
	  		break;	
	  	case "collegesavings" :
  			this.chart = "cht";
  			this.$chart = $("#collegeChart");
  			this.offset = 0;
	  		break;  		
  	}

    if(this.$chart) {
    	var isMouseOverChart = ($mousedOver.get(0).id == this.$chart.get(0).id) ? true : false;
        if (isMouseOverChart) {
        	try { blowChartBubble(this.mouseX -= this.offset); } catch(e) { }
        } else {
        	//we must be OUTSIDE chart area
        	try {
        		expBubble._bubble.PopBubble();
        		calculators.hideZoomLine();
        	} catch(e){ }
        }
	}
}

rollover_class.prototype.mouseCoords = function(e) {
    /*
	
	if(e.nativeEvent.pageX || e.nativeEvent.pageY){
    return {x:e.nativeEvent.pageX, y:e.nativeEvent.pageY};
    }
    return {
    x:e.nativeEvent.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:e.nativeEvent.clientY + document.body.scrollTop  - document.body.clientTop
    };
    */

    x = this.mouseX;
    console.log(x)
    

    return { x: this.mouseX, y: this.mouseY };
}

ExplainBubble = function(){
	this._bubble = new InfoBubble();
	this._bubble.bubbleWidth = 305;
	//this._bubble.floatDistance = -150;
	//this._bubble.driftDistance = -125;
	this._bubble.SetPoint("none");
	this._bubble.enableRollOutPop = false;
	this._bubble.title = '&nbsp;';
	this._bubble.closeButton = false;	
	this._bubble.Init();
	this._bubble.AttachBubble(document.getElementsByTagName("body")[0]);
}

function InitExplainBubble(){expBubble = new ExplainBubble();}
function InitYellowBubble(){yellowBubble = new ExplainBubble();}
function InitBarBubble(){barBubble = new ExplainBubble();}


$(document).ready(function(){
	
	InitExplainBubble();
	InitYellowBubble();
	InitBarBubble();
	
	rollover = new rollover_class();
	
	//cursor position
	$(document.body).mousemove( function(e) {
		rollover.mouseX = e.pageX;
		rollover.mouseY = e.pageY;
		rollover.mouseMove(e);
	});
});
