'use strict';

var angular = require('angular');
require('../modules');
var module = angular.module('infoDisplay.directives');
module.directive('sinoTabsNavigationBar', function($ionicScrollDelegate, $timeout ) {
  return {
    restrict: 'E',
    templateUrl: 'views/infoDisplay/sinoTabItem.tpl.html',
    link: function(scope, element, attrs) {
      var scrollView = $ionicScrollDelegate.$getByHandle('modelsScrollView');
      var screen_width = window.screen.width;

      scope.$on('infoModelChange', function(event, selectedItemId) {
        var selectedIndex = scope.getSelectedIndex(selectedItemId);
        setPosition(selectedIndex);
      });

      scope.onClickTab = function(item) {
        scope.$broadcast('infoModelChange', item.id, scope.selectedItems);
      };
      
      init();
      
      function init() {
        $timeout(setPosition);
      }
      
      function setPosition(selectedIndex) {
        var scrollLeft = scrollView.getScrollPosition().left;
        var item_dom = document.querySelectorAll('a.control-item')[selectedIndex];
        if (item_dom) {
          var item_width = item_dom.offsetWidth;
          var item_left = item_dom.offsetLeft - scrollLeft;
          if(item_left != (screen_width / 2)) {
            var offsetLeft = item_left - screen_width / 2 + item_width / 2 + scrollLeft;
            scrollView.scrollTo(offsetLeft, 0, true);
          }
        }
      }
    }
  };
});


