//	ColourMod v2.1 Plug-N-Play
//  DHTML Dynamic Color Picker/Selector
//	© 2005 ColourMod.com
//	Design/Programming By Stephen Hallgren (www.teevio.net)
//	Produced By The Noah Institute (www.noahinstitute.org)

	var _currentColourDiv = 0, _coloursChecked = false;
	var rgb = new Array();
	var hsv = new Array();
	var hex = new Array();
	var H,S,V,sliderX,sliderY,dotX,dotY;
	
	//Set Drag Status To False
	var isdrag = false;
	var ie = document.all;
	var nn6 = document.getElementById && !document.all;
	var colorselector = "default";
	var scrollLeftOffset = 0;
	var scrollTopOffset = 0;
	var detect = navigator.userAgent.toLowerCase();
	var OS,browser,total,thestring;
	var version = 0;
	var _pickerType = "";

	function pickcolor(_type) {
		_pickerType = _type;
		var _hex = $("cmHex").value;
		if (isHex(_hex)) {
			hexUpdate();
		} else {
			$("cmHex").value = "FFFFFF";
		}

		if (_pickerType == "p") {
			for (_i=0;_i<5;_i++) {
				$("newColourName" + _i).value = "";
			}
		} else {
			addColourReference(_hex);
		}

		$("ColourMod").style.display = "block";
		$("cmHex").onkeyup = hexUpdate;
		$("ColourMod").onmousedown = selectmouse;
		$("ColourMod").onmouseup = unselectmouse;
		if (nn6) {
			$("cmHex").type = "search";
		}
	}

	function checkIt(string) {
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	}

	function getScrollXY() {
		var scrollOffset = new Array();
		if (document.documentElement && document.documentElement.scrollTop) {
			scrollOffset["x"] = document.documentElement.scrollLeft;
			scrollOffset["y"] = document.documentElement.scrollTop;
		} else if (document.body) {
			scrollOffset["x"] = document.body.scrollLeft;
			scrollOffset["y"] = document.body.scrollTop;
		}
		return scrollOffset;
	}

	function selectmouse(e) {
		mouseX = nn6 ? e.clientX : event.clientX;
		mouseY = nn6 ? e.clientY : event.clientY;

		scrollOffset = getScrollXY();
		if (!scrollOffset["y"]) {
			scrollOffset["y"] = 0;
		}
		if (!scrollOffset["x"]) {
			scrollOffset["x"] = 0;
		}

		//Adjust for positioning
		if (checkIt("safari")) {
			dotX = (mouseX - 24 - $("ColourMod").offsetLeft);
			dotY = (mouseY - 53 - $("ColourMod").offsetTop);
			sliderX = (mouseX - 185 - $("ColourMod").offsetLeft);
			sliderY = (mouseY - 52 - $("ColourMod").offsetTop);
		} else {
			dotX = (mouseX - 24 - $("ColourMod").offsetLeft + scrollOffset["x"]);
			dotY = (mouseY - 53 - $("ColourMod").offsetTop + scrollOffset["y"]);
			sliderX = (mouseX - 185 - $("ColourMod").offsetLeft + scrollOffset["x"]);
			sliderY = (mouseY - 52 - $("ColourMod").offsetTop + scrollOffset["y"]);
		}

		//Check to see if mouse is in the selection area
		if ((0 <= dotX) && (dotX <= 150) && (0 <= dotY) && (dotY <= 150)) {
			isdrag = true;
			cancelNewColours();
			$("cmBlueDot").style.left = dotX + "px";
			$("cmBlueDot").style.top = dotY + "px";
			arrowY = replaceString($("cmBlueArrow").style.top,"px","");

			H = Math.round(YToH(arrowY));
			S = XToS(dotX);
			V = YToV(dotY);

			$("cmHue").value = H;
			rgb = HSVToRGB(H,S,V);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmHex").value = hex;
			updateHexDiv(hex);
			$("cmColorContainer").style.backgroundColor = ("#" + hex);
			document.onmousemove = dragSV;
		} else if ((0 <= sliderX) && (sliderX <= 35) && (0 <= sliderY) && (sliderY <= 150)) {
			isdrag = true;
			cancelNewColours();
			$("cmBlueArrow").style.top = (dotY + "px");

			sliderY = replaceString($("cmBlueArrow").style.top,"px","");
			dotX = replaceString($("cmBlueDot").style.left,"px","");
			dotY = replaceString($("cmBlueDot").style.top,"px","");

			H = YToH(sliderY);
			S = XToS(dotX);
			V = YToV(dotY);

			rgb = HSVToRGB(H,100,100);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);
			$("cmSatValBg").style.backgroundColor = ("#" + hex);
			$("cmHue").value = H;

			rgb = HSVToRGB(H,S,V);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmHex").value = hex;
			updateHexDiv(hex);
			$("cmColorContainer").style.backgroundColor = ("#" + hex);
			document.onmousemove = dragH;
		}
	}

	function unselectmouse(e) {
		isdrag = false;
		newColours();
	}

	function hexUpdate() {
		hex = $("cmHex").value;

		if (isHex(hex)) {
			if (_pickerType == "p") {
				newColours();
				updateHexDiv(hex);
			}
			rgb = HexToRGB(hex);
			hsv = RGBToHSV(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmHue").value = hsv["hue"];
			sliderY = HToY(hsv["hue"]);
			dotX = SToX(hsv["sat"]);
			dotY = VToY(hsv["val"]);

			$("cmBlueArrow").style.top = (sliderY + "px");
			$("cmBlueDot").style.left = (dotX + "px");
			$("cmBlueDot").style.top = (dotY + "px");
			$("cmColorContainer").style.backgroundColor = ("#" + hex);

			rgb = HSVToRGB(hsv["hue"],100,100);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmSatValBg").style.backgroundColor = ("#" + hex);
		}
	}

	/***********************/
	//Default Color Selection
	/***********************/
	function dragSV(e) {
		if (isdrag) {
			mouseX = nn6 ? e.clientX : event.clientX;
			mouseY = nn6 ? e.clientY : event.clientY;

			scrollOffset = getScrollXY();
			if (!scrollOffset["y"]) {
				scrollOffset["y"] = 0;
			}
			if (!scrollOffset["x"]) {
				scrollOffset["x"] = 0;
			}
			if (checkIt("safari")) {
				xlimit = (mouseX - 24 - $("ColourMod").offsetLeft);
				ylimit = (mouseY - 53 - $("ColourMod").offsetTop);
			} else {
				xlimit = (mouseX - 24 - $("ColourMod").offsetLeft + scrollOffset["x"]);
				ylimit = (mouseY - 53 - $("ColourMod").offsetTop + scrollOffset["y"]);
			}

			if (xlimit <= 0) {
				xlimit = 0;
			} else if (xlimit >= 150) {
				xlimit = 150;
			}
			if (ylimit <= 0) {
				ylimit = 0;
			} else if (ylimit >= 150) {
				ylimit = 150;
			}

			$("cmBlueDot").style.left = (xlimit + "px");
			$("cmBlueDot").style.top = (ylimit + "px");

			H = $("cmHue").value;
			S = XToS(xlimit);
			V = YToV(ylimit);

			rgb = HSVToRGB(H,S,V);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmHex").value = hex;
			updateHexDiv(hex);
			$("cmColorContainer").style.backgroundColor = ("#" + hex);
		}
	}

	function dragH(e) {
		if (isdrag) {
			mouseY = nn6 ? e.clientY : event.clientY;

			scrollOffset = getScrollXY();
			if (!scrollOffset["y"]) {
				scrollOffset["y"] = 0;
			}
			if (!scrollOffset["x"]) {
				scrollOffset["x"] = 0;
			}

			if (checkIt("safari")) {
				sliderY = (mouseY - 52 - $("ColourMod").offsetTop);
			} else {
				sliderY = (mouseY - 52 - $("ColourMod").offsetTop + scrollOffset["y"]);
			}

			if (sliderY < 0) {
				sliderY = 0;
			}
			if (sliderY > 150) {
				sliderY = 150;
			}

			$("cmBlueArrow").style.top = (sliderY + "px");
			H = YToH(sliderY);	
			rgb = HSVToRGB(H,100,100);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);
			$("cmSatValBg").style.backgroundColor = ("#" + hex);

			dotX = replaceString($("cmBlueDot").style.left,"px","");
			dotY = replaceString($("cmBlueDot").style.top,"px","");

			S = XToS(dotX);
			V = YToV(dotY);	

			rgb = HSVToRGB(H,S,V);
			hex = RGBToHex(rgb["red"],rgb["green"],rgb["blue"]);

			$("cmHex").value = hex;
			updateHexDiv(hex);
			$("cmColorContainer").style.backgroundColor = ("#" + hex);
		}
	}

	function replaceString (string, find, replace) {
		return string.replace(find,replace);
	}

	/****************************************/
	//Default Coordinate Conversion Functions
	/****************************************/
	function XToS(dotX) {
		return (dotX / 1.5);
	}

	function YToV(dotY) {
		return (100 - (dotY / 1.5));
	}

	function SToX(S) {
		return (S * 1.5);
	}

	function VToY(V) {
		return ((-V + 100) * 1.5);
	}

	function HToY(H) {
		return ((H / 360) * 150);
	}

	function YToH(sliderY) {
		return ((sliderY / 150) * 360);
	}

	/***************************/
	//Color Conversion Functions
	/***************************/

	function HSVToRGB(H,S,V) {
		H /= 360;
		S /= 100;
		V /= 100;

		if (S <= 0) {
			V = Math.round(V * 255);
			rgb["red"] = V;
			rgb["green"] = V;
			rgb["blue"] = V;
			return rgb;
		} else {
			if (H >= 1.0) {
				H = 0;
			}
			H = (6 * H);
			F = (H - Math.floor(H));
			P = Math.round(255 * V * (1.0 - S));
			Q = Math.round(255 * V * (1.0 - (S * F)));
			T = Math.round(255 * V * (1.0 - (S * (1.0 - F))));
			V = Math.round(255 * V);
			switch (Math.floor(H)) {
				case 0: R = V; G = T; B = P; break;
				case 1: R = Q; G = V; B = P; break;
				case 2: R = P; G = V; B = T; break;
				case 3: R = P; G = Q; B = V; break;
				case 4: R = T; G = P; B = V; break;
				case 5: R = V; G = P; B = Q; break;
			}
			rgb["red"] = R;
			rgb["green"] = G;
			rgb["blue"] = B;
			return rgb;
		}
	}

	function RGBToHex(R,G,B) {
		return (toHex(R) + toHex(G) + toHex(B));
	}

	function toHex(N) {
		if (N == null) {
			return "00";
		}
		N = parseInt(N); 
		if (N == 0 || isNaN(N)) {
			return "00";
		}
		N = Math.max(0,N);
		N = Math.min(N,255);
		N = Math.round(N);
		return "0123456789ABCDEF".charAt((N - N % 16) / 16) + "0123456789ABCDEF".charAt(N % 16);
	}

	function HexToRGB(H) { 
		hexR = H.substr(0,2);
		rgb["red"] = parseInt((hexR).substring(0,2),16);
		hexG = H.substr(2,2);
		rgb["green"] = parseInt((hexG).substring(0,2),16);
		hexB = H.substr(4,2);
		rgb["blue"] = parseInt((hexB).substring(0,2),16);
		return rgb;
	}

	function RGBToHSV(R,G,B) {
		var max = Math.max(R,G,B);
		var min = Math.min(R,G,B);
		var delta = (max - min);
		V = Math.round((max / 255) * 100);
		if (max != 0) {
			S = Math.round(delta / max * 100);
		} else {
			S = 0;
		}

		if (S == 0) {
			H = 0;
		} else {
			if (R == max) {
				H = ((G - B) / delta);
			} else if (G == max) {
				H = (2 + (B - R) / delta);
			} else if (B == max) {
				H = (4 + (R - G) / delta);
			}
			H = Math.round(H * 60);
			if (H > 360) {
				H = 360;
			}
			if (H < 0) {
				H += 360;
			}
		}
		hsv["hue"] = H;
		hsv["sat"] = S;
		hsv["val"] = V;
		return hsv;
	}

