
var markers = [];
var myloc=[];
var request={};
var myloc_andis=0;
var map;
var input;
var searchBox;
input = document.getElementById("pac-input");
var Location_name="chalus Mazandaran Province ";

//alert("hey");

// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

// MAP DESIGN 4 BUTTONS------------------------------::> Fullscreen
function initZoomControl(map) {
    document.querySelector(".zoom-control-in").onclick = function () {
      map.setZoom(map.getZoom() + 1);
    };
  
    document.querySelector(".zoom-control-out").onclick = function () {
      map.setZoom(map.getZoom() - 1);
    };
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(
      document.querySelector(".zoom-control")
    );
  }
  
  function initMapTypeControl(map) {
    const mapTypeControlDiv = document.querySelector(".maptype-control");
  
    document.querySelector(".maptype-control-map").onclick = function () {
      mapTypeControlDiv.classList.add("maptype-control-is-map");
      mapTypeControlDiv.classList.remove("maptype-control-is-satellite");
      map.setMapTypeId("roadmap");
    };
  
    document.querySelector(".maptype-control-satellite").onclick = function () {
      mapTypeControlDiv.classList.remove("maptype-control-is-map");
      mapTypeControlDiv.classList.add("maptype-control-is-satellite");
      map.setMapTypeId("hybrid");
    };
    map.controls[google.maps.ControlPosition.LEFT_TOP].push(mapTypeControlDiv);
  }
  
  function initFullscreenControl(map) {
    const elementToSendFullscreen = map.getDiv().firstChild;
    const fullscreenControl = document.querySelector(".fullscreen-control");
    map.controls[google.maps.ControlPosition.RIGHT_TOP].push(fullscreenControl);
  
    fullscreenControl.onclick = function () {
      if (isFullscreen(elementToSendFullscreen)) {
        exitFullscreen();
      } else {
        requestFullscreen(elementToSendFullscreen);
      }
    };
    document.getElementById("fullScreenButton").addEventListener("click", () => {   
        var obj=document.getElementById("fullScreenButton")
        var x=Number(obj.value);
        if(x==0){
            obj.value=1;
            obj.children[0].classList.remove("fa-expand");
            obj.children[0].classList.add("fa-external-link-alt");
        }else{
            obj.value=0;
            obj.children[0].classList.add("fa-expand");
            obj.children[0].classList.remove("fa-external-link-alt");

        }
        
      });

    document.onwebkitfullscreenchange = document.onmsfullscreenchange = document.onmozfullscreenchange = document.onfullscreenchange = function () {
      if (isFullscreen(elementToSendFullscreen)) {
        fullscreenControl.classList.add("is-fullscreen");
      } else {
        fullscreenControl.classList.remove("is-fullscreen");
      }
    };
  }
  
  
  function isFullscreen(element) {
    return (
      (document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement) == element
    );
  }
  
  function requestFullscreen(element) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.msRequestFullScreen) {
      element.msRequestFullScreen();
    }
  }
  
  function exitFullscreen() {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
//----------------------------------------------------------------------------------

// map initializing
function initAutocomplete() {
    map = new google.maps.Map(document.getElementById("google_map"), {
    center: { lat:  36.66, lng: 51.42}, 
    zoom: 14,
    mapTypeId: "roadmap",
    disableDefaultUI: true,
    streetViewControl: true,
    streetViewControlOptions: {
        position: google.maps.ControlPosition.LEFT_BOTTOM
      },
  });
  
  // creating the map buttons 
  initZoomControl(map);
  initMapTypeControl(map);
  initFullscreenControl(map);
//   map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.querySelector(".zoom-control"));
  // Create the search box and link it to the UI element.
  input = document.getElementById("pac-input");
  searchBox = new google.maps.places.SearchBox(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener("bounds_changed", () => {
    searchBox.setBounds(map.getBounds());
  });

  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.

  searchBox.addListener("places_changed", () => {   
    clearData();
    google_map_search();
  });
  document.getElementById("search_btn").addEventListener("click", () => {   
    serch_Box_trigger(document.getElementById('pac-input'));
  });
  
}


// will press the Enter inorder to start searching 4 the locations that we searched 
function serch_Box_trigger(btn){
    google.maps.event.trigger(btn, 'focus', {});
    google.maps.event.trigger(btn, 'keydown', { keyCode: 13 });
    google.maps.event.trigger(this, 'focus', {});
}
// Clear out the old markers.
function clearData(){
    document.getElementById("map_search_result").innerHTML="<br/><br/><br/>";
    markers.forEach((marker) => {
        marker.setMap(null);
    });
    myloc_andis=0;
    markers = [];
    myloc=[];
}
// search 4 new locations
function google_map_search(){
    
    var places=null;
    places=searchBox.getPlaces();
    if (places.length == 0) {
    return;
    }
    // For each place, get the icon, name and location.
    const bounds = new google.maps.LatLngBounds();
    places.forEach((place) => {
    if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
    }
    if(place.place_id in myloc){}else{myloc.push(place.place_id);}
    
    
    if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
    } else {
        bounds.extend(place.geometry.location);
    }
    });
    findGoogle();
    map.fitBounds(bounds); 
}


