function PainmentOrder(params){
	var params = params || {};
	this.params = params;
	this.fields = ['nameRes','namePayer','nameBank','bik','summ','inn','kpp','bankAccount','duty','payerAccount', 'paymentType', 'caseNumber', 'caseDate', 'judge', 'detailPayment'];
	this.bind();
}
PainmentOrder.prototype.bind = function(){
	$('#printDuty').click(function(){
		window.print();
		return false;
	});
	for(var i = 0, length = this.fields.length; i < length; i++){
		var $field = $('#form_'+this.fields[i]);
		if ($field.length) {
			new LinkFields({
				name: this.fields[i],
				input: '#form_' + this.fields[i],
				view: '#duty_' + this.fields[i]
			});
		}
	}
}

function LinkFields(params){
	this.name = params.name;
	this.$input = $(params.input);
	this.$view = $(params.view);
	this.duty = {};
	this.bind();
}
LinkFields.prototype.bind = function(){
	var self = this;
	$('#duty_nameRes').html('...');
	$('#duty_caseDate').html('...');
	$('#duty_caseudge').html('...');

	function initString() {
		var val = self.$input.val();
		
		if (self.name == 'paymentType') {
			if (val) {
				var paymentType = val;
				
				self.$view.text(paymentType.charAt(0).toUpperCase() + paymentType.slice(1));
			} else {
				self.$view.text('...');
			}
			
		} else if ((self.name == 'caseNumber') || self.name == 'nameRes') {
			self.$view.text(!val ? '...' : val);
			
		} else if (self.name == 'summ') {
			val = val ? reFormatDuty(val) : '...';
			self.$view.text(val);
			
		} else if(self.name == 'duty') {
			val = reFormatDuty(val);
			self.$view.text(val);
			self.calcLiteralSumm();
			
		} else {
			self.$view.text(val);
		}
	}
	
	function reFormatDuty(val) {
		var matches = val.match(/^(\d*)[A-Za-zА-Яа-я\s\.\,\-\/]*(\d*)[A-Za-zА-Яа-я\s\.\,\-]*/),
			rub = matches[1] ? matches[1] : '0',
			kop = matches[2] ? matches[2] : '00',
			result = reFormatRub(rub) + ' руб. ' + kop + ' коп. ';
			
		self.duty.rub = rub;
		self.duty.kop = kop;
		
		return result;
	}
	
	function reFormatRub(val) {
		var l = val.length;
		
		return (l > 3) ? reFormatRub(val.substring(0, l - 3)) + ' ' + val.substring(l - 3) : val;
	}

	initString();

	$(this.$input).keyup(function(){
		initString();
		value = $('input[id="form_duty"]').val(),
		matches = value.match(/^(\d*)[A-Za-zА-Яа-я\s\.\,\-\/]*(\d*)[A-Za-zА-Яа-я\s\.\,\-]*/);

		$('input[id="form_duty"]').keyup(function() {
			if (!matches[2]) {
				$('.duty_kop').text(' 00 коп.');
			} else {
				$('.duty_kop').text(matches[2] + ' коп.');
			}
		});
		$('input[id="form_duty"]').focusout(function() {
			var value = $(this).val();
			if (!value) {
				$('.duty_kop').text('');
			}
		});
	});

}
LinkFields.prototype.calcLiteralSumm = function(){
	var rub = parseInt(this.duty.rub),
		kop = parseInt(this.duty.kop);
	$('#duty_literalSumm').text(rub.toLiteral() + kop.toLiteral(['копейка', 'копейки', 'копеек', 'female']));
}

