<script src="https://maps.googleapis.com/maps/api/js?key=<?= $this->config->item('api_map_key') ?>&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
    function validateForm() {
        var jumlah = document.forms["form"]["jarak"].value;
        var angka = /^[0-9]+$/;

        if (!jumlah.match(angka)) {
            alert("Inputan harus angka!");
            //from.no_hp.focus();
            return false;
        }
    }

	$(function() {
		$('#cabang').select2({
			placeholder: 'Pilih Cabang',
			ajax: {
			  // type: 'POST',
                url: '<?= route("dropdown.cabang")  ?>',
                dataType: 'json',
                delay: 250,
                processResults: function (data) {
                return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
		});

        $(document).on('click','#btn_new_input', function(){
                $('#form_input input[type=text]').prop("disabled",false);
                $("#form_input input[type=text]").val('');

                $('#cabang').prop("disabled",false);
                $("#cabang").val('').trigger('change');

                $('.btn_save').show();
                $('#btn_new_input').hide();
                $('#message').hide();
            });
	});

    $(document).on("click",".btn_save",function(e){
        e.preventDefault();
        $('#message').html("");
        var loading = Ladda.create(this);

        if(!$("#kantor").val()){
            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama Lokasi belum diisi</font>");
            $("#kantor").focus();
            return false;
        }

        <?php
            if(in_array($this->session->userdata("level_user"),["1"]) || $this->session->userdata("multi_cabang") == true){
        ?>
                var id_cabang = $("#cabang").val();

                if(!$("#cabang").val()){
                    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama cabang belum dipilih</font>");
                    $('#cabang').focus();
                    return false;
                }
        <?php
            }else{
        ?>
                var id_cabang = '<?= $this->session->userdata("id_cabang") ?>';
        <?php
            }
        ?>
        if(!$("#lat").val()){
            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Latitude belum diiisi</font>");
            $('#lat').focus();
            return false;
        }else if(!$("#lng").val()){
            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Longitude belum diiisi</font>");
            $('#lng').focus();
            return false;
        }else if(!$("#jarak").val()){
            $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Radius belum diiisi</font>");
            $('#jarak').focus();
            return false;
        }

        loading.start();

        var param = 'kantor='+$("#kantor").val()+
                    '&cabang='+id_cabang+
                    '&flag='+$("#flag").val()+
                    '&lat='+$("#lat").val()+
                    '&lng='+$("#lng").val()+
                    '&jarak='+$("#jarak").val()+
                    '&id_lok='+$("#id_lok").val();

        $.ajax({
            type: 'POST',
            url: "<?= site_url('master/lokasi/update') ?>",
            data: param,
            dataType:'JSON',
            success: function(result) {
                if(result.success == true){
                    if(result.type == 'save'){
                        <?php
                            if(in_array($this->session->userdata("level_user"),["1"])){
                        ?>
                                $("#kantor, #cabang, #lat, #lng, #jarak").prop("disabled", true);
                        <?php
                            }else{
                        ?>
                                $("#kantor, #lat, #lng, #jarak").prop("disabled", true);
                        <?php
                            }
                        ?>
                        $('.btn_save').hide();
                        $('#btn_new_input').show();
                    }

                }
                loading.stop();
                $('#message').show();
                $('#message').html(result.message);
            },
            error:function(){
                loading.stop();
                $('#message').show();
                $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
            }
        });
    });
</script>
<div class="content-header">
    <div class="row align-items-center">
        <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
            <h3 class="content-header-title"><?= $judul ?></h3>
            <div class="row breadcrumbs-top">
                <div class="breadcrumb-wrapper col-12">
                    <ol class="breadcrumb">
                        </li>
                        <li class="breadcrumb-item"><a href="#">Master Data</a>
                        </li>
                        <li class="breadcrumb-item"><a href="#">Lokasi</a>
                        </li>
                        <li class="breadcrumb-item active"><?= $judul ?>
                        </li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div class="card-body">
            <fieldset class="gllpLatlonPicker">
                <div class="row">
                    <div class="col-md-9">
                        <div class="row">
                            <div class="col-md-12">
                                <label id="msg_maps"></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text" id="basic-addon1"><i class="fa fa-search"></i></span>
                                    </div>
                                    <input type="text" class="form-control gllpSearchField" placeholder="CARI LOKASI ANDA">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <input type="hidden" class="gllpLatitude" value="<?= $data->lat_asli ?>" />
                                <input type="hidden" class="gllpLongitude" value="<?= $data->long_asli ?>" />
                                <input type="hidden" class="gllpZoom" value="18" />
                                <div class="gllpMap" style="width:100%;height: 450px;">Google Maps</div>
                            </div>
                        </div>
                    </div>
                    <div id="form_input" class="col-lg-3">
                        <input type="hidden" id="id_lok" value="<?= $data->id_lokasi_kantor ?>">
                        <div class="form-group">
                            <label class="control-label" for="nama">Nama Lokasi <span class="text-danger">*</span></label>
                            <input type="text"  id="kantor" class="form-control input-xlarge" value="<?= $data->nama_kantor ?>">
                        </div>
                        <?php
                            if(in_array($this->session->userdata("level_user"),["1"]) || $this->session->userdata("multi_cabang") == true){
                        ?>
                                <div class="form-group">
                                    <label class="control-label" for="lat">Nama Cabang <span class="text-danger">*</span></label>
                                    <select type="text" id="cabang" class="form-control">
                                        <option value="<?= $data->id_cabang ?>" selected="selected"><?= $nama_cabang ?></option>
                                    </select>
                                </div>
                        <?php
                            }
                        ?>

                        <div class="form-group">
                            <label class="control-label" for="lat">Latitude <span class="text-danger">*</span></label>
                            <input type="text" id='lat' class="form-control gllpLatitude" onkeyup="this.value = this.value.replace(/[^0-9.-]/g, '')" value="<?= $data->lat_asli ?>">
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="lng">Longitude <span class="text-danger">*</span></label>
                            <input type="text" id='lng' class="form-control gllpLongitude" onkeyup="this.value = this.value.replace(/[^0-9.]/g, '')" value="<?= $data->long_asli ?>">
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="lat">Radius <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name='jarak' id='jarak' onkeyup="this.value = this.value.replace(/[^0-9.]/g, '')" value="<?= $data->jarak ?>">
                            <small class="form-control-feedback">*) radius dalam meter</small>
                            <input type="hidden" id="flag" value="<?= $data->flag ?>">
                        </div>
                        <div class="form-group">
                            <div class="input-control text-left">
                                <div id="message"></div>
                            </div>
                            <div class="input-control text-left">
                                <button class="btn btn-warning btn_save ladda-button" name='aksi' data-style="expand-left"><i class="fa fa-edit (alias)"></i> PERBARUI</button>
                                <a href="<?= site_url('master/lokasi') ?>" class="btn btn-secondary">KEMBALI</a>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>
        </div>
    </div>
</div>



<script type="text/javascript">
    (function($) {

        // for ie9 doesn't support debug console >>>
        if (!window.console)
            window.console = {};
        if (!window.console.log)
            window.console.log = function() {};

        $.fn.gMapsLatLonPicker = (function() {

            var _self = this;

            ///////////////////////////////////////////////////////////////////////////////////////////////
            // PARAMETERS (MODIFY THIS PART) //////////////////////////////////////////////////////////////
            _self.params = {
                defLat: 0,
                defLng: 0,
                defZoom: 7,
                queryLocationNameWhenLatLngChanges: true,
                queryElevationWhenLatLngChanges: true,
                mapOptions: {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl: false,
                    disableDoubleClickZoom: true,
                    zoomControlOptions: true,
                    streetViewControl: false,
                    // center: google.maps.LatLng(-6.990581698473311, 110.42295643957527)
                    center: google.maps.LatLng(-1.1686938,117.8632823)
                },
                strings: {
                    markerText: "Geser Penanda Ini ",
                    error_empty_field: '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Tidak dapat menemukan koordinat untuk tempat ini</font>',
                    error_no_results: '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Tidak dapat menemukan koordinat untuk tempat ini</font>'
                },
                displayError: function(message) {
                    $(".gllpLatlonPicker #msg_maps").html(message);
                    // alert(message);
                }
            };


            ///////////////////////////////////////////////////////////////////////////////////////////////
            // VARIABLES USED BY THE FUNCTION (DON'T MODIFY THIS PART) ////////////////////////////////////
            _self.vars = {
                ID: null,
                LATLNG: null,
                map: null,
                marker: null,
                geocoder: null
            };

            ///////////////////////////////////////////////////////////////////////////////////////////////
            // PRIVATE FUNCTIONS FOR MANIPULATING DATA ////////////////////////////////////////////////////
            var setPosition = function(position) {
                _self.vars.marker.setPosition(position);
                _self.vars.map.panTo(position);

                $(_self.vars.cssID + ".gllpZoom").val(_self.vars.map.getZoom());
                $(_self.vars.cssID + ".gllpLongitude").val(position.lng());
                $(_self.vars.cssID + ".gllpLatitude").val(position.lat());

                $(_self.vars.cssID).trigger("location_changed", $(_self.vars.cssID));

                if (_self.params.queryLocationNameWhenLatLngChanges) {
                    getLocationName(position);
                }
                if (_self.params.queryElevationWhenLatLngChanges) {
                    getElevation(position);
                }
            };

            // for reverse geocoding
            var getLocationName = function(position) {
                var latlng = new google.maps.LatLng(position.lat(), position.lng());
                _self.vars.geocoder.geocode({
                    'latLng': latlng
                }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK && results[1]) {
                        $(_self.vars.cssID + ".gllpLocationName").val(results[1].formatted_address);
                    } else {
                        $(_self.vars.cssID + ".gllpLocationName").val("");
                    }
                    $(_self.vars.cssID).trigger("location_name_changed", $(_self.vars.cssID));
                });
            };

            // for getting the elevation value for a position
            var getElevation = function(position) {
                var latlng = new google.maps.LatLng(position.lat(), position.lng());

                var locations = [latlng];

                var positionalRequest = {
                    'locations': locations
                };

                _self.vars.elevator.getElevationForLocations(positionalRequest, function(results, status) {
                    if (status == google.maps.ElevationStatus.OK) {
                        if (results[0]) {
                            $(_self.vars.cssID + ".gllpElevation").val(results[0].elevation.toFixed(3));
                        } else {
                            $(_self.vars.cssID + ".gllpElevation").val("");
                        }
                    } else {
                        $(_self.vars.cssID + ".gllpElevation").val("");
                    }
                    $(_self.vars.cssID).trigger("elevation_changed", $(_self.vars.cssID));
                });
            };

            // search function
            var performSearch = function(string, silent) {
                if (string == "") {
                    if (!silent) {
                        _self.params.displayError(_self.params.strings.error_empty_field);
                    }
                    return;
                }
                _self.vars.geocoder.geocode({
                        "address": string
                    },
                    function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            $(_self.vars.cssID + ".gllpZoom").val(13);
                            _self.vars.map.setZoom(parseInt($(_self.vars.cssID + ".gllpZoom").val()));
                            setPosition(results[0].geometry.location);
                        } else {
                            if (!silent) {
                                _self.params.displayError(_self.params.strings.error_no_results);
                            }
                        }
                    }
                );
            };

            ///////////////////////////////////////////////////////////////////////////////////////////////
            // PUBLIC FUNCTIONS  //////////////////////////////////////////////////////////////////////////
            var publicfunc = {
                // INITIALIZE MAP ON DIV //////////////////////////////////////////////////////////////////
                init: function(object) {

                    if (!$(object).attr("id")) {
                        if ($(object).attr("name")) {
                            $(object).attr("id", $(object).attr("name"));
                        } else {
                            $(object).attr("id", "_MAP_" + Math.ceil(Math.random() * 10000));
                        }
                    }

                    _self.vars.ID = $(object).attr("id");
                    _self.vars.cssID = "#" + _self.vars.ID + " ";

                    _self.params.defLat = $(_self.vars.cssID + ".gllpLatitude").val() ? $(_self.vars.cssID + ".gllpLatitude").val() : _self.params.defLat;
                    _self.params.defLng = $(_self.vars.cssID + ".gllpLongitude").val() ? $(_self.vars.cssID + ".gllpLongitude").val() : _self.params.defLng;
                    _self.params.defZoom = $(_self.vars.cssID + ".gllpZoom").val() ? parseInt($(_self.vars.cssID + ".gllpZoom").val()) : _self.params.defZoom;

                    _self.vars.LATLNG = new google.maps.LatLng(_self.params.defLat, _self.params.defLng);

                    _self.vars.MAPOPTIONS = _self.params.mapOptions;
                    _self.vars.MAPOPTIONS.zoom = _self.params.defZoom;
                    _self.vars.MAPOPTIONS.center = _self.vars.LATLNG;

                    _self.vars.map = new google.maps.Map($(_self.vars.cssID + ".gllpMap").get(0), _self.vars.MAPOPTIONS);
                    _self.vars.geocoder = new google.maps.Geocoder();
                    _self.vars.elevator = new google.maps.ElevationService();

                    // var goldStar = {
                    //     path: 'M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z',
                    //     fillColor: 'yellow',
                    //     fillOpacity: 0.8,
                    //     scale: 1,
                    //     strokeColor: 'gold',
                    //     strokeWeight: 14
                    // };

                    // var svgMarker = {
                    //     path: "M10.453 14.016l6.563-6.609-1.406-1.406-5.156 5.203-2.063-2.109-1.406 1.406zM12 2.016q2.906 0 4.945 2.039t2.039 4.945q0 1.453-0.727 3.328t-1.758 3.516-2.039 3.070-1.711 2.273l-0.75 0.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.906 2.039-4.945t4.945-2.039z",
                    //     fillColor: "blue",
                    //     fillOpacity: 0.6,
                    //     strokeWeight: 0,
                    //     rotation: 0,
                    //     scale: 2,
                    //     anchor: new google.maps.Point(15, 30),
                    // };

                    _self.vars.marker = new google.maps.Marker({
                        position: _self.vars.LATLNG,
                        // position: google.maps.LatLng(-6.990581698473311, 110.42295643957527),
                        map: _self.vars.map,
                        // icon: goldStar,
                        // icon: "https://your_domain.com/your_directory/your_image.jpg",
                        // icon: "https://www.pngkit.com/png/full/444-4449930_airport-map-marker-icon-clipart-computer-icons-8.png",
                        // icon:svgMarker,
                        title: _self.params.strings.markerText,
                        draggable: true
                    });



                    // Set position on doubleclick
                    google.maps.event.addListener(_self.vars.map, 'dblclick', function(event) {
                        setPosition(event.latLng);
                    });

                    // Set position on marker move
                    google.maps.event.addListener(_self.vars.marker, 'dragend', function(event) {
                        setPosition(_self.vars.marker.position);
                    });

                    // Set zoom feld's value when user changes zoom on the map
                    google.maps.event.addListener(_self.vars.map, 'zoom_changed', function(event) {
                        $(_self.vars.cssID + ".gllpZoom").val(_self.vars.map.getZoom());
                        $(_self.vars.cssID).trigger("location_changed", $(_self.vars.cssID));
                    });

                    // Update location and zoom values based on input field's value
                    $(_self.vars.cssID + ".gllpUpdateButton").bind("click", function() {
                        var lat = $(_self.vars.cssID + ".gllpLatitude").val();
                        var lng = $(_self.vars.cssID + ".gllpLongitude").val();
                        var latlng = new google.maps.LatLng(lat, lng);
                        _self.vars.map.setZoom(parseInt($(_self.vars.cssID + ".gllpZoom").val()));
                        setPosition(latlng);
                    });

                    // Search function by search button
                    // $(_self.vars.cssID + ".gllpSearchButton").bind("click", function() {
                    //     performSearch($(_self.vars.cssID + ".gllpSearchField").val(), false);
                    // });

                    $(_self.vars.cssID + ".gllpSearchField").bind("keypress", function(e) {
                        if(e.which == 13) {
                            performSearch($(_self.vars.cssID + ".gllpSearchField").val(), false);
                            $(".gllpLatlonPicker #msg_maps").html("");
                        }

                    });

                    // Search function by gllp_perform_search listener
                    $(document).bind("gllp_perform_search", function(event, object) {
                        performSearch($(object).attr('string'), true);
                    });

                    // Zoom function triggered by gllp_perform_zoom listener
                    $(document).bind("gllp_update_fields", function(event) {
                        var lat = $(_self.vars.cssID + ".gllpLatitude").val();
                        var lng = $(_self.vars.cssID + ".gllpLongitude").val();
                        var latlng = new google.maps.LatLng(lat, lng);
                        _self.vars.map.setZoom(parseInt($(_self.vars.cssID + ".gllpZoom").val()));
                        setPosition(latlng);
                    });
                },
                // EXPORT PARAMS TO EASILY MODIFY THEM ////////////////////////////////////////////////////
                params: _self.params

            };

            return publicfunc;
        });

        $(document).ready(function() {
            if (!$.gMapsLatLonPickerNoAutoInit) {
                $(".gllpLatlonPicker").each(function() {
                    $obj = $(document).gMapsLatLonPicker();
                    $obj.init($(this));
                });
            }
        });

        $(document).bind("location_changed", function(event, object) {
            console.log("changed: " + $(object).attr('id'));
        });

        $(document).ready(function() {
            var i = 1;

            var dropdown = <?php echo json_encode(form_dropdown('name[]', $dd_nama, $nama_selected, 'class="form-control name_list "')); ?>;

            $('#add').click(function() {
                i++;
                $('#dynamic_field').append('<tr id="row' + i + '" class="dynamic-added"><td>' + dropdown + '</td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
                $('#' + i).focus();
            });


            $(document).on('click', '.btn_remove', function() {
                var button_id = $(this).attr("id");
                $('#row' + button_id + '').remove();
            });
        });

        $(document).on('keypress',function(e) {
            if(e.which == 13) {
                // $('.gllpSearchButton').click();
                $('.gllpSearchField').click();
            }
        });

    }(jQuery));
</script>
