$(function(){//clear all numbers on refresh or new pageload.
	$("input.nbr").val("0,00");	
});

/* =================== */
/* = NAMED FUNCTIONS = */
/* =================== */
function getDays(){//get days between beginDate and endDate for further calculation down the line
	var one_day=1000*60*60*24;
	var beginDateVal = new Date($('input.beginDate').datepicker('getDate'));
	var endDateVal = new Date($('input.endDate').datepicker('getDate'));
	var result = Math.round((endDateVal - beginDateVal)/(one_day));
	result++;//++ to include starting day
	return result;
}

function getMonths(){//get months between beginDate and endDate for further calculation down the line
	var one_day=1000*60*60*24;
	var beginDateVal = new Date($('input.beginDate').datepicker('getDate'));
	beginDateVal.setDate(1);
	var endDateVal = new Date($('input.endDate').datepicker('getDate'));
	endDateVal.setDate(1);//get first day of month
	endDateVal.setMonth(endDateVal.getMonth()+1);//add a month
	endDateVal.setDate(endDateVal.getDate()-1);//subtract one day to get last day of chosen month
	var result = Math.ceil((endDateVal - beginDateVal)/(one_day)/31);
	return result;
}

function getFullMonths(date1,date2){
	var date1 = new Date(date1);
	if(date1.getDate() != 1){
		date1.setDate(1);
		date1.setMonth(date1.getMonth()+1);
	}
	//////console.log(date1);
	var date2 = new Date(date2);
	//////console.log(date2);
	var checker = new Date(date2);
		if(date2.getDate() != date2.getDaysInMonth()){
			date2.setDate(1);
			date2.setDate(date2.getDate()-1);
			////console.log(date2);
		}
	var one_day=1000*60*60*24;
	var result = Math.ceil((date2 - date1)/(one_day)/31);
	return result;	
}

function getRestDaysFirstMonth(date1){
	var date1 = new Date(date1);
	var totalDaysInMonth = date1.getDaysInMonth();
	var chosenDay = date1.getDate();
	var restDays = (totalDaysInMonth - chosenDay + 1)/totalDaysInMonth;
	return Math.round(restDays*1000)/1000;
}

function getRestDaysLastMonth(date2){
	var endDate = new Date(date2);
	var chosenDate = endDate.getDate();
	var daysInMonth = endDate.getDaysInMonth();
	var restDays = chosenDate/daysInMonth;
	//////console.log(result);
	return Math.round(restDays*1000)/1000;
}

function getMonthsPeriodDecimals(){
	var date1 = new Date($('input.beginDate').datepicker('getDate')); // 01/01/2010
	var date2 = new Date($('input.endDate').datepicker('getDate')); // 31/12/2010
	var fullMonths = getFullMonths(date1,date2);
	var restDaysBegin = 0;
	var restDaysEnd = 0;
	if(date1.getDate() != 1){
		restDaysBegin = getRestDaysFirstMonth(date1);
	}
	if(date2.getDate() != date2.getDaysInMonth()){
		restDaysEnd = getRestDaysLastMonth(date2);
	}
	return fullMonths + restDaysBegin + restDaysEnd;
}

function getMonthsVariationDecimals(date1,date2){
	//var date1 = new Date($('input.beginDate').datepicker('getDate')); // 01/01/2010
	//var date2 = new Date($('input.endDate').datepicker('getDate')); // 31/12/2010
	var fullMonths = getFullMonths(date1,date2);
	var restDaysBegin = 0;
	var restDaysEnd = 0;
	if(date1.getDate() != 1){
		restDaysBegin = getRestDaysFirstMonth(date1);
	}
	if(date2.getDate() != date2.getDaysInMonth()){
		restDaysEnd = getRestDaysLastMonth(date2);
	}
	return fullMonths + restDaysBegin + restDaysEnd;	
}

function getTauxBase(){
	var totalDays = getDays();
	var endDateVal = new Date($('input.endDate').datepicker('getDate'));
	var limit = new Date(2010,11,31);
	if(endDateVal>=limit){var tauxBase = 3.800;}//current taux
	else{var tauxBase = 4.473;}//taux of previous year!
	return tauxBase;
}

