var TaxiApp = angular.module('LandmarksApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'angularUtils.directives.dirPagination', 'ui.bootstrap', 'angularAwesomeSlider', 'angular-growl', 'ngAnimate', 'AxelSoft','elif']);
TaxiApp.config(['growlProvider', function (growlProvider) {
    growlProvider.globalTimeToLive({ success: 1000, error: 2000, warning: 150000, info: 150000 });
}]);


TaxiApp.controller('LandmarksCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl', 
function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl) {
    $scope.loading = false;
    var TokenID = sessionStorage.TokenID;
    var orgOID = sessionStorage.ORGOID;
    var userOID = sessionStorage.UserOID;
    $scope.Landmarks = [];
    var markers = [];
    $scope.longitude = 0
    $scope.latitude = 0;
    if (sessionStorage.OrderId < 2) {
        window.location.href = "../../Access.html";
    }
    var map;
    $scope.getdetails = function (msg) {

        $scope.result = msg;
        alert();
    }
    Localization(sessionStorage.selectedLanguage, 'mapview', $scope, sessionStorage);
    $scope.utils = {
        zoom: function(lat, long){
            gMap.zoom(lat, long);
        }
    }
    gMap = {
        zoom: function(lat, long){
            map.setZoom(22);
            map.panTo({ lat: lat, lng: long });
        },
        clear: function(){
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        },
        addMarker: function (lat, long, name) {
            var icon = {
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
            };
            markers.push(new google.maps.Marker({
                map: map,
                title: name,
                position: { lat: lat, lng: long }
            }));
        },
        init: function () {
            var latitude = 31.903812293438545; // YOUR LATITUDE VALUE
            var longitude =35.20421675503561; // YOUR LONGITUDE VALUE

            var myLatLng = { lat: latitude, lng: longitude };

            map = new google.maps.Map(document.getElementById('dvmap'), {
                center: myLatLng,
                zoom: 14,
                disableDoubleClickZoom: true, // disable the default map zoom on double click
            });
            // Create the search box and link it to the UI element.
            var input = document.getElementById('pac-input');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function () {
                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', function () {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function (marker) {
                    marker.setMap(null);
                });

                // For each place, get the icon, name and location.
                var bounds = new google.maps.LatLngBounds();
                places.forEach(function (place) {
                    if (!place.geometry) {
                        console.log("Returned place contains no geometry");
                        return;
                    }
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };

                    // Create a marker for each place.
                    markers.push(new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: place.name,
                        position: place.geometry.location
                    }));

                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
            });
            // Update lat/long value of div when anywhere in the map is clicked
            google.maps.event.addListener(map, 'click', function (event) {
                //alert('clicked');
            });

         

            // Create new marker on double click event on the map
            google.maps.event.addListener(map, 'dblclick', function (event) {
                gMap.clear();
                $scope.longitude = event.latLng.lng().toFixed(6);
                $scope.latitude = event.latLng.lat().toFixed(6);
                document.getElementById('coordinates').value = $scope.latitude + "," + $scope.longitude

                $scope.landmark.get($scope.latitude, $scope.longitude);

                var marker = new google.maps.Marker({
                    position: event.latLng,
                    map: map,
                    title: event.latLng.lat() + ', ' + event.latLng.lng()
                });
                markers.push(marker);
                // Update lat/long value of div when the marker is clicked
                marker.addListener('click', function () {
                    //alert('clicked');
                });
            });

            // Create new marker on single click event on the map
            /*google.maps.event.addListener(map,'click',function(event) {
            var marker = new google.maps.Marker({
            position: event.latLng,
            map: map,
            title: event.latLng.lat()+', '+event.latLng.lng()
            });
            });*/
        }
    }
    $scope.landmark = {
        showRegionsCtrl: null,
        listRegionsCtrl: null,
        delete: function (id) {
            $scope.loading = true;
            var landmark = {};
            landmark.id = id;
            landmark.userid = userOID;
            landmark.tokenid = TokenID;
            landmark.lng = 0
            landmark.lat = 0;
            landmark.name = 0;
            landmark.street = 0;
            landmark.area = 0;

            var obj = {
                "lmObj": landmark
            };

            $.ajax({

                type: "POST",
                url: ManagementServiceUrl + "DeleteLandmark",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (result) {
                    if (result.DeleteLandmarkResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                   
                    var data = result.DeleteLandmarkResult;
                    $scope.loading = false;
                    if (data == 0) {
                        alert("حدث خطأ")
                    } else {
                        $scope.landmark.get($scope.latitude, $scope.longitude);

                    }
                    $scope.loading = false;
                    $scope.$apply();


                },
                error: function (error) {
                    $scope.loading = false;
                    alert("حدث خطأ" + error);
                    $scope.$apply();
                }
            });
        },
        add: function () {
            $scope.loading = true;

            var coordinates = document.getElementById('coordinates').value;
            var name = document.getElementById('name').value;
            var street = document.getElementById('street').value;
            var area = document.getElementById('area').value;
            if (coordinates == null || coordinates == ''||
                name == null ||name ==''||
                street== null || street=='' ||
                area == null || area == ''
                ) {
                alert('يجب ادخال جميع الحقول..');
                $scope.loading = false;

                return;

            }

            var cords = coordinates.split(',');
            var lat = cords[0];
            var long = cords[1];
            if (lat == null || long == null) {
                alert('الاحداثيات غير صحيحة...');
                $scope.loading = false;
                return;

            }

            var landmark = {};
            landmark.id = 0;
            landmark.userid = userOID;
            landmark.tokenid = TokenID;
            landmark.lng = long
            landmark.lat = lat;
            landmark.name = name;
            landmark.street = street;
            landmark.area = area;

            var obj = {
                "lmObj": landmark
            };
            
            $.ajax({

                type: "POST",
                url: ManagementServiceUrl + "AddLandmark",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (result) {
                    if (result.AddLandmarkResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    var data = result.AddLandmarkResult;
                    $scope.loading = false;
                    if (data > 0) {
                        alert("تم حفظ الموقع، تشكرات ...");
                        $scope.landmark.get($scope.latitude, $scope.longitude);
                    }
                    else if (data == "0")
                        alert("لا يمكنك ادخال نقاط ...");
                    else
                        alert("حدث خطأ")
                    $scope.loading = false;
                    $scope.$apply();


                },
                error: function (error) {
                    $scope.loading = false;
                    alert("حدث خطأ"+error);
                    $scope.$apply();
                }
            });
        },
        get: function (lat, long) {
            $scope.loading = true;
            gMap.clear();
            var landmark = {};
            landmark.id = 0;
            landmark.userid = userOID;
            landmark.tokenid = TokenID;
            landmark.lng = long;
            landmark.lat = lat;
            landmark.name = name;
            landmark.street = street;
            landmark.area = area;

            var obj = {
                "lmObj": landmark
            };

            $.ajax({

                type: "POST",
                url: ManagementServiceUrl + "GetLandmarks",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (result) {
                    if (result.GetLandmarksResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    var data = result.GetLandmarksResult;
                    $scope.Landmarks = JSON.parse(data);
                    for (item in $scope.Landmarks) {
                        gMap.addMarker($scope.Landmarks[item].latitude, $scope.Landmarks[item].longitude, $scope.Landmarks[item].building);
                    }
                  
                    $scope.loading = false;
                    $scope.$apply();


                },
                error: function (error) {
                    $scope.loading = false;
                    alert("حدث خطأ");
                    $scope.$apply();
                }
            });

    }
    }

}
])
    

