'use strict';
/** 
 * @property scope 
 * @property location
 * @property route
 * @property System
 * @property OdjeljenjeService
 */

var AppController =  angular.module('app', [])
    .controller('AppController', [
        '$scope',
        '$timeout',
        '$location',
        '$route',
        '$locale',       
        '$window',
        'Config',
        'System',
        'Global',
        '$routeParams',
        'NavigationService',
        'PageService',
        'PageFactory',
        'ContentService',
        'JezikService',
        'NewslettersService',
        'ImageService',
        'VideoService',
        'LibraryService',
        function ($scope,$timeout, $location,  $window, $locale, $route, Config, System, Global, $routeParams, NavigationService, PageService, PageFactory, ContentService, JezikService, NewslettersService, ImageService, VideoService, LibraryService) {
            $locale.id = $location.search().Culture || Globalize.culture().name;
            var cul = Globalize.culture().name;
            $scope.ui = {};
            if ($locale.id != cul)
            {
                Global.init($scope);
                $scope.language.current = $location.search().Culture || Globalize.culture().name;
            }
            else {
                $locale.id = 'sr';
                $scope.ui = {};
                Global.init($scope);
                $scope.language.current = 'sr';
            }
          
          


            $scope.language.current = $location.search().Culture || Globalize.culture().name;

            var adSluzba = 'as';
            var ju = 'ju';
            System.Page.title();
            $scope.newsletter = {};
            $scope.formp = {};

            // Cacth all errors
            System.Broadcast.on($scope, Config.HTTP_ERROR_KEY, function (e, val) {
                switch (val) {
                    case 401:
                    case 403:
                        window.location.href = Config.API_LOGIN_URL + "?ReturnUrl=" + window.location.href;
                        break;
                    default:
                }
            });

            // Message
            System.Message.on($scope, function (e, message) {
                $scope.ui.alert = { type: message.type, text: message.value };
                $timeout(function () {
                    $scope.ui.alert = null;
                }, 5000);
            });

            // Cacth http status for loader
            System.Broadcast.on($scope, Config.HTTP_STATUS_KEY, function (e, val) {
                $scope.ui.loader = (val == Config.HTTP_REQUEST_STATUS.LOADING);
            });

            // catch route change
            $scope.$on('$routeChangeSuccess', function (scope, next, current) {
                $scope.refresh();
                // close all popovers
                angular.element(':qusion-popover').popover('close');
            });

            NavigationService.language($scope.navigationKey)
                .then(function (jezici) {
                    $scope.jezicine = jezici;
                    $scope.isActive = function (jezik) {
                        if (jezik.name == $locale.id)
                            return true;
                        return false;
                    };

                });

            // determines if provided link is active
            $scope.isActive = function (jezik) {
                if (jezik.name == $locale.id)
                    return true;
                return false;
            };

            $scope.setLang = function (q, la) {
                $locale.id = la;
                $scope.ui = {};
                JezikService.setCulture(la).then(function () {
                });
                Global.init($scope);
                $scope.language.current = la;
                $scope.Culture = q;
                $scope.query = q;
                //angular.extend($scope.query, q);
                $location.search($scope.query);
                if (la == 'sr') {
                    window.location = '/#/dashboard/?Culture=sr';
                }
                if(la == 'en')
                {
                    window.location = '/En/#/dashboarden/?Culture=en';
                }
              
                $scope.isActive = function (jezik) {
                    if (jezik.name == la)
                        return true;
                    return false;
                };

            };
           
            $scope.refresh = function () {
                var tip = 1;
                PageService.top(tip).then(function (data) {
                    $scope.pages = qusion.list.hierarchy(data.pages);
                    console.log($scope.pages);
                    $timeout(function () {
                        $("#treeTable").treetable({
                            expandable: true,
                            column: 1,
                            expanderTemplate: '<a href="#">&nbsp;</a>',
                            indenterTemplate: '<span class="indenter">&nbsp</span>',
                            onNodeCollapse: function () {
                                PageFactory.removeExpanded(this.id);
                            },
                            onNodeExpand: function (e) {
                                PageFactory.addExpanded(this.id);
                            }
                        });

                        var expanded = PageFactory.allExpanded();
                        for (var i = 0; i < expanded.length; i++) {
                            $("#treeTable").treetable("expandNode", expanded[i]);
                        }

                    }, 100);
                });

                $scope.selectLibrary = function (tip) {
                    if (tip != null)
                        $location.url('/documentst/' + tip);
                    else
                        $location.url('/documentst');
                };
              


                $scope.content = function (page) {
                    $location.url('/page/' + page.ID);
                }
          
            };



          
            $(document).ready(function () {
                //Check to see if the window is top if not then display button
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 100) {
                        $('.scrollToTop').fadeIn();
                    } else {
                        $('.scrollToTop').fadeOut();
                    }
                });

                //Click event to scroll to top
                $('.scrollToTop').click(function () {
                    $('html, body').animate({ scrollTop: 0 }, 800);
                    return false;
                });

            });
            /**
         * @action content redirects user to content form
         * @param radnik
         */
            $scope.selectRadnik = function (radnikid) {
                $location.url('/radnik/' + radnikid);
            };

            //    /**
            //* @action content redirects user to content form
            //* @param odjeljenje
            //*/
            $scope.selectOdjeljenje = function (odjeljenjeid) {
                $location.url('/odjeljenja/' + odjeljenjeid);
            };

            // determines if provided link is active
            $scope.isActive = function (item) {
                if ($scope.active)
                    return $scope.active.name == item.name;
                return false;
            };

            
            /**
              *@method NEWSLETER REGISRAIJACA
            **/
            $scope.otvori = function () {
                $scope.dialogPostica.dialog("open");
            };

            $scope.dialogPostica = {};

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


            $scope.registracija = function () {
                $scope.newsletter.status = 5;
                NewslettersService.create($scope.newsletter).then(function (response) {
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        System.Message.error($scope.$resource('users.EmailExist'));
                    } else {
                        System.Message.success($scope.$resource('newsletters.NewsletterCreated'));
                        $scope.dialogPostica.dialog("close");

                    }
                });
            };


            /**
            *@method MAPA 
            */
            $scope.initialize = function (la, lo) {
                if (la == null && lo == null) {
                    var lat = "44.907110";
                    var lon = "17.303310";
                }
                else
                {
                    lat = la;
                    lon = lo;
                }

                var styles = [
          {
              featureType: 'road.highway',
              elementType: 'geometry',
              stylers: [
                { hue: '#ff0022' },
                { saturation: 60 },
                { lightness: -20 }
              ]
          }, {
              featureType: 'road.arterial',
              elementType: 'all',
              stylers: [
                { hue: '#2200ff' },
                { lightness: -40 },
                { visibility: 'simplified' },
                { saturation: 30 }
              ]
          }, {
              featureType: 'road.local',
              elementType: 'all',
              stylers: [
                { hue: '#f6ff00' },
                { saturation: 50 },
                { gamma: 0.7 },
                { visibility: 'simplified' }
              ]
          }, {
              featureType: 'water',
              elementType: 'geometry',
              stylers: [
                { saturation: 40 },
                { lightness: 40 }
              ]
          }, {
              featureType: 'road.highway',
              elementType: 'labels',
              stylers: [
                { visibility: 'on' },
                { saturation: 98 }
              ]
          }, {
              featureType: 'administrative.locality',
              elementType: 'labels',
              stylers: [
                { hue: '#0022ff' },
                { saturation: 50 },
                { lightness: -10 },
                { gamma: 0.90 }
              ]
          }, {
              featureType: 'transit.line',
              elementType: 'geometry',
              stylers: [
                { hue: '#ff0000' },
                { visibility: 'on' },
                { lightness: -70 }
              ]
          }
                ];

                var options = {
                    mapTypeControlOptions: {
                        mapTypeIds: ['Styled']
                    },
                    center: new google.maps.LatLng(lat,lon),
                    zoom: 16,
                    disableDefaultUI: true,
                    mapTypeId: 'Styled'
                };
                var div = document.getElementById('map_canvas');
                var map = new google.maps.Map(div, options);
                var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
                map.mapTypes.set('Styled', styledMapType);
                var iconBase = 'http://www.laktasi.net/Areas/cms/Style/images/';
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat,lon),
                    map: map,
                    icon: iconBase + 'marker.png',
                    shadow: iconBase + 'marker.png',
                    size: new google.maps.Size(5, 5)

                });

              
                var message = '<h5 style="padding:0px 0px 10px 0px !important;">Opština Laktaši</h5>' +
                    '<div style="width: 100%; height:100%;color:#25282A;">' +
                    '<p><b>Adresa:</b>Karađorđeva 56<br />' +
                    '<b>Grad:</b> Laktaši <br />' +
                    '<b>Oblast/Država:</b> Republika Srpska - Bosna i Hercegovina<br />' +
                   '</p><p>' +
                   '<b>Telefon:</b> Info - 051/334-200<br />' +
                    '</p>' +
                    '<a class="see-all" href="http://www.laktasi.net">' +
                   '<h5 style="color:#25282A;">web:http://www.laktasi.net</h5></a> ' +
                    '</div>';
                var infowindow = new google.maps.InfoWindow({ content: message });
                google.maps.event.addListener(marker, 'click', function () {
                    infowindow.open(marker.get('map'), marker);
                    google.maps.event.trigger(map, 'resize')
                });

            };

            $scope.mapa = function () {
                $scope.dialogMap.dialog("open");
                $scope.initialize();
            };

            $scope.dialogMap = {};

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

            $scope.cancelMap = function () {
                $scope.load();
                $scope.dialogMap.dialog("close");
            };

         

            /**
            *@method MESSAGE - PORUKE NA SAJTU
            */
            $scope.message = function () {
                $scope.dialogMessage.dialog("open");
            };

            $scope.dialogMessage = {};

            $scope.ui.dialogMessage = {
                width: 550,
                height: 550,
                create: function () {
                    $scope.dialogMessage = $(this);
                }
            };

            $scope.cancelMessage = function () {
                $scope.dialogMessage.dialog("close");
            };

            $scope.sendMessage = function () {
                $scope.formp.Title = "Питајте управу";
                NewslettersService.sendMessage($scope.formp).then(function (response) {
                    $scope.dialogMessage.dialog("close");
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        System.Message.error($scope.$resource('newsletters.NewsletterSendError'));
                    } else {
                        System.Message.success($scope.$resource('newsletters.NewsletterSend'));
                        $scope.dialogMessage.dialog("close");
                    }
                });
            };

            $scope.sendMobileMessage = function () {
                $scope.formp.Title = "Питајте управу";
                NewslettersService.sendMessage($scope.formp).then(function (response) {
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        $location.url('/home');
                        System.Message.error($scope.$resource('newsletters.NewsletterSendError'));
                    } else {
                        $location.url('/home');
                        System.Message.success($scope.$resource('newsletters.NewsletterSend'));
                        
                    }
                });
            };
            /**
          *@method GALLERY GALERIJA SLIKA
          */
            $scope.galerijaslika = function () {
                $scope.dialogGalerija.dialog("open");
                $scope.refreshLibraries();
                $scope.lib();
            };

            $scope.dialogGallery = {};

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

            $scope.cancelGalerija = function () {
                $scope.dialogGallery.dialog("close");
            };
            /**
          * @method refreshLibraries
          * @description Load libraryes for the user.
          */
            $scope.refreshLibraries = function () {
                ImageService.libraries().then(function (data) {
                    $scope.libraries = data;
                });
            };


            /**
           * @method lib
           * @description Loads images for provided library.
           */
            $scope.lib = function (library) {
                if (library != undefined) {
                    ImageService.query({ LibraryID: library.ID })
                   .then(function (data) {
                       $scope.galerije = data.Images;
                   }
                   );
                }
                else {
                    ImageService.queryall()
                   .then(function (data) {
                       $scope.galerije = data;
                    });
                }
                
            };


            /**
           *@method GALLERY FILMS 
           */
            $scope.dialogVideo = {};

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

            $scope.galerijavideo = function () {
                $scope.dialogVideo.dialog("open");
                $scope.refreshLibrariesVideo();
            };



            $scope.cancelGalerijaVideo = function () {
                $scope.dialogVideo.dialog("close");
            };



            /**
         * @method refreshLibraries
         * @description Load libraryes for the user.
         */
            $scope.refreshLibrariesVideo = function () {
                $scope.query = {};
                VideoService.query($scope.query)
                   .then(function (data) {
                       $scope.videos = data.Videos;
                   });
            };

            $scope.goToVideo = function (videoId) {
                VideoService.get(videoId)
                    .then(function (data) {
                        $scope.video = data;
                        VideoService.query({ libraryId: data.LibraryID }).then(function (response) {
                            $scope.video = response.Video;
                        });

                    });
            };
      
        }
    ]);





