$(document).ready(function(){
    if ($.browser.msie) {
        $(document.body).ajaxSend(function(evt, request, settings) {
            if (!settings.ifModified && settings.type.toLowerCase() == 'get')
                request.setRequestHeader('If-Modified-Since', 'Thu, 01 Jan 1970 00:00:00 GMT');
        });
    }
    $.ajaxSetup({scriptCharset:'utf-8'});

    $("#term").change(function(){
        if (!$("#term").val()) {
            $("#price1").attr({"selectedIndex":0,"disabled":"disabled"});
            $("#price2").attr({"selectedIndex":0,"disabled":"disabled"});
        } else {
            $("#price1").attr({"disabled":""});
            $("#price2").attr({"disabled":""});
        }
    });

    $('input:radio[name^="_class_"]').click(function(){
        $('._class_').attr({'selectedIndex':0, 'disabled':'disabled'});
        $('select[name="class_' + $(this).val() + '"]').attr('disabled', '');
    });

    $('input:checkbox[name^="installation_"]').click(function(){
        var disabled = $(this).attr('checked') ? '' : 'disabled';
        $('select[name="installation_val_' + $(this).val() + '"]').attr({'selectedIndex':0, 'disabled':disabled});
    });

    $('#estimate').click(function(){
        return estimate();
    });

    $('#reset_estimate').click(function(){
        return resetEstimate();
    })

    $('#estimate_mycar').click(function(){
        return estimateMycar();
    });

    $('#reset_mycar').click(function(){
        return resetMycar();
    })

    $('#estimate_corpcar').click(function(){
        return estimateCorpcar();
    });

    $('#reset_corpcar').click(function(){
        return resetCorpcar();
    })

    $('input:radio[name="grade"]').change(function(){
        constraintCorpcar($(this).val());
    })
});

function error(mes) {
    alert(mes);
    return false;
}

function ajaxRequest(url, param, callback) {
    try {
        $.ajax({
            type: 'POST',
            url: url,
            data: param,
            success: callback,
            dataType: 'json'
        });
    } catch(e) {
        callback(false);
    }
}

function numberFormat(str) {
    var num = new String(str).replace(/,/g, '');
    while (num != (num = num.replace(/^(-?\d+)(\d{3})/, '$1,$2')));
    return num;
}

function resetEstimate() {
    $('input:radio, input:checkbox').attr('checked', '');
    $('select').attr('selectedIndex', 0);
    $('._class_').attr('disabled', 'disabled');
    $('select[name^="installation_val_"]').attr('disabled', 'disabled');
    $('#estimate_price').html('&nbsp;');
    return false;
}

function estimate() {
    try {
        var post_data = {};
        $('#estimate_price').html('&nbsp;');

        $('select[name^="class_"] option:selected').each(function(){
            post_data['class_id'] = (post_data['class_id'] || $(this).val());
        });
        if (!post_data['class_id']) return error('車種を選択してください');

        post_data['indemnification'] = $('input:radio[name="indemnification"]:checked').val();
        if (!post_data['indemnification']) return error('免責補償の加入について選択してください');

        post_data['term'] = $('select[name="term"]').val();
        if (!post_data['term']) return error('ご利用予定期間を選択してください');

        var mes = '';
        $('input:checkbox[name^="installation_"]:checked').each(function(){
            var num = $(this).attr('name').replace(/installation_/, '');
            var target = $('select[name="installation_val_' + num + '"]');
            if (target.length && !target.val()) {
                mes = $('input:checkbox[name="installation_' + num + '"]').attr('title');
                mes = '「' + mes + '」の個数を選択してください';
                return false;
            }
            post_data['installation_' + num] = target.val() ? target.val() : 1;
        })
        if (mes) return error(mes);

        ajaxRequest('rent_estimate.php', post_data, estimateAjax);
    } catch(e) {
        $('#estimate_price').text('#error#');
    }
    return false;
}

function estimateAjax(jsData) {
    try {
        if (jsData.price) {
            var price_html = '<span class="text20_bold">' + numberFormat(jsData.price) + '</span>円（税込）';
            $('#estimate_price').html(price_html);
            return;
        }
    } catch(e) {
    }
    $('#estimate_price').text('#error#');
}

function resetMycar() {
    try {
        $('input:radio, input:checkbox').attr('checked', '');
        $('select').attr('selectedIndex', 0);
        $('#price_deposit').html('&nbsp;');
        $('#price').html('&nbsp;');
        $('#price_bonus').html('&nbsp;');
        $('#price_residual').html('&nbsp;');
        $('#estimate_price').html('&nbsp;');
    } catch(e) {
    }
    return false;
}