function setDateAndStuff(){//execute function when a date2 is picked
	var obj = $(this);//get the object that was clicked on, saved in a variable. this is always a date2 field as date1 is not selectable.
	var date1 = $(this).datepicker("getDate");//get the date object from the datepicker
	var myDate = new Date(date1);//copy the chosen date for manipulation
	var endOfPeriod = $('input.endDate').datepicker("getDate");
	
	//get the last day for the chosen month
	myDate.setDate(1);//get first day of month
	myDate.setMonth(myDate.getMonth()+1);//add a month
	myDate.setDate(myDate.getDate()-1);//subtract one day to get last day of chosen month
	//console.log(myDate);
	//get previous date
	var prevdate = $(this).prev().datepicker("getDate");//get the date1 date object
	//prevdate.setDate(1);
	// ////console.log(prevdate);
	var duration = getMonthsVariationDecimals(prevdate,myDate);
	// ////console.log(duration);
	$(this).next().html(duration);
	
	if(myDate>endOfPeriod){
		myDate=endOfPeriod;
	}
	$(this).parent().find('input.nbr').trigger('keyup'); //trigger a keyup for the nbr input so the monthtotal gets recalculated
	$(this).val($.datepicker.formatDate('dd-mm-yy', myDate));
	var endDateValue = $('input.endDate').val();
	var thisParentIndex = $(this).parent().index();
	if($(this).val() != endDateValue){
		myDate.setDate(myDate.getDate()+1);//now add one day to the result for insertion in the following box
		$(obj).parent().next().slideDown(500).addClass("working visible");//1. show the next div and add the class working for further manipulation later
		$('div.working input.date').datepicker('destroy');//destroy existing datepicker
		$('div.working input.date').datepicker({ dateFormat: 'dd-mm-yy'}).attr("disabled", true);//add a datepicker to input.date and disable user interaction
		$('div.working input.date').datepicker('setDate',myDate);//set the date to the UPDATED calculated date (mydate+1 = first day of next month)
		date1 = $('div.working input.date').datepicker('getDate');
		
		date1.setDate(1);
		myDate.setMonth(myDate.getMonth()+1);//add 1 month to the result for insertion in the following box
		myDate.setDate(myDate.getDate()-1);//subtract one day to the result to get the last day of the chosen month
		$('div.working input.date2').datepicker('setDate',endOfPeriod).datepicker( "option", "minDate", myDate );
		date2 = $('div.working input.date2').datepicker('getDate');
		//date2.setDate(1);//get first day of month
		date2.setMonth(date2.getMonth()+1);//add 1 month to the result for insertion in the following box
		date2.setDate(date2.getDate()-1);//subtract one day to the result to get the last day of the chosen month
		duration = getMonthsVariationDecimals($('div.working input.date').datepicker('getDate'),endOfPeriod);//duration... in months
		$('div.working span.months').html(duration);
		$(this).parent().parent().find('div.line').slice(thisParentIndex+1).hide().removeClass('visible');
		
		$('div.working').find('input.nbr').trigger('keyup');//calculate the monthtotal for the new line
		$('div.working').removeClass("working");
		
		
	} else {
		
		$(this).parent().parent().find('div.line').slice(thisParentIndex).hide().removeClass('visible');
		$(this).parent().parent().find('div.line input.nbr').slice(thisParentIndex).val('0,00');
		$(this).parent().find('input.nbr').trigger('keyup');//recalculate the total for the year
	}
	//lastly, calculate and set the variation for current question
	var variationStart = $(this).parent().parent().parent().find('div.line input.nbr:visible:first').parseNumber();
	var variationEnd = $(this).parent().parent().parent().find('input.blue').parseNumber();
	//////console.log(variationEnd);
	var variation = variationEnd-variationStart;
	//////console.log(variationStart);
	//////console.log(variationEnd-variationStart);
	if($(this).closest('div.page').is('#page3')){//this inverts all variations on page 3!! 
			variation = -variation;
		}
	$(this).parent().parent().parent().find('span.variation').html(variation);
	$('span.variation').format({format:"#,###.00", locale:"fr"});
}

