// Source: src/js/app.js
var modules = [
  'ngAnimate',
  'ngLodash',
  'ngResource',
  'ngRoute',
  'ngProgress',
  'ui.bootstrap',
  'ui.route',
  'monospaced.qrcode',
  'gettext',
  'angularMoment',
  'owsExplorerApp.controllers',
  'owsExplorerApp.directives',
  'owsExplorerApp.filters',
  'owsExplorerApp.models',
  'owsExplorerApp.services',
  'owsExplorerApp.translations',
];

var owsExplorerApp = angular.module('owsExplorerApp', modules);

angular.module('owsExplorerApp.controllers', []);
angular.module('owsExplorerApp.directives', []);
angular.module('owsExplorerApp.filters', []);
angular.module('owsExplorerApp.models', []);
angular.module('owsExplorerApp.services', []);
angular.module('owsExplorerApp.translations', []);

// Source: src/js/controllers/address.js
angular.module('owsExplorerApp.controllers').controller('AddressController', function($scope, $rootScope, $routeParams, $location, Address, SocketService) {
  var addrStr = $routeParams.addrStr;
  var socket;

  var _init = function() {
    socket = SocketService.getSocket($scope);
    if (!socket) return;

    if (!socket.isConnected()) {
      socket.on('connect', function() {
        _startSocket();
        _refresh();
      });
    } else {
      _startSocket();
      _refresh();
    }
  };

  var _refresh = function() {
    $scope.findOne();
  };

  $rootScope.$on('Local/SocketChange', function(event) {
    _init();
  });

  $scope.$on('$destroy', function() {
    _stopSocket();
  });

  var _startSocket = function() {
    socket.on('node/addresstxid', function(data) {
      if (data.address === addrStr) {
        $rootScope.$broadcast('tx', data.txid);
        var base = document.querySelector('base');
        var beep = new Audio(base.href + '/sound/transaction.mp3');
        beep.play();
      }
    });
    socket.emit('subscribe', 'node/addresstxid', [addrStr]);
  };

  var _stopSocket = function () {
    socket.emit('unsubscribe', 'node/addresstxid', [addrStr]);
  };

  $scope.findOne = function() {
    $rootScope.currentAddr = $routeParams.addrStr;
    _startSocket();

    Address.get({
        addrStr: $routeParams.addrStr
      },
      function(address) {
        $rootScope.titleDetail = address.addrStr.substring(0, 7) + '...';
        $rootScope.flashMessage = null;
        $scope.address = address;
      },
      function(e) {
        if (e.status === 400) {
          $rootScope.flashMessage = 'Invalid Address: ' + $routeParams.addrStr;
        } else if (e.status === 503) {
          $rootScope.flashMessage = 'Backend Error. ' + e.data;
        } else {
          $rootScope.flashMessage = 'Address Not Found';
        }
        $location.path('/');
      });
  };

  _init();

});

// Source: src/js/controllers/blocks.js
angular.module('owsExplorerApp.controllers').controller('BlocksController', function($timeout, $scope, $rootScope, $routeParams, $location, Block, Blocks, BlockByHeight) {
  $scope.loading = false;
  $scope.calendar = {
    open: false
  };

  $rootScope.$on('Local/SocketChange', function(event) {
    _init();
  });

  var _init = function() {
    if ($routeParams.blockHeight) {
      $scope.findByHeight();
    } else if ($routeParams.blockHash) {
      $scope.findOne();
    } else {
      $scope.list();
    }
  };

  //Datepicker
  var _formatTimestamp = function (date) {
    var yyyy = date.getUTCFullYear().toString();
    var mm = (date.getUTCMonth() + 1).toString(); // getMonth() is zero-based
    var dd  = date.getUTCDate().toString();

    return yyyy + '-' + (mm[1] ? mm : '0' + mm[0]) + '-' + (dd[1] ? dd : '0' + dd[0]); //padding
  };

  $scope.$watch('calendar.dt', function(newValue, oldValue) {
    if (newValue !== oldValue) {
      $location.path('/blocks-date/' + _formatTimestamp(newValue));
    }
  });

  $scope.openCalendar = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.calendar.open = true;
  };

  $scope.humanSince = function(time) {
    var m = moment.unix(time).startOf('day');
    var b = moment().startOf('day');
    return m.max().from(b);
  };

  $scope.list = function() {
    $scope.loading = true;

    if ($routeParams.blockDate) {
      var parts = $routeParams.blockDate.split('-');
      $scope.calendar.dt = new Date(parts[0], parts[1]-1, parts[2]); 
    } else {
      $scope.calendar.dt = new Date();
    }

    if ($routeParams.startTimestamp) {
      var d=new Date($routeParams.startTimestamp*1000);
      var m=d.getMinutes();
      if (m<10) m = '0' + m;
      $scope.before = ' before ' + d.getHours() + ':' + m;
    }

    Blocks.get({
      blockDate: $routeParams.blockDate,
      startTimestamp: $routeParams.startTimestamp
    }, function(res) {
      $scope.loading = false;
      $scope.blocks = res.blocks;
      $scope.pagination = res.pagination;
    });
  };

  $scope.findByHeight = function() {
    BlockByHeight.get({
      blockHeight: $routeParams.blockHeight
    }, function(hash) {
      $location.path('/block/' + hash.blockHash);
    }, function() {
      $rootScope.flashMessage = 'Bad Request';
      $location.path('/');
    });
  };

  $scope.findOne = function() {
    $scope.loading = true;

    Block.get({
      blockHash: $routeParams.blockHash
    },
    function(block) {
      $rootScope.titleDetail = block.height;
      $rootScope.flashMessage = null;
      $scope.loading = false;
      $scope.block = block;
    }, function(e) {
      if (e.status === 400) {
        $rootScope.flashMessage = 'Invalid Transaction ID: ' + $routeParams.txId;
      }
      else if (e.status === 503) {
        $rootScope.flashMessage = 'Backend Error. ' + e.data;
      }
      else {
        $rootScope.flashMessage = 'Block Not Found';
      }
      $location.path('/');
    });
  };

  _init();

});

// Source: src/js/controllers/connection.js
angular.module('owsExplorerApp.controllers').controller('ConnectionController', function($rootScope, $scope, $window, Status, SocketService, PeerSync, NodeService) {
  // Set initial values
  $scope.statusUpdate = false;
  $scope.errorAlertDismissed = false;
  $scope.apiOnline = true;
  $scope.serverOnline = true;
  $scope.clientOnline = true;

  var socket;

  var _init = function() {
    socket = SocketService.getSocket($scope);
    if (!socket) return;

    socket.on('connect', function() {
      $scope.serverOnline = true;
      socket.on('disconnect', function() {
        $scope.serverOnline = false;
        $scope.errorAlertDismissed = false;
      });
      _refresh();
    });

    socket.emit('subscribe', 'sync');
    socket.on('status', function(sync) {
      $scope.sync = sync;
      $scope.apiOnline = (sync.status !== 'aborted' && sync.status !== 'error');
    });
  };

  var _refresh = function() {
    $scope.getConnStatus();
  };

  $rootScope.$on('Local/SocketChange', function(event) {
    _init();
  });

  $scope.closeErrorAlert = function() {
    $scope.errorAlertDismissed = true;
  };

  $scope.closeInfoAlert = function() {
    $scope.statusUpdate = false;
  };

  // Check for the  api connection
  $scope.getConnStatus = function() {
    $scope.connectedNode = NodeService.getNode();

    PeerSync.get({},
      function(peer) {
        $scope.apiOnline = peer.connected;
        $scope.statusUpdate = true;
      },
      function() {
        $scope.apiOnline = false;
        $scope.errorAlertDismissed = false;
      });
  };

  // Check for the client connection
  $window.addEventListener('offline', function() {
    $scope.$apply(function() {
      $scope.clientOnline = false;
      $scope.errorAlertDismissed = false;
    });
  }, true);

  $window.addEventListener('online', function() {
    $scope.$apply(function() {
      $scope.clientOnline = true;
      $scope.statusUpdate = true;
    });
  }, true);

  _init();

});

// Source: src/js/controllers/header.js
angular.module('owsExplorerApp.controllers').controller('HeaderController', function($scope, $rootScope, $uibModal, SocketService, Block, NodeService, CurrencyService) {
  $rootScope.isCollapsed = true;

  $scope.menu = [{
    'title': 'Blocks',
    'link': 'blocks'
  }, {
    'title': 'Status',
    'link': 'status'
  }];

  var socket;

  var _init = function() {
    socket = SocketService.getSocket($scope);
    if (!socket) return;

    socket.emit('subscribe', 'inv');

    socket.on('block', function(block) {
      var blockHash = block.toString();
      _getBlock(blockHash);
    });
  };

  $rootScope.$on('Local/NodeChange', function(event, data) {
    $scope.node = data.newNode;
  });

  $rootScope.$on('Local/SocketChange', function(event) {
    _init();
  });

  $rootScope.getCurrencyConversion = function(value) {
    return CurrencyService.getCurrencyConversion(value);
  };

  $scope.openScannerModal = function() {
    var modalInstance = $uibModal.open({
      templateUrl: 'scannerModal.html',
      controller: 'ScannerController'
    });
  };

  var _getBlock = function(hash) {
    Block.get({
      blockHash: hash
    },
    function(res) {
      $scope.totalBlocks = res.height;
    });
  };

  _init();

});