Number.prototype.toLiteral = function(mainUnit){
	if(isNaN(this.valueOf())){
		return '';
	}
	var mainUnit = mainUnit || ['рубль', 'рубля', 'рублей'];
	var units = [];
	units[0] = mainUnit;
	units[1] = ['тысяча', 'тысячи', 'тысяч', 'female'];
	units[2] = ['миллион', 'миллиона', 'миллионов'];
	units[3] = ['миллиард', 'миллиарда', 'миллиардов'];
	units[4] = ['триллион', 'триллиона', 'триллионов'];
	var result = '';
	for(var i = 0, summ = this.valueOf(); summ >= 1; summ = summ / 1000, i++){
		var excess = summ % 1000;// остаток от деления
		summ = summ - excess;
		if(units[i]){
			result = Number.prototype.toLiteral.numBefore1000(excess, units[i]) + ' ' + result;
		}
		else{
			result = 'Слишком большое число';
			break;
		}
	}
	return result;
}
Number.prototype.toLiteral.numBefore1000 = function(numBefore1000, units){
	units[3] = units[3] || 'male';
	var numbers = [];
	switch(units[3]){
		case 'male':
			numbers[1] = 'один';
			numbers[2] = 'два';
		break;
		case 'female':
			numbers[1] = 'одна';
			numbers[2] = 'две';
		break;
		case 'gender':
			numbers[1] = 'одно';
			numbers[2] = 'два';
		break;
	}
	numbers[3] = 'три';
	numbers[4] = 'четыре';
	numbers[5] = 'пять';
	numbers[6] = 'шесть';
	numbers[7] = 'семь';
	numbers[8] = 'восемь';
	numbers[9] = 'девять';
	numbers[10] = 'десять';
	numbers[11] = 'одиннадцать';
	numbers[12] = 'двенадцать';
	numbers[13] = 'тринадцать';
	numbers[14] = 'четырнадцать';
	numbers[15] = 'пятнадцать';
	numbers[16] = 'шестнадцать';
	numbers[17] = 'семнадцать';
	numbers[18] = 'восемнадцать';
	numbers[19] = 'девятнадцать';
	numbers[20] = 'двадцать';
	numbers[30] = 'тридцать';
	numbers[40] = 'сорок';
	numbers[50] = 'пятьдесят';
	numbers[60] = 'шестьдесят';
	numbers[70] = 'семьдесят';
	numbers[80] = 'восемьдесят';
	numbers[90] = 'девяносто';
	numbers[100] = 'сто';
	numbers[200] = 'двести';
	numbers[300] = 'триста';
	numbers[400] = 'четыреста';
	numbers[500] = 'пятьсот';
	numbers[600] = 'шестьсот';
	numbers[700] = 'семьсот';
	numbers[800] = 'восемьсот';
	numbers[900] = 'девятьсот';

	var result = '';
	for(var i = 0, summ = numBefore1000;(i == 0) || (summ >= 1); summ = summ / 10, i++){
		var excess = summ % 10;// остаток от деления
		summ = summ - excess;
		var excessNext = ( summ / 10 ) % 10;
		if( (i == 0) && (excessNext != 1)){
			if(excess == 0){
				result = units[2];
			}
			else if(excess == 1){
				result = numbers[excess] + ' ' + units[0];
			}
			else if( excess < 5 ){
				result = numbers[excess] + ' ' + units[1];
			}
			else{
				result = numbers[excess] + ' ' + units[2];
			}
		}
		else if( (i == 0) && (excessNext == 1) ){//10-19
			result = numbers[10 + excess] + ' ' + units[2];
		}
		else if( (i == 1) && ((excess == 1) || (excess == 0)) ){
			//11-19 уже вывели
			//а 0-ой десяток не выводится
		}
		else{
			var index = excess * Math.pow( 10, i );
			result = numbers[index] + ' ' + result;
		}
	}
	return result;
}

function save_pdf(id, mode, doc) {
	var fields = ['nameRes','namePayer','nameBank','bik','summ','inn','kpp','bankAccount','duty','payerAccount','paymentType','caseNumber','date','judgeName', 'caseDate', 'judge', 'detailPayment'],
		requisites = ['name', 'title', 'code', 'inn', 'kpp', 'bic', 'account', 'okato', 'field_1', 'field_8'],
		extra = ['literalSumm', 'duty', 'summ', 'date'],
		path = window.location.pathname.split('/').slice(1, 4),
		href = '/' + path.join('/') + '/pdf?mode='+mode+'&id='+id+'&doc='+doc, 
		i, $field;
	
	if (path[2] == 'deposit') {
		requisites = requisites.concat(['personal_account', 'current_account', 'bank', 'recipient', 'ablative']);
	}
	
	for (i in fields) {
		$field = $('#form_'+fields[i]);
		if ($field.length) {
			href += '&'+fields[i]+'='+$field.val();
		}
	}
	
	for (i in requisites) {
		$field = $('#form_court_'+requisites[i]);
		if ($field.length) {
			href += '&court_'+requisites[i]+'='+$field.val();
		}
	}
	
	for (i in extra) {
		$field = $('#duty_'+extra[i]);
		if ($field.length) {
			href += '&duty_'+extra[i]+'='+$field.text();
		}
	}

	window.open(href);
}
$(function() {
	var title = $('.js-title'),
		fieldSelect = $('select.js-detail-payment'),
		isASGM = false;
	
	if (title.hasClass('b-blank-title--asgm')) {
		isASGM = true;
	}
	$('.js-type-payment').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-payment_amount');
		
		addField.text(value);
	});
	$('.js-case-number').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-number_count');
		
		addField.text(value);
	});
	$('.js-type-payment').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-duty_payment_details');
		
		addField.text(value);
	});
	$('.js-case-number').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-duty-case_number');
		
		addField.text(value);
	});
	$('.js-judge_name').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-duty-judge_name');
		
		addField.text(value);
	});
	$('.js-date').keyup(function() {
		var value = $(this).val(),
			addField = $('.js-duty-date');
		
		addField.text(value);
	});
	
	if (fieldSelect.length) {
		fieldSelect.change(function(){
			var self = $(this),
				select = self.val(),
				value = self.find('option[value="' + select + '"]').text(),
				addField = $('#duty_detailPayment');
			
			addField.text(value);
		});
		fieldSelect.sSelect();
	}
});

