function empty( mixed_var ) {	// Determine whether a variable is empty
	return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false  ||  ( mixed_var.isArray && mixed_var.length === 0 ) || 
		(typeof(mixed_var)==='object' && mixed_var.length === 0));
}
function consolelog(message){
	if(console !== undefined)
		console.log(message);
}

var calc = {
	currency_short_names:{'RUR':' р.','EUR_USD':'$'},
	depo_db: '',
	current_deposit: '',
	currency: false,
	sum: 0,
	percent: 0,
	days: 0,
	cashing_type: false,// mounth, capitalization, minimal_balance,end_cashing
	begin_date: '',
	end_date: '',
	min_days: 0,
	max_days: 0,
	hashEncode:function(obj){
		var ret = "#params[";
		for(i in obj){
			ret += i+":"+obj[i]+"|";
		}
		ret+="]";
		return ret;
	},
	hashDecode:function(str){
		 str = str.replace('#params[','').replace(']','').split('|');
		 var r   = {};
		 var tmp = [];
		 for(i in str){
		  tmp = str[i].split(":");
		  if(tmp[1]===undefined) continue;
		  r[tmp[0]] = tmp[1];
		 }
		 return r;
	},
	loadDepositParams: function(deposit){
		if(document.location.hash !="")
			var params = calc.hashDecode(document.location.hash);
		this.current_deposit = deposit;
		if(document.location.hash !="")
			var days = this.days = params.days;
		else 
			var days = this.days = Math.round((deposit.max_d-deposit.min_d)/3+deposit.min_d);
		var count = 0;

		this.cashing_type = false;
		$('#cashing_type').empty();
		$('#minimal_balance_row').css({'display':'none'});
		if(deposit.mounth_cashing){
			if(!this.cashing_type) this.cashing_type = 'mounth_cashing';
			$('#cashing_type').append($('<option></option>').val('mounth_cashing').html('Ежемесячная выплата на счет'));	
		}
		if(deposit.capitalization_deposit){
			if(!this.cashing_type) this.cashing_type = 'capitalization_deposit';
			$('#cashing_type').append($('<option></option>').val('capitalization_deposit').html('Ежемесячная(ежедневная) капитализация'));
		}
		if(deposit.end_cashing){
			if(!this.cashing_type) this.cashing_type = 'end_cashing';
			$('#cashing_type').append($('<option></option>').val('end_cashing').html('Выплата в конце срока'));
		}
		if(deposit.minimal_balance){
			if(!this.cashing_type) this.cashing_type = 'minimal_balance';
			$('#cashing_type').append($('<option></option>').val('end_cashing').html('С вожмозностью частичного снятия средств'));
			$('#minimal_balance_row').css({'display':'block'});
		}

		$('#cashing_type').change(function(){
			calc.cashing_type = $('#cashing_type option:selected').val();
			calc.writeNewValues(calc.sum,calc.days);
		});
		$('#minimal_balance').change(function(){
			var min = $('#minimal_balance option:selected').val();
			var deposit = calc.current_deposit;
			var currency = calc.currency;
			var min_summ = calc.tables[min].min_summ;
			if(document.location.hash !="")
				var sum = calc.sum = params.sum;
			else
				var sum = calc.sum = Math.round((deposit.deposites[currency].max_summ - min_summ)/3+min_summ);
			var maxSumm = deposit.deposites[currency].max_summ
			var max = 1000*Math.log(parseInt(maxSumm));
			$( "#slider-summ" ).slider({
				range: "min",
				value: 1000*Math.log(sum),
				min:   1000*Math.log(parseInt(min_summ)),
				max:   max,
				step:  1,
				slide: function( event, ui ) {
					if(ui.value != max)
						var sum = calc.sum = 1000*Math.round(Math.pow(Math.E,parseInt(ui.value)/1000)/1000);
					else
						var sum = calc.sum = maxSumm;
					var days = calc.days = $("#slider-duration").slider("value");
					calc.writeNewValues(sum,days);
				}
			});

			$("#summ_amount").val(sum + calc.currency_short_names[currency]);
			$("#summ_amount").change(function(){
				var new_sum = parseInt($(this).val());
			if (new_sum < deposit.deposites[currency].min_summ)
				new_sum = deposit.deposites[currency].min_summ;
			else if(new_sum > deposit.deposites[currency].max_summ)
				new_sum = deposit.deposites[currency].max_summ;
				$(this).val(new_sum);
				var sum = calc.sum = new_sum;

				var days = calc.days = $("#slider-duration").slider("value");
				calc.writeNewValues(sum,days);
			});
			$("#summ_slider_left").text(min_summ);
			$("#summ_slider_right").text(deposit.deposites[currency].max_summ);
			calc.writeNewValues(sum,$("#slider-duration").slider("value"));
		});
		//duration slider initialization begin//
		this.min_days = deposit.min_d;
		this.max_days = deposit.max_d;
		$( "#slider-duration" ).slider({
			range: "min",
			value: days,
			min: parseInt(deposit.min_d),
			max: parseInt(deposit.max_d),
			slide: function( event, ui ) {
				var sum = calc.sum = parseInt($( "#summ_amount" ).val());
				var days = calc.days = parseInt(ui.value);
				calc.end_date = meDate.addDays2Date(calc.begin_date,days);
				calc.changePickerValues(calc.begin_date,calc.end_date);
				calc.writeNewValues(sum,days);
			}
		});
		$("#duration_amount" ).val( $( "#slider-duration" ).slider( "value" ) + " дней");
		$("#duration_amount").unbind('change');
		$("#duration_amount").bind('change',function(){
			var sum = calc.sum = parseInt($("#summ_amount").val());
			var new_days = parseInt($(this).val());
			if (new_days < deposit.min_d){
				new_days = deposit.min_d;
			}
			else if(new_days > deposit.max_d){
				new_days = deposit.max_d;
			}

			$(this).val(new_days);
			var days = new_days;
			calc.end_date = meDate.addDays2Date(calc.begin_date,days);
			calc.changePickerValues(calc.begin_date,calc.end_date);
			calc.writeNewValues(sum,days);
		});
		$("#duration_slider_left").text(deposit.min_d);
		$("#duration_slider_right").text(deposit.max_d);
		this.begin_date= new Date();
		this.end_date= meDate.addDays2Date(this.begin_date,days);
		this.initDatePickers(this.begin_date,this.end_date);
		//-------------end------------------//
		$('#depo_currency').empty();
		for(i in deposit.deposites){
			$('#depo_currency').append($('<option></option>').val(i).html(deposit.deposites[i].currency_name));

			if(!count){
				this.currency = i;

				//---amount slider initialization---//
				this.loadNewCurrency(i);
				//-------------end------------------//
				count++;

			}
		}
		$('#depo_currency').change(function(){
			calc.currency = $('#depo_currency option:selected').val();
			calc.loadNewCurrency(calc.currency);
		});

		if(document.location.hash !=""){
			var params = calc.hashDecode(document.location.hash);
			this.cashing_type= params.cashing_type;
			this.loadNewCurrency(params.currency);
			this.sum = params.sum;
		}
		this.writeNewValues(this.sum,this.days);
	},

	loadNewCurrency:function(currency){

		deposit = this.current_deposit;
		this.currency = currency;
		this.loadTables();
		if(this.cashing_type == 'minimal_balance'){
			$('#minimal_balance').empty();
			var count;
			var selected;
			for(i in this.tables){
				if(!count){
					selected ="selected";
					count=1;
				}
				$('#minimal_balance').append($('<option '+selected+'></option>').val(i).text(this.tables[i].min_summ));
				selected = "";
			}
		}
		if(currency == "RUR")
			var koef = 1000;
		else
			var koef = 100;
		var sum = this.sum = Math.round((deposit.deposites[currency].max_summ - deposit.deposites[currency].min_summ)/3+deposit.deposites[currency].min_summ);
		var max = koef*Math.log(parseInt(deposit.deposites[currency].max_summ));
		var maxSumm = deposit.deposites[currency].max_summ;
		$( "#slider-summ" ).slider({
			range: "min",
			value: Math.log(sum)*koef,
			min:   koef*Math.log(parseInt(deposit.deposites[currency].min_summ)),
			max:   max,
			step:  1,
			slide: function( event, ui ) {
				if(ui.value != max)
					var sum = calc.sum = koef*Math.round(Math.pow(Math.E,parseInt(ui.value)/koef)/koef);
				else 
					var sum = calc.sum = maxSumm;
				var days = calc.days = $("#slider-duration").slider("value");
				calc.writeNewValues(sum,days);
			}
		});
		$("#summ_amount").val(sum + calc.currency_short_names[currency]);
		$("#summ_amount").unbind('change');
		$("#summ_amount").bind('change',function(){
			var new_sum = parseInt($(this).val());
			if (new_sum < deposit.deposites[currency].min_summ)
				new_sum = deposit.deposites[currency].min_summ;
			else if(new_sum > deposit.deposites[currency].max_summ)
				new_sum = deposit.deposites[currency].max_summ;
			$(this).val(new_sum);
			var sum = calc.sum = new_sum;
			var days = calc.days = $("#slider-duration").slider("value");
			calc.writeNewValues(sum,days);
		});
		$("#summ_slider_left").text(deposit.deposites[currency].min_summ);
		$("#summ_slider_right").text(deposit.deposites[currency].max_summ);
		this.writeNewValues(sum,$("#slider-duration").slider("value"));
		
	},
	initDatePickers:function(begin, end){
		$('#begin_day').empty();
		$('#end_day').empty();
		$('#begin_month').empty();
		$('#end_month').empty();
		$('#begin_year').empty();
		$('#end_year').empty();
		var selected = "";
		for(var i = 1;i<=meDate.getDaysInMonthDate(begin);i++)
		{
			if(begin.getDate() == i) selected = "selected";
			$('#begin_day').append($('<option '+selected+'></option>').val(i).text(i));
			selected = "";
		}
		for(var i = 1;i<=meDate.getDaysInMonthDate(end);i++)
		{
			if(end.getDate() == i) selected = "selected";
			$('#end_day').append($('<option '+selected+'></option>').val(i).text(i));
			selected = "";
		}
		for(i in meDate.monthNames)
		{
			if(begin.getMonth()+1 == i) selected = "selected";
			$('#begin_month').append($('<option '+selected+'></option>').val(i).text(meDate.monthNames[i]));
			selected = "";
			if(end.getMonth()+1 == i) selected = "selected";
			$('#end_month').append($('<option '+selected+'></option>').val(i).text(meDate.monthNames[i]));
			selected = "";
		}
		for(var i=0; i<=3;i++)
		{
			var t = i+begin.getFullYear();
			if(i==0) selected = "selected";
			$('#begin_year').append($('<option '+selected+'></option>').val(t).text(t));
			selected = "";
			if(end.getFullYear() == t) selected = "selected";
			$('#end_year').append($('<option '+selected+'></option>').val(t).text(t));
			selected = "";
		}
		$('#begin_day').change(function()
		{
			var val = $(this).children('option:selected').val();
			var b_date = new Date(calc.begin_date.getFullYear(),calc.begin_date.getMonth(),val);
			var e_date = calc.end_date;

			if(meDate.getDays(b_date, calc.end_date) < calc.min_days){
				e_date = meDate.addDays2Date(b_date,calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date));
		});
		$('#end_day').change(function()
		{
			var val = $(this).children('option:selected').val();
			var e_date = new Date(calc.end_date.getFullYear(),calc.end_date.getMonth(),val);
			var b_date = calc.begin_date;

			if(meDate.getDays(b_date, e_date) < calc.min_days){
				b_date = meDate.addDays2Date(e_date,-calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date)+1);
		});
		$('#begin_month').change(function()
		{
			var val = $('#begin_month option:selected').val();
			var b_date = new Date(calc.begin_date.getFullYear(),val-1,calc.begin_date.getDate());
			var e_date = calc.end_date;
			if(meDate.getDays(b_date, calc.end_date) < calc.min_days){
				e_date = meDate.addDays2Date(b_date,calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date));
		});
		$('#end_month').change(function()
		{
			var val = $(this).children('option:selected').val();
			var e_date = new Date(calc.end_date.getFullYear(),val-1,calc.end_date.getDate());
			var b_date = calc.begin_date;

			if(meDate.getDays(b_date, e_date) < calc.min_days){
				b_date = meDate.addDays2Date(e_date,-calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date)+1);
		});
		$('#begin_year').change(function()
		{
			var val = $(this).children('option:selected').val();
			var b_date = new Date(val,calc.begin_date.getMonth(),calc.begin_date.getDate());
			var e_date = calc.end_date;

			if(meDate.getDays(b_date, calc.end_date) < calc.min_days){
				e_date = meDate.addDays2Date(b_date,calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date));
		});
		$('#end_year').change(function()
		{
			var val = $(this).children('option:selected').val();
			var e_date = new Date(val,calc.end_date.getMonth(),calc.end_date.getDate());
			var b_date = calc.begin_date;

			if(meDate.getDays(b_date, e_date) < calc.min_days){

				b_date = meDate.addDays2Date(e_date,-calc.min_days);
			}
			calc.changePickerValues(b_date,e_date);
			calc.writeNewValues(calc.sum, meDate.getDays(b_date,e_date)+1);
		});
		this.begin_date = begin;
		this.end_date = end;
	}, 
	changePickerValues:function(begin,end)
	{
		var eM = end.getMonth()+1;
		$('#end_day').empty();
		for(var i = 1;i<=meDate.getDaysInMonthDate(end);i++){
			$('#end_day').append($('<option></option>').val(i).text(i));
		}
		$('#end_day option:selected').removeAttr('selected');
		$('#end_day option[value='+end.getDate()+']').attr('selected',true);

		$('#end_month option:selected').removeAttr('selected');
		$('#end_month option[value='+eM+']').attr('selected',true);

		$('#end_year option:selected').removeAttr('selected');
		if(empty($('#end_year option[value='+end.getFullYear()+']')))
			$('#end_year').append($('<option></option>').val(end.getFullYear()).text(end.getFullYear()));
		$('#end_year option[value='+end.getFullYear()+']').attr('selected',true);
		var bM = begin.getMonth()+1;
		$('#begin_day').empty();
		for(var i = 1;i<=meDate.getDaysInMonthDate(begin);i++){
			$('#begin_day').append($('<option></option>').val(i).text(i));
		}
		$('#begin_day option:selected').removeAttr('selected');
		$('#begin_day option[value='+begin.getDate()+']').attr('selected',true);

		$('#begin_month option:selected').removeAttr('selected');
		$('#begin_month option[value='+bM+']').attr('selected',true);

		$('#begin_year option:selected').removeAttr('selected');

		$('#begin_year option[value='+begin.getFullYear()+']').attr('selected',true);
		this.begin_date = begin;
		this.end_date = end;

	},
	loadTables:function()
	{
		this.tables = this.current_deposit.deposites[this.currency].table;
	},
	loadDB: function(depo_db)
	{
		for(i in depo_db)
		{
			$('#depo_type').append($('<option></option>').val(i).html(depo_db[i]['title']));
		}
		this.depo_db = depo_db;
		$('#depo_type').change(function()
		{
			var deposit_id = $('#depo_type option:selected').val();
			calc.loadDepositParams(calc.depo_db[deposit_id]);
		});
	},
	calcContributionWithCapitalization: function(sum,percent,days){
		var res = sum;
		for (var i=28;i<=31;i++){
			mPercent=1+percent*i/(100*365);
			res*=Math.pow(mPercent,meDate.getFCMbDwDC(this.begin_date,this.end_date,i)); 
		}
		res*=1+percent*(meDate.getDays2MonthEnd(this.begin_date)+this.end_date.getDate())/(100*365);
		return res;
	},
	calcCap:function(sum,percent){
		var res = sum;
		var currentMonth = this.begin_date.getMonth()+1;
		var currentYear  = this.begin_date.getFullYear();
		var cyclingProtection = 0;
		res *= 1+percent*meDate.getDays2MonthEnd(this.begin_date)/(100*365);
		res  = Math.ceil(res*100)/100;
		currentMonth++;
		if(currentMonth == 13){
			currentYear++;
			currentMonth = 1;
		}
		while(currentMonth != this.end_date.getMonth()+1 || currentYear != this.end_date.getFullYear()){			
			res *= 1+percent*meDate.getDaysInMonth(currentMonth,currentYear)/(100*365);
			res  = Math.ceil(res*100)/100; 
			currentMonth++;
			if(currentMonth == 13){
				currentYear++;
				currentMonth = 1;
			}
		}

		res *= 1 + percent*this.end_date.getDate()/(100*365);
		res  = Math.ceil(res*100)/100;
		return res;
	},
	calcContributionMounthCashing:function(sum,percent,days){
		//return Math.round(sum*(1+percent*days/(100*365)));
		var perc = 0;
		perc = meDate.getDays(this.begin_date,this.end_date)*percent/(100*365);
		return sum*(1+perc);
	},
	calcProfit: function(sum,old_sum){
		return sum - old_sum;
	},
	calcMounthProfit: function(profit,days){
		return profit*30/(days);
	},
	calcPercent: function(sum,days){
		var percTab = false;
		if(this.cashing_type == 'minimal_balance'){
			var min = $('#minimal_balance option:selected').val();
			percTab = this.tables[min].percentages;
			for(j in percTab){
				if(days>=percTab[j].min_d && days<=percTab[j].max_d)
						return percTab[j].p;
				}
		}
		else
			for(i in this.tables){
				if(sum >= this.tables[i].min_summ && sum < this.tables[i].max_summ){
					percTab = this.tables[i].percentages;
					for(j in percTab){
						if(days>=percTab[j].min_d && days<=percTab[j].max_d)
						{
							return percTab[j].p;
						}
					}
				}
			}
		return false;
	},
	writeNewValues: function(sum,days){
		this.days = days;
		this.sum = sum;
		var percent = this.percent = this.calcPercent(sum,days);
		if(this.currency == "RUR")
			var koef = 1000;
		else 
			var koef = 100;
		var contributionWithPercent = false; 
		switch(this.cashing_type) {
			case 'mounth_cashing': 
			case 'end_cashing':
			case 'minimal_balance':
				contributionWithPercent = this.calcContributionMounthCashing(sum,this.percent,days);
				$('#mounth_profit').css({'display':'block'});
				break;
			case 'capitalization_deposit':
				contributionWithPercent = this.calcCap(sum,this.percent,days);
				$('#mounth_profit').css({'display':'none'});
				break;
		}

		var summaryIncome = this.calcProfit(contributionWithPercent,sum);
		var mounthProfit = this.calcMounthProfit(summaryIncome,days);
		$("#money_summ").text( contributionWithPercent.toFixed(2) + this.currency_short_names[this.currency]);                                                         
		$("#summary_income").text(summaryIncome.toFixed(2) + this.currency_short_names[this.currency]);
		$("#month_income").text( mounthProfit.toFixed(2) + this.currency_short_names[this.currency]); 
		$("#summ_amount" ).val(sum + this.currency_short_names[this.currency]);

		$( "#slider-summ" ).slider("value", Math.log(sum)*koef);

		$( "#duration_amount" ).val( days + " дней" );
		$("#slider-duration").slider("value",days);
		$("#percents").val(calc.percent.toFixed(2)+ '%');
	}
};