// Source: src/js/controllers/index.js
angular.module('owsExplorerApp.controllers').controller('IndexController', function($rootScope, $scope, SocketService, Blocks) {
  var TRANSACTION_DISPLAYED = 10;
  var BLOCKS_DISPLAYED = 5;
  var socket;

  var _init = function() {
    socket = SocketService.getSocket($scope);
    if (!socket) return;

    if (!socket.isConnected()) {
      socket.on('connect', function() {
        _startSocket();
        _refresh();
      });
    } else {
      _startSocket();
      _refresh();
    }
  };

  var _refresh = function() {
    $scope.txs = [];
    $scope.blocks = [];
    _getBlocks();
  };

  $rootScope.$on('Local/SocketChange', function(event) {
    _init();
  });

  var _getBlocks = function() {
    Blocks.get({
      limit: BLOCKS_DISPLAYED
    }, function(res) {
      $scope.blocks = res.blocks;
      $scope.blocksLength = res.length;
    });
  };

  var _startSocket = function() { 
    socket.emit('subscribe', 'inv');

    socket.on('tx', function(tx) {
      $scope.txs.unshift(tx);
      if (parseInt($scope.txs.length, 10) >= parseInt(TRANSACTION_DISPLAYED, 10)) {
        $scope.txs = $scope.txs.splice(0, TRANSACTION_DISPLAYED);
      }
    });

    socket.on('block', function() {
      _getBlocks();
    });
  };

  $scope.closeFlashAlert = function() {
    $rootScope.flashMessage = null;
  };

  $scope.humanSince = function(time) {
    var m = moment.unix(time);
    return m.max().fromNow();
  };

  _init();

});

// Source: src/js/controllers/message.js
angular.module('owsExplorerApp.controllers').controller('MessageController', function($scope, $http, NodeService) {
  $scope.message = {
    address: '',
    signature: '',
    message: ''
  };

  $scope.verification = {
    status: 'unverified',  // ready|loading|verified|error
    result: null,
    error: null,
    address: ''
  };

  $scope.verifiable = function() {
    return ($scope.message.address
            && $scope.message.signature
            && $scope.message.message);
  };

  $scope.verify = function() {
    $scope.verification.status = 'loading';
    $scope.verification.address = $scope.message.address;
    $http.post(NodeService.getNode().api + '/messages/verify', $scope.message)
      .then(function(data, status, headers, config) {
        if(typeof(data.result) != 'boolean') {
          // API returned 200 but result was not true or false
          $scope.verification.status = 'error';
          $scope.verification.error = null;
          return;
        }

        $scope.verification.status = 'verified';
        $scope.verification.result = data.result;
      }, function(data, status, headers, config) {
        $scope.verification.status = 'error';
        $scope.verification.error = data;
      });
  };

  // Hide the verify status message on form change
  var unverify = function() {
    $scope.verification.status = 'unverified';
  };

  $scope.$watch('message.address', unverify);
  $scope.$watch('message.signature', unverify);
  $scope.$watch('message.message', unverify);

});

// Source: src/js/controllers/rawTransaction.js
angular.module('owsExplorerApp.controllers').controller('RawTransactionController', function($scope, $http, NodeService) {
  $scope.transaction = '';
  $scope.status = 'ready';  // ready|loading|sent|error
  $scope.txid = '';
  $scope.error = null;

  $scope.formValid = function() {
    return !!$scope.transaction;
  };
  
  $scope.send = function() {
    var postData = {
      rawtx: $scope.transaction
    };
    $scope.status = 'loading';
    $http.post(NodeService.getNode().api + '/tx/send', postData)
      .then(function(data, status, headers, config) {
        if(typeof(data.txid) != 'string') {
          // API returned 200 but the format is not known
          $scope.status = 'error';
          $scope.error = 'The transaction was sent but no transaction id was got back';
          return;
        }

        $scope.status = 'sent';
        $scope.txid = data.txid;
      }, function(data, status, headers, config) {
        $scope.status = 'error';
        if(data) {
          $scope.error = data;
        } else {
          $scope.error = "No error message given (connection error?)"
        }
      });
  };

});

// Source: src/js/controllers/scanner.js
angular.module('owsExplorerApp.controllers').controller('ScannerController', function($scope, $rootScope, $uibModalInstance, NodeService) {
  // Detect mobile devices
  var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
  };

  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

  $scope.isMobile = isMobile.any();
  $scope.scannerLoading = false;

  var $searchInput = angular.element(document.getElementById('search')),
      cameraInput,
      video,
      canvas,
      $video,
      context,
      localMediaStream;

  var _scan = function(evt) {
    if ($scope.isMobile) {
      $scope.scannerLoading = true;
      var files = evt.target.files;

      if (files.length === 1 && files[0].type.indexOf('image/') === 0) {
        var file = files[0];

        var reader = new FileReader();
        reader.onload = (function(theFile) {
          return function(e) {
            var mpImg = new MegaPixImage(file);
            mpImg.render(canvas, { maxWidth: 200, maxHeight: 200, orientation: 6 });

            setTimeout(function() {
              qrcode.width = canvas.width;
              qrcode.height = canvas.height;
              qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height);

              try {
                //alert(JSON.stringify(qrcode.process(context)));
                qrcode.decode();
              } catch (e) {
                alert(e);
              }
            }, 1500);
          };
        })(file);

        // Read  in the file as a data URL
        reader.readAsDataURL(file);
      }
    } else {
      if (localMediaStream) {
        context.drawImage(video, 0, 0, 300, 225);

        try {
          qrcode.decode();
        } catch(e) {
          //qrcodeError(e);
        }
      }

      setTimeout(_scan, 500);
    }
  };

  var _successCallback = function(stream) {
    video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
    localMediaStream = stream;
    video.play();
    setTimeout(_scan, 1000);
  };

  var _scanStop = function() {
    $scope.scannerLoading = false;
    $uibModalInstance.close();
    if (!$scope.isMobile) {
      if (localMediaStream.stop) localMediaStream.stop();
      localMediaStream = null;
      video.src = '';
    }
  };

  var _videoError = function(err) {
    console.log('Video Error: ' + JSON.stringify(err));
    _scanStop();
  };

  qrcode.callback = function(data) {
    _scanStop();
    str = data.trim();

    // Detect a protocol and switch nodes if able.
    if (str.indexOf(':') > 0) {
      var protocol = data.substr(0, str.indexOf(':') + 1);
      var requiredNode = NodeService.getNodeByProtocol(protocol);

      if (requiredNode) {
        NodeService.setNode(requiredNode.info.description.name);
      } else {
        $rootScope.flashMessage = 'Warning: unknown protocol or node not available\'' + protocol + '\'';
        console.log('Warning: unknown protocol or node not available \'' + protocol + '\'');
      }
      str = data.substring(protocol.length);
    }

    console.log('QR code detected: ' + str);
    $searchInput
      .val(str)
      .triggerHandler('change')
      .triggerHandler('submit');
  };

  $scope.cancel = function() {
    _scanStop();
  };

  $uibModalInstance.opened.then(function() {
    $rootScope.isCollapsed = true;
    
    // Start the scanner
    setTimeout(function() {
      canvas = document.getElementById('qr-canvas');
      context = canvas.getContext('2d');

      if ($scope.isMobile) {
        cameraInput = document.getElementById('qrcode-camera');
        cameraInput.addEventListener('change', _scan, false);
      } else {
        video = document.getElementById('qrcode-scanner-video');
        $video = angular.element(video);
        canvas.width = 300;
        canvas.height = 225;
        context.clearRect(0, 0, 300, 225);

        navigator.getUserMedia({video: true}, _successCallback, _videoError); 
      }
    }, 500);
  });
  
});

// Source: src/js/controllers/search.js
angular.module('owsExplorerApp.controllers').controller('SearchController', function($scope, $routeParams, $location, $timeout, Block, Transaction, Address, BlockByHeight) {
  $scope.loading = false;

  var _badQuery = function() {
    $scope.badQuery = true;

    $timeout(function() {
      $scope.badQuery = false;
    }, 2000);
  };

  var _resetSearch = function() {
    $scope.q = '';
    $scope.loading = false;
  };

  $scope.search = function() {
    var q = $scope.q;
    $scope.badQuery = false;
    $scope.loading = true;

    Block.get({
      blockHash: q
    },
    function() {
      _resetSearch();
      $location.path('block/' + q);
    }, function() { //block not found, search on TX
      Transaction.get({
        txId: q
      }, function() {
        _resetSearch();
        $location.path('tx/' + q);
      }, function() { //tx not found, search on Address
        Address.get({
          addrStr: q
        }, function() {
          _resetSearch();
          $location.path('address/' + q);
        }, function() { // block by height not found
          if (isFinite(q)) { // ensure that q is a finite number. A logical height value.
            BlockByHeight.get({
              blockHeight: q
            }, function(hash) {
              _resetSearch();
              $location.path('/block/' + hash.blockHash);
            }, function() { //not found, fail :(
              $scope.loading = false;
              _badQuery();
            });
          }
          else {
            $scope.loading = false;
            _badQuery();
          }
        });
      });
    });
  };

});

