var angular = require('angular');
require('ngIonic');
require('../modules');
var module = angular.module('commons.directives.breadcrumb');

module.directive('sinoBreadcrumbContent', function($window, $ionicScrollDelegate) {
  return {
    restrict: 'C',
    link: function(scope, element) {
      var sinoBreadcrumbScrollView = $ionicScrollDelegate. $getByHandle('sinoBreadcrumbScrollView');

      scope.$watch('items', function() {
        element[0].style.width = '100000px';//解决在内容区域宽度不够导致换行情况下计算的sino-breadcrumb-item宽度偏小的问题。
        $window.setTimeout(function() {
          resize();
        }, 15);
      }, true);

      function resize() {
        var content = element[0],
          items = content.querySelectorAll('.sino-breadcrumb-item'),
          width = 1, //避免safari浏览器上的0.xpx问题导致宽度计算不够的bug
          item = null;

        for (var i = 0, len = items.length; i < len; i++) {
          item = items[i];
          width += item.offsetWidth;
        }

        content.style.width = width + 'px';
        sinoBreadcrumbScrollView.scrollTo(width);
      }
    }
  };
});

module.directive('sinoBreadcrumbItem', function($window) {
  return {
    restrict: 'C',
    link: function(scope, element) {
      element.on('click', function() {
        element.addClass('actived');
        $window.setTimeout(function() {
          element.removeClass('actived');
        }, 200);
      });
    }
  };
});

module.directive('sinoBreadcrumb', function() {
  return {
    restrict: 'AE',
    replace: true,
    templateUrl: 'views/commons/directives/sinoBreadcrumb.tpl.html',
    scope: {
      first: '=',
      items: '=',
      loading: '=',
      _onClick: '&onItemClick'
    },
    link: function(scope) {
      scope.onClick = function(item, index) {
        if (scope.items && scope.items.length - 1 > index) {
          if (scope._onClick) {
            scope._onClick({item: item, index: index});
          }
          scope.items.splice(index + 1, scope.items.length - index);
        }
      };
    }
  };
});
