//
// BCU (Bugimus Color Utilities)
//
// invertColor() - returns complement color
// threeToSix() - converts #0033cc to #0033cc
// sixToThree() - converts #0033cc to #03c
//

function BCU_invertColor(incolor) {
	var myhex = new Array ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
	var chhex = new Array
	incolor = 0xffffff - parseInt("0x" + incolor.slice(1))
	for(rval="#",i=5; i>=0; i--) rval += myhex[ Math.floor(incolor/Math.pow(16,i))%16 ]
	return rval //+= myhex[incolor%16]
}

// requires color to follow this format: #000
function BCU_threeToSix(incolor) {
	if(incolor.length==4)
		return incolor.slice(0,-2) + incolor.slice(1,-2) + incolor.slice(2,-1) + incolor.slice(2,-1) + incolor.slice(3) + incolor.slice(3) 
	else
		return incolor
}

// requires color to follow this format: #000000
function BCU_sixToThree(incolor) {
	var returncolor
	
	document.writeln("incolor = "+incolor)
	document.write("<br />")
	document.write(incolor.slice(1,-4))
	document.write("<br />")
	document.write(incolor.slice(3,-2))
	document.write("<br />")
	document.write(incolor.slice(5))
	document.write("<br />")

	return returncolor
}

function BCU_blackOrWhite(incolor) {
	if(parseInt("0x" + incolor.slice(1)) <= (0xffffff/2)) return "#FFFFFF"
	else return "#000000"
}

// ------------------------------------------------------------------------
// BCU_makeLegible
// Accepts background color and determines whether black or white will be 
// the most legible text color to use upon it.  This determination is 
// based on the background color's luminance value.
//
// return value: black or white
// ------------------------------------------------------------------------
function BCU_makeLegible(backgroundcolor) {
	var color = BCU_computeLuminance( backgroundcolor )

	if (color <= 118) return "#FFFFFF"
	else return "#000000"
}

// ------------------------------------------------------------------------
// BCU_getRedAsHex
// accepts 6 char hex color value
// return value: Red component as a hex string
// ------------------------------------------------------------------------
function BCU_getR(incolor) {
	return incolor.slice(1,-4)
}

function BCU_getG(incolor) {
	return incolor.slice(3,-2)
}

function BCU_getB(incolor) {
	return incolor.slice(5)
}

function BCU_computeLuminance(incolor) {
	// luminance, Y=0.30 R + 0.59 G + 0.11 B
	luminance = 0.30 * parseInt("0x" + BCU_getR(incolor)) 
	          + 0.59 * parseInt("0x" + BCU_getG(incolor)) 
			  + 0.11 * parseInt("0x" + BCU_getB(incolor))
	return parseInt(luminance)
}
