/*
 * ImpactJS Per-Pixel Collision Detection Plugin
 * Written by Abraham Walters
 * v1.0 - January 2012
 * v1.1 - August 2012
 *
 */
ig.module(
	'plugins.perpixel'
)
.requires(
	'impact.impact',
	'impact.image',
	'impact.entity'
)
.defines(function () {

    ig.Image.inject({

        alphas: [],
        alphasLoaded: false,

        loadAlphas: function(){
            var canvas = ig.$new( 'canvas' );
            canvas.width = this.data.width;
            canvas.height = this.data.height;
            var ctx = canvas.getContext( '2d' );

            ctx.drawImage( this.data, 0, 0 );
            var pixels = ctx.getImageData( 0, 0, this.data.width, this.data.height ).data,
                aIndex = 0,
                width = this.data.width * 4,
                height = this.data.height * width;

            for( var y = 3; y < height; y += width ){
                for( var x = 0; x < width; x += 4 ){
                    this.alphas[aIndex++] = pixels[x + y] ? true : false;
                }
            }
            this.alphasLoaded = true;
        },

        onload: function( event ){
            if ( !this.alphasLoaded ){
                this.loadAlphas();
            }
            this.parent( event );
        }

    });

    ig.Entity.inject({
             
     
		 touches: function( other ){
			  if( ig.global.wm || this.currentAnim === null || other.currentAnim === null ){
                return this.parent( other );
				}
				var radius1=0;
				var radius2=0;
				
				if( typeof other.radius != "undefined" &&  typeof this.radius != "undefined" ){
					if( typeof this.name=="undefined" && this.name == "player_organism"){
				var tile = this.currentAnim.tile;
		          var index=parseInt(tile/7);
		          if(index == (tile/7)){
		         index--;
		          }
				  radius1=this.radius[index];
				  radius2=other.radius;
				}else if( typeof other.name=="undefined" && other.name == "player_organism"){
                  var tile = other.currentAnim.tile;
		          var index=parseInt(tile/7);
		          if(index == (tile/7)){
		         index--;
		          }
				  radius1=this.radius;
				  radius2=other.radius[index]; 
                  }	else{
				   radius1=this.radius;
				  radius2=other.radius; 
				  }
				  }
				  
				  if(this.distanceTo(other) <= (radius1+radius2));
				  {
				  return true;
				  }
				return false;

			 
		}
          

    });

});