/*
include mootools 1.2 modules:
- Selectors
- Class Extras
- Browser
*/

//var u = new Utils();
var isIE     = Browser.Engine.trident;
var isMoz    = Browser.Engine.gecko;
var isSafari = Browser.Engine.webkit;

var Rounder = new Class({

	Implements:Options,
	
	options:{
		tl: { radius: 20 },
		tr: { radius: 20 },
		bl: { radius: 20 },
		br: { radius: 20 },
		antiAlias: true,
		autoPad: true,
		validTags: ["div"]
	},

	initialize:function(options){
	  			
		this.boxes = null;
		this.validElements = [];
		this.curvyObjects = [];
		
		// Check parameters
		if(typeof(arguments[0]) != "object"){ alert("First parameter of curvyCorners() must be an object."); return; };
		if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string"){
			alert("Second parameter of curvyCorners() must be an object or a class name."); 
			return;
		}
		
		this.setOptions(options);
		this.prepareRounder(arguments);
	},
	
	prepareRounder:function(args){
		//Get object(s)
		if(args.length == 2 && args[1].indexOf('.') == 0){//is it's a class
			this.boxes = $$(args[1]);
		} else if(args.length != 2 || args[1].indexOf('.') != 0){//if it's a div list
			this.boxes = $A(args).slice(1).map(function(item){ return $(item); });
		} else { alert('arguments error'); }

		this.validElements = (this.options.validTags) ? this.options.validTags : ["div"];

		// Loop through each argument
		this.boxes.each(function(box,index){
			//console.log(box)
			if(box){ 
				var currentTag = box.get('tag') 
				if(this.validElements.contains(currentTag)){
				  this.curvyObjects.push(new CurvyObject(this.options, this.boxes[index]));
				}
			}
		}.bind(this));
		
		//console.log(this.curvyObjects)

	},//end prepareRounder()
	
	applyCornersToAll:function(){
		this.curvyObjects.each(function(obj){ obj.applyCorners() });
	}
	
});//END ROUNDER


/* CURVYOBJECT CLASS */