function checkifbothset(){//checks if bot beginDate and endDate are set, and if so, shown nav button
	if( $('input.endDate').val() != '' && $('input.beginDate').val() != '' ) {
	    $('div#page1 img.to2').fadeIn(2000);
	}	
}

function h_i_j(){
	var e = new Number($('span.e1').parseNumber());
	//////console.log("e = "+e);
	var f = new Number($('input.f1').parseNumber());
		if(f>e){//f must be <= e!
			f=e;
			$("input.f1").val(e).format({format:"#,###.00", locale:"fr"});
		};
	//////console.log("f = "+f);
	var g = new Number($('span.g1').parseNumber());
	//////console.log("g = "+g);
	var h = new Number($('input.h1').parseNumber());
	h = Math.round(h*100)/100;
	//h=h.toFixed(3);
	//////console.log("h = "+h);
	var i = new Number($('input.i1').parseNumber());
		if(i>h){//f must be <= e!
			i=h;
			$("input.i1").val(h).format({format:"#,###.00", locale:"fr"});
		};
	//////console.log("i = "+i);
	$('span.g1').html(e-f);
	//////console.log("g = "+g);
	$('#page6 span.g1').format({format:"#,###.00", locale:"fr"});
	//////console.log("new g = "+g);
	$('span.j1').html(f+i);
	//////console.log("j = "+(f+i));
	$('#page6 span.j1').format({format:"#,###.00", locale:"fr"});
	var eb = new Number($('span.e1').parseNumber());
	var fb = new Number($('input.f1').parseNumber());
	var gb = new Number($('span.g1').parseNumber());
	var hb = new Number($('input.h1').parseNumber());
	hb = Math.round(hb*100)/100;
	//////console.log(hb);
	var ib = new Number($('input.i1').parseNumber());
	var k = gb+(hb-ib);
	//////console.log("k = "+k);
	$('span.k1').html(k).format({format:"#,###.00", locale:"fr"});
	//$('#page6 span.k1').format({format:"#,###.00", locale:"fr"});
}

function calcFields(){
	//calculate, set, and format A
	$('#page6 span.a1').html($('input.a1').sum());//CALCULATE and SET A1
	$('#page6 span.a1').format({format:"#,###.00", locale:"fr"});
	
	//calculate, set, and format all B elements
	$('#page6 span.b1').html($('#page3 div.question div.question.b1 input.first').val());//CALCULATE and SET B1
	$('#page6 span.b2').html($('#page3 div.question div.question.b2 input.first').val());//CALCULATE and SET B2
	$('#page6 span.b3').html($('#page3 div.question div.question.b3 input.first').val());//CALCULATE and SET B3
	$('#page6 span.b4').html($('#page3 div.question div.question.b4 input.first').val());//CALCULATE and SET B4
	$('#page6 span.b5').html($('#page3 div.question div.question.b5 input.first').val());//CALCULATE and SET B5
	$('#page6 span.b6').html($('#page3 div.question div.question.b6 input.first').val());//CALCULATE and SET B6
	$('#page6 span.b7').html($('#page3 div.question div.question.b7 input.first').val());//CALCULATE and SET B7
	$('#page6 span.b8').html($('#page3 div.question div.question.b8 input.first').val());//CALCULATE and SET B8
	$('#page6 span.b9').html($('#page3 div.question div.question.b9 input.first').val());//CALCULATE and SET B9
	$('#page6 span.b10').html($('#page3 div.question div.question.b10 input.first').val());//CALCULATE and SET B10
	$('#page6 span.b11').html($('#page3 div.question div.question.b11 input.first').val());//CALCULATE and SET B11
	$('#page6 span.b12').html($('#page3 div.question div.question.b12 input.first').val());//CALCULATE and SET B12
	$('#page6 span.b13').html($('#page3 div.question div.question.b13 input.first').val());//CALCULATE and SET B13
	$('#page6 span.btotal').html($('span.b').sum());
	$('#page6 span.btotal').format({format:"#,###.00", locale:"fr"});
	var positivevariations = $('span.variation').filter( function(){//get sum of positive variations
		if($(this).html().indexOf( "-" ) == -1) {return true;} else {return false;}
	}).sum();
	var negativevariations = $('span.variation').filter( function(){//get sum of negative variations
		if($(this).html().indexOf( "-" ) != -1) {return true;} else {return false;}
	}).sum();
	$('#page6 span.c1').html(positivevariations);
	$('#page6 span.c1').format({format:"#,###.00", locale:"fr"});
	$('#page6 span.c2').html(-negativevariations);//invert the negative number to match the final result formatting
	$('#page6 span.c2').format({format:"#,###.00", locale:"fr"});
	var a1 = parseFloat($('#page6 span.a1').parseNumber());
	var btotal = parseFloat($('#page6 span.btotal').parseNumber());
	var c1 = parseFloat($('#page6 span.c1').parseNumber());
	var c2 = parseFloat($('#page6 span.c2').parseNumber());
	var p1 = Math.round((a1-btotal+c1-c2)*100)/100;
	if(p1<0){p1=0};
	//////console.log(p1);
	$('#page6 span.d1').html(p1);
	$('#page6 span.d1').format({format:"#,###.00", locale:"fr"});
	
	//calculate e
	var a = $('#page4 div.middle p.wide').html();
	var totalDays = getDays();
	var endDateVal = new Date($('input.endDate').datepicker('getDate'));
	var limit = new Date(2010,11,31);
	var tauxDeBase = getTauxBase();
	if(a.indexOf('majoré') != -1){
		tauxDeBase +=0.500;
	}
	var tauxCalc = Math.round((tauxDeBase*totalDays/365)*1000)/1000;
	//console.log(tauxCalc);
	var tarif = Math.round(p1*tauxCalc)/100;
	$('span.e1').html(tarif);	
	$('#page6 span,#page6 input.nbr').format({format:"#,###.00", locale:"fr"});//format results
	$('span.e1').format({format:"#,###.00", locale:"fr"});//format results
	$("#page6 span:contains('NaN,Na')").html('---');//format errors
	h_i_j();
}

