
function slider (a_init, a_tpl) {

	this.f_setValue  = f_sliderSetValue;
	this.f_getPos    = f_sliderGetPos;
	this.f_setMax   = f_sliderSetMax;
	this.f_setLength   = f_setPathLength;
    this.f_setbaseWidth = f_setsliderBaseWidth;
	
	this.txtcover=5;
	
	// register in the global collection	
	if (!window.A_SLIDERS)
		window.A_SLIDERS = [];
	this.n_id = window.A_SLIDERS.length;
	window.A_SLIDERS[this.n_id] = this;

	// save config parameters in the slider object
	var s_key;
	if (a_tpl)
		for (s_key in a_tpl)
			this[s_key] = a_tpl[s_key];
	for (s_key in a_init)
			this[s_key] = a_init[s_key];

	var divVal=(this.n_maxValue - this.n_minValue);
	if(divVal>0)
		this.n_pix2value = this.n_pathLength / divVal;		
	else
		this.n_pix2value = this.n_pathLength;
		
	//alert(this.n_pathLength+" > >"+(this.n_maxValue - this.n_minValue));	
	if (this.n_value == null)
		this.n_value = this.n_minValue;		

	//var sliderbar='<input size=2 axlength=3 type="text" class="sliderText" style="position:relative;left:' + this.n_pathLeft + 'px;top:' + this.n_pathTop + 'px;z-index:' + this.n_zIndex + ';cursor:pointer;" name="sl' + this.n_id + 'slider" id="sl' + this.n_id + 'slider" />'	
	
       var sliderbar='<div style="font-size:9px;height:18px;position:relative;display:block;left:' + this.n_pathLeft + 'px;top:' + this.n_pathTop + 'px;z-index:' + this.n_zIndex + ';cursor:pointer;" name="txt' + this.n_id + 'slider" id="txt' + this.n_id + 'slider" /></div>';
		 
	// generate the control's HTML
	document.write(
		'<div style="width:' + this.n_controlWidth + 'px;height:' + this.n_controlHeight + 'px;border:1px solid #01a4e9; background:#e5f6fd; " id="sl' + this.n_id + 'base">' +
		'<div style="border:0px;padding:0px;background:#01a4e9;width:auto;height:' + this.n_controlHeight + 'px;" id="sl' + this.n_id + 'barcolor">' +sliderbar+
		'</div></div>'
	);	
	
	this.e_base   = get_element('sl' + this.n_id + 'base');
	this.e_slider = get_element('sl' + this.n_id + 'slider');	
	this.e_slidertxt = get_element('txt' + this.n_id + 'slider');	
	this.e_barcolor = get_element('sl' + this.n_id + 'barcolor');		
	
	// safely hook document/window events
	if (document.onmousemove != f_sliderMouseMove) {
		window.f_savedMouseMove = document.onmousemove;
		document.onmousemove = f_sliderMouseMove;
	}
	if (document.onmouseup != f_sliderMouseUp) {
		window.f_savedMouseUp = document.onmouseup;
		document.onmouseup = f_sliderMouseUp;
	}
	// preset to the value in the input box if available
	var e_input = this.s_form == null
		? get_element(this.s_name)
		: document.forms[this.s_form]
			? document.forms[this.s_form].elements[this.s_name]
			: null;
	var dispval= (e_input && e_input.value != '' ? e_input.value : null, 1);
	this.f_setValue('');
	var calcvalue=parseFloat(dispval)+this.txtcover;
	
	this.e_slider.style.visibility = 'visible';
	this.e_slidertxt.innerHTML="£0";	
	//alert(" >ID:"+this.e_slidertxt.id+" | "+calcvalue);
}

