@push('head')
    <style>

	</style>
@endpush

<div class="modal fade" id="osmMap" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<!-- Modal Header -->
			<div class="modal-header" style="background: orange">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true" class="ion-android-close"></span></button>
				<h4 class="modal-title" id="myModalLabel" style="color: whitesmoke;">Donation For Siddhyog Sadhan Mandal</h4>
			</div>            <!-- Modal Body -->
			<div class="modal-body">
			   <div  class="map" id="map"></div>
			</div>
		</div>
	</div>
</div>
<div class='form-group peta {{$header_group_class}} {{ ($errors->first($name))?"has-error":"" }}'>
    <label class='control-label col-sm-2'>{{$form['label']}}
        @if($required)
            <span class='text-danger' title='{!! trans('crudbooster.this_field_is_required') !!}'>*</span>
        @endif
    </label>
	
    <div class="{{$col_width?:'col-sm-10'}}">
		

        <div class="input-group">
		
            <input type="hidden" class="form-control" id="{{$name}}" {{ ($readonly)?"readonly":"" }} {{ ($required)?"required":""}} value="{{$value}}"
                   name="{{$name}}">
            <input type="hidden" name="input-latitude-{{$name}}" id="input-latitude-{{$name}}" value="{{ ($form['latitude'])?$row->$form['latitude']:0 }}">
            <input type="hidden" name="input-longitude-{{$name}}" id="input-longitude-{{$name}}" value="{{ ($form['longitude'])?$row->$form['longitude']:0 }}">
			<span class="input-group-btn">
						        <button class="btn btn-primary" onclick="showMapModal{{$name}}()" type="button"><i
                                            class='fa fa-map-marker'></i>   Tandai Peta	</button>
						      </span>
			
        </div><!-- /input-group -->
		

        <div id='osmmaps-modal-{{$name}}' class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title"><i class='fa fa-search'></i> </h4>
                    </div>
                    <div class="modal-body">
						<div  class="map" id="map-{{$name}}"></div>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="setIt{{$name}}()" data-dismiss="modal">Selesai</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->


    </div>