function taux_maj(){
	$('div#page4 span').val('0');//reset counters
	
	if($('div#page4 div.chiffre input.y2011').parseNumber() > 7300000){
		$('div#page4 div.chiffre span.y2011').html('1');
	} else $('div#page4 div.chiffre span.y2011').html('0');
	
	if($('div#page4 div.chiffre input.y2010').parseNumber() > 7300000){
		$('div#page4 div.chiffre span.y2010').html('1');
	}else $('div#page4 div.chiffre span.y2010').html('0');
	
	if($('div#page4 div.bilan input.y2011').parseNumber() > 3650000){
		$('div#page4 div.bilan span.y2011').html('1');
	} else $('div#page4 div.bilan span.y2011').html('0');
	
	if($('div#page4 div.bilan input.y2010').parseNumber() > 3650000){
		$('div#page4 div.bilan span.y2010').html('1');
	} else $('div#page4 div.bilan span.y2010').html('0');
	
	if($('div#page4 div.travailleurs input.y2011').parseNumber() > 50 && $('div#page4 div.travailleurs input.y2011').parseNumber() <= 100){
		$('div#page4 div.travailleurs span.y2011').html('1');} 
	else if($('div#page4 div.travailleurs input.y2011').parseNumber() > 100){
		$('div#page4 div.travailleurs span.y2011').html('2');}	
	else {$('div#page4 div.travailleurs span.y2011').html('0');}
	
	if($('div#page4 div.travailleurs input.y2010').parseNumber() > 50 && $('div#page4 div.travailleurs input.y2010').parseNumber() <= 100){
		$('div#page4 div.travailleurs span.y2010').html('1');} 
	else if($('div#page4 div.travailleurs input.y2010').parseNumber() > 100){
		$('div#page4 div.travailleurs span.y2010').html('2');}	
	else {$('div#page4 div.travailleurs span.y2010').html('0');}
	
	$('div#page4 span').format({
		format:"0,000.00", locale:"fr"//some number formatting first
	});
	var tauxDeBase = getTauxBase();
	var tauxMajore = tauxDeBase+0.500;
	var endDateVal = new Date($('input.endDate').datepicker('getDate'));
	var limit = new Date(2010,11,31);
	var totalDays = getDays();
	var tauxCalc = Math.round((tauxDeBase*totalDays/365)*1000)/1000;
	var tauxCalcMaj = Math.round((tauxMajore*totalDays/365)*1000)/1000;
	
	
	if(($('div#page4 span.y2011').sum()>1) || ($('div#page4 span.y2010').sum()>1)){
		$('div#page4 p.wide').html('Taux normal ('+tauxDeBase+'%)');
		if(endDateVal>=limit){
			$('div#page4 p.wide2').html('Année d\'imposition : 2011');
		}//current taux
		else{
			$('div#page4 p.wide2').html('Année d\'imposition : 2010');
		}
		$('div#page4 p.wide3').html('Taux d\'application : '+tauxCalc+'%');
	} 
	
	
	else {
		$('div#page4 p.wide').html('Taux majoré ('+tauxDeBase+' + 0,5% = '+tauxMajore+'%)');
		if(endDateVal>=limit){
			$('div#page4 p.wide2').html('Année d\'imposition : 2011');
		}//current taux
		else{
			$('div#page4 p.wide2').html('Année d\'imposition : 2010');
		}
		$('div#page4 p.wide3').html('Taux d\'application : '+tauxCalcMaj+'%');
	}
	
	
}


