'use strict'
angular.module('angular-tour', ['angular-tour.tour']);
 
var app = angular.module("mindinkApp", [
	'mindinkControllers',
	'mindinkServices',
	'ngRoute',
    'ngCookies',
    'restangular',
    'ui.bootstrap',
	'ngSanitize',
    'ga',
    'ngTouch',
	'angular-tour', 
	'ivpusic.cookie'
	]); 

app.config(['$routeProvider', '$locationProvider', '$httpProvider', 'RestangularProvider', function($routeProvider, $locationProvider, $httpProvider, RestangularProvider) {
        $locationProvider.html5Mode(true);
        RestangularProvider.setBaseUrl(apiUrl);
        RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});

        $routeProvider.
            when('/index', {
                templateUrl: 'viewindex'
            }).
            when('/mindink', {
                templateUrl: 'viewmindink' ,
                controller: 'updateAccountCtrl'
            }).
            when('/viewProfile', {
                templateUrl: 'viewmindink' ,
                controller: 'updateAccountCtrl'
            }).
            when('/joinmindink', {
                templateUrl: 'viewjoinmindink',
                controller: 'userCtrl'
            }).
            when('/signin', {
                templateUrl: 'viewsignin'
            }).
            when('/useractivation', {
                templateUrl: 'viewuseractivation',
                controller: 'userCtrl'
            }).
            when('/activationerror', {
                templateUrl: 'viewactivationerror',
                controller: 'userCtrl'
            }).
            when('/emailsignin', {
                templateUrl: 'viewemailsignin',
                controller: 'userCtrl'
            }).
            when('/forgotpassword', {
                templateUrl: 'viewforgotpassword',
                controller: 'userCtrl'
            }).
            when('/forgotpasswordsent', {
                templateUrl: 'viewforgotpasswordsent'
            }).
            when('/resetpassword', {
                templateUrl: 'viewresetpassword',
                controller: 'userCtrl'
            }).
            when('/resetpasswordsent', {
                templateUrl: 'viewresetpasswordsent'
            }).
            when('/reader', {
                templateUrl: 'viewreader',
                controller: 'readerCtrl'
            }).
            when('/register', {
                templateUrl: 'viewregister',
                controller: 'userCtrl'
            }).
            when('/reader/book/:ISBN', {
                templateUrl: '/ereader',
                controller: 'ereaderCtrl',
                resolve:{
                    epubLocation: function(){
                        return '/content/books/';
                    }
                }
            }).
            when('/reader/preview/:ISBN', {
                templateUrl: '/ereader',
                controller: 'ereaderCtrl',
                resolve:{
                    epubLocation: function(){
                        return '/content/mindink/books/preview/';
                    }
                }
            }).
            otherwise({
                redirectTo: '/mindink'
            });
}]);

app.run(['$rootScope', 'mindinkUser','ga', '$location', 'ieVersion', function($rootScope, mindinkUser, ga, $location, ieVersion){
    mindinkUser.getCurrentUser().then(function(user){
        $rootScope.currentUser = user;

        //Tracking Page View
        $rootScope.$on("$viewContentLoaded", function($scope, next, current){
            ga('send','pageview', $location.path());
        });
    }, function(){
        console.log("Not logged in");
    });

    $rootScope.ieVersion = ieVersion;
    if ($rootScope.ieVersion != -1 && $rootScope.ieVersion < 10.0){
        window.location.href='/html/browserupgrade.html';
    }

    $rootScope.isTouch = Modernizr.touch;
    $rootScope.isIos = /iPhone|iPad|iPod/i.test(navigator.userAgent);

}]);

app.factory('ieVersion', [function(){
    return (function(){

        var rv = -1; // Return value assumes failure.

        // check ie 10 or below, coz ie 11 will use "Netscape" as appName.
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.test(ua) != null)
                rv = parseFloat( RegExp.$1 );
        }

        return rv;
    })();
}]);

app.directive('onlyNumber', function() {
    return {
        restrict: 'A',
        scope: {
            max: '='
        },
        link: function(scope, element, attrs) {

            var keyCodes = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
            var directions = [8, 9, 37, 38, 39, 40];

            element.bind("keydown", function(event) {
                var selection = attrs.$$element[0].selectionEnd - attrs.$$element[0].selectionStart;
                var noOfChar = attrs.$$element[0].value.length;
                if((keyCodes.indexOf(event.which) == -1) || (directions.indexOf(event.which) == -1 && noOfChar >= scope.max && selection == 0)) {
                    scope.$apply(function (){
                        scope.$eval(attrs.onlyNumber);
                        event.preventDefault();
                    });

                    event.preventDefault();
                }
            });
        }
    }
});

