/*
color_utils.js.php

Copyright (c) Gareth Hadfield 2008
*/

function rgb_to_hex(r,g,b){
  return("#" +
    zero_pad(dec_to_hex(r), 2) +
    zero_pad(dec_to_hex(g), 2) +
    zero_pad(dec_to_hex(b), 2));
}

function rgb_gamma_to_hex(r, g, b, aGamma){
  // r g b = 0...255
  // aGamma = -1...1
  var aGammaPercent = (aGamma + 1);
  r = Math.min(255, parseInt(r * aGammaPercent, 10));
  g = Math.min(255, parseInt(g * aGammaPercent, 10));
  b = Math.min(255, parseInt(b * aGammaPercent, 10));
  return("#" +
    zero_pad(dec_to_hex(r), 2) +
    zero_pad(dec_to_hex(g), 2) +
    zero_pad(dec_to_hex(b), 2));
}

function gamma_precent(aGamma){
  // returns gamma as 0...2
  return(aGamma + 1);
}

function get_gamma(aGamma){
  // returns gamma as 0...255
  return(gamma_precent(aGamma) / 2 * 255);
}

function get_r_value(aColor){
  var result;
  if(is_color(aColor)){
    result = hex_to_dec(aColor.substr(1,2));
  }
  return(result);
}

function get_g_value(aColor){
  var result;
  if(is_color(aColor)){
    result = hex_to_dec(aColor.substr(3,2));
  }
  return(result);
}

function get_b_value(aColor){
  var result;
  if(is_color(aColor)){
    result = hex_to_dec(aColor.substr(5,2));
  }
  return(result);
}

function get_shade(aColor){
  return((get_r_value(aColor) + get_g_value(aColor) + get_b_value(aColor)) / 3);
}

function is_color(aString){
  var result = false;
  result = (aString != undefined) &&
    (aString.length==7) && (aString.substr(0,1) == "#") &&
    (hex_to_dec(aString.substr(1,2)) != NaN) &&
    (hex_to_dec(aString.substr(3,2)) != NaN) &&
    (hex_to_dec(aString.substr(5,2)) != NaN);
  return(result);
}