// Source: src/js/controllers/settings.js
angular.module('owsExplorerApp.controllers').controller('SettingsController', function($rootScope, $scope, $timeout, $route, $templateCache, gettextCatalog, amMoment, lodash, gettextCatalog, ConfigService, NodeService, CurrencyService) {

  $rootScope.$on('Local/NodeConnected', function(e, node) {
    init();
  });

  var init = function(nodeName) {
    $scope.config = ConfigService.getConfig();
    $scope.nodes = NodeService.getAvailableNodes();

    $scope.nodeWarning = null;
    if (!NodeService.isNodeAvailable($scope.config.preferredNodeName)) {
      $scope.nodeWarning = gettextCatalog.getString('Offline');
    }

    $scope.defaultLanguage = $scope.config.language || 'en';
    $scope.availableLanguages = [{
      name: 'Deutsch',
      isoCode: 'de_DE',
    }, {
      name: 'English',
      isoCode: 'en',
    }, {
      name: 'Spanish',
      isoCode: 'es',
    }, {
      name: 'Japanese',
      isoCode: 'ja',
    }];
  };

  var setLanguage = function(isoCode) {
    gettextCatalog.currentLanguage = $scope.defaultLanguage = isoCode;
    amMoment.changeLocale(isoCode);

    var currentPageTemplate = $route.current.templateUrl;
    $templateCache.remove(currentPageTemplate);
    $route.reload();
  };

  $scope.getNodeUnits = function(nodeName) {
    var node = NodeService.getNodeByName(nodeName);
    if (!node) return [];

    // TODO: exclude selection of fiat currencies for now; service needs historical rates.
    return lodash.filter(node.info.units, function(u) {
      return u.kind != 'fiat';
    });
  };

  $scope.isFiatSelected = function() {
    if ($rootScope.currency) {
      return $rootScope.currency.kind == 'fiat';
    }
    return false;
  };

  $scope.hasFiatRateProviders = function() {
    if ($rootScope.currency && $rootScope.currency.availableFiatRateProviders) {
      return $rootScope.currency.availableFiatRateProviders.length > 0;
    }
    return false;
  };

  $scope.updateSettings = function() {
    var oldConfig = ConfigService.getConfig();
    ConfigService.saveConfig($scope.config, true);

    if ($scope.config.language != oldConfig.language) {
      setLanguage($scope.config.language);
    }

    if ($scope.config.preferredNodeName != oldConfig.preferredNodeName) {
      NodeService.setNode($scope.config.preferredNodeName);
    }
  };

  // Come back to update config and UI if fiat currency is selected; setting of the currency.fiatRateProvider is async.
  var unwatchCurrencyFiatRateProvider = $rootScope.$watch('currency.fiatRateProvider', function() {
    if ($scope.isFiatSelected()) {
      $scope.fiatRateProvider = $rootScope.currency.fiatRateProvider;
      $scope.config.nodes[$scope.config.preferredNodeName].fiatRateProvider = $scope.fiatRateProvider;
      $scope.updateSettings();
    }
  });

  $scope.$on("$destroy", function() {
    if (typeof unwatchCurrencyFiatRateProvider == 'function') {
      unwatchCurrencyFiatRateProvider();
    }
  });

  init();

});

// Source: src/js/controllers/status.js
angular.module('owsExplorerApp.controllers').controller('StatusController', function($rootScope, $scope, $routeParams, $location, Status, Sync, SocketService, Version) {
    var socket;

    var _init = function() {
      socket = SocketService.getSocket($scope);
      if (!socket) return;

      if (!socket.isConnected()) {
        socket.on('connect', function() {
          _startSocket();
          _refresh();
        });
      } else {
        _startSocket();
        _refresh();
      }
    };

    var _refresh = function() {
      $scope.getStatus('Info');
      $scope.getStatus('LastBlockHash');
      $scope.getSync();
      $scope.version = _getVersion();
    };

    $rootScope.$on('Local/SocketChange', function(event) {
      _init();
    });

    $scope.getStatus = function(q) {
      Status.get({
        query: 'get' + q
      },
      function(d) {
        $scope.loaded = 1;
        angular.extend($scope, d);
      },
      function(e) {
        $scope.error = 'API ERROR: ' + e.data;
      });
    };

    $scope.humanSince = function(time) {
      var m = moment.unix(time / 1000);
      return m.max().fromNow();
    };

    var _onSyncUpdate = function(sync) {
      $scope.sync = sync;
    };

    var _startSocket = function () {
      socket.emit('subscribe', 'sync');
      socket.on('status', function(sync) {
        _onSyncUpdate(sync);
      });
    };
    
    $scope.getSync = function() {
      Sync.get(
        function(sync) {
          _onSyncUpdate(sync);
        },
        function(e) {
          var err = 'Could not get sync information' + e.toString();
          $scope.sync = {
            error: err
          };
        });
    };

    var _getVersion = function() {
      Version.get({},
        function(res) {
          $scope.version = res.version;
        });
    };

    _init();
    
  });

// Source: src/js/controllers/transactions.js
angular.module('owsExplorerApp.controllers').controller('TransactionsController', function($scope, $rootScope, $routeParams, $location, Transaction, TransactionsByBlock, TransactionsByAddress) {
  $scope.loading = false;
  $scope.loadedBy = null;

  var pageNum = 0;
  var pagesTotal = 1;

  var _aggregateItems = function(items) {
    if (!items) return [];

    var l = items.length;

    var ret = [];
    var tmp = {};
    var u = 0;

    for(var i=0; i < l; i++) {

      var notAddr = false;
      // non standard input
      if (items[i].scriptSig && !items[i].addr) {
        items[i].addr = 'Unparsed address [' + u++ + ']';
        items[i].notAddr = true;
        notAddr = true;
      }

      // non standard output
      if (items[i].scriptPubKey && !items[i].scriptPubKey.addresses) {
        items[i].scriptPubKey.addresses = ['Unparsed address [' + u++ + ']'];
        items[i].notAddr = true;
        notAddr = true;
      }

      // multiple addr at output
      if (items[i].scriptPubKey && items[i].scriptPubKey.addresses.length > 1) {
        items[i].addr = items[i].scriptPubKey.addresses.join(',');
        ret.push(items[i]);
        continue;
      }

      var addr = items[i].addr || (items[i].scriptPubKey && items[i].scriptPubKey.addresses[0]);

      if (!tmp[addr]) {
        tmp[addr] = {};
        tmp[addr].valueSat = 0;
        tmp[addr].count = 0;
        tmp[addr].addr = addr;
        tmp[addr].items = [];
      }
      tmp[addr].isSpent = items[i].spentTxId;

      tmp[addr].doubleSpentTxID = tmp[addr].doubleSpentTxID   || items[i].doubleSpentTxID;
      tmp[addr].doubleSpentIndex = tmp[addr].doubleSpentIndex || items[i].doubleSpentIndex;
      tmp[addr].dbError = tmp[addr].dbError || items[i].dbError;
      tmp[addr].valueSat += Math.round(items[i].value * $rootScope.currency.standardUnit.value);
      tmp[addr].items.push(items[i]);
      tmp[addr].notAddr = notAddr;

      if (items[i].unconfirmedInput)
        tmp[addr].unconfirmedInput = true;

      tmp[addr].count++;
    }

    angular.forEach(tmp, function(v) {
      v.value    = v.value || parseInt(v.valueSat) / $rootScope.currency.standardUnit.value;
      ret.push(v);
    });
    return ret;
  };

  var _processTX = function(tx) {
    tx.vinSimple = _aggregateItems(tx.vin);
    tx.voutSimple = _aggregateItems(tx.vout);
  };

  var _paginate = function(data) {
    $scope.loading = false;

    pagesTotal = data.pagesTotal;
    pageNum += 1;

    data.txs.forEach(function(tx) {
      _processTX(tx);
      $scope.txs.push(tx);
    });
  };

  var _byBlock = function() {
    TransactionsByBlock.get({
      block: $routeParams.blockHash,
      pageNum: pageNum
    }, function(data) {
      _paginate(data);
    });
  };

  var _byAddress = function () {
    TransactionsByAddress.get({
      address: $routeParams.addrStr,
      pageNum: pageNum
    }, function(data) {
      _paginate(data);
    });
  };

  var _findTx = function(txid) {
    Transaction.get({
      txId: txid
    }, function(tx) {
      $rootScope.titleDetail = tx.txid.substring(0,7) + '...';
      $rootScope.flashMessage = null;
      $scope.tx = tx;
      _processTX(tx);
      $scope.txs.unshift(tx);
    }, function(e) {
      if (e.status === 400) {
        $rootScope.flashMessage = 'Invalid Transaction ID: ' + $routeParams.txId;
      }
      else if (e.status === 503) {
        $rootScope.flashMessage = 'Backend Error. ' + e.data;
      }
      else {
        $rootScope.flashMessage = 'Transaction Not Found';
      }

      $location.path('/');
    });
  };

  //Initial load
  $scope.load = function(from) {
    $scope.loadedBy = from;
    $scope.loadMore();
  };

  //Load more transactions for pagination
  $scope.loadMore = function() {
    if (pageNum < pagesTotal && !$scope.loading) {
      $scope.loading = true;

      if ($scope.loadedBy === 'address') {
        _byAddress();
      }
      else {
        _byBlock();
      }
    }
  };

  // Highlighted txout
  if ($routeParams.v_type == '>' || $routeParams.v_type == '<') {
    $scope.from_vin = $routeParams.v_type == '<' ? true : false;
    $scope.from_vout = $routeParams.v_type == '>' ? true : false;
    $scope.v_index = parseInt($routeParams.v_index);
    $scope.itemsExpanded = true;
  }
  
  //Init without txs
  $scope.txs = [];

  $scope.$on('tx', function(event, txid) {
    _findTx(txid);
  });

  if ($routeParams.txId) {
    _findTx($routeParams.txId);
  }

});