/* ======== */
/* = PREP = */
/* ======== */
$(function(){//show first page on document ready
		$('div.page').hide(); //@TODO: UNCOMMENT WHEN DONE
		$('div.page#page1').addClass('current').fadeIn();	
});

$(function(){// make div.page div.question input.nbr numeric and allow commas and numbers only
	$('div.page div.question input.nbr').numeric({allow:",-"});
});

$(function(){//initially set all line totals to 0,00
	$('div#page2 span.linetotal,div#page3 span.linetotal').html('0.00');
});

$(function(){//disable date inputs and Make the first line for each question visible in the browser
		$('div.line[class*=first]').addClass('visible');
		//var defDate = new Date(2010,11,31);
		$('input.date, input.date2').attr('disabled','disabled');	
});


/* ============== */
/* = NAVIGATION = */
/* ============== */
$(function(){//nav buttons 2
		$('img.to2').click(function(){
			$('div.page').hide();
			$('div#page2').fadeIn();
			$('input.nbr.code15').keyup();
			//$('input.code15').next().next().attr("disabled", true);
		});		
});

$(function(){//nav buttons 3
		$('img.to3').click(function(){
			$('div.page').hide();
			$('div#page3').fadeIn();
			//$('input.nbr.code15').keyup();
			$('div.b11').remove();
			$("div.cadrea.a1:last").clone(true).removeAttr("id").removeClass("cadrea a1").addClass('cadreb b11').insertBefore("div.b12");
			$('div.b11 input.nbr').removeClass('a1').keyup();
			//$('span.variation').sum();
			$('div.question.b11 input:visible').attr("disabled", true);
			$('div.question.b11 div.label p').append(' <img id="b11" class="info" alt="Info Icon" src="css/images/info-icon.png">');
			$('#b11').qtip({
				content: '<p>Le montant des subsides en capital.</p><p style="color:lightgrey;font-style:italic;">Afin d\'assurer un calcul correct, ces montants sont figés. Afin de modifier les montants des subsides en capital, veuillez vous référer à la page précédente.</p>', 
				position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
				show: { effect: { type: 'fade',length: 1}}, 
				hide: { when: 'mouseout', fixed: true }, 
				style:{tip:true,name:'mystyle'} 
			});
		});		
});

$(function(){//nav buttons 4
		$('img.to4').click(function(){
			$('div.page').hide();
			$('div#page4').fadeIn();
		});		
});

$(function(){//nav buttons 5
		$('img.to5').click(function(){
			$('div.page').hide();
			$('div#page5').fadeIn();
		});		
});

$(function(){//nav buttons 6
		$('img.to6').click(function(){
			calcFields();
			$('div.page').hide();
			$('div#page6').fadeIn();
		});		
});


