﻿var gDefColor = new Array(
    '000000', '666666',
    'ff0000', '990000',
    '00ff00', '009900', 
    '0000ff', '000099',
    'ffff00', '999900',
    '00ffff', '009999',
    'ff00ff', '990099',
    'ff9900', '663300',
    '99ff00', '336600',
    '6600ff', '330099')
var gUsedColor = new Array();
function getColor()
{
    for (var i = 0; i < gDefColor.length; ++i)
    {
        var isUsed = false;
        for (var j = 0; j < gUsedColor.length; ++j)
        {
            if (gUsedColor[j] == gDefColor[i])
            {
                isUsed = true;
                break;
            }
        }
        if (!isUsed)
        {
            useColor(gDefColor[i]);
            return gDefColor[i];
        }
        
    }
    useColor(gDefColor[0]);
    return gDefColor[0];
}
function useColor(clr)
{
    gUsedColor.push(clr);
}

var g_show_links_openned = false;
function showLinks()
{
    try
    {
        var show_links_elem = document.getElementById("show_links");
        var links_elem = document.getElementById("links");
        
        if (!g_show_links_openned)
        {
            show_links_elem.className = "show-links-openned";
            links_elem.style.display = "block";
        }
        else
        {
            show_links_elem.className = "";
            links_elem.style.display = "none";
        }
        g_show_links_openned = !g_show_links_openned;
    }
    catch (exp) { }
}

var gFunctionsIndex = gFunctionsCount;
function addFunction(functionType)
{
    try
    {
        var functionsBlock = document.getElementById("functions");
        var hf = document.getElementById("functionsCount");

        var funcColor = getColor();
        
        var htmlBefore = "<div id='function_ID' class='box'>";
        htmlBefore += "<div id='param'>";
        htmlBefore += "<input type='hidden' id='clr_ID' name='clr_ID' value='" + funcColor + "'/>";
        htmlBefore += "<span>";
        htmlBefore += "<a href='javascript:;' title='" + Res.ChooseColor + "' onclick='showColorPicker(_ID);'>";
        htmlBefore += "<img id='color_ID' src='images/colorsel.gif' style='background-color:#" + funcColor + ";'/>";
        htmlBefore += "</a>";
        htmlBefore += "</span>&nbsp;";
        htmlBefore += "<a href='javascript:;' onclick='delFunction(_ID);return false;' title='" + Res.Delete + "'><img src='images/delete.gif' /></a>";
        htmlBefore += "</div>";

        var htmlAfter = "</div>";

        var html = "";
        switch (functionType)
        {
            case "norm":
                html = "<span class='name'>y(x)&nbsp;=&nbsp;</span><input type='text' class='input' name='exp_ID'/>";
                break;
            case "param":
                html = "<span class='name'>x(t)&nbsp;=&nbsp;</span><input type='text' class='input' name='x_ID'/><br/>";
                html += "<span class='name'>y(t)&nbsp;=&nbsp;</span><input type='text' class='input' name='y_ID'/><br/>";
                html += "<div>";
                html += Res.Interval + "&nbsp;t&nbsp;";
                html += "[&nbsp;<input type='text' class='parametr' name='mit_ID' value='-10'/>&nbsp;,&nbsp;";
                html += "<input type='text' class='parametr' name='mat_ID' value='10'/>&nbsp;]&nbsp;&nbsp;";
                html += Res.Units + ":&nbsp;";
                html += "<select name='ut_ID'>";
                html += "<option value='mm'>" + Res.UnitsMM + "</option>";
                html += "<option value='pi'>" + Res.UnitsPI + "</option>";
                html += "</select>";
                html += "</div>";
                break;
            case "byval":
                html = "<span class='name'>" + Res.Points + "(x;y):</span><input type='text' id='textPoint_ID' style='width:80px;' value='(1;1)'/>";
                html += "&nbsp;<input type='button' id='mButtonPointAdd_ID' onclick='addPoint(_ID);' value='" + Res.Add + "'/>";
                html += "&nbsp;&nbsp;<span class='name'><input type='checkbox' id='checkboxPointSmooth_ID' name='ps_ID' /><label for='checkboxPointSmooth_ID'>" + Res.Smoofly + "</label></span>";
                html += "&nbsp;&nbsp;<span class='name'><input type='checkbox' id='checkboxPointVisible_ID' name='pv_ID' /><label for='checkboxPointVisible_ID'>" + Res.MarkPoints + "</label></span>";
                html += "<div>";
                html += "<textarea type='text' id='textareaPoint_ID' name='pt_ID' style='width:530px;height:100px'></textarea>";
                html += "</div>";
                break;
        }

        ++gFunctionsCount;
        var newId = gFunctionsIndex++;

        html = htmlBefore.replace(/_ID/g, newId) + html.replace(/_ID/g, newId) + htmlAfter.replace(/_ID/g, newId);
        functionsBlock.innerHTML += html;
        hf.value = gFunctionsCount;
    }
    catch (exp) { }
}
function delFunction(id)
{
    var functionsBlock = document.getElementById("functions");
    var func = document.getElementById("function" + id);
    var hf = document.getElementById("functionsCount");
    try
    {
        functionsBlock.removeChild(func);
        --gFunctionsCount;
        hf.value = gFunctionsCount;
    }
    catch (exp) { }
}
function addPoint(id)
{
    try
    {
        var mTextPoint = document.getElementById("textPoint" + id);
        var mTextareaPoint = document.getElementById("textareaPoint" + id);
        var val = mTextPoint.value;
        val = val.replace(/[\s\t]/g, "");
        if (val.match(/^\(-?\d+\,?\d*\;-?\d+\,?\d*\)$/g))
            mTextareaPoint.value += val;
    }
    catch (ex) { }
}
function enableCtrl(id, enable)
{
    try
    {
        var ctrl = document.getElementById(id);
        ctrl.disabled = !enable;
    }
    catch (ex) { }
}

