if(String.prototype.padStart == null) {
	String.prototype.padStart = function(length, fill) {
		var padding = "";
		while(padding.length + this.length < length)
			padding += fill.substr(0, length - (padding.length + this.length));
		return padding + this;
	}
}

try {
	eval("let x;"); // this will break the try catch pre-ECMAScript 6
	var html5 = document.getElementsByClassName("html5");
	for(var i = 0; i < html5.length; i++) {
		html5[i].classList.remove("html5");
	}
} catch(e) {}

function updateColor(color) {
	var rgb = [0, 0, 0];


	// Parse into RGB values
	if(typeof color == "object") { // Split RGB 
		var colors = color.getElementsByTagName("input");
		for(var i = 0; i < colors.length; i++) {
			rgb[i] = parseInt(colors[i].value);
		}
	} else {
		// Remove any extra formatting
		color = color.toLowerCase().replace(/\s+/g, " ").replace(/#/g, "").replace(/0x/g, "");

		if(color.length == 3) { // Three digit hex
			for(var i = 0; i < rgb.length; i++)
				rgb[i] = parseInt(color[i] + color[i], 16);
		} else if(color.length == 6) { // Six digit hex
			for(var i = 0; i < rgb.length; i++)
				rgb[i] = parseInt(color.substr(i * 2, 2), 16);
		} else if(color.length == 4) { // BGR15
			var val = parseInt(color, 16);
			rgb[0] = Math.round(( val         & 0x1F) * 255 / 31);
			rgb[1] = Math.round(((val >> 0x5) & 0x1F) * 255 / 31);
			rgb[2] = Math.round(((val >> 0xA) & 0x1F) * 255 / 31);
		} else {
			return alert("Error: Invalid color!");
		}
	}

	// Ensure the colors are valid
	for(var i = 0; i < rgb.length; i++) {
		if(rgb[i] < 0x00 || rgb[i] > 0xFF)
			return alert("Error: Invalid color!");
	}

	// Write to all inputs
	var hex = "#";
	for(var i = 0; i < rgb.length; i++)
		hex += rgb[i].toString(16).padStart(2, "0").toUpperCase();
	document.getElementById("html-text").value = hex;
	document.getElementById("html-color").value = hex;
	
	var bgr15 = ((Math.round(rgb[2] * 31 / 255) & 0x1F) << 10 | (Math.round(rgb[1] * 31 / 255) & 0x1F) << 5 | (Math.round(rgb[0] * 31 / 255) & 0x1F));
	document.getElementById("bgr15-no-bit15").value = "0x" + bgr15.toString(16).padStart(4, "0").toUpperCase();
	document.getElementById("bgr15-bit15").value = "0x" + (bgr15 | 1 << 15).toString(16).padStart(4, "0").toUpperCase();

	document.getElementById("rgb-r").value = rgb[0];
	document.getElementById("rgb-g").value = rgb[1];
	document.getElementById("rgb-b").value = rgb[2];

	document.getElementById("preview").style.backgroundColor = hex;
}

updateColor("#000000");