$(function(){
    var API_KEY = "AIzaSyD_6488ihyz6QKZuaPObrWUe0teMUVfIp8";
    $('#zipToAddress').on('click', function(){
        var address_name1;
        var address_name2;
        var address_name3;
        var zip = $('[name=zip]').val();
        if(zip != "") {
            $.ajax({
                url: 'https://maps.googleapis.com/maps/api/geocode/json',
                type: 'GET',
                dataType: 'json',
                data: {
                    key: API_KEY,
                    address: zip,
                    language: 'ja'
                }
            }).done(function(data) {
                if (data.status == "OK") {
                    if(data["results"][0]["address_components"].length == 5) {
                        address_name1 = data["results"][0]["address_components"][3]["long_name"];
                        address_name2 = data["results"][0]["address_components"][2]["long_name"];
                        address_name3 = data["results"][0]["address_components"][1]["long_name"];
                    } else {
                        address_name1 = data["results"][0]["address_components"][4]["long_name"];
                        address_name2 = data["results"][0]["address_components"][3]["long_name"]+data["results"][0]["address_components"][2]["long_name"];
                        address_name3 = data["results"][0]["address_components"][1]["long_name"];
                    }

                    $('[name=lat_text]').text(data["results"][0]["geometry"]["location"]["lat"]);
                    $('[name=lng_text]').text(data["results"][0]["geometry"]["location"]["lng"]);
                    $('[name=lat]').val(data["results"][0]["geometry"]["location"]["lat"]);
                    $('[name=lng]').val(data["results"][0]["geometry"]["location"]["lng"]);
                    

                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        type: 'POST',
                        datatype: 'json',
                        url: '/admin/city_name',
                        data: {
                            prefName: address_name1,
                            cityName: address_name2
                        }
                    })
                    .done(function(data){ //ajaxの通信に成功した場合
                        // alert("success!");
                        var obj = $('[name^=address2]');
                        $(obj).val(data[2]);
                        $(obj).next('[name^=address3]').children('option').remove();
                        $(obj).next('[name^=address3]').append($('<option>').text('町村を選択').attr('value', ''));
            
                        $('[name=primary_school_city] option').remove();
                        $('[name=primary_school_city]').append($('<option>').text('町村を選択').attr('value', ''));
                        $('[name=primary_school2_city] option').remove();
                        $('[name=primary_school2_city]').append($('<option>').text('町村を選択').attr('value', ''));
                        $('[name=primary_school3_city] option').remove();
                        $('[name=primary_school3_city]').append($('<option>').text('町村を選択').attr('value', ''));
            
                        $('[name=secondary_school_city] option').remove();
                        $('[name=secondary_school_city]').append($('<option>').text('町村を選択').attr('value', ''));
                        $('[name=secondary_school2_city] option').remove();
                        $('[name=secondary_school2_city]').append($('<option>').text('町村を選択').attr('value', ''));
                        $('[name=secondary_school3_city] option').remove();
                        $('[name=secondary_school3_city]').append($('<option>').text('町村を選択').attr('value', ''));
                        $.each(data[0], function(row, value){
                            if(value['name'] == address_name3) {
                                $(obj).next('[name^=address3]').append($('<option selected>').text(value['name']).attr('value', value['code']));
                            } else {
                                $(obj).next('[name^=address3]').append($('<option>').text(value['name']).attr('value', value['code']));
                            }
                            
                        });
            
                        $.each(data[1], function(row, value){
                            $('[name=primary_school_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                            $('[name=primary_school2_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                            $('[name=primary_school3_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                            $('[name=secondary_school_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                            $('[name=secondary_school2_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                            $('[name=secondary_school3_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                        });
                    })
                    .fail(function(data){ //ajaxの通信に失敗した場合
                        alert("error!");
                    });
                }
            });
        }
    });

    $('.p-vendor-list__displink').on('click', function(){
        $('.article_list').toggle();
        $("html, body").animate( {scrollTop: $(this).offset().top}, 100 );
        
    });

    $('#addressToZip').on('click', function(){
        var address = "";
        if($('[name=address1] option:selected').val() != "") {
            address += $('[name=address1] option:selected').text();
        }
        if($('[name=address2] option:selected').val() != "") {
            address += $('[name=address2] option:selected').text();
        }
        if($('[name=address3] option:selected').val() != "") {
            address += $('[name=address3] option:selected').text();
        }
        if($('[name=address4] option:selected').val() != "") {
            address += $('[name=address4] option:selected').text();
        }
        
        if(address != "") {
            $.ajax({
                url: 'https://maps.googleapis.com/maps/api/geocode/json',
                type: 'GET',
                dataType: 'json',
                data: {
                    key: API_KEY,
                    address: address,
                    language: 'ja'
                }
            }).done(function(data) {
                if (data.status == "OK") {
                    if(data["results"][0]["address_components"][6] != undefined && data["results"][0]["address_components"][6]["types"][0] == "postal_code") {
                        $('[name=zip]').val(data["results"][0]["address_components"][6]["long_name"]);
                        $('[name=lat]').val(data["results"][0]["geometry"]["location"]["lat"]);
                        $('[name=lng]').val(data["results"][0]["geometry"]["location"]["lng"]);
                    } else if(data["results"][0]["address_components"][5] != undefined && data["results"][0]["address_components"][5]["types"][0] == "postal_code") {
                        $('[name=zip]').val(data["results"][0]["address_components"][5]["long_name"]);
                        $('[name=lat]').val(data["results"][0]["geometry"]["location"]["lat"]);
                        $('[name=lng]').val(data["results"][0]["geometry"]["location"]["lng"]);
                    }
                }
            });
        }
    });

    // 町会費
    $('[name=council]').on('change', function(){
        var selected = $(this).val();
        if(selected == 0) {
            $('#council_presence_area').hide(500);
            $('#council_cost_area').hide(500);
        } else {
            $('#council_presence_area').show(500);
        }
    });

    $('[name=council_presence]').on('change', function(){
        var selected = $(this).val();
        if(selected == 1) {
            $('#council_cost_area').show(500);
        } else {
            $('#council_cost_area').hide(500);
        }
    });

    $('[name=broadcasting], [name=internet], [name=catv]').on('change', function(){
        var selected = $(this).val();
        var parent = $(this).parent();
        if(selected == 0 || selected == 2) {
            $(parent).find('.initial_cost').hide(500);
            $(parent).find('.running_cost').hide(500);
        } else {
            $(parent).find('.initial_cost').show(500);
            $(parent).find('.running_cost').show(500);
        }
    });

    $('[name=broadcasting_presence], [name=internet_presence], [name=catv_presence]').on('change', function(){
        var selected = $(this).val();
        var parent = $(this).parent();
        if(selected == 1) {
            $(parent).find('.initial_cost_detail').show(500);
            $(parent).find('.initial_cost_detail').show(500);
        } else {
            $(parent).find('.initial_cost_detail').hide(500);
            $(parent).find('.initial_cost_detail').hide(500);
        }
    });

    $('[name=broadcasting_fixed_presence], [name=internet_fixed_presence], [name=catv_fixed_presence]').on('change', function(){
        var selected = $(this).val();
        var parent = $(this).parent();
        if(selected == 1) {
            $(parent).find('.running_cost_detail').show(500);
            $(parent).find('.running_cost_detail').show(500);
        } else {
            $(parent).find('.running_cost_detail').hide(500);
            $(parent).find('.running_cost_detail').hide(500);
        }
    });

    // 温泉
    $('[name=spring]').on('change', function(){
        var selected = $(this).val();
        if(selected == 0) {
            $('#spring_area').hide(500);
            $('#spring_cost_area').hide(500);
            $('#spring_kind_area').hide(500);
        } else {
            $('#spring_area').show(500);
            $('#spring_kind_area').show(500);
        }
    });

    $('[name=spring_presence]').on('change', function(){
        var selected = $(this).val();
        if(selected == 1) {
            $('#spring_cost_area').show(500);
        } else {
            $('#spring_cost_area').hide(500);
        }
    });

    // 土地条件
    $('[name^=land_condition]').on('change', function(){
        if($(this).prop("checked")) {
            $(this).parent().parent().children('div').show(500);
        } else {
            $(this).parent().parent().children('div').hide(500);
        }
    });

    // 現状
    $('[name=current_status]').on('change', function(){
        var selected = $(this).val();
        if(selected == 3) {
            $('#land_status_area').show(500);
        } else {
            $('#land_status_area').hide(500);
        }
    });

    // 引渡し
    $('[name=land_delivery]').on('change', function(){
        var selected = $(this).val();
        if(selected == 3) {
            $('#land_delivery_area').show(500);
        } else {
            $('#land_delivery_area').hide(500);
        }
    });

    // 建築条件
    $('[name=land_condition]').on('change', function(){
        var selected = $(this).val();
        if(selected == 1) {
            $('#land_condition_area').show(500);
        } else {
            $('#land_condition_area').hide(500);
        }
    });

    // 私道負担
    $('[name=road_burden]').on('change', function(){
        var selected = $(this).val();
        if(selected == 2) {
            $('#road_burden_area1').show(500);
            $('#road_burden_area2').show(500);
        } else if(selected == 1) {
            $('#road_burden_area1').show(500);
            $('#road_burden_area2').hide(500);
        }else {
            $('#road_burden_area1').hide(500);
            $('#road_burden_area2').hide(500);
        }
    });

    // 地役権
    $('[name=easement]').on('change', function(){
        var selected = $(this).val();
        if(selected == 2 || selected == 3 || selected == 4 || selected == 5 || selected == 6 ) {
            $('#easement_area').show(500);
        } else {
            $('#easement_area').hide(500);
        }
    });

    // セットパック
    $('[name=set]').on('change', function(){
        var selected = $(this).val();
        if(selected == 2 || selected == 3 ) {
            $('#set_area').show(500);
        } else {
            $('#set_area').hide(500);
        }
    });

    // 都市計画
    $('[name=city_plan]').on('change', function(){
        var selected = $(this).val();
        if(selected == 2) {
            $('#city_plan_area').show(500);
        } else {
            $('#city_plan_area').hide(500);
        }
    });


    if($('[name=move_in]:checked').val() == 3){
        $('#move_in_year').show(500);
        $('#move_in_month').hide(500);
    } else if($('[name=move_in]:checked').val() == 4){
        $('#move_in_year').hide(500);
        $('#move_in_month').show(500);
    } else {
        $('#move_in_year').hide(500);
        $('#move_in_month').hide(500);
    };

    $('[name=move_in]').on('change', function(){
        var selected = $(this).val();
        if(selected == 3){
            $('#move_in_year').show(500);
            $('#move_in_month').hide(500);
        } else if(selected == 4){
            $('#move_in_year').hide(500);
            $('#move_in_month').show(500);
        } else {
            $('#move_in_year').hide(500);
            $('#move_in_month').hide(500);
        };
    });


    // 外装
    $('[name=exterior]').on('change', function(){
        var selected = $(this).val();
        if(selected != 1) {
            $('#exterior_detail').show(500);
        } else {
            $('#exterior_detail').hide(500);
        }
    });

    // 内装
    $('[name=interior]').on('change', function(){
        var selected = $(this).val();
        if(selected != 1) {
            $('#interior_detail').show(500);
        } else {
            $('#interior_detail').hide(500);
        }
    });

    // 区分
    $('[name=classfication]').on('change', function(){
        var selected = $(this).val();
        if(selected == 2) {
            $('#classfication_area').show(500);
        } else {
            $('#classfication_area').hide(500);
        }
    });

    // 日程
    $('[name=event_schedule]').on('change', function(){
        var selected = $(this).val();
        if(selected == 3) {
            $('#event_schedule_area1').show(500);
            $('#event_schedule_area2').hide(500);
        } else if(selected == 4) {
            $('#event_schedule_area1').hide(500);
            $('#event_schedule_area2').show(500);
        }else {
            $('#event_schedule_area1').hide(500);
            $('#event_schedule_area2').hide(500);
        }
    });

    $('[name=event_schedule_area_clear1]').on('click', function(){
        $('[name=event_day]').val('');
    });

    $('[name=event_schedule_area_clear2]').on('click', function(){
        $('[name=from_event]').val('');
        $('[name=to_event]').val('');
    });

    $(document).on('change', '[name=address1]', function(){
	if ($(this).hasClass("sai-kyoto")) {
            return;
        }
        var prefId = $(this).val();
        var obj = $(this);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref',
            data: {
                prefId: prefId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=address2]').children('option').remove();
            $(obj).next('[name^=address2]').append($('<option>').text('市区郡を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj).next('[name^=address2]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
            $(obj).next().next('[name^=address3]').children('option').remove();
            $(obj).next().next('[name^=address3]').append($('<option>').text('町村を選択').attr('value', ''));

            getLatlng($(obj));
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('change', '[name^=address2]', function(){
	if ($(this).hasClass("sai-kyoto")) {
            return;
        }
        var cityId = $(this).val();
        var obj = $(this);
        var prefId = $('[name^=address1]').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/city',
            data: {
                prefId: prefId,
                cityId: cityId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=address3]').children('option').remove();
            $(obj).next('[name^=address3]').append($('<option>').text('町村を選択').attr('value', ''));

            $('[name=primary_school_city] option').remove();
            $('[name=primary_school_city]').append($('<option>').text('町村を選択').attr('value', ''));
            $('[name=primary_school2_city] option').remove();
            $('[name=primary_school2_city]').append($('<option>').text('町村を選択').attr('value', ''));
            $('[name=primary_school3_city] option').remove();
            $('[name=primary_school3_city]').append($('<option>').text('町村を選択').attr('value', ''));

            $('[name=secondary_school_city] option').remove();
            $('[name=secondary_school_city]').append($('<option>').text('町村を選択').attr('value', ''));
            $('[name=secondary_school2_city] option').remove();
            $('[name=secondary_school2_city]').append($('<option>').text('町村を選択').attr('value', ''));
            $('[name=secondary_school3_city] option').remove();
            $('[name=secondary_school3_city]').append($('<option>').text('町村を選択').attr('value', ''));
            $.each(data[0], function(row, value){
                $(obj).next('[name^=address3]').append($('<option>').text(value['name']).attr('value', value['code']));
            });

            $.each(data[1], function(row, value){
                $('[name=primary_school_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                $('[name=primary_school2_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                $('[name=primary_school3_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                $('[name=secondary_school_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                $('[name=secondary_school2_city]').append($('<option>').text(value['name']).attr('value', value['name']));
                $('[name=secondary_school3_city]').append($('<option>').text(value['name']).attr('value', value['name']));
            });

            getLatlng($(obj));
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $('[name^=address3]').on('change', function(){
        getLatlng($(this));
    });

    $('[name^=address4]').on('blur', function(){
        getLatlng($(this));
    });


    function getLatlng(obj) {
        var address = "";
        
        if($(obj).parents('tr').find('[name^=address1]').val() != 0) {
            address = $(obj).parents('tr').find('[name^=address1] option:selected').text();

            if($(obj).parents('tr').find('[name^=address2]').val() != 0) {
                address += $(obj).parents('tr').find('[name^=address2] option:selected').text();

                if($(obj).parents('tr').find('[name^=address3]').val() != 0) {
                    address += $(obj).parents('tr').find('[name^=address3] option:selected').text();
                }

                if($(obj).parents('tr').find('[name^=address4]').val() != "") {
                    address += $(obj).parents('tr').find('[name^=address4]').val();
                }
            }
        }

        if(address != "") {
            $.ajax({
                url: 'https://maps.googleapis.com/maps/api/geocode/json',
                type: 'GET',
                dataType: 'json',
                data: {
                    key: API_KEY,
                    address: address,
                    language: 'ja'
                }
            }).done(function(data) {
                if (data.status == "OK") {
                    if(data["results"][0]["address_components"][6] != undefined && data["results"][0]["address_components"][6]["types"][0] == "postal_code") {
                        $('[name=lat]').val(data["results"][0]["geometry"]["location"]["lat"]);
                        $('[name=lng]').val(data["results"][0]["geometry"]["location"]["lng"]);
                    } else if(data["results"][0]["address_components"][5] != undefined && data["results"][0]["address_components"][5]["types"][0] == "postal_code") {
                        $('[name=lat]').val(data["results"][0]["geometry"]["location"]["lat"]);
                        $('[name=lng]').val(data["results"][0]["geometry"]["location"]["lng"]);
                    }
                }
            });
        }
        
    }

    $( ".cal_picker" ).datepicker({ 
        dateFormat: "yy/mm/dd" 
    });

    $('[name=facility_area]').on('change', function(){
        var area = $(this).val();
        var obj = $(this);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/facility_property',
            data: {
                area: area
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $(obj).parents('dl').find('[name=facility_property]').children('option').remove();
            $(obj).parents('dl').find('[name=facility_property]').append($('<option>').text('施設種別を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj).parents('dl').find('[name=facility_property]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('change', '[name=search_lot_address1]', function(){
        var prefId = $(this).val();
        var obj = $(this);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref',
            data: {
                prefId: prefId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=search_lot_address2]').children('option').remove();
            $(obj).next('[name^=search_lot_address2]').append($('<option>').text('市区郡を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj).next('[name^=address2]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
            $(obj).next().next('[name^=search_lot_address3]').children('option').remove();
            $(obj).next().next('[name^=search_lot_address3]').append($('<option>').text('町村を選択').attr('value', ''));

            getLatlng($(obj));
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('change', '[name^=search_lot_address2]', function(){
        var cityId = $(this).val();
        var obj = $(this);
        var prefId = $('[name^=search_lot_address1]').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/city',
            data: {
                prefId: prefId,
                cityId: cityId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=search_lot_address3]').children('option').remove();
            $(obj).next('[name^=search_lot_address3]').append($('<option>').text('町村を選択').attr('value', ''));

            $.each(data[0], function(row, value){
                $(obj).next('[name^=search_lot_address3]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('change', '[name=search_address1]', function(){
        var prefId = $(this).val();
        var obj = $(this);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref',
            data: {
                prefId: prefId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=search_address2]').children('option').remove();
            $(obj).next('[name^=search_address2]').append($('<option>').text('市区郡を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj).next('[name^=search_address2]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
            $(obj).next().next('[name^=search_address3]').children('option').remove();
            $(obj).next().next('[name^=search_address3]').append($('<option>').text('町村を選択').attr('value', ''));

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('change', '[name^=search_address2]', function(){
        var cityId = $(this).val();
        var obj = $(this);
        var prefId = $('[name^=search_address1]').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/city',
            data: {
                prefId: prefId,
                cityId: cityId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $(obj).next('[name^=search_address3]').children('option').remove();
            $(obj).next('[name^=search_address3]').append($('<option>').text('町村を選択').attr('value', ''));

            $.each(data[0], function(row, value){
                $(obj).next('[name^=search_address3]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });


    $(document).on('click', '[name=photo_disp_change]', function(){
        $(this).val();
        if($(this).prop("checked")) {
            $(this).parents('.c-switch').next('input').val(1);
        } else {
            $(this).parents('.c-switch').next('input').val(0);
        }
    });

    $(document).on("click", ".btn_imagedel", function(){
        $(this).parent().parent().remove();
    });

    $(document).on('click', '[name=del_store_photo]', function(event){
        var id = $(this).parent('td').find('[name^=tmp_store_photo_id_]').val();
        var url = '/admin/del_store_tmpimage';
        if(id === undefined || id == "") {
            id = $(this).parent('td').find('[name^=store_photo_id_]').val();
            url = '/admin/del_store_image';
        }
        var target = $(this).parents('tr')[0];
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: url,
            data: {
                id: id
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $(target).remove();
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $(document).on('click', '[name=del_reform_photo]', function(event){
        var id = $(this).parent('td').find('[name^=tmp_reform_photo_id_]').val();
        var url = '/admin/del_reform_tmpimage';
        if(id === undefined || id == "") {
            id = $(this).parent('td').find('[name^=reform_photo_id_]').val();
            url = '/admin/del_reform_image';
        }
        var target = $(this).parents('tr')[0];
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: url,
            data: {
                id: id
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $(target).remove();
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $('[name=del_before_img]').on('click', function(){
        if($('#imageArea2').find('img').attr('src') != '') {
            $('#imageArea2').find('img').attr('src', '');
            $('[name=del_before_flag]').val(1);
        } else {
            var cvs = $('#imageArea2').find('canvas');
            var ctx = cvs[0].getContext('2d');
            ctx.clearRect(0, 0, 200, 200);
            cvs.width(0);
            cvs.height(0);
        }

    });
    $('[name=del_after_img]').on('click', function(){
        if($('#imageArea3').find('img').attr('src') != '') {
            $('#imageArea3').find('img').attr('src', '');
            $('[name=del_after_flag]').val(1);
        } else {
            var cvs = $('#imageArea3').find('canvas');
            var ctx = cvs[0].getContext('2d');
            ctx.clearRect(0, 0, 200, 200);
            cvs.width(0);
            cvs.height(0);
        }

    });

    $(document).on('click', '[name=del_photo]', function(){
        if($(this).parents('td').find('[name=photo_id]').length != 0) {
            var del = $('[name=del_photo_id]').val();

            if(del != "") {
                del += ",";
            }
            del += $(this).parents('td').find('[name=photo_id]').val();
            $('[name=del_photo_id]').val(del);
        } else if($(this).parents('td').find('[name^=article_photo_id]').length != 0) {
            var del = $('[name=del_photo_id]').val();
            var target = $(this).parents('td').find('[name^=article_photo_id]').val();

            if(del != "") {
                del += ",";
            }
            del += target;
            $('[name=del_photo_id]').val(del);

            var saved = $('[name=saved_photo_id]').val();
            if(saved.match(target+',')) {
                saved = saved.replace(target+',', '');
            } else if(saved.match(','+target)) {
                saved = saved.replace(','+target, '');
            } else if(saved.match(target)) {
                saved = saved.replace(target, '');
            }
            $('[name=saved_photo_id]').val(saved);
        }

        var target = $('#image_list').find('tr');
        var count = 0;
        var num = 0;
        $.each(target, function(row, obj){
            if(count < 3) {
                count++;
            } else {
                var tmp_target = $(obj).find('[name^=photo_property]');
                $.each(tmp_target, function(row, tmp_obj){
                    var tmp_name = $(tmp_obj).attr('name');
                    tmp_name = tmp_name.slice(0, -1);
                    $(tmp_obj).attr('name', tmp_name+num)
                });

                // tmp_name = $(obj).find('[name^=photo_property_sub]').attr('name');
                // tmp_name = tmp_name.slice(0, -1);
                // $(obj).find('[name^=photo_property_sub]').attr('name', tmp_name+num);

                var tmp_name = $(obj).find('[name^=photo_comment]').attr('name');
                if(count > 12) {
                    tmp_name = tmp_name.slice(0, -2);
                } else {
                    tmp_name = tmp_name.slice(0, -1);
                }
                
                $(obj).find('[name^=photo_comment]').attr('name', tmp_name+num);

                var tmp_name = $(obj).find('[name^=article_photo_id]').attr('name');
                if(tmp_name !== undefined) {
                    if(count > 12) {
                        tmp_name = tmp_name.slice(0, -2);
                    } else {
                        tmp_name = tmp_name.slice(0, -1);
                    }
                    $(obj).find('[name^=article_photo_id]').attr('name', tmp_name+num);
                }

                num++;
            }
        });

    });

    var disp_thumbnail = function(f, i) {
        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値
        
        var tr = $("#add-photo-template");
        var clone = $(tr).clone();

        $(clone).find('[name=photo_disp_change]').attr('name', 'photo_disp_change'+i);
        $(clone).find('[name=photo_property]').attr('name', 'photo_property'+i);
        $(clone).find('[name=photo_property_sub]').attr('name', 'photo_property_sub'+i);
        $(clone).find('[name=photo_comment]').attr('name', 'photo_comment'+i);
        $(clone).find('[name=photo_comment_count]').attr('name', 'photo_comment'+i+'_count');

        $(clone).find('[name=photo_disp_tmp]').attr('name', 'photo_disp'+i);
        $.each($(clone).find('[name=photo_property_tmp]'), function(row, value){
            value.id = value.id.replace('tmp', i);
            value.name = value.name.replace('tmp', i);
        });

        $.each($(clone).find('label'), function(row, value){
            if(value.htmlFor.match(/photo_property_tmp/)) {
                value.htmlFor = value.htmlFor.replace('tmp', i);
            }

            if(value.htmlFor.match(/photo_list_tmp/)) {
                value.htmlFor = value.htmlFor.replace('tmp-1', i);
            }
        });

        
        
        
        $(clone).find('[name=del_reform_photo_tmp]').attr('name', 'del_reform_photo');
        $(clone).find('[name=photo_comment_tmp]').attr('name', 'photo_comment'+i);
        $(clone).find('#photo_list_tmp-1').val(i);
        $(clone).find('#photo_list_tmp-1').attr('name', 'photo_list');
        $(clone).find('#photo_list_tmp-1').attr('id', 'photo_list_'+i);
        $(clone).find('[name=photo_list_tmp-1]').attr('name', 'photo_list');
        
        $(clone).find('[name=del_photo_tmp]').attr('name', 'del_photo');

        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")
                
            // 画像をリサイズする
            var image = new Image();
            var reader = new FileReader();
            reader.onload = function(e) {
                image.onload = function() {
                    var width, height;
                    if(image.width > image.height){
                        // 横長の画像は横のサイズを指定値にあわせる
                        var ratio = image.height/image.width;
                        width = THUMBNAIL_WIDTH;
                        height = THUMBNAIL_WIDTH * ratio;
                    } else {
                        // 縦長の画像は縦のサイズを指定値にあわせる
                        var ratio = image.width/image.height;
                        width = THUMBNAIL_HEIGHT;
                        height = THUMBNAIL_HEIGHT;
                    }
                    // サムネ描画用canvasのサイズを上で算出した値に変更
                    var canvas = $(clone).find('canvas').attr('width', width).attr('height', height);
                    var ctx = $(canvas)[0].getContext('2d');
                    // canvasに既に描画されている画像をクリア
                    ctx.clearRect(0,0,width,height);
                    // canvasにサムネイルを描画
                    ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                    // canvasからbase64画像データを取得
                    var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                    // base64からBlobデータを作成
                    var barr, bin, n, len;
                    bin = atob(base64.split('base64,')[1]);
                    len = bin.length;
                    barr = new Uint8Array(len);
                    n = 0;
                    while (n < len) {
                        barr[n] = bin.charCodeAt(n);
                        n++;
                    }
                    blob = new Blob([barr], {type: 'image/jpeg'});
                    console.log(blob);
                }
                image.src = e.target.result;
            }
            reader.readAsDataURL(f);

            $("#image_list").append(clone);
    }

    var disp_thumbnail_new = function(f, i, id) {
        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値
        
        var tr = $("#add-photo-template");
        var clone = $(tr).clone();

        $(clone).find('[name=article_photo_id]').val(id);
        $(clone).find('[name=article_photo_id]').attr('name', 'article_photo_id'+i);
        $(clone).find('[name=photo_disp_change]').attr('name', 'photo_disp_change'+i);
        $(clone).find('[name=photo_property]').attr('name', 'photo_property'+i);
        $(clone).find('[name=photo_property_sub]').attr('name', 'photo_property_sub'+i);
        $(clone).find('[name=photo_comment]').attr('name', 'photo_comment'+i);
        $(clone).find('[name=photo_comment_count]').attr('name', 'photo_comment'+i+'_count');

        $(clone).find('[name=photo_disp_tmp]').attr('name', 'photo_disp'+i);
        $.each($(clone).find('[name=photo_property_tmp]'), function(row, value){
            value.id = value.id.replace('tmp', i);
            value.name = value.name.replace('tmp', i);
        });

        $.each($(clone).find('label'), function(row, value){
            if(value.htmlFor.match(/photo_property_tmp/)) {
                value.htmlFor = value.htmlFor.replace('tmp', i);
            }

            if(value.htmlFor.match(/photo_list_tmp/)) {
                value.htmlFor = value.htmlFor.replace('tmp-1', i);
            }
        });

        
        
        
        $(clone).find('[name=del_reform_photo_tmp]').attr('name', 'del_reform_photo');
        $(clone).find('[name=photo_comment_tmp]').attr('name', 'photo_comment'+i);
        $(clone).find('#photo_list_tmp-1').val(i);
        $(clone).find('#photo_list_tmp-1').attr('name', 'photo_list');
        $(clone).find('#photo_list_tmp-1').attr('id', 'photo_list_'+i);
        $(clone).find('[name=photo_list_tmp-1]').attr('name', 'photo_list');
        
        $(clone).find('[name=del_photo_tmp]').attr('name', 'del_photo');

        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")
                
            // 画像をリサイズする
            var image = new Image();
            var reader = new FileReader();
            reader.onload = function(e) {
                image.onload = function() {
                    var width, height;
                    if(image.width > image.height){
                        // 横長の画像は横のサイズを指定値にあわせる
                        var ratio = image.height/image.width;
                        width = THUMBNAIL_WIDTH;
                        height = THUMBNAIL_WIDTH * ratio;
                    } else {
                        // 縦長の画像は縦のサイズを指定値にあわせる
                        var ratio = image.width/image.height;
                        width = THUMBNAIL_HEIGHT;
                        height = THUMBNAIL_HEIGHT;
                    }
                    // サムネ描画用canvasのサイズを上で算出した値に変更
                    var canvas = $(clone).find('canvas').attr('width', width).attr('height', height);
                    var ctx = $(canvas)[0].getContext('2d');
                    // canvasに既に描画されている画像をクリア
                    ctx.clearRect(0,0,width,height);
                    // canvasにサムネイルを描画
                    ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                    // canvasからbase64画像データを取得
                    var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                    // base64からBlobデータを作成
                    var barr, bin, n, len;
                    bin = atob(base64.split('base64,')[1]);
                    len = bin.length;
                    barr = new Uint8Array(len);
                    n = 0;
                    while (n < len) {
                        barr[n] = bin.charCodeAt(n);
                        n++;
                    }
                    blob = new Blob([barr], {type: 'image/jpeg'});
                    console.log(blob);
                }
                image.src = e.target.result;
            }
            reader.readAsDataURL(f);

            $("#image_list").append(clone);
    }
    

    var disp_thumbnail_single = function(f, target_obj) {
        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値
                
            // 画像をリサイズする
            var image = new Image();
            var reader = new FileReader();
            reader.onload = function(e) {
                image.onload = function() {
                    var width, height;
                    if(image.width > image.height){
                        // 横長の画像は横のサイズを指定値にあわせる
                        var ratio = image.height/image.width;
                        width = THUMBNAIL_WIDTH;
                        height = THUMBNAIL_WIDTH * ratio;
                    } else {
                        // 縦長の画像は縦のサイズを指定値にあわせる
                        var ratio = image.width/image.height;
                        width = THUMBNAIL_HEIGHT;
                        height = THUMBNAIL_HEIGHT;
                    }
                    // サムネ描画用canvasのサイズを上で算出した値に変更
                    $(target_obj).removeAttr('style');
                    var canvas = $(target_obj).attr('width', width).attr('height', height);
                    var ctx = $(canvas)[0].getContext('2d');
                    
                    // canvasに既に描画されている画像をクリア
                    ctx.clearRect(0,0,width,height);
                    // canvasにサムネイルを描画
                    ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                    // canvasからbase64画像データを取得
                    var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                    // base64からBlobデータを作成
                    var barr, bin, n, len;
                    bin = atob(base64.split('base64,')[1]);
                    len = bin.length;
                    barr = new Uint8Array(len);
                    n = 0;
                    while (n < len) {
                        barr[n] = bin.charCodeAt(n);
                        n++;
                    }
                    blob = new Blob([barr], {type: 'image/jpeg'});
                    console.log(blob);
                    $(canvas).next('p').hide();
                }
                image.src = e.target.result;

            }
            reader.readAsDataURL(f);

            
            
            // $("#image_list").append(clone);
    }

    var disp_thumbnail_store = function(f, i) {

        var tr = $("#add-store-photo-template");
        var clone = $(tr).clone();

        $(clone).find('[name=tmp_photo_comment_tmp]').attr('name', 'tmp_photo_comment_'+i);
        $(clone).find('[name=tmp_store_photo_id_tmp]').attr('name', 'tmp_store_photo_id_'+i);
        $(clone).find('[name=del_store_photo_tmp]').attr('name', 'del_store_photo');
        $(clone).find('[name=tmp_photo_comment_tmp_count]').attr('name', 'tmp_photo_comment_'+i+'_count');

        $.each($(clone).find('[name=tmp_photo_property_tmp]'), function(row, value){
            value.id = value.id.replace('_tmp', '_'+i);
            value.name = value.name.replace('_tmp', '_'+i);
        });

        $.each($(clone).find('[name=photo_list_tmp]'), function(row, value){
            value.id = value.id.replace('tmp-1', i);
            value.name = value.name.replace('_tmp', '');
        });

        $.each($(clone).find('label'), function(row, value){
            if(value.htmlFor.match(/tmp_photo_property_tmp/)) {
                value.htmlFor = value.htmlFor.replace('_tmp', '_'+i);
            }

            if(value.htmlFor.match(/photo_list_tmp/)) {
                value.htmlFor = value.htmlFor.replace('_tmp-1', '_'+i);
            }
        });

        var formData = new FormData();
        formData.append('tmp_image', f);
        formData.append('num', i);

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            contentType: false,
            processData: false,
            url: '/admin/save_tmp_store',
            data: formData,
            dataType: 'json',
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $(clone).find('[name=tmp_store_photo_id_'+i+']').val(data);
            $(clone).find('[name=photo_list]').val('tmp_'+data);
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });

        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")


        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値        
        // 画像をリサイズする
        var image = new Image();
        var reader = new FileReader();
        reader.onload = function(e) {
            image.onload = function() {
                var width, height;
                if(image.width > image.height){
                    // 横長の画像は横のサイズを指定値にあわせる
                    var ratio = image.height/image.width;
                    width = THUMBNAIL_WIDTH;
                    height = THUMBNAIL_WIDTH * ratio;
                } else {
                    // 縦長の画像は縦のサイズを指定値にあわせる
                    var ratio = image.width/image.height;
                    width = THUMBNAIL_HEIGHT;
                    height = THUMBNAIL_HEIGHT;
                }
                // サムネ描画用canvasのサイズを上で算出した値に変更
                var canvas = $(clone).find('canvas').attr('width', width).attr('height', height);
                var ctx = $(canvas)[0].getContext('2d');
                // canvasに既に描画されている画像をクリア
                ctx.clearRect(0,0,width,height);
                // canvasにサムネイルを描画
                ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                // canvasからbase64画像データを取得
                var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                // base64からBlobデータを作成
                var barr, bin, n, len;
                bin = atob(base64.split('base64,')[1]);
                len = bin.length;
                barr = new Uint8Array(len);
                n = 0;
                while (n < len) {
                    barr[n] = bin.charCodeAt(n);
                    n++;
                }
                blob = new Blob([barr], {type: 'image/jpeg'});
                console.log(blob);
            }
            image.src = e.target.result;
        }
        reader.readAsDataURL(f);

        $("#image_list").append(clone);
    }

    var disp_thumbnail_reform = function(f, i) {

        var tr = $("#add-reform-photo-template");
        var clone = $(tr).clone();

        $(clone).find('[name=tmp_photo_comment_tmp]').attr('name', 'tmp_photo_comment_'+i);
        $(clone).find('[name=tmp_reform_photo_id_tmp]').attr('name', 'tmp_reform_photo_id_'+i);
        $(clone).find('[name=del_reform_photo_tmp]').attr('name', 'del_reform_photo');
        $(clone).find('[name=tmp_photo_comment_tmp_count]').attr('name', 'tmp_photo_comment_'+i+'_count');

        $.each($(clone).find('[name=tmp_photo_property_tmp]'), function(row, value){
            value.id = value.id.replace('_tmp', '_'+i);
            value.name = value.name.replace('_tmp', '_'+i);
        });

        $.each($(clone).find('[name=photo_list_tmp]'), function(row, value){
            value.id = value.id.replace('tmp-1', i);
            value.name = value.name.replace('_tmp', '');
        });

        $.each($(clone).find('label'), function(row, value){
            if(value.htmlFor.match(/tmp_photo_property_tmp/)) {
                value.htmlFor = value.htmlFor.replace('_tmp', '_'+i);
            }

            if(value.htmlFor.match(/photo_list_tmp/)) {
                value.htmlFor = value.htmlFor.replace('_tmp-1', '_'+i);
            }
        });

        var formData = new FormData();
        formData.append('tmp_image', f);
        formData.append('num', i);

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            contentType: false,
            processData: false,
            url: '/admin/save_tmp_reform',
            data: formData,
            dataType: 'json',
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $(clone).find('[name=tmp_reform_photo_id_'+i+']').val(data);
            $(clone).find('[name=photo_list]').val('tmp_'+data);
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });

        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")


        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値        
        // 画像をリサイズする
        var image = new Image();
        var reader = new FileReader();
        reader.onload = function(e) {
            image.onload = function() {
                var width, height;
                if(image.width > image.height){
                    // 横長の画像は横のサイズを指定値にあわせる
                    var ratio = image.height/image.width;
                    width = THUMBNAIL_WIDTH;
                    height = THUMBNAIL_WIDTH * ratio;
                } else {
                    // 縦長の画像は縦のサイズを指定値にあわせる
                    var ratio = image.width/image.height;
                    width = THUMBNAIL_HEIGHT;
                    height = THUMBNAIL_HEIGHT;
                }
                // サムネ描画用canvasのサイズを上で算出した値に変更
                var canvas = $(clone).find('canvas').attr('width', width).attr('height', height);
                var ctx = $(canvas)[0].getContext('2d');
                // canvasに既に描画されている画像をクリア
                ctx.clearRect(0,0,width,height);
                // canvasにサムネイルを描画
                ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                // canvasからbase64画像データを取得
                var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                // base64からBlobデータを作成
                var barr, bin, n, len;
                bin = atob(base64.split('base64,')[1]);
                len = bin.length;
                barr = new Uint8Array(len);
                n = 0;
                while (n < len) {
                    barr[n] = bin.charCodeAt(n);
                    n++;
                }
                blob = new Blob([barr], {type: 'image/jpeg'});
                console.log(blob);
            }
            image.src = e.target.result;
        }
        reader.readAsDataURL(f);

        $("#image_list").append(clone);
    }

    var disp_thumbnail_facility = function(f, num) {
        const THUMBNAIL_WIDTH = 199; // 画像リサイズ後の横の長さの最大値
        const THUMBNAIL_HEIGHT = 149; // 画像リサイズ後の縦の長さの最大値
        
        var div = $("#add-facility-template");
        var clone = $(div).clone();
        var names = $(clone).find("input, select, textarea");

        $.each(names, function(row, value){
            if(value['name'] != 'file_single_input' && value['name'] != 'file_path') {
                $(clone).find('[name='+value['name']+']').attr('name', value['name']+'_'+num);
            }
        });
        $(clone).find('[name=memo_count]').attr('name', 'memo_'+num+'_count');

        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")
                
            // 画像をリサイズする
            var image = new Image();
            var reader = new FileReader();
            reader.onload = function(e) {
                image.onload = function() {
                    var width, height;
                    if(image.width > image.height){
                        // 横長の画像は横のサイズを指定値にあわせる
                        var ratio = image.height/image.width;
                        width = THUMBNAIL_WIDTH;
                        height = THUMBNAIL_WIDTH * ratio;
                    } else {
                        // 縦長の画像は縦のサイズを指定値にあわせる
                        var ratio = image.width/image.height;
                        width = THUMBNAIL_HEIGHT;
                        height = THUMBNAIL_HEIGHT;
                    }
                    // サムネ描画用canvasのサイズを上で算出した値に変更
                    var canvas = $(clone).find('canvas').attr('width', width).attr('height', height);
                    var ctx = $(canvas)[0].getContext('2d');
                    // canvasに既に描画されている画像をクリア
                    ctx.clearRect(0,0,width,height);
                    // canvasにサムネイルを描画
                    ctx.drawImage(image,0,0,image.width,image.height,0,0,width,height);

                    // canvasからbase64画像データを取得
                    var base64 = $(canvas).get(0).toDataURL('image/jpeg');        
                    // base64からBlobデータを作成
                    var barr, bin, n, len;
                    bin = atob(base64.split('base64,')[1]);
                    len = bin.length;
                    barr = new Uint8Array(len);
                    n = 0;
                    while (n < len) {
                        barr[n] = bin.charCodeAt(n);
                        n++;
                    }
                    blob = new Blob([barr], {type: 'image/jpeg'});
                    console.log(blob);
                }
                image.src = e.target.result;
            }
            reader.readAsDataURL(f);

            $("#image_list_sub").append(clone);
    }

    $('#btnBack').on('click', function(){
        var uri = location.href.replace(/\?.*/g, '');
	        window.location.href = uri;
    });

    // 画像まとめて
    $(".p-imgupload-large__area").on("drop",function(e){
        
        e.preventDefault();
        var saved_photo = $('[name=saved_photo_id]').val();
        var result = [];
        var len = 0;
        if(saved_photo != "") {
            result = saved_photo.split(',');
            len = result.length;
        }
        

        var files = e.originalEvent.dataTransfer.files;
        // $("#fileInput")[0].files = files;

        var def = $.Deferred().resolve().promise();
        var i = 0;
        $.each(files, function(key, file){

            // $.ajax() の戻り値(jqXHR)を .then() で繋げる
            def = def.then(function(){
                var article_id = $('[name=article_id]').val();
                var formData = new FormData();
                formData.append('image', file);
                formData.append('article_id', article_id);

                return $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    url: '/admin/article_photo_save',
                    data: formData,
                    dataType: 'json',
                    async: true
                })
                .then(function(data){
                    // リクエスト成功時に呼ばれる
                    disp_thumbnail_new(file, i+len, data);
                    var saved = $('[name=saved_photo_id]').val();
                    if(saved != "") {
                        saved += ",";
                    }
                    $('[name=saved_photo_id]').val(saved+data);
                    i++;
                });
            })
        });

        
        // for (var i=0; i<files.length; i++) {
        //     //画像じゃない場合はスルー
        //     if (!files[i] || files[i].type.indexOf('image/') < 0) {
        //         continue;
        //     }

        //     imageFileUpload(files[i])


        // }
    });

    function imageFileUpload(f) {
        var formData = new FormData();
        formData.append('image', f);
        formData.append('article_id', 3006);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            contentType: false,
            processData: false,
            url: '/admin/article_photo_save',
            data: formData,
            dataType: 'json',
            async: true
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("aaa");
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    }

    $(".p-imgupload-large__area").on("dragover",function(e){
        e.preventDefault();
    });

    $(".p-imgupload-large__store").on("drop",function(e){
        
        e.preventDefault();
        var len = $('[name^=del_store_photo]').length;
        var files = e.originalEvent.dataTransfer.files;
        // $("#fileInput")[0].files = files;

        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            disp_thumbnail_store(files[i], i+len);
        }
    });

    $(".p-imgupload-large__store").on("dragover",function(e){
        e.preventDefault();
    });

    $(".p-imgupload-large__reform").on("drop",function(e){
        
        e.preventDefault();
        var len = $('[name^=del_reform_photo]').length;
        var files = e.originalEvent.dataTransfer.files;
        // $("#fileInput")[0].files = files;

        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            disp_thumbnail_reform(files[i], i+len);
        }
    });

    $(".p-imgupload-large__reform").on("dragover",function(e){
        e.preventDefault();
    });

    $('[name=save_mansion_to_room]').on('click', function(){
        $(this).parents('form').attr('action', $(this).parents('form').attr('action')+'?room=1');
        $(this).parents('form').submit();
    });


    $('.c-band__lot__btn').on('click', function(){
        var id = $('#target_id').text();
        window.location.href = "/admin/copyLot?copy="+id; 

    });

    $('.btnSearchDelete').on('click', function(){
        if(window.confirm('この物件を削除しますがよろしいですか？')){
            var id = $(this).parent('div').find('[name=target_article]').val();

            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                url: '/admin/article_del',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });
        }
        return false;
    });
    
    //************************************************************************************ */

    $(".p-imgupload__area").on("drop",function(e){
        
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        if(files.length > 1) {
            alert("アップロードできる画像は１枚です。");
            return false;
        }
        $("#fileSingleInput")[0].files = files;

        $(this).find('img').hide();

        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            var obj = $('[name=canvas_floor]');
            var clone = disp_thumbnail_single(files[i], obj);
        }
    });

    $(".p-imgupload__area").on("dragover",function(e){
        e.preventDefault();
    });

    $("#imageArea2").on("drop",function(e){
        
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        if(files.length > 1) {
            alert("アップロードできる画像は１枚です。");
            return false;
        }
        $("#fileSingleInput2")[0].files = files;

        $(this).find('img').hide();

        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            var obj = $('[name=canvas_floor2]');
            var clone = disp_thumbnail_single(files[i], obj);
        }
    });

    $("#imageArea2").on("dragover",function(e){
        e.preventDefault();
    });

    $("#imageArea3").on("drop",function(e){
        
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        if(files.length > 1) {
            alert("アップロードできる画像は１枚です。");
            return false;
        }
        $("#fileSingleInput3")[0].files = files;

        $(this).find('img').hide();

        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            var obj = $('[name=canvas_floor3]');
            var clone = disp_thumbnail_single(files[i], obj);
        }
    });

    $("#imageArea3").on("dragover",function(e){
        e.preventDefault();
    });

    $(document).on('click', '[name=vendor_modal_btn]', function(){
        $('[name=open_num]').val($(this).attr('data-num'));
    });
    $('[name=modal_vendor_search]').on('click', function(){
        $('[name=open_num]').val($(this).attr('data-num'));
    });
    
    //************************************************************************************ */

    var marker;
    function getClickLatLng(lat_lng, map, marker) {

        // 座標を表示
        $('[name=lat]').val(lat_lng.lat());
        $('[name=lng]').val(lat_lng.lng());

        //生成済マーカーを順次すべて削除する
        marker.setMap(null);
        marker = null;	//参照を開放
  
        // マーカーを設置
        marker = new google.maps.Marker({
          position: lat_lng,
          map: map
        });
  
        // 座標の中心をずらす
        map.panTo(lat_lng);
      }

    //モーダルウィンドウを出現させるクリックイベント
    $(document).on('click', '.modal-open',  function(){
        var num = $(this).data("n");

        if(num == 2) {
            var target_lat = "35.44778";
            var target_lng = "139.6425";
            if($('[name=lat]').val() != "") {
                target_lat = $('[name=lat]').val();
            }
            if($('[name=lng]').val() != "") {
                target_lng = $('[name=lng]').val();
            }
            var MyLatLng = new google.maps.LatLng(target_lat, target_lng);
            var Options = {
             zoom: 15,      //地図の縮尺値
             center: MyLatLng,    //地図の中心座標
             mapTypeId: 'roadmap'   //地図の種類
            };
            var map = new google.maps.Map(document.getElementById('map'), Options);

            // マーク表示
            posNCM = new google.maps.LatLng(target_lat,target_lng);
            marker = new google.maps.Marker({
                position: posNCM,
                map: map,
                navigationControl: false,
                navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN}
            });

            // クリックイベントを追加
            map.addListener('click', function(e) {
                getClickLatLng(e.latLng, map, marker);
            });
        }

        //キーボード操作などにより、オーバーレイが多重起動するのを防止する
        $( this ).blur() ;  //ボタンからフォーカスを外す
        // if( $( "#modal-overlay" )[0] ) return false ;       //新しくモーダルウィンドウを起動しない (防止策1)
        if($("#modal-overlay")[0]) $("#modal-overlay").remove() ;     //現在のモーダルウィンドウを削除して新しく起動する (防止策2)

        //オーバーレイを出現させる
        $( "body" ).append( '<div id="modal-overlay"></div>' ) ;
        $( "#modal-overlay" ).fadeIn( "slow" ) ;

        //コンテンツをセンタリングする
        centeringModalSyncer(num) ;

        //コンテンツをフェードインする
        $( "#modal-content"+num ).fadeIn( "slow" ) ;

        //[#modal-overlay]、または[#modal-close]をクリックしたら…
        $( "#modal-overlay,.modal-close" ).unbind().click( function(){
            //[#modal-content]と[#modal-overlay]をフェードアウトした後に…
            $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){

                //[#modal-overlay]を削除する
                $('#modal-overlay').remove() ;

            } ) ;

        } ) ;

    } ) ;

    //リサイズされたら、センタリングをする関数[centeringModalSyncer()]を実行する
    $( window ).resize( centeringModalSyncer ) ;

    //センタリングを実行する関数
    function centeringModalSyncer(num) {
        if($(".modal-contents").length == 0) {
            return false;
        }

        //画面(ウィンドウ)の幅、高さを取得
        var w = $( window ).width() ;
        var h = $( window ).height() ;

        // コンテンツ(#modal-content)の幅、高さを取得
        var cw = $( "#modal-content"+num ).outerWidth();
        var ch = $( "#modal-content"+num ).outerHeight();

        //センタリングを実行する
        
        $( ".modal-contents" ).css( {"left": ((w - cw)/2) + "px","top": ((h - ch)/2) + "px"} ) ;
    }

    $(document).on('click', '[name=event_schedule_area_clear1]', function(){
        $(this).parent().children('input').val('');

    });
    $('[name=event_schedule_area_clear2]').on('click', function(){
        $(this).parent().children('input').val('');
    });
    $(document).on('click', '[name=event_schedule_area_add]', function(){
        var div = $(this).parent();
        var clone = $(div).clone();
        $(div).after(clone);
        $('.cal_picker', clone).removeClass("hasDatepicker")
            .removeData("datepicker")
            .removeAttr("id")
            .val('')
            .datepicker({ 
                dateFormat: "yy/mm/dd" 
            });
    });

    $('[name=add_vendor]').on('click', function(){
        addVendor();

        return false;
    });
    
    function addVendor() {
        var table = $("#vendor_template");
        var clone = $(table).clone();
        var tables = $('[name=vendor_list]').find('[name=vendor_num]');
        var count = tables.length;
        var num = $('[name=vendor_list]').find('[name=vendor_name]').length + 1;
        $(clone).find('[name=vendor_num]').text(('0000000000' + count).slice(-2));
        $(clone).find('.btn_search').attr('data-num', num);
        
        $(clone).removeClass("d-none").removeAttr("id");

        $('[name=vendor_list]').append(clone);
    }
    $('[name=all_check_vendor]').on('click', function(){
        var target = $('[name=print]');
        if($(this).prop('checked')) {
            $(target).each(function() {
                $(this).prop('checked', true);
            });
        } else {
            $(target).each(function() {
                $(this).prop('checked', false);
            });
        }
    });

    $('[name=print_fax]').on('click', function(){
        var target = $('[name=print]');
        var post_id = "";
        $(target).each(function() {
            if($(this).prop('checked')) {
                if(post_id != "") {
                    post_id += ',';
                }
                post_id += $(this).parents('td').find('[name=print_id]').val();
            }
        });
        $('[name=print_id_list]').val(post_id);
        
        $(this).parents('form').submit();
    });

    $('[name=news_link]').on('change', function(){
        var selected = $(this).val();
        if(selected == 1) {
            $('[name=news_link]').parents('tr').next('tr').show(500);
        } else {
            $('[name=news_link]').parents('tr').next('tr').hide(500);
        }
    });

    $('[name=news_delete]').on('click', function(){
        
        if(window.confirm('このお知らせを削除しますがよろしいですか？')){
            var id = $(this).parent('div').find('[name=news_id]').val();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteNews',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });

        }
        return false;
    });

    $('[name=store_delete]').on('click', function(){
        
        if(window.confirm('この店舗を削除しますがよろしいですか？')){
            var id = $(this).parent('td').find('[name=store_id]').val();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteStore',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });

        }
        return false;
    });

    $('[name=delete_facility]').on('click', function(){
        
        if(window.confirm('この施設を削除しますがよろしいですか？')){
            var id = $(this).parent('div').find('[name=facility_id]').val();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteFacility',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                $('#test').submit();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });

        }
        return false;
    });

    $('[name=recommend_save]').on('click', function(){
        var id = "";
        var remaining = $('[name=remaining]').val();
        if($(':checkbox:checked').length > remaining) {
            alert('残り最大'+remaining+'件までしか登録できません。');
            return false;
        }

        $(':checkbox:checked').each(function() {
            if(id == "") {
                id = $(this).val();
            } else {
                id += ","+$(this).val(); 
            }
        });

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/saveRecommend',
            data: {
                id: id
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            window.location.href = "/admin/recommend"; 
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });

        return false;
    });

    $('[name=recommend_delete]').on('click', function(){
        
        if(window.confirm('このおすすめ設定を削除しますがよろしいですか？')){
            var id = $(this).parent('td').find('[name=recommend_id]').val();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteRecommend',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });

        }
        return false;
    });

    $('[name=parking]').on('change', function(){
        var id = $(this).val();
        var name = 'parking_cost_area_'+id;
        $('.parking_cost_area').hide();
        $('#'+name);
        if(id == 3 || id == 4 || id == 5 || id == 6) {
            $('#'+name).show();
        }
    });

    $('[name=parking_yes]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_yes_area').show();
        } else {
            $('#parking_yes_area').hide();
        }
    });

    $('[name=parking_require_management]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_require_management_area').show();
        } else {
            $('#parking_require_management_area').hide();
        }
    });
    $('[name=parking_require_repair]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_require_repair_area').show();
        } else {
            $('#parking_require_repair_area').hide();
        }
    });

    $('[name=parking_any_management]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_any_management_area').show();
        } else {
            $('#parking_any_management_area').hide();
        }
    });
    $('[name=parking_any_repair]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_any_repair_area').show();
        } else {
            $('#parking_any_repair_area').hide();
        }
    });
    $('[name=parking_designated]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_designated_area').show();
        } else {
            $('#parking_designated_area').hide();
        }
    });

    $('[name=parking_out]').on('change', function(){
        var id = $(this).val();
        if(id == 1) {
            $('#parking_out_area').show();
        } else {
            $('#parking_out_area').hide();
        }
    });

    $('.p-vendor-list__subtbl__btn').on('click', function(){
        var obj = $(this).parents('form');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/save_vendor_info',
            data: $(obj).serialize(), 
        })
        .done(function(data){ //ajaxの通信に成功した場合
            console.log(data);
            $('#saved_message').text('保存しました。');
            openMessageModal();
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            console.log(data);
            alert("error!");
        });
    });
    
    

    $('[name=reform_delete]').on('click', function(){
        
        if(window.confirm('このリフォームを削除しますがよろしいですか？')){
            var id = $(this).parent('td').find('[name=reform_id]').val();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteReform',
                data: {
                    id: id
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });

        }
        return false;
    });


    $('[name=search_station_multi_pref]').on('change', function(){
        var prefId = $(this).val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref_station',
            data: {
                prefId: prefId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            $('[name=search_station_multi_city] option').remove();
            $('[name=search_station_multi_city]').append($('<option>').text('市区郡を選択').attr('value', ''));
            $.each(data[0], function(row, value){
                $('[name=search_station_multi_city]').append($('<option>').text(value['name']).attr('value', value['code']));
            });

            $('#station_list_multi tbody tr').remove();
            $.each(data[1], function(row, value){
                var tr ="<tr><td>"+value['line']+"</td><td>"+value['name']+"</td></tr>";
                $('#station_list_multi').append(tr);
            });

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $('[name=search_station_multi_city]').on('change', function(){
        var cityId = $(this).val();
        var prefId = $('[name=search_station_multi_pref]').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/city_station',
            data: {
                prefId: prefId,
                cityId: cityId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('#station_list_multi tr').remove();
            $('#station_list_multi').append("<tr><th>沿線名</th><th>駅名</th></tr>");
            $.each(data[0], function(row, value){
                var tr ="<tr><td>"+value['line']+"<input type=\"hidden\" value=\""+value['line_id']+"\" name=\"line_id\"><input type=\"hidden\" value=\""+value['id']+"\" name=\"station_id\"></td><td>"+value['name']+"</td></tr>";
                $('#station_list_multi').append(tr);
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $("#set_main_traffic, #set_sub_traffic1, #set_sub_traffic2").on('click', function(){
        var active_obj = $('#station_list_multi').find('.activeLine');
        var active_td = $(active_obj).find('td');
        if(active_td.length != 0) {
            $(this).parents('tr').next().find('[name=selected_line]').text($(active_td)[0].innerText);
            $(this).parents('tr').next().find('[name=selected_station]').text($(active_td)[1].innerText);
            $(this).parents('tr').next().find('[name=selected_line_id]').val($(active_td)[0].children[0].value);
            $(this).parents('tr').next().find('[name=selected_station_id]').val($(active_td)[0].children[1].value);
        }
        return false;
    });

    $("#del_main_traffic, #del_sub_traffic1, #del_sub_traffic2").on('click', function(){
        var active_obj = $('#station_list_multi').find('.activeLine');
        $(this).parents('tr').next().find('[name=selected_line]').text('');
        $(this).parents('tr').next().find('[name=selected_station]').text('');
        $(this).parents('tr').next().find('[name=selected_time]').val('');
        return false;
    });

    $(".set_parent_traffic").on('click', function(){
        var num = $(this).attr('data-n');
        var obj_main = $('[name=modal_main_traffic]');
        var obj_sub1 = $('[name=modal_sub_traffic1]');
        var obj_sub2 = $('[name=modal_sub_traffic2]');
        var obj_main_line_info = $(obj_main).find('p');
        var obj_main_walk_info = $(obj_main).find('input');
        var obj_main_line_id = $(obj_main).find('[name=selected_line_id]');
        var obj_main_sttion_id = $(obj_main).find('[name=selected_station_id]');

        var obj_sub_line_info1 = $(obj_sub1).find('p');
        var obj_sub_walk_info1 = $(obj_sub1).find('input');
        var obj_sub_line_id1 = $(obj_sub1).find('[name=selected_line_id]');
        var obj_sub_sttion_id1 = $(obj_sub1).find('[name=selected_station_id]');
        var obj_sub_line_info2 = $(obj_sub2).find('p');
        var obj_sub_walk_info2 = $(obj_sub2).find('input');
        var obj_sub_line_id2 = $(obj_sub2).find('[name=selected_line_id]');
        var obj_sub_sttion_id2 = $(obj_sub2).find('[name=selected_station_id]');

        $('[name=main_traffic_line]').val($(obj_main_line_info)[0].innerText);
        $('[name=main_traffic_station]').val($(obj_main_line_info)[1].innerText);
        $('[name=main_traffic_time]').val($(obj_main_walk_info).val());
        $('[name=main_traffic_line_id]').val($(obj_main_line_id).val());
        $('[name=main_traffic_station_id]').val($(obj_main_sttion_id).val());

        $('[name=sub_traffic1_line]').val($(obj_sub_line_info1)[0].innerText);
        $('[name=sub_traffic1_station]').val($(obj_sub_line_info1)[1].innerText);
        $('[name=sub_traffic1_time]').val($(obj_sub_walk_info1).val());

        $('[name=sub_traffic1_line_id]').val($(obj_sub_line_id1).val());
        $('[name=sub_traffic1_station_id]').val($(obj_sub_sttion_id1).val());

        $('[name=sub_traffic2_line]').val($(obj_sub_line_info2)[0].innerText);
        $('[name=sub_traffic2_station]').val($(obj_sub_line_info2)[1].innerText);
        $('[name=sub_traffic2_time]').val($(obj_sub_walk_info2).val());
        $('[name=sub_traffic2_line_id]').val($(obj_sub_line_id2).val());
        $('[name=sub_traffic2_station_id]').val($(obj_sub_sttion_id2).val());

        $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){
            //[#modal-overlay]を削除する
            $('#modal-overlay').remove() ;
        } ) ;
    });

    $(document).on('click', '#station_list_multi td', function(){
        var tag_tr = $(this).parent()[0];
        var all_tr = $('#station_list_multi tr');

        $.each(all_tr, function(row, tr){
            $(tr).removeClass('activeLine');
        });

        $(tag_tr).addClass('activeLine');
    });

    $('[name=search_station_pref]').on('change', function(){
        get_city($(this));

        var parent = $(this).parents('main');
        search_line(parent);

	
        var prefId = $(this).val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref_station',
            data: {
                prefId: prefId
            }
        })
            .done(function(data){ //ajaxの通信に成功した場合
                // alert("success!");
                $('[name=search_station_city] option').remove();
                $('[name=search_station_city]').append($('<option>').text('市区郡を選択').attr('value', ''));
                $.each(data[0], function(row, value){
                    $('[name=search_station_city]').append($('<option>').text(value['name']).attr('value', value['code']));
                });

            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!");
            });
    });

    $('[name=search_station_city]').on('change', function(){
        var parent = $(this).parents('main');
        search_line(parent);
    });

    $('[name=search_line_key]').on('keyup', function(){
        var parent = $(this).parents('main');
        search_line(parent);
    });

    function get_city(obj) {
        var prefId = $(obj).val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/pref',
            data: {
                prefId: prefId
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            var obj_op = $(obj).next().find('option');
            $.each(obj_op, function(row, op){
                $(op).remove();
            });

            $(obj).next().append($('<option>').text('市区郡を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj).next().append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    }

    function search_line(obj_base) {
        var prefId = $(obj_base).find('[name=search_station_pref]').val();
        var cityId = $(obj_base).find('[name=search_station_city]').val();
        var key = $(obj_base).find('[name=search_line_key]').val();
        var obj_line = $(obj_base).find('[name=line_list]');
        var obj_station = $(obj_base).find('[name=station_list]');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_line',
            data: {
                prefId: prefId,
                cityId: cityId,
                key: key
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            var del_tr = $(obj_line).find('tr');
            $.each(del_tr, function(row, obj_tr){
                $(obj_tr).remove();
            });
            del_tr = $(obj_station).find('tr');
            $.each(del_tr, function(row, obj_tr){
                $(obj_tr).remove();
            });
            $.each(data, function(row, value){
                var tr ="<tr><td>"+value['line']+"<input type=\"hidden\" value=\""+value['line_id']+"\" name=\"line_id\"></td></tr>";
                $(obj_line).append(tr);
            });

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    }

    $(document).on('click', '[name=line_list] td', function(){
        var all_tr = $(this).parents('[name=line_list]').find('td');
        $.each(all_tr, function(row, td){
            $(td).removeClass('activeLine');
        });
        $(this).addClass("activeLine");

        var parent = $(this).parents('main');
        search_station(parent);
        
    });

    $(document).on('click', '[name=station_list] td', function(){
        var all_td = $(this).parents('[name=station_list]').find('td');
        $.each(all_td, function(row, td){
            $(td).removeClass('activeStation');
        });
        $(this).addClass("activeStation");
        
    });

    $('[name=search_station_key]').on('keyup', function(){
        var parent = $(this).parents('main');
        search_station(parent);
    });

    function search_station(obj_base) {
        var active_line_name = $(obj_base).find('.activeLine')[0].innerText;
        var key = $(obj_base).find('[name=search_station_key]').val();
        var obj_station = $(obj_base).find('[name=station_list]');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_station',
            data: {
                line: active_line_name,
                key: key
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            del_tr = $(obj_station).find('tr');
            $.each(del_tr, function(row, obj_tr){
                $(obj_tr).remove();
            });
            $.each(data, function(row, value){
                var tr ="<tr><td>"+value['name']+"<input type=\"hidden\" value=\""+value['id']+"\" name=\"station_id\"></td></tr>";
                $(obj_station).append(tr);
            });

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    }

    $('.set_traffic').on('click', function(){
        var parent = $(this).parents('main');
        var num = $(this).attr('data-n');
        var line_obj = parent.find('.activeLine');
        var station_obj = parent.find('.activeStation');
        var obj = $('button[data-n='+num+']').parents('tr');

        if(line_obj.length == 0 || station_obj.length == 0) {
            alert("路線、駅を選択してください。");
        } else {
            obj.find('.line_name').val(line_obj[0].innerText);
            obj.find('.station_name').val(station_obj[0].innerText);

            obj.find('.line_id').val($(line_obj).find('[name=line_id]').val());
            obj.find('.station_id').val($(station_obj).find('[name=station_id]').val());

            $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){
                //[#modal-overlay]を削除する
                $('#modal-overlay').remove() ;
            } ) ;
        }
    });

    $('.del_traffic').on('click', function(){
        var parent = $(this).parents('main');
        var num = $(this).attr('data-n');
        var obj = $('button[data-n='+num+']').parents('tr');

        obj.find('.line_name').val('');
        obj.find('.station_name').val('');
        $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){
            //[#modal-overlay]を削除する
            $('#modal-overlay').remove() ;
        } ) ;
    });


    // 学校検索
    $('[name=primary_school_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_e_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=primary_school_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('小学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });
    $('[name=primary_school2_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_e_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=primary_school2_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('小学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });
    $('[name=primary_school3_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_e_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=primary_school3_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('小学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    $('[name=secondary_school_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_j_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=secondary_school_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('中学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });
    $('[name=secondary_school2_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_j_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=secondary_school2_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('中学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });
    $('[name=secondary_school3_city]').on('change', function(){
        var town = $('option:selected',this).text();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_j_school',
            data: {
                town: town
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            var obj_school = $('[name=secondary_school3_school]');
            $(obj_school).find('option').remove();
            $(obj_school).append($('<option>').text('中学校を選択').attr('value', ''));
            $.each(data, function(row, value){
                $(obj_school).append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
    });

    charactersChange = function(ele){
        var val = ele.val();
        var han = val.replace(/[０-９]/g,function(s){return String.fromCharCode(s.charCodeAt(0)-0xFEE0)});

        if(val.match(/[０-９]/g)){
            $(ele).val(han);
        }
    }
    
    $('[name=primary_school_distance]').bind('change',function(e){

        charactersChange($(this));
        var input = $(this).val();
        var time = 0;
        if($.isNumeric(input)) {
            time = Math.ceil(input / 80);
        } else {
            alert("数値を入力してください。");
        }
        $('[name=primary_school_time]').text(time);
    });

    $('[name=primary_school2_distance]').bind('change',function(e){

        charactersChange($(this));
        var input = $(this).val();
        var time = 0;
        if($.isNumeric(input)) {
            time = Math.ceil(input / 80);
        } else {
            alert("数値を入力してください。");
        }
        $('[name=primary_school2_time]').text(time);
    });

    $('[name=secondary_school_distance]').bind('change',function(){
        charactersChange($(this));
        var input = $(this).val();
        var time = 0;
        if($.isNumeric(input)) {
            time = Math.ceil(input / 80);
        } else {
            alert("数値を入力してください。");
        }
        $('[name=secondary_school_time]').text(time);
    });

    $('[name=secondary_school2_distance]').bind('change',function(){
        charactersChange($(this));
        var input = $(this).val();
        var time = 0;
        if($.isNumeric(input)) {
            time = Math.ceil(input / 80);
        } else {
            alert("数値を入力してください。");
        }
        $('[name=secondary_school2_time]').text(time);
    });

    $(document).bind('keydown keyup keypress change', function(event){
        if(event.target.tagName == 'TEXTAREA') {
            var name = event.target.name + '_count';
            var thisValueLength = $(event.target).val().replace(/[\n　]/g, "").length;
            $('[name='+name+']').html(thisValueLength);
        }
    });

    // 全不可
    $(document).on('click', '.btn_allcheck', function(){
        var obj_select = $(this).parent().parent().find('select');
        $.each(obj_select, function(index, element){
            $(element).val(3);
        });
        return false;
    });

    $(".delete_user").on('click', function(){
        if(confirm('本当に削除しますか？')){
            var id = $(this).parents('tr').find('[name=user_id]').text();
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                datatype: 'json',
                url: '/admin/deleteUser',
                data: {
                    id: id,
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!"); 
            });
        }
    });

    $("[name=shop]").on('change', function(){
        var id = $(this).val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/admin/search_charge',
            data: {
                id: id,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('[name=hp_charge]').children().remove();
            $.each(data, function(row, value){
                $('[name=hp_charge]').append($('<option>').text(value['name']).attr('value', value['code']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });
    });
    
    // 業者登録
    $('[name=save_vendor]').on('click', function(){
        var obj_id = $(this).parent().prev().find('[name=vendor_id]');
        var id = obj_id.val();
        var name = $(this).parent().prev().find('[name=vendor_name]').val();
        var manner = $(this).parent().prev().find('[name=manner]').val();
        var vendor_tel = $(this).parent().parent().next().find('[name=vendor_tel]').val();
        var vendor_fax = $(this).parent().parent().next().find('[name=vendor_fax]').val();
        var vendor_charge = $(this).parent().parent().next().find('[name=vendor_charge]').val();
        
        var flyer = $(this).parent().parent().next().next().find('[name=flyer]').val();
        var freepaper = $(this).parent().parent().next().next().find('[name=freepaper]').val();
        var house_hp = $(this).parent().parent().next().next().find('[name=house_hp]').val();
        var portal = $(this).parent().parent().next().next().find('[name=portal]').val();
        var signboard = $(this).parent().parent().next().next().find('[name=signboard]').val();
        var ad_conf_day = $(this).parent().parent().next().next().find('[name=ad_conf_day]').val();
        
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/save_vendor',
            data: {
                id: id,
                name: name,
                manner: manner,
                vendor_tel: vendor_tel,
                vendor_fax: vendor_fax,
                vendor_charge: vendor_charge,
                flyer: flyer,
                freepaper: freepaper,
                house_hp: house_hp,
                portal: portal,
                signboard: signboard,
                ad_conf_day: ad_conf_day,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!");
            obj_id.val(data);



        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });

        return false;
    });

    // 施設管理
    $('[name=facility_property]').on('change', function(){
        var kind = $(this).val();
        var lat = $('[name=lat]').val();
        var lng = $('[name=lng]').val();
        
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_facility',
            data: {
                kind: kind,
                lat: lat,
                lng: lng
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('[name=facility]').children().remove();
            $('[name=facility]').append($('<option>').text('施設名を選択').attr('value', ''));
            $.each(data, function(row, value){
                $('[name=facility]').append($('<option>').text(value['name']).attr('value', value['id']));
            });
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });

        return false;
    });

    $('[name=facility]').on('change', function(){
        var id = $(this).val();
        var lat = $('[name=lat]').val();
        var lng = $('[name=lng]').val();
        
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_facility_info',
            data: {
                id: id,
                lat: lat,
                lng: lng
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            if(data['img'] != "") {
                $('[name=facility_img]').attr('src', data['img']);
            } else {
                $('[name=facility_img]').attr('src', '/img/noimage2.jpg');
            }
            
            
            $('[name=facility_distance]').val(data['distance']);
            $('[name=facility_num]').val(data['id']);
            $('[name=facility_time]').text(data['time']);
            // alert(data);
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });

        return false;
    });

    $('.add_facility').on('click', function(){
        var tr = $("#facilty_tmplate");
        var clone = $(tr).clone();

        var td = $(this).parents('td');

        if($(td).find('[name=facility] option:selected').val() == "") {
            alert('施設を選択してください。');
            return false;
        }

        var img = $(td).find('[name=facility_img]').attr('src');
        var kind = $(td).find('[name=facility_property] option:selected').text();
        var name = $(td).find('[name=facility] option:selected').text();
        var num = $(td).find('[name=facility_num]').val();
        var time = $(td).find('[name=facility_time]').text();
        var distance = $(td).find('[name=facility_distance]').val();

        $(clone).find('[name=save_facility_img]').attr('src', img);
        $(clone).find('[name=save_facility_property]').text(kind);
        $(clone).find('[name=save_facility_name]').text(name);
        $(clone).find('[name=save_facility_num]').text(num);
        $(clone).find('[name=save_facility_id\\[\\]]').val(num);
        $(clone).find('[name=save_facility_time]').text(Math.ceil(distance/80));
        $(clone).find('[name=save_facility_distance\\[\\]]').val(distance);
        $(clone).removeClass("d-none").removeAttr("id");
        $('#facility_list').append(clone);

        
        
        $(td).find('[name=facility_img]').attr('src', '/img/noimage2.jpg');
        $(td).find('[name=facility_area]').val('');
        $(td).find('[name=facility_property]').children('option').remove();
        $(td).find('[name=facility_property]').append($('<option>').text('施設種別を選択').attr('value', ''));
        $(td).find('[name=facility_num]').val('');
        $(td).find('[name=facility_time]').text('');
        $(td).find('[name=facility_distance]').val(0);
        $(td).find('[name=facility]').children().remove();
        $('[name=facility]').append($('<option>').text('施設名を選択').attr('value', ''));
    });

    $('[name=facility_distance]').on('change', function(){
        charactersChange($(this));
        var input = $(this).val();
        var time = 0;
        if($.isNumeric(input)) {
            time = Math.ceil(input / 80);
            $(this).parents('dd').find('[name=facility_time]').text(time);
        } else {
            alert("数値を入力してください。");
        }
        
    });

    $(document).on('click', '.del_article_facility', function(){
        var del_text = $('[name=delete_facility_list]').val();
        if(del_text != "") {
            del_text += ",";
        }
        var target = $(this).parents('tr').find('[name=save_facility_id\\[\\]]').val();
        del_text+=target;
        $('[name=delete_facility_list]').val(del_text)

        $(this).parents('tr').remove();
    });

    $('[name=save_facility]').on('click', function(){
        var img = $('[name=facility_img]').attr('src');
        var id = $('[name=facility_num]').val();
        var name = $('[name=facility] option:selected').text();
        var property = $('[name=facility_property] option:selected').text();
        

        var _html1 = (function () {/*
            <tr>
        <td>
            <div id="facilty_tmp" class="d-flex">
                <div class="w200 mr10">
                    <img src="
        */}).toString().replace(/(\n)/g, '').split('*')[1];
       var _html2 = (function () {/*
        " width="200">
                </div>
                <div class="w500 mr10">
                    <div>
                    施設種別
        */}).toString().replace(/(\n)/g, '').split('*')[1];
        var _html3 = (function () {/*
                    現地までの距離
                    <select class="c-selectbox " name="f_distance">
<option value="" selected="">距離を選択</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
</select>                                    </div>
                    <div>
                    施設名
        */}).toString().replace(/(\n)/g, '').split('*')[1];
                //    +name+
        var _html4 = (function () {/*
                    施設番号
                   */}).toString().replace(/(\n)/g, '').split('*')[1];
                //    +id+
        var _html5 = (function () {/*
                    </div>
                </div>
                <div>
                    <a class="" href="/admin/editFacility/
                   */}).toString().replace(/(\n)/g, '').split('*')[1];
                //    +id+
        var _html6 = (function () {/*
                   ">編集</a>
                    <a class="" href="javascript:void(0);" name="delete_facility_
                */}).toString().replace(/(\n)/g, '').split('*')[1];
        var _html7 = (function () {/*
                   ">削除</a>
                </div>
            </div>
        </td>
    </tr>
        */}).toString().replace(/(\n)/g, '').split('*')[1];
        $('#facility_list').append(_html1+img+_html2+property+_html3+name+_html4+id+_html5+id+_html6+id+_html7);



    });
    

    $(".upload__image").on("drop",function(e){
        
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        if(files.length > 1) {
            alert("アップロードできる画像は１枚です。");
            return false;
        }
        $(this).find("#fileInput")[0].files = files;

        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            disp_thumbnail(files[i], i);
        }
    });

    $(".upload__image").on("dragover",function(e){
        e.preventDefault();
    });

    $(".save_change").on('click', function(){
        var selected = $('[name=target]').val();
        
        if(selected == 0) {
            alert('処理種別を選択してください。');
            return false;
        } else if(selected == 2) {
            var count = $('[name^=change_target]:checked').length;
            if(count == 0) {
                alert('重複対象を選択してください。');
                return false;
            } else if(count > 1) {
                alert('重複対象は１つにしてください。');
                return false;
            }
        } else if(selected == 4) {
            if(!confirm('本当に削除しますか？')){
                return false;
            }
        } else if(selected == 5) {
            var count = $('[name^=change_target]:checked').length;
            var property = $('[name^=change_target]:checked').parents('td').find('[name^=save_targe]').val();
            var target = $('[name^=change_target]:checked').val();
            if(count == 0) {
                alert('対象のマンションを選択してください。');
                return false;
            } else if(count > 1) {
                alert('対象のマンションは１つにしてください。');
                return false;
            } else if(property != 6 && property != 7) {
                alert('対象はマンション建物を選択してください。');
                return false;
            } else {
                $('[name=m_target]').val(target);
            }
        }
    });

    $('[name^=con]').on('click', function(){
        var num = $(this).data('tabnum');
        var tab_obj = $('[name^=con]');
        var table_obj = $('[name^=duplicate_data]');

        if(num == 5) {
            if($("[name=target] option[value=5]").length == 0) {
                $("[name=target] option[value=0]").after($("<option>").val(5).text("m部屋を仮登録"));
                $("[name=target] option[value=2]").remove();
            }
        } else {
            if($("[name=target] option[value=5]").length == 1) {
                $("[name=target] option[value=5]").remove();
                $("[name=target] option[value=0]").after($("<option>").val(2).text("重複"));
            }
        }

        // タブの状態変化
        $.each(tab_obj, function(index, obj){
            $(obj).removeClass('active');
            if((num-1) == index) {
                $(obj).addClass('active');
            }
        });

        // データ部の表示非表示
        $.each(table_obj, function(index, obj){
            $(obj).addClass('p-rains__none');
            if((num-1) == index) {
                $(obj).removeClass('p-rains__none');
            }
        });

    });

    $(document).on("click", ".clear-button", function () {
        clearForm($(this).parents('form'));
    });

    $(".clear-lot").on("click", function () {
        clearForm($(this).parents('.search_vendor'));
    });

    $(".facility_clear").on("click", function () {
        clearForm($(this).parents('.search_vendor'));
    });

    function clearForm (form) {
        $(form)
            .find("input, select, textarea")
            .not(":button, :submit, :reset, :hidden, [name=address1], [name=search_lot_address1], [name=search_address1]")
            .val("")
            .prop("checked", false)
            .prop("selected", false)
        ;
    }



    $('[name=vendor_modal]').on('show.bs.modal', function (event) {
        // var button = $(event.relatedTarget);
        // var sampledata = button.data('sample');
        // var modal = $(this);
        // modal.find('.modal-title').val(sampledata);
        // alert("aaaa");
    })

    $(".p-imgupload-facility__area").on("drop",function(e){
        
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        // var new_files_len = new_files.length;
        // var old_files = $("#fileInput")[0].files;

        // var files = $.merge( new_files, old_files);
        $("#fileInput")[0].files = files;

        $("#image_list_sub").children().remove();
        
        for (var i=0; i<files.length; i++) {
            //画像じゃない場合はスルー
            if (!files[i] || files[i].type.indexOf('image/') < 0) {
                continue;
            }

            disp_thumbnail_facility(files[i], i);
        }
    });

    $('[name=open_table]').on('click', function(){
        $(this).parents('tr').next('tr').find('.article_info').toggle();
    });
    $('[name=close_table]').on('click', function(){
        $(this).parents('.article_info').toggle();
    });

    $('[name=open_article]').on('click', function(){
        var num = $(this).parents('td').prev('td').attr('rowspan');

        var target = $(this).parents('tr');
        if(num !== undefined) {
            for(var i = 1; i < num; i++) {
                $(target).next('tr').find('.article_list').removeClass('d-none');
                target = $(target).next('tr');
            }
        }
    });
    $('[name=close_article]').on('click', function(){
        var num = $(this).parents('td').find('.row_iteration').text();
        var target = $(this).parents('tr');
        for(var i = 0; i < num; i++) {
            target = $(target).prev('tr');
        }
        num = $(target).find('.parent_td').attr('rowspan');

        if(num !== undefined) {
            for(var i = 1; i < num; i++) {
                $(target).next('tr').find('.article_list').addClass('d-none');
                target = $(target).next('tr');
            }
        }
    });

    $('.saved_to_image').on('click', function(){
        var action = $(this).parents('form').attr('action');
        action += '?toimage=1';
        $(this).parents('form').attr('action', action);
    });

    $('.link_to_room').on('click', function(){
        var action = $(this).parents('form').attr('action');
        var target = $(this).parents('td').find('[name=target_to_room]').val();
        action += '?toroom='+target;
        $(this).parents('form').attr('action', action);
    });

    $('[name=del_staff_photo]').on('click', function(){
        $('[name=del_photo]').val(1);

        if($(this).parents('td').find('.p-imgupload__area').find('img').length == 1) {
            $(this).parents('td').find('.p-imgupload__area').find('img').remove();
        }
        
        var cvs = $(this).parents('td').find('canvas');
        var ctx = cvs[0].getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        cvs.width(0);
        cvs.height(0);
        $('.p-imgupload__text').show();
    });

    $('[name=user_disp]').on('change', function(){
        var id = $(this).parents('td').find('[name=user_id]').val();
        var check = 0;
        if($(this).prop('checked')) {
            check = 1;
        }
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/disp_user',
            data: {
                id: id,
                check: check,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });
    });

    $('[name=reform_disp]').on('change', function(){
        var id = $(this).parents('td').next('td').find('[name=reform_id]').val();
        var check = 0;
        if($(this).prop('checked')) {
            check = 1;
        }
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/disp_reform',
            data: {
                id: id,
                check: check,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });
    });

    $('[name=news_disp]').on('change', function(){
        var id = $(this).parents('td').next('td').find('[name=news_id]').val();
        var check = 0;
        if($(this).prop('checked')) {
            check = 1;
        }
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/disp_news',
            data: {
                id: id,
                check: check,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });
    });

    $('[name=store_disp]').on('change', function(){
        var id = $(this).parents('td').next('td').find('[name=store_id]').val();
        var check = 0;
        if($(this).prop('checked')) {
            check = 1;
        }
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/disp_store',
            data: {
                id: id,
                check: check,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合

        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
        });
    });

    $('#sortable_new').sortable({
        axis: 'y'
      }).disableSelection();
        
    $('#sortable_new').bind('sortstop', function (e, ui) {
        var rows = $('#sortable_new tbody');

        $.each(rows, function(key, row){
            $(row).removeClass('even');
            $(row).removeClass('odd');
            if((key+1) % 2 == 0) {
                $(row).addClass('even');
            } else {
                $(row).addClass('odd');
            }
            $(row).find('.rank').text(key+1);

            var id = $(row).find('[name=recommend_id]').val();
            var num = key+1;
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                url: '/admin/set_recommend_rank',
                data: {
                    id: id,
                    num: num,
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
    
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!"); 
            });
        });
    });

    $('#sortable_reform').sortable({
        axis: 'y'
      }).disableSelection();
        
    $('#sortable_reform').bind('sortstop', function (e, ui) {
        var rows = $('#sortable_reform tbody');

        $.each(rows, function(key, row){
            $(row).removeClass('even');
            $(row).removeClass('odd');
            if((key+1) % 2 == 0) {
                $(row).addClass('even');
            } else {
                $(row).addClass('odd');
            }
            $(row).find('.rank').text(key+1);

            var id = $(row).find('[name=reform_id]').val();
            var num = key+1;
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                url: '/admin/set_reform_rank',
                data: {
                    id: id,
                    num: num,
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
    
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!"); 
            });
        });
    });



    $('#sortable_article_image  tbody').sortable(); 
        
    $('#sortable_article_image').bind('sortstop', function (e, ui) {
        var rows = $('#sortable_article_image tbody .ui-sortable-handle');

        var save = '';
        $.each(rows, function(key, row){
            var target = $(row).find('[name^=article_photo_id]').val();
            if(target !== undefined) {
                if(save != '') {
                    save += ',';
                }
                save += target;
            }
        });
        $('[name=saved_photo_id]').val(save);
    });
    $('#sortable_store_image  tbody').sortable();
    $('#sortable_reform_image  tbody').sortable();  



    $('[name=del_article_floor_photo]').on('click', function(){
        if($(this).parents('td').find('.p-imgupload__area').find('img').length == 1) {
            $(this).parents('td').find('.p-imgupload__area').find('img').remove();
        }
        var cvs = $(this).parents('td').find('canvas');
        var ctx = cvs[0].getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        cvs.width(0);
        cvs.height(0);

        $('.p-imgupload__text').show();

        
        $('#floor_file_delete_flg').val(1);
    });

    $('[name=del_article_sheet_photo2]').on('click', function(){
        if($(this).parents('td').find('.p-imgupload__area2').find('img').length == 1) {
            $(this).parents('td').find('.p-imgupload__area2').find('img').remove();
        }
        var cvs = $(this).parents('td').find('canvas');
        var ctx = cvs[0].getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        cvs.width(0);
        cvs.height(0);

        $('.p-imgupload__text').show();

        
        $('#floor_file_delete_flg2').val(1);
    });

    $('[name=del_article_sheet_photo3]').on('click', function(){
        if($(this).parents('td').find('.p-imgupload__area3').find('img').length == 1) {
            $(this).parents('td').find('.p-imgupload__area3').find('img').remove();
        }
        var cvs = $(this).parents('td').find('canvas');
        var ctx = cvs[0].getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        cvs.width(0);
        cvs.height(0);

        $('.p-imgupload__text').show();

        
        $('#floor_file_delete_flg3').val(1);
    });

    $('.p-mansion-search__open').on('click', function(){
        $(this).parents('tr').next('tr').find('.room_info').toggle();
    });

    $('.close_room_list').on('click', function(){
        $(this).parents('.room_info').toggle();
    });

    $('[name=management]').on('change', function(){
        if($(this).val() == 1) {
            $('#management_cost_area').show();
        } else {
            $('#management_cost_area').hide();
        }
    });

    $('[name=repair]').on('change', function(){
        if($(this).val() == 1) {
            $('#repair_cost_area').show();
        } else {
            $('#repair_cost_area').hide();
        }
    });

    $('[name=current_status]').on('change', function(){
        if($(this).val() == 12) {
            $('#current_status_area').show();
        } else {
            $('#current_status_area').hide();
        }
    });


    $('[name=pet]').on('change', function(){
        if($(this).val() == 1) {
            $('[name=pet_count]').attr('disabled',true);
        } else {
            $('[name=pet_count]').attr('disabled',false);
        }
    });
    $('[name=land_right]').on('click', function(){
        $('[name=leasehold_kind]:checked').val();
        if($(this).val() == 1 || $(this).val() == 0) {
            $('#land_right1').hide();
            $('#land_right2').hide();
            $('#land_right3').hide();
            $('#land_right4').hide();
            $('#land_right5').hide();
            $('#land_right6').hide();
            $('#land_right7').hide();
            $('#land_right8').hide();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        } else if($(this).val() == 2) {
            $('#land_right1').show();
            $('#land_right2').hide();
            $('#land_right3').show();
            $('#land_right4').show();
            $('#land_right5').show();
            $('#land_right6').show();
            $('#land_right7').show();
            $('#land_right8').show();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        } else if($(this).val() == 3) {
            $('#land_right1').show();
            $('#land_right2').show();
            $('#land_right3').show();
            $('#land_right4').show();
            $('#land_right5').show();
            $('#land_right6').show();
            $('#land_right7').show();
            $('#land_right8').show();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        }
    });

    $('[name=leasehold_kind]').on('click', function(){
        if($(this).val() == 1 || $(this).val() == 2 || $(this).val() == 5 || $(this).val() == 6) {
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        } else {
            $('#land_right9').show();
            $('#land_right10').show();
            $('#land_right11').show();
            $('#land_right12').show();
        }
    });

    $('[name=land_rent]').on('click', function(){
        if($(this).val() == 1) {
            $('#land_rent_area').show();
        } else {
            $('#land_rent_area').hide();
        }
    });
    
    $('[name=right_cost]').on('click', function(){
        if($(this).val() == 1) {
            $('#right_cost_area').show();
        } else {
            $('#right_cost_area').hide();
        }
    });
    
    $('[name=deposit_cost]').on('click', function(){
        if($(this).val() == 1) {
            $('#deposit_cost_area').show();
        } else {
            $('#deposit_cost_area').hide();
        }
    });
    
    $('[name=security_deposit_cost]').on('click', function(){
        if($(this).val() == 1) {
            $('#security_deposit_cost_area').show();
        } else {
            $('#security_deposit_cost_area').hide();
        }
    });

    $('[name=regular_leased_season]').on('click', function(){
        if($(this).val() != 1) {
            $('#regular_leased_season_area').hide();
        } else {
            $('#regular_leased_season_area').show();
        }
    });

    $('[name=regular_leased_transfer]').on('click', function(){
        if($(this).val() != 1) {
            $('#regular_leased_transfer_area').hide();
        } else {
            $('#regular_leased_transfer_area').show();
        }
    });
    
    $('[name=balcony_area]').on('click', function(){
        if($(this).val() == 0) {
            $('#balcony_area_area').hide();
        } else {
            $('#balcony_area_area').show();
        }
    });

    $('[name=loof_balcony_area]').on('click', function(){
        if($(this).val() == 0) {
            $('#loof_balcony_area_area').hide();
        } else {
            $('#loof_balcony_area_area').show();
        }
    });

    $('[name=garden_area]').on('click', function(){
        if($(this).val() == 0) {
            $('#garden_area_area').hide();
        } else {
            $('#garden_area_area').show();
        }
    });

    $('[name=terrace_area]').on('click', function(){
        if($(this).val() == 0) {
            $('#terrace_area_area').hide();
        } else {
            $('#terrace_area_area').show();
        }
    });


    // 読み込み時処理
    $(document).ready(function() {
        if($('[name=land_right]:checked').val() == 1 || $('[name=land_right]:checked').val() == 0) {
            $('#land_right1').hide();
            $('#land_right2').hide();
            $('#land_right3').hide();
            $('#land_right4').hide();
            $('#land_right5').hide();
            $('#land_right6').hide();
            $('#land_right7').hide();
            $('#land_right8').hide();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        } else if($('[name=land_right]:checked').val() == 2) {
            $('#land_right1').show();
            $('#land_right2').hide();
            $('#land_right3').show();
            $('#land_right4').show();
            $('#land_right5').show();
            $('#land_right6').show();
            $('#land_right7').show();
            $('#land_right8').show();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        } else if($('[name=land_right]:checked').val() == 3) {
            $('#land_right1').show();
            $('#land_right2').show();
            $('#land_right3').show();
            $('#land_right4').show();
            $('#land_right5').show();
            $('#land_right6').show();
            $('#land_right7').show();
            $('#land_right8').show();
            $('#land_right9').hide();
            $('#land_right10').hide();
            $('#land_right11').hide();
            $('#land_right12').hide();
        }

        if($('[name=land_right]:checked').val() != 1 && $('[name=land_right]:checked').val() != 0) {
            if($('[name=leasehold_kind]:checked').val() == 1 || $('[name=leasehold_kind]:checked').val() == 2 || 
            $('[name=leasehold_kind]:checked').val() == 5 || $('[name=leasehold_kind]:checked').val() == 6) {
                $('#land_right9').hide();
                $('#land_right10').hide();
                $('#land_right11').hide();
                $('#land_right12').hide();
            } else {
                $('#land_right9').show();
                $('#land_right10').show();
                $('#land_right11').show();
                $('#land_right12').show();
            }
        }

        if($('[name=balcony_area]:checked').val() == 0) {
            $('#balcony_area_area').hide();
        } else {
            $('#balcony_area_area').show();
        }
        if($('[name=loof_balcony_area]:checked').val() == 0) {
            $('#loof_balcony_area_area').hide();
        } else {
            $('#loof_balcony_area_area').show();
        }
        if($('[name=garden_area]:checked').val() == 0) {
            $('#garden_area_area').hide();
        } else {
            $('#garden_area_area').show();
        }
        if($('[name=terrace_area]:checked').val() == 0) {
            $('#terrace_area_area').hide();
        } else {
            $('#terrace_area_area').show();
        }


        

        


        if($('[name=land_rent]:checked').val() == 0) {
            $('#land_rent_area').hide();
        } else {
            $('#land_rent_area').show();
        }
        if($('[name=right_cost]:checked').val() == 0) {
            $('#right_cost_area').hide();
        } else {
            $('#right_cost_area').show();
        }
        if($('[name=deposit_cost]:checked').val() == 0) {
            $('#deposit_cost_area').hide();
        } else {
            $('#deposit_cost_area').show();
        }
        if($('[name=security_deposit_cost]:checked').val() == 0) {
            $('#security_deposit_cost_area').hide();
        } else {
            $('#security_deposit_cost_area').show();
        }

        if($('[name=regular_leased_season]:checked').val() != 1) {
            $('#regular_leased_season_area').hide();
        } else {
            $('#regular_leased_season_area').show();
        }

        if($('[name=regular_leased_transfer]:checked').val() != 1) {
            $('#regular_leased_transfer_area').hide();
        } else {
            $('#regular_leased_transfer_area').show();
        }


        if($('.room_info') !== undefined) {
            $('.room_info').hide();
        }

        if($('.article_info') !== undefined) {
            $('.article_info').hide();
        }

        if($('[name=management]:checked').val() == 1) {
            $('#management_cost_area').show();
        } else {
            $('#management_cost_area').hide();
        }

        if($('[name=repair]:checked').val() == 1) {
            $('#repair_cost_area').show();
        } else {
            $('#repair_cost_area').hide();
        }

        if($('[name=pet]:checked').val() == 1) {
            $('[name=pet_count]').attr('disabled',true);
        }

        if($('[name=parking]:checked').val() == 0 || $('[name=parking]:checked').val() == 1 || $('[name=parking]:checked').val() == 2) {
            $('#parking_cost_area_3').hide(500);
            $('#parking_cost_area_4').hide(500);
            $('#parking_cost_area_5').hide(500);
            $('#parking_cost_area_6').hide(500);
        } else if($('[name=parking]:checked').val() == 3) {
            $('#parking_cost_area_3').show(500);
            $('#parking_cost_area_4').hide(500);
            $('#parking_cost_area_5').hide(500);
            $('#parking_cost_area_6').hide(500);
        } else if($('[name=parking]:checked').val() == 4) {
            $('#parking_cost_area_3').hide(500);
            $('#parking_cost_area_4').show(500);
            $('#parking_cost_area_5').hide(500);
            $('#parking_cost_area_6').hide(500);
        } else if($('[name=parking]:checked').val() == 5) {
            $('#parking_cost_area_3').hide(500);
            $('#parking_cost_area_4').hide(500);
            $('#parking_cost_area_5').show(500);
            $('#parking_cost_area_6').hide(500);
        } else if($('[name=parking]:checked').val() == 6) {
            $('#parking_cost_area_3').hide(500);
            $('#parking_cost_area_4').hide(500);
            $('#parking_cost_area_5').hide(500);
            $('#parking_cost_area_6').show(500);
        }

        if($('[name=parking_yes]:checked').val() == 1){
            $('#parking_yes_area').show();
        } else {
            $('#parking_yes_area').hide();
        };

        if($('[name=parking_require_management]:checked').val() == 1){
            $('#parking_require_management_area').show();
        } else {
            $('#parking_require_management_area').hide();
        };

        if($('[name=parking_require_repair]:checked').val() == 1){
            $('#parking_require_repair_area').show();
        } else {
            $('#parking_require_repair_area').hide();
        };

        if($('[name=parking_any_management]:checked').val() == 1){
            $('#parking_any_management_area').show();
        } else {
            $('#parking_any_management_area').hide();
        };

        if($('[name=parking_any_repair]:checked').val() == 1){
            $('#parking_any_repair_area').show();
        } else {
            $('#parking_any_repair_area').hide();
        };

        if($('[name=parking_designated]:checked').val() == 1){
            $('#parking_designated_area').show();
        } else {
            $('#parking_designated_area').hide();
        };

        if($('[name=parking_out]:checked').val() == 1){
            $('#parking_out_area').show();
        } else {
            $('#parking_out_area').hide();
        };

        if($('[name=broadcasting]:checked').val() == 0 || $('[name=broadcasting]:checked').val() == 2) {
            $('[name=broadcasting]').parent().find('.initial_cost').hide(500);
            $('[name=broadcasting]').parent().find('.running_cost').hide(500);
        } else {
            $('[name=broadcasting]').parent().find('.initial_cost').show(500);
            $('[name=broadcasting]').parent().find('.running_cost').show(500);
        }

        if($('[name=broadcasting_presence]:checked').val() == 1) {
            $('[name=broadcasting_presence]').parent().find('.initial_cost_detail').show(500);
        } else {
            $('[name=broadcasting_presence]').parent().find('.initial_cost_detail').hide(500);
        }

        if($('[name=broadcasting_fixed_presence]:checked').val() == 1) {
            $('[name=broadcasting_fixed_presence]').parent().find('.running_cost_detail').show(500);
        } else {
            $('[name=broadcasting_fixed_presence]').parent().find('.running_cost_detail').hide(500);
        }

        if($('[name=internet]:checked').val() == 0 || $('[name=internet]:checked').val() == 2) {
            $('[name=internet]').parent().find('.initial_cost').hide(500);
            $('[name=internet]').parent().find('.running_cost').hide(500);
        } else {
            $('[name=internet]').parent().find('.initial_cost').show(500);
            $('[name=internet]').parent().find('.running_cost').show(500);
        }

        if($('[name=internet_presence]:checked').val() == 1) {
            $('[name=internet_presence]').parent().find('.initial_cost_detail').show(500);
        } else {
            $('[name=internet_presence]').parent().find('.initial_cost_detail').hide(500);
        }

        if($('[name=internet_fixed_presence]:checked').val() == 1) {
            $('[name=internet_fixed_presence]').parent().find('.running_cost_detail').show(500);
        } else {
            $('[name=internet_fixed_presence]').parent().find('.running_cost_detail').hide(500);
        }

        if($('[name=catv]:checked').val() == 0 || $('[name=catv]:checked').val() == 2) {
            $('[name=catv]').parent().find('.initial_cost').hide(500);
            $('[name=catv]').parent().find('.running_cost').hide(500);
        } else {
            $('[name=catv]').parent().find('.initial_cost').show(500);
            $('[name=catv]').parent().find('.running_cost').show(500);
        }

        if($('[name=catv_presence]:checked').val() == 1) {
            $('[name=catv_presence]').parent().find('.initial_cost_detail').show(500);
        } else {
            $('[name=catv_presence]').parent().find('.initial_cost_detail').hide(500);
        }

        if($('[name=catv_fixed_presence]:checked').val() == 1) {
            $('[name=catv_fixed_presence]').parent().find('.running_cost_detail').show(500);
        } else {
            $('[name=catv_fixed_presence]').parent().find('.running_cost_detail').hide(500);
        }

        if($('[name=council]:checked').val() == 0) {
            $('#council_presence_area').hide(500);
            $('#council_cost_area').hide(500);
        } else {
            $('#council_presence_area').show(500);
        }
    
        if($('[name=council_presence]:checked').val() == 1) {
            $('#council_cost_area').show(500);
        } else {
            $('#council_cost_area').hide(500);
        }

        if($('[name=spring]:checked').val() == 0) {
            $('#spring_area').hide(500);
            $('#spring_kind_area').hide(500);
        } else {
            $('#spring_area').show(500);
            $('#spring_kind_area').show(500);
            
        }

        if($('[name=spring_presence]:checked').val() == 1) {
            $('#spring_cost_area').show(500);
        } else {
            $('#spring_cost_area').hide(500);
        }



        if($('[name=land_condition1]').is(':checked')) {
            $('#land_condition1_area').show(500);
        } else {
            $('#land_condition1_area').hide(500);
        }

        if($('[name=land_condition2]').is(':checked')) {
            $('#land_condition2_area').show(500);
        } else {
            $('#land_condition2_area').hide(500);
        }

        if($('[name=land_condition3]').is(':checked')) {
            $('#land_condition3_area').show(500);
        } else {
            $('#land_condition3_area').hide(500);
        }

        if($('[name=current_status]:checked').val() != 3) {
            $('#land_status_area').hide(500);
        } else {
            $('#land_status_area').show(500);
        }

        if($('[name=land_delivery]:checked').val() != 3) {
            $('#land_delivery_area').hide(500);
        } else {
            $('#land_delivery_area').show(500);
        }

        if($('[name=land_condition]:checked').val() != 1) {
            $('#land_condition_area').hide(500);
        } else {
            $('#land_condition_area').show(500);
        }

        if($('[name=road_burden]:checked').val() == 0) {
            $('#road_burden_area1').hide(500);
            $('#road_burden_area2').hide(500);
        } else if($('[name=road_burden]:checked').val() == 1) {
            $('#road_burden_area1').show(500);
            $('#road_burden_area2').hide(500);
        } else if($('[name=road_burden]:checked').val() == 2) {
            $('#road_burden_area1').show(500);
            $('#road_burden_area2').show(500);
        }

        if($('[name=easement]:checked').val() == 2 || $('[name=easement]:checked').val() == 3 || 
        $('[name=easement]:checked').val() == 4 || $('[name=easement]:checked').val() == 5 || 
        $('[name=easement]:checked').val() == 6) {
            $('#easement_area').show(500);
        } else {
            $('#easement_area').hide(500);
        }

        if($('[name=set]:checked').val() != 1 && $('[name=set]:checked').val() != 0) {
            $('#set_area').show(500);
        } else {
            $('#set_area').hide(500);
        }

        if($('[name=classfication]:checked').val() == 1) {
            $('#classfication_area').hide(500);
        } else {
            $('#classfication_area').show(500);
        }

        if($('[name=city_plan]:selected').val() == 2){
            $('#city_plan_area').show(500);
        } else {
            $('#city_plan_area').hide(500);
        };

        if($('[name=move_in]:checked').val() == 3){
            $('#move_in_year').show(500);
            $('#move_in_month').hide(500);
        } else if($('[name=move_in]:checked').val() == 4){
            $('#move_in_year').hide(500);
            $('#move_in_month').show(500);
        } else {
            $('#move_in_year').hide(500);
            $('#move_in_month').hide(500);
        };


        if($('[name=exterior]:checked').val() != 1){
            $('#exterior_detail').show(500);
        } else {
            $('#exterior_detail').hide(500);
        };

        if($('[name=interior]:checked').val() != 1){
            $('#interior_detail').show(500);
        } else {
            $('#interior_detail').hide(500);
        };

        
        if($('[name=current_status]').val() != 12) {
            $('#current_status_area').hide(500);
        }


 

        


        var obj_span = $(document).find('span');
        $.each(obj_span, function(index, element){
            if($(element).hasClass('require')){
                $(element).parents('tr').addClass('require_tr');

                var count = $(element).parents('tr').find('th').attr('rowspan');
                var target = $(element).parents('tr');
                if(count !== undefined) {
                    for(var i = 1; i < count; i++) {
                        $(target).next('tr').addClass('require_tr');
                        target = $(target).next('tr');
                    }
                }
                
            }
            if($(element).hasClass('require_applicable')){
                $(element).parents('tr').addClass('require_applicable_tr');
            }
        });

        var obj_text = $(document).find('textarea');
        $.each(obj_text, function(index, element){
            var name = $(element).attr('name');
            if(name.match(/\[\]/)) {
                name = name.replace('\[\]', '\\[\\]');
            }
            var name = name + '_count';
		    var thisValueLength = $(element).val().replace(/[\n　]/g, "").length;
		    $('[name='+name+']').html(thisValueLength);
        });

        var obj_input = $(document).find('.t_count');
        $.each(obj_input, function(index, element){
            var name = $(element).attr('name') + '_count';
		    var thisValueLength = $(element).val().replace(/[\n　]/g, "").length;
		    $('[name='+name+']').html(thisValueLength);
        });

        var obj_lat = $(document).find('[name=lat]');
        var obj_lng = $(document).find('[name=lng]');

    });

    $("#regist_vendor").on('click', function(){
        window.location.href = "/admin/registVendor";
        return false;
    });

    $('[name=store]').on('change', function(){
        var id = $(this).val();
        var action = $("#rains_form").attr('action');
        action = action.replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]store=[0-9]*/g,'')
        window.location.href = action+"?store="+id;
    });

    $('[name=store_provisional]').on('change', function(){
        var id = $(this).val();
        var url = location.href;
        var action = url.replace(location.protocol+'//'+location.host, '');
        action = action.replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]store=[0-9]*/g,'')
        window.location.href = action+"?store="+id;
    });

    $('[name=search_vendor_modal_duplicate_btn]').on('click', function(){
        var search_vendor_name = $('[name=search_vendor_name]').val();
        var search_vendor_tel = $('[name=search_vendor_tel]').val();
        var search_vendor_fax = $('[name=search_vendor_fax]').val();
        var dup = $('[name=save_vendor_list]').val();
        // var num = $(this).parents('tr').find('[name=vendor_num]');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_vendor',
            data: {
                name: search_vendor_name,
                tel: search_vendor_tel,
                fax: search_vendor_fax,
                dup: dup
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('#vendor_list tr').remove();
            $.each(data, function(row, value){
                var tr = '<tr><td class="w100"><input type="hidden" name="set_vendor_id" value="'+value['id']+'"><input type="hidden" name="set_vendor_name" value="'+value['name']+'"><input type="hidden" name="set_vendor_tel" value="'+value['vendor_tel1']+'"><input type="hidden" name="set_vendor_fax" value="'+value['vendor_fax']+'"><button type="button" class="w80" name="search_vendor_set_btn_buplicate">選択</button></td>';
                tr += '<td class="w200"><a class="target_link_id" href="/admin/editVendor/'+value['id']+'">'+value['id']+'</a></td>';
                tr += '<td>'+value['name']+'</td></tr>';
                $('#vendor_list').append(tr);
            });

            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });
    });
    $('[name=search_vendor_modal_btn]').on('click', function(){
        var search_vendor_name = $('[name=search_vendor_name]').val();
        var search_vendor_tel = $('[name=search_vendor_tel]').val();
        var search_vendor_fax = $('[name=search_vendor_fax]').val();
        var dup = $('[name=save_vendor_list]').val();
        // var num = $(this).parents('tr').find('[name=vendor_num]');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_vendor',
            data: {
                name: search_vendor_name,
                tel: search_vendor_tel,
                fax: search_vendor_fax,
                dup: dup
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('#vendor_list tr').remove();
            $.each(data, function(row, value){
                var tr = '<tr><td class="w100"><input type="hidden" name="set_vendor_id" value="'+value['id']+'"><input type="hidden" name="set_vendor_name" value="'+value['name']+'"><input type="hidden" name="set_vendor_tel" value="'+value['vendor_tel1']+'"><input type="hidden" name="set_vendor_fax" value="'+value['vendor_fax']+'"><button type="button" class="w80" name="search_vendor_set_btn">選択</button></td>';
                tr += '<td class="w200"><a class="target_link_id" href="/admin/editVendor/'+value['id']+'">'+value['id']+'</a></td>';
                tr += '<td>'+value['name']+'</td></tr>';
                $('#vendor_list').append(tr);
            });

            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });
    });
    $(document).on('click', '[name=search_vendor_set_btn_buplicate]', function(){
        var id = $(this).parent('td').find('[name=set_vendor_id]').val();
        var name = $(this).parent('td').find('[name=set_vendor_name]').val();
        var tel = $(this).parent('td').find('[name=set_vendor_tel]').val();
        var fax = $(this).parent('td').find('[name=set_vendor_fax]').val();
        if(name == 'null') {
            name='';
        }
        if(tel == 'null') {
            tel='';
        }
        if(fax == 'null') {
            fax='';
        }


        var table = $("#vendor_tmplate");
        var clone = $(table).clone();
        var target_id = $('[name=open_num]').val();

        $(clone).find('[name=vendor_name]').text(name);
        $(clone).find('[name=vendor_id_]').val(id)
        $(clone).find('[name=vendor_id_]').attr('name', $(clone).find('[name=vendor_id_]').attr('name')+target_id+'[]');
        $(clone).find('[name=charge_]').attr('name', $(clone).find('[name=charge_]').attr('name')+target_id+'_'+id);
        $(clone).find('#vendor_id').text(id);
        $(clone).find('[name=manner_]').attr('name', $(clone).find('[name=manner_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=vendor_fax]').text(fax);

        $(clone).find('[name=ad_conf_day_]').attr('name', $(clone).find('[name=ad_conf_day_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=flyer_]').attr('name', $(clone).find('[name=flyer_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=freepaper_]').attr('name', $(clone).find('[name=freepaper_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=house_hp_]').attr('name', $(clone).find('[name=house_hp_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=portal_]').attr('name', $(clone).find('[name=portal_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=signboard_]').attr('name', $(clone).find('[name=signboard_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=ad_conf_]').attr('name', $(clone).find('[name=ad_conf_]').attr('name')+target_id+'_'+id);
        $(clone).find('[name=article_conf_day_]').attr('name', $(clone).find('[name=article_conf_day_]').attr('name')+target_id+'_'+id);


        $(clone).removeAttr("id");
        $(clone).removeClass("d-none")

        
        
        // console.log($('[data-num='+num+']'));
        $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){

            //[#modal-overlay]を削除する
            $('#modal-overlay').remove() ;

        } ) ;
        
        $('#vendor_list_area'+target_id).append(clone);

    });
    
    $(document).on('click', '[name=search_vendor_set_btn]', function(){
        var num = $('[name=open_num]').val();
        var id = $(this).parent('td').find('[name=set_vendor_id]').val();
        var name = $(this).parent('td').find('[name=set_vendor_name]').val();
        var tel = $(this).parent('td').find('[name=set_vendor_tel]').val();
        var fax = $(this).parent('td').find('[name=set_vendor_fax]').val();
        if(name == 'null') {
            name='';
        }
        if(tel == 'null') {
            tel='';
        }
        if(fax == 'null') {
            fax='';
        }

        $('[data-num='+num+']').parents('table').find('[name^=vendor_id]').val(id);
        $('[data-num='+num+']').parents('table').find('[name=vendor_name]').val(name);
        $('[data-num='+num+']').parents('table').find('[name=vendor_tel]').val(tel);
        $('[data-num='+num+']').parents('table').find('[name=vendor_fax]').val(fax);
        
        // console.log($('[data-num='+num+']'));
        $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){

            //[#modal-overlay]を削除する
            $('#modal-overlay').remove() ;

        } ) ;
        var target = $('[name=vendor_list]').find('[name=vendor_id\\[\\]]');
        var saved = "";
        $.each(target, function(row, obj){
            if(saved != "") {
                saved += ",";
            }
            saved+=$(obj).val();
        });
        $('[name=save_vendor_list]').val(saved);

        $('#vendor_list').children().remove();

    });

    $('.btnSearchSave').on('click', function(){
        var form = $(this).parents('form');
        
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            datatype: 'json',
            url: '/business/save_vendor',
            data: form.serialize(),
        })
        .done(function(data){ //ajaxの通信に成功した場合
            alert("保存しました。");
            location.reload();
            
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!");
        });
        return false;
    });

    $(document).on('click', '[name=del_vendor]', function(){
        var del_text = $('[name=delete_vendor_list]').val();
        if(del_text != "") {
            del_text += ",";
        }
        var target = $(this).parents('tr').find('[name=vendor_id\\[\\]]').val();
        del_text+=target;
        $('[name=delete_vendor_list]').val(del_text)

        var saved = $('[name=save_vendor_list]').val();
        if(saved.match(target+',')) {
            saved = saved.replace(target+',', '');
        } else if(saved.match(','+target)) {
            saved = saved.replace(','+target, '');
        } else if(saved.match(target)) {
            saved = saved.replace(target, '');
        }
        $('[name=save_vendor_list]').val(saved);

        $(this).parents('table').remove();

        if($('[name=save_vendor_list]').val() == "") {
            addVendor();
        }

        return false;
    });

    $('[name=search_lot_modal_btn]').on('click', function(){
        var search_vendor_name = $('[name=search_lot_name]').val();
        var search_vendor_num = $('[name=search_lot_num]').val();
        var search_vendor_address1 = $('[name=search_lot_address1] option:selected').val();
        var search_vendor_address2 = $('[name=search_lot_address2] option:selected').val();
        var search_vendor_address3 = $('[name=search_lot_address3] option:selected').val();
        // var num = $(this).parents('tr').find('[name=vendor_num]');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: '/admin/search_lot',
            type: 'POST',
            dataType: 'json',
            data: {
                name: search_vendor_name,
                num: search_vendor_num,
                address1: search_vendor_address1,
                address2: search_vendor_address2,
                address3: search_vendor_address3,
            }
            
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('#lot_list tr').remove();
            $.each(data, function(row, value){
                var tr = '<tr><td class="w100"><button type="button" class="w80" name="search_lot_set_btn">登録</button></td>';
                tr += '<td class="w200"><a href="/admin/editLot/'+value['building_id']+'">'+value['building_id']+'</a></td>';
                tr += '<td>'+value['name']+'</td></tr>';
                $('#lot_list').append(tr);
            });

            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });
    });

    $(document).on('click', '[name=search_lot_set_btn]', function(){
        var id = $(this).parents('tr').find('a').text();
        $('[name=sale_no]').val(id);
        $('[name=disp_sale_no]').text(id);
        
        $( ".modal-contents,#modal-overlay" ).fadeOut( "slow" , function(){

            //[#modal-overlay]を削除する
            $('#modal-overlay').remove() ;

        } ) ;
    });



    $('[name=facility_property]').on('change', function(){
        var selected = $(this).val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            dataType: 'json',
            url: '/admin/regist_search_facility',
            data: {
                property: selected,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('[name=facility] option').remove();
            $('[name=facility]').append($('<option>').text('施設名を選択').attr('value', ''));
            $.each(data, function(row, value){
                $('[name=facility]').append($('<option>').text(value['name']).attr('value', value['id']));
            });
            $('[name=facility_distance]').val(0);
            $('[name=facility_num]').text('');
            $('[name=facility_time]').text('');
            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });
    });

    $('.provisional_btn').on('click', function(){
        var selected = $(this).parents('td').find('[name=target]').val();
        var del = $(this).parents('td').find('[name=del_id]').val();
        if(selected == 2) {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                dataType: 'json',
                url: '/admin/provisional_del',
                data: {
                    del: del,
                }
            })
            .done(function(data){ //ajaxの通信に成功した場合
                location.reload();
                return false;
            })
            .fail(function(data){ //ajaxの通信に失敗した場合
                alert("error!"); 
                return false
            });
            return false;
        }
    });

    $('.save_info_btn').on('click', function(){
        var push_btn = $(this);
        var target_vendor_name = ["vendor_id","charge","manner","ad_conf_day","flyer","freepaper","house_hp","portal","signboard","ad_conf","article_conf_day"];
        var vendor_info = [];
        var change_info = [];
        var tmp_target = "";
        
        $.each(target_vendor_name, function(key, value){
            var tmp = [];
            tmp_target = $(push_btn).parents('table').find('[name='+value+']');
            $.each(tmp_target, function(row, obj){
                tmp.push($(obj).val());
            });
            vendor_info[value] = tmp;
        });
        
        var target_change_name = ["price_change","price","change_day","status","price_closing","closing_day","bk","key","memo1",];
        $.each(target_change_name, function(key, value){
            var tmp = [];
            tmp_target = $(push_btn).parents('table').find('[name='+value+']');
            $.each(tmp_target, function(row, obj){
                if(value == "price_change"){
                    if($(obj).prop("checked") == true) {
                        tmp.push(1);
                    } else {
                        tmp.push(0);
                    }
                } else {
                    tmp.push($(obj).val());
                }
                
            });
            change_info[value] = tmp;
        });

        var array_json = JSON.stringify(change_info)

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            dataType: 'json',
            url: '/admin/save_change_vendor',
            data: {
                // vendor: vendor_info,
                change: array_json,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!"); 
            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });

        // var target_charge = $(this).parents('table').find('[name=charge]');
        // var target_manner = $(this).parents('table').find('[name=manner]');
        // var target_ad_conf_day = $(this).parents('table').find('[name=ad_conf_day]');
        // var target_flyer = $(this).parents('table').find('[name=flyer]');
        // var target_freepaper = $(this).parents('table').find('[name=freepaper]');
        // var target_house_hp = $(this).parents('table').find('[name=house_hp]');
        // var target_portal = $(this).parents('table').find('[name=portal]');
        // var target_signboard = $(this).parents('table').find('[name=signboard]');
        // var target_ad_conf = $(this).parents('table').find('[name=ad_conf]');
        // var target_article_conf_day = $(this).parents('table').find('[name=article_conf_day]');

        // var target_price_change = $(this).parents('table').find('[name=price_change]');
        // var target_price = $(this).parents('table').find('[name=price]');
        // var target_change_day = $(this).parents('table').find('[name=change_day]');
        // var target_status = $(this).parents('table').find('[name=status]');
        // var target_price_closing = $(this).parents('table').find('[name=price_closing]');
        // var target_closing_day = $(this).parents('table').find('[name=closing_day]');
        // var target_bk = $(this).parents('table').find('[name=bk]');
        // var target_key = $(this).parents('table').find('[name=key]');
        // var target_memo1 = $(this).parents('table').find('[name=memo1]');
        
        console.log(vendor_info);
        console.log(change_info);
    });

    $('[name=search_vendor_btn]').on('click', function(){
        var search_condition = $(this).parent('div').prev('table');
        var search_vendor_name = $(search_condition).find('[name=search_vendor_name]').val();
        var search_vendor_shop = $(search_condition).find('[name=search_vendor_shop]').val();
        var search_vendor_tel = $(search_condition).find('[name=search_vendor_tel]').val();
        var search_vendor_fax = $(search_condition).find('[name=search_vendor_fax]').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_vendor',
            data: {
                name: search_vendor_name,
                shop: search_vendor_shop,
                tel: search_vendor_tel,
                fax: search_vendor_fax,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            // alert("success!"); 
            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });

        return false;

    });

    $(document).on('change', '[name=access1]', function(){
        var id = $(this).val();

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/admin/search_station_line',
            data: {
                line: id,
            }
        })
        .done(function(data){ //ajaxの通信に成功した場合
            $('[name=access2] option').remove();
            $('[name=access2]').append($('<option>').text('駅を選択').attr('value', ''));
            $.each(data, function(row, value){
                $('[name=access2]').append($('<option>').text(value['name']).attr('value', value['id']));
            });

            return false;
        })
        .fail(function(data){ //ajaxの通信に失敗した場合
            alert("error!"); 
            return false
        });

        return false;

    });

    $('[name=search_vendor_btn]').on('click', function(){
        window.location.href = "/admin/registVendor";
    });

        // クリックで矢印切り替え
    $(".p-search-common__collapse-link").click(function() {
        var $this = $(".p-search-common__collapse-link");
        if ($("#searchUnique").hasClass("show")) {
            $this.addClass("p-search-common__collapse-link--open");
            $this.removeClass("p-search-common__collapse-link--close");
        } else {
            $this.removeClass("p-search-common__collapse-link--open");
            $this.addClass("p-search-common__collapse-link--close");
        }
    });


