/// <reference path="../app/views/diversos.html" />
/// <reference path="../app/views/diversos.html" />
/// <reference path="../app/views/teste1.html" />
var app = angular.module('cibe', ['ngRoute', 'ui.bootstrap', 'ngResource', 'angularFileUpload', 'ngAnimate', 'ngSanitize', 'ngProgress', 'ngTable', 'angucomplete-alt']);



app.config(['ngProgressProvider', function (ngProgressProvider) {
    ngProgressProvider.setColor('#bdd55f');
    ngProgressProvider.setHeight('3px');
}]);

app.config(['$routeProvider',
function ($routeProvider) {
    $routeProvider.
      when('/cadastro', {
          templateUrl: 'views/cadastro.html',
          controller: 'cadastroController',

      }).
      when('/diversos/:p', {
          //templateUrl: function (params) { return '/diversos/' + params.p },
          templateUrl: 'views/diversos.html',
          controller: 'diversosController'
      }).
      when('/diversos', {
          templateUrl: 'views/diversos.html',
          controller: 'diversosController'
      }).
      when('/local', {
          templateUrl: 'views/local.html',
          //controller: 'localCadastroController'
      }).
      when('/login', {
          templateUrl: 'views/login.html?v=' + new Date(),
          controller: 'loginController'
      }).
      when('/gestao', {
            templateUrl: 'views/gestao.html',
            //controller: 'localCadastroController'
      }).
      when('/plano', {
          templateUrl: 'views/planoManutencaoGeral.html',
          //controller: 'localCadastroController'
      }).
      otherwise({
          redirectTo: '/login'

      });
}]);





app.filter('filtroPerfil', function () {



    return function (arr, searchString) {

        if (!searchString) {
            return [];
        }

        var result = [];


        if (searchString == "")
            return result;

        angular.forEach(arr, function (item) {

            if (item.idperfil == searchString)
                result.push(item);
        });

        return result;
    };

});



app.filter('filtroNomeInventario', function () {

    return function (arr, searchString) {

        if (!searchString) {
            return arr;
        }

        var result = [];

        searchString = searchString.toLowerCase();

        angular.forEach(arr, function (item) {

            if (item.Nome.toLowerCase().indexOf(searchString) !== -1) {
                result.push(item);
            }
        });

        return result;
    };

});

app.filter('filtroAvancadoInventario', function () {

    return function (arr, searchString, procurarAbates, procurarLocal, procurarValor) {

        if (!searchString) {
            return arr;
        }

        var result = [];
        if (procurarLocal == null)
            procurarLocal = false;
        if (procurarAbates == null)
            procurarAbates = false;
        if (procurarValor == null)
            procurarValor = false;

        searchString = searchString.toLowerCase();

        angular.forEach(arr, function (item) {

            //if (procurarLocal == true) {
            //    if (item.Localizacao.toLowerCase().indexOf(searchString) !== -1) {
            //        result.push(item);
            //    }
            //}

            if (procurarLocal == false && procurarValor == false) {
                if (item.Nome.toLowerCase().indexOf(searchString) !== -1) {
                    result.push(item);
                }
            }

        });

        return result;
    };

});

app.controller("TabCadController", function ($scope, $location) {
    $scope.isActive = function (viewLocation) {

        return viewLocation === $location.path();
    };
});

app.factory("dataService", function () {
    var servico = {};
    servico.devDataHoje = function () {
        var dat = new Date();
        var dia = dat.getDate();
        if (dia < 10) { dia = "0" + dia; }
        var mes = dat.getMonth() + 1;
        if (mes < 10) { mes = "0" + mes; }


        return dat.getFullYear() + "-" + mes + "-" + dia;
    };

    servico.getDataStr = function (dat) {
        dat = dat.toString();
        dat = dat.substring(0, 10);
        var separa = dat.split('-');
        var ano = Number(separa[0]);
        var mes = Number(separa[1]);
        var dia = Number(separa[2]);
        
        if (dia < 10) { dia = "0" + dia; }
        if (mes < 10) { mes = "0" + mes; }


        return ano + "-" + mes + "-" + dia;
    };

    servico.dataIsValid = function (dat) {
        if (dat == null || dat == '')
            return false;
        dat = dat.toString();
        //if (dat == null || dat == '')
        //    return false;
        
        if (dat.length < 10)
            return false;
        dat = dat.substring(0, 10);
        var bits = dat.split('-');
        if (bits.length != 3)
            return false;

        var d = new Date(bits[0] + '-' + bits[1] + '-' + bits[2]);
        return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]));

    };

    servico.toDataStr = function (dat) {
        if (typeof dat == "string")
            return dat;
        if (dat == null)
            return "";
        var dia = dat.getDate();
        if (dia < 10) { dia = "0" + dia; }
        var mes = dat.getMonth() + 1;
        if (mes < 10) { mes = "0" + mes; }


        return dat.getFullYear() + "-" + mes + "-" + dia;
    };

    servico.toHHmmss=function(dat) {
        var current_datetime = new Date()
        var formatted_date = current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds();
        return formatted_date;
    };

    return servico;
});

