
var ColorPickerWriteTo = '';
var callBack= '';

function $(v) { return(document.getElementById(v)); }
function $S(v) { return($(v).style); }

function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function toggle(v,id) {
	$S(v).display=($S(v).display=='none'?'block':'none');
	ColorPickerWriteTo = id;

}
function toggleoff(v) { $S(v).display='none'; }
function within(v,a,z) { return((v>=a && v<=z)?true:false); }
function XY(e,v) {
var z=agent('msie')?[event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,event.clientY+document.body.scrollTop+document.documentElement.scrollTop]:[e.pageX,e.pageY];

return(z[zero(v)]); }
function XYwin(v) { var z=agent('msie')?[document.body.clientHeight,document.body.clientWidth]:[window.innerHeight,window.innerWidth];  return(!isNaN(v)?z[v]:z); }
function zero(v) { v=parseInt(v); return(!isNaN(v)?v:0); }

/* CP_plugin */

var maxValue={'h':360,'s':100,'v':100}, HSV={0:360,1:100,2:100};
var hSV=165, wSV=162, hH=163, slideHSV={0:360,1:100,2:100}, zINDEX=15, stop=1;



function HSVslide(d,o,e) {

	function tXY(e) { tY=XY(e,1)-top; tX=XY(e)-left; }
	function mkHSV(a,b,c) { return(Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a)))); }
	function ckHSV(a,b) { if(within(a,0,b)) return(a); else if(a>b) return(b); else if(a<0) return('-'+oo); }
	function drag(e) { if(!stop) { if(d!='drag') tXY(e);



		if(d=='SVslide') {


		ds.left=ckHSV(tX-oo,wSV)+'px';
		ds.top=ckHSV(tY-oo,wSV)+'px';
//

			slideHSV[1]=mkHSV(100,wSV,ds.left); slideHSV[2]=100-mkHSV(100,wSV,ds.top); HSVupdate(0,'none');

		}
		else if(d=='Hslide') { var ck=ckHSV(tY-oo,hH), j, r='hsv', z={};

			ds.top=(ck-5)+'px'; slideHSV[0]=mkHSV(360,hH,ck);

			for(var i=0; i<=r.length-1; i++) { j=r.substr(i,1); z[i]=(j=='h')?maxValue[j]-mkHSV(maxValue[j],hH,ck):HSV[i]; }

			HSVupdate(z,'none'); $S('SV').backgroundColor='#'+hsv2hex([HSV[0],100,100]);

		}
		else if(d=='drag') { ds.left=XY(e)+oX-eX+'px'; ds.top=XY(e,1)+oY-eY+'px'; }

	}}

	if(stop) { stop=''; var ds=$S(d!='drag'?d:o);

		if(d=='drag') {
		  var oX=parseInt(ds.left), oY=parseInt(ds.top), eX=XY(e), eY=XY(e,1); $S(o).zIndex=zINDEX++;
        }	else {

		  var left=($(o).offsetLeft+3), top=($(o).offsetTop+2), tX, tY, oo=(d=='Hslide')?2:4;
		  if(d=='SVslide') slideHSV[0]=HSV[0];
        }

		document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; }; drag(e);

	}
}


function HSVupdate(v,omit) {

	v=hsv2hex(HSV=v?v:slideHSV);



	$S('curCol').background='#'+v;
	if (omit != 'hex') {
	$(ColorPickerWriteTo+'_HEX').value=v;
	}
	//$('plugHEX').innerHTML=v;
	var rgb = hex2rgb(v);
	if (omit != 'rgb') {
	$(ColorPickerWriteTo+'_R').value=rgb[0];
	$(ColorPickerWriteTo+'_G').value=rgb[1];
	$(ColorPickerWriteTo+'_B').value=rgb[2];
//	$(ColorPickerWriteTo+'_HSV').value=HSV[0]+','+HSV[1]+','+HSV[2]+' -  z:'+$('Hslide').style.top;
	}
	var cmyk = rgb2cmyk(rgb);
	if (omit != 'cmyk') {
	$(ColorPickerWriteTo+'_C').value=cmyk[0];
	$(ColorPickerWriteTo+'_M').value=cmyk[1];
	$(ColorPickerWriteTo+'_Y').value=cmyk[2];
	$(ColorPickerWriteTo+'_K').value=cmyk[3];
	}

	if (callBack) {
	    callBack.func(v);
	}


	return(v);

}

