var DAYS_IN_MONTH = 30;
var DAYS_IN_YEAR = 360;


var names = new Array ( '«VIP»', '«Поощрительный»', '«Изобилие»', '«Универсальный»', '«Пенсионный»', '«Классический Успех»' );
var capitalisation = new Array ( 1, 0, 1, 0, 1, 0 );

var min_amount = new Array ();
min_amount[0] = new Array ( '1 000 000', '25 000' );
min_amount[1] = new Array ( '5 000', '100' );
min_amount[2] = new Array ( '4 000', '100' );
min_amount[3] = new Array ( '5 000', '100' );
min_amount[4] = new Array ( '1 000', '10' );
min_amount[5] = new Array ( '4 000', '100' );

var periods = new Array ();
periods[0] = new Array ( 3, 6, 9, 12, 18 );
periods[1] = new Array ( 3, 6, 9, 12, 18 );
periods[2] = new Array ( 3, 6, 12, 13, 18, 24 );
periods[3] = new Array ( 3, 6, 9, 12 );
periods[4] = new Array ( 3, 6, 12, 18 );
periods[5] = new Array ( 3, 6, 9, 12, 18, 24 );

var rates = new Array ();

rates[0] = new Array ();
rates[0][0] = new Array ( 6.0, 8.5, 10.5, 11.5, 12.5 );
rates[0][1] = new Array ( 1.5, 5.0, 7.0, 8.5, 9.5 );

rates[1] = new Array ();
rates[1][0] = new Array ( 4.0, 7.0, 8.0, 11.0, 11.5 );
rates[1][1] = new Array ( 1.0, 2.0, 4.0, 8.0, 8.5 );

rates[2] = new Array ();
rates[2][0] = new Array ( 6.0, 8.0, 11.0, 11.5, 12.0, 13.0 );
rates[2][1] = new Array ( 4.0, 6.0, 9.0, 9.5, 10.0, 11.0 );

rates[3] = new Array ();
rates[3][0] = new Array ( 4.5, 8.0, 10.0, 11.0 );
rates[3][1] = new Array ( 1.0, 4.0, 6.5, 8.0 );

rates[4] = new Array ();
rates[4][0] = new Array ( 6.0, 8.0, 11.0, 12.0 );
rates[4][1] = new Array ( 1.0, 4.5, 8.0, 9.0 );

rates[5] = new Array ();
rates[5][0] = new Array ( 6.0, 9.0, 10.0, 12.0, 13.0, 14.0 );
rates[5][1] = new Array ( 4.0, 7.0, 8.0, 10.0, 11.0, 12.0 );


var months = new Array ( 'январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь' );


var details = '';
var deposit = 0;

function details_print () { $( '#placeholder' ).html ( $( '#placeholder' ).html () + details ); }
function details_clear () { $( '#placeholder' ).html ( '' ); details = ''; }
function details_append ( info ) { details += info; }

function trim ( s ) { return s.replace (/ +/g, '' ); }

function format_decimal ( number ) {
	result = Math.round ( number * 100 ) / 100;
	result = result.toString ().replace ( /\$|\,/g, '' );
	if ( isNaN ( result ) ) result = '0';
	sign = ( result == ( result = Math.abs ( result ) ) );
	result = Math.floor ( result * 100 + 0.50000000001 );
	cents = result % 100;
	result = Math.floor ( result / 100 ).toString ();
	if ( cents < 10 ) cents = '0' + cents;
	for ( var i = 0; i < Math.floor ( ( result.length - ( 1 + i ) ) / 3); i++ )
	result = result.substring ( 0,result.length - ( 4 * i + 3 ) ) + ' ' + result.substring ( result.length - ( 4 * i + 3 ) );
	return ( ( ( sign ) ? '' : '-' ) + result + '.' + cents );	
}

function get_closing_date ( d, m, y, len ) {
	var result = new Array ();
	for ( i = 0; i < len; i++ ) {
		if ( 13 == m ) { m = 1; y++; }
		if ( 12 == m ) { var nextM = 1; var nextY = y+1;} else {var nextM = m+1; var nextY = y;}
		result[i] = new Array ( d, nextM < 10 ? '0' + nextM : nextM, nextY );
		m++;
	}
	return result;
};

function select_option ( combo, index ) {
	var obj = $ ( '#' + combo );

	obj.get ( 0 ).selectedIndex = index;
	obj.trigger ( 'change' );
}

