//
function setBudgetSlider(slider, disenableswitch, setValues) {
	slider.parent().parent().find("input").removeAttr('disabled');
	var budget = parseInt(slider.parent().siblings(".budget").val());
	// slider
	var addforbudget				= slider.slider('option', 'addforbudget');
	var sliderid					= slider.slider('option', 'sliderid');
	var pointer						= slider.slider('option', 'value');
	var start						= slider.slider('option', 'start');
	var isincome					= slider.slider('option', 'isincome');
	var isdisabled					= slider.slider('option', 'isdisabled');
	var isinvestment				= slider.slider('option', 'isinvestment');
	var depreciationterm			= slider.slider('option', 'depreciationterm');
	var investmentcostpercentage 	= slider.slider('option', 'investmentcostpercentage');
	var consequenceofamount			= slider.slider('option', 'consequenceofamount');
	var consequenceofcomment		= slider.slider('option', 'consequenceofcomment');
	
	var difference = 0;
	if(disenableswitch >=0)	{
		if(isdisabled == 1) {
			if (isincome === 0) {
				difference = pointer;
			}
			else if (isincome === 2) {
				difference = pointer;
			}
			else {
				difference = - pointer;
			}
		}
		else {
			if (isincome === 0) {
				difference = - pointer;
			}
			else {
				difference = pointer;
			}			
		}							
	}
	else {
		if (isincome === 0) {
			difference = start - pointer;
		}
		else if (isincome === 2) {
			difference = start - pointer;
		}		
		else {
			difference = pointer - start ;
		}
	}
	// If item is an investment, calc yearly cost(difference)
	if (isinvestment == 1) {
		difference = Math.round(difference / depreciationterm * (1 + investmentcostpercentage / 100), 0);
	}
	if (addforbudget > 0) { 
		budget = budget + difference;
	}
	else {
		budget = budget - difference;
	}

	var budgetOverTekort = "Overschot";
	if (budget < 0 ) { budgetOverTekort = "Tekort";} 
	slider.slider('option', 'start', pointer);		
	
	slider.parent().siblings(".budget").val(budget);
	if(setValues) {
		slider.slider('option', 'valueconfirmed', pointer);
		var inoutdifference = parseInt($("#amountBudget").text(), 10) - budget;		
		disenableswitch = Math.abs(disenableswitch) -1;
		if (addforbudget > 0) {
			slider.parent().next().val( addforbudget - pointer );
		}
		else {
			slider.parent().next().val( pointer );
		}
		slider.parent().parent().find(".useritem_option").val(disenableswitch);
		$("#amountBudget").text(budget);
		if( $("#leftColumn").hasClass("bezuiniginsgwijzer")) {
			var standaardtekort = parseInt(rmFormat($("#totalBudgetSpend").text()));
			$("#totalBudgetIncome").text(addCommas(standaardtekort + budget)+ ",-");
			Cufon.replace('#totalBudgetIncome');	
		}
		else {
			if (isincome === 0) {
				//inkomsten
				var budgetincome = parseInt($("#amountBudgetIncome").text(), 10);
				$("#amountBudgetIncome").text(budgetincome - inoutdifference);
				$("#budget .income").text(addCommas(budgetincome - inoutdifference) + ",-");
				Cufon.replace('#budget .income');			
			}
			else {
				//uitgave
				var budgetspend = parseInt($("#amountBudgetSpendings").text(), 10);
				$("#amountBudgetSpendings").text(budgetspend + inoutdifference);
				$("#budget .spend").text(addCommas(budgetspend + inoutdifference) + ",-");
				Cufon.replace('#budget .spend');						
			}
		}

		$(".budgetLeft").text(budgetOverTekort+": \u20AC " + addCommas(Math.abs(budget)) + ",-");
		$(".budget").val(budget);
		$(".left.sumleft").text(addCommas(Math.abs(budget)) + ",-");
		$(".left.textleft").text(budgetOverTekort);
		Cufon.replace('.left');		

		// update graphs
		// get id
		var radioID = slider.parent().attr('id');
		var besparingID = '#' + radioID + 'besparing';
		var besparingSomID = '#' + radioID + 'Som';
		
		// get besparing
		var huidigeBesparing = parseInt($(besparingID).text());
		var huidigeSomBesparing = parseInt(rmFormat($(besparingSomID).text()));

		//set besparing
		if(radioID.indexOf("sid") > 0) {
			$(besparingID).text(huidigeBesparing + inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing + inoutdifference) + ",-");
		}
		// TEMP hack bargraph, zie issues
		else {
			$(besparingID).text(huidigeBesparing - inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing - inoutdifference) + ",-");
		}

		// create graph.? Werkt al direct. Wordt ergens anders al aangeroepen
		if(radioID.indexOf("sid") > 0) {
			radioID = radioID.substring(0, radioID.indexOf("sid"));
			besparingID = '#' + radioID + 'besparing';
			besparingSomID = '#' + radioID + 'Som';
			// get besparing
			huidigeBesparing = parseInt($(besparingID).text());
			huidigeSomBesparing = parseInt(rmFormat($(besparingSomID).text()));
			//set besparing
			$(besparingID).text(huidigeBesparing + inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing + inoutdifference) + ",-");
		}
	}
	else {
		slider.parent().siblings(".budgetLeft").text(budgetOverTekort+": \u20AC " + addCommas(Math.abs(budget)) + ",-");	
	}
	
	// set comment
	if (consequenceofamount.length > 0) {
		for (var i in consequenceofamount) {
			if(pointer < consequenceofamount[i]) {
				var elemAmountDisplay = "#"+sliderid+" .consequenceOfAmountDisplay";
				$(elemAmountDisplay).text(consequenceofcomment[i]);
				break;
			}
		}
	}
}