// *********************************

    $('[name=c-circle-btn__check]').on('click', function(){
        $(this).parents('.p-results-noimage').find('.p-form-check').toggle();
        return false;
    });


    $('.modal-open-history').on('click', function(){
        var num = $(this).attr('data-num');
        openSelectModal("", num);
        return false;
    });

    $('.disp_room_noimage').on('click', function(){
        $(this).parents('.mansion-list').find('.p-mansion-room').toggle();
        return false;
    });

    $('.c-circle-btn__check-mansion_noimage').on('click', function(){
        $(this).parents('.mansion-list').find('.p-form-check').toggle();
        return false;
    });

    $('.business_search > .pagination > li > a').on('click', function(){
        var uri = location.href.replace(location.host, '').replace(/https:\/\//g,'').replace(/http:\/\//g,'').replace(/[\?||&]page=[0-9]*/g,'');

        var num = $(this).text();
        if ( uri.match(/\?/)) {
            uri += '&page='+num;
        } else {
            uri += '?page='+num;
        }
        $('#link_detail').attr('action', uri)
        $('#link_detail').submit();
        return false;
    });
    
    $('.p-results-sort__sort li').on('click', function(){
        var uri = location.href.replace(location.host, '').replace(/https:\/\//g,'').replace(/http:\/\//g,'').replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]sort=[^&]*/g,'');

        var sort = $(this).children('a').attr('class');
        sort = sort.replace('p-results-sort', '');
        if ( uri.match(/\?/)) {
            uri += '&sort='+sort;
        } else {
            uri += '?sort='+sort;
        }

        $('#link_detail').attr('action', uri)
        $('#link_detail').submit();
        return false;
    });

    $('#btnAllImg').on('click', function(){
        var id = $(this).attr('id');
        var uri = location.href.replace(location.host, '').replace(/https:\/\//g,'').replace(/http:\/\//g,'').replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]sort=[^&]*/g,'').replace(/[\?||&]image=[^&]*/g,'');

        $('#link_detail').attr('action', uri)
        $('#link_detail').submit();
        return false;
    });

    $('#btnNoImg').on('click', function(){
        var id = $(this).attr('id');
        var uri = location.href.replace(location.host, '').replace(/https:\/\//g,'').replace(/http:\/\//g,'').replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]sort=[^&]*/g,'').replace(/[\?||&]image=[^&]*/g,'');

        if ( uri.match(/\?/)) {
            uri += '&image=1';
        } else {
            uri += '?image=1';
        }

        $('#link_detail').attr('action', uri)
        $('#link_detail').submit();
        return false;
    });

    $('#btnImg').on('click', function(){
        var id = $(this).attr('id');
        var uri = location.href.replace(location.host, '').replace(/https:\/\//g,'').replace(/http:\/\//g,'').replace(/[\?||&]page=[0-9]*?/g,'').replace(/[\?||&]sort=[^&]*/g,'').replace(/[\?||&]image=[^&]*/g,'');

        if ( uri.match(/\?/)) {
            uri += '&image=2';
        } else {
            uri += '?image=2';
        }

        $('#link_detail').attr('action', uri)
        $('#link_detail').submit();
        return false;
    });

    //モーダルウィンドウを出現させるクリックイベント
    function openSelectModal(type, num) {

        //キーボード操作などにより、オーバーレイが多重起動するのを防止する
        $( this ).blur();  //ボタンからフォーカスを外す
        if( $( "#modal-overlay" )[0] ) return false;       //新しくモーダルウィンドウを起動しない (防止策1)
        //if($("#modal-overlay")[0]) $("#modal-overlay").remove();     //現在のモーダルウィンドウを削除して新しく起動する (防止策2)
        if(type != "") {
            $('#type').val(type);
        }

        //オーバーレイを出現させる
        $( "body" ).append( '<div id="modal-overlay"></div>' );
        $( "#modal-overlay" ).fadeIn( "slow" );

        //コンテンツをセンタリングする
        centeringModalSyncer(num);

        //コンテンツをフェードインする
        if(num == "") {
            $( "#modal-content" ).fadeIn( "slow" );
        } else {
            $( "#modal-content"+num ).fadeIn( "slow" );
        }

        if(num == "") {
        //[#modal-overlay]、または[#modal-close]をクリックしたら…
            $( "#modal-overlay,#modal-close" ).unbind().click( function(){

                //[#modal-content]と[#modal-overlay]をフェードアウトした後に…
                $( "#modal-content,#modal-overlay" ).fadeOut( "slow" , function(){

                    //[#modal-overlay]を削除する
                    $('#modal-overlay').remove();

                });
        });
        } else {
            //[#modal-overlay]、または[#modal-close]をクリックしたら…
            $( "#modal-overlay,#modal-close" ).unbind().click( function(){

                //[#modal-content]と[#modal-overlay]をフェードアウトした後に…
                $( "#modal-content"+num+",#modal-overlay" ).fadeOut( "slow" , function(){

                    //[#modal-overlay]を削除する
                    $('#modal-overlay').remove();

                });
        });
        }

    }

    //リサイズされたら、センタリングをする関数[centeringModalSyncer()]を実行する
    $( window ).resize( centeringModalSyncer );

    //センタリングを実行する関数
    function centeringModalSyncer(num) {

        //画面(ウィンドウ)の幅、高さを取得
        var w = $( window ).width();
        var h = $( window ).height();

        // コンテンツ(#modal-content)の幅、高さを取得
        if(num == "") {
            var cw = $( "#modal-content" ).outerWidth();
            var ch = $( "#modal-content" ).outerHeight();

            //センタリングを実行する
            $( "#modal-content" ).css( {"left": ((w - cw)/2) + "px","top": ((h - ch)/2) + "px"} );
        } else {
            var cw = $( "#modal-content"+num ).outerWidth();
            var ch = $( "#modal-content"+num ).outerHeight();

            //センタリングを実行する
            $( "#modal-content"+num ).css( {"left": ((w - cw)/2) + "px","top": ((h - ch)/2) + "px"} );
        }

    }



// *************************************


    $('.c-circle-btn__check').on('click', function(){
        $(this).parents('li').find('.p-form-check').toggle();
        return false;
    });




    $('.c-circle-btn__display').on('click', function(){
        $(this).parents('li').toggle();
        return false;
    });

    $('#btnAllDisp').on('click', function(){
        $('.list-unstyled').find('li').each(function(index, element){
            $(element).show(500);
        })
        return false;
    });

    $('[name=del_facility_img]').on('click', function(){
        $(this).parent().prev('div').find('img').attr('src', '');
        $('[name=del_img]').val(1);
    });

    $(document).on('click', '[name=del_facility]', function(){
        var cvs = $(this).parents('td').find('canvas');
        var ctx = cvs[0].getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        cvs.width(0);
        cvs.height(0);

        var num = $(this).parents('tr').next('tr').find('[name^=name]')[0].name.replace('name_', '');
        var del = $('[name=not_save_img_id]').val();
        if( del != "") {
            del += ",";
        }
        del += num;
        $('[name=not_save_img_id]').val(del);
    });


    $('[name=show_room_btn]').on('click', function(){
        $(this).parents('table').next('.room_list').toggle();
    });

    $('.validate_btn').on('click', function(){
        var target = $('.require_target');
        $.each(target, function(key, obj){
            var target = $(obj).val();
            if(target == '') {
                var text = $(obj).parents('tr').find('th').text();
                alert(text);
            }
            
            
        });
        return false;

    });
});













function sendFileToServer(formData, status) {
    var uploadURL = "/admin/uploadCsv"; //←アップロード後の処理ページURL
    var extraData = {}; //Extra Data.
    var jqXHR = 
    $.ajax({
      xhr: function () {
        var xhrobj = $.ajaxSettings.xhr();
        if (xhrobj.upload) {
          xhrobj.upload.addEventListener('progress', function (event) {
            var percent = 0;
            var position = event.loaded || event.position;
            var total = event.total;
            if (event.lengthComputable) {
              percent = Math.ceil(position / total * 100);
            }
            //Set progress
            status.setProgress(percent);
          }, false);
        }
        return xhrobj;
      },
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      url: uploadURL,
      type: "POST",
      contentType: false,
      processData: false,
      cache: false,
      data: formData,
      beforeSend: function(){
        $('.loading_disp').removeClass('loading_hide');
      }
    })
    .then(
        function(data) {
            $('.loading').addClass('loading_hide');
            sleep(5000);
            window.location.href = "/admin/duplicateCsv";
            // status.setProgress(100);
            // $("#status1").append("File upload Done<br>");
            // $("#status1").append(data); //←処理後の表示のため、戻り値を表示させる
        },
        function(data) {
            window.location.href = "/admin/duplicateCsv";
        }
    );
    status.setAbort(jqXHR);
  }

  function sleep(waitMsec) {
    var startMsec = new Date();
   
    // 指定ミリ秒間だけループさせる（CPUは常にビジー状態）
    while (new Date() - startMsec < waitMsec);
  }
  
  var rowCount = 0;
  
  function createStatusbar(obj) {
    rowCount++;
    var row = "odd";
    if (rowCount % 2 == 0) row = "even";
    this.statusbar = $("<div class='statusbar " + row + "'></div>");
    this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
    this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
    this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
    this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
    obj.after(this.statusbar);
    this.setFileNameSize = function (name, size) {
      var sizeStr = "";
      var sizeKB = size / 1024;
      if (parseInt(sizeKB) > 1024) {
        var sizeMB = sizeKB / 1024;
        sizeStr = sizeMB.toFixed(2) + " MB";
      } else {
        sizeStr = sizeKB.toFixed(2) + " KB";
      }
      this.filename.html(name);
      this.size.html(sizeStr);
    }
    this.setProgress = function (progress) {
      var progressBarWidth = progress * this.progressBar.width() / 100;
      this.progressBar.find('div').animate({
        width: progressBarWidth
      }, 10).html(progress + "% ");
      if (parseInt(progress) >= 100) {
        this.abort.hide();
      }
    }
    this.setAbort = function (jqxhr) {
      var sb = this.statusbar;
      this.abort.click(function () {
        jqxhr.abort();
        sb.hide();
      });
    }
  }
  
  function handleFileUpload(files, obj) {
    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].name;
        var type = fileName.split('.');
        if (type[type.length - 1].toLowerCase() != 'csv') {
            alert('csvではないファイルが含まれています。');
            return false;
        }        
    }
    for (var i = 0; i < files.length; i++) {
      var fd = new FormData();
      fd.append('file', files[i]);
      var status = new createStatusbar(obj); //Using this we can set progress.
      status.setFileNameSize(files[i].name, files[i].size);
      sendFileToServer(fd, status);
    }
  }
  $(document).ready(function () {
    var obj = $("#uploadCsv");
    obj.on('dragenter', function (e) {
      e.stopPropagation();
      e.preventDefault();
    });
    obj.on('dragover', function (e) {
      e.stopPropagation();
      e.preventDefault();
    });
    obj.on('drop', function (e) {
      e.preventDefault();
      var files = e.originalEvent.dataTransfer.files;
      //We need to send dropped files to Server
      handleFileUpload(files, obj);
    });
    $(document).on('dragenter', function (e) {
      e.stopPropagation();
      e.preventDefault();
    });
    $(document).on('dragover', function (e) {
      e.stopPropagation();
      e.preventDefault();
    });
    $(document).on('drop', function (e) {
      e.stopPropagation();
      e.preventDefault();
    });
  });


//モーダルウィンドウを出現させるクリックイベント
function openMessageModal() {

    //キーボード操作などにより、オーバーレイが多重起動するのを防止する
    $( this ).blur();  //ボタンからフォーカスを外す
    if( $( "#modal-overlay" )[0] ) return false;       //新しくモーダルウィンドウを起動しない (防止策1)

    //オーバーレイを出現させる
    $( "body" ).append( '<div id="modal-overlay"></div>' );
    $( "#modal-overlay" ).fadeIn( "slow" );

    //コンテンツをセンタリングする
    centeringMessageModalSyncer();

    //コンテンツをフェードインする
    $( "#modal-message-content" ).fadeIn( "slow" );

    //[#modal-overlay]、または[#modal-close]をクリックしたら…
    $( "#modal-overlay,#modal-close" ).unbind().click( function(){

        //[#modal-content]と[#modal-overlay]をフェードアウトした後に…
        $( "#modal-message-content,#modal-overlay" ).fadeOut( "slow" , function(){

            //[#modal-overlay]を削除する
            $('#modal-overlay').remove();

        });
    });
};
//リサイズされたら、センタリングをする関数[centeringModalSyncer()]を実行する
$( window ).resize( centeringMessageModalSyncer );

//センタリングを実行する関数
function centeringMessageModalSyncer() {

    //画面(ウィンドウ)の幅、高さを取得
    var w = $( window ).width();
    var h = $( window ).height();

    // コンテンツ(#modal-content)の幅、高さを取得
    var cw = $( "#modal-message-content" ).outerWidth();
    var ch = $( "#modal-message-content" ).outerHeight();

    //センタリングを実行する
    $( "#modal-message-content" ).css( {"left": ((w - cw)/2) + "px","top": ((h - ch)/2) + "px"} );
};

  