function f_sliderSetValue (n_value, b_noInputCheck) {
	
	//alert("f_sliderSetValue:"+n_value);	
	var cal_minValue=this.n_minValue;
	
	if (n_value == null)
		n_value = this.n_value == null ? cal_minValue : this.n_value;
	if (isNaN(n_value))
		return false;
	// round to closest multiple if step is specified
	if (this.n_step)
		n_value = (parseFloat((n_value - cal_minValue) / this.n_step) * this.n_step + cal_minValue).toFixed(2);
	// smooth out the result
	if (n_value % 1)
		n_value = (parseFloat(n_value * 1e5) / 1e5).toFixed(2);

	if (parseFloat(n_value)< parseFloat(cal_minValue))
		n_value = cal_minValue;
	if (parseFloat(n_value) > parseFloat(this.n_maxValue))
		n_value = this.n_maxValue;		

	this.n_value = n_value;
	
	//alert(this.n_pathLeft + " n_value "+n_value +" cal_minValue"+cal_minValue+" n_pix2value "+this.n_pix2value);
	
	// move the slider		
	this.e_slider.style.left = ( this.n_pathLeft + Math.round((n_value - cal_minValue) * this.n_pix2value))-15  + 'px';
		
	// save new value
	var e_input;
	if (this.s_form == null) {
		e_input = get_element(this.s_name);
		if (!e_input)
			return b_noInputCheck ? null : f_sliderError(this.n_id, "Can not find the input with ID='" + this.s_name + "'.");
	}
	else {
		var e_form = document.forms[this.s_form];
		if (!e_form)
			return b_noInputCheck ? null : f_sliderError(this.n_id, "Can not find the form with NAME='" + this.s_form + "'.");
		e_input = e_form.elements[this.s_name];
		if (!e_input)
			return b_noInputCheck ? null : f_sliderError(this.n_id, "Can not find the input with NAME='" + this.s_name + "'.");
	}
	e_input.value = n_value;
	this.e_barcolor = get_element('sl' + this.n_id + 'barcolor');

	var calcvalue=parseFloat((n_value*100)/this.n_maxValue);
	
  	if(isNaN(calcvalue))
		calcvalue=0;
	//alert("FIR: "+calcvalue+" | NVAL"+(n_value*100)+" | MAX"+this.n_maxValue);
	calcvalue+=parseFloat(this.n_sliderWidth)+this.txtcover;	
	//alert("F2IR: "+calcvalue);

	var dispvalue=0;
	
	if(n_value == this.n_maxValue)
		dispvalue=0;
	else if(n_value!='')
		{
		    dispvalue=this.n_maxValue-n_value;						
		}

	var dispvalue2=0;

	if(dispvalue >0)
		dispvalue2=parseFloat((dispvalue*100)/this.n_maxValue);
	
  	if(isNaN(dispvalue2))
		dispvalue2=0;

	if(dispvalue>0)
		this.e_barcolor.style.width=parseInt(dispvalue2)+this.txtcover+15+"px";	
	else
		this.e_barcolor.style.width=this.txtcover+15+"px";	
	this.e_slidertxt.innerHTML="£"+parseInt(dispvalue);
	//alert("n_value:"+n_value);
	
	if(n_value==0)
		this.e_slidertxt.style.left="0px";
	else
		this.e_slidertxt.style.left=parseInt(dispvalue2+this.txtcover)-15 +"px";
}

// get absolute position of the element in the document
function f_sliderGetPos (b_vertical, b_base) {
	var n_pos = 0,
		s_coord = (b_vertical ? 'Top' : 'Left');
	var o_elem = o_elem2 = b_base ? this.e_base : this.e_slider;
	
	while (o_elem) {
		n_pos += o_elem["offset" + s_coord];
		o_elem = o_elem.offsetParent;
	}
	o_elem = o_elem2;

	var n_offset;
	while (o_elem.tagName != "BODY") {
		n_offset = o_elem["scroll" + s_coord];
		if (n_offset)
			n_pos -= o_elem["scroll" + s_coord];
		o_elem = o_elem.parentNode;
	}
	return n_pos;
}
function f_sliderSetMax(maxval){
		//alert(maxval);
		this.n_maxValue=maxval;
		//alert("NMAX:"+this.n_maxValue);
		//this.n_controlWidth=maxval+10;
} 
function f_setPathLength(pathval){
        this.n_pathLength=pathval;
}
function f_setsliderBaseWidth(num){
	 var e_base   = get_element('sl' + this.n_id + 'base');
	 //alert(e_base.style.width+" >> "+num);
     e_base.style.width=parseInt(num)+5+"px";	
}
function f_sliderMouseDown (n_id) {
	window.n_activeSliderId = n_id;
	return false;
}