app.directive('stopEvent', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('click', function (e) {
                e.stopPropagation();
            });
        }
    };
});

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

app.directive('markdown', function () {
    var converter = new Showdown.converter();
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var htmlText = converter.makeHtml(element.text());
            element.html(htmlText);
        }
    };
});

app.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                        element.parent().parent().children().find('img').css("display","none");
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);

app.service("MiEndpoint",[function(){
    return{
        getAvatarPath: function(id, size){
            var size = size || 'small';
            return '/content/users/'+id+'/avatar/'+size;
        },
        getBookCoverPath: function(isbn, size){
            var size = size || 'small';
            return '/content/mindink/books/'+isbn+'/cover/'+size;
        }
    };
}]);

app.filter("timeago", function () {
    //time: the time
    //local: compared to what time? default: now
    //raw: wheter you want in a format of "5 minutes ago", or "5 minutes"
    return function (time, local, raw) {
        if (!time) return "never";

        if (!local) {
            (local = Date.now())
        }

        if (angular.isDate(time)) {
            time = time.getTime();
        } else if (typeof time === "string") {
            time = new Date(time).getTime();
        }

        if (angular.isDate(local)) {
            local = local.getTime();
        }else if (typeof local === "string") {
            local = new Date(local).getTime();
        }

        if (typeof time !== 'number' || typeof local !== 'number') {
            return;
        }

        var
            offset = Math.abs((local - time) / 1000),
            span = [],
            MINUTE = 60,
            HOUR = 3600,
            DAY = 86400,
            WEEK = 604800,
            MONTH = 2629744,
            YEAR = 31556926,
            DECADE = 315569260;

        if (offset <= MINUTE)              span = [ '', raw ? 'now' : 'less than a minute' ];
        else if (offset < (MINUTE * 60))   span = [ Math.round(Math.abs(offset / MINUTE)), 'min' ];
        else if (offset < (HOUR * 24))     span = [ Math.round(Math.abs(offset / HOUR)), 'hr' ];
        else if (offset < (DAY * 7))       span = [ Math.round(Math.abs(offset / DAY)), 'day' ];
        else if (offset < (WEEK * 52))     span = [ Math.round(Math.abs(offset / WEEK)), 'week' ];
        else if (offset < (YEAR * 10))     span = [ Math.round(Math.abs(offset / YEAR)), 'year' ];
        else if (offset < (DECADE * 100))  span = [ Math.round(Math.abs(offset / DECADE)), 'decade' ];
        else                               span = [ '', 'a long time' ];

        span[1] += (span[0] === 0 || span[0] > 1) ? 's' : '';
        span = span.join(' ');

        if (raw === true) {
            return span;
        }
        return (time <= local) ? span + ' ago' : 'in ' + span;
    }
});

app.directive('onFinishRender', ['$timeout',function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            var id = attr.onFinishRender;
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished', id);
                });
            }
        }
    }
}]);

app.directive('updateOnResize', ['$window',function ($window) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            var id = attr.updateOnResize;

            var timeout;
            angular.element($window).bind('resize', function () {

                // throttle resize;
                clearTimeout(timeout);
                timeout = setTimeout(function(){
                    scope.$emit('ngRepeatFinished', id);
                }, 200);

            });

        }
    }
}]);

app.directive('anyaxisScroll', ['$timeout',function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {

            var mouseWheelEvt = function (e)
            {

                var event = e || window.event;
                if (document.body.doScroll){
                    console.log(event.wheelDelta>0?"left":"right");
                }

                if (event.axis == 2 || event.wheelDeltaY || event.deltaY)
                    element[0].scrollLeft = element[0].scrollLeft + (event.wheelDelta || event.detail)

                //return false;
            }
            if ("onmousewheel" in document.body)
                element[0].onmousewheel = mouseWheelEvt;
            else
                element[0].addEventListener("DOMMouseScroll", mouseWheelEvt);

        }
    }
}]);