// Source: src/js/models/ScopedSocket.js
function ScopedSocket(socket, $rootScope, $timeout) {
  this.socket = socket;
  this.$rootScope = $rootScope;
  this.$timeout = $timeout;
  this.listeners = [];
};

ScopedSocket.prototype.isConnected = function() {
  return this.socket.connected;
};

ScopedSocket.prototype.disconnect = function() {
  this.socket.disconnect();
};

ScopedSocket.prototype.removeAllListeners = function(opts) {
  if (!opts) opts = {};
  for (var i = 0; i < this.listeners.length; i++) {
    var details = this.listeners[i];
    if (opts.skipConnect && details.event === 'connect') {
      continue;
    }
    this.socket.removeListener(details.event, details.fn);
  }
  this.listeners = [];
};

ScopedSocket.prototype.on = function(event, callback) {
  var socket = this.socket;
  var $rootScope = this.$rootScope;

  var wrapped_callback = function() {
    var args = arguments;
    $rootScope.$apply(function() {
      callback.apply(socket, args);
    });
  };
  socket.on(event, wrapped_callback);

  this.listeners.push({
    event: event,
    fn: wrapped_callback
  });
};

ScopedSocket.prototype.emit = function(event, data, callback) {
  var socket = this.socket;
  var $rootScope = this.$rootScope;
  var args = Array.prototype.slice.call(arguments);

  args.push(function() {
    var args = arguments;
    $rootScope.$apply(function() {
      if (callback) {
        callback.apply(socket, args);
      }
    });
  });

  socket.emit.apply(socket, args);
};

// Source: src/js/services/address.js
angular.module('owsExplorerApp.services').factory('Address', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/addr/:addrStr/?noTxList=1', {addrStr: '@addrStr'}, {
        get: {
          method: 'GET',
          interceptor: {
            response: function (res) {
              return res.data;
            },
            responseError: function (res) {
              if (res.status === 404) {
                return res;
              }
            }
          }
        }
      });

      r.get({addrStr: params.addrStr}, success, error);
    });
  };

  return root;

});

// Source: src/js/services/block.js
angular.module('owsExplorerApp.services').factory('Block', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/block/:blockHash', {blockHash: '@blockHash'}, {
        get: {
          method: 'GET',
          interceptor: {
            response: function (res) {
              return res.data;
            },
            responseError: function (res) {
              if (res.status === 404) {
                return res;
              }
            }
          }
        }
      });

      r.get({blockHash: params.blockHash}, success, error);
    });
  };

  return root;
})
.factory('Blocks', function($resource, NodeService) {
  var root = {};

  root.get = function(success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/blocks');
      r.get(success, error);
    });
  };

  return root;
})
.factory('BlockByHeight', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/block-index/:blockHeight', {blockHeight: '@blockHeight'});
      r.get({blockHeight: params.blockHeight}, success, error);
    });
  };

  return root;
});

// Source: src/js/services/config.js
angular.module('owsExplorerApp.services').factory('ConfigService', function($rootScope, lodash) {
  var root = {};

  // localStorage
  //
  // config = {
  //   language = 'en',
  //   preferredNodeName = 'Bitcoin',
  //   nodes: {
  //     'Bitcoin': {
  //       currencyUnit: 'BTC',
  //       fiatRateProvider: 'Bitstamp'
  //     },
  //     'Bitcoin Cash': {
  //       currencyUnit: 'bits',
  //       fiatRateProvider: 'Kraken'
  //     },
  //     ...
  //   }
  // }

  $rootScope.$on('Local/NodeConnected', function(e, node) {
    var config = lodash.merge(getDefaultNodeConfig(node), root.getConfig());
    if (!config.preferredNodeName) {
      // No preferred node configured, initialize to the first node to connect.
      config.preferredNodeName = node.info.description.name;
    }
    root.saveConfig(config);
  });

  root.getConfig = function() {
    return JSON.parse(localStorage.getItem('config')) || {};
  };

  root.getConfigForNode = function(node) {
    var config = root.getConfig();
    return config.nodes[node.info.description.name] || {};
  };

  root.saveConfig = function(config, replace) {
    replace = replace || false;
    if (config) {
      if (replace) {
        config = lodash.assign(root.getConfig(), config);
      } else {
        config = lodash.merge(root.getConfig(), config);
      }
      localStorage.setItem('config', JSON.stringify(config));
    }
  };

  var init = function() {
    var config = JSON.parse(localStorage.getItem('config'));
    if (config == null) {
      config = {
        language: 'en',
      }
      root.saveConfig(config, true);
    }
  };

  var getDefaultNodeConfig = function(node) {
    var defaultConfig = {
      nodes: {}
    };

    if (node) {
      // Default to select standard currency.
      var standardCurrencyUnit = lodash.find(node.info.units, function(u) {
        return u.kind == 'standard';
      });

      defaultConfig.nodes[node.info.description.name] = {
        currencyUnitName: standardCurrencyUnit.shortName
      };
    }

    return defaultConfig;
  };

  init();

  return root;

});

// Source: src/js/services/currency.js
angular.module('owsExplorerApp.services').factory('CurrencyService', function($rootScope, $resource, lodash, NodeService, ConfigService) {
  var root = {};

  $rootScope.$on('Local/NodeChange', function(e, data) {
    root.setCurrency(data.newNode);
  });

  var get = function(success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/currency');
      r.get(success, error);
    });
  };

  root.setCurrency = function(node) {
  	// Set currency based on user config.
    var configNode = ConfigService.getConfigForNode(node);

    if (configNode) {
      $rootScope.currency = lodash.find(node.info.units, function(u) {
        return u.shortName == configNode.currencyUnitName;
      });
  	} else {
      // No config set, use currency standard unit.
      $rootScope.currency = lodash.find(node.info.units, function(u) {
        return u.kind == 'standard';
      });
  	}

    // Currency conversions (non-fiat) are relative to the standard unit value.
    // Attach the standard unit to the selected currency.
  	$rootScope.currency.standardUnit = lodash.find(node.info.units, function(u) {
  		return u.kind == 'standard';
  	});

    // For fiat currencies get the market exchange rate for conversions.
    if ($rootScope.currency.kind == 'fiat') {
      get({}, function(res) {
        var providerRates = res.data.rates[$rootScope.currency.code];
        $rootScope.currency.availableFiatRateProviders = lodash.map(providerRates, function(p) {
          return p.name;
        });

        // Default to first entry in response if user has not configured provider.
        var provider = configNode.fiatRateProvider || res.data.rates[$rootScope.currency.code][0].name;
        $rootScope.currency.fiatRateProvider = provider;
        $rootScope.currency.value = res.data.rates[$rootScope.currency.code][provider].rate;

        $rootScope.currency.rateStr = '1 ' + $rootScope.currency.standardUnit.shortName + ' = ' +
          $rootScope.currency.value.toFixed($rootScope.currency.decimals) + ' ' + $rootScope.currency.shortName;
      });
    }
  };

  // Convert from standard unit to selected currency unit.
  // This function needed globally.
  root.getCurrencyConversion = function(value) {
    // Wait for currency to be initialized.
    if (!$rootScope.currency) {
      return '';
    }

    var _roundFloat = function(x, n) {
      if(!parseInt(n, 10) || !parseFloat(x)) n = 0;
      return Math.round(x * Math.pow(10, n)) / Math.pow(10, n);
    };

    value = value * 1; // Convert to number

    if (isNaN(value) || typeof value == 'undefined' || value == null) {
      return 'value error';
    }

    if (value === 0.00000000) {
      return value.toFixed($rootScope.currency.decimals) + ' '+ $rootScope.currency.shortName;
    }

    var response;
    if ($rootScope.currency.kind == 'fiat') {
      response = _roundFloat((value * $rootScope.currency.value), $rootScope.currency.decimals);
    } else {
      response = _roundFloat((value * $rootScope.currency.standardUnit.value / $rootScope.currency.value), $rootScope.currency.decimals);
    }

    return response.toFixed($rootScope.currency.decimals) + ' ' + $rootScope.currency.shortName;
  };

  return root;
});

