@extends('frontend3')

@section('content')
    @php
        $provincedt = null;
        $warddt = null;
        $districtdt = null;
        $addressdt = null;
        $lat = null;
        $lng = null;
            if(session()->has('data') &&  !str_contains(request()->fullUrl(), 'tim-ban/cap-nhat'))
        {

            $data = session()->get('data');

        if(isset($data['province'])) {
            $provincedt = $data['province'];
            }
            if(isset($data['ward'])) {
            $warddt= $data['ward'];
            }
            if(isset($data['lat'])) {
            $lat= $data['lat'];
            }
             if(isset($data['lng'])) {
            $lng= $data['lng'];
            }
            if(isset($data['district'])) {
            $districtdt = $data['district'];
            }

            if(isset($data['address'])) {
            $addressdt = $data['address'];
            }
        }
    else {

    if(str_contains(request()->fullUrl(), 'tim-ban/cap-nhat'))
    {
        if(isset($room))
        {
             $provincedt = $room->province;
             $warddt = $room->ward;
             $districtdt = $room->district;
             $addressdt = $room->address;
             $lat = $room->lat;
             $lng = $room->lng;

        }
        }
    }
    @endphp
    <div id="siteContainer">



        <form role="form" id="form-add-news">
            <!-- site content -->
            <div id="siteContent" class="site-content">
                <div class="container mt-12 mb-48 col-md-8" style="float: none;">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12 mb-12">
                            <div class="add-post__single-info-section ht-depth-1 mb-12">
                                <div class="section-header">
                                    <div class="flex flex-ai-center">
                                        <div class="flex-item flex-item-tw">
                                            <div class="section-header__icon"><img src="http://via.placeholder.com/20x20"
                                                                                   width="20" height="20" alt=""></div>
                                        </div>
                                        <div class="flex-item flex-item-dw">
                                            <h3 class="section-header__title">Địa chỉ nhà trọ</h3>
                                        </div>
                                    </div>
                                </div>
                                <div class="section-content">
                                    <div class="row">
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4">
                                                    <div class="filter-label-wrap">
                                                        <label>Tên chủ trọ</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8 more-pr">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">

                                                            <input type="text" class="form-control" placeholder="Nhập tên" value="" name="owner_name" id="owner_name">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4 more-pl">
                                                    <div class="filter-label-wrap">
                                                        <label>SĐT chủ trọ</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">

                                                            <input type="text" class="form-control" placeholder="Nhập SĐT" value="" name="owner_phone" id="owner_phone">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <hr>
                                    <div class="row">
                                        <div class="col-xs-12 col-sm-4">
                                            <div class="form-group">
                                                <select class="form-control select2-form-control" id="province2"
                                                        name="province">
                                                    <option value="" selected disabled>Tỉnh / Thành phố</option>
                                                    @php $provinces = \App\Components\Functions::getProvinces(); @endphp

                                                    @foreach($provinces as $province)
                                                        <option data-lat="{{ $province->lat }}"
                                                                data-lng="{{ $province->lng }}"
                                                                @if($province->provinceid == $provincedt) selected=""
                                                                @endif value="{{ $province->provinceid }}">{{ $province->name }}</option>
                                                    @endforeach

                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-xs-12 col-sm-4">
                                            <div class="form-group">
                                                <select class="form-control select2-form-control" id="district2"
                                                        name="district">

                                                    @php if(!empty($provincedt)) {
                            $districts = DB::table('district')->where('provinceid', $provincedt)->get();
                        } else {
                            $districts = null;
                        }@endphp

                                                    @if(!empty($districts))
                                                        <option value="" selected disabled>Quận / Huyện</option>
                                                        @foreach($districts as $district)
                                                            <option @if($district->districtid == $districtdt) selected=""
                                                                    @endif value="{{ $district->districtid }}">{{ $district->name }}</option>
                                                        @endforeach
                                                    @else
                                                        <option value="" selected disabled>Quận / Huyện</option>
                                                    @endif
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-xs-12 col-sm-4">
                                            <div class="form-group">
                                                <select class="form-control select2-form-control" id="ward2" name="ward">

                                                    @php if(!empty($districtdt)) {
                            $wards = DB::table('ward')->where('districtid', $districtdt)->get();
                        } else {
                            $wards = null;
                        }@endphp

                                                    @if(!empty($wards))

                                                        <option value="" selected disabled>Xã / Phường</option>
                                                        @foreach($wards as $ward)
                                                            <option @if($ward->wardid == $warddt) selected=""
                                                                    @endif value="{{ $ward->wardid }}">{{ $ward->name }}</option>
                                                        @endforeach
                                                    @else
                                                        <option value="" selected disabled>Xã / Phường</option>
                                                    @endif


                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group mb-0">
                                <textarea class="form-control autosize-form-control" rows="2" name="address"
                                          value="{{ $addressdt }}" id="query"
                                          placeholder="Nhập địa chỉ chi tiết: số nhà, tên đường">{{ nl2br($addressdt) }}</textarea>
                                    </div>
                                    <input type="hidden" name="lat" id="query_lat" value="{{ $lat }}">
                                    <input type="hidden" name="lng" id="query_lng" value="{{ $lng }}">
                                    <hr>
                                    <div id="map" style="height: 350px; width: 100%">

                                    </div>
                                </div>
                            </div>
                            <div class="add-post__single-info-section ht-depth-1 mb-12">
                                <div class="section-header">
                                    <div class="flex flex-ai-center">
                                        <div class="flex-item flex-item-tw">
                                            <div class="section-header__icon"><img src="http://via.placeholder.com/20x20"
                                                                                   width="20" height="20" alt=""></div>
                                        </div>
                                        <div class="flex-item flex-item-dw">
                                            <h3 class="section-header__title">Mô tả</h3>
                                            <div class="section-header__subtitle">Hãy mô tả chi tiết nhà của bạn</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="section-content">
                                    <div class="col-xs-12">
                                        <div class="row">
                                            <div class="col-xs-2">
                                                <div class="filter-label-wrap">
                                                    <label>Tiêu Đề</label>
                                                </div>
                                            </div>
                                            <div class="col-md-10">
                                                <div class="form-group">
                                                    <div class="input-group col-md-10 col-xs-10">
                                                        <input id="title" name="title" type="text" class="form-control spinner col-md-8"
                                                               placeholder="Điền tiêu đề để thu hút nhiều lượt xem hơn">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                    <textarea id="description" name="description" rows="10" class="form-control autosize-form-control"
                                              placeholder="Mô tả chi tiết."></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="add-post__single-info-section ht-depth-1 mb-12">
                                <div class="section-header">
                                    <div class="flex flex-ai-center">
                                        <div class="flex-item flex-item-tw">
                                            <div class="section-header__icon"><img src="http://via.placeholder.com/20x20"
                                                                                   width="20" height="20" alt=""></div>
                                        </div>
                                        <div class="flex-item flex-item-dw">
                                            <h3 class="section-header__title">Ảnh phòng</h3>
                                            <div class="section-header__subtitle">Ít nhất 01 ảnh. Để được nhiều người quan
                                                tâm, hãy chụp ảnh ở mỗi góc của căn phòng và đảm bảo chất lượng ảnh đủ tốt
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="section-content">
                                    <div class="post-uploaded-images form-group clearfix mb-24" id="uploaded-images">
                                        <label class="single-uploaded-image cs-pt" id="form-upload">
                                            <input name="images[]" type="file" class="hidden" id="image-input2" multiple>
                                            <div class="image-wrap ht-rectangle ratio-11">
                                                <div class="ht-inner ht-fit-img">
                                                    <i class="ion-android-add fz-40 color-grey-500"></i>
                                                </div>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="add-post__single-info-section ht-depth-1 mb-12">
                                <div class="section-header">
                                    <div class="flex flex-ai-center">
                                        <div class="flex-item flex-item-tw">
                                            <div class="section-header__icon"><img src="http://via.placeholder.com/20x20"
                                                                                   width="20" height="20" alt=""></div>
                                        </div>
                                        <div class="flex-item flex-item-dw">
                                            <h3 class="section-header__title">Giá phòng & Ngày chuyển</h3>
                                        </div>
                                    </div>
                                </div>

                                <div class="section-content">
                                    <div class="row">
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4">
                                                    <div class="filter-label-wrap">
                                                        <label>Diện tích</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8 more-pr">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">
                                                            <input type="number" step="0.1" class="form-control" value="" name="size"
                                                                   placeholder="Điền diện tích" id="size">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4 more-pl">
                                                    <div class="filter-label-wrap">
                                                        <label>Ngày chuyển</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">
                                                            <input id="date_available" name="date_available" type="text" class="form-control datepicker-form-control"
                                                                   placeholder="Chọn ngày có thể chuyến tới">
                                                            <div class="input-group-addon"><i
                                                                        class="ion-android-calendar"></i></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4">
                                                    <div class="filter-label-wrap">
                                                        <label>Tiền phòng</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8 more-pr">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">
                                                            <input id="price" name="price" type="text" class="form-control"
                                                                   placeholder="Điền số tiền">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-xs-12 col-sm-6">
                                            <div class="row">
                                                <div class="col-xs-4 more-pl">
                                                    <div class="filter-label-wrap">
                                                        <label>Đặt cọc</label>
                                                    </div>
                                                </div>
                                                <div class="col-xs-8">
                                                    <div class="form-group">
                                                        <div class="input-group col-md-12">
                                                            <input id="deposit" name="deposit" type="text" class="form-control"
                                                                   placeholder="Điền số tiền">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <div class="row">

                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                            <div class="add-post__single-info-section ht-depth-1 mb-12">
                                <div class="section-header">
                                    <div class="flex flex-ai-center">
                                        <div class="flex-item flex-item-tw">
                                            <div class="section-header__icon"><img src="http://via.placeholder.com/20x20"
                                                                                   width="20" height="20" alt=""></div>
                                        </div>
                                        <div class="flex-item flex-item-dw">
                                            <h3 class="section-header__title">Tiện ích & Quy định</h3>
                                        </div>
                                    </div>
                                </div>
                                <div class="section-content amenitie-items">
                                    @if(isset($amenities))
                                        <div class="row">
                                            <div class="col-xs-4 col-sm-3 col-md-2">
                                                <div class="filter-label-wrap">
                                                    <label>Tiện ích</label>
                                                </div>
                                            </div>
                                            <div class="col-xs-8 col-sm-9 col-md-10">
                                                <div class="form-group">
                                                    <div class="col-xs-12 col-sm-12">
                                                        <div class="form-group">
                                                            @foreach($amenities as $amenity)
                                                                @if($amenity->type ==0 )
                                                                    <div class="col-xs-3 col-sm-3">
                                                                        <div class="checkbox checkbox--customized"><label><input
                                                                                        type="checkbox" class="amenitie-item" value="{{$amenity->id}}"><span></span>{{$amenity->name}}</label>
                                                                        </div>
                                                                    </div>
                                                                @endif
                                                            @endforeach
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="row">
                                            <div class="col-xs-4 col-sm-3 col-md-2">
                                                <div class="filter-label-wrap">
                                                    <label>Quy định</label>
                                                </div>
                                            </div>
                                            <div class="col-xs-8 col-sm-9 col-md-10">
                                                <div class="form-group">
                                                    <div class="col-xs-12 col-sm-12">
                                                        <div class="form-group">
                                                            @foreach($amenities as $policie)
                                                                @if($policie->type ==1 )
                                                                    <div class="col-xs-3 col-sm-3">
                                                                        <div class="checkbox checkbox--customized"><label><input
                                                                                        type="checkbox" class="amenitie-item" value="{{$policie->id}}"><span></span>{{$policie->name}}</label>
                                                                        </div>
                                                                    </div>
                                                                @endif
                                                            @endforeach
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endif
                                </div>
                            </div>


                            <div class="text-right mt-24">
                                <button id="add_news" class="btn ht-btn-primary px-24">Đăng tin ngay</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- END site content -->
        </form>
    </div>