//@mention Component
app.controller('TypeaheadCtrl', function($scope, $http, filterFilter, $rootScope, $window) {
   
        $scope.states = [];
	$rootScope.sub = '';
	$scope.onKeyPressResult = "";
	$scope.dat22 = [];
	$scope.name = [];
	$scope.email = [];
	$scope.arrayNew = [];
        $rootScope.endpt = "";
	$rootScope.userinfo = [];
        var first_endpt = 0;
        
  
	$scope.onKeyPress = function ($event) {
           $scope.onKeyPressResult = $event.charCode;
        };
    
        $scope.$watch("typehead", function editorListener() {
            var editor = $window.document.getElementById("typehead");
            var start = editor.selectionStart;
            $rootScope.endpt = editor.selectionEnd;
        });    
        
        $scope.dat2 = [ {'name':'John','id':'1','mail':'john@mail.com'}, 
                        {'name':'Sam','id':'2','mail':'Sam@mail.com'},
                        {'name':'Stuart','id':'3','mail':'stuart@mail.com'},
                        {'name':'Vincent','id':'4','mail':'vincent@mail.com'},
                        {'name':'Williamson','id':'5','mail':'williamson@mail.com'},
                        {'name':'Abraham','id':'6','mail':'abraham@mail.com'},
                        {'name':'Fleming','id':'7','mail':'fleming@mail.com'},
                        {'name':'Anthony','id':'8','mail':'adeane@mindink.com'},
                        {'name':'Mark Benz','id':'9','mail':'markben@mail.com'},
                        {'name':'Luke Wright','id':'10','mail':'ukwright@mail.com'},
                        {'name':'Mention','id':'11','mail':'mention@mail.com'}];

        $scope.arrayNew.push($scope.dat2);

        angular.forEach($scope.arrayNew,function(data){
            for(var i=0; i<data.length; i++){
               $scope.name.push(data[i].name+data[i].id);
               $scope.email.push(data[i].mail);
            }
        });
        $rootScope.set_user_val = function(param) {
             $scope.user_email = param.substring(param.lastIndexOf('~~')+1);
             $rootScope.userinfo.push($scope.user_email);
        }
       
	$scope.gettest = function(param){
	
            $rootScope.sub = $scope.typehead;

            if($scope.onKeyPressResult === 64) {

                $scope.genData = function(key){

                    $scope.keypt = key.substring(0,$rootScope.endpt);

                    $rootScope.key = $scope.keypt.substring($scope.keypt.lastIndexOf("@") + 1);             
                   
                    if(($rootScope.key.length >= 1) && ($scope.onKeyPressResult != 8) && ($rootScope.key.length != 2) &&  $scope.typehead.length > 1) {

                       $scope.filterval = filterFilter($scope.name, $rootScope.key);
                        
                       return $scope.filterval;
                    }
                }
            }
        }
  
        $scope.comment = [];
          $scope.btn_add = function() {
            if($scope.typehead !==''){            
                $scope.comment.push($scope.typehead);
                $scope.typehead = "";
                
             }
        };
    $scope.remItem = function($index) {
        $scope.comment.splice($index, 1);
    }; 
 
});
app.filter('tweetLinky',['$filter',
    function($filter) {
        return function(text, target) {
            if (!text) return text;

            var replacedText = $filter('linky')(text, target);

            var targetAttr = "";
            if (angular.isDefined(target)) {
                targetAttr = ' target="' + target + '"';
            }
            // replace #hashtags and send them to twitter
            var replacePattern1 = /(^|\s)#(\w*[a-zA-Z_]+\w*)/gim;
            replacedText = text.replace(replacePattern1, '$1<a href="https://mindink.com/search?q=%23$2"' + targetAttr + '>#$2</a>');
            
            // replace @mentions but keep them to our site
            var replacePattern2 = /(^|\s)\@(\w*[a-zA-Z_]+\w*)/gim;
            replacedText = replacedText.replace(replacePattern2, '$1</div><div><a href="https://mindink.com/$2"' + targetAttr + '>@$2</a></div><div>');
            replacedText = "<div>"+replacedText+"</div>";

            return replacedText;
        };

    }
]);

app.controller('TourCtrl', function($scope, ipCookie) {
		  // load from cookie if possible, otherwise set step to 0
		  $scope.currentStep = ipCookie('myTour') || 0;

		  // callback for when we've finished going through the tour
		  $scope.postTourCallback = function() {
			console.log('tour over');
		  };

		  // optional way of saving tour progress with cookies
		  $scope.postStepCallback = function() {
			ipCookie('myTour', $scope.currentStep, { expires: 3000 });
		  };      

		}); 