app.factory("globalService", function () {
    var servico = {};
    servico.devListaMeses = function () {
        var lstMeses = [];
        lstMeses.push({ mes: 1, NomeMes: 'Janeiro' });
        lstMeses.push({ mes: 2, NomeMes: 'Fevereiro' });
        lstMeses.push({ mes: 3, NomeMes: 'Março' });
        lstMeses.push({ mes: 4, NomeMes: 'Abril' });
        lstMeses.push({ mes: 5, NomeMes: 'Maio' });
        lstMeses.push({ mes: 6, NomeMes: 'Junho' });
        lstMeses.push({ mes: 7, NomeMes: 'Julho' });
        lstMeses.push({ mes: 8, NomeMes: 'Agosto' });
        lstMeses.push({ mes: 9, NomeMes: 'Setembro' });
        lstMeses.push({ mes: 10, NomeMes: 'Outubro' });
        lstMeses.push({ mes: 11, NomeMes: 'Novembro' });
        lstMeses.push({ mes: 12, NomeMes: 'Dezembro' });

        return lstMeses;
    };

    return servico;
});

app.directive('ncgRequestVerificationToken', function ($http) {

    return function (scope, element, attrs) {

        $http.defaults.headers.common['RequestVerificationToken'] = attrs.ncgRequestVerificationToken || " ";
    };
});



app.directive('numberInput', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {

            ctrl.$parsers.push(function (inputValue) {

                var inputVal = element.val();

                //clearing left side zeros
                /*while (inputVal.charAt(0) == '0') {
                    
                    inputVal = inputVal.substr(1);
                }*/

                inputVal = inputVal.replace(/[^\d.\',']/g, '');

                var point = inputVal.indexOf(".");
                if (point >= 0) {
                    inputVal = inputVal.slice(0, point + 5); //4 casas decimais
                }

                var decimalSplit = inputVal.split(".");
                var intPart = decimalSplit[0];
                var decPart = decimalSplit[1];

                intPart = intPart.replace(/[^\d]/g, '');
                if (intPart.length > 3) {
                    var intDiv = Math.floor(intPart.length / 3);
                    while (intDiv > 0) {
                        var lastComma = intPart.indexOf(",");
                        if (lastComma < 0) {
                            lastComma = intPart.length;
                        }

                        if (lastComma - 3 > 0) {
                            //intPart = intPart.slice(0, lastComma - 3) + "," + intPart.slice(lastComma - 3);
                            intPart = intPart.slice(0, lastComma - 3) + "" + intPart.slice(lastComma - 3);
                        }
                        intDiv--;
                    }
                }

                if (decPart === undefined) {
                    decPart = "";
                }
                else {
                    decPart = "." + decPart;
                }
                var res = intPart + decPart;



                if (res != inputValue) {
                    ctrl.$setViewValue(res);
                    ctrl.$render();
                }
                return res;
            });

        }
    };
});


app.directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                // this next if is necessary for when using ng-required on your input. 
                // In such cases, when a letter is typed first, this parser will be called
                // again, and the 2nd time, the value will be undefined
                if (inputValue == undefined) return ''
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});



// register the interceptor as a service
// intercepts ALL angular ajax HTTP calls
app.factory('errorHttpInterceptor',
function ($q, $location, $rootScope) {

    return function (promise) {
        return promise.then(function (response) {
            return response;
        }, function (response) {
            if (response.status === 401) {

                $location.path('/login');
                //$rootScope.$broadcast('event:loginRequired');
            } else if (response.status >= 400 && response.status < 500) {

            }
            return $q.reject(response);
        });
    };
});

//app.config(function ($httpProvider) {

