

// Returns a color that is contrasted with the passed color
@function text-color-for($color) {
    @return contrasting-color($color, $color-text-light, $color-text-dark);
}

// darken the color, with brighter colors given more weight
@function darkened($color) {
    @return darken($color, brightness($color) / 4);
}

// lighten the color, with darker colors given more weight
@function lightened($color) {
    @return lighten($color, (100 - brightness($color)) / 4);
}

// subtly tint a color towards another
@function tint($color, $accent) {
    $brightness-color: brightness($color);
    $brightness-accent: brightness($accent);
    $difference: abs($brightness-color - $brightness-accent);
    @return mix($color, $accent, $difference);
}


/***
    Code from: <http://www.antimath.info/css/sass-sqrt-function/>
*/

@function sqrt($r) {
  $x0: 1;
  $x1: $x0;
 
  @for $i from 1 through 10 {
    $x1: $x0 - ($x0 * $x0 - abs($r)) / (2 * $x0);
    $x0: $x1;
  }
 
  @return $x1;
}


/***
    Code from: <https://gist.github.com/jlong/f06f5843104ee10006fe>
*/

// Brightness math based on:
//   http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx

$red-magic-number: 241;
$green-magic-number: 691;
$blue-magic-number: 68;
$brightness-divisor: $red-magic-number + $green-magic-number + $blue-magic-number;

@function brightness($color) {
  // Extract color components
  $red-component: red($color);
  $green-component: green($color);
  $blue-component: blue($color);

  // Calculate a brightness value in 3d color space between 0 and 255
  $number: sqrt((($red-component * $red-component * $red-magic-number) + ($green-component * $green-component * $green-magic-number) + ($blue-component * $blue-component * $blue-magic-number)) / $brightness-divisor);

  // Convert to percentage and return
  @return 100% * $number / 255;
}

@function contrasting-color($color, $light, $dark) {
  @if brightness($color) < 65% {
    @return $light;
  } @else {
    @return $dark;
  }
}