function f_sliderMouseUp (e_event, b_watching) {
	if (window.n_activeSliderId != null) {
		var o_slider = window.A_SLIDERS[window.n_activeSliderId];
		o_slider.f_setValue(o_slider.n_minValue + (o_slider.b_vertical
			? (o_slider.n_pathLength - parseFloat(o_slider.e_slider.style.top) + o_slider.n_pathTop)
			: (parseFloat(o_slider.e_slider.style.left) - o_slider.n_pathLeft)) / o_slider.n_pix2value);
		if (b_watching)	return;
		window.n_activeSliderId = null;
	}
	if (window.f_savedMouseUp)
		return window.f_savedMouseUp(e_event);
}

function f_sliderMouseMove (e_event) {

	if (!e_event && window.event) e_event = window.event;

	// save mouse coordinates
	if (e_event) {
		window.n_mouseX = e_event.clientX + f_scrollLeft();
		window.n_mouseY = e_event.clientY + f_scrollTop();
	}

	// check if in drag mode
	if (window.n_activeSliderId != null) {
		var o_slider = window.A_SLIDERS[window.n_activeSliderId];

		var n_pxOffset;
		if (o_slider.b_vertical) {
			var n_sliderTop = window.n_mouseY - o_slider.n_sliderHeight / 2 - o_slider.f_getPos(1, 1) - 3;
			// limit the slider movement
			if (n_sliderTop < o_slider.n_pathTop)
				n_sliderTop = o_slider.n_pathTop;
			var n_pxMax = o_slider.n_pathTop + o_slider.n_pathLength;
			if (n_sliderTop > n_pxMax)
				n_sliderTop = n_pxMax;
			o_slider.e_slider.style.top = n_sliderTop + 'px';
			n_pxOffset = o_slider.n_pathLength - n_sliderTop + o_slider.n_pathTop;
		}
		else {
			
			//var n_sliderLeft = window.n_mouseX - o_slider.n_sliderWidth / 2 - o_slider.f_getPos(0, 1) - 3;
			var comwidth=o_slider.n_sliderWidth;
			var n_sliderLeft = window.n_mouseX - comwidth / 2 - o_slider.f_getPos(0, 1) - 3;
			// limit the slider movement
			if (n_sliderLeft < o_slider.n_pathLeft)
				n_sliderLeft = o_slider.n_pathLeft;
			var n_pxMax = o_slider.n_pathLeft + o_slider.n_pathLength;
			if (n_sliderLeft > n_pxMax)
				n_sliderLeft = n_pxMax;
			o_slider.e_slider.style.left = n_sliderLeft -15 + 'px';
			n_pxOffset = n_sliderLeft - o_slider.n_pathLeft;
		}
		if (o_slider.b_watch)
			 f_sliderMouseUp(e_event, 1);

		return false;
	}
	
	if (window.f_savedMouseMove)
		return window.f_savedMouseMove(e_event);
}

// get the scroller positions of the page
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function f_sliderError (n_id, s_message) {
	alert("Slider #" + n_id + " Error:\n" + s_message);
	window.n_activeSliderId = null;
}

get_element = document.all ?
	function (s_id) { return document.all[s_id] } :
	function (s_id) { return document.getElementById(s_id) };

