'use strict';

/** 
 * @controller KartaDetailsController
 * @property scope 
 * @property route
 * @property location
 * @property window
 * @property System
 * @property KartaService
 * @property Resource
 */

var KartaDetailsController = angular.module('karta.controllers.karta',[
    'system'
])
    .controller('KartaDetailsController', [
        '$scope',
        '$location',
        '$route',
        '$window',
        'System',
        'KartaService',
         'ClassificationService',
        function ($scope, $location, $route, $window, System, KartaService, ClassificationService) {
             System.Page.title("Karta Laktaša");
            $scope.query = $route.current.params || {};
            $scope.currentView = 'view';
            $(".tooltip").tooltip();

            $scope.classifications = { category: [] };
            $scope.treeObject = {};
            /**
            * @method refresh
            * @description refreshes page and loads all initial data
            */

               $scope.IconSelectorOpiton = {
                multipleSeletcion: false
            };

            ClassificationService.getByAlias('lokacije').then(function (response) {
                $scope.categories = qusion.list.jsTree(response.Labels, "ID", "Name");
            });

            $scope.refresh = function () {
                KartaService.query($scope.query).then(function (data) {
                    $scope.karte = data.karte;
                    $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                });

                $scope.gmap = {
                    fromAddress: 'Лакташи',
                    streetAddress: "Карађорђева 56",
                    businessWriteup: "<b>Nenad Ješić</b><br/>Лакташи<br/>",
                    businessTitle: "Nenad Ješić",
                    Lon: 17.303310,
                    Lat: 44.907110,
                    showError: function (status) {
                        toastr.error(status);
                    }
                }
                $scope.lokacija = {
                    fromAddress: 'Лакташи',
                    streetAddress: "Карађорђева 56",
                    businessWriteup: "<b>Nenad Ješić</b><br/>Лакташи<br/>",
                    businessTitle: "Nenad Ješić",
                    Lon: 17.303310,
                    Lat: 44.907110,
                    showError: function (status) {
                        toastr.error(status);
                    }
                }      
            };


            
      
            /* padajuca lista*/

            $scope.stViewChange = function (agent) {
                console.log('click', agent); //object
            }

            /**
            * @action back returns to location /karta
            */
            $scope.back = function () {
                $location.url('/karta');
            };

            $scope.addkarta = function () {
                $location.url('/karta/create');
            };

            $scope.ruta = function () {
                $location.url('/karta/ruta');
            };
            /**
            * @method isCurrentView
            * @description returns value that indicates if currentView is initialized
            */
            $scope.isCurrentView = function (name) {
                return $scope.currentView == name;
            };
       
            
            /**
            * @method show
            * @description shows current view
            */
            $scope.show = function (name) {
                $scope.currentView = name;
            };

            /* gleda u padajucu listu i pozicionira na izabrano naselje */
            $scope.$watch('Selected', function (value) {
                if (value) {
                    $scope.query = { OdjeljenjeID: value };
                    KartaService.query($scope.query).then(function (data) {
                        $scope.karta = data.karta;
                        $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                    });
                   
                    $scope.DisplayUpdate = true;
                }
            });

            /**
          * @method create
          * @description kartaService creates new karta
          */
            $scope.create = function () {
                $scope.karta.Labels = [];

                var keys = (function (obj) {
                    var k = [], x;
                    for (x in obj) {
                        k.push(x);
                    }
                    return k;
                })($scope.classifications);

                for (var i = 0; i < keys.length; i++) {
                    for (var j = 0; j < $scope.classifications[keys[i]].length; j++) {
                        $scope.karta.Labels.push($scope.classifications[keys[i]][j]);
                    }
                }
                var lat = document.getElementById("latitude").value;
                var lng = document.getElementById("longitude").value;
                $scope.karta.Latitude = lat;
                $scope.karta.Longitude = lng;
                  KartaService.create($scope.karta)
                    .then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource("utility.changeNotSave"));
                        } else {
                            $location.url('/karta');
                            System.Message.success($scope.$resource("karte.KartaCreated"));
                        }
                    });
            };

            /**
          * @method remove
          * @param karta
          * @param index
          * @description removes karta by its id and removes it from local karta list by its index
          */ 

            $scope.remove = function (karta, index) {
                if ($window.confirm($scope.$resource('utility.areYouShure'))) {
                    KartaService.remove({ id: karta.ID }).then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            $scope.karte.splice(index, 1);
                            System.Message.success($scope.$resource('utility.deleted'));
                        }
                    });
                }
            };

            /*Prikaz karte*/

            $scope.prikazKarte = function (karta) {
                $scope.karta = karta;
                $scope.lokacija = {
                    businessTitle: karta.Title,
                    Lon: karta.Longitude,
                    Lat: karta.Latitude,
                    showError: function (status) {
                        toastr.error(status);
                    }
                }

           
                var myLatlng = new google.maps.LatLng(karta.Latitude, karta.Longitude);
                var mapOptions = {
                    zoom: 15,
                    center: myLatlng
                }
                var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

                var marker = new google.maps.Marker({
                    position: myLatlng,
                    title: karta.Title
                });
                google.maps.event.addListenerOnce(map, 'idle', function () {
                    google.maps.event.trigger(map, 'resize');
                    map.setCenter(mapOptions.center);
                });
                // To add the marker to the map, call setMap();
                marker.setMap(map);
                $scope.dialogKarta.dialog("open");
            };
            /**
           *zatvori novo pitanje
           */
            $scope.cancelEdit = function () {
                $scope.dialogKarta.dialog("close");
            };

            $scope.ui.dialogKarta = {
                width: 600,
                create: function () {
                    $scope.dialogKarta = $(this);
                }
            };

            $scope.$watch("pager.page", function () {
                if (!$scope.pager || !$scope.pager.page) return;
                $scope.query.page = $scope.pager.page;
                $scope.search($scope.query, false);
            });

            $scope.refresh();
            $scope.treeOptions = {
                selectMode: 2,
                dialogTitle: $scope.$resource('articles.select_dialog_categories')
            };
        }
    ]);