function setBudgetRadio(radio, disenableswitch, setValues) {
	radio.parent().parent().find(".confirm").removeAttr('disabled');
	var budget = radio.parent().siblings(".budget").val();
	var budgetObject = {};
	var budgetLeftObject = {};
	if(typeof(budget) == 'undefined') {
		budget = radio.parent().find(".budget").val();
		budgetObject = radio.parent().find(".budget");
		budgetLeftObject = radio.parent().find(".budgetLeft");
	}
	else {
		budgetObject =  radio.parent().siblings(".budget");
		budgetLeftObject = radio.parent().siblings(".budgetLeft");
	}
	var difference = 0;

	var radiostart = parseInt(radio.parent().find(".tempRadio").text(), 10 );
	var radiodefault = parseInt(radio.parent().find(".amountDefaultRadio").text(), 10 );
	var radioisincome = parseInt(radio.parent().find(".isincomeRadio").text(), 10 );
	var radioisinvestement = parseInt(radio.parent().find(".isInvestmentRadio").text(), 10 );
	var radiodepreciation = parseInt(radio.parent().find(".depreciationTermRadio").text() , 10);
	var radioisinvestmentcostpercentage = parseInt(radio.parent().find(".investmentCostPercentageRadio").text() , 10);
	var radiovalue = radio.val() ;
	if(radiovalue <= 1) {
		radiovalue = 0;
	}

	if(disenableswitch > -1) {
		if(disenableswitch == 1) {
			if (radioisincome === 0) {
				difference = radiostart;
			}
			else {
				difference = - radiostart;
			}
		}
		else {
			if (radioisincome === 0) {
				difference = - radiodefault;
			}
			else {
				difference = radiodefault;
			}
			radiovalue =		radiodefault;
		}
	}	
	else  {					
		if (radioisincome === 0) {
				difference = radiostart - radiovalue;
			}
			else {
				difference = radiovalue - radiostart ;
			}
	}
	// If item is an investment, calc yearly cost(difference)
	if (radioisinvestement == 1) {
		difference = Math.round(difference / radiodepreciation * (1 + radioisinvestmentcostpercentage / 100), 0);
	}				
	budget = budget - difference;	
	var budgetOverTekort = "Overschot";
	if (budget < 0 ) { budgetOverTekort = "Tekort";}
	if( $("#leftColumn").hasClass("bezuiniginsgwijzer")) {
		budgetLeftObject.text(budgetOverTekort + ": \u20AC " + addCommas(Math.abs(budget)) + ",-");
	}
	else {
		budgetLeftObject.text(budgetOverTekort + ": \u20AC " + addCommas(budget) + ",-");
	}
	
	budgetObject.val(budget);
	radio.parent().find(".tempRadio").text(radiovalue);
	if(setValues) {
		var inoutdifference = parseInt($("#amountBudget").text(), 10) - budget;	
		disenableswitch = Math.abs(disenableswitch) -1;
		radio.parent().find(".radiovalue").val(radiovalue);
		radio.parent().parent().find(".useritem_option").val(disenableswitch);

		// bezuinigingswijzer, andere bedragen.
		// plek '#budget .spend' is vast bedrag (standard tekort)
		// plek '#budget .income' is bezuiniging user
		// lek '#budget .sumleft' is overschot/tekort (zelfde)
		
		if( $("#leftColumn").hasClass("bezuiniginsgwijzer")) {
			var standaardtekort = parseInt(rmFormat($("#totalBudgetSpend").text()));
			$("#totalBudgetIncome").text(addCommas(standaardtekort + budget)+ ",-");
			Cufon.replace('#totalBudgetIncome');	
		}
		else {
			if (radioisincome === 0) {
				//inkomsten
				var budgetincome = parseInt($("#amountBudgetIncome").text(), 10);
				$("#amountBudgetIncome").text(budgetincome - inoutdifference);
				$("#budget .income").text(addCommas(budgetincome - inoutdifference) + ",-");
				Cufon.replace('#budget .income');			
			}
			else {
				//uitgave
				var budgetspend = parseInt($("#amountBudgetSpendings").text(), 10);
				$("#amountBudgetSpendings").text(budgetspend + inoutdifference);
				$("#budget .spend").text(addCommas(budgetspend + inoutdifference) + ",-");
				Cufon.replace('#budget .spend');						
			}
		}
				
		radio.parent().find(".amountStartRadio").text(radiovalue);
		$("#amountBudget").text(budget);
		$(".budget").val(budget);
		if( $("#leftColumn").hasClass("bezuiniginsgwijzer")) {
			$(".budgetLeft").text(budgetOverTekort + ": \u20AC " + addCommas(Math.abs(budget)) + ",-");
		}
		else {
			$(".budgetLeft").text(budgetOverTekort + ": \u20AC " + addCommas(budget) + ",-");
		}
		$(".left.sumleft").text(addCommas(Math.abs(budget)) + ",-");
		$(".left.textleft").text(budgetOverTekort);
		Cufon.replace('.left');
		
		// get id
		var radioID = radio.parent().attr('id');
		var besparingID = '#' + radioID + 'besparing';
		var besparingSomID = '#' + radioID + 'Som';
		
		// get besparing
		var huidigeBesparing = parseInt($(besparingID).text());
		var huidigeSomBesparing = parseInt(rmFormat($(besparingSomID).text()));

		//set besparing
		if(radioID.indexOf("sid") > 0) {
			$(besparingID).text(huidigeBesparing + inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing + inoutdifference) + ",-");
		}
		// TEMP hack bargraph, zie issues
		else {
			$(besparingID).text(huidigeBesparing - inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing - inoutdifference) + ",-");
		}
		

		// create graph.? Werkt al direct. Wordt ergens anders al aangeroepen
		if(radioID.indexOf("sid") > 0) {
			radioID = radioID.substring(0, radioID.indexOf("sid"));
			besparingID = '#' + radioID + 'besparing';
			besparingSomID = '#' + radioID + 'Som';
			// get besparing
			huidigeBesparing = parseInt($(besparingID).text());
			huidigeSomBesparing = parseInt(rmFormat($(besparingSomID).text()));
			//set besparing
			$(besparingID).text(huidigeBesparing + inoutdifference);
			$(besparingSomID).text("€ " + addCommas(huidigeSomBesparing + inoutdifference) + ",-");
		}
	}
}