// Source: src/js/services/nodeService.js
angular.module('owsExplorerApp.services').factory('NodeService', function($rootScope, $resource, $timeout, lodash, nodeConfig, ConfigService) {
	var root = {};

  var CONNECTION_RETRIES = 1000000;
  var CONNECTION_RETRY_DELAY = 10000;

	var _nodes = [];
  var _currentNodeName = null;
  var _queue = [];
  var _waiting = false;
  var _retries = [];

  var _isStartup = function() {
    return _currentNodeName == null;
  };

  var _init = function() {
    // Initialize nodes list from configuration.
    for (var i = 0; i < nodeConfig.fullNodes.length; i++) {
      _nodes.push({
        url: nodeConfig.fullNodes[i].url || '',
        api: (nodeConfig.fullNodes[i].url || '') + '/' + (nodeConfig.fullNodes[i].apiPrefix || ''),
        info: {},
        status: 'pending'
      });
      _tryConnectNode(_nodes[_nodes.length-1]); // Asynchronous call
    }

    // Wait for nodes connect to before setting the current node.
    root.whenAvailable(function(availableNodes) {
      if (_isStartup()) {
        var config = ConfigService.getConfig();

        // Try to set the users preferred node.
        if (root.getNodeByName(config.preferredNodeName)) {
          root.setNode(config.preferredNodeName);
        } else {
          root.setNode(availableNodes[0].info.description.name);
        }
      }
    });

  };

  var _tryConnectNode = function(node) {
    var retry = function(node) {
      $timeout(function() {
        var r = lodash.find(_retries, function(r) {
          return node.url == r.url;
        });

        if (!r) {
          r = { url: node.url, count: 1 };
          _retries.push(r);
        } else {
          r.count++;
        }

        if (r.count <= CONNECTION_RETRIES) {
          _tryConnectNode(node);
        } else {
          console.log('Failed to connect to node at ' + node.url);
        }
      }, CONNECTION_RETRY_DELAY);
    };

    console.log('Attempting to connect to node at ' + node.url);
    var Status = $resource(node.api + '/status', {q: '@q'});
    Status.get({q: 'getInfo'},
      function(d) {
        node.info = d.info;
        node.status = 'ready';
        $rootScope.$emit('Local/NodeConnected', node);
        console.log('Node connected - ' + node.info.description.name + ' @ ' + node.url);
      },
      function(e) {
        node.error = e.data;
        node.status = 'error';
        retry(node);
      });
  };

  root.whenAvailable = function(callback) {
    var isReady = function() {
      // Ready if at least one node is ready
      var ready = false;
      lodash.forEach(_nodes, function(n) {
        if (n.status == 'ready') {
          ready = true;
        }
      });
      return ready;
    };

    var wait = function() {
      _waiting = true;

      $timeout(function() {
        if (!isReady()) {
          return wait();
        } else {
          // Make all callbacks and empty the queue.
          lodash.each(_queue, function(cb) {
            $timeout(function() {
              return cb(root.getAvailableNodes());
            }, 1);
          });
          _queue = [];
          _waiting = false;
        }
      }, 1000);
    };

    if (!isReady()) {
      _queue.push(callback);

      if (_waiting) return;
      wait();
      return;
    }
    return callback(root.getAvailableNodes());
  };

  root.getNodes = function() {
  	return _nodes;
  };

  root.getAvailableNodes = function() {
    return lodash.filter(_nodes, function(n) {
      return n.status == 'ready';
    });
  };

  root.getNodeByName = function(name) {
    var n = lodash.find(root.getAvailableNodes(), function(n) {
      return n.info.description.name == name;
    });
    return n;
  };

  root.getNodeByProtocol = function(protocol) {
    var n = lodash.find(root.getAvailableNodes(), function(n) {
      return n.info.description.protocol == protocol;
    });
    return n;
  };

  // Get the currently selected node.
  root.getNode = function() {
    return root.getNodeByName(_currentNodeName);
  };

  root.isNodeAvailable = function(nodeName) {
    var n = root.getNodeByName(nodeName);
    if (n) {
      return n.status == 'ready';
    }
    return false;
  };

  // Set the current node.
  root.setNode = function(name) {
    var node = root.getNodeByName(name);

    if (node) {
      var oldNode = root.getNode();
      _currentNodeName = name;
      $rootScope.node = node;
      $rootScope.$emit('Local/NodeChange', {
        oldNode: oldNode,
        newNode: node
      });
    } else {
      console.log('Error: ignored attempt to set node with unrecognized node name (' + name + ')');
    }
  };

  _init();

	return root;
});

// Source: src/js/services/socketService.js
angular.module('owsExplorerApp.services').factory('SocketService', function($rootScope, $timeout, NodeService) {
  var root = {};
  var socket;
  var scopedSocket;

  var _connect = function(node) {
    socket = io.connect(node.url, {
      'reconnect': true,
      'reconnection delay': 500
    });
  };

  var _disconnect = function(callback) {
    if (scopedSocket) {
      scopedSocket.removeAllListeners();
      $timeout(function() {
        scopedSocket.disconnect();
        callback();
      }, 100);
    } else {
      callback();
    }
  };

  $rootScope.$on('Local/NodeChange', function(event, data) {
    // Only re-establish socket if node has really changed.
    if (data.oldNode != data.newNode) {
      _disconnect(function() {
        _connect(data.newNode);
        $rootScope.$emit('Local/SocketChange');
      });
    }
  });

  root.getSocket = function(scope) {
    // Return if no socket connected.
    if (!socket) return null;

    scopedSocket = new ScopedSocket(socket, $rootScope, $timeout);

    scope.$on('$destroy', function() {
      scopedSocket.removeAllListeners();
    });

    socket.on('connect', function() {
      scopedSocket.removeAllListeners({
        skipConnect: true
      });
    });

    return scopedSocket;
  };

  return root;

});

// Source: src/js/services/status.js
angular.module('owsExplorerApp.services').factory('Status', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/status', {q: '@q'});
      r.get({q: params.query}, success, error);
    });
  };

  return root;
})
.factory('Sync', function($resource, NodeService) {
  var root = {};

  root.get = function(success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/sync');
      r.get({}, success, error);
    });
  };

  return root;
})
.factory('PeerSync', function($resource, NodeService) {
  var root = {};

  root.get = function(success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/peer');
      r.get({}, success, error);
    });
  };

  return root;
});

// Source: src/js/services/transaction.js
angular.module('owsExplorerApp.services').factory('Transaction', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/tx/:txId', {txId: '@txId'}, {
        get: {
          method: 'GET',
          interceptor: {
            response: function (res) {
              return res.data;
            },
            responseError: function (res) {
              if (res.status === 404) {
                return res;
              }
            }
          }
        }
      });

      r.get({txId: params.txId}, success, error);
    });
  };

  return root;
})
.factory('TransactionsByBlock', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/txs', {block: '@block'});
      r.get({block: params.block}, success, error);
    });
  };

  return root;
})
.factory('TransactionsByAddress', function($resource, NodeService) {
  var root = {};

  root.get = function(params, success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/txs', {address: '@address'});
      r.get({address: params.address}, success, error);
    });
  };

  return root;
})
.factory('Transactions', function($resource, NodeService) {
  var root = {};

  root.get = function(success, error) {
    NodeService.whenAvailable(function() {
      var r = $resource(NodeService.getNode().api + '/txs');
      r.get(success, error);
    });
  };

  return root;
});

// Source: src/js/services/version.js
angular.module('owsExplorerApp.services').factory('Version', function($resource, NodeService) {
  var root = {};

  root.get = function(success, error) {
    NodeService.whenAvailable(function() {
	    var r = $resource(NodeService.getNode().api + '/version');
	    r.get(success, error);
	  });
  };

  return root;
});

// Source: src/js/directives.js
var ZeroClipboard = window.ZeroClipboard;