function newspend(obj,num){

	var obs=eval("slnm"+num);	
	var setval=0;

	if(typeof(obj.value)!='undefined'){
		setval=obj.value;
	}
	/*setval=parseInt(setval);*/


	if(typeof(obs)!='undefined')
	    obs.f_setValue('',true);

	if(obj.value.length>0)
	{	
		if(isInteger(setval)){
			if(setval>=0 && typeof(obs)!='undefined'){
				if((obs.n_maxValue*1)>=setval){
					obs.f_setValue(setval, true);
				}else{
					alert("Limit exceeded");									
					obj.value='0';
					obj.select();
					obs.f_setValue('', true);
				}
			}else{
				alert("Please enter a weekly save in whole pounds, using numbers only.");
				obj.value='0';
				obj.select();
				return false;					
			}
		}else{
			alert("Please enter a weekly save in whole pounds, using numbers only");
			obj.value='0';
			obj.select();
			return false;					
		}
	}

	caltotal("s");
}
function updateSlider(obj,num){		

		var setval=0;
		var obr=eval("slnm"+num);
		
		if(typeof(obj.value)!='undefined')
			setval=obj.value;
		
		if(setval==''){
		    setval=0;
		    obr.f_setMax(setval);
		}		

		if(typeof(obr)!='undefined')
			  obr.f_setValue('',true);
	 
		var newspend=document.getElementById("newspendnm"+num);
		
        //alert(">>"+obr.n_maxValue+" -- "+isNaN(setval)+" Setval:"+setval);
		
		if(isInteger(setval)){
			if(setval<0)
			{
				alert("Please enter a weekly spend in whole pounds, using numbers only");
				obj.value='';
				newspend.value='0';
				return false;
			}else if(typeof(obr)!='undefined'){
				obr.f_setMax(setval);
				obr.f_setValue(0);
				//obr.f_setbaseWidth(setval);
				newspend.value='0';
			}
			
		}else{
			
			alert("Please enter a weekly spend in whole pounds, using numbers only.");
			obj.value='';
			newspend.value='0';
			return false;
		}		
		caltotal("");
	}
	
function caltotal(typ){
	var totalslider=15;
	
	if(typ=="s"){
		document.getElementById("wstotal").value="£"+(getTotal("newspendnm",totalslider)).toFixed(2);		
		document.getElementById("astotal").value="£"+(getTotal("newspendnm",totalslider)*52).toFixed(2);		
		updateGraph();
	}else	{
		document.getElementById("wtotal").value="£"+(getTotal("textfield",totalslider)).toFixed(2);
		document.getElementById("atotal").value="£"+(getTotal("textfield",totalslider)*52).toFixed(2);
	}		

}
function getTotal(fld,totalslider){
	var sumtotal=0;
	
	for(var i=0;i<totalslider;i++){
		var obr=document.getElementById(fld+i);
		if(typeof(obr)!='undefined')
		{
			//alert("obr:"+typeof(obr)+"--"+obr.name)
			if(!isNaN(obr.value) && obr.value!=''){				
				if(obr.value>0)
						sumtotal=parseFloat(sumtotal)+parseFloat(obr.value);				
			}
		}
	}
	return sumtotal;
}
function updateGraph(){
	
	if(document.getElementById("astotal")!=null){	
		x=document.getElementById("astotal").value;		
		x= x.toString().replace(/\£|\,/g,'');
	}else
		x=0;

  if (x < 0) {
    x = 0;
  } else if (x > 12000) {
    x = 12000;
  }

  var ha = 0;
  var la = 0;
  var hp = 0;
  var lp = 0;

  if (x < 101){
    ha = 100;
    la = 0;
    hp = 84;
    lp = 35;
  } else if (x < 601){
    ha = 600;
    la = 100;
    hp = 261;
    lp = 84;
  } else if (x < 1001){
    ha = 1000;
    la = 600;
    hp = 432;
    lp = 261;
  } else if (x < 10001){
    ha = 10000;
    la = 1000;
    hp = 605;
    lp = 432;
  } else if (x < 12001){
    ha = 12000;
    la = 10000;
    hp = 703;
    lp = 605;
  }

  var on = Math.round(((hp-lp)*(x - la)/(ha - la)) + lp);
  var off = 727 - on;

  var onSize  = on  + "px";
  var offSize = off + "px";

  var objOn  = document.getElementById("box1");
  objOn.style.width  = onSize;
  var objOff = document.getElementById("box2");
  objOff.style.width = offSize;
}
winname	=null;
val			= null;
function displaypopup(num){
	
textfield=document.getElementById("textfield"+num);
val=document.getElementById("tip"+num);
newspendnm=document.getElementById("newspendnm"+num);
	
		if(typeof(winname)!='undefined'){
			if (winname && !winname.closed )
			{		
				winname.close();
				winname = null;
			}
		}		
	
		//document.write(unescape(content));
		winname=window.open("savingTips_popup.html","SAVINGTIPS"+num,"status=0,width=415,height=150");				
	
}
function  assign()
{	
	//alert(winname);
	winname.document.getElementById("tiptext").innerHTML=val.innerHTML;	
}