var CurvyObject = new Class({

	initialize:function(){
		
		//Setup Globals
		this.settings        = arguments[0];
		this.box             = arguments[1];
		this.topContainer    = null;
		this.bottomContainer = null;	  
		this.contentDIV      = null;
		this.masterCorners   = [];

		//Set formatting details/propertes
		this.boxHeight       = this.box.getScrollSize().y;
		this.boxWidth        = this.box.getScrollSize().x;
		this.borderWidth     = this.box.getStyle("borderTopWidth").toInt();
		
		//console.log(this.borderWidth)
		
		this.borderColour    = this.box.getStyle("borderTopColor");
		this.borderString    = this.borderWidth + "px" + " solid " + this.borderColour;
		this.boxColour       = (this.box.getStyle('backgroundColor') != 'transparent') ? this.box.getStyle('backgroundColor') : '#ffffff';
		this.backgroundImage = (this.box.getStyle("backgroundImage") != 'none') ? this.box.getStyle("backgroundImage") : "";
		this.boxPadding      = this.box.getStyle("paddingTop").toInt();
		this.boxContent      = this.box.innerHTML;
		var boxPosition      = this.box.getStyle("position");
		
		// Make box relative if not already absolute and remove any padding
		if(boxPosition != "absolute"){ this.box.setStyle('position','relative'); };
		this.box.setStyle('padding','0');

		// If IE and height and width are not set, we need to set width so that we get positioning
		// NOTA: per ora non implemento, forse non serve
		//if(this.isIE && boxWidth == "auto" && boxHeight == "auto"){ this.box.setStyle('width',"100%"); };
		
		// BOH: Resize box so that it stays to the orignal height
		
		// Remove content if box is using autoPad
		if(this.settings.autoPad == true && this.boxPadding > 0){
			this.box.innerHTML = "";
		}

		//console.log(backgroundImage);
	},//end initialize
	
	createNewMainContainer:function(){
		var newMainContainer = new Element('div',{
			'styles':{
				'width':'100%',
				'fontSize':'1px',
				'overflow':'hidden',
				'position':'absolute',
				'left':0 - this.borderWidth + "px",
				'paddingLeft':this.borderWidth + 'px',
				'paddingRight':this.borderWidth + 'px'
			}
		});
		
		return newMainContainer;
	},
	
	/*
	This method creates the corners and
	applies them to the div element.
	*/
	applyCorners:function(){
	  /*
	  Create top and bottom containers.
	  These will be used as a parent for the corners and bars.
	  */

	  for(var t = 0; t < 2; t++){
		  switch(t){
			  case 0: //Top
				  // Only build top bar if a top corner is to be draw
				  if(this.settings.tl || this.settings.tr){
					  var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0);
					  
					  var newMainContainer = this.createNewMainContainer();
					  newMainContainer.set({
					  	'styles':{ 'height': topMaxRadius + "px", 'top': 0 - topMaxRadius + "px" }
					  });
					  this.topContainer = newMainContainer.inject(this.box);
				  }
				  break;
			 
			  case 1://Bottom
				  // Only build bottom bar if a top corner is to be draw
				  if(this.settings.bl || this.settings.br){
					  var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0);
					  
					  var newMainContainer = this.createNewMainContainer();
					  newMainContainer.set({
					  	'styles':{ 'height': botMaxRadius + "px", 'bottom': 0 - botMaxRadius + "px" }
					  });
					  this.bottomContainer = newMainContainer.inject(this.box);
				  }
				  break;
		  }//fine switch
	  }//fine for
	
	  // Turn off current borders
	  if(this.topContainer){ this.box.setStyle('borderTopWidth','0'); }
	  if(this.bottomContainer){ this.box.setStyle('borderBottomWidth','0'); }
		
	  // Create array of available corners
	  var corners = ["tr", "tl", "br", "bl"];
	
	  /* Loop for each corner */
	  
	  for(var i in corners){
		  // FIX for prototype lib
		  if(i > -1 < 4){
			  // Get current corner type from array
			  var cc = corners[i];
	
			  // Has the user requested the currentCorner be round?
			  if(!this.settings[cc]){
				  // No
				  if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)){
					  // We need to create a filler div to fill the space upto the next horzontal corner.
					  
						var newCorner = new Element('div',{
							'styles':{
								'fontSize':'1px',
								'overflow':'hidden',
								'position':'relative'
							}
						});
					  
					  
//					  var newCorner = document.createElement("DIV");
	
					  // Setup corners properties
// 					  newCorner.style.position = "relative";
// 					  newCorner.style.fontSize = "1px";
// 					  newCorner.style.overflow = "hidden";
	
					  // Add background image?

					  
					  if(this.backgroundImage == ""){
//						newCorner.style.backgroundColor = this.boxColour;
						newCorner.setStyle('backgroundColor',this.boxColour);
					  } else {
//						newCorner.style.backgroundImage = this.backgroundImage;
						newCorner.setStyle('backgroundImage',this.backgroundImage);
					  }
					  
					  switch(cc){
						  case "tl":
						  	  newCorner.set({
						  	  	'styles':{
						  	  		'height':topMaxRadius - this.borderWidth + "px",
							  		'marginRight':this.settings.tr.radius - (this.borderWidth*2) + "px",
							  		'borderLeft':this.borderString,
							  		'borderTop':this.borderString,
							  		'left':-this.borderWidth + "px"
						  	  	}
						  	  });
							  
							  break;
	
						  case "tr":
						  	  newCorner.set({
						  	  	'styles':{
						  	  		'height':topMaxRadius - this.borderWidth + "px",
							  		'marginLeft':this.settings.tl.radius - (this.borderWidth*2) + "px",
							  		'borderRight':this.borderString,
							  		'borderTop':this.borderString,
							  		'backgroundPosition':"-" + (topMaxRadius + this.borderWidth) + "px 0px",
							  		'left':this.borderWidth + "px"
						  	  	}
						  	  });
							  break;
	
						  case "bl":
						  	  newCorner.set({
						  	  	'styles':{
						  	  		'height':botMaxRadius - this.borderWidth + "px",
							  		'marginRight':this.settings.br.radius - (this.borderWidth*2) + "px",
							  		'borderLeft':this.borderString,
							  		'borderBottom':this.borderString,
							  		'backgroundPosition':"-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px",
							  		'left':-this.borderWidth + "px"
						  	  	}
						  	  });
						  	  break;
	
						  case "br":
						  	  newCorner.set({
						  	  	'styles':{
						  	  		'height':botMaxRadius - this.borderWidth + "px",
							  		'marginLeft':this.settings.bl.radius - (this.borderWidth*2) + "px",
							  		'borderRight':this.borderString,
							  		'borderBottom':this.borderString,
							  		'backgroundPosition':"-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px",
							  		'left':this.borderWidth + "px"
						  	  	}
						  	  });
							  break;
					  }//fine switch
				  }//fine if interno ((cc..)
			  } else {
				  
// 				  PERFORMANCE NOTE:
// 	
// 				  If more than one corner is requested and a corner has been already
// 				  created for the same radius then that corner will be used as a master and cloned.
// 				  The pixel bars will then be repositioned to form the new corner type.
// 				  All new corners start as a bottom right corner.
				  
				  if(this.masterCorners[this.settings[cc].radius]) {
					  // Create clone of the master corner
//					  NOTA: vedere per clonare i nodi.
					  var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);
				  } else {
					  // Yes, we need to create a new corner
					  
					  var newCorner = new Element('div',{
							'styles':{
								'height':this.settings[cc].radius + "px",
								'width':this.settings[cc].radius + "px",
								'fontSize':'1px',
								'overflow':'hidden',
								'position':'absolute'
							}
					  });
					  
// 					  var newCorner = document.createElement("DIV");
// 					  newCorner.style.height = this.settings[cc].radius + "px";
// 					  newCorner.style.width  = this.settings[cc].radius + "px";
// 					  newCorner.style.position = "absolute";
// 					  newCorner.style.fontSize = "1px";
// 					  newCorner.style.overflow = "hidden";
	
					  // THE FOLLOWING BLOCK OF CODE CREATES A ROUNDED CORNER
					  // ---------------------------------------------------- TOP
	
					  // Get border radius
					  var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth);
	
					  // Cycle the x-axis
					  for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++){
						  // Calculate the value of y1 which identifies the pixels inside the border
						  if((intx +1) >= borderRadius)
							var y1 = -1;
						  else
							var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1);
	
						  // Only calculate y2 and y3 if there is a border defined
						  if(borderRadius != j){
							  if((intx) >= borderRadius)
								var y2 = -1;
							  else
								var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2)));
	
							  if((intx+1) >= j)
								var y3 = -1;
							  else
								var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);
						  }
	
						  // Calculate y4
						  if((intx) >= j){
							var y4 = -1;
						  } else {
							var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2)));
						  }
						  
						  // Draw bar on inside of the border with foreground colour
						  if(y1 > -1){ this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); }
	
						  // Only draw border/foreground antialiased pixels and border if there is a border defined
						  if(borderRadius != j){
							  // Cycle the y-axis
							  for(var inty = (y1 + 1); inty < y2; inty++){
								  // Draw anti-alias pixels
								  if(this.settings.antiAlias){
									  // For each of the pixels that need anti aliasing between the foreground and border colour draw single pixel divs
									  if(this.backgroundImage != ""){
									  	  //METODO: PIXELFRACT;
										  var borderFract = (pixelFraction(intx, inty, borderRadius) * 100);
	
										  //METODO: DRAWPIXEL;
										  if(borderFract < 30){
												this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);
										  } else {
												this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);
										  }
									  } else {
									  	  //METODO: BLENDCOLOUR;
										  var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius));
										  this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);
									  }//fine if interno
								  }//fine if esterno
							  }//fine for
	
							  // Draw bar for the border
							  if(this.settings.antiAlias){
								  if(y3 >= y2){
									 if (y2 == -1) y2 = 0;
									 //METODO: DRAWPIXEL;
									 this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);
								  }
							  } else {
								  if(y3 >= y1){
								  //METODO: DRAWPIXEL;
									  this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);
								  }
							  }
	
							  // Set the colour for the outside curve
							  var outsideColour = this.borderColour;
						  } else {
							  // Set the coour for the outside curve
							  var outsideColour = this.boxColour;
							  var y3 = y1;
						  }//fine if(borderRadius...)
	
						  // Draw aa pixels?
						  if(this.settings.antiAlias){
							  // Cycle the y-axis and draw the anti aliased pixels on the outside of the curve
							  for(var inty = (y3 + 1); inty < y4; inty++){
							  	//METODO: DRAWPIXEL, PIXELFRACTION;
								  // For each of the pixels that need anti aliasing between the foreground/border colour & background draw single pixel divs
								  this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);
							  }//fine for
						  }//fine if
					  }//fine for (var intx = 0....)
	
					  // END OF CORNER CREATION
					  // ---------------------------------------------------- END
					 
					 //NOTA: VEDERE SE UNTILIZZA CLONE() DI MOOTOOLS
					 
					  // We now need to store the current corner in the masterConers array
					  this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);
				  }//fine else di if(this.masterCorners[this.settings....)
	
				  /*
				  Now we have a new corner we need to reposition all the pixels unless
				  the current corner is the bottom right.
				  */
				  if(cc != "br"){
					  // Loop through all children (pixel bars)
					  
					  //NOTA: semplificare il for, magari con getChildren()
					  for(var t = 0, k = newCorner.childNodes.length; t < k; t++){
						  // Get current pixel bar
//						  var pixelBar = newCorner.childNodes[t];
						  var pixelBar = newCorner.getChildren()[t];
						  //console.log(pixelBar)

						  // Get current top and left properties
						  var pixelBarTop    = pixelBar.getStyle('top').toInt();
						  var pixelBarLeft   = pixelBar.getStyle('left').toInt();
						  var pixelBarHeight = pixelBar.getStyle('height').toInt();

// 						  var pixelBarTop    = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px")));
// 						  var pixelBarLeft   = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px")));
// 						  var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px")));
	
						  // Reposition pixels
						  if(cc == "tl" || cc == "bl"){
							  //pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px"; // Left
							  pixelBar.setStyle('left',this.settings[cc].radius -pixelBarLeft -1); // Left
						  }
						  
						  if(cc == "tr" || cc == "tl"){
							  //pixelBar.style.top =  this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px"; // Top
							  pixelBar.setStyle('top',this.settings[cc].radius -pixelBarHeight -pixelBarTop);// Top
						  }
	
						  switch(cc){
							  case "tr":
								  //pixelBar.style.backgroundPosition  = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px";
								  pixelBar.setStyle('backgroundPosition',"-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px");
								  break;
	
							  case "tl":
								  //pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1)  - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px";
								  pixelBar.setStyle('backgroundPosition',"-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px");
								  break;
	
							  case "bl":
								  //pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px";
								  pixelBar.setStyle('backgroundPosition',"-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px");
								  break;
						  }//fine switch
					  }//fine for interno
				  }//fine if(cc..)
			  }//fine else di if(!settings[cc...)

			  if(newCorner){
			  	  //NOTA: si possono accorciare
				  // Position the container
				  switch(cc){
					  case "tl":
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('top','0'); }
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('left','0'); }
						if(this.topContainer){ this.topContainer.grab(newCorner); }
						break;
	
					  case "tr":
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('top','0'); }
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('right','0'); }
						if(this.topContainer){ this.topContainer.grab(newCorner); }
						break;
	
					  case "bl":
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('bottom','0'); }
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('left','0'); }
						if(this.bottomContainer){ this.bottomContainer.grab(newCorner); }
						break;
	
					  case "br":
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('bottom','0'); }
						if(newCorner.getStyle('position') == "absolute") { newCorner.setStyle('right','0'); }
						if(this.bottomContainer){ this.bottomContainer.grab(newCorner); }
						break;
				  }//fine switch
			  }//fine if
		  }//fine if(i > -1 < 4)...
	  }//fine for(var i in corners...
	
	  /*
	  The last thing to do is draw the rest of the filler DIVs.
	  We only need to create a filler DIVs when two corners have
	  diffrent radiuses in either the top or bottom container.
	  */
	
	  // Find out which corner has the bigger radius and get the difference amount
	  var radiusDiff = [];
	  radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius);
	  radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius);
	
	  for(z in radiusDiff){
		  // FIX for prototype lib
		  if(z == "t" || z == "b"){
			  if(radiusDiff[z]){
				  // Get the type of corner that is the smaller one
				  var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius) ? z +"l" : z +"r");
				  
				  var newFiller = new Element('div',{
						'styles':{
							'height':radiusDiff[z] + "px",
							'width':this.settings[smallerCornerType].radius+ "px",
							'fontSize':'1px',
							'overflow':'hidden',
							'position':'absolute',
							'backgroundColor':this.boxColour
						}
				  });
	
				  // Position filler
				  switch(smallerCornerType){
					  case "tl":
						  newFiller.setStyle('bottom','0');
						  newFiller.setStyle('left','0');
						  newFiller.setStyle('borderLeft',this.borderString);
						  this.topContainer.grab(newFiller);
						  break;
	
					  case "tr":
						  newFiller.setStyle('bottom','0');
						  newFiller.setStyle('right','0');
						  newFiller.setStyle('borderRight',this.borderString);
						  this.topContainer.grab(newFiller);
						  break;
	
					  case "bl":
						  newFiller.setStyle('top','0');
						  newFiller.setStyle('left','0');
						  newFiller.setStyle('borderLeft',this.borderString);
						  this.bottomContainer.grab(newFiller);
						  break;
	
					  case "br":
						  newFiller.setStyle('top','0');
						  newFiller.setStyle('right','0');
						  newFiller.setStyle('borderRight',this.borderString);
						  this.bottomContainer.grab(newFiller);
						  break;
				  }//fine switch
			  }//fine if(radius..)
	
			  // Create the bar to fill the gap between each corner horizontally
			  
			  var newFillerBar = new Element('div',{
					'styles':{
						'fontSize':'1px',
						'overflow':'hidden',
						'position':'relative',
						'backgroundColor':this.boxColour,
						'backgroundImage':this.backgroundImage
					}
			  });
	
			  switch(z){
				  case "t":
					  // Top Bar
					  if(this.topContainer){
						  // Edit by Asger Hallas: Check if settings.xx.radius is not false
						  if(this.settings.tl.radius && this.settings.tr.radius){
						  	  
						  	  newFillerBar.set({
						  	  	'styles':{
									'height':topMaxRadius - this.borderWidth + "px",
							  		'marginLeft':this.settings.tl.radius - this.borderWidth + "px",
							  		'marginRight':this.settings.tr.radius - this.borderWidth + "px",
							  		'borderTop':this.borderString
						  	  	}
						  	  });
	
							  if(this.backgroundImage != ""){
								newFillerBar.setStyle('backgroundPosition',"-" + (topMaxRadius + this.borderWidth) + "px 0px");
							  }
							  
							  this.topContainer.grab(newFillerBar);
						  }//fine (if(this.settings.tl....)
	
						  // Repos the boxes background image
						  this.box.setStyle('backgroundPosition',"0px -" + (topMaxRadius - this.borderWidth) + "px");
					  }
					  break;

				  case "b":
					  if(this.bottomContainer){
						  // Edit by Asger Hallas: Check if settings.xx.radius is not false
						  if(this.settings.bl.radius && this.settings.br.radius){
							  // Bottom Bar
								newFillerBar.set({
									'styles':{
										'height':botMaxRadius - this.borderWidth + "px",
										'marginLeft':this.settings.bl.radius - this.borderWidth + "px",
										'marginRight':this.settings.br.radius - this.borderWidth + "px",
										'borderBottom':this.borderString
									}
								});
	
								if(this.backgroundImage != ""){
									newFillerBar.setStyle('backgroundPosition','-' + (botMaxRadius + this.borderWidth) + 'px -' + (this.boxHeight + (topMaxRadius + this.borderWidth)) + 'px');
								}
							  
							  this.bottomContainer.grab(newFillerBar);
						  }//fine if interno
					  }//fine if esterno 
					  break;
			  }//fine switch
		  }//fine if(z..)
	  }//fine for(z in radiusDiff)..
	
	  /*
	  AutoPad! apply padding if set.
	  */
	  if(this.settings.autoPad == true && this.boxPadding > 0){
		  //Create content container

		  var contentContainer = new Element('div',{
				'styles':{
					'position':'relative'
				},
				'class':"autoPadDiv",
				'html':this.boxContent
		  });
	
		  //Get padding amounts
		  var topPadding = Math.abs(topMaxRadius - this.boxPadding);
		  var botPadding = Math.abs(botMaxRadius - this.boxPadding);
	
		  //Apply top padding
		  if(topMaxRadius < this.boxPadding)
			contentContainer.setStyle('paddingTop',topPadding + "px");
	
		  //Apply Bottom padding
		  if(botMaxRadius < this.boxPadding)
			contentContainer.setStyle('paddingBottom',botMaxRadius + "px");
	
		  //Apply left and right padding
		  contentContainer.setStyle('paddingLeft',this.boxPadding + "px");
		  contentContainer.setStyle('paddingRight',this.boxPadding + "px");
	
		  //Append contentContainer
		  this.contentDIV = this.box.grab(contentContainer);
	  }//fine if autopad
	},//FINE APPLY CORNERS
	
  /*
  This function draws the pixles
  */
	drawPixel:function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius){
	  // Create pixel
	  var pixel = new Element('div',{
		'styles':{
	  		'height':height + "px",
	  		'width':"1px",
	  		'fontSize':"1px",
	  		'overflow':"hidden",
			'position':'absolute'
		}
	  });
	
	  // Max Top Radius
	  var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius);
	
	  // Dont apply background image to border pixels
	  if(image == -1 && this.backgroundImage != ""){
		  pixel.setStyle('backgroundImage',this.backgroundImage);
		  pixel.setStyle('backgroundPosition',"-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px");
	  } else {
		  pixel.setStyle('backgroundColor',colour);
	  }
	
	  // Set opacity if the transparency is anything other than 100
	  if (transAmount != 100)
	  
	  setOpacity(pixel, transAmount);
	  //pixel.setStyle('opacity',transAmount/100)
	
	  // Set the pixels position
	  pixel.setStyle('top',inty + "px");
	  pixel.setStyle('left',intx + "px");
	
	  newCorner.grab(pixel);
	}//fine drawPixel()
	
});//END CURVYOBJECT