angular.module('owsExplorerApp.directives')
  .directive('scroll', function ($window) {
    return function(scope, element, attrs) {
      angular.element($window).bind('scroll', function() {
        if (this.pageYOffset >= 200) {
          scope.secondaryNavbar = true;
        } else {
          scope.secondaryNavbar = false;
        }
        scope.$apply();
      });
    };
  })
  .directive('whenScrolled', function($window) {
    return {
      restric: 'A',
      link: function(scope, elm, attr) {
        var pageHeight, clientHeight, scrollPos;
        $window = angular.element($window);

        var handler = function() {
          pageHeight = window.document.documentElement.scrollHeight;
          clientHeight = window.document.documentElement.clientHeight;
          scrollPos = window.pageYOffset;

          if (pageHeight - (scrollPos + clientHeight) === 0) {
            scope.$apply(attr.whenScrolled);
          }
        };

        $window.on('scroll', handler);

        scope.$on('$destroy', function() {
          return $window.off('scroll', handler);
        });
      }
    };
  })
  .directive('clipCopy', function() {
    ZeroClipboard.config({
      moviePath: '/lib/zeroclipboard/ZeroClipboard.swf',
      trustedDomains: ['*'],
      allowScriptAccess: 'always',
      forceHandCursor: true
    });

    return {
      restric: 'A',
      scope: { clipCopy: '=clipCopy' },
      template: '<div class="tooltip fade right in"><div class="tooltip-arrow"></div><div class="tooltip-inner">Copied!</div></div>',
      link: function(scope, elm) {
        var clip = new ZeroClipboard(elm);

        clip.on('load', function(client) {
          var onMousedown = function(client) {
            client.setText(scope.clipCopy);
          };

          client.on('mousedown', onMousedown);

          scope.$on('$destroy', function() {
            client.off('mousedown', onMousedown);
          });
        });

        clip.on('noFlash wrongflash', function() {
          return elm.remove();
        });
      }
    };
  })
  .directive('focus', function ($timeout) {
    return {
      scope: {
        trigger: '@focus'
      },
      link: function (scope, element) {
        scope.$watch('trigger', function (value) {
          if (value === "true") {
            $timeout(function () {
              element[0].focus();
            });
          }
        });
      }
    };
  });

// Source: src/js/filters.js
angular.module('owsExplorerApp.filters')
  .filter('startFrom', function() {
    return function(input, start) {
      start = +start; //parse to int
      return input.slice(start);
    }
  })
  .filter('split', function() {
    return function(input, delimiter) {
      var delimiter = delimiter || ',';
      return input.split(delimiter);
    }
  });

// Source: src/js/config.js
//Setting up route
angular.module('owsExplorerApp').config(function($routeProvider) {
  $routeProvider.
    when('/block/:blockHash', {
      templateUrl: 'views/block.html',
      title: 'Block '
    }).
    when('/block-index/:blockHeight', {
      controller: 'BlocksController',
      templateUrl: 'views/redirect.html'
    }).
    when('/tx/send', {
      templateUrl: 'views/transaction-sendraw.html',
      title: 'Broadcast Raw Transaction'
    }).
    when('/tx/:txId/:v_type?/:v_index?', {
      templateUrl: 'views/transaction.html',
      title: 'Transaction '
    }).
    when('/', {
      templateUrl: 'views/index.html',
      title: 'Home'
    }).
    when('/blocks', {
      templateUrl: 'views/block-list.html',
      title: 'Blocks solved Today'
    }).
    when('/blocks-date/:blockDate/:startTimestamp?', {
      templateUrl: 'views/block-list.html',
      title: 'Blocks solved '
    }).
    when('/address/:addrStr', {
      templateUrl: 'views/address.html',
      title: 'Address '
    }).
    when('/status', {
      templateUrl: 'views/status.html',
      title: 'Status'
    }).
    when('/messages/verify', {
      templateUrl: 'views/messages-verify.html',
      title: 'Verify Message'
    }).
    when('/tools', {
      templateUrl: 'views/tools.html',
      title: 'Tools'
    }).
    when('/settings', {
      templateUrl: 'views/settings.html',
      title: 'Settings'
    })
    .otherwise({
      templateUrl: 'views/404.html',
      title: 'Error'
    });
});

//Setting HTML5 Location Mode
angular.module('owsExplorerApp')
  .config(function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');
  })
  .run(function($rootScope, $route, $location, $routeParams, $anchorScroll, ngProgress, gettextCatalog, amMoment) {
    var defaultLanguage = 'en';
    gettextCatalog.currentLanguage = defaultLanguage;
    amMoment.changeLocale(defaultLanguage);
    $rootScope.$on('$routeChangeStart', function() {
      ngProgress.start();
    });

    $rootScope.$on('$routeChangeSuccess', function() {
      ngProgress.complete();

      //Change page title, based on Route information
      $rootScope.titleDetail = '';
      $rootScope.title = $route.current.title;
      $rootScope.isCollapsed = true;
      $rootScope.currentAddr = null;

      $location.hash($routeParams.scrollTo);
      $anchorScroll();
    });
  });

// Source: src/js/init.js
angular.element(document).ready(function() {
  // Init the app
  // angular.bootstrap(document, ['owsExplorerApp']);
});

