Binding:: =
	## ==========================================================================
	## Instance-mutating methods
	## ========================================================================== 
	convertToLive: (force)->
		_ = @
		switch @type
			when 'ObjectProp'
				propertyDescriptor = Object.getOwnPropertyDescriptor(@object, @property) or dummyPropertyDescriptor
				shouldWriteLiveProp = force or propertyDescriptor.configurable
				import [browserOnly] prototype.convertToLive-StylingConstructorCheck.coffee
				
				if shouldWriteLiveProp
					@isLiveProp = true
					
					Object.defineProperty @object, @property,
						configurable: true
						enumerable: propertyDescriptor.enumerable
						get: ()-> _.value
						set: if propertyDescriptor.set
								(newValue)-> propertyDescriptor.set(newValue); _.setValue(newValue); return
							else
								(newValue)-> _.setValue(newValue); return
			


			when 'Array'
				arrayMutatorMethods.forEach (method)->
					Object.defineProperty _.value, method, 
						configurable: true
						value: ()->
							result = Array::[method].apply _.value, arguments
							_.updateAllSubs(_)
							return result

				
				if settings.trackArrayChildren and not @trackedChildren
					@trackedChildren = [] # Required so we can add new children that are bound to a specific index of this array
					@updateSelf = ()-> _.updateAllSubs(_) # Saved to 'this' so it can be reused when adding new children in .setObject
					
					@value.forEach (item, index)->
						_.trackedChildren.push(''+index)
						
						SimplyBind(index, OPTS_NOUPDATE).of(_.value)
							.to _.updateSelf



			when 'Proxy'
				origFn = @origFn = @value
				context = @object
				@value = result:null, args:null

				if checkIf.isFunction(origFn)
					slice = [].slice
					
					@object[@property] = ()-> 
						args = slice.call(arguments)
						_.value.args = args = if _.selfTransform then _.selfTransform(args) else args
						_.value.result = result = origFn.apply(context, args)
						_.updateAllSubs(_)
						return result

		return




	addSub: (sub, options, updateOnce)->
		if sub.isMulti
			@addSub(subItem, options, updateOnce) for subItem in sub.bindings
		else
			if metaData=@subsMeta[sub.ID]
				alreadyHadSub = true
			else
				sub.pubsMap[@ID] = @
				@subs.unshift(sub)
				
				metaData = @subsMeta[sub.ID] = genObj()
				metaData.updateOnce = updateOnce
				metaData.opts = cloneObject(options)
				metaData.opts.updateEvenIfSame = true if @type is 'Event' or @type is 'Proxy'
				metaData.valueRef = if sub.type is 'Func' then 'valuePassed' else 'value'
			
		return alreadyHadSub



	removeSub: (sub, bothWays)->
		if sub.isMulti
			@removeSub(subItem, bothWays) for subItem in sub.bindings
		else
			if @subsMeta[sub.ID]
				@subs.splice(@subs.indexOf(sub), 1)
				delete @subsMeta[sub.ID]
				delete sub.pubsMap[@ID]

			if bothWays
				sub.removeSub(@)
				delete @pubsMap[sub.ID]

		if @subs.length is 0 and Object.keys(@pubsMap).length is 0
			@destroy() # Since it's no longer a subscriber or has any subscribers
	
		return

	

	removeAllSubs: (bothWays)->
		@removeSub(sub, bothWays) for sub in @subs.slice()
		return




	destroy: ()-> # Resets object to initial state (pre-binding state)
		delete boundInstances[@ID]
		@removePollInterval()
		
		if @type is 'Event'
			@unRegisterEvent(event, @customEventMethod.listen) for event in @attachedEvents
			delete @object._sb_map

		else if @type is 'Array'
			delete @object._sb_ID
			delete @object[method] for method in arrayMutatorMethods
		
		else if @type is 'Func'
			delete @object._sb_ID

		else
			if @type is 'ObjectProp'
				Object.defineProperty @object, @property, {'value':@value, 'writable':true}
			
			else if @type is 'Proxy'
				@object[@property] = @origFn
			
			delete @object._sb_map
			delete @object._sb_ID


		return







	## ==========================================================================
	## Value-related methods
	## ========================================================================== 
	fetchDirectValue: ()->
		type = @type
		switch
			when type is 'Func' then @object()
			when type is 'Array' then @object
			import [browserOnly] prototype.fetchDirectValue-DOMTypes.coffee
			else @object[@property]
	



	setValue: (newValue, publisher, fromSelf)->
		publisher ||= @
		newValue = @selfTransform(newValue) if @selfTransform
		
		switch @type
			when 'ObjectProp'
				@object[@property] = newValue if not @isLiveProp and newValue isnt @value import [browserOnly] prototype.setValue-DOMText.coffee

			when 'Pholder'
				parent = @parentBinding
				parent.pholderValues[@pholder] = newValue
				entireValue = applyPlaceholders(parent.pholderContexts, parent.pholderValues, parent.pholderIndexMap)
				import [browserOnly] prototype.setValue-Pholder-DOMText.coffee	
				parent.setValue(entireValue, publisher, true)

			when 'Func'
				prevValue = @valuePassed
				newValue = newValue.slice() if publisher.type is 'Array' and newValue is publisher.value
				@valuePassed = newValue
				newValue = @object(newValue, prevValue)

			when 'Event'
				if not fromSelf
					@isEmitter = true
					@emitEvent(newValue)
					@isEmitter = false
		
			import [browserOnly] prototype.setValue-DOMTypes.coffee
		
		@value = newValue
		@updateAllSubs(publisher)

		return





	updateAllSubs: (publisher)-> if @subs.length
		if @throttleRate
			currentTime = +(new Date)
			timePassed = currentTime - @lastUpdate
			
			if timePassed < @throttleRate
				clearTimeout(@throttleTimeout)
				return @throttleTimeout = setTimeout (()=> @updateAllSubs(publisher)), @throttleRate-timePassed
			else
				@lastUpdate = currentTime
		

		i = (arr=@subs).length
		@updateSub(arr[i], publisher) while i--
		
		return



			

	updateSub: (sub, publisher)->
		return if (publisher is sub) or (publisher isnt @ and publisher.subsMeta[sub.ID]) # indicates this is an infinite loop

		meta = @subsMeta[sub.ID]
		newValue = @value
		subValue = sub[meta.valueRef]
		newValue = if transform=meta.transformFn then transform(newValue, subValue, sub.object) else newValue

		return if newValue is subValue and not meta.opts.updateEvenIfSame or
			meta.conditionFn and not meta.conditionFn(newValue, subValue, sub.object)

		# Why do we need the 'promiseTransforms' option when we can just check for the existance of .then method?
		# Because tests show that when searching for the .then prop on the object results in a performance slowdown of up to 30%!
		# Checking if the promiseTransforms option is enabled first eliminates unnecessary lookups & slowdowns.
		if meta.opts.promiseTransforms and newValue and checkIf.isFunction(newValue.then)
			newValue.then (newValue)-> sub.setValue(newValue, publisher); return
		else
			sub.setValue(newValue, publisher)

		@removeSub(sub) if meta.updateOnce
		return



















	## ==========================================================================
	## Transforms & Conditions
	## ==========================================================================
	addModifierFn: (target, subInterfaces, subjectFn, updateOnBind)->
		if not checkIf.isFunction(subjectFn)
			throwWarning('fnOnly',2)

		else
			for subInterface in subInterfaces
				subscriber = subInterface._ or subInterface # Second is chosen when the passed subscriber interfaces multi-binding (is a recursive call of this method)

				if subscriber.isMulti
					@addModifierFn(target, subscriber.bindings, subjectFn, updateOnBind)
				
				else
					subMetaData = @subsMeta[subscriber.ID]
					subMetaData[target] = subjectFn
					updateOnBind = updateOnBind and not subMetaData.updateOnce

					if @pubsMap[subscriber.ID]
						subscriber.subsMeta[@ID][target] = subjectFn

					@updateSub(subscriber, @) if (updateOnBind or @type is 'Func') and target is 'transformFn'

			return true



	setSelfTransform: (transformFn, updateOnBind)->
		@selfTransform = transformFn
		@setValue(@value) if updateOnBind
		return













	## ==========================================================================
	## Placeholders
	## ========================================================================== 
	scanForPholders: ()-> unless @pholderValues
		@pholderValues = genObj()
		@pholderIndexMap = genObj()
		@pholderContexts = []

		if checkIf.isString(@value)
			@pholderContexts = @value.split pholderRegExSplit
			
			index = 0
			@value = @value.replace pholderRegEx, (e, pholder)=>
				@pholderIndexMap[index++] = pholder
				@pholderValues[pholder] = pholder
		
		import [browserOnly] prototype.scanForPholders-DOMText.coffee
		return
	







	## ==========================================================================
	## Polling
	## ========================================================================== 
	addPollInterval: (time)-> if @type isnt 'Event'
		@removePollInterval()
		
		@pollInterval = setInterval ()=>
			polledValue = @fetchDirectValue()

			@setValue polledValue
		, time


	removePollInterval: ()->
		clearInterval(@pollInterval)
		@pollInterval = null










	## ==========================================================================
	## Events
	## ========================================================================== 
	import [browserOnly] prototype.addUpdateListener.coffee
	
	attachEvents: ()->
		if @eventName
			@registerEvent @eventName, @customEventMethod.listen
		import [browserOnly] prototype.attachEvents-DOM.coffee
		return
	


	registerEvent: (eventName, customInMethod)-> if not targetIncludes(@attachedEvents, eventName)
		import [browserOnly] prototype.registerEvent.defaultInMethod-browser.coffee
		import [nodeOnly] prototype.registerEvent.defaultInMethod-node.coffee

		@attachedEvents.push(eventName)
		attachmentMethod = customInMethod or defaultInMethod
		
		@invokeEventMethod(eventName, attachmentMethod, defaultInMethod)
		return



	unRegisterEvent: (eventName, customMethod)->
		indexOfEvent = @attachedEvents.indexOf eventName
		return if indexOfEvent is -1
		import [browserOnly] prototype.unRegisterEvent.defaultRemoveMethod-browser.coffee
		import [nodeOnly] prototype.unRegisterEvent.defaultRemoveMethod-node.coffee

		@attachedEvents.splice(indexOfEvent, 1)
		removalMethod = customMethod or defaultRemoveMethod

		@invokeEventMethod(eventName, removalMethod, defaultRemoveMethod)
		return




	invokeEventMethod: (eventName, eventMethod, backupMethod)->
		subject = @object
		import [browserOnly] prototype.invokeEventMethod-jQuery.coffee
		eventMethod = backupMethod unless subject[eventMethod]
		@eventHandler = handleUpdateFromEvent.bind(@) unless @eventHandler#exists

		subject[eventMethod]? eventName, @eventHandler
		return



	emitEvent: (extraData)->
		subject = @object
		import [browserOnly] prototype.emitEvent.defaultOutMethod-browser.coffee
		import [nodeOnly] prototype.emitEvent.defaultOutMethod-node.coffee
		
		emitMethod = @customEventMethod.emit or defaultOutMethod
		import [browserOnly] prototype.emitEvent-jQuery.coffee
		emitMethod = defaultOutMethod unless subject[emitMethod]#exists

		import [browserOnly] prototype.emitEvent-dispatchEventObject.coffee
		subject[emitMethod](@eventName, extraData)
		return




handleUpdateFromEvent = ()-> unless @isEmitter
	fetchedValue = if @type is 'Event' then arguments[@property] else @fetchDirectValue()

	@setValue(fetchedValue, null, true)
	return