//----------------------------------------------------------------------------------
/* DHTML Color Picker, Programming by Ulyses, ColorJack.com */
/* This version featured on/ available at Dynamic Drive: http://www.dynamicdrive.com */
/*Minor fixes by DD: Disabled text selection during dragging, fixed IE doctype issue with document.body */

var standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body
function $(v) { return(document.getElementById(v)); }
function $S(v) { return($(v).style); }
function browser(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function toggleVisible(v) { $S(v).display=($S(v).display=='none'?'block':'none'); }
function within(v,a,z) { return((v>=a && v<=z)?true:false); }
function XY(e,v)
{
    var z = browser('msie') ?
        Array(event.clientX + standardbody.scrollLeft, event.clientY + standardbody.scrollTop) :
        Array(e.pageX, e.pageY);
        return (z[zero(v)]); 
}
function zero(v)
{
    v = parseInt(v);
    return (!isNaN(v) ? v : 0 );
}
function zindex(d)
{
    d.style.zIndex=zINDEX++;
}

/* PLUGIN */

var maxValue={'h':'359','s':'100','v':'100'},HSV={0:359,1:100,2:100};
var SVHeight=165,wSV=162,wH=162,slideHSV={0:359,1:100,2:100},zINDEX=15;
var stop = true;

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(-4);
	}
	function drag(e)
	{
	    if(!stop)
	    {
		    if (d == 'clrpkr_SVslide')
		    {
		        tXY(e);
		        ds.left = ckHSV(tX, wSV) + 'px';
		        ds.top  = ckHSV(tY, wSV) + 'px';
			    slideHSV[1] = mkHSV(100, wSV, ds.left);
			    slideHSV[2] = 100 - mkHSV(100,wSV,ds.top);
			    HSVupdate();
		    }
		    else if (d == 'clrpkr_Hslide')
		    {
			    tXY(e);
			    ds.top = (ckHSV(tY,wH)) + 'px';
			    slideHSV[0] = mkHSV(359, wH, ds.top);
     
			    function commit()
			    {
			        var r='hsv', z={}, j='';
				    for (var i = 0; i <= r.length - 1; i++)
				    {
				        j = r.substr(i,1);
				        z[i] = (j=='h') ? maxValue[j] - mkHSV(maxValue[j], wH, ds.top) : HSV[i];
				    }
				    return HSVupdate(hsv2hex(z));
			    }
			    makeColor(commit());
			    $S('clrpkr_SV').backgroundColor = '#' + hsv2hex(Array(HSV[0],100,100));
		    }
	    }
	    if (e && e.preventDefault)
		    e.preventDefault()
	    else
		    return false
	}
	if (stop)
	{
	    stop = false;
	    var ds = $S(d);
	    var left = ($(o).offsetLeft + 11);
	    var top  = ($(o).offsetTop + 11);
	    var tX;
	    var tY;
	    if (d == 'clrpkr_SVslide')
	        slideHSV[0] = HSV[0];
	    
		document.onmousemove = drag;
		document.onmouseup = function(){ stop = true; document.onmousemove=''; document.onmouseup=''; };
		drag(e);
	}
}
function HSVupdate(v) 
{
    HSV = v ? hex2hsv(v) : Array(slideHSV[0], slideHSV[1], slideHSV[2]);
	if (!v)
	    v = hsv2hex(Array(slideHSV[0], slideHSV[1], slideHSV[2]));
	makeColor(v);
	return(v);
}
function loadSV()
{
    var z='';
    for (var i = SVHeight; i >= 0; i--)
        z += "<div style=\"background:#" + hsv2hex(Array(Math.round((359 / SVHeight) * i), 100, 100)) + ";\"><br /><\/div>";
    $('clrpkr_Hmodel').innerHTML = z;

    // predefined colors
    var clr = '';
    for (var i = 0; i < gDefColor.length; ++i)
        clr += "<a href='javascript:;' class='defclr' style='background-color:#" + gDefColor[i] + ";' onclick='chooseDefColor(\"" + gDefColor[i] + "\");'>&nbsp;&nbsp;&nbsp;</a> ";
    $('clrpkr_def').innerHTML = clr;
}
function updateH(v)
{
    HSV=hex2hsv(v);
	$S('clrpkr_SV').backgroundColor='#'+hsv2hex(Array(HSV[0],100,100)); 
	$S('clrpkr_SVslide').top=(parseInt(wSV-wSV*(HSV[2]/100))-4)+'px';
	$S('clrpkr_SVslide').left=parseInt(wSV*(HSV[1]/100))+'px';
	$S('clrpkr_Hslide').top=(parseInt(wH*((maxValue['h']-HSV[0])/maxValue['h']))-7)+'px';
}