// get and set the markers which is gotten from google search
function findGoogle(){
    finder(myloc[myloc_andis]);
}
function finder(id){
          const request = {
              placeId: id,
              fields: ["name", "formatted_address", "place_id", "geometry",'rating', 'international_phone_number',"photos"],
          };
          
          const service = new google.maps.places.PlacesService(map);
          service.getDetails(request, (place, status) => {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                //alert(JSON.stringify(place.photos));
                const icon = {
                  url: "https://cdn1.iconfinder.com/data/icons/navigation-46/100/navigation_location-06-512.png", //place.icon  // or you can try your icon  
                  size: new google.maps.Size(30, 30),
                  origin: new google.maps.Point(0, 0),
                  anchor: new google.maps.Point(17, 34),
                  scaledSize: new google.maps.Size(25, 25),
                };
                var marker;
                markers.push(
                    marker = new google.maps.Marker({
                    map,
                    icon,
                    position: place.geometry.location,
                    })
                );
                addresult(marker,place);
                google.maps.event.addListener(marker, "click", function () {
                    //alert(JSON.stringify(place.photos));
                  if(place.name){document.getElementById('info-content-name').innerHTML=place.name;}else{document.getElementById('info-content-name').innerHTML="";}
                  if(place.formatted_address){document.getElementById("info-content-address").style.display = "block";document.getElementById('info-content-address').innerHTML=place.formatted_address;}else{document.getElementById("info-content-address").style.display = "none";document.getElementById('info-content-address').innerHTML="";}
                  if(place.international_phone_number){document.getElementById("info-content-phone").style.display = "inline-block";document.getElementById('info-content-phone').innerHTML=phone_IRformat_creator(place.international_phone_number);}else{document.getElementById("info-content-phone").style.display = "none";document.getElementById('info-content-phone').innerHTML="";}
                  
                  if (place.rating) {
                        let ratingHtml = "";
                        var star_on=true;
                        var counter=0;
                        var min_rate=0;
                        document.getElementById("info-content-rate").style.display = "inline-block";
                        min_rate=Math.floor(place.rating);
                        counter+=min_rate;
                        for(i=0;i<min_rate;i++){
                            ratingHtml =ratingHtml+ ('<span class="fas fa-star star-checked"></span>');
                        }
                        if((place.rating-min_rate)>0.5){
                            ratingHtml+= '<span class="fas fa-star-half-alt star-checked"></span>';
                            counter++; 
                        }else{}
                        for(i=0;i<(5-counter);i++){
                            ratingHtml +='<span class="fas fa-star"></span>';
                        }
                        document.getElementById("info-content-rate").innerHTML = ratingHtml+'<small style="color:#777;font-wight:700;">('+place.rating+')</small>';
                        
                  } else {
                        document.getElementById("info-content-rate").style.display = "none";
                  }
                  google_info_menu_down();
                  
                });
                myloc_andis++;
            }else{
              
            }
             if(myloc_andis<myloc.length){ findGoogle();}else{alert("done");}
          });

}

// this func add the result to the result list in right bar  
function addresult(marker,place){
    var resBox = document.getElementById("map_search_result");
    const newres = document.createElement("div");
    newres.onclick = function () {
        google.maps.event.trigger(marker, "click");
        map.panTo(place.geometry.location);
    };
    newres.innerHTML='<a><img src="images/icon/hotel.png"/><div><p>'+place.name+'</p><p><i class="fas fa-map-marker-alt"></i>'+place.formatted_address+'</p></div></a><span><i class="material-icons">share</i><i class="material-icons"> bookmark</i></span>'+'</a>'
    resBox.appendChild(newres);
}
//  .... its for the phone number that we take from google api ... its fucking reverse and we need this function to write it currectly
function phone_IRformat_creator(text){formatPlus=false;txt="";for(x=0;x<text.length;x++){if(text[x]=="+"){formatPlus=true;}if(text[x]!=" " && (text[x]!="+")){txt+=text[x];}}if(formatPlus){return txt+"+"}else{return txt;}}


// it will rewrited on jquery
var google_info_menu_down=function ride(){}

// function clickevent()
// {                
//      var e = this.Event("keydown");
//      e.which = 13;
//      e.keyCode = 13;
//      $(document).trigger(e);     
// }
// var keypress=function aac(){};

$(document).ready(function(){
    google_info_menu_down = function(){
        $("#info-content").stop();
        $("#info-content").animate({top:"10px"},function(){
            $("#info-content").animate({top:"5px"},100);
        });
    }
    $("#info-content").children().filter("button").click(function(){
            $("#info-content").stop();
            $("#info-content").animate({top:"10px"},100,function(){
                $("#info-content").animate({top:"-50%"});
            });
    });
    $(".map_menuBar").children().eq(1).children().filter("a").click(function(){
        var val=$(this).attr("value");
        var input_value=Location_name + val;
        $("#pac-input").val(input_value);
        serch_Box_trigger(document.getElementById('pac-input'));
    });

    // $(".gmnoprint").children().eq(0).children().eq(0).css({background:"red"});
    
 
    // $("#pac-input").keydown(function(event){
    //     if(event.keyCode == 13){                
    //         //alert("keypressed");
    //     }
    // });
    // keypress=function(){
    //     $("#pac-input").keydown(function() { return true; });
    //     var keyEvent = jQuery.Event("keydown");
    //     keyEvent.keyCode = 13;
    //     $("#pac-input").trigger(keyEvent);
    //     //alert("keyhasbeen pressed");
    // }
    
});