//    $httpProvider.responseInterceptors.push('errorHttpInterceptor');
//});


app.animation('.myfade', function ($location) {


    return {
        enter: function (element, done) {

            if ($location.path() == "/login")
                return;
            element.css('opacity', 0.1);
            element.css('transform', "scale(0.1,0.1");
            jQuery(element).animate({
                opacity: 1,
                transform: 'scale(1,1)'
            }, 500, "linear", done);

            // optional onDone or onCancel callback
            // function to handle any post-animation
            // cleanup operations
            return function (isCancelled) {
                if (isCancelled) {
                    jQuery(element).stop();
                }
            }
        },
        leave: function (element, done) {

            element.css('opacity', 1);
            element.css('transform', "scale(1,1");
            jQuery(element).animate({
                opacity: 0,
                transform: 'scale(0.5,0.5)'
            }, 100, "linear", done);

            // optional onDone or onCancel callback
            // function to handle any post-animation
            // cleanup operations
            return function (isCancelled) {
                if (isCancelled) {
                    jQuery(element).stop();
                }
            }
        },
        move: function (element, done) {
            element.css('opacity', 0);
            jQuery(element).animate({
                opacity: 1
            }, 0, "linear", done);

            // optional onDone or onCancel callback
            // function to handle any post-animation
            // cleanup operations
            return function (isCancelled) {
                if (isCancelled) {
                    jQuery(element).stop();
                }
            }
        },

        // you can also capture these animation events
        addClass: function (element, className, done) { },
        removeClass: function (element, className, done) { }
    }
});



app.factory('Base64', function () {
    var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    return {
        encode: function (input) {
            var output = "";
            var chr1, chr2, chr3 = "";
            var enc1, enc2, enc3, enc4 = "";
            var i = 0;

            input = this._utf8_encode(input);

            do {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);

                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;

                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }

                output = output +
                    keyStr.charAt(enc1) +
                    keyStr.charAt(enc2) +
                    keyStr.charAt(enc3) +
                    keyStr.charAt(enc4);
                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";
            } while (i < input.length);

            return output;
        },

        decode: function (input) {
            var output = "";
            var chr1, chr2, chr3 = "";
            var enc1, enc2, enc3, enc4 = "";
            var i = 0;

            // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
            var base64test = /[^A-Za-z0-9\+\/\=]/g;
            if (base64test.exec(input)) {
                alert("There were invalid base64 characters in the input text.\n" +
                    "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                    "Expect errors in decoding.");
            }
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

            do {
                enc1 = keyStr.indexOf(input.charAt(i++));
                enc2 = keyStr.indexOf(input.charAt(i++));
                enc3 = keyStr.indexOf(input.charAt(i++));
                enc4 = keyStr.indexOf(input.charAt(i++));

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                output = output + String.fromCharCode(chr1);

                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }

                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";

            } while (i < input.length);

            output = this._utf8_decode(output);

            return output;
        },

        // private method for UTF-8 encoding
        _utf8_encode: function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utftext += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }

            return utftext;
        },

        // private method for UTF-8 decoding
        _utf8_decode: function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;

            while (i < utftext.length) {

                c = utftext.charCodeAt(i);

                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                }
                else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                }
                else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }

            }

            return string;
        }

    };
});


$(document).keydown(function (e) {
    var elid = $(document.activeElement).is('input:focus, textarea:focus, #editableDiv:focus');

    if (e.keyCode === 8 && !elid) {
        return false;
    };
});


app.directive("contenteditable", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {

            function read() {
                ngModel.$setViewValue(element.html());
            }

            ngModel.$render = function () {
                element.html(ngModel.$viewValue || "");
            };

            element.bind("blur keyup change", function () {
                scope.$apply(read);
            });
        }
    };
});

app.directive('utFocus', function ($timeout) {
    return {
        link: function (scope, elem, attr) {
            var focusTarget = attr['utFocus'];
            scope.$watch(focusTarget, function (value) {
                $timeout(function () {
                    elem[0].focus();
                }, 500);
            });
        }
    }
});

app.controller("CollapseGeralCtrl", function ($scope) {
    
    $scope.isCollapsed = false;
   

    $scope.toggle = function () {
        $scope.isCollapsed = !$scope.isCollapsed;
    };

    $scope.setCollapse = function (estado) {
        $scope.isCollapsed = estado;
    };
});

