function rgbToHsl(r, g, b)
{ 
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var l = (max + min) / 2;
    var h = 0;
    var s = 0;
    if(max != min)
    {
        if (l<.5)
        {
           s= (max - min) / (max + min);
        }
        else
        {
           s=(max - min) / (2 - max - min);
        }
        if (r==max) 
        {
           h = (g-b)/(max-min)/6;
        }
        if (g==max) 
        {
           h = (2.0 + (b-r)/(max-min))/6;
        }
        if (b==max) 
        {
           h = (4.0 + (r-g)/(max-min))/6;
        }
    }
    if(h < 0)
    {
        h += 1;
    }
    return [h, s, l];
}


//calculate rgb component
function hToC(x, y, h)
{
    var c;
    if(h < 0)
    {
        h += 1;
    }
    if(h > 1)
    {
        h -= 1;
    }
    if (h<1/6)
    {
       c=x +(y - x) * h * 6;
    }
    else
    {
       if(h < 1/2)
       {
          c=y;
       }
       else
       {
          if(h < 2/3)
          {
             c=x + (y - x) * (2 / 3 - h) * 6;
          }
          else
          {
             c=x;
          }
       }
       
    }
    return c;
} 

//convert hsl to rgb (all values 0..1)
function hslToRgb(h, s, l){ 
    var
        y = (l > .5)?
            l + s - l * s:
            l * (s + 1),
        x = l * 2 - y,
        r = hToC(x, y, h + 1 / 3),
        g = hToC(x, y, h),
        b = hToC(x, y, h - 1 / 3);
    return [r, g, b];
}

//convert hsl to an html color string
function hslToHtmlColor(h,s,l)
{
   var rgb=hslToRgb(h,s,l);
   return "#"+toHex(rgb[0]*255)+toHex(rgb[1]*255)+toHex(rgb[2]*255);
}

//convert decimal to hex
function toHex(decimal,places) 
{
   if(places == undefined || isNaN(places))  places = 2;
   var hex = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
   var next = 0;
   var hexidecimal = "";
   decimal=Math.floor(decimal);
   while(decimal > 0)
   {
      next = decimal % 16;
      decimal = Math.floor((decimal - next)/16);
      hexidecimal = hex[next] + hexidecimal;
      }
   while (hexidecimal.length<places) 
   {
      hexidecimal = "0"+hexidecimal;
   }
   return hexidecimal;
}

