document.observe("click",clickHandler);
function clickHandler(e)  {
	var vinilo = window.viniloFlash;
	if (vinilo.changeColor == window.undefined)
	{
		vinilo = $("viniloFlash2")
	}
	
	obj = Event.element(e);
	while (!obj.className && obj.parentNode && !obj.id)
	{
		obj = obj.parentNode;
	}
	if (!obj.style) {
		return;
	}
	if (obj.className=="fg") {
		if (hexa = obj.style.backgroundColor.split("#")[1]) {
			r = parseInt(hexa.substr(0,2),16);
			g = parseInt(hexa.substr(2,2),16);
			b = parseInt(hexa.substr(4,2),16);
		}
		else {
			colorArray = obj.style.backgroundColor.split(")")[0].substr(4).split(",");
			r = colorArray[0];
			g = colorArray[1];
			b = colorArray[2];
		}

		//Es un flash viejo o nuevo? tiene indice?
		if ($("flashType").value == "single")
		{
			vinilo.changeColor(r,g,b);

			$("colorValue-1").value = obj.style.backgroundColor;
			$("colorName-1").value = obj.title;
		
		}
		else {
			var index = $(obj).up("ul").className.split("-")[1];
			vinilo.changeColor(r,g,b,index);

			$("colorValue-"+index).value = obj.style.backgroundColor;
			$("colorName-"+index).value = obj.title;

		}
		var capa = $(obj).up(".capa");
		var selected = capa.select(".selected")[0];
		if (selected) {
			selected.removeClassName("selected");
		}
		$(obj).up().addClassName("selected");

		//$("colorNameBg").value = obj.title;
	}
	if (obj.className.indexOf("bg") > -1) {
		var color = obj.backgroundColor ? obj.backgroundColor : obj.style.backgroundColor;
		changeSimulatorBackground(color);

		var selected = $(obj).up("ul").select(".selected")[0];
		if (selected) {
			selected.removeClassName("selected");
		}

		$("colorValue").value = color;
		$("colorName").value = obj.title;

		obj.up().addClassName("selected");
	}
	if (obj.id == "direccionNormal") {
		vinilo.mirror(-1);
	}
	if (obj.id == "direccionInvertida") {
		vinilo.mirror(1);
	}
	if (obj.className.indexOf("tab") > -1 && obj.className.indexOf("selected") == -1) {
		tabDestination = obj.className.substr(4);
		$$(".foregroundContainer").invoke("hide");
		$$(".capa."+tabDestination)[0].up().show();
		$$(".tab.selected")[0].removeClassName("selected");
		obj.addClassName("selected");
	}
}

document.observe("dom:loaded",checkDefaultBackground);

function checkDefaultBackground() {
	var selected = $$(".colorContainer.selected .bg");
	if (selected.length > 0) {
		var color = selected[0].backgroundColor ? selected[0].backgroundColor : selected[0].style.backgroundColor;
		changeSimulatorBackground(color);
	}
}

function changeSimulatorBackground(color) {
	$("simulator").style.backgroundColor = color;
}

