 @param {Integer} mac-scroll-spy-offset Top offset when calculating scroll position
 ###
 angular.module("Mac").directive("macScrollSpy", [
+  "$window"
   "scrollSpy"
   "scrollSpyDefaults"
   "util"
-  (scrollSpy, defaults, util) ->
+  ($window, scrollSpy, defaults, util) ->
     link: ($scope, element, attrs) ->
       options = util.extendAttributes "macScrollSpy", defaults, attrs
 
       spyElement =
         if element[0].tagName is "BODY"
-          angular.element window
+          angular.element $window
         else
           element
 

# @name mac-scroll-spy-anchor
# @description
# Section in the spied element
# @param {Event} refresh-scroll-spy To refresh the top offset of all scroll spy anchors
#

directive("macScrollSpyAnchor", [
  "scrollSpy"
  (scrollSpy) ->
    compile: (element, attrs) ->
      id         = attrs.id or attrs.macScrollSpyAnchor
      observeKey = if attrs.id then "id" else "macScrollSpyAnchor"

      unless id
        throw new Error("Missing scroll spy anchor id")

      interpolate = id.match /{{(.*)}}/

      ($scope, element, attrs) ->
        registering  = ->
          return unless id
          scrollSpy.register id, element
          $scope.$on "$destroy", -> scrollSpy.unregister id

        $scope.$on "refresh-scroll-spy", registering

        if interpolate
          attrs.$observe observeKey, (value) ->
            id = value
            registering()
        else
          registering()
]).

#

directive("macScrollSpyTarget", [
  "scrollSpy"
  (scrollSpy) ->
    link: ($scope, element, attrs) ->
      target         = attrs.macScrollSpyTarget
      highlightClass = attrs.macScrollSpyTargetClass or "active"
      registered     = false

      unless target
        throw new Error("Missing scroll spy target name")

      register = (id) ->
        return unless id

        callback = (active) ->
          action = if id is active.id then "addClass" else "removeClass"
          element[action] highlightClass

        # Update target class if target is re-rendered
        callback scrollSpy.active if scrollSpy.active?

        unless registered
          scrollSpy.addListener callback
          $scope.$on "$destroy", -> scrollSpy.removeListener callback

      if /{{(.*)}}/.test target
        attrs.$observe "macScrollSpyTarget", (value) -> register value
      else
        register target

])