function viewAnnual(){
	
	var ItemNames = new Array('Magazines etc.','Music','Clothes','Cinema etc.','Make up','Lunchtimes','Takeaways','Restaurants','Coffee','Smoking','The pub','Clubbing','Books','Treats','Other');
	
	spendValues=getSpend();
	generateTable2("leftPan",ItemNames,spendValues);
	savingValues=getSaving();
	generateTable2('rightPan',ItemNames,savingValues);	
	//document.getElementById("contentFritter").style.height="1800px";		
}

function toggle(tag,typ){
	
		var annualspend=document.getElementById(tag);		
		if(typ=='show'){
			annualspend.style.display="block";
		}else
			annualspend.style.display="none";	
}

function viewAnnualSpend(typ){
	var contentFritter=document.getElementById("contentFritter");
	
		if(typ=="show"){
			viewAnnual();					
		}	
		toggle("annualBreakdownSection",typ);
}
function generateTable2(container,ItemNames,values)
{						
			var leftPanelDiv=document.getElementById(container);
			leftPanelDiv.innerHTML="";

				for(i=0;i<ItemNames.length;i++)
				{
						itemNameCol=null;
						dailyCol=null;
						weeklyCol=null;
						annaulCol=null;
						
				if(typeof(values[i])!='undefined'){				
						itemNameCol=document.createElement("span")	;			
						itemNameCol.className="collargeorg size10";
						itemNameCol.style.cssText="width:30%;text-align:left;";
						itemNameCol.innerHTML=ItemNames[i];
						leftPanelDiv.appendChild(itemNameCol);
						
						dailyCol=document.createElement("div")	;			
						dailyCol.className="collargeorg size10 dailyCal";						
						dailyCol.innerHTML=(values[i]/7).toFixed(2);
						leftPanelDiv.appendChild(dailyCol);			
												
						weeklyCol=document.createElement("div")	;			
						weeklyCol.className="collargeorg size10 weeklyCal";
						weeklyCol.style.cssText="width:21%";
						weeklyCol.innerHTML=values[i];
						leftPanelDiv.appendChild(weeklyCol);
						
						annaulCol=document.createElement("div")	;			
						annaulCol.className="collargeorg size10 annualCal";
						annaulCol.innerHTML=parseInt(values[i]*52);
						leftPanelDiv.appendChild(annaulCol);																		
					}
			}			
		toggle("annualBreakdownSection","show");
}
function getSpend()
{
	  var nuArr2 = new Array();	   
		for(i=0;i<15;i++)
		{
			var spend=document.getElementById("textfield"+i);		
			if(!isNaN(parseInt(spend.value)))
				{	
					nuArr2[i]=spend.value;
				}	
			
		}	
	return nuArr2;
}
function getSaving()
{
	  var nuArr = new Array();
	  
	for(i=0;i<15;i++)
	{
		var newspendnm=document.getElementById("newspendnm"+i);		
		if(!isNaN(parseInt(newspendnm.value)))
		{	
				nuArr[i]=newspendnm.value;
		}	
	}	
	return nuArr;
}
function isInteger(s) {
	var regEx = /^\d+$/;
	return regEx.test(s);
}