/* =========================== */
/* = BEGINDATE ENDDATE SETUP = */
/* =========================== */
$(function(){//stuff to do when beginDate gets set by user
	$('input.beginDate').change(function(){
		var date1 = $(this).datepicker("getDate");//get the date object from the datepicker
		var myDate = new Date(date1);
	//get last day of the chosen month
	//myDate.setDate(1);//get first day of month
	$(this).val($.datepicker.formatDate('dd-mm-yy', myDate));//some formatting
	$('div#page2 div.inputs div.line.first input.date,div#page3 div.inputs div.line.first input.date').datepicker({ dateFormat: 'dd-mm-yy' }).datepicker( "setDate" , myDate);
	//in case endDate was already chosen, alter the minDate option in all existing date2 fields
	$('div#page2 div.inputs div.line.first input.date2.hasDatepicker,div#page3 div.inputs div.line.first input.date2.hasDatepicker').datepicker('option', 'minDate', myDate);		
	checkifbothset();//force setting both dates before showing nav button
	});
});

$(function(){//stuff to do when endDate gets set by user
	$('input.endDate').change(function(){
		var date1 = $(this).datepicker("getDate");//get the date object from the datepicker
		var myDate = new Date(date1);//save chosen date in a variable
		var minDate = $('input.beginDate').datepicker("getDate");//get this to set the mindate option later
		//myDate.setDate(1);//get first day of month
		//myDate.setMonth(myDate.getMonth()+1);//add 1 month
		//myDate.setDate(myDate.getDate()-1);//subtract one day to get last day of chosen month
		$(this).val($.datepicker.formatDate('dd-mm-yy', myDate));//some formatting
		$('div.inputs input.date2').datepicker('destroy').datepicker({ dateFormat: 'dd-mm-yy', maxDate: myDate, minDate:minDate, onSelect:setDateAndStuff});//destroy any datepickers in date2 fields and replace with new options
		//	$('div.inputs input.date2').datepicker("option", maxDate, myDate);
        // $('div.line.first input.date2').val($.datepicker.formatDate('dd-mm-yy', myDate));
		$('input.date2').parent().parent().find('div.line.first input.date2').val($.datepicker.formatDate('dd-mm-yy', myDate));
		//$('div.line:not(.first)').slideUp(500).removeClass("visible");
		$('input.date2').attr('disabled','');
		checkifbothset();			
	});
});

$(function(){//calculate months between begindate and enddate on change
	$('input.beginDate, input.endDate').change(function(){
		var result = getMonthsPeriodDecimals();
		if($('input.beginDate').val() != "" && $('input.endDate').val() != ""){
			$('div.period p span').html('(' + result +' mois)');
			$('div.question .line span.months').html(result);
		}
	});
});

/* ============================= */
/* = INPUTS AND NUMBER FORMATS = */
/* ============================= */
$(function(){//switching from a number formats the number to the required format:"0,000.00", locale:"fr"
	$('input.nbr').blur(function(){
		var thisnumber = $(this).parseNumber();
		thisnumber = Math.round(thisnumber*100)/100; //rounds correctly. 0.155 => 0.16 and not 0.15... javascript issue. 
		$(this).val(thisnumber);
		//////console.log("this number = "+thisnumber);
		$('input.nbr').format({
			format:"0,000.00", locale:"fr"//some number formatting first
			
		});
		h_i_j();
	});
});

/* =================== */
/* = jQuery UI STUFF = */
/* =================== */
$(function() {//buttonset p5 replaces radio buttons
	$(".buttons").buttonset();
});
	
$(function(){//set default dates for begindate and enddate calendars (01/01/2010 and 31/12/2010)
	//disable date fields
	//$('input.date, input.date2').attr('disabled','disabled');
	var beginDate = new Date(2010,0,1);
	var endDate = new Date(2010,11,31);
	var maxDate = new Date(2011,11,30);
	$('input.beginDate').datepicker({ dateFormat: 'dd-mm-yy', defaultDate:beginDate}).datepicker( "setDate" , beginDate ).trigger('change');
	$('input.endDate').datepicker({ dateFormat: 'dd-mm-yy', defaultDate:endDate, minDate:beginDate, maxDate:maxDate}).datepicker( "setDate" , endDate ).trigger('change');		
});


