'use strict';

var LedgerCtrl = ['$scope', '$routeParams', '$location', 'ledger', 'Ledger', function ($scope, $routeParams, $location, ledger, Ledger) {
    $scope.info = ledger;
    $scope.show = function () {
        var id = $scope.info.Ledger.LedgerID;
        var start_date = $scope.info.StartDate;
        var finish_date = $scope.info.FinishDate;
        if (id == $routeParams.id && start_date == $routeParams.StartDate && finish_date == $routeParams.FinishDate) {
            Ledger.get({id:id, StartDate:start_date, FinishDate:finish_date}, function (data) {
                $scope.info = data;
            });
        }
        else {
            $location.path('/Ledger/' + $scope.info.Ledger.LedgerID).search('StartDate', $scope.info.StartDate).search('FinishDate', $scope.info.FinishDate);
        }
    };
    $scope.downloadTable = function () {
        var table = $('#gvGrid'),
            html = table.clone().wrap('<div></div>').parent().html();
        html = html.replace(/á/g, '&aacute;');
        window.open('data:application/vnd.ms-excel;charset=UTF-8,' + encodeURIComponent(html));
    }
    $('#txtLedger').focus();
}]

LedgerCtrl.resolve = {
    ledger:['$q', '$route', 'Ledger', function ($q, $route, Ledger) {
        var deferred = $q.defer();

        var id = $route.current.params.id;
        var start_date = $route.current.params.StartDate;
        var finish_date = $route.current.params.FinishDate;

        var successCb = function (result) {
            deferred.resolve(result);
        };

        if (typeof id === 'undefined') {
            Ledger.get({}, successCb);
        } else {
            Ledger.get({id:id, StartDate:start_date, FinishDate:finish_date}, successCb);
        }
        return deferred.promise;
    }]
};


