package com.squidder.base.baseLoader.types {
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	import com.squidder.base.baseLoader.BaseLoaderProperties;	

	/**
	 * Loader item for images (.jpg, .png, etc).
	 * @author Jon Reiling
	 */
	public class ImageItem extends BaseLoaderItem {

		private var _loader : Loader;

		/**
		 * Item constructor.
		 * @param url URL of the item.
		 * @param props Properties, if any, of the item.
		 */
		public function ImageItem(url : String, props : BaseLoaderProperties) {
			super( url , props );
			
			_loader = new Loader( );
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE , _handleComplete , false , 0 , true );
			_loader.contentLoaderInfo.addEventListener( Event.INIT , _handleInit , false , 0 , true );
			_loader.contentLoaderInfo.addEventListener( ProgressEvent.PROGRESS , _handleProgress , false , 0 , true );
			_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR , _handleError , false , 0 , true );
		}

		/**
		 * Begin loading the item.
		 */
		override public function load() : void {
			
			_loader.load( new URLRequest( _url ) , _props.loaderContext );	
		}

		/**
		 * Set the content of the item for access.
		 */
		override protected function _setContent() : void {
			_content = _loader.content;
		}		
		
		protected function _handleInit( event : Event ) : void {
			_content = _loader.content;
			dispatchEvent( event );
		}

		/**
		 * Clean out the item.
		 */
		override public function clean() : void {
			
			_loader.contentLoaderInfo.removeEventListener( Event.COMPLETE , _handleComplete );
			_loader.contentLoaderInfo.removeEventListener( Event.INIT , _handleInit );
			_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS , _handleProgress );
			_loader.contentLoaderInfo.removeEventListener( IOErrorEvent.IO_ERROR , _handleError );
			
			try {
				_loader.close();
			} catch ( e:* ) { }

			_loader = null;
			
			if ( !_props.isPersistent ){
				
				_content = null;	
			}
		}
	}
}