/* ================ */
/* = CALCULATIONS = */
/* ================ */
$(function(){// set defaults for calculation plugin
	$.Calculation.setDefaults({
		// a regular expression for detecting European-style formatted numbers
		reNumbers: /(-|-\$)?(\d+(\ \d{3})*(,\d{1,})?|,\d{1,})?/g,
		// define a procedure to convert the string number into an actual usable number
		cleanseNumber: function (v){
			// cleanse the number one more time to remove extra data (like commas and dollar signs)
			// use this for European numbers: v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".")
			return v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
		}
	});
});

$(function(){// calculate total field value on input.nbr keyup and recalculate variation
	$('div#page2 div.line input.nbr,div#page3 div.line input.nbr').keyup(function(){
		//var obj = $(this);
		var fieldValue = $(this).val().replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
		var months = $(this).parent().find('span.months').html();
		var totalmonths = getMonthsPeriodDecimals();
		var number = months*parseFloat(fieldValue)/totalmonths;
		//console.log(months);
		//console.log(parseFloat(fieldValue));
		//console.log(totalmonths);
		//console.log(number);
		$(this).parent().find('span.linetotal').html(number);
		$(this).parent().find('span.linetotal').each(function(){
			$(this).format({format:"###.00000", locale:"fr"});
			$(this).text().replace(' ','');
		});
		var total = $(this).parent().parent().find('div.line:visible span.linetotal').sum();
		//var numberoflines = $(this).parent().parent().find('div.line:visible span.linetotal').length;
		var result = (total);
		result = Math.round(result*100)/100;
		//change this to first insert whole number, then format it.
		//result = result.toFixed(5);
		//console.log(result);
		$(this).parent().parent().find('div.total input.nbr').val(result);
		$('input.blue').format({format:"#,###.00", locale:"fr"});
		//lastly, calculate and set the variation for current question
		var variationStart = $(this).parent().parent().parent().find('div.line input.nbr:visible:first').parseNumber();
		var variationEnd = $(this).parent().parent().parent().find('input.blue').parseNumber();
		var variation = variationEnd-variationStart;
		
		if($(this).closest('div.page').is('#page3')){//this inverts all variations on page 3!! ALSO CHANGE CODE IN CALCFIELDS FUNCTION
			variation = -variation;
		}
		//////console.log(variationEnd, variationStart);
		$(this).parent().parent().parent().find('span.variation').html(variation);
		$('span.variation').format({format:"#,###.00", locale:"fr"});
	});
});

$(function(){// p4 taux majoré?
	$('div#page4 input').keyup(function(){
		taux_maj();
	});	
});

$(function(){//recalculate linetotal if date2 is changed
	$('div#page2 input.date2,div#page3 input.date2').change(function(){
		var fieldValue = $(this).val().replace(',','.');
		var months = $(this).parent().find('span.months').html();
		var number = parseInt(months, 10)*parseFloat(fieldValue);
		$(this).parent().find('span.linetotal').html(number);
		var total = $(this).parent().parent().find('span.linetotal:visible').avg();
	});
});

$(function(){//launch h_i_j calc on keyup of any of the fields involved
	$('input.f1, input.h1, input.i1').keyup(h_i_j);
});

//$(function(){//synchronize code15 elements
//	$('input.code15').blur(function(){
//		if($(this).closest('div.page').is('#page2')){
//			$('#page3 input.code15').val($(this).val());
//			$('#page3 input.code15').keyup();
//                        //console.log($(this).parent().index());
//		}
//		else {
//			$('#page2 input.code15').val($(this).val());
//                        $('#page2 input.code15').keyup();
//		}
//	});
//});



/* ===================== */
/* = ZOMG BUBBLES!1!1! = */
/* ===================== */
$(function(){//set defaults for info bubbles
	$.fn.qtip.styles.mystyle = { width: 200, textAlign: 'center', border: { radius: 5 }, name: 'dark'};
});

$(function(){//bubble 1
	$('div.question div.line:first input.nbr').qtip({content: '<p>Veuillez n\'utiliser QUE la virgule pour les décimales.</p><p> <strong>Pas de séparateur de milliers!</strong></p>', position: { corner: {target: 'leftCenter', tooltip: 'rightCenter' }}, show: { effect: { type: 'fade', length: 1}}, hide: { when: 'mouseout', fixed: true}, style:{ tip: true, name: 'mystyle'} });
});

