/* [FIXME] : удалить файл после перехода на тему Courts_model */
function func_number(num) {
	var cnt = 0;
	num = num.toString();
	for (var x = num.length; x >= 0; x--) {
		if (cnt % 3 == 0 && cnt > 0 && x > 0)
			num = num.substr(0, x)+' '+num.substr(x, num.length);
		cnt++;
	}
	return num;
}

function Sum2Str(sum, is_cent) {
	if (!sum) var sum = '0';
	sum = sum.toString();
	sum = parseFloat(sum.replace(/,/, '.'));
	iSum = parseInt(sum);
	rSum = Math.round((sum - iSum) * 100);

	if (is_cent == false)
	   return '<span class="rub">'+func_number(iSum) + '</span> руб.';
	else
		return '<span class="rub">'+func_number(iSum) + '</span> руб. <span class="kop">' + rSum + '</span> коп. ';
}
$(document).ready(function() {
    calc_expand_reset();
    checked_any('param1');
    checked_any('param2');
    
    var param1Val = $('.js-param1:checked').val(),
    	param2Val = $('.js-param2:checked').val();
    _calc_expand(param1Val);
    _calc_expand(param2Val);
    calc();
    customCheckbox();

	var input = $('#sum_input');
    input.bind('click focus', function(e) {
        var value = sum_prepare(input.val(), true, true, true);
    	input.val(value);
    }).bind('keydown keyup', function(e) {
		var value = sum_prepare(input.val(), true, true, true);
    	input.val(value);
    }).bind('blur change', function(e) {
        var value = sum_prepare(input.val(), false, true);
    	input.val(value);
    });
});

// $.log()
(function(b){b.log=function(){var a=window,c=a.console;if(c&&c.log)c.log.apply(c,arguments);else a.opera&&a.opera.postError&&a.opera.postError(arguments)};b.fn.log=function(a){b.log.apply(b,a?["%s: %o",a,this]:[this]);return this}})(jQuery);

function sum_prepare(value, not_zero, makeDot, notTrimDot)
{
	var val = value.replace(/[^0-9,\.]/g, '').replace(/,/g, '.');

	val = parseFloat(val);
	if (isNaN(val)) {
		val=0;
	}

	var tail = Math.pow(10, 2);
	val = Math.round(val * tail) / tail;

	if (not_zero && !val) {
		return '';
	}

	if (makeDot) {
		val = (val+'').replace(/\./g, ',');
	}

	if (notTrimDot) {
		if (/[,.]/.test(value) && !/[,.]/.test(val)) {
			val += ',';
		}
	}

	return val;
}

function func_check_val(val, is_strict) {
    if (is_strict == true)
        new_val = val.replace(/[^0-9]/g, '');
    else
        new_val = val.replace(/[^0-9,\.]/g, '');
    if (new_val == val) {
    	return true;
    }    	
}

function calc() {
    $('#calc-link').css('display', 'none');

    var main_switcher = $('[name=param2]:checked').val();
    var secondary_main_switcher = $('[name=param1]:checked').val();

    if (secondary_main_switcher == 1) {
        $('#calc-link').html('Заполнить квитанцию для оплаты');
        $('#calc-link').attr('href', '/process/duty/invoice');
    }
    else  {
        $('#calc-link').html('Заполнить платежное поручение');
        $('#calc-link').attr('href', '/process/duty/commission');
    }

    var result = 0;
    var is_note = false;
    if (main_switcher == 10) {
        sum = document.calc_frm.sum.value;
        //if (!func_check_val(sum)) is_note = 'Неверный формат ввода';
        sum = sum_prepare(document.calc_frm.sum.value);
        if (!sum && !is_note) is_note = 'Введите сумму иска.';
        
        if (sum <= 100000)
            result = Math.max(2000, sum * 0.04);
        else if (sum > 100000 && sum <= 200000)
            result = 4000  + (sum - 100000) * 0.03;
        else if (sum > 200000 && sum <= 1000000)
            result = 7000 + (sum - 200000) * 0.02;
        else if (sum > 1000000 && sum <= 2000000)
            result = 23000 + (sum - 1000000) * 0.01;
        else if (sum > 2000000)
            result = Math.min(200000, 33000 + (sum - 2000000) * 0.005);
    } else if (main_switcher == 20 || main_switcher == 30) {
		checked_any('param3');
		
		var param3 = $('.js-param3:checked'),
			idParam = param3.attr('id'),
			result = param3.val();
		
		if (secondary_main_switcher == 1 && idParam == 'p3-4') {
			result /= 10;
		}
			
		if (main_switcher == 30) {
			result *= 0.5;
		}
	}
    
    if (is_note) {
        $('#calc_title').css('display', 'none');
        $('#calc_sum').html(is_note);
    }
    else {
        $('#calc_title').css('display', '');
        $('#calc-link').css('display', '');
        var url = $('#calc-link').attr('href')+'?gp='+result;
        if (main_switcher == 10) url += '&sum='+sum;
        $('#calc-link').attr('href', url);
        $('#calc_sum').html(Sum2Str(result, true));
    }
}

function checked_any(name)  {
    value = $('[name='+name+']:checked').val();
    if (!value)
        $('[name='+name+']')[0].checked = true;
}

function calc_expand_reset() {
    $('#calc_body_10').css('display', 'none');
    $('#calc_body_20').css('display', 'none');
}

function _calc_expand(index) {
    calc_expand_reset();
    if (index == 10)
        $('#calc_body_10').css('display', '');
    if (index == 20 || index == 30)
        $('#calc_body_20').css('display', '');
}

function calc_expand(index) {
    _calc_expand(index);
    calc();
}

function customCheckbox() {
    $('input[type="radio"]').click(function() {
        var el = $(this),
	    name = el.attr('name');

        $('input[name="' + name + '"]').closest('.b-checkbox').removeClass('b-selected');
        el.closest('.b-checkbox').addClass('b-selected');
    });
    $('input[type="radio"]:checked').closest('.b-checkbox').addClass('b-selected');
}