 @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
 

directive("macScrollSpyTarget", [
  "scrollSpy"
  (scrollSpy) ->
    compile: (element, attrs) ->
      target         = attrs.macScrollSpyTarget
      highlightClass = attrs.macScrollSpyTargetClass or "active"
      unless target
        throw new Error("Missing scroll spy target name")

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

      ($scope, element, attrs) ->
        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?
          scrollSpy.addListener callback

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

        if interpolate
          attrs.$observe "macScrollSpyTarget", (value) -> register value
        else
          register target

])

# @name mac-scroll-spy-anchor
# @description
# Section in the spied element
# @param {String} id                    ID to identify anchor
# @param {String} mac-scroll-spy-anchor ID to identify anchor (user either id or this attribute)
# @param {Event}  refresh-scroll-spy    To refresh the top offset of all scroll spy anchors
#

directive("macScrollSpyAnchor", [
  "scrollSpy"
  (scrollSpy) ->
    link: ($scope, element, attrs) ->
      id         = attrs.id or attrs.macScrollSpyAnchor
      registered = false

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

      registering = ->
        scrollSpy.register id, element

        # Only add $destroy listener on initial run
        unless registered
          $scope.$on "$destroy", -> scrollSpy.unregister id

        registered = true

      # Reregister anchor to update position/offset
      $scope.$on "refresh-scroll-spy", registering

      # Check if id is interpolated value
      if /{{(.*)}}/.test id
        observeKey = if attrs.id then "id" else "macScrollSpyAnchor"
        attrs.$observe observeKey, (value) ->
          if value? and value
            id = value
            registering()
      else
        registering()
]).

#