function estimateMycar() {
    try {
        var deposit = $('input:radio[name="deposit"]:checked').val();
        if (!deposit) return error('頭金を選択してください');
        var bonus = $('input:radio[name="bonus"]:checked').val();
        if (!bonus) return error('ボーナス月加算額を選択してください');

        var data = [
            [[0,0,19800],[0,30000,16800],[0,60000,13800]],
            [[300000,0,14200],[300000,30000,11200],[300000,60000,8200]]
        ];
        var result = data[deposit - 1][bonus - 1];
        $('#price_deposit').text(numberFormat(result[0]) + '円');
        $('#price').text(numberFormat(result[2]) + '円');
        $('#price_bonus').text(numberFormat(result[1]) + '円');
        $('#price_residual').text(numberFormat('250,000円'));
        var price_html = '月々<span class="text20_bold">' + numberFormat(result[2]) + '</span>円（税込）で乗れる！';
        $('#estimate_price').html(price_html);
    } catch(e) {
        $('#estimate_price').text('#error#');
    }
    return false;
}

function resetCorpcar(not_all) {
    try {
        if (!not_all) {
            $('input:radio').attr('checked', '');
        } else {
            $('input:radio[name="option_navi"]').attr('checked', '');
        }
        $('input:radio[name="option_navi"]').attr('disabled', 'disabled');
        $('input:checkbox').attr('checked', '').attr('disabled', 'disabled');
        $('#price_grade').html('&nbsp;');
        $('#price_option').html('&nbsp;');
        $('#estimate_price').html('&nbsp;');
    } catch(e) {
    }
    return false;
}

function constraintCorpcar(grade) {
    resetCorpcar(true);

    var data_constraint = [
        [10, 13],
        [0, 3, 11, 14, 16, 17, 18],
        [0, 3, 11, 14, 17, 18],
        [1, 2, 4, 5, 11, 12, 13, 15, 16, 18],
        [1, 2, 4, 5, 11, 12, 13, 15, 18],
        [6, 7, 8, 9, 13, 15, 18],
    ];
    try {
        for (var i = 0; i < data_constraint[grade].length; i++) {
            $('#option_' + data_constraint[grade][i]).attr('disabled', '');
        }
    } catch(e) {
    }
}

function estimateCorpcar() {
    try {
        var grade = $('input:radio[name="grade"]:checked').val();
        if (!grade) return error('グレードを選択してください');
        var term = $('input:radio[name="term"]:checked').val();
        if (!term) return error('リース期間を選択してください');

        var data_grade = [
            [2170000, 48600, 42900, 38700],
            [2320000, 51800, 45800, 41300],
            [2520000, 57200, 50000, 45500],
            [2520000, 57200, 50000, 45500],
            [2720000, 62400, 54800, 49800],
            [3340000, 74100, 66600, 59800]
        ];
        var data_option = [
            [ 317000,  8800, 6600, 5300],
            [ 357000,  9900, 7400, 6000],
            [ 403000, 11200, 8400, 6700],
            [ 369000, 10300, 7700, 6200],
            [ 409000, 11400, 8500, 6800],
            [ 455000, 12700, 9500, 7600],
            [  46000,  1300, 1000,  800],
            [  52000,  1500, 1100,  900],
            [  98000,  2800, 2100, 1700],
            [-377000,-10500,-7900,-6300],
            [ -19000,  -500, -400, -300],
            [ -20000,  -550, -400, -300],
            [ 140000,  3900, 2900, 2300],
            [  22000,   600,  500,  400],
            [  32000,   900,  700,  500],
            [ 200000,  5600, 4200, 3300],
            [  15000,   400,  300,  200],
            [  10000,   300,  200,  200],
            [  30000,   800,  600,  500]
        ];
        var price = data_grade[grade][term];
        var price_option = 0;
        $('input[name^="option_"]').each(function(){
            if ($(this).attr('checked')) {
                var num = $(this).attr('id').replace(/option_/, '');
                price += data_option[num][term];
                price_option += data_option[num][0];
            }
        });

        $('#price_grade').text(numberFormat(data_grade[grade][0]) + '円');
        $('#price_option').text(numberFormat(price_option) + '円');
        var price_html = '月々<span class="text20_bold">' + numberFormat(price) + '</span>円（税込）で乗れる！';
        $('#estimate_price').html(price_html);
    } catch(e) {
        $('#estimate_price').text('#error#');
    }
    return false;
}