app.controller("PlanoContasCtrl", function ($scope, httpRequestFactory, notificationFactory, ngProgress, $modal, $upload) {
    $scope.estaGravar = false;

    $scope.lstContas = [];
    $scope.setListaContas = function (lst) {
        $scope.lstContas = lst
    }

    $scope.validaDados = function (dados) {
        if (dados.ContaSNC == '') {
            notificationFactory.error("Conta inválida");
            return false;
        }
        if (dados.Descricao == '') {
            notificationFactory.error("Descrição inválida");
            return false;
        }

        return true;
    };

    $scope.gravaContaPlano = function (dados) {

        if ($scope.validaDados(dados) == false)
            return;

        var getSuccessCallback = function (data, status) {
            notificationFactory.success(data);
            ngProgress.complete();
            $scope.estaGravar = false;
        };

        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
            ngProgress.reset();
            $scope.estaGravar = false;
        };

        httpRequestFactory.postData('../api/SNC/contabilidade/plano/gravarConta', dados).success(getSuccessCallback).error(errorCallback);
        ngProgress.start();
        $scope.estaGravar = true;
    };

    $scope.modalEditaConta = function (info, ano, callbackOk, args) {

        if (info == null) {
            info = {
                ContaSNC: '',
                VidaUtilControlo: 0,
                Descricao: '',
                Ativa: true,
                AnoEconomico: ano,
                Pk_Conta: 0
            };
        }
        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalEditarConta.html',
            controller: 'modalController',
            size: 'md',
            resolve: {
                items: function () { return info; }
            }
        });

        modalInstance.result.then(function (item) {
            if (callbackOk!=null)
                callbackOk.apply(this, args);
        }, function () {

        });
    };

   

    //$scope.lstDadosContas = [];
    $scope.onFileContasPlanoExcel = function ($files, ano, callbackOk, args) {
        $scope.estaGravar = false;
        var $file = $files[0];
        (function (index) {
            $upload.upload({
                url: "../api/SNC/contabilidade/plano/importar/Excel/"+ano,
                method: "POST",
                file: $file
            }).progress(function (evt) {
                // get upload percentage
                $scope.uploadprogress = parseInt(100.0 * evt.loaded / evt.total);
                $scope.estaGravar = true;

            }).success(function (data, status, headers, config) {
                if (data.Success == false) {
                    notificationFactory.error(data.Message);
                }
                else {
                    notificationFactory.success('Concluido');
                    //$scope.lstDadosContas = data.Dados;
                    //console.log($scope.lstDadosContas);
                    if (callbackOk != null)
                        callbackOk.apply(this, args);
                }
                $scope.estaGravar = false;
            }).error(function (data, status, headers, config) {
                notificationFactory.error(data);
                $scope.estaGravar = false;
            });

        })(0);

    };
});

app.controller("ClassificacaoEconomicaCtrl", function ($scope, httpRequestFactory, notificationFactory, ngProgress, $modal, $upload) {
    $scope.estaGravar = false;

   
    $scope.validaDados = function (dados) {
        if (dados.Val1 == '' || dados.Val2 == '' || dados.Val3 == '') {
            notificationFactory.error("Classificação inválida");
            return false;
        }
        if (dados.Descricao == '') {
            notificationFactory.error("Descrição inválida");
            return false;
        }

        return true;
    };

    $scope.gravaClEconomica = function (dados) {

        if ($scope.validaDados(dados) == false)
            return;

        var getSuccessCallback = function (data, status) {
            notificationFactory.success(data);
            ngProgress.complete();
            $scope.estaGravar = false;
        };

        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
            ngProgress.reset();
            $scope.estaGravar = false;
        };

        httpRequestFactory.postData('../api/cleconomica/gravar', dados).success(getSuccessCallback).error(errorCallback);
        ngProgress.start();
        $scope.estaGravar = true;
    };

    $scope.modalEditaClEconomica = function (info, callbackOk, args) {

        if (info == null) {
            info = {
                Val1: '',
                Val2: '',
                Val3: '',
                Value: '',
                Descricao: ''
            };
        }
        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalEditarClEconomica.html',
            controller: 'modalController',
            size: 'md',
            resolve: {
                items: function () { return info; }
            }
        });

        modalInstance.result.then(function (item) {
            if (callbackOk != null)
                callbackOk.apply(this, args);
        }, function () {

        });
    };


});
