/*

   Based on MooCirclePack version 0.1
   which as Based on http://www.cricketschirping.com/processing/CirclePacking1/CirclePacking1.pde
   and      http://en.wiki.mcneel.com/default.aspx/McNeel/2DCirclePacking

   Copyright (c) 2008 unwieldy studios
   
   Joshua Gross (unwieldy studios)
   twist at unwieldy dot net

   [MIT License]

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:
   
   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.
   
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/


var globalScope = new Array();
// Class for each individual circle
function Circle(x,y,r,c,label,value){

   this.x = x;
   this.y = y;
   this.radius = r;
   this.color = c;
   this.scale = 1;
   this.label = label;
   this.value = value;

   
   // scale is a multiplier that increases or decreases the size of the circle
   // it is mainly used for zooming.
   this.draw = function(canvas, scale) {
      this.scale = scale;
      
      //canvas text for firefox 3.0
      var cx = canvas.getContext('2d');
	if(cx.mozMeasureText && !cx.measureText) {
	    cx.__defineSetter__('font', function(x) { this.mozTextStyle = x;});
	    cx.__defineGetter__('font', function() { return this.mozTextStyle;});
	}
	if(cx.mozMeasureText && !cx.measureText) {
	    cx.measureText = function(text) { return {'width': this.mozMeasureText(text)}; };
	}
	if(cx.mozPathText && !cx.strokeText) {
	    cx.strokeText = function(text, x, y) {
		this.translate(x, y);
		this.mozPathText(text);
		this.stroke();
		this.translate(-x, -y);
	    };
	}
	if(cx.mozDrawText && !cx.fillText) {
	    cx.fillText = function(text, x, y) {
		this.translate(x, y);
		this.mozDrawText(text);
		this.translate(-x, -y);
	    };
	}

	
      
      cx.beginPath();
      cx.arc(this.x, this.y, this.radius * scale, 0, Math.PI * 2, 0);
      cx.closePath();
      
      cx.fillStyle = this.color;
      cx.fill();

//conditional compilation for IE, webkit, and firefox
/*@cc_on
   /*@if (@_win32)
      cx.font = "12px verdana";
      cx.fillStyle = "#fff";
      cx.textAlign = "center";
      cx.fillText( this.label , this.x , this.y+23 );

      cx.font = "bold 22px verdana";
      cx.fillStyle = "#fff";
      cx.textAlign = "center";
      cx.fillText( this.value , this.x , this.y );
     @else @*/ 
	var browse_chrome = /AppleWebKit/.test(navigator.userAgent);
	if (browse_chrome || /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		//if ( true || browse_chrome || ffversion<=3){ //true for debugging purposes
		if (ffversion > 0 && ffversion<=3){ 

		      cx.font = "12px verdana";
		      cx.fillStyle = "#fff";
		      cx.textAlign = "center";
		      cx.fillText( this.label , this.x-cx.measureText(this.label).width/2 , this.y+23 );

		      cx.font = "bold 22px verdana";
		      cx.fillStyle = "#fff";
		      cx.textAlign = "center";
		      cx.fillText( this.value , this.x-cx.measureText(this.value).width/2 , this.y );

		//same as IE, above
		}else{
		      cx.font = "12px verdana";
		      cx.fillStyle = "#fff";
		      cx.textAlign = "center";
		      cx.fillText( this.label , this.x , this.y+23 );

		      cx.font = "bold 22px verdana";
		      cx.fillStyle = "#fff";
		      cx.textAlign = "center";
		      cx.fillText( this.value , this.x , this.y );
		}
	}
   /*@end
@*/

      
   };
   
   this.distanceTo = function(x, y) {
      var dx = this.x - x;
      var dy = this.y - y;
      
      return Math.sqrt((dx*dx) + (dy*dy));
   };
   
   this.contains = function(x, y) {
      var dx = this.x - x;
      var dy = this.y - y;
      
      return Math.sqrt((dx*dx) + (dy*dy)) <= (this.radius * this.scale);
   };
   
   this.intersects = function(otherCircle) {
      var dx = otherCircle.x - this.x;
      var dy = otherCircle.y - this.y;
      
      var d  = Math.sqrt((dx*dx) + (dy*dy));
      
      return (d < (this.radius * this.scale)) || (d < (otherCircle.radius * this.scale));
   };
}

function Vector2D(x,y){
    this.x = x;
    this.y = y;
    
    
    this.normalize = function() {
       this.magnitude = Math.sqrt((this.x * this.x) + (this.y * this.y));
       
       this.x = this.x / this.magnitude;
       this.y = this.y / this.magnitude;
    };
    
    this.mult = function(m) {
       this.x *= m;
       this.y *= m;
    };
}
 