function refresh () {
	deposit = parseInt ( $( '#name' ).val () );
	if ( isNaN ( deposit ) ) deposit = 0;

	var combo = $( '#period' );
	combo.empty ();
	for ( i = 0; i < periods[deposit].length; i++ ) {
		$( '<option></option>' )
			.attr ( 'value', i )
			.html ( periods[deposit][i] )
			.appendTo ( combo );
	}
	select_option ( 'period', 2 );

	$( '#amount' ).val ( min_amount[deposit][$( '#currency' ).val ()] );
}

function update () {
	var period = parseInt ( $( '#period' ).val () );
	if ( isNaN ( period ) ) period = 2;

	var len = parseInt ( $( '#period option:selected' ).text () );
	var date = get_closing_date ( day, month, year, len );

	$( '#rate' ).val ( rates[deposit][$( '#currency' ).val ()][period] + '%' );

	$( '#date_day' ).val ( day );
	$( '#date_month' ).val ( months[month-1] );
	$( '#date_year' ).val ( year );

	$( '#date_close_day' ).val ( day );
	$( '#date_close_month' ).val ( months[date[date.length-1][1]-1] );
	$( '#date_close_year' ).val ( date[date.length-1][2] );
};

function error ( description ) {
	$( '#error' ).text ( description ).slideDown ( 'normal' );
	setTimeout ( function () {
		$( '#error' ).text ( description ).slideUp ( 600 );
	}, 10000 );
}

function check () {
	var amount = parseInt ( trim ( $( '#amount' ).val () ) );
	if ( isNaN ( amount ) ) {
		error ( 'Некорректное значение суммы вклада.' ); 
		return false;
	}
	if ( amount < 0 ) {
		error ( 'Сумма вклада меньше нуля.' ); 
		return false;
	}
	if ( amount < min_amount[deposit][$( '#currency' ).val ()] ) {
		error ( 'Сумма вклада меньше минимальной.' ); 
		return false;
	}
	return true;
}

function calculate () {
	if ( ! check () ){
		return false;
	}

	var s = parseInt ( trim ( $( '#amount' ).val () ) );
	var p = rates[deposit][$( '#currency' ).val ()][$( '#period' ).val ()];
	var m = parseInt ( $( '#period option:selected' ).text () );
	var t = 0;
	var d = get_closing_date ( day, month, year, m );
	var c = capitalisation[deposit];

	details_clear ();
	details_append ( '<h3>Детализация начислений</h3>' );
	details_append ( '<ul>' );

	for ( i = 0; i < m; i++ ) {
		var tmp;
		if ( c ) {
			tmp = (s + t) * (p / 100) * DAYS_IN_MONTH / DAYS_IN_YEAR;
		} else {
			tmp = s * (p / 100) * DAYS_IN_MONTH / DAYS_IN_YEAR;
		}
		t += parseFloat ( trim ( format_decimal ( tmp ) ) );
		details_append ( "<li><span class='green'>" + d[i][0] + '.' + d[i][1] + '.' + d[i][2] + '</span>' + format_decimal ( tmp ) + '</li>' );
	}

	details_append ( '</ul>' );

	$( '#percent' ).val ( format_decimal ( t ) );
	$( '#summ' ).val ( format_decimal ( s + t ) );

	details_print ();

	return false;
};

function calendar ( date ) {
	var array = date.split ( '.' );

	year = parseInt ( array[2] );
	month = parseInt ( array[1] );
	day = parseFloat ( array[0] );

	update ();
};

$( document ).ready ( function () {
	var combo = $( '#name' );
	for ( i = 0; i < names.length; i++ ) {
		$( '<option></option>' )
			.attr ( 'value', i )
			.html ( names[i] )
			.appendTo ( combo );
	}

	$( '#name' ).bind ( 'change', refresh );
	$( '.update-on-change' ).bind ( 'change', update );

	select_option ( 'name', 0 );

	$( '#calculator' ).bind ( 'submit', calculate );
	$( '#date_day' ).datepicker ( {
		dayNamesMin: [ 'Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
		hideIfNoPrevNext: true,
		monthNamesShort: [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ],
		onSelect: calendar,
		yearRange: '2009:2015'
	} );
	$( '#calendar' ).bind ( 'click', function () {
		$( '#date_day' ).triggerHandler ( 'focus' );
	} );
} );