$(function(){//bubble 2
	$('div.line:first input.date2').qtip({
		content: '<p>En cas de variations d\'un poste pendant l\'exercice, veuillez modifier la date de fin et remplir la nouvelle ligne avec le montant correspondant à la nouvelle période.</p>',
		position: {corner: {target: 'topCenter',tooltip: 'bottomCenter'}}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'}
	});
});

$(function(){//bubble 3: droit au taux de déduction majoré?
	$('#deduction_majoree').qtip({
		content: '<p>Lorsque plus de la moitié des produits résultant de l\'activité normale d\'une société sont des produits non visés par la définition du poste " chiffre d\'affaires ", il y a lieu d\'entendre par " chiffre d\'affaires ", <strong><em>le total des produits à l\'exclusion des produits exceptionnels.</em></strong></p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble 4: B2 code 28...
	$('#b1').qtip({
		content: '<p>Valeur fiscale nette des actions et parts propres à la fin de la période imposable précédente</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B1 code 50...
	$('#b2').qtip({
		content: '<p>Valeur fiscale nette des immobilisations financières consistant en participations et autres actions et parts à la fin de la période imposable précédente</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B3...
	$('#b3').qtip({
		content: '<p>Valeur fiscale nette à la fin de la période imposable précédente des actions ou parts émises par des sociétés d\'investissement dont les revenus sont susceptibles d\'être déduits des bénéfices en vertu des articles 202 et 203, CIR92</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B4...
	$('#b4').qtip({
		content: '<p>Différence positive entre la valeur comptable nette des éléments d\'actifs des établissements étrangers, à l\'exception des actions ou parts visées à l\'article 205ter, § 1er, alinéa 2, et le total des éléments de passif qui ne font pas partie des capitaux propres de la société et qui sont imputables à ces établissements</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B5...
	$('#b5').qtip({
		content: '<p>Différence positive entre la valeur comptable nette des immeubles situés à l\'étranger ou de droits relatifs à de tels immeubles (non affectés à un établissement étranger) et le total des éléments du passif qui ne font pas partie des capitaux propres de la société et qui sont imputables à ces immeubles ou droits</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B6...
	$('#b6').qtip({
		content: '<p>Valeur comptable nette des actifs dont les frais y afférents dépassent de manière déraisonnable les besoins professionnels. Exemple: voitures de grand luxe</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B7...
	$('#b7').qtip({
		content: '<p>Valeur comptable nette des actifs détenus à titre de placement n\'étant pas destinés à produire un revenu périodique. Exemple: or, bijoux, oeuvres d\'art, actions de capitalisation</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B8...
	$('#b8').qtip({
		content: '<p>Valeur comptable nette des immeubles occupés par un dirigeant d\'entreprise. Uniquement la partie privée si votre comptabilité distingue partie privée et professionnelle.</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B9...
	$('#b9').qtip({
		content: '<p>Les plus-values exprimées mais non réalisées visées à l\'art. 44, § 1er; 1º, CIR92, qui ne portent pas sur des éléments de l\'actif visés aux points 4 à 8 supra</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B10...
	$('#b10').qtip({
		content: '<p>Le montant du crédit d\'impôt pour recherche et développement visé aux art. 298 quater et suivants, CIR92</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B11...
	$('#b11').qtip({
		content: '<p>Le montant des subsides en capital</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B12...
	$('#b12').qtip({
		content: '<p>Le montant visé à l\'art. 4de la loi du 26.12.2006 portant sur une mesure d\'accompagnement pour l\'actualisation des stocks par les diamantaires agréés</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});

$(function(){//bubble: B13...
	$('#b13').qtip({
		content: '<p>le montants des moyens empruntés dans le chef du siège principal, dont les intérêts sont à charge du résultat imposable de(s) l\'établissement(s) belge(s) (ce montant est à déduire des capitaux propres dudit (desdits) établissement(s)).</p>', 
		position: {	corner: {target: 'rightCenter',	tooltip: 'leftTop' }}, 
		show: { effect: { type: 'fade',length: 1}}, 
		hide: { when: 'mouseout', fixed: true }, 
		style:{tip:true,name:'mystyle'} 
	});
});