// Main circle packing class
function CirclePack(canvas,circles){
   
   this.canvas = canvas;
   this.circles = circles;
   this.dragCircle = null;
   this.scale = 1;
   
   
   this.iterator = function(iteration) {
      /*
      this.circles.sort( function(circle1, circle2) {
      
      var dtc1 = circle1.distanceTo( parseInt($(canvas).css('width')) / 2, parseInt($(canvas).css('height')) / 2);
      var dtc2 = circle2.distanceTo( parseInt($(canvas).css('width')) / 2, parseInt($(canvas).css('height')) / 2);
      
      if(dtc1 < dtc2)
         return 1;
      else if(dtc1 > dtc2)
         return -1;
      else
         return 0;
   });
   */
      
      var ci, cj;
      var v = new Vector2D(0,0);
      
      for(var i = 0; i < this.circles.length; i++) {
         ci = this.circles[i];
         
         for(var j = i + 1; j < this.circles.length; j++) {
            if(i == j)
               continue;
               
            cj = this.circles[j];
            
            var dx = cj.x - ci.x;
            var dy = cj.y - ci.y;
            var d  = (dx * dx) + (dy * dy);
            var r  = (cj.radius * this.scale) + (ci.radius * this.scale);
            
            if(d < ((r * r) - 0.01) && false ) {
               v.x = dx;
               v.y = dy;
               
               v.normalize();
               v.mult((r - Math.sqrt(d)) * 0.5);
               
               if(cj != this.dragCircle) {
                  cj.x += v.x;
                  cj.y += v.y;
               }

               if(ci != this.dragCircle) {
                  ci.x -= v.x;
                  ci.y -= v.y;
               }
            } 

		if( false && cj.y-cj.radius<=10 ){
		        var v = new Vector2D(0,0);
			v.y = -(cj.y-cj.radius-10);
			var d = v.y*v.y;
			v.normalize();
			v.mult( (cj.radius-Math.sqrt(d))*0.5);
			cj.y += v.y;
		        var v = new Vector2D(0,0);
			v.y = -(cj.y-cj.radius-10);
			var d = v.y*v.y;
			v.normalize();
			v.mult( (cj.radius-Math.sqrt(d))*0.5);
			ci.y -= v.y;
		}
		if( cj.y-cj.radius<=0 ){
		}
		if( ci.y+ci.radius>=360 ){
			/*
			console.log( '+c' + ci.label );
		        var v = new Vector2D(0,0);
			v.y = -(ci.y+ci.radius);
			var d = v.y*v.y;
			v.normalize();
			v.mult( (ci.radius-Math.sqrt(d))*0.5);
			ci.y -= v.y;
			*/
		}
		if( ci.y+ci.radius>=360 ){
			/*
			console.log( ci.y+ci.radius );
			console.log( '+c' + ci.label );
		        var v = new Vector2D(0,0);
			v.y = -(ci.y+ci.radius);
			var d = v.y*v.y;
			v.normalize();
			v.mult( (ci.radius-Math.sqrt(d))*0.5);
			ci.y -= v.y;
			console.log( 'affected' + ci.label );
		        var v = new Vector2D(0,0);
			v.y = -(ci.y+ci.radius);
			var d = v.y*v.y;
			v.normalize();
			v.mult( (ci.radius-Math.sqrt(d))*0.5);
			cj.y += v.y;
			*/
		}


         }
      }

      // decrease the amount that the circles are contracted by 2% each time,
      // providing the "settling" effect/objective.
      this.damping *= 0.98;
      //this.contract(this.damping);
   };
   
   this.contract = function(damping) {
      if(damping < 0.01)
         return;
      
      var x, y;   
      
      for(var i = 0; i < this.circles.length; i++) {
         if(this.circles[i] == this.dragCircle)
            continue;
            
         x = (this.circles[i].x - ( parseInt($(canvas).css('width')) / 2)) * damping;
         y = (this.circles[i].y - ( parseInt($(canvas).css('height')) / 2)) * damping;

         this.circles[i].x -= x;
         this.circles[i].y -= y;
      }
   },
   
   this.draw = function() {
      var cx = this.canvas.getContext('2d');
      cx.clearRect(0, 0, parseInt($(canvas).css('width')) , parseInt($(canvas).css('height')) );
      
      for(var i = 0; i < this.circles.length; i++)
         this.circles[i].draw(this.canvas, this.scale);
   };
   
   this.run = function(it) {
      this.iteration = it ? it : 1;
      this.damping = it ? Math.pow(0.98, it) * 0.1 : 0.1;
      
      if(this.runner)
         clearInterval(this.runner);//$$clear(this.runner);
      
      // Unfortunately, in browsers, it is currently impractical to run a for-loop
      // on the circle packing algorithm. Instead, we do it with a timer which,
      // while more sloppy, allows the processor to breathe and prevents the browser
      // from locking up.
	/*
	if( document.all ){//IE detection
		globalScope[ this.label ] = this;
		setInterval( 'ieIntervalHandler("'+this.label+'","_run")', 30 );
	}else{
		this.runner = setInterval( function(thisCircle){ thisCircle._run() } , 30 , this );
	}
	*/
	this._run();

      
      //this.fireEvent('settleStart');
   };
   
   this._run = function() {
      this.draw();
      
      this.iterator(this.iteration++);
      
      // stop the iterator at a reasonable point, to free up the processor
      if(this.damping < 0.007) {
         clearInterval(this.runner);//$$clear(this.runner);
         
         //this.fireEvent('settleEnd');
	      /*
	      for(var i = 0; i < this.circles.length; i++) {
		 console.log(this.circles[i].label)
		 console.log(this.circles[i].x)
		 console.log(this.circles[i].y)
	      }
	      */
      }
   };

}

function ieIntervalHandler( id, strFunc ){
	var scope = globalScope[id];
	eval( "scope." + strFunc + "()"  );
}

