/*
	VERSION:		1.6
	1.6		Sprites with "underAll" set to true will always appear under all other sprites
	1.5		Added "ignoreList"
	1.4		Sprites with "overAll" set will appear on top of all other sprites
	
	USAGE:
		var addAutoSort;
		#include "functions/autoSort.as"
		sorting_object = addAutoSort( spriteLayer_mc );
		react.to("onload").then = function(){
			clearInterval( sorting_object.loopInterval );
		}
*/
addAutoSort = function( spriteLayer_mc, ignoreList )
{
	// create container
	var _this = new Object();
	
	// Store settings
	_this.spriteLayer_mc = spriteLayer_mc;		// movieClip contaiing all the sprites that will be sorted
	_this.ignoreList = ignoreList || [];			// list of movieClip names to ignore
	_this.parallelSprites = 10;								// number of sprites allowed side-by-side, at the same _y
	
	// Sort the sprites
	_this.loop = function()
	{
		if(_this.spriteLayer_mc._name != undefined)
		{// if:  sprite movieClip exists
			for (var nam in spriteLayer_mc)
			{
				var includeSprite = true;
				for(var i=0; i<ignoreList.length; i++){
					if(nam == ignoreList[i])
						includeSprite = false;
				}// for: ignoreList
				
				if(includeSprite == true)
				{// if:  not ignoring this sprite
					var thisSprite = _this.spriteLayer_mc[nam];
					if(thisSprite._y != 0)
					{// if:  _y is NOT zero  (it would get stuck)
						var newDepth =  thisSprite._y * _this.parallelSprites;
						if(thisSprite.overAll){
							newDepth = 2880 * _this.parallelSprites +_this.parallelSprites;		// max depth for max map height +1
						}else if(thisSprite.underAll){
							newDepth -= 2880;		// current depth - max depth for max map height
						}
						var currentDepth = thisSprite.getDepth();
						var existingSprite = _this.spriteLayer_mc.getInstanceAtDepth(newDepth);
						while (existingSprite != undefined  &&  existingSprite != thisSprite)
						{	// if something exists at the intended depth, and it isn't thisSprite
							newDepth++;
							existingSprite = _this.spriteLayer_mc.getInstanceAtDepth(newDepth);
						}// while:  a movieClip exists at this location
						thisSprite.swapDepths(newDepth);
					}// if:  _y is NOT zero  (it would get stuck)
				}// if:  not ignoring this sprite
			}// for...in:   spriteLayer_mc
		}// if:  sprite movieClip exists
		else
		{// if:  sprite movieClip doesn't exist
			clearInterval( _this.loopInterval );
		}// if:  sprite movieClip doesn't exist
	}// loop()
	_this.loopInterval = setInterval( _this.loop, 1000/30 );		// 30 FPS
	
	// return this object
	return _this;
}// addAutoSort()