/* UTILITY FUNCTIONS */

/*
Blends the two colours by the fraction
returns the resulting colour as a string in the format "#FFFFFF"
*/
function BlendColour(Col1, Col2, Col1Fraction){
	var red1 = parseInt(Col1.substr(1,2),16);
	var green1 = parseInt(Col1.substr(3,2),16);
	var blue1 = parseInt(Col1.substr(5,2),16);
	var red2 = parseInt(Col2.substr(1,2),16);
	var green2 = parseInt(Col2.substr(3,2),16);
	var blue2 = parseInt(Col2.substr(5,2),16);
	
	if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1;
	
	var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction)));
	if(endRed > 255) endRed = 255;
	if(endRed < 0) endRed = 0;
	
	var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction)));
	if(endGreen > 255) endGreen = 255;
	if(endGreen < 0) endGreen = 0;
	
	var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction)));
	if(endBlue > 255) endBlue = 255;
	if(endBlue < 0) endBlue = 0;
	
	return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);
}

/*
Converts a number to hexadecimal format
*/
function IntToHex(strNum){
  base = strNum / 16;
  rem = strNum % 16;
  base = base - (rem / 16);
  baseS = MakeHex(base);
  remS = MakeHex(rem);

  return baseS + '' + remS;
}


/*
gets the hex bits of a number
*/
function MakeHex(x){
  if((x >= 0) && (x <= 9)){
	  return x;
  } else {
	  switch(x) {
		  case 10: return "A";
		  case 11: return "B";
		  case 12: return "C";
		  case 13: return "D";
		  case 14: return "E";
		  case 15: return "F";
	  }
  }//fine else
}//fine