$(window).load( function(){
		
	/**
	 * SLIDER: INITIALIZE ALL SLIDERS
	 */		
	$(".slider").each(function() {
		var consequenceofamount = [];
		var consequenceofcomment = [];
		var sliderid, minimum, maximum, step, pointer, start, isincome, isdisabled, isinvestment, depreciationterm,investmentcostpercentage,addforbudget, valueconfirmed ;
		// read initial values from markup		
		$(this).children("span").each( function(){
			if ($(this).hasClass("sliderID")){ sliderid = $(this).text();}
			if ($(this).hasClass("amountMinimum")){ minimum = parseInt(rmFormat($(this).text()), 10); }
			if ($(this).hasClass("amountMaximum")){ maximum = parseInt(rmFormat($(this).text()), 10); }
			if ($(this).hasClass("amountStep")){ step = parseInt($(this).text(), 10); }
			if ($(this).hasClass("amountPointer")){ pointer = parseInt(rmFormat($(this).text()), 10); }
			if ($(this).hasClass("amountStart")){ start = parseInt($(this).text(), 10);}
			if ($(this).hasClass("isIncome")){ isincome = parseInt($(this).text(), 10);}
			if ($(this).hasClass("isDisabled")){ isdisabled = parseInt($(this).text(), 10);}
			if ($(this).hasClass("isInvestment")){ isinvestment = parseInt($(this).text(), 10);}
			if ($(this).hasClass("depreciationTerm")){ depreciationterm = parseInt($(this).text(), 10);}
			if ($(this).hasClass("investmentCostPercentage")){ investmentcostpercentage = parseInt($(this).text(), 10);}
			if ($(this).hasClass("addForBudget")){ addforbudget = parseInt($(this).text(), 10);}
		});
		// read comment of choice.
		$(this).children("div").each( function() {
			if ($(this).hasClass("conseqOfAmount")) { 
				$(this).children().each( function() {
					if ($(this).hasClass("consequenceOfAmountValue")) {
						consequenceofamount[consequenceofamount.length] = parseInt($(this).text(), 10);
					}
					if ($(this).hasClass("consequenceOfAmountComment")){
						consequenceofcomment[consequenceofcomment.length] = $(this).text();
					}
				});	
			}
		});		
		
		// create slider from values
		$(this).slider({ 
			sliderid: sliderid,
			min: minimum, 
			max: maximum, 
			value: pointer, 
			step: step,
			start: start,
			isincome: isincome,
			isdisabled: isdisabled,
			isinvestment: isinvestment,
			depreciationterm: depreciationterm,
			investmentcostpercentage: investmentcostpercentage,
			consequenceofamount: consequenceofamount,
			consequenceofcomment: consequenceofcomment,
			addforbudget: addforbudget,
			valueconfirmed : start,
			slide: function(event, ui) {
				$(this).children("a").each( function(i){
					$(this).html( "<span class=\"amountPointer\">" + addCommas(ui.value) + "</span>");
				});
			} 
		});

		// set amount in moveable pointer div
		$(this).children("a").each( function(i){
			$(this).html( "<span class=\"amountPointer\">" + addCommas(pointer) + "</span>");
		});
		
		// set all values to default amount
		// $(this).parent().next().val( pointer );
		
		if(isdisabled == 1) {
			$(this).slider('disable');
		}		
		
	});

	// if slider is disabled, set budget for item to 0.
	$(".slider").bind('slidestop', function(event, ui) {
			setBudgetSlider($(this), -1, false);
	});

	// $(".confirm.choice").attr('disabled', true);
	
});