function cp_tinymce (id,hex,w) {

	var inst = tinyMCE.getInstanceById(id);
	if (!inst) {
		window.setTimeout("cp_tinymce ('"+id+"','"+hex+"','"+w+"')",50);
	} else {
		if (w=='left') {
			//alert(inst.foreColor);

		}
		inst.foreColor = '#'+hex;
		inst.getDoc().execCommand('forecolor', false, '#'+hex);
	}

}

function loadSV() {

	var z='';

	for(var i=hSV; i>=0; i--) z+="<div style=\"BACKGROUND: #"+hsv2hex([Math.round((360/hSV)*i),100,100])+";\"><br /><\/div>";

	$('Hmodel').innerHTML=z;

}

/* CONVERSIONS */
function mkCord(a,b,c) { return(Math.min(a,Math.max(0,Math.ceil((b*a)/c)))); }

function toHex(v) { v=Math.round(Math.min(Math.max(0,v),255)); return("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16)); }
function rgb2hex(r) { return(toHex(r[0])+toHex(r[1])+toHex(r[2])); }
function hex2rgb(r) { return({0:parseInt(r.substr(0,2),16),1:parseInt(r.substr(2,2),16),2:parseInt(r.substr(4,2),16)}); }
function rgb2hsv(r) { var max=Math.max(r[0],r[1],r[2]), delta=max-Math.min(r[0],r[1],r[2]), H, S, V;
	if(max!=0) { S=Math.round(delta/max*100);
		if(r[0]==max) H=(r[1]-r[2])/delta; else if(r[1]==max) H=2+(r[2]-r[0])/delta; else if(r[2]==max) H=4+(r[0]-r[1])/delta;
		var H=Math.min(Math.round(H*60),360); if(H<0) H+=360;
	}
	return({0:H?H:0,1:S?S:0,2:Math.round((max/255)*100)});
}


function hsv2hex(h) { return(rgb2hex(hsv2rgb(h))); }

function hsv2rgb(r) { // easyrgb.com/math.php?MATH=M21#text21

    var R,B,G,S=r[1]/100,V=r[2]/100,H=r[0]/360;

    if(S>0) { if(H>=1) H=0;

        H=6*H; F=H-Math.floor(H);
        A=Math.round(255*V*(1.0-S));
        B=Math.round(255*V*(1.0-(S*F)));
        C=Math.round(255*V*(1.0-(S*(1.0-F))));
        V=Math.round(255*V);

        switch(Math.floor(H)) {

            case 0: R=V; G=C; B=A; break;
            case 1: R=B; G=V; B=A; break;
            case 2: R=A; G=V; B=C; break;
            case 3: R=A; G=B; B=V; break;
            case 4: R=C; G=A; B=V; break;
            case 5: R=V; G=A; B=B; break;

        }

        return([R?R:0,G?G:0,B?B:0]);

    }
    else return([(V=Math.round(V*255)),V,V]);
}
function rgb2cmyk(r) { var C=1-(r[0]/255), M=1-(r[1]/255), Y=1-(r[2]/255), K=Math.min(Y,Math.min(M,Math.min(C,1)));
C=Math.round((C-K)/(1-K)*100); M=Math.round((M-K)/(1-K)*100); Y=Math.round((Y-K)/(1-K)*100); K=Math.round(K*100);
return([C?C:0,M?M:0,Y?Y:0,K]);
}

function cmyk2rgb(r) { r[3]=r[3]/100;
var R=(1-(r[0]/100*(1-r[3])+r[3]))*255, G=(1-(r[1]/100*(1-r[3])+r[3]))*255, B=(1-(r[2]/100*(1-r[3])+r[3]))*255;
return([R,G,B]);
}

function hsv2ryb(h,v) { if(!v) return(h); else { // HSV, MODE (0=RGB, 1=RYB)
if(h[0]>=240 && h[0]<=360) v=(0.0022*Math.pow(h[0],2))-(0.2257*h[0])+155.18;
else if(h[0]>=0 && h[0]<=60) v=(-0.0042*Math.pow(h[0],2))+(0.8386*h[0]);
else if(h[0]>=60 && h[0]<=180) v=(0.0047*Math.pow(h[0],2))-(0.427*h[0])+45.166;
else if(h[0]>=180 && h[0]<=240) v=(-0.0084*Math.pow(h[0],2))+(5.3235*h[0])-567.45;
return([Math.round(v),h[1],h[2]]);
} }

function websafe(r,v) { // RGB, MODEL (0=SPECTRUM, 1=WEBSMART, 2=WEBSAFE)
	if(v) var n=(v==2?51:17), z=[Math.round(r[0]/n)*n,Math.round(r[1]/n)*n,Math.round(r[2]/n)*n];
	return(rgb2hex(z?z:r));
}
function hex2hsv(v) { return(rgb2hsv(hex2rgb(v))); }


/* LOAD */

function changeHEX (id) {
    var o = $(id);

	rgb = hex2rgb(o.value);

	rgb[0] = rgb[0]>255 ? 255 : rgb[0];
	rgb[1] = rgb[1]>255 ? 255 : rgb[1];
	rgb[2] = rgb[2]>255 ? 255 : rgb[2];
	hex = rgb2hex(rgb);
	//o.value = hex;
	loadColor(o.value,'hex');
}

var changeTimeout = '';
function changeValue(v,o) {
if (changeTimeout && o) {
    window.clearTimeout(changeTimeout);
}
switch (v) {
    case 'rgb':
        changeTimeout = window.setTimeout("changeRGB('"+o.id+"');",900);
        break;
    case 'cmyk':
        changeTimeout = window.setTimeout("changeCMYK('"+o.id+"');",900);
        break;
    case 'hex':
        if (o.value.length==6) {
          var s = o.value;
         // alert (isNaN(parseInt(s[0],16)) ? 'yes' : 'no');
          if (
            isNaN(parseInt(s[0],16)) ||
            isNaN(parseInt(s[1],16)) ||
            isNaN(parseInt(s[2],16)) ||
            isNaN(parseInt(s[3],16)) ||
            isNaN(parseInt(s[4],16)) ||
            isNaN(parseInt(s[5],16))
          ) {
            loadColor(s,'hex');
          } else {
            changeTimeout = window.setTimeout("changeHEX('"+o.id+"');",900);
          }
        }
        break;

}

}

function changeRGB(id) {
    var o = $(id);
	if (o.value > 255) {
		o.value = 255;
	}
	loadColor(rgb2hex([$(ColorPickerWriteTo+'_R').value,$(ColorPickerWriteTo+'_G').value,$(ColorPickerWriteTo+'_B').value]),'rgb');
}

function changeCMYK (id) {
    var o = $(id);
	if (o.value > 100) {
		o.value = 100;
	}
	//cmyk2rgb
	loadColor(rgb2hex(cmyk2rgb([$(ColorPickerWriteTo+'_C').value,$(ColorPickerWriteTo+'_M').value,$(ColorPickerWriteTo+'_Y').value,$(ColorPickerWriteTo+'_K').value])),'cmyk');
}

function loadColor (hex,omit) {
	var hsv=hex2hsv(hex);
	slideHSV=hsv;
	$('SVslide').style.top = mkCord(hSV,100-hsv[2],100)+'px';
	$('SVslide').style.left = mkCord(wSV,hsv[1],100)+'px';
	$('Hslide').style.top = mkCord(hH-5,360-hsv[0],360)+'px';
	$S('SV').backgroundColor='#'+hsv2hex([hsv[0],100,100]);
	HSVupdate(0,omit);
}

var CP_pluginPrinted = false;

function ColorPicker (id,color,o) {
	if (!CP_pluginPrinted) {
		ColorPickerWriteTo = id;
		var col = color.slice(1);
		var rgb = hex2rgb(col);
		var cmyk = rgb2cmyk(rgb);



		if (o) {
			callBack = o;
			//cp_tinymce (callBackId,col);
		}



		// document.write('<div id="CP_plugin"><div id="plugCUR"></div><div id="plugHEX" onmousedown="stop=0; setTimeout(\'stop=1\',100);">FFFFFF</div><div id="plugCLOSE">&nbsp;</div><br><div id="SV" onmousedown="HSVslide(\'SVslide\',\'CP_plugin\',event)" title="S&auml;ttigung + Wert"><div id="SVslide" style="TOP: -4px; LEFT: -4px;"><br /></div></div><div id="H" onmousedown="HSVslide(\'Hslide\',\'CP_plugin\',event)" title="Farbton"><div id="Hslide" style="TOP: -7px; LEFT: -8px;"><br /></div><div id="Hmodel"></div></div></div>');
		document.write('<div id="CP_ctr"><div id="CP_plugin"><div id="SV" onmousedown="HSVslide(\'SVslide\',\'CP_plugin\',event)" title="S&auml;ttigung + Wert"><div id="SVslide"><br /></div></div><div id="H" onmousedown="HSVslide(\'Hslide\',\'CP_plugin\',event)" title="Farbton"><div id="Hslide"><br /></div><div id="Hmodel"></div></div></div></div>');
		document.write('<div class="curColBox"><div id="curCol" style="" onClick="if (callBack) { callBack.func(document.getElementById(\''+id+'_HEX\').value,\'left\'); }">&nbsp;</div></div>')
		document.write('<div class="cp_inputbox"><div id="inputRGB">');
		document.write('<div class="colvallabel">R:</div><input type="text" size="3" name="'+id+'_R" id="'+id+'_R" value="'+rgb[0]+'" onKeyUp="changeValue(\'rgb\',this);return false;"/><br/>');
		document.write('<div class="colvallabel">G:</div><input type="text" size="3" name="'+id+'_G" id="'+id+'_G" value="'+rgb[1]+'" onKeyUp="changeValue(\'rgb\',this);return false;"/><br/>');
		document.write('<div class="colvallabel">B:</div><input type="text" size="3" name="'+id+'_B" id="'+id+'_B" value="'+rgb[2]+'" onKeyUp="changeValue(\'rgb\',this);return false;"/><br/>');
		document.write('<div class="colvallabel">#:</div><input type="text" size="6" name="'+id+'_HEX" id="'+id+'_HEX" value="'+col+'" onKeyUp="changeValue(\'hex\',this); return false;"/></div>')
		document.write('<div  id="inputCMYK">');
		document.write('<div class="cmykMar1"><div class="colvallabel">C:</div><input type="text" size="3" name="'+id+'_C" id="'+id+'_C" value="'+cmyk[0]+'" onKeyUp="changeValue(\'cmyk\',this);return false;"/><div class="percent"> %</div><div class="ctlFloatClr ctlEmptyBox"><span>&nbsp;</span></div></div>');
		document.write('<div class="cmykMar2"><div class="colvallabel">M:</div><input type="text" size="3" name="'+id+'_M" id="'+id+'_M" value="'+cmyk[1]+'" onKeyUp="changeValue(\'cmyk\',this);return false;"/><div class="percent"> %</div><div class="ctlFloatClr ctlEmptyBox"><span>&nbsp;</span></div></div>');
		document.write('<div class="cmykMar3"><div class="colvallabel">Y:</div><input type="text" size="3" name="'+id+'_Y" id="'+id+'_Y" value="'+cmyk[2]+'" onKeyUp="changeValue(\'cmyk\',this);return false;"/><div class="percent"> %</div><div class="ctlFloatClr ctlEmptyBox"><span>&nbsp;</span></div></div>');
		document.write('<div class="cmykMar4"><div class="colvallabel">K:</div><input type="text" size="3" name="'+id+'_K" id="'+id+'_K" value="'+cmyk[3]+'" onKeyUp="changeValue(\'cmyk\',this);return false;"/><div class="percent"> %</div></div><div class="ctlFloatClr ctlEmptyBox"><span>&nbsp;</span></div><br clear="all"/></div><br clear="all"/></div>');

		loadSV();

		loadColor(col,'none');



		CPCP_pluginPrinted = true;
	}

}