/* CONVERSIONS */

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 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 rgb2hex(r) { return(toHex(r[0])+toHex(r[1])+toHex(r[2])); }
function hsv2hex(h) { return(rgb2hex(hsv2rgb(h))); }	
function hex2hsv(v) { return(rgb2hsv(hex2rgb(v))); }

function rgb2hsv(r) { // easyrgb.com/math.php?MATH=M20#text20

	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 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({0:R?R:0,1:G?G:0,2:B?B:0});
	}
	else return({0:(V=Math.round(V*255)),1:V,2:V});
}
//----------------------------------------------------------------------
function chooseDefColor(clr)
{
    makeColor(clr);    
    updateH(clr);
}

var gId = 0;
function makeColor(clr)
{
    try
    {
        var clrElem = document.getElementById("color" + gId);
        var clrHdn = document.getElementById("clr" + gId);
        clrElem.style.backgroundColor = '#' + clr;
        clrHdn.value = clr;
    }
    catch (ex) { }
}
function getElementRect(elem)
{
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;    
    var l = 0;
    var t = 0;
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return {"left":l, "top":t, "width":w, "height":h};
}
function showColorPicker(id)
{
    try
    {
        gId = id;
        var owner = document.getElementById('color' + id);
        var clrpkr = document.getElementById('clrpkr');
        var pos = getElementRect(owner);
        clrpkr.style.left = pos.left + 'px';
        clrpkr.style.top = pos.top + pos.height + 'px';

        var clrHdn = document.getElementById("clr" + id);
        if (clrHdn.value != '')
            updateH(clrHdn.value);
        
        toggleVisible('clrpkr');
    }
    catch (e) {}
}
//----------------------------------------------------------------------------