/**
 * POPUP: CONFIRM SLIDERS/RADIO EVENT 
 */
$( function(){
	$("input.choice").click( function() {
		// is item optional
		var optionID = $(this).parent().find(".optional").find("input").attr("name");
		// default, item is not optional
		var optionValue = 0;
		// if optional, is it enabled or disabled
		if(typeof(optionID) !== 'undefined')  {
			optionValue = $("input[name$='"+optionID+"']:checked").val();
		}

		// radio-values
		$(this).parent().find("div.options").each( function(){ 
			var radioID = $(this).find("input").attr("name");
			if(typeof(radioID) !== 'undefined')  {
				var radiovalue = $("input[name$='"+radioID+"']:checked").val()  ;
				if(typeof(radiovalue) !== 'undefined')  {
					setBudgetRadio( $("input[name$='"+radioID+"']:checked"), -1 -optionValue , true );
				}
				else {
					setBudgetRadio( $(this).parent().find(".options"),  -1 -optionValue, true );
				}
			}				
		} ) ;
		// slider-values
		$(this).parent().find(".slider").each( function(){ setBudgetSlider( $(this), -1 -optionValue, true ); }  ) ;
		
		$(this).attr('disabled', true);
//		$(this).parent().parent().parent().addClass('confirmed');
		$("ul.accounts span.itembar").createStats();
		// close popups
		$(".accounts li").each( function(i) {
			$(this).children(".popup").each( function(i){
				if( $(this).parent().hasClass("active") ){
					$(this).parent().toggleClass("active");
					$(this).animate({left: "0px", opacity: 0}, 750, function(){ 
						$(this).css("display", "none")
					});
				}
			});
		});
		
	});
		
} );

/**
 * OPTION: SWITCH SLIDER/RADIOBUTTONS ON OR OF IF THE ITEM IS OPTIONAL
 */
