<?php $lang=Yii::app()->session['lang'] ;
header('Content-Type:text/javascript'); 
?>
 
 
$('#governorateSelect').on('change', function(){
var country_id = this.value;

$("#regionSelect").prepend("<option value='' selected='selected'><?php echo ($lang=='en'?'Area':'المنطقة')?></option>");
$('#regionSelect option:not([data-region|="'+country_id+'"])').css({"display":"none"} );
$('#regionSelect option[data-region|="'+country_id+'"]') .css({"display":"block"} );
  });

      var map;
	  var zoom=10;
	  var initial_lon = 36.2850706;
	  var initial_lat = 33.520296;
	  var markers = new Array();

    function hideAllPopups(){
        var overlays = map.getOverlays();
        overlays.forEach(element => {
            element.setPosition(undefined);
        });
    }

      function initMap() {
       
 
  var locations = [<?php 
  $branches=Branch::model()->findAll();
  $coun=1;
  foreach($branches as $branche)
  {
    if($lang=='ar')
    {
	    echo "['".$branche->name_ar."',".$branche->longitude.",".$branche->latitudes.",'".$branche->phone."','".$branche->fax."','".$branche->address."','".$branche->type."',".$coun."],";
    }else
    {
      echo "['".$branche->name_en."',".$branche->longitude.",".$branche->latitudes.",'".$branche->phone."','".$branche->fax."','".$branche->address_en."','".$branche->type."',".$coun."],";
    }
  }
  ?>
     
];

    var baseUrl = <?= json_encode(Yii::app()->getBaseUrl(true)) ?>;

    
    // Marker as ATM icon
    var atmIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
            src: baseUrl + "/images/atm.png",
        })
    });

    // Marker as branch icon
    var branchIconStyle = new ol.style.Style({
        image: new ol.style.Icon({
            src: baseUrl + "/images/branch.png",
        })
    });

    map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([initial_lon, initial_lat]),
            zoom: zoom
        })
    });
    
    for (i = 0; i < locations.length; i++) {
        var lonLat = ol.proj.fromLonLat([locations[i][1], locations[i][2]]);
        var feature = new ol.Feature({
          geometry: new ol.geom.Point(lonLat),
        });
        
        var popup;
        
        if(locations[i][6] == 'atm'){
          feature.setStyle(atmIconStyle);

          var element = document.createElement('div');
          element.innerHTML = '<div id="content" class="script-governorate-content">' + 
              '<div id="bodyContent">' + 
              '<p class="text-align-left ltr-direction"><b>ATM: </b></p>' +
              '<p class="text-align-left ltr-direction"><b>phone: </b>' + locations[i][3] + '</p>' +
              '<p class="text-align-left ltr-direction"><b>fax: </b>' + locations[i][4] + '</p>' +
              '<p class="text-align-left ltr-direction"><b>address: </b>' + locations[i][5] + '</p>' +
              '</div>' +
              '</div>'.trimt();
          popup = new ol.Overlay({
            element: element,
			});
        }
        else{
          feature.setStyle(branchIconStyle);

          var element = document.createElement('div');
          element.innerHTML = '<div id="content" class="script-governorate-content-padding-all">' +
              '<div id="bodyContent">' + 
              '<p class="text-align-left ltr-direction"><b>phone: </b>' + locations[i][3] + '</p>' +
              '<p class="text-align-left ltr-direction"><b>fax: </b>' + locations[i][4] + '</p>' +
              '<p class="text-align-left ltr-direction"><b>address: </b>' + locations[i][5] + '</p>' +
              '</div>' +
              '</div>'.trim();
          popup = new ol.Overlay({
            element: element,
          });
        }

        popup.setPosition(lonLat);
		popup.setOffset([-150,0]);
        markers[i] = feature;
        markers[i].popup = popup;

        map.addOverlay(popup);
    }

    hideAllPopups();

    map.on('click', function(e){
        map.forEachFeatureAtPixel(e.pixel, function(feature, layer){
            hideAllPopups();
            feature.popup.setPosition(e.coordinate);
            map.getView().animate({
				zoom:12,
                center: feature.getGeometry().getCoordinates(),
            });
        });
    });

    var layer = new ol.layer.Vector({
        source: new ol.source.Vector({
          features: markers
        })
      });

      map.addLayer(layer);
    }

$(document).ready(function (){

    function newLocation(newLat, newLng, z){
        
        map.getView().setCenter(ol.proj.transform([newLng, newLat], 'EPSG:4326','EPSG:3857'));
        map.getView().setZoom(z);
        hideAllPopups();
    }

    var citiesArray=[
        <?php 
            $covres="";
            $governorates=Governorate::model()->findAll();
            foreach($governorates as $governorate){
                $covres.= "[".$governorate->id.",".$governorate->longitude.",".$governorate->latitudes."],";
            }
            echo substr($covres,0,strlen($covres)-1);
        ?>
    ];
 
    var areaArray=[
        <?php 
            $areares="";
            $areas=Area::model()->findAll();
            foreach($areas as $area){
                $areares.="[".$area->id.",".$area->longitude.",".$area->latitudes."],";
            }
            echo substr($areares,0,strlen($areares)-1);
        ?>
    ];

    function mapSearch(){
	    var gover=$('#governorateSelect').find(":selected").val();
	    var area=$('#regionSelect').find(":selected").val();
	  
	
        for(var i=0; i<citiesArray.length; i++){
            if (citiesArray[i][0] == gover) {
                newLocation(citiesArray[i][2], citiesArray[i][1], 10);
            }
        }

        for(var i=0; i<areaArray.length; i++) {
            if (areaArray[i][0] == area) {
                newLocation(areaArray[i][2], areaArray[i][1], 14);
            }
        }

        if(gover!=0 && area!==0){
            for(var i=0; i<areaArray.length; i++) {
                if (areaArray[i][0] == area) {
                    newLocation(areaArray[i][2], areaArray[i][1], 10)
                }
            }
        }
    }

    $("#search").on('click', function(){
		mapSearch();
    });

});


$(window).on('load',initMap);
     