// Source: src/js/translations.js
angular.module('owsExplorerApp.translations').run(['gettextCatalog', function (gettextCatalog) {
/* jshint -W100 */
    gettextCatalog.setStrings('de_DE', {"(Input unconfirmed)":"(Eingabe unbestätigt)","404 Page not found :(":"404 Seite nicht gefunden :(","<strong>explorer</strong>  is an <a href=\"http://live.explorer.is/\" target=\"_blank\">open-source blockchain explorer</a> with complete REST and websocket APIs that can be used for writing web wallets and other apps  that need more advanced blockchain queries than provided by bitcoind RPC.  Check out the <a href=\"https://github.com/owstack/explorer-ui\" target=\"_blank\">source code</a>.":"<strong>explorer</strong> ist ein <a href=\"http://live.explorer.is/\" target=\"_blank\">Open Source Blockchain Explorer</a> mit vollständigen REST und Websocket APIs um eigene Wallets oder Applikationen zu implementieren. Hierbei werden fortschrittlichere Abfragen der Blockchain ermöglicht, bei denen die RPC des Bitcoind nicht mehr ausreichen. Der aktuelle <a href=\"https://github.com/owstack/explorer-ui\" target=\"_blank\">Quellcode</a> ist auf Github zu finden.","<strong>explorer</strong> is still in development, so be sure to report any bugs and provide feedback for improvement at our <a href=\"https://github.com/owstack/explorer/issues\" target=\"_blank\">github issue tracker</a>.":"<strong>explorer</strong> befindet sich aktuell noch in der Entwicklung. Bitte sende alle gefundenen Fehler (Bugs) und Feedback zur weiteren Verbesserung an unseren <a href=\"https://github.com/owstack/explorer-ui/issues\" target=\"_blank\">Github Issue Tracker</a>.","About":"Über explorer","Address":"Adresse","Age":"Alter","Application Status":"Programmstatus","Best Block":"Bester Block","Bitcoin node information":"Bitcoin-Node Info","Block":"Block","Block Reward":"Belohnung","Blocks":"Blöcke","Bytes Serialized":"Serialisierte Bytes","Can't connect to bitcoind to get live updates from the p2p network. (Tried connecting to bitcoind at {{host}}:{{port}} and failed.)":"Es ist nicht möglich mit Bitcoind zu verbinden um live Aktualisierungen vom P2P Netzwerk zu erhalten. (Verbindungsversuch zu bitcoind an {{host}}:{{port}} ist fehlgeschlagen.)","Can't connect to explorer server. Attempting to reconnect...":"Keine Verbindung zum explorer-Server möglich. Es wird versucht die Verbindung neu aufzubauen...","Can't connect to internet. Please, check your connection.":"Keine Verbindung zum Internet möglich, bitte Zugangsdaten prüfen.","Complete":"Vollständig","Confirmations":"Bestätigungen","Conn":"Verbindungen","Connections to other nodes":"Verbindungen zu Nodes","Current Blockchain Tip (explorer)":"Aktueller Blockchain Tip (explorer)","Current Sync Status":"Aktueller Status","Details":"Details","Difficulty":"Schwierigkeit","Double spent attempt detected. From tx:":"Es wurde ein \"double Spend\" Versuch erkannt.Von tx:","Error!":"Fehler!","Fee":"Gebühr","Final Balance":"Schlussbilanz","Finish Date":"Fertigstellung","Go to home":"Zur Startseite","Hash Serialized":"Hash Serialisiert","Height":"Höhe","Included in Block":"Eingefügt in Block","Incoherence in levelDB detected:":"Es wurde eine Zusammenhangslosigkeit in der LevelDB festgestellt:","Info Errors":"Fehlerbeschreibung","Initial Block Chain Height":"Ursprüngliche Blockchain Höhe","Input":"Eingänge","Last Block":"Letzter Block","Last Block Hash (Bitcoind)":"Letzter Hash (Bitcoind)","Latest Blocks":"Letzte Blöcke","Latest Transactions":"Letzte Transaktionen","Loading Address Information":"Lade Adressinformationen","Loading Block Information":"Lade Blockinformation","Loading Selected Date...":"Lade gewähltes Datum...","Loading Transaction Details":"Lade Transaktionsdetails","Loading Transactions...":"Lade Transaktionen...","Loading...":"Lade...","Mined Time":"Block gefunden (Mining)","Mined by":"Gefunden von","Mining Difficulty":"Schwierigkeitgrad","Next Block":"Nächster Block","No Inputs (Newly Generated Coins)":"Keine Eingänge (Neu generierte Coins)","No blocks yet.":"Keine Blöcke bisher.","No matching records found!":"Keine passenden Einträge gefunden!","No. Transactions":"Anzahl Transaktionen","Number Of Transactions":"Anzahl der Transaktionen","Output":"Ausgänge","Powered by":"Powered by","Previous Block":"Letzter Block","Protocol version":"Protokollversion","Proxy setting":"Proxyeinstellung","Received Time":"Eingangszeitpunkt","Redirecting...":"Umleitung...","Search for block, transaction or address":"Suche Block, Transaktion oder Adresse","See all blocks":"Alle Blöcke anzeigen","Show Transaction Output data":"Zeige Abgänge","Show all":"Zeige Alles","Show input":"Zeige Eingänge","Show less":"Weniger anzeigen","Show more":"Mehr anzeigen","Size":"Größe","Size (bytes)":"Größe (bytes)","Skipped Blocks (previously synced)":"Verworfene Blöcke (bereits syncronisiert)","Start Date":"Startdatum","Status":"Status","Summary":"Zusammenfassung","Summary <small>confirmed</small>":"Zusammenfassung <small>bestätigt</small>","Sync Progress":"Fortschritt","Sync Status":"Syncronisation","Sync Type":"Art der Syncronisation","Synced Blocks":"Syncronisierte Blöcke","Testnet":"Testnet aktiv","There are no transactions involving this address.":"Es gibt keine Transaktionen zu dieser Adressse","Time Offset":"Zeitoffset zu UTC","Timestamp":"Zeitstempel","Today":"Heute","Total Amount":"Gesamtsumme","Total Received":"Insgesamt empfangen","Total Sent":"Insgesamt gesendet","Transaction":"Transaktion","Transaction Output Set Information":"Transaktions Abgänge","Transaction Outputs":"Abgänge","Transactions":"Transaktionen","Type":"Typ","Unconfirmed":"Unbestätigt","Unconfirmed Transaction!":"Unbestätigte Transaktion!","Unconfirmed Txs Balance":"Unbestätigtes Guthaben","Value Out":"Wert","Version":"Version","Waiting for blocks...":"Warte auf Blöcke...","Waiting for transactions...":"Warte auf Transaktionen...","by date.":"nach Datum.","first seen at":"zuerst gesehen am","mined":"gefunden","mined on:":"vom:","Waiting for blocks":"Warte auf Blöcke"});
    gettextCatalog.setStrings('es', {"(Input unconfirmed)":"(Entrada sin confirmar)","404 Page not found :(":"404 Página no encontrada :(","<strong>explorer</strong>  is an <a href=\"http://live.explorer.is/\" target=\"_blank\">open-source blockchain explorer</a> with complete REST and websocket APIs that can be used for writing web wallets and other apps  that need more advanced blockchain queries than provided by bitcoind RPC.  Check out the <a href=\"https://github.com/owstack/explorer-ui\" target=\"_blank\">source code</a>.":"<strong>explorer</strong>  es un <a href=\"http://live.explorer.is/\" target=\"_blank\">explorador de bloques open-source</a> con un completo conjunto de REST y APIs de websockets que pueden ser usadas para escribir monederos y otras aplicaciones que requieran consultar un explorador de bloques.  Obtén el código en <a href=\"http://github.com/owstack/explorer\" target=\"_blank\">el repositorio abierto de Github</a>.","<strong>explorer</strong> is still in development, so be sure to report any bugs and provide feedback for improvement at our <a href=\"https://github.com/owstack/explorer/issues\" target=\"_blank\">github issue tracker</a>.":"<strong>explorer</strong> esta en desarrollo aún, por ello agradecemos que nos reporten errores o sugerencias para mejorar el software. <a href=\"https://github.com/owstack/explorer-ui/issues\" target=\"_blank\">Github issue tracker</a>.","About":"Acerca de","Address":"Dirección","Age":"Edad","Application Status":"Estado de la Aplicación","Best Block":"Mejor Bloque","Bitcoin node information":"Información del nodo Bitcoin","Block":"Bloque","Block Reward":"Bloque Recompensa","Blocks":"Bloques","Bytes Serialized":"Bytes Serializados","Can't connect to bitcoind to get live updates from the p2p network. (Tried connecting to bitcoind at {{host}}:{{port}} and failed.)":"No se pudo conectar a bitcoind para obtener actualizaciones en vivo de la red p2p. (Se intentó conectar a bitcoind de {{host}}:{{port}} y falló.)","Can't connect to explorer server. Attempting to reconnect...":"No se pudo conectar al servidor explorer. Intentando re-conectar...","Can't connect to internet. Please, check your connection.":"No se pudo conectar a Internet. Por favor, verifique su conexión.","Complete":"Completado","Confirmations":"Confirmaciones","Conn":"Con","Connections to other nodes":"Conexiones a otros nodos","Current Blockchain Tip (explorer)":"Actual Blockchain Tip (explorer)","Current Sync Status":"Actual Estado de Sincronización","Details":"Detalles","Difficulty":"Dificultad","Double spent attempt detected. From tx:":"Intento de doble gasto detectado. De la transacción:","Error!":"¡Error!","Fee":"Tasa","Final Balance":"Balance Final","Finish Date":"Fecha Final","Go to home":"Volver al Inicio","Hash Serialized":"Hash Serializado","Height":"Altura","Included in Block":"Incluido en el Bloque","Incoherence in levelDB detected:":"Detectada una incoherencia en levelDB:","Info Errors":"Errores de Información","Initial Block Chain Height":"Altura de la Cadena en Bloque Inicial","Input":"Entrada","Last Block":"Último Bloque","Last Block Hash (Bitcoind)":"Último Bloque Hash (Bitcoind)","Latest Blocks":"Últimos Bloques","Latest Transactions":"Últimas Transacciones","Loading Address Information":"Cargando Información de la Dirección","Loading Block Information":"Cargando Información del Bloque","Loading Selected Date...":"Cargando Fecha Seleccionada...","Loading Transaction Details":"Cargando Detalles de la Transacción","Loading Transactions...":"Cargando Transacciones...","Loading...":"Cargando...","Mined Time":"Hora de Minado","Mined by":"Minado por","Mining Difficulty":"Dificultad de Minado","Next Block":"Próximo Bloque","No Inputs (Newly Generated Coins)":"Sin Entradas (Monedas Recién Generadas)","No blocks yet.":"No hay bloques aún.","No matching records found!":"¡No se encontraron registros coincidentes!","No. Transactions":"Nro. de Transacciones","Number Of Transactions":"Número de Transacciones","Output":"Salida","Powered by":"Funciona con","Previous Block":"Bloque Anterior","Protocol version":"Versión del protocolo","Proxy setting":"Opción de proxy","Received Time":"Hora de Recibido","Redirecting...":"Redireccionando...","Search for block, transaction or address":"Buscar bloques, transacciones o direcciones","See all blocks":"Ver todos los bloques","Show Transaction Output data":"Mostrar dato de Salida de la Transacción","Show all":"Mostrar todos","Show input":"Mostrar entrada","Show less":"Ver menos","Show more":"Ver más","Size":"Tamaño","Size (bytes)":"Tamaño (bytes)","Skipped Blocks (previously synced)":"Bloques Saltados (previamente sincronizado)","Start Date":"Fecha de Inicio","Status":"Estado","Summary":"Resumen","Summary <small>confirmed</small>":"Resumen <small>confirmados</small>","Sync Progress":"Proceso de Sincronización","Sync Status":"Estado de Sincronización","Sync Type":"Tipo de Sincronización","Synced Blocks":"Bloques Sincornizados","Testnet":"Red de prueba","There are no transactions involving this address.":"No hay transacciones para esta dirección","Time Offset":"Desplazamiento de hora","Timestamp":"Fecha y hora","Today":"Hoy","Total Amount":"Cantidad Total","Total Received":"Total Recibido","Total Sent":"Total Enviado","Transaction":"Transacción","Transaction Output Set Information":"Información del Conjunto de Salida de la Transacción","Transaction Outputs":"Salidas de la Transacción","Transactions":"Transacciones","Type":"Tipo","Unconfirmed":"Sin confirmar","Unconfirmed Transaction!":"¡Transacción sin confirmar!","Unconfirmed Txs Balance":"Balance sin confirmar","Value Out":"Valor de Salida","Version":"Versión","Waiting for blocks...":"Esperando bloques...","Waiting for transactions...":"Esperando transacciones...","by date.":"por fecha.","first seen at":"Visto a","mined":"minado","mined on:":"minado el:","Waiting for blocks":"Esperando bloques"});
    gettextCatalog.setStrings('ja', {"(Input unconfirmed)":"(入力は未検証です)","404 Page not found :(":"404 ページがみつかりません (´・ω・`)","<strong>explorer</strong>  is an <a href=\"http://live.explorer.is/\" target=\"_blank\">open-source blockchain explorer</a> with complete REST and websocket APIs that can be used for writing web wallets and other apps  that need more advanced blockchain queries than provided by bitcoind RPC.  Check out the <a href=\"https://github.com/owstack/explorer-ui\" target=\"_blank\">source code</a>.":"<strong>explorer</strong>は、bitcoind RPCの提供するものよりも詳細なブロックチェインへの問い合わせを必要とするウェブウォレットやその他のアプリを書くのに使える、完全なRESTおよびwebsocket APIを備えた<a href=\"http://live.explorer.is/\" target=\"_blank\">オープンソースのビットコインブロックエクスプローラ</a>です。<a href=\"https://github.com/owstack/explorer-ui\" target=\"_blank\">ソースコード</a>を確認","<strong>explorer</strong> is still in development, so be sure to report any bugs and provide feedback for improvement at our <a href=\"https://github.com/owstack/explorer/issues\" target=\"_blank\">github issue tracker</a>.":"<strong>explorer</strong>は現在開発中です。<a href=\"https://github.com/owstack/explorer/issues\" target=\"_blank\">githubのissueトラッカ</a>にてバグの報告や改善案の提案をお願いします。","About":"はじめに","Address":"アドレス","Age":"生成後経過時間","An error occured in the verification process.":"検証過程でエラーが発生しました。","An error occured:<br>{{error}}":"エラーが発生しました:<br>{{error}}","Application Status":"アプリケーションの状態","Best Block":"最良ブロック","Bitcoin comes with a way of signing arbitrary messages.":"Bitcoinには任意のメッセージを署名する昨日が備わっています。","Bitcoin node information":"Bitcoinノード情報","Block":"ブロック","Block Reward":"ブロック報酬","Blocks":"ブロック","Broadcast Raw Transaction":"生のトランザクションを配信","Bytes Serialized":"シリアライズ後の容量 (バイト)","Can't connect to bitcoind to get live updates from the p2p network. (Tried connecting to bitcoind at {{host}}:{{port}} and failed.)":"P2Pネットワークからライブ情報を取得するためにbitcoindへ接続することができませんでした。({{host}}:{{port}} への接続を試みましたが、失敗しました。)","Can't connect to explorer server. Attempting to reconnect...":"explorer サーバに接続できません。再接続しています...","Can't connect to internet. Please, check your connection.":"インターネットに接続できません。コネクションを確認してください。","Complete":"完了","Confirmations":"検証数","Conn":"接続数","Connections to other nodes":"他ノードへの接続","Current Blockchain Tip (explorer)":"現在のブロックチェインのTip (explorer)","Current Sync Status":"現在の同期状況","Details":"詳細","Difficulty":"難易度","Double spent attempt detected. From tx:":"二重支払い攻撃をこのトランザクションから検知しました：","Error message:":"エラーメッセージ:","Error!":"エラー！","Fee":"手数料","Final Balance":"最終残高","Finish Date":"終了日時","Go to home":"ホームへ","Hash Serialized":"シリアライズデータのハッシュ値","Height":"ブロック高","Included in Block":"取り込まれたブロック","Incoherence in levelDB detected:":"levelDBの破損を検知しました:","Info Errors":"エラー情報","Initial Block Chain Height":"起動時のブロック高","Input":"入力","Last Block":"直前のブロック","Last Block Hash (Bitcoind)":"直前のブロックのハッシュ値 (Bitcoind)","Latest Blocks":"最新のブロック","Latest Transactions":"最新のトランザクション","Loading Address Information":"アドレス情報を読み込んでいます","Loading Block Information":"ブロック情報を読み込んでいます","Loading Selected Date...":"選択されたデータを読み込んでいます...","Loading Transaction Details":"トランザクションの詳細を読み込んでいます","Loading Transactions...":"トランザクションを読み込んでいます...","Loading...":"ロード中...","Message":"メッセージ","Mined Time":"採掘時刻","Mined by":"採掘者","Mining Difficulty":"採掘難易度","Next Block":"次のブロック","No Inputs (Newly Generated Coins)":"入力なし (新しく生成されたコイン)","No blocks yet.":"ブロックはありません。","No matching records found!":"一致するレコードはありません！","No. Transactions":"トランザクション数","Number Of Transactions":"トランザクション数","Output":"出力","Powered by":"Powered by","Previous Block":"前のブロック","Protocol version":"プロトコルバージョン","Proxy setting":"プロキシ設定","Raw transaction data":"トランザクションの生データ","Raw transaction data must be a valid hexadecimal string.":"生のトランザクションデータは有効な16進数でなければいけません。","Received Time":"受信時刻","Redirecting...":"リダイレクトしています...","Search for block, transaction or address":"ブロック、トランザクション、アドレスを検索","See all blocks":"すべてのブロックをみる","Send transaction":"トランザクションを送信","Show Transaction Output data":"トランザクションの出力データをみる","Show all":"すべて表示","Show input":"入力を表示","Show less":"隠す","Show more":"表示する","Signature":"署名","Size":"サイズ","Size (bytes)":"サイズ (バイト)","Skipped Blocks (previously synced)":"スキップされたブロック (同期済み)","Start Date":"開始日時","Status":"ステータス","Summary":"概要","Summary <small>confirmed</small>":"サマリ <small>検証済み</small>","Sync Progress":"同期の進捗状況","Sync Status":"同期ステータス","Sync Type":"同期タイプ","Synced Blocks":"同期されたブロック数","Testnet":"テストネット","The message failed to verify.":"メッセージの検証に失敗しました。","The message is verifiably from {{verification.address}}.":"メッセージは{{verification.address}}により検証されました。","There are no transactions involving this address.":"このアドレスに対するトランザクションはありません。","This form can be used to broadcast a raw transaction in hex format over\n        the Bitcoin network.":"このフォームでは、16進数フォーマットの生のトランザクションをBitcoinネットワーク上に配信することができます。","This form can be used to verify that a message comes from\n        a specific Bitcoin address.":"このフォームでは、メッセージが特定のBitcoinアドレスから来たかどうかを検証することができます。","Time Offset":"時間オフセット","Timestamp":"タイムスタンプ","Today":"今日","Total Amount":"Bitcoin総量","Total Received":"総入金額","Total Sent":"総送金額","Transaction":"トランザクション","Transaction Output Set Information":"トランザクションの出力セット情報","Transaction Outputs":"トランザクションの出力","Transaction succesfully broadcast.<br>Transaction id: {{txid}}":"トランザクションの配信に成功しました。<br>トランザクションID: {{txid}}","Transactions":"トランザクション","Type":"タイプ","Unconfirmed":"未検証","Unconfirmed Transaction!":"未検証のトランザクションです！","Unconfirmed Txs Balance":"未検証トランザクションの残高","Value Out":"出力値","Verify":"検証","Verify signed message":"署名済みメッセージを検証","Version":"バージョン","Waiting for blocks...":"ブロックを待っています...","Waiting for transactions...":"トランザクションを待っています...","by date.":"日毎。","first seen at":"最初に発見された日時","mined":"採掘された","mined on:":"採掘日時:","(Mainchain)":"(メインチェーン)","(Orphaned)":"(孤立したブロック)","Bits":"Bits","Block #{{block.height}}":"ブロック #{{block.height}}","BlockHash":"ブロックのハッシュ値","Blocks <br> mined on:":"ブロック <br> 採掘日","Coinbase":"コインベース","Hash":"ハッシュ値","LockTime":"ロック時間","Merkle Root":"Merkleルート","Nonce":"Nonce","Ooops!":"おぉっと！","Output is spent":"出力は使用済みです","Output is unspent":"出力は未使用です","Scan":"スキャン","Show/Hide items details":"アイテムの詳細を表示または隠す","Waiting for blocks":"ブロックを待っています","by date. {{detail}} {{before}}":"日時順 {{detail}} {{before}}","scriptSig":"scriptSig","{{tx.confirmations}} Confirmations":"{{tx.confirmations}} 検証","<span class=\"glyphicon glyphicon-warning-sign\"></span> (Orphaned)":"<span class=\"glyphicon glyphicon-warning-sign\"></span> (孤立したブロック)","<span class=\"glyphicon glyphicon-warning-sign\"></span> Incoherence in levelDB detected: {{vin.dbError}}":"<span class=\"glyphicon glyphicon-warning-sign\"></span> Incoherence in levelDB detected: {{vin.dbError}}","Waiting for blocks <span class=\"loader-gif\"></span>":"ブロックを待っています <span class=\"loader-gif\"></span>"});
/* jshint +W100 */
}]);