(function($, window) {
}).call(this, jQuery, window);
var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
              return $window._; // assumes underscore has already been loaded on the page
}]);
var publicToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicHVibGljIiwicm9sZXMiOlsicHVibGljIl0sImV4cCI6MTczNDE2NTcxMCwiaWF0IjoxNDc0OTY1NzEwLCJuYmYiOjE0NzQ5NjU3MTAsImlkZW50aXR5IjoiNTdlOWVmMjZjMjU0ZmQ4N2Q3ZmQ4MzM2In0.-9fcm5s8qYbdqBDUX7cZJ5J3AX91fe6VrCLs_S-_eBU";
var ottCats = [
	{title: 'MCOT HD', cat: [ 'MCOT HD'], varName: 'sports' },
	{title: 'Economic', cat: [ 'ข่าวทันสถานการณ์'], varName: 'econs'  },
	{title: 'Money', cat: [ 'เศรษฐกิจ'], varName: 'money'}
];
angular.module('ottApp', ['ui.router', 'ngSanitize','bootstrapLightbox',  'mcot.services', 'slimdir', 'mcot.filters'])
.config([
        '$locationProvider',
        '$stateProvider', '$urlRouterProvider', '$sceDelegateProvider',  function( $locationProvider,  $stateProvider, $urlRouterProvider, $sceDelegateProvider) {

            $locationProvider.html5Mode(true).hashPrefix('!');
            $sceDelegateProvider.resourceUrlWhitelist([
                    // Allow same origin resource loads.
                    'self',
                    // Allow loading from our assets domain.  Notice the difference between * and **.
                    'http://simplico.net:6066/**',
                    'http://119.46.61.109/**',
                    'http://cdn.mcot.net/**',
                    'http://git.simplico.net/**']);

            $urlRouterProvider.otherwise('/app.index');

            $stateProvider
                .state('app', {
                    abstract: true,
                    //url: '/',
                    templateUrl: '/static/templates/app.html',
                    controller: 'AppCtrl',
                    ncyBreadcrumb: {
                        label: 'Home'
                    }
                })
            .state('app.index', {
                //url: '/',
                url: '/',
                templateUrl: '/static/templates/app.index.html',
                controller: 'IndexCtrl',
                ncyBreadcrumb: {
                    label: 'Index'
                }
            })
            .state('app.view', {
                url: '/view/:id',
                templateUrl: '/static/templates/app.view.html',
                controller: 'ViewCtrl',
            })
			.state('app.program', {
                url: '/program',
                templateUrl: '/static/templates/app.program.html',
                controller: 'ProgramCtrl',
                ncyBreadcrumb: {
                    label: 'Program'
                }
            });


            // for dev
            var myAppId = '707598586069289'; // for prod
			//var myAppId = '105438229594549'; // for dev

            // You can set appId with setApp method
            // FacebookProvider.setAppId('myAppId');

            /**
             * After setting appId you need to initialize the module.
             * You can pass the appId on the init method as a shortcut too.
             */
        }
])
.filter('find_image_size', function(){
    return function(doc, key) {

        if( doc.medias === undefined )
            return '';
        var r = $.grep(doc.medias, function(e){ return e.ott_image == key; });
        if (r.length == 0) {
        // not found
            return doc.feature_url;
        } else {
            return r[0].value;
        }
    };
})
.controller('MainCtrl', function($state,  $scope, PUBLIC_TOKEN, $timeout, $uibModal){
    $scope.ottCats = ottCats;
    $state.transitionTo('app.index');
    $scope.openMenu = function() {
        console.log("open menu");
        $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title-bottom',
            ariaDescribedBy: 'modal-body-bottom',
            templateUrl: '/static/templates/menumodal.html',
            size: 'lg',
            controller: function($scope) {
                $scope.name = 'bottom';
            }
        });
    };

})
.controller('AppCtrl', function($state,  $scope,  $timeout, $window,$rootScope){

})
.controller('ViewCtrl', function($state, $stateParams, mcotcms, $scope, PUBLIC_TOKEN, $rootScope, $location, $filter, $timeout){
    $scope.id = $stateParams.id;
    console.log("vew ...");
    $scope.sideTab = 'breakingNews';
    mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'categories.text': "Breaking News"}})
        .then(function(success){
            console.log(" Breaking ");
            $scope.breakings = success.data.output;
            console.log($scope.breakings);
        });
    mcotcms.post_api(PUBLIC_TOKEN, "GET", {id: $scope.id})
        .then(function(success){
            $scope.post = success.data.output;
            $rootScope.title = success.data.output.title;
			$scope.cats = _.map($scope.post.categories, function(o) { return o.text }).join(',');
            $scope.catText = _.filter($scope.post.categories, function(o) {
                    if( o.text !== 'root' && o.text !== 'TNA' ) {
                        return true;
                    }else {
                        return false;
                    }
                } );
			$scope.tags = _.map($scope.post.focus_tags, function(o) { return o.text });
            if($scope.tags.length > 0 ) {
                mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'tags.text': {'$all': $scope.tags}, 'is_active': true }, limit: 25})
                    .then(function(success){
                        $scope.focusTags = success.data.output;
                    });
            }
			$rootScope.url = $location.absUrl();
			$rootScope.title = $scope.post.title;
			$rootScope.description  = $scope.post.description;
			$rootScope.image = $filter("image_server")($scope.post, "-600x315x2");

		});
})
.controller('ProgramCtrl', function($state,  $scope,  $timeout, $window,$rootScope){

})
.controller('IndexCtrl', function($state,  $scope,  $timeout, PUBLIC_TOKEN, $rootScope, $http, mcotcms){

    mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'categories.text': {'$all': ["OTT Top Story"]}, 'is_active': true}})
        .then(function(success){
            console.log('post ', success.data.output);
            $scope.topStory = success.data.output;
        });
    mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'categories.text': {'$all': ["OTT Top Picks"]}, 'is_active': true} , 'limit': 10})
        .then(function(success){
            $scope.topPicks = success.data.output;
        });

    mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'categories.text': {'$all': ["OTT Recommended"]}, 'is_active': true} , 'limit': 2})
        .then(function(success){
            $scope.recs = success.data.output;
        });
	$scope.ottCats.forEach(function(e) {

        mcotcms.post_api(PUBLIC_TOKEN, "LIST", {query: {'categories.text': {'$all': e.cat}, 'is_active': true} , 'limit': 10})
            .then(function(success){
                console.log('ott mmm ');
                $scope[e.varName] = success.data.output
            });
	});
	$timeout(function(){
		$(".regular").slick({
            dots: true,
            infinite: true,
            slidesToShow: 5,
            slidesToScroll: 5,
            autoplay: false,
            autoplaySpeed: 6000,
            responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    infinite: true,
                    dots: true
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            }
			]
		});
	}, 1000);
});