//////////////////
// My functions //
//////////////////

	updateHexDiv = function(_hex) {
		if (_pickerType == "p") {
			$("colour" + _currentColourDiv).style.backgroundColor = ("#" + _hex);
			$("hex" + _currentColourDiv).innerHTML = _hex.toUpperCase();
			$("colour" + _currentColourDiv).innerHTML = "";
		} else {
			_coloursChecked = false;
		}
		$("newColourTD" + _currentColourDiv).style.backgroundColor = ("#" + _hex);
	}

	setCurrentColourDiv = function(_divNum) {
		_currentColourDiv = _divNum;
		for (_i=0;_i<5;_i++) {
			$("colourHeader" + _i).style.backgroundColor = "#333333";
		}
		$("colourHeader" + _currentColourDiv).style.backgroundColor = "#cc0000";
	}

	setHex = function(_divNum) {
		_hex = $("hex" + _divNum).innerHTML
		if (isHex(_hex)) {
			$("cmHex").value = _hex;
			hexUpdate();
		}
	}

	clearColour = function(_colorNum) {
		$("colour" + _colorNum).style.backgroundColor = "#dddddd";
		$("newColourTD" + _currentColourDiv).style.backgroundColor = "#ffffff";
		$("hex" + _colorNum).innerHTML = "";
		$("colour" + _colorNum).innerHTML = "No Colour";
	}

	hideNewColourDivs = function() {
		$("cNotice").style.display = "none";
		for (_i=0;_i<5;_i++) {
			$("newColourDiv" + _i).style.display = "none";
		}
	}

	cancelNewColours = function() {
		if (_pickerType == "p") {
			try {
				clearTimeout(_timeOutColour);
			} catch(_e) {}
		}
	}

	newColours = function() {
		if (_pickerType == "p") {
			_timeOutColour = setTimeout("refreshRandColours()",200);
		}
	}

	refreshRandColours = function() {
		var _rgb = HexToRGB($("cmHex").value);
		var _hsb = RGBToHSV(_rgb["red"],_rgb["green"],_rgb["blue"]);
		(new httpRequest()).sendRequest("similarColours",[12,_hsb["hue"]]);
	}

	addPalette = function() {
		var _paletteColours = _paletteColoursCheck = _hex = _thisHex = "", _paletteColoursArray = [];
		var _numColours = 0;

		if (typeof _colourBoxOrder == "string") {
			_colourBoxOrder = _colourBoxOrder.split("|");
		}

		for (_i=0;_i<5;_i++) {
			_thisKey = parseInt(_colourBoxOrder[_i]);
			_hex = $("hex" + _thisKey).innerHTML;
			if (_hex != "") {
				_numColours++;
				_paletteColours += (_hex + "|");
				_paletteColoursArray[_thisKey] = _hex;
				if ($("newColourName" + _thisKey).value == "") { 
					_paletteColoursCheck += (_hex + "|");
				}
			}
		}

		if (_numColours >= 2) {
			if (_coloursChecked == false) {
				// Send request to server //
				(new httpRequest()).sendRequest("checkIfColoursExist",[_paletteColoursCheck.substr(0,(_paletteColoursCheck.length - 1)),_pickerType]);
			} else {
				// Request back from server //
				if (_newColours != "nc") {
					hideNewColourDivs();
					_newColours = _newColours.split("|");

					for (_i=0;_i<_newColours.length;_i++) {
						for (_j=0;_j<_paletteColoursArray.length;_j++) {
							if (_newColours[_i] == _paletteColoursArray[_j]) {
								$("cNotice").style.display = "block";
								$("newColourDiv" + _j).style.display = "block";
							}
						}
					}
					_coloursChecked = false;
				} else {
					var _ov = new objectVerify();
					var _thisKey = 0;
					_ov.addElement("paletteName");
					_ov.addElement("cmHex","colorHex");

					if (verifyByObject(_ov,"Please wait ...","submitBtn")) {
						for (_i=0;_i<5;_i++) {
							_thisKey = _colourBoxOrder[_i];

							if ($("newColourName" + _thisKey).value != "") { 
								_thisHex = $("hex" + _thisKey).innerHTML;
								$("c" + _thisKey).value = _thisHex + "|" + $("newColourName" + _thisKey).value;
							}
						}

						$("paletteColours").value = _paletteColours.substr(0,(_paletteColours.length - 1));
						hideNewColourDivs();
						// Submit Form //
						$("addPaletteForm").submit();
						return true;
					}
				}
			}
		} else {
			alert("Palettes need two or more colours!");
		}
		return false;
	}

	savePalette = function() {
		for (_i=0;_i<5;_i++) {
			$("c" + _i).value = $("hex" + _i).innerHTML;
		}
		return true;
	}

	addColour = function() {
		if (_coloursChecked == false) {
			// Send request to server //
			var _hex = $("cmHex").value;

			(new httpRequest()).sendRequest("checkIfColoursExist",[_hex,_pickerType]);
			addColourReference(_hex);
			return false;
		} else {
			if (!_colourExists) {
				var _ov = new objectVerify();
				_ov.addElement("colourName");
				_ov.addElement("cmHex","colorHex");

				if (verifyByObject(_ov,"Adding Colour ...","submitBtn")) {
					$("colour").value = $("cmHex").value;
					// Submit Form //
					$("addColourForm").submit();
				}
			}
			return false;
		}
	}

	saveColour = function() {
		$("colour").value = $("cmHex").value;
		return true;
	}

	addColourReference = function(_hex) {
		(new httpRequest()).sendRequest("addColourReference",[_hex]);
	}

	pickerMod = function() {
		var _hex = "";
		for (_j=0;_j<5;_j++) {
			_hex = $("hex" + _j).innerHTML;
			if (isHex(_hex)) {
				setCurrentColourDiv(_j);
				updateHexDiv(_hex);
			}
		}
		setCurrentColourDiv(0);
	}