$( function(){
	
	$(".optional").each(function() {
		$(this).children("input").each( function(){	
			$(this).click( function(){  
				if( $(this).val() != $(this).parent().parent().find(".useritem_optiontemp").text()  ) {
					$(this).parent().parent().find(".useritem_optiontemp").text($(this).val());
					var radioID = $(this).parent().next(".options").find("input").attr("name");
					if(typeof(radioID) !== 'undefined')  {
						if($(this).val() == 1) {
							// disable radio	
							$(this).parent().next().find("input").attr('disabled', true);
							$(this).parent().next().find("input").removeAttr('checked');
						}
						else {
							// enable radio
							var amountDefault = parseInt($(this).parent().next(".options").find(".amountDefaultRadio").text(), 10 );
							$(this).parent().next().find("input").removeAttr('disabled');
							var isNotChecked = true;
							$(this).parent().next().find("input").each( function() {if( $(this).val() == amountDefault ){$(this).attr('checked', 'checked'); isNotChecked = false;} } );
							// No default, take first (or only).
							if(isNotChecked) {
								$(this).parent().next().find("input").each( function() {if(isNotChecked) {$(this).attr('checked', 'checked'); isNotChecked = false;} } );
							}
						}	
						setBudgetRadio($(this).parent().next(".options"), $(this).val(), false);
					}
					else {
						if($(this).val() == 1) {
							// disable slider	
							$(this).parent().parent().find(".slider").slider('disable');
							$(this).parent().next().find("input").attr('disabled', true);
							$(this).parent().next().find("input").removeAttr('checked');
							$(this).parent().parent().find(".slider").slider('option', 'isdisabled', 1); 
							setBudgetSlider($(this).parent().parent().find(".slider"), 1, false);
						}
						else {
							// enable slider
							$(this).parent().parent().find(".slider").slider('enable');
							$(this).parent().next().find("input").removeAttr('disabled');
							$(this).parent().parent().find(".slider").slider('option', 'isdisabled', 0); 
							setBudgetSlider($(this).parent().parent().find(".slider"), 0, false);
							
						}							
					}
				}
										
			});
		});
	});
});

/**
 * OPTION: CHANGE BUDGET DIRECTLY ON CLICK
 */
$( function(){
	$(".options").each(function() {
		$(this).children("input").each( function(){	
				$(this).click( function(){  
				setBudgetRadio($(this), -1, false);				
			});		
		});
	});	
});			

function resetPopup(popup) {
	popup.find(".slider").each( function() {
		var addforbudget = 0;
		var pointer = 0;
		$(this).children("span").each( function(){
			if ($(this).hasClass("addForBudget")){ addforbudget = parseInt($(this).text(), 10);}
		});
		if (addforbudget > 0) {
			pointer = addforbudget - $(this).parent().next().val();
		}
		else {
			pointer = $(this).parent().next().val();
		}

		$(this).slider('value', pointer);
		var startvalue =  $(this).slider('option', 'start');
		$(this).slider('option', 'start', $(this).slider('option', 'valueconfirmed')  );
		$(this).children("a").each( function(i){
			$(this).html( "<span class=\"amountPointer\">" + addCommas(pointer) + "</span>");
		});
		var budget = parseInt($("#amountBudget").text(), 10);
		var budgetOverTekort = "Overschot";
		if (budget < 0 ) { budgetOverTekort = "Tekort";}
		$(this).parent().parent().find(".budgetLeft").text(budgetOverTekort + ": \u20AC " + addCommas(Math.abs(budget)) + ",-");			
		$(this).parent().parent().find(".budget").val(budget);			
	});
	
	popup.find(".options").each( function() {
		var pointer = $(this).find(".amountStartRadio").text();
		$(this).find(".tempRadio").text(pointer);
		$(this).find(".radioOption").each( function() {if( $(this).val() == pointer ){$(this).attr('checked', 'checked');} } );
		var budget = parseInt($("#amountBudget").text(), 10);
		var budgetOverTekort = "Overschot";
		if (budget < 0 ) { budgetOverTekort = "Tekort";}
		$(this).parent().find(".budgetLeft").text(budgetOverTekort + ": \u20AC " + addCommas(Math.abs(budget)) + ",-");			
		$(this).parent().find(".budget").val(budget);	
	});
	
	popup.find(".optional").each( function() {
		var useritem_option = parseInt($(this).parent().find(".useritem_option").val(), 10);
		$(this).find(".radioButton").each( function() {if( $(this).val() == useritem_option ){$(this).attr('checked', 'checked');} } );
		if(useritem_option == 1) {
			$(this).parent().find(".options").find("input").attr('disabled', true);
			$(this).parent().find(".options").find("input").removeAttr('checked');
			$(this).parent().find(".sliderContainer").find(".slider").slider('disable');	
		}
		var budget = parseInt($("#amountBudget").text(), 10);
		var budgetOverTekort = "Overschot";
		if (budget < 0 ) { budgetOverTekort = "Tekort";}
		$(this).parent().find(".budgetLeft").text(budgetOverTekort + ": \u20AC " + addCommas(Math.abs(budget)) + ",-");			
		$(this).parent().find(".budget").val(budget);			
	});
}
