function getElement(id){
    return $(id);
}

//////////////////////////////////////////////////
//Calling the dialog
function fnProcessReturnValue(retVal){
    if(retVal){
        if(retVal.substr(0,3)=='OK!'){
            return retVal.substring(3, retVal.length);
        }
    }
    return "";
}

/////////////////////////////////////////////////////////////////////////////////
//Coockies
function Get_Cookie(name){
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    var cookieString = name + "=" +escape(value) +
       ( (expires) ? ";expires=" + expires.toGMTString() : "") +
       ( (path) ? ";path=" + path : "") +
       ( (domain) ? ";domain=" + domain : "") +
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

function Delete_Cookie(name,path,domain) {
   if (Get_Cookie(name)) document.cookie = name + "=" +
      ( (path) ? ";path=" + path : "") +
      ( (domain) ? ";domain=" + domain : "") +
      ";expires=Sun, 01-Jan-70 00:00:01 GMT";
}


function setCookieColor(colorName,value){
	var myDate=new Date();
	myDate.setFullYear(2040,0,1);
	Set_Cookie(colorName,value,myDate,"","","");
}


function getCookieColor(colorName){
	val = Get_Cookie(colorName);
	if (val == null)
		return "#ffffff";
	return val;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//RGB HLS Color transforms

	var RANGE = 240;
	var HLSMAX = RANGE;/* H,L, and S vary over 0-HLSMAX */
   	var RGBMAX  = 255;   /* R,G, and B vary over 0-RGBMAX */
                           /* HLSMAX BEST IF DIVISIBLE BY 6 */
                           /* RGBMAX, HLSMAX must each fit in a byte. */

   /* Hue is undefined if Saturation is 0 (grey-scale) */
   /* This value determines where the Hue scrollbar is */
   /* initially set for achromatic colors */
   var UNDEFINED  = HLSMAX*2/3;

   function  RGBtoHLS(R,G,B)
   {
      cMax = Math.max( Math.max(R,G), B);
      cMin = Math.min( Math.min(R,G), B);

      L = Math.floor(( ((cMax+cMin)*HLSMAX) + RGBMAX )/(2*RGBMAX));

      if (cMax == cMin) {           /* r=g=b --> achromatic case */
         S = 0;                     /* saturation */
         H = UNDEFINED;             /* hue */
      }
      else {                        /* chromatic case */
         /* saturation */
         if (L <= (HLSMAX/2))
            S = Math.floor( ( ((cMax-cMin)*HLSMAX) + ((cMax+cMin)/2) ) / (cMax+cMin) );
         else
            S = Math.floor( ( ((cMax-cMin)*HLSMAX) + ((2*RGBMAX-cMax-cMin)/2) )/ (2*RGBMAX-cMax-cMin) );

         /* hue */
      Rdelta = Math.floor( ( ((cMax-R)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin) );
      Gdelta = Math.floor( ( ((cMax-G)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin) );
      Bdelta = Math.floor( ( ((cMax-B)*(HLSMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin) );

         if (R == cMax)
            H = Bdelta - Gdelta;
         else if (G == cMax)
            H = (HLSMAX/3) + Rdelta - Bdelta;
         else /* B == cMax */
            H = ((2*HLSMAX)/3) + Gdelta - Rdelta;

         if (H < 0)
            H += HLSMAX;
         if (H > HLSMAX)
            H -= HLSMAX;
      }

	  res = new Array();
	  res[0] = Math.floor(H);
	  res[1] = Math.floor(L);
	  res[2] = Math.floor(S);

	  return res;
   }
   /* utility routine for HLStoRGB */

   function  HueToRGB(n1,n2,hue)
   {

		n1 = Math.floor(n1);
		n2 = Math.floor(n2);
		hue = Math.floor(hue);
      /* range check: note values passed add/subtract thirds of range */
      if (hue < 0)
         hue += HLSMAX;

      if (hue > HLSMAX)
         hue -= HLSMAX;

      /* return r,g, or b value from this tridrant */
      if (hue < (HLSMAX/6))
          return Math.floor( n1 + Math.floor((((n2-n1)*hue+(HLSMAX/12))/(HLSMAX/6))) );
      if (hue < (HLSMAX/2))
         return ( n2 );
      if (hue < ((HLSMAX*2)/3))
         return Math.floor( n1 +    Math.floor( (((n2-n1)*(((HLSMAX*2)/3)-hue)+(HLSMAX/12)) / (HLSMAX/6)) ) );
      else
         return Math.floor( n1 );
   }

   function HLStoRGB(hue,lum,sat)
    {

      if (sat == 0) {            /* achromatic case */
         R=G=B=(lum*RGBMAX)/HLSMAX;
         if (hue != UNDEFINED) {
            /* ERROR */
          }
       }
      else  {                    /* chromatic case */
         /* set up magic numbers */
         if (lum <= (HLSMAX/2))
            Magic2 = Math.floor(	(lum*(HLSMAX + sat) + (HLSMAX/2)) / HLSMAX	);
         else
            Magic2 = (lum + sat - Math.floor( ((lum*sat) + (HLSMAX/2))/HLSMAX) );

         Magic1 = 2*lum-Magic2;

         /* get RGB, change units from HLSMAX to RGBMAX */
         R = (HueToRGB(Magic1,Magic2,hue+(HLSMAX/3))*RGBMAX + (HLSMAX/2))/HLSMAX;
         G = (HueToRGB(Magic1,Magic2,hue)*RGBMAX + (HLSMAX/2)) / HLSMAX;
         B = (HueToRGB(Magic1,Magic2,hue-(HLSMAX/3))*RGBMAX +  (HLSMAX/2))/HLSMAX;
      }


	  res = new Array();
	  res[0] = Math.floor(R);
	  res[1] = Math.floor(G);
	  res[2] = Math.floor(B);

	  return res;

    }

/////////////////////////////////////////////////////////////////
//drawing
var g_param = 0;

var step = 6;
var visStep = 5;

function myParseInt(strIntNum){
    strIntNum = String(strIntNum);
	if(strIntNum.length<=0 || strIntNum=="")
		return 0;

	var intStr = "0123456789";

	for(i = 0 ; i < strIntNum.length; i++){
	   if(intStr.indexOf(strIntNum.substring(i,1))<0)
			return 0;
	}
	return parseInt(strIntNum);
}

function getHex(num){
   hexStr = "0123456789ABCDEF";
   hex="";
   if (num>=16) {
      hex = hexStr.substr(parseInt(num/16),1);
      num = num%16;
   }
   hex += hexStr.substr(num,1);

   if(hex.length == 1)
		hex = "0" +  hex;

   return hex;
}

function getNum(hex){
	if(hex.length !=2 )
		return 0;
	hexStr = "0123456789ABCDEFabcdef";

	for(i = 0 ; i < hex.length; i++){
	   if(hexStr.indexOf(hex.substring(i,1))<0)
			return 0;
	}

	return parseInt(hex,16);
}

function LTable(H,S,parentEl){
    ///*
    if(document.getElementById('sliderTable')){
        document.getElementById(parentEl).removeChild(document.getElementById('sliderTable'));
    }

    var table = document.createElement('TABLE');
    table.setAttribute('cellPadding',0);
    table.setAttribute('cellSpacing',0);
    table.setAttribute('border',0);
    table.setAttribute('id','sliderTable');

    var tBody = document.createElement('TBODY');
    table.appendChild(tBody);

    var maxL = Math.floor((HLSMAX-1)/step)*step;

    for(L = maxL ;L >= 0 ; L-=step){
        var row = document.createElement('TR');
        var cell = document.createElement('TD');
        var res = HLStoRGB(H,L,S);
        cell.style.backgroundColor = "#" + getHex(res[0])+getHex(res[1]) + getHex(res[2]);
        cell.style.width = 10+ "px";
        cell.style.height = visStep + "px";
        row.appendChild(cell);
        tBody.appendChild(row);
    }
    document.getElementById(parentEl).appendChild(table);
return;
//*/

    table = document.getElementById('sliderTable');

    var maxL = Math.floor((HLSMAX-1)/step)*step;
    pos = 0;
    rows = table.getElementsByTagName('TR');

    for(L = maxL ;L >= 0 ; L-=step){
        row = rows[pos];
        if(row){
            cell = row.getElementsByTagName('TD')[0];
            if(cell){
                var res = HLStoRGB(H,L,S);
                //cell.style.backgroundColor = "#" + getHex(res[0])+getHex(res[1]) + getHex(res[2]);
            }
        }

        pos ++;
    }
}


var curColElX = 0;
var curColElY = 0;


function fnOnColorClick(color,x,y){
	cell = getElement("basic_color_"+curColElX+"_"+curColElY);
	cell.style.borderColor = "#ffffff";

	curColElX = x;
	curColElY = y;
	cell = getElement("basic_color_"+curColElX+"_"+curColElY);
	cell.style.borderColor = "#ff0000";

	getElement('R_id').value = getNum(color.substr(1,2));
	getElement('G_id').value = getNum(color.substr(3,2));
	getElement('B_id').value = getNum(color.substr(5,2));
	OnChangeRGB();
}

//////////////////////////////////////////////////////////////////////////
var curCustElX = 0;
var curCustElY = 0;

function fnAddCustColorClick(red,green,blue){
	cell = document.getElementById("custom_color_"+curCustElX+"_"+curCustElY);
	color = "#" + getHex(red)+getHex(green) + getHex(blue);
	cell.style.backgroundColor = color;
	cell.style.color = color;

	onClickEvent =
		function(col,colX,colY) {
			return (
				function (){
					fnOnCustColorClick(col,colX,colY);
				}
			);
		} (color,curCustElX,curCustElY);

	if (document.all) { //IE4 and up
		cell.attachEvent("onclick",onClickEvent);
	} else if (document.layers) {
		cell.addeventlistener("onclick",onClickEvent,false);
	} else if (document.getElementById) {
		cell.addEventListener("click",onClickEvent,false);
	}

	setCookieColor("custom_color_"+curCustElX+"_"+curCustElY,color);
}


function fnOnCustColorClick(color,x,y){
	cell = document.getElementById("custom_color_"+curCustElX+"_"+curCustElY);
	cell.style.borderColor = "#000000";

	curCustElX = x;
	curCustElY = y;
	cell = document.getElementById("custom_color_"+curCustElX+"_"+curCustElY);
	cell.style.borderColor = "#ff0000";

//	color = cell.style.color;
//	alert(color);

	document.getElementById('R_id').value = getNum(color.substr(1,2));
	document.getElementById('G_id').value = getNum(color.substr(3,2));
	document.getElementById('B_id').value = getNum(color.substr(5,2));
	OnChangeRGB();


}


////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Dialog functionality
////////////////////////////////////////////////////////////////////////////////////////////////////////////

var graphicsHeight = (HLSMAX/step)*visStep;
/////////////////////////////////////////////////////
//relative to div_graphics
var selectLeft = 0;
var selectTop = 0;
var selectWidth = (HLSMAX/step)*visStep;
var selectHeight = graphicsHeight;

var selectPointerWidth = 20;
var selectPointerHeight = 20;

var sliderLeft = selectLeft + selectWidth + 10;
var sliderTop = selectTop;
var sliderWidth = 10;
var sliderHeight = selectHeight;

var sliderPointerWidth = 5;
var sliderPointerHeight = 9;

function fnVerifyNumber(strFieldId,maxVal){
	iValue = myParseInt(document.getElementById(strFieldId).value);
	if(iValue<0)
		document.getElementById(strFieldId).value = "0";
	else if(iValue>maxVal)
		document.getElementById(strFieldId).value=maxVal.toString();
	else if( iValue.toString() != document.getElementById(strFieldId).value)
		document.getElementById(strFieldId).value = myParseInt(document.getElementById(strFieldId).value).toString();
}


function fnGetColorByRelativePos(pos,relVal){
	return 	Math.round((pos/relVal)*HLSMAX);
}

function fnGetRelativePosByColor(col,relVal){
	return 	Math.round((col/HLSMAX)*relVal);
}

function scrollFromLeft(){
    return (document.documentElement.scrollLeft ? parseInt(document.documentElement.scrollLeft) : parseInt(document.body.scrollLeft));
}

function getMouseXPos(e) {
	if (document.all) { //IE4 and up
            return parseInt(e.clientX) + scrollFromLeft() - parseInt(document.all['colorPicker'].offsetLeft);
	} else if (document.layers) {
		if(!e) e = window.event;
	    return myParseInt(e.pageX)
	} else if (document.getElementById) {
                return (parseInt(e.pageX) - parseInt(getElement('colorPicker').offsetLeft));
	}
}

// <B style="color:black;background-color:#A0FFFF">Get</B> the vartical <B style="color:black;background-color:#ff9999">position</B> of the mouse

function scrollFromTop(){
    return (document.documentElement.scrollTop ? parseInt(document.documentElement.scrollTop) : parseInt(document.body.scrollTop));
}

function getMouseYPos(e) {
	if (document.all) { //IE4 and up
            return parseInt(e.clientY) + scrollFromTop() - parseInt(document.all['colorPicker'].offsetTop);
	} else if (document.layers) {
		if(!e) e = window.event;
	    return myParseInt(e.pageY);
	} else if (document.getElementById) { // mozilla
                return (parseInt(e.pageY) - parseInt(getElement('colorPicker').offsetTop));
	}
}

function CalcSliderPos(e){
        e = Event.extend(e);
        pos = e.pointerY() - $('LTable').cumulativeOffset().top;
	Lum = fnGetColorByRelativePos(pos,sliderHeight);

	if(Lum<0){
		Lum = 0;
		pos = 0;
	}
	if(Lum>HLSMAX){
		Lum = HLSMAX;
		pos = sliderHeight;
	}

	if(Lum>HLSMAX || Lum<0) return;

	slider = getElement('div_slider');
	CalcLumByPos(pos);
	slider.style.top = (pos - sliderPointerHeight - 2 ) + 'px';
}

function CalcSelectPos(e){
	var selectEl = $('div_select');
        e = Event.extend(e);
        pos = e.pointerX() - $('HSTable').cumulativeOffset().left;

	Hue = fnGetColorByRelativePos(pos,selectWidth);

	if(Hue<0){
		Hue = 0;
		pos = 0;
	}
	if(Hue>HLSMAX){
		Hue = HLSMAX;
		pos = selectWidth;
	}

	if(Hue>=0 && Hue<=HLSMAX){
		CalcHueByPos(pos);

		selectEl.style.left = (pos - selectPointerWidth/2) + 'px';
	}

        pos = e.pointerY() - $('HSTable').cumulativeOffset().top;
	Sat = fnGetColorByRelativePos(pos,selectHeight);


	if(Sat<0){
		Sat = 0;
		pos = 0;
	}
	if(Sat>HLSMAX){
		Sat = HLSMAX;
		pos = selectWidth;
	}

	if(Sat>=0 && Sat<=HLSMAX){
		CalcSatByPos(pos);
		selectEl.style.top = (pos - selectPointerHeight/2) + 'px';
	}

}
///////////////////////////////////////////////////////////////////////
var curElementName;
function CaptureElement(elementDivName,elWidth,elHeight,parentLeft,parentTop,e){
	el = document.getElementById(elementDivName);
	if(el){
		mX = getMouseXPos(e);
		mY = getMouseYPos(e);
		if(
			(el.offsetLeft + parentLeft <= mX && mX <= el.offsetLeft + parentLeft + elWidth) &&
			(el.offsetTop + parentTop <= mY && mY <= el.offsetTop + parentTop + elHeight)
		){
			curElementName = elementDivName;
			return true;
		}
	}
	return false;
}

function CaptureSelectImg(e){
	parentLeft = document.getElementById('div_graphics').offsetLeft + document.getElementById('HSTable').offsetLeft;
	parentTop = document.getElementById('div_graphics').offsetTop + document.getElementById('HSTable').offsetTop;
	return CaptureElement('div_select',selectPointerWidth,selectPointerHeight,parentLeft,parentTop,e);
}

function CaptureSlideImg(e){
	parentLeft = document.getElementById('div_graphics').offsetLeft + document.getElementById('LTable').offsetLeft;
	parentTop = document.getElementById('div_graphics').offsetTop + document.getElementById('LTable').offsetTop + sliderPointerHeight/2;

	return CaptureElement('div_slider',sliderPointerWidth,sliderPointerHeight,parentLeft,parentTop,e);
}


function doMouseMove(e) {

	if (document.all) { //IE4 and up
		if(!e)
			e = event;
		btn = 1;
		el = e.srcElement;
	} else if (document.layers) {
		if(!e)
			e = window.event;
		btn = 0;
		el = e.target;
	} else if (document.getElementById) {
		if(!e)
			e = window.Event;
		btn = 0;
		el = e.target;
	}

	if (/*(e.button==btn) && */(curElementName!=null)){
		if(curElementName =='div_select'){
			CalcSelectPos(e);
			e.returnValue = false
			e.cancelBubble = true
		}else if(curElementName =='div_slider'){
			CalcSliderPos(e);
			e.returnValue = false
			e.cancelBubble = true
		}else{

		}
	}
}

function doDragStart(e, transferData, action) {
    if (document.all) { //IE4 and up
        e = event;
    } else if (document.layers) {
        if(!e) e = window.event;
    } else if (document.getElementById) {
        if(!e) e = window.Event;
    }

    if ("IMG"==event.srcElement.tagName)
      event.returnValue=false;
}

function doMouseDown(e) {
    if (document.all) { //IE4 and up
        if(!e) e = event;
        btn = 1;
        el = e.srcElement;
    } else if (document.layers) {
        if(!e) e = window.event;
        btn = 0;
        el = e.target;
    } else if (document.getElementById) {
        if(!e) e = window.Event;
        btn = 0;
        el = e.target;
    }

    if ((e.button==btn) && (el.tagName=="IMG")){
        if(!CaptureSelectImg(e)){
            if(CaptureSlideImg(e)){
                return false;
            }
        }
        else{
            return false;
        }
    }
}
/*
document.ondragstart = doDragStart;
document.onmousedown = doMouseDown;

document.onmousemove = doMouseMove;
document.onmouseup = new Function("curElementName=null;	");
*/

////////////////////////////////////////////////////////////////////////////////////

function returnFalse() {
    return false;
}

var onFinishEvent;

var colordialog;

function showColorChooserDialog(divid, prevColor, onFinish){
    onFinishEvent = onFinish;
    if(prevColor){
        if(prevColor.length == 7){
            if(prevColor.substr(0,1) == '#'){
                document.getElementById('R_id').value = getNum(prevColor.substr(1,2));
                document.getElementById('G_id').value = getNum(prevColor.substr(3,2));
                document.getElementById('B_id').value = getNum(prevColor.substr(5,2));
                OnChangeRGB();
            }
        }
    }
    else{
        document.getElementById('H_id').value = 0;
        document.getElementById('S_id').value = HLSMAX;
        document.getElementById('L_id').value = 0;
        RGBByHSL();
        LTable(0,HLSMAX,'LTable');
    }

    if(!colordialog){
       colordialog = getElement('colorPicker');
    }

    document.ondragstart = function() {
    return false;
};
    document.onselectstart = function () {
    return false;
};
    colordialog.style.display = '';
}



function CalcHueByPos(pos){
	document.getElementById('H_id').value = fnGetColorByRelativePos(pos,selectWidth);

	OnChangeHS();
}

function CalcPosByHue(){

	Hue = document.getElementById('H_id').value;

	selectEl = document.getElementById('div_select');
	selectEl.style.left = fnGetRelativePosByColor(Hue,selectWidth) - selectPointerWidth/2 + 'px';

	OnChangeHS();
}

function CalcSatByPos(pos){
	document.getElementById('S_id').value = HLSMAX - fnGetColorByRelativePos(pos,selectHeight);

	OnChangeHS();
}

function CalcPosBySat(){
	Sat = document.getElementById('S_id').value;

	selectEl = document.getElementById('div_select');
	selectEl.style.top = fnGetRelativePosByColor(HLSMAX - Sat,selectHeight) - selectPointerHeight/2 + 'px';

	OnChangeHS();
}

function CalcLumByPos(pos){
	document.getElementById('L_id').value = HLSMAX - fnGetColorByRelativePos(pos,sliderHeight);
	OnChangeL();
}


function CalcPosByLum(){
	Lum = document.getElementById('L_id').value;

	slider = document.getElementById('div_slider');
	slider.style.top = fnGetRelativePosByColor(HLSMAX - Lum,sliderHeight) - sliderPointerHeight  + 'px';

	OnChangeL();
}

function RGBByHSL(){
	H = myParseInt(document.getElementById('H_id').value);
	L = myParseInt(document.getElementById('L_id').value);
	S = myParseInt(document.getElementById('S_id').value);

	res = HLStoRGB(H,L,S);

	document.getElementById('R_id').value = res[0];
	document.getElementById('G_id').value = res[1];
	document.getElementById('B_id').value = res[2];

	setPreviewColor();
}

function HSLByRGB(){
	R = myParseInt(document.getElementById('R_id').value);
	G = myParseInt(document.getElementById('G_id').value);
	B = myParseInt(document.getElementById('B_id').value);

	res = RGBtoHLS(R,G,B);

	document.getElementById('H_id').value = res[0];
	document.getElementById('L_id').value = res[1];
	document.getElementById('S_id').value = res[2];

	setPreviewColor();
}

function OnChangeHS(){
	RGBByHSL();

	H = myParseInt(document.getElementById('H_id').value);
	S = myParseInt(document.getElementById('S_id').value);

	LTable(H,S,'LTable');
}

function OnChangeL(){
	RGBByHSL();
}

function OnChangeRGB(){
	HSLByRGB();

	Hue = parseInt(getElement('H_id').value);
	Sat = parseInt(getElement('S_id').value);

	selectEl = getElement('div_select');
	selectEl.style.left = (fnGetRelativePosByColor(Hue,selectWidth) - selectPointerWidth/2) + 'px';
	selectEl.style.top = (fnGetRelativePosByColor(HLSMAX - Sat,selectWidth) - selectPointerHeight/2) + 'px';
	LTable(Hue,Sat,'LTable');

	Lum = parseInt(getElement('L_id').value);

	slider = getElement('div_slider');
	slider.style.top = fnGetRelativePosByColor(HLSMAX - Lum,sliderHeight) - sliderPointerHeight + 'px';

}

function setPreviewColor(){
	R = myParseInt(document.getElementById('R_id').value);
	G = myParseInt(document.getElementById('G_id').value);
	B = myParseInt(document.getElementById('B_id').value);

	prevEl = document.getElementById("previewColor");
	prevEl.style.backgroundColor = '#'+getHex(R)+getHex(G)+getHex(B);
}

function EndDialog(val){
	var retVal = null;
	if(val=="OK"){
		R = myParseInt(document.getElementById('R_id').value);
		G = myParseInt(document.getElementById('G_id').value);
		B = myParseInt(document.getElementById('B_id').value);
		retVal = "#" + getHex(R)+getHex(G) + getHex(B);
	}

        onFinishEvent(retVal);
}

var isShownCustColors = true;
function ShowHideCustColors(){
    if(isShownCustColors){
        $('div_cust_colors').hide();
        $('DefineCustomColors').value = 'Define Custom Colors >>';
    }else{
        $('div_cust_colors').show();
        $('DefineCustomColors').value = 'Define Custom Colors <<';
    }
	isShownCustColors = !isShownCustColors;
}