@endsection

@push('scripts')
    <script src="/assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/2.1.2/jquery.scrollTo.min.js"></script>
    <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCydLs7dhJPuozABFQjJO-uk1PITW18oo8&libraries=places&region=vi&language=vi&sensor=false"></script>
    <script type="text/javascript" src="/frontend/scripts/infobox.min.js"></script>
    <script type="text/javascript" src="/frontend/scripts/markerclusterer.js"></script>

    <script>
        $('#add_news').click(function () {
            //variable
            var owner_name = $('#owner_name').val();
            var owner_phone = $('#owner_phone').val();
            var province = $('#province2').val();
            var district = $('#district2').val();
            var ward = $('#ward2').val();
            var address = $('#query').val();
            var title = $('#title').val();
            var description = $('#description').val();
            var input =$("#image-input2")[0];

            var images = [];
            var amenities = [];
            $(".amenitie-items .amenitie-item:checked").each(function () {
                amenities.push($(this).val());
            });


            // if (input[0].files) {
            //
            //     for (i = 0; i < input[0].files.length; i++) {
            //         if (input[0].files[i]) {
            //             var image = input[0].files[i].name;
            //             images.push(image)
            //         }
            //     }
            // }



            var size = $('#size').val();
            var price = $('#price').val();
            var deposit = $('#deposit').val();
            var date_available = $('#date_available').val();

            var form_data = new FormData();

            if (input.files) {
                for (i = 0; i < input.files.length; i++) {

                    if (input.files[i]) {

                        var form_data = new FormData();
                        form_data.append('image', input.files[i]);
                    }
                }
            }

            form_data.append('owner_name',owner_name);
            form_data.append('owner_phone',owner_phone);
            form_data.append('province',province);
            form_data.append('district',district);
            form_data.append('ward', ward);
            form_data.append('address',address);
            form_data.append('title',title);
            form_data.append('description',description);
            //form_data.append('images', JSON.stringify(images));
            form_data.append('size', size);
            form_data.append('price',price);
            form_data.append('deposit',deposit);
            form_data.append('date_available',date_available);
            form_data.append('amenities',JSON.stringify(amenities));

            var formStatus = $('#form-add-news').validate({
                errorElement: "span",
                errorClass: "help-block help-block-error",
                highlight: function (e) {
                    $(e).closest(".form-group").addClass("has-error");
                },
                unhighlight: function (e) {
                    $(e).closest(".form-group").removeClass("has-error")
                },
                success: function (e) {
                    $(e).closest(".form-group").removeClass("has-error")
                },
                rules: {
                    // 'hostel_id': "required",
                    'owner_name': "required",
                    //  'amenities[]': "required",
                    'owner_phone': {
                        required: true,
                    },
                    'title': {
                        required: true,
                        maxlength: 100,
                    },
                    'description': {
                        required: true,
                        minlength: 100,
                    },
                    'images': {
                        required: true,
                    },
                    'deposit': {
                        required: true,
                    },
                    'size': {
                        required: true,
                    },
                    'price': {
                        required: true,
                    },
                    'date_available': {
                        required: true,
                    }
                },
                messages: {
                    //  'hostel_id': "Không được bỏ trống nhà trọ",
                    'owner_name': "Không được bỏ trống tên chủ trọ",
                    'owner_phone': "Không được bỏ trống số điện thoại chủ trọ",
                    'title':{
                        required: "Không được bỏ trống tiêu đề",
                        maxlength: "Tiêu đề không được quá 100 kí tự",
                    },
                    'description': {
                        required: "Không được bỏ trống mô tả",
                        minlength: "Mô tả phải lớn hơn 100 kí tự",
                    },

                    'deposit': "Không được bỏ trống tiền cọc",
                    'size': "Không được bỏ trống diện tích",
                    'price': "Không được bỏ trống giá",
                    'date_available': "Không được bỏ trống ngày nhận phòng",
                    // 'amenities[]': "Không được bỏ trống tiện ích"
                }
            }).form();
            if(formStatus){
                $.ajax({
                    url: '{{ route('dangtin.create') }}',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    type: 'post',
                    dataType: 'json',
                    data: form_data,
                    processData: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    cache: false,
                    beforeSend: function () {
                        $('#form-add-news').addClass('ht-on-loading');
                    },
                    success: function (response) {
                        console.log(response);
                        $('#form-add-news').removeClass('ht-on-loading');
                        if (response.status == 1) {
                            swal('Thành công', 'Thêm tin mới thành công', 'success');
                        } else {
                            swal('Thông báo', response.message, 'warning');
                        }
                    },
                    error: function (error) {
                    }
                })
            }



        })
    </script>

    <script>
        //XỬ LÝ NGÀY THÁNG VÀO PHÒNG
        $('.datepicker').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true
        });

        $('#price,#deposit').keyup(function (event) {

            // skip for arrow keys
            if (event.which >= 37 && event.which <= 40)
                return;

            // format number
            $(this).val(function (index, value) {
                return value
                    .replace(/\D/g, "")
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                    ;
            });
        });

    </script>
    <script>
        // XỬ LÝ ĐỊA CHỈ
        $(document).on('change', '#province2', function (e) {
            var lat = $('option:selected', this).attr('data-lat');
            var lng = $('option:selected', this).attr('data-lng');
            $.ajax({
                url: '{{ url('get-sub-location') }}',
                type: 'get',
                data: {
                    'id': $(this).val(),
                    'type': 'province',
                },
                dataType: 'html',
                success: function (response) {
                    $('#district2').html(response);
                    $('#ward2').html('');
                }
            });
        });

        $(document).on('change', '#district2', function (e) {
            $.ajax({
                url: '{{ url('get-sub-location') }}',
                type: 'get',
                data: {
                    'id': $(this).val(),
                    'type': 'district'
                },
                dataType: 'html',
                success: function (response) {
                    $('#ward2').html(response);

                }
            });
        });
    </script>

    <script>
        //XỬ LÝ GOOGLE MAPS
        $(document).ready(function () {
            //+++++++++++++++++++++++++google map API+++++++++++++++++++
            var geocoder = new google.maps.Geocoder();
            var infowindow = new google.maps.InfoWindow();
            var map;
            function initMap(position){
                var myLatLng = {lat: 21.028511, lng: 105.804817};

                map = new google.maps.Map(document.getElementById('map'), {
                    center: myLatLng,
                    zoom: 15
                });

                infoWindow = new google.maps.InfoWindow;

                //Thêm maker vào bản đồ/////////
                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    title: 'Vị trí của bạn.'
                });


                var input2 = document.getElementById('query');
                var searchBox2 = new google.maps.places.SearchBox(input2);
                //   map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                // Bias the SearchBox results towards current map's viewport.
                google.maps.event.addListener(searchBox2, 'places_changed', function () {
                    searchBox2.set('map', null);
                    var places = searchBox2.getPlaces();

                    var bounds = new google.maps.LatLngBounds();

                    var i, place;
                    for (i = 0; place = places[i]; i++) {
                        (function (place) {

                            marker.setPosition(place.geometry.location);
                            infowindow.setContent(place.formatted_address);
                            infowindow.open(map, marker);

                            $('#query_lat').val(place.geometry.location.lat());
                            $('#query_lng').val(place.geometry.location.lng());

                            google.maps.event.addListener(marker, 'map_changed', function () {
                                if (!this.getMap()) {
                                    this.unbindAll();
                                }
                            });
                            bounds.extend(place.geometry.location);


                        }(place));

                    }
                    map.fitBounds(bounds);
                    searchBox2.set('map', map);
                    map.setZoom(Math.min(map.getZoom(), 12));

                });


                google.maps.event.addListener(marker, 'dragend', function () {

                    geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {

                                $('#query_lat').val(marker.getPosition().lat());
                                $('#query_lng').val(marker.getPosition().lng());
                                infowindow.setContent(results[0].formatted_address);
                                infowindow.open(map, marker);
                            }
                        }
                    });
                });
                // geocoder = new google.maps.Geocoder();
                // var province = '';
                // var district = '';
                // var ward = '';
                // $('#province2').change(function () {
                //     province = $('#province2 option:selected').text();
                // })
                // $('#district2').change(function () {
                //     district = $('#district2 option:selected').text();
                // })
                // $('#ward2').change(function () {
                //     ward = $('#ward2 option:selected').text();
                // })
                //
                // $('#query').keyup(function(){
                //     var query = $('#query').val();
                //         var address = query+', '+ward+', '+district+', '+province;
                //     codeAddress(address);
                //
                // })





                // Try HTML5 geolocation.
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function(position) {
                        var pos = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude
                        };

                        //Thêm maker vào bản đồ/////////
                        var marker = new google.maps.Marker({
                            position: pos,
                            map: map,
                            title: 'Vị trí của bạn.',
                            draggable: true
                        });

                        infoWindow.setPosition(pos);
                        infoWindow.open(map, marker);
                        infoWindow.setContent('Vị trí của bạn');
                        map.setCenter(pos);
                    }, function() {
                        handleLocationError(true, infoWindow, map.getCenter());
                    });
                } else {
                    // Browser doesn't support Geolocation
                    handleLocationError(false, infoWindow, map.getCenter());
                }

            }

            function handleLocationError(browserHasGeolocation, infoWindow, pos) {
                infoWindow.setPosition(pos);
                infoWindow.setContent(browserHasGeolocation ?
                    'Error: The Geolocation service failed.' :
                    'Error: Your browser doesn\'t support geolocation.');
                infoWindow.open(map);
            }

            //hiển thị maps theo địa chỉ
            function codeAddress(address)
            {
                geocoder.geocode( {address:address}, function(results, status)
                {
                    if (status == google.maps.GeocoderStatus.OK)
                    {
                        map.setCenter(results[0].geometry.location);//center the map over the result
                        //place a marker at the location
                        var marker = new google.maps.Marker(
                            {
                                map: map,
                                position: results[0].geometry.location
                            });
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }
            google.maps.event.addDomListener(window, 'load', initMap);
        })


    </script>

    <script>
        //XỬ LÝ UPLOAD ẢNH
        function readURL2(input) {
            if (input.files) {

                for (i = 0; i < input.files.length; i++) {

                    if (input.files[i]) {
                        var reader = new FileReader();

                        reader.onload = function (e) {
                            $('<div class="single-uploaded-image">' +
                                '<div class="image-wrap ht-rectangle ratio-11">' +
                                '<div class="ht-inner">' +
                                '<img src="' + e.target.result + '" alt=""' +
                                'class="image-main">' +
                                '</div>' +
                                '</div>' +
                                '<a href="#" class="image-delete-btn"><i class="ion-android-close"></i></a>' +
                                '</div>').insertBefore('#form-upload');
                        }


                        reader.readAsDataURL(input.files[i]);

                        var form_data = new FormData();
                        form_data.append('image', input.files[i]);

                        $.ajax({
                            url: '{{ url('dang-tin/upload-image-room-need-more') }}',
                            type: 'post',
                            dataType: 'json',
                            data: form_data,
                            processData: false,
                            contentType: false,
                            enctype: 'multipart/form-data',
                            cache: false,
                            success: function (response) {
                            },
                            error: function (error) {

                            }
                        });
                    }
                }
            }
        }
        $("#image-input2").change(function () {
            readURL2(this);
        });

        $(document).on('click', '.image-delete-btn', function (e) {
            e.preventDefault();
            var that = this;

            bootbox.confirm({
                message: "Bạn có chắc chắn muốn xóa",
                buttons: {
                    confirm: {
                        label: 'Có',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: 'Không',
                        className: 'btn-danger'
                    }
                },


                callback: function (result) {
                    if (result == true) {
                        var name = $(that).attr('data-name');

                        $.ajax({
                            url: '{{ url('dang-tin/update-images-need-more-upload') }}',
                            data: {
                                image: name
                            },
                            type: 'post',
                            success: function (response) {
                                if (response.status == 1) {
                                    $(that).parent().remove();
                                }
                            }
                        });

                    }
                }
            });


        });
    </script>
    {{--<script>--}}
        {{--////ĐĂNG TIN NGAY--}}
        {{--$('#add_news').click(function () {--}}
            {{--//variable--}}
            {{--var owner_name = $('#owner_name').val();--}}
            {{--var owner_phone = $('#owner_phone').val();--}}
            {{--var province = $('#province2').val();--}}
            {{--var district = $('#district2').val();--}}
            {{--var ward = $('#ward2').val();--}}
            {{--var address = $('#query').val();--}}
            {{--var title = $('#title').val();--}}
            {{--var description = $('#description').val();--}}
            {{--var input =$("#image-input2");--}}
            {{--console.log(input.files[0]);--}}
            {{--var images = [];--}}
            {{--var amenities = [];--}}
            {{--$(".amenitie-items .amenitie-item:checked").each(function () {--}}
                {{--amenities.push($(this).val());--}}
            {{--});--}}


            {{--// if (input[0].files) {--}}
            {{--//--}}
            {{--//     for (i = 0; i < input[0].files.length; i++) {--}}
            {{--//         if (input[0].files[i]) {--}}
            {{--//             var image = input[0].files[i].name;--}}
            {{--//             images.push(image)--}}
            {{--//         }--}}
            {{--//     }--}}
            {{--// }--}}

            {{--if (input.files) {--}}

                {{--for (i = 0; i < input.files.length; i++) {--}}

                    {{--if (input.files[i]) {--}}
                        {{--var form_data = new FormData();--}}
                        {{--form_data.append('image[]', input.files[i]);--}}
                    {{--}--}}
                {{--}--}}
            {{--}--}}

            {{--var size = $('#size').val();--}}
            {{--var price = $('#price').val();--}}
            {{--var deposit = $('#deposit').val();--}}
            {{--var date_available = $('#date_available').val();--}}

            {{--var form_data = new FormData();--}}
            {{--form_data.append('owner_name',owner_name);--}}
            {{--form_data.append('owner_phone',owner_phone);--}}
            {{--form_data.append('province',province);--}}
            {{--form_data.append('district',district);--}}
            {{--form_data.append('ward', ward);--}}
            {{--form_data.append('address',address);--}}
            {{--form_data.append('title',title);--}}
            {{--form_data.append('description',description);--}}
            {{--form_data.append('images', JSON.stringify(images));--}}
            {{--form_data.append('size', size);--}}
            {{--form_data.append('price',price);--}}
            {{--form_data.append('deposit',deposit);--}}
            {{--form_data.append('date_available',date_available);--}}
            {{--form_data.append('amenities',JSON.stringify(amenities));--}}


            {{--var formStatus = $('#form-add-news').validate({--}}
                {{--errorElement: "span",--}}
                {{--errorClass: "help-block help-block-error",--}}
                {{--highlight: function (e) {--}}
                    {{--$(e).closest(".form-group").addClass("has-error");--}}
                {{--},--}}
                {{--unhighlight: function (e) {--}}
                    {{--$(e).closest(".form-group").removeClass("has-error")--}}
                {{--},--}}
                {{--success: function (e) {--}}
                    {{--$(e).closest(".form-group").removeClass("has-error")--}}
                {{--},--}}
                {{--rules: {--}}
                    {{--// 'hostel_id': "required",--}}
                    {{--'owner_name': "required",--}}
                    {{--//  'amenities[]': "required",--}}
                    {{--'owner_phone': {--}}
                        {{--required: true,--}}
                    {{--},--}}
                    {{--'title': {--}}
                        {{--required: true,--}}
                        {{--maxlength: 100,--}}
                    {{--},--}}
                    {{--'description': {--}}
                        {{--required: true,--}}
                        {{--minlength: 100,--}}
                    {{--},--}}
                    {{--'images': {--}}
                        {{--required: true,--}}
                    {{--},--}}
                    {{--'deposit': {--}}
                        {{--required: true,--}}
                    {{--},--}}
                    {{--'size': {--}}
                        {{--required: true,--}}
                    {{--},--}}
                    {{--'price': {--}}
                        {{--required: true,--}}
                    {{--},--}}
                    {{--'date_available': {--}}
                        {{--required: true,--}}
                    {{--}--}}
                {{--},--}}
                {{--messages: {--}}
                    {{--//  'hostel_id': "Không được bỏ trống nhà trọ",--}}
                    {{--'owner_name': "Không được bỏ trống tên chủ trọ",--}}
                    {{--'owner_phone': "Không được bỏ trống số điện thoại chủ trọ",--}}
                    {{--'title':{--}}
                        {{--required: "Không được bỏ trống tiêu đề",--}}
                        {{--maxlength: "Tiêu đề không được quá 100 kí tự",--}}
                    {{--},--}}
                    {{--'description': {--}}
                        {{--required: "Không được bỏ trống mô tả",--}}
                        {{--minlength: "Mô tả phải lớn hơn 100 kí tự",--}}
                    {{--},--}}

                    {{--'deposit': "Không được bỏ trống tiền cọc",--}}
                    {{--'size': "Không được bỏ trống diện tích",--}}
                    {{--'price': "Không được bỏ trống giá",--}}
                    {{--'date_available': "Không được bỏ trống ngày nhận phòng",--}}
                    {{--// 'amenities[]': "Không được bỏ trống tiện ích"--}}
                {{--}--}}
            {{--}).form();--}}
            {{--if(formStatus){--}}
                {{--console.log(1);--}}
                {{--$.ajax({--}}
                    {{--url: '{{ route('dangtin.create') }}',--}}
                    {{--headers: {--}}
                        {{--'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')--}}
                    {{--},--}}
                    {{--type: 'post',--}}
                    {{--dataType: 'json',--}}
                    {{--data: form_data,--}}
                    {{--processData: false,--}}
                    {{--contentType: false,--}}
                    {{--enctype: 'multipart/form-data',--}}
                    {{--cache: false,--}}
                    {{--beforeSend: function () {--}}
                        {{--$('#form-add-news').addClass('ht-on-loading');--}}
                    {{--},--}}
                    {{--success: function (response) {--}}
                        {{--$('#form-add-news').removeClass('ht-on-loading');--}}
                        {{--if (response.status == 1) {--}}
                            {{--swal('Thành công', 'Thêm tin mới thành công', 'success');--}}
                        {{--} else {--}}
                            {{--swal('Thông báo', response.message, 'warning');--}}
                        {{--}--}}
                    {{--},--}}
                    {{--error: function (error) {--}}
                    {{--}--}}
                {{--})--}}
            {{--}--}}

        {{--})--}}
    {{--</script>--}}
@endpush