// Returns an array of rbg values
function rgb2Array(rgbColour){
  // Remove rgb()
  var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")"));

  // Split RGB into array
  var rgbArray = rgbValues.split(", ");

  return rgbArray;
}

function pixelFraction(x, y, r){
	var pixelfraction = 0;
	
	/*
	determine the co-ordinates of the two points on the perimeter of the pixel that the
	circle crosses
	*/
	var xvalues = new Array(1);
	var yvalues = new Array(1);
	var point = 0;
	var whatsides = "";
	
	// x + 0 = Left
	var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2)));
	
	if ((intersect >= y) && (intersect < (y+1))){
	  whatsides = "Left";
	  xvalues[point] = 0;
	  yvalues[point] = intersect - y;
	  point =  point + 1;
	}
	
	// y + 1 = Top
	var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2)));
	
	if ((intersect >= x) && (intersect < (x+1))){
	  whatsides = whatsides + "Top";
	  xvalues[point] = intersect - x;
	  yvalues[point] = 1;
	  point = point + 1;
	}
	
	// x + 1 = Right
	var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2)));
	
	if ((intersect >= y) && (intersect < (y+1))){
	  whatsides = whatsides + "Right";
	  xvalues[point] = 1;
	  yvalues[point] = intersect - y;
	  point =  point + 1;
	}
	
	// y + 0 = Bottom
	var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2)));
	
	if ((intersect >= x) && (intersect < (x+1))){
	  whatsides = whatsides + "Bottom";
	  xvalues[point] = intersect - x;
	  yvalues[point] = 0;
	}
	
	/*
	depending on which sides of the perimeter of the pixel the circle crosses calculate the
	fraction of the pixel inside the circle
	*/
	switch (whatsides){
		  case "LeftRight":
		  pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2);
		  break;
	
		  case "TopRight":
		  pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2);
		  break;
	
		  case "TopBottom":
		  pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2);
		  break;
	
		  case "LeftBottom":
		  pixelfraction = (yvalues[0]*xvalues[1])/2;
		  break;
	
		  default:
		  pixelfraction = 1;
	}
	
	return pixelfraction;
}//fine pixelFraction


//NOTA: Sostituire le istanze con setStyle()
function setOpacity(obj, opacity){
	opacity = (opacity == 100)?99.999:opacity;
	
	if(isSafari && obj.tagName != "IFRAME"){
	  // Get array of RGB values
	  var rgbArray = rgb2Array(obj.style.backgroundColor);
	
	  // Get RGB values
	  var red   = parseInt(rgbArray[0]);
	  var green = parseInt(rgbArray[1]);
	  var blue  = parseInt(rgbArray[2]);
	
	  // Safari using RGBA support
	  obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";
	}
	
	else if(typeof(obj.style.opacity) != "undefined"){
	  // W3C
	  obj.style.opacity = opacity/100;
	}
	
	else if(typeof(obj.style.MozOpacity) != "undefined"){
	  // Older Mozilla
	  obj.style.MozOpacity = opacity/100;
	}
	
	else if(typeof(obj.style.filter) != "undefined"){
	  // IE
	  obj.style.filter = "alpha(opacity:" + opacity + ")";
	}
	
	else if(typeof(obj.style.KHTMLOpacity) != "undefined"){
	  // Older KHTML Based Browsers
	  obj.style.KHTMLOpacity = opacity/100;
	}
}//fine






