Scriptname _00E_ScrollUnlockAlias extends ReferenceAlias Hidden 

event OnPlayerLoadGame()
	if UnlockScrollEquipped()
		GotoState("Equipped")
	endif
endevent

Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference)
	if akBaseObject as Scroll && _00E_UnlockScrolls.HasForm(akBaseObject)
		GotoState("Equipped")
	endif
endEvent

bool function UnlockScrollEquipped()
	Actor PlayerREF = GetReference() as Actor
	if PlayerREF.IsEquipped(_00E_UnlockScrolls)
		return true
	endif
	Form leftHand = PlayerREF.GetEquippedObject(0)
	return leftHand && _00E_UnlockScrolls.HasForm(leftHand)
endfunction

Event OnUpdate()
	if UnlockScrollAliases.IsStopped()
		if ! UnlockScrollAliases.Start()
			RegisterForSingleUpdate(0.1)
		endif
	elseif UnlockScrollAliases.IsStopping()
		RegisterForSingleUpdate(0.01)
	elseif UnlockScrollAliases.IsStarting()
		RegisterForSingleUpdate(0.01)
	endif
EndEvent

state Equipped
	event OnPlayerLoadGame()
		if ! UnlockScrollEquipped()
			GotoState("")
		endif
	endevent

	event OnBeginState()
		ObjectReference actorRef = GetReference()
		RegisterForAnimationEvent(actorRef, "BeginCastRight")
		RegisterForAnimationEvent(actorRef, "BeginCastLeft")
	endevent
	
	event OnEndState()
		ObjectReference actorRef = GetReference()
		UnregisterForAnimationEvent(actorRef, "BeginCastRight")
		UnregisterForAnimationEvent(actorRef, "BeginCastLeft")
	endevent
	
	Event OnUpdate()
		if UnlockScrollAliases.IsStopped()
			if ! UnlockScrollAliases.Start()
				RegisterForSingleUpdate(0.1)
			endif
		elseif UnlockScrollAliases.IsStopping()
			RegisterForSingleUpdate(0.01)
		elseif UnlockScrollAliases.IsStarting()
			RegisterForSingleUpdate(0.01)
		endif
	EndEvent

	Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference)
		; do nothing
	endEvent

	Event OnObjectUnequipped(Form akBaseObject, ObjectReference akReference)
		if ! UnlockScrollEquipped()
			GotoState("")
		endif
	endEvent

	Event OnAnimationEvent(ObjectReference akSource, string asEventName)
		ObjectReference crosshairRef = Game.GetCurrentCrosshairRef()

		if crosshairRef
			Form baseObject = crosshairRef.GetBaseObject()
			if baseObject as Container || baseObject as Door
				ScrollTarget.ForceRefTo(crosshairRef)
				UnlockScrollAliases.Stop()
				return
			endif
		endif
		
		UnlockScrollAliases.Stop()
		RegisterForSingleUpdate(0.01)
		ScrollTarget.Clear()
	endEvent
endstate

Quest Property UnlockScrollAliases Auto  
FormList Property _00E_UnlockScrolls  Auto  
ReferenceAlias Property ScrollTarget  Auto