</div>
@push('bottom')
    <script type="text/javascript">
        <?php $berhasil = false ?>
        var mode = '{{ $command }}'
        if(mode=="add"){
          initGeolocation()
        }
        
        function initGeolocation()
         {
            if( navigator.geolocation )
            {
               // Call getCurrentPosition with success and failure callbacks
               navigator.geolocation.getCurrentPosition( success, fail );
            }
            else
            {
               alert("Sorry, your browser does not support geolocation services.");
            }
         }
    
         function success(position)
         {
    
             document.getElementById('lon').value = position.coords.longitude;
             document.getElementById('lat').value = position.coords.latitude
             <?php $berhasil = true ?>
         }
    
         function fail()
         {
          <?php $berhasil = false ?>
            // Could not obtain location
         }

		var address_temp_{{$name}}, latitude_temp_{{$name}}, longitude_temp_{{$name}};

        function setIt{{$name}}() {
            console.log(address_temp_{{$name}});
            $('#{{$name}}').val(address_temp_{{$name}});
            $("#input-latitude-{{$name}}").val(latitude_temp_{{$name}});
            $("#input-longitude-{{$name}}").val(longitude_temp_{{$name}});
        }

        var is_init_map_{{$name}} = false;

        function showMapModal{{$name}}() {
            var api_key = "{{CRUDBooster::getSetting('google_api_key')}}";

            if (api_key == '') {
                alert('GOOGLE_API_KEY is missing, please set at setting !');
                return false;
            }

            $('#osmmaps-modal-{{$name}}').modal('show');
        }

        $('#osmmaps-modal-{{$name}}').on('shown.bs.modal', function () {
            if (is_init_map_{{$name}} == false) {
                console.log('Init Map {{$name}}');
                initMap{{$index}}();
                is_init_map_{{$name}} = true;
            }
        });
	
	
	  var map, newUser, users, mapquest, firstLoad, videofirst, layers, Me;

      firstLoad = true;
	  videofirst = true;

      //users = new L.FeatureGroup();
      users = new L.MarkerClusterGroup({spiderfyOnMaxZoom: true, showCoverageOnHover: false, zoomToBoundsOnClick: true});
      newUser = new L.LayerGroup();
	  Me = new L.LayerGroup();
	  
		function initMap{{$index}}() {
			  mapquest = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
				maxZoom: 18,
				attribution: 'Basemap tiles courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png">. Map data (c) <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> contributors, CC-BY-SA.'
			  });
			   //alert(<?php echo $row->lat ?: 0;?>);
			  layers = [mapquest, users, newUser];
			  map = new L.Map('map-{{$name}}', {
				@if($row->lat && $row->lon)
				center: {lat: <?php echo $row->lat ?: 0;?>, lng: <?php echo $row->lon ?: 0;?> },
				zoom: 18,
        @elseif($berhasil==true)		 
				center: new L.LatLng(document.getElementById('lat').value, document.getElementById('lon').value),
				zoom: 14,
				@else		 
				center: new L.LatLng(-3.440513, 114.83058),
				zoom: 14,
				@endif        
				
				layers: layers
			  });
			  
			  @if($row->lat && $row->lon)
				  var markerIcon = L.icon({
					iconUrl: '{{asset('/')}}<?php echo $row->icon; ?>',

					iconSize:     [80, 80], // size of the icon
					shadowSize:   [50, 64], // size of the shadow
					iconAnchor:   [40, 80], // point of the icon which will correspond to marker's location
					shadowAnchor: [4, 62],  // the same for the shadow
					popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
				});
				  markThis(<?php echo $row->lat ?: 0;?>,<?php echo $row->lon ?: 0;?>);
			  @endif
				
			  
			  function markThis(lat,lon){
				  var markerLocation = new L.LatLng(lat, lon);
				  var marker = new L.Marker(markerLocation);
				  newUser.clearLayers();
				  newUser.addLayer(marker);
			  }
			  
			  initRegistration();
			  
			  geoLocate();
		}
	  
	  //var osmb = new OSMBuildings(map).load('https://{s}.data.osmbuildings.org/0.2/anonymous/tile/{z}/{x}/{y}.json');
      // GeoLocation Control

      var geolocControl = new L.control({
        position: 'topright'
      });
      geolocControl.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'leaflet-control-zoom leaflet-control');
        div.innerHTML = '<a class="leaflet-control-geoloc" href="#" onclick="geoLocate(); return false;" title="Lokasi Saya"></a>';
        return div;
      };
      
      map.addControl(geolocControl);
      map.addControl(new L.Control.Scale());

      //map.locate({setView: true, maxZoom: 3});

      $(document).ready(function() {
        $.ajaxSetup({cache:false});
        //$('#map').css('height', ($(window).height() - 40));
        //getUsers();
		
		//$('#osmMap').show();
      });

      $(window).resize(function () {
       // $('#map-{{$name}}').css('height', ($(window).height() - 40));
      }).resize();

       function geoLocate() {
	     var myLocation = Android.getMyLocation();
		 var resml = myLocation.split(",");
		 map.setView([ resml[0],resml[1]], 17);
	  }
	  
	  function myLocation(lat, lng){
		  var myIconFromSiapkk = Android.getMyIcon();
		
		
			var markerLocation = new L.LatLng(lat, lng);
			if(myIconFromSiapkk.length>0){
				// var myCustomColour = '#583470';

				// var markerHtmlStyles = 'background-color: '+myCustomColour+';width: 3rem;height: 3rem;display: block;left: -1.5rem;top: -1.5rem;position: relative;border-radius: 3rem 3rem 0;transform: rotate(-'+Android.getDegree()+'deg);border: 1px solid #FFFFFF';
				  
				 // var myIcon = L.divIcon({
					  // className: "my-custom-pin",
					  // iconAnchor: [0, 24],
					  // labelAnchor: [-6, 0],
					  // popupAnchor: [0, -36],
					  // label : "Wahyu",
					  // html: '<span style="'+markerHtmlStyles+'" />'
					// });

				var myIcon = L.icon({
					iconUrl: myIconFromSiapkk,
					iconSize: [50, 50],
					iconAnchor: [25, 50],
					popupAnchor: [3, -20],
					//shadowUrl: 'shlogocctv.png',
					shadowSize: [80, 50],
					shadowAnchor: [20, 35],
					setTransform: 'rotate('+Android.getDegree()+'deg)'
				});
				
				//console.log(myIcon);
				var marker = new L.Marker(markerLocation);
			}else{
				var marker = new L.Marker(markerLocation);
			}
			
			// marker._icon.style.WebkitTransform = marker._icon.style.WebkitTransform + ' rotate(' + Android.getDegree() + 'deg)';
			// marker._icon.style.MozTransform = 'rotate(' + Android.getDegree() + 'deg)';
			
			Me.clearLayers();
			Me.addLayer(marker);
	  }

      function initRegistration() {
        map.addEventListener('click', onMapClick);
        $('#map-{{$name}}').css('cursor', 'crosshair');
		//alert();
        return false;
      }

      function cancelRegistration() {
        newUser.clearLayers();
        $('#map-{{$name}}').css('cursor', '');
        map.removeEventListener('click', onMapClick);
      }
	  
	    function onMarkerClick(e) {
			//console.log(e.target);
			var oldPlayer = document.getElementById('player');
			if(oldPlayer){
				videojs(oldPlayer).dispose();
			}
			var video = "<div id='pop' style='text-align: center; margin-left: auto; margin-right: auto;width:300px;height:200px'><div style='font-size: 18px; color: #0078A8;'>"+ this.options.desc + "</div><video id='player' width=100% height=90% class='video-js vjs-default-skin vjs-16-9 vjs-big-play-centered' muted autoplay controls><source src='http://103.133.56.188:8105/cctv/hls/"+this.options.title+".m3u8' type='application/x-mpegURL'></video></div>";
			this._popup.setContent( video );
			//var vids = "";
			//if(vids!=videojs(this.options.title)){
			videojs('player');
			//}			
		}

      function getUsers() {
        $.getJSON("get_streams.php", function (data) {
          for (var i = 0; i < data.length; i++) {
            var location = new L.LatLng(data[i].lat, data[i].lng);
            var name = data[i].name;
            var input = data[i].input;
			var deskripsi = data[i].deskripsi;
              var title = "<div style='text-align: center; margin-left: auto; margin-right: auto;'><div style='font-size: 18px; color: #0078A8;'>"+ data[i].deskripsi + "</div><video id='"+name+"' width=100% height=90% class='video-js vjs-default-skin vjs-16-9 vjs-big-play-centered' muted controls autoplay preload='auto'><source src='http://103.133.56.188:8105/cctv/hls/"+name+".m3u8' type='application/x-mpegURL'></video></div>";
			  //console.log(title);
			  //var video = '';
 
            // if (data[i].city.length > 0) {
              // var city = "<div style='font-size: 14px;'>"+ data[i].city +"</div>";
            // }
            // else {
              // var city = "";
            // }
			var myIcon = L.icon({
				iconUrl: 'logocctv.png',
				iconSize: [80, 80],
				iconAnchor: [40, 80],
				popupAnchor: [3, -20],
				shadowUrl: 'shlogocctv.png',
				shadowSize: [80, 50],
				shadowAnchor: [20, 35]
			});
			
            var marker = new L.Marker(location, {
              title: name,
			  desc : deskripsi,
			  icon: myIcon
            });	
			
			
            marker.bindPopup("<div id='pop' style='text-align: center; margin-left: auto; margin-right: auto;width:500;height:400px'>"+ title +"</div>", {maxWidth: '600'});
            //var popup = marker.getPopup(); 
			users.addLayer(marker);
			
			marker.on('click', onMarkerClick );
			
			
          }
        }).complete(function() {
          if (firstLoad == true) {
            map.fitBounds(users.getBounds());
            firstLoad = false;
          };
        });
      }
	  
	


      function insertUser() {
        $("#loading-mask").show();
        $("#loading").show();
        var name = $("#name").val();
        var email = $("#email").val();
        var website = $("#website").val();
        var city = $("#city").val();
        var lat = $("#lat").val();
        var lng = $("#lng").val();
        if (name.length == 0) {
          alert("Name is required!");
          return false;
        }
        if (email.length == 0) {
          alert("Email is required!");
          return false;
        }
        var dataString = 'name='+ name + '&email=' + email + '&website=' + website + '&city=' + city + '&lat=' + lat + '&lng=' + lng;
        $.ajax({
          type: "POST",
          url: "insert_user.php",
          data: dataString,
          success: function() {
            cancelRegistration();
            users.clearLayers();
            getUsers();
            $("#loading-mask").hide();
            $("#loading").hide();
            $('#insertSuccessModal').modal('show');
          }
        });
        return false;
      }
	  
	  function insertStream() {
        $("#loading-mask").show();
        $("#loading").show();
        var name = $("#name").val();
        var input = $("#input").val();
        var deskripsi = $("#deskripsi").val();
        var lat = $("#lat").val();
        var lng = $("#lng").val();
        if (name.length == 0) {
          alert("Name is required!");
          return false;
        }
        if (input.length == 0) {
          alert("Input is required!");
          return false;
        }
		if (deskripsi.length == 0) {
          alert("Deskripsi is required!");
          return false;
        }
        var dataString = 'name='+ name + '&input=' + input + '&deskripsi=' + deskripsi + '&lat=' + lat + '&lng=' + lng;
		//alert(dataString);
        $.ajax({
          type: "POST",
          url: "insert_stream.php",
          data: dataString,
          success: function() {
            cancelRegistration();
            users.clearLayers();
            getUsers();
            $("#loading-mask").hide();
            $("#loading").hide();
            $('#insertSuccessModal').modal('show');
          }
        });
        return false;
      }

      function removeUser() {
        var name = $("#email_remove").val();
        if (name.length == 0) {
          alert("Name is required!");
          return false;
        }
        var dataString = 'name='+ name;
        $.ajax({
          type: "POST",
          url: "remove_stream.php",
          data: dataString,
          success: function(data) {
            //console.log(data);
            if (data > 0) {
              $('#removemeModal').modal('hide');
              users.clearLayers();
              getUsers();
              $('#removeSuccessModal').modal('show');
            }
            else {
              alert("Incorrect email or token. Please try again.");
            }
          }
        });
        return false;
      }

      function onMapClick(e) {
            @if($row->lat && $row->lon)
              var markerIcon = L.icon({
              iconUrl: '{{asset('/')}}<?php echo $row->icon; ?>',

              iconSize:     [80, 80], // size of the icon
              shadowSize:   [50, 64], // size of the shadow
              iconAnchor:   [40, 80], // point of the icon which will correspond to marker's location
              shadowAnchor: [4, 62],  // the same for the shadow
              popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
            });
            @endif
                var markerLocation = new L.LatLng(e.latlng.lat, e.latlng.lng);
            @if($row->icon)
              var marker = new L.Marker(markerLocation,{icon: markerIcon});
            @else
              var marker = new L.Marker(markerLocation);
            @endif
                
                newUser.clearLayers();
                newUser.addLayer(marker);
            $("#lat").val(e.latlng.lat);
            $("#lon").val(e.latlng.lng);
                // var form =  '<form id="inputform" enctype="multipart/form-data" class="well">'+
                      // '<label><strong>Name:</strong> <i>marker title</i></label>'+
                      // '<input type="text" class="span3" placeholder="Required" id="name" name="name" />'+
                      // '<label><strong>Input:</strong> <i>never shared</i></label>'+
                      // '<input type="text" class="span3" placeholder="Required" id="input" name="input" />'+
                // '<label><strong>Deskripsi:</strong> <i>marker description</i></label>'+
                      // '<input type="text" class="span3" placeholder="Required" id="deskripsi" name="deskripsi" />'+
                      // '<input style="display: none;" type="text" id="lat" name="lat" value="'+e.latlng.lat.toFixed(6)+'" />'+
                      // '<input style="display: none;" type="text" id="lng" name="lng" value="'+e.latlng.lng.toFixed(6)+'" /><br><br>'+
                      // '<div class="row-fluid">'+
                        // '<div class="span6" style="text-align:center;"><button type="button" class="btn" onclick="cancelRegistration()">Cancel</button></div>'+
                        // '<div class="span6" style="text-align:center;"><button type="button" class="btn btn-primary" onclick="insertStream()">Submit</button></div>'+
                      // '</div>'+
                      // '</form>';
                // marker.bindPopup(form).openPopup();
		
      }

    </script>
@endpush