/* DHTML Color Picker : v1.0.4 : 2008/04/17 */
/* http://www.colorjack.com/software/dhtml+color+picker.html */
/* Heavily modified by John Green -- turned into a widget-like class that doesn't overly pollute the global namespace.
 */

function $e(v, o)
{
    return ((typeof (o) == 'object' ? o : document).getElementById(v));
}
function $S(o)
{
    o = $e(o);
    if (o) return (o.style);
}
function abPos(o)
{
    var o = (typeof (o) == 'object' ? o : $e(o)), z = {
        X :0,
        Y :0
    };
    while (o != null)
    {
        z.X += o.offsetLeft;
        z.Y += o.offsetTop;
        o = o.offsetParent;
    }
    ;
    return (z);
}
function within(v, a, z)
{
    return ((v >= a && v <= z) ? true : false);
}
function XY(e, v)
{
    var z = Math.max(navigator.userAgent.toLowerCase().indexOf('msie'), 0) ? [ event.clientX + document.body.scrollLeft, event.clientY + document.body.scrollTop ] : [ e.pageX, e.pageY ];
    return (z[(isNaN(parseInt(v, 10)) ? 0 : v)]);
}

/**
 * An object which encapsulates a dynamically created, modifiable stylesheet.
 * This is a singleton, hence no constructor.
 * 
 */
var Css = {};
Css.cache = {};
Css.firstIndex = -1;;
Css.indicies = [];
Css.change = function(tclass, tel, tval)
{
    var cssRules = (document.all) ? 'rules' : 'cssRules';
    var pLen = document.styleSheets.length - 1;
    
    if (Css.cache[tclass] == null) Css.cache[tclass] = {};
    Css.cache[tclass][tel] = tval;
    
    if (document.styleSheets[pLen].insertRule)
    {
        Css.indicies.push(document.styleSheets[pLen].insertRule(tclass + ' { ' + tel + ': ' + tval + '; }', document.styleSheets[pLen][cssRules].length));
    }
    else if (document.styleSheets[pLen].addRule)
    {
        Css.indicies.push(document.styleSheets[pLen].addRule(tclass, tel + ': ' + tval + ';'));
    }
    if (Css.firstIndex == -1)
    {
        Css.firstIndex = Css.indicies[0];
    }
};

Css.clear = function()
{
    if (Css.firstIndex < 0) return;
    var pLen = document.styleSheets.length - 1; 
    var pLen2 = (document.styleSheets[pLen].cssRules) ? document.styleSheets[pLen].cssRules.length -1 : document.styleSheets[pLen].rules.length -1;
    for (var i =pLen2; i >=Css.firstIndex; i--)
    {
        
        if (document.styleSheets[pLen].cssRules)
        {
            document.styleSheets[pLen].deleteRule(i);
        }
        else
        {
            document.styleSheets[pLen].removeRule(i);            
        }
    }
    Css.cache = {};    
};

Css.getUpdates = function()
{
    var pOut = '';
    for ( var key in Css.cache)
    {
        pOut += key + '{';
        for ( var subkey in Css.cache[key])
        {
            pOut += subkey + ':' + Css.cache[key][subkey] + ';';
        }
        pOut += '}';
    }
    return pOut;
}

/* COLOR PICKER */

var colorPicker = {};
colorPicker.maxValue = {
    'H' :360,
    'S' :100,
    'V' :100
}, HSV = {
    H :360,
    S :100,
    V :100
};
colorPicker.zIndex = 15;
colorPicker.stop = 1;
colorPicker.slideHSV = {
    H :360,
    S :100,
    V :100
};
colorPicker.currentColor = 0x000000;
colorPicker.parent = null;
colorPicker.currentElement = null;

colorPicker.isIE = null;
colorPicker.getIsIE = function()
{
    return ((colorPicker.isIE == null) ? (navigator.userAgent.toLowerCase().indexOf('msie') > 0) : false);
};
colorPicker.getPosition = function(e)
{
    return ((colorPicker.getIsIE()) ? {
        'x' :event.clientX + document.body.scrollLeft,
        'y' :event.clientY + document.body.scrollTop
    } : {
        'x' :e.pageX,
        'y' :e.pageY
    });
    // return(z[(isNaN(parseInt(v,10)) ? 0 : v )]);
};

colorPicker.elementsValue = {};
colorPicker.elementsForeground = {};
colorPicker.elementsBackground = {};
colorPicker.elementsBorder = {};

colorPicker.clearUpdaters = function()
{
    colorPicker.elementsValue = {};
    colorPicker.elementsForeground = {};
    colorPicker.elementsBackground = {};
    colorPicker.elementsBorder = {};
}

colorPicker.getComputedColor = function(element, attribute, attributeJS)
{
    if (element == null) return false;
    if (element.currentStyle) return element.currentStyle[attributeJS];
    if (window.getComputedStyle)
    {
        var elementStyle = window.getComputedStyle(element, "");
        if (elementStyle) return elementStyle.getPropertyValue(attribute);
    }
    // Return 0 if both methods failed.
    return false;
}

colorPicker.show = function(currentElement,elementsValue, elementsBackground, elementsForeground, elementsBorder)
{
    colorPicker.clearUpdaters();
    colorPicker.currentElement = $(currentElement);
    pOffset = abPos(colorPicker.currentElement);
    
    $('plugin').style.left = pOffset.X + 'px';
    $('plugin').style.top = pOffset.Y + 'px';

    
    
    for ( var i = 0; i < elementsValue.length; i++)
    {
        colorPicker.elementsValue[elementsValue[i]] = $(elementsValue[i]);
    }
    if (elementsBackground)
    {    
        for ( var i = 0; i < elementsBackground.length; i++)
        {
            colorPicker.elementsBackground[elementsBackground[i]] = (elementsBackground[i]);
        }
    }
    if (elementsForeground)
    {    
        for ( var i = 0; i < elementsForeground.length; i++)
        {
            colorPicker.elementsForeground[elementsForeground[i]] = (elementsForeground[i]);
        }
    }
    if (elementsBorder)
    {
        for ( var i = 0; i < elementsBorder.length; i++)
        {
            colorPicker.elementsBorder[elementsBorder[i]] = (elementsBorder[i]);
        }
    }
    colorPicker.parent.style.display = 'block';
    pCol = color.RGB_HSV(color.IND_RGB(colorPicker.getComputedColor($(currentElement), 'background-color', 'backgroundColor')));
    
    colorPicker.HSVupdate(pCol);
    $S("SVslide").position = "absolute";
    $S('SVslide').left = Math.round(pCol.S * 1.67 - 5) + 'px';
    $S('SVslide').top = Math.round(162 - pCol.V * 1.67) + 'px';
    
    pCol.S = 100;
    pCol.V = 100;
    $S('SV').backgroundColor = '#' + color.HSV_HEX(pCol);
    Event.observe($('body'), "mousedown", colorPicker.hide);
    Event.observe($('plugin'), "mousedown", colorPicker.cancel);
}

colorPicker.cancel = function(e)
{
    Event.stop(e);
}

colorPicker.hide = function()
{
    colorPicker.parent.style.display = 'none';
    colorPicker.clearUpdaters();
    Event.stopObserving($('body'), "mousedown", 'colorPicker.hide');
    Event.stopObserving($('plugin'), "mousedown", 'colorPicker.cancel');
    
}

// Event.observe('window','load','colorPicker.init(elId)');

colorPicker.init = function(elId)
{
    
    var pEl = $(elId);
    
    colorPicker.parent = pEl;
    pEl
            .update('<div id="plugin" style="BACKGROUND: #0d0d0d; COLOR: #AAA; CURSOR: move; DISPLAY: block; FONT-FAMILY: arial; FONT-SIZE: 11px; PADDING: 7px 10px 11px 10px; _PADDING-RIGHT: 0; Z-INDEX: 20; POSITION: absolute; WIDTH: 199px; _width: 210px; _padding-right: 0px;"><div style="float: left; width: 10px; height: 10px; font-size: 1px; background: #FFF; margin-right: 3px;" id="plugCUR"></div><div id="plugHEX" style="FLOAT: left; position: relative; top: -1px;" onmousedown="colorPicker.stop=0; setTimeout(\'colorPicker.stop=1\',100);">FFFFFF</div><div id="plugCLOSE" style="FLOAT: right; cursor: pointer; MARGIN: 0 8px 3px; _MARGIN-RIGHT: 10px; COLOR: #FFF; -moz-user-select: none; -khtml-user-select: none; user-select: none;" onmousedown="colorPicker.hide()">X</div><br style="CLEAR: both; MARGIN: 0; PADDING: 0;" /><div id="SV" style="background: #FF0000 url(\'images/SatVal.png\'); _BACKGROUND: #FF0000; POSITION: relative; CURSOR: crosshair; FLOAT: left; HEIGHT: 166px; WIDTH: 167px; _WIDTH: 166px; MARGIN-RIGHT: 10px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/SatVal.png\', sizingMethod=\'scale\'); -moz-user-select: none; -khtml-user-select: none; user-select: none;" onmousedown="colorPicker.HSVslide(\'SVslide\',\'plugin\',event)" title="Saturation + Value"><div id="SVslide" style="TOP: -4px; LEFT: -4px;"><br style="CLEAR: both; MARGIN: 0; PADDING: 0;" /></div></div><form id="H" style="BORDER: 1px solid #000; CURSOR: crosshair; FLOAT: left; HEIGHT: 154px; POSITION: relative; WIDTH: 19px; PADDING: 0; TOP: 4px; -moz-user-select: none; -khtml-user-select: none; user-select: none;" onmousedown="colorPicker.HSVslide(\'Hslide\',\'plugin\',event)" title="Hue"><div id="Hslide" style="TOP: -7px; LEFT: -8px;BACKGROUND: url(\'images/slideHue.gif\'); HEIGHT: 5px; WIDTH: 33px; POSITION: absolute; _font-size: 1px; line-height: 1px;"><br style="CLEAR: both; MARGIN: 0; PADDING: 0;" /></div><div id="Hmodel" style="POSITION: relative; TOP: -5px;"></div>');
    
    var z = '';
    for ( var i = 165; i >= 0; i--)
    {
        z += "<div style=\"HEIGHT: 1px; WIDTH: 19px; font-size: 1px; line-height: 1px; MARGIN: 0; PADDING: 0; BACKGROUND: #" + color.HSV_HEX( {
            H :Math.round((360 / 165) * i),
            S :100,
            V :100
        }) + ';"><br style="CLEAR: both; MARGIN: 0; PADDING: 0;" /><\/div>';
    }
    $e('Hmodel').innerHTML = z;
}

colorPicker.HSVupdate = function(v)
{
    v = color.HSV_HEX(HSV = v ? v : colorPicker.slideHSV);
    colorPicker.currentColor = v;
    $e('plugHEX').innerHTML = v;
    
//    for ( var i = 0; i < colorPicker.updateElements.length; i++)
//    {
//        colorPicker.updateElements[i].innerHTML = v;
//    }
    $S('plugCUR').background = '#' + v;
    
    for (var key in colorPicker.elementsValue)
    {
        colorPicker.elementsValue[key].value = '#' + v;
    }    
    for (var key in colorPicker.elementsBackground)
    {
        Css.change(key, 'background-color', '#' + v);
    }
    for (var key in colorPicker.elementsForeground)
    {
        Css.change(key, 'color', '#' + v);
    }
    for (var key in colorPicker.elementsBorder)
    {
        Css.change(key, 'border-color', '#' + v);
    }
    return (v);
};

colorPicker.HSVslide = function(d, o, e)
{
    function tXY(e)
    {
        pos = colorPicker.getPosition(e);
        tY = pos['y'] - ab.Y - 22;
        tX = pos['x'] - ab.X - 10;// - 24;
    }
    
    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 (!colorPicker.stop)
        {
            if (d != 'drag') tXY(e);
            
            if (d == 'SVslide')
            {
                ds.left = ckHSV(tX - oo, 162) + 'px';
                ds.top = ckHSV(tY - oo, 162) + 'px';
                colorPicker.slideHSV.S = mkHSV(100, 162, ds.left);
                colorPicker.slideHSV.V = 100 - mkHSV(100, 162, ds.top);
                colorPicker.HSVupdate();
                
            }
            else if (d == 'Hslide')
            {
                var ck = ckHSV(tY - oo, 163), r = 'HSV', z = {};
                
                ds.top = (ck - 5) + 'px';
                colorPicker.slideHSV.H = mkHSV(360, 163, ck);
                
                for ( var i in r)
                {
                    i = r.substr(i, 1);
                    z[i] = (i == 'H') ? colorPicker.maxValue[i] - mkHSV(colorPicker.maxValue[i], 163, ck) : HSV[i];
                }
                
                colorPicker.HSVupdate(z);
                $S('SV').backgroundColor = '#' + color.HSV_HEX( {
                    H :HSV.H,
                    S :100,
                    V :100
                });
                
            }
            else if (d == 'drag')
            {
                pos = colorPicker.getPosition(e);
                // ds.left=pos['x']+oX-eX+'px';
                // ds.top=pos['y']+oY-eY+'px';
                ds.left = pos['x'] + oX - eX + 'px';
                ds.top = pos['y'] + oY - eY + 'px';
            }
        }
    }
    
    if (colorPicker.stop)
    {
        colorPicker.stop = '';
        var ds = $S(d != 'drag' ? d : o);
        if (d == 'drag')
        {
            pos = colorPicker.getPosition(e);
            var oX = parseInt(ds.left), oY = parseInt(ds.top), eX = pos['x'], eY = pos['y'];
            $S(o).zIndex = colorPicker.zIndex++;
        }
        else
        {
            // var ab=abPos($e(o)), tX, tY, oo=(d=='Hslide')?2:4;
            // var ab=abPos(colorPicker.currentElement), tX, tY,
            // oo=(d=='Hslide')?2:4;
            var ab = abPos(colorPicker.currentElement), tX, tY, oo = (d == 'Hslide') ? 2 : 4;
            // ab.X+=10;
            // ab.Y+=22;
            if (d == 'SVslide') colorPicker.slideHSV.H = HSV.H;
        }
        
        document.onmousemove = drag;
        document.onmouseup = function()
        {
            colorPicker.stop = 1;
            document.onmousemove = '';
            document.onmouseup = '';
        };
        // document.body.onmousedown = function(){ colorPicker.hide() };
        
        // colorPicker.currentElement.onmousedown = function(e)
        // {e.cancelEvent(); e.stopPropogation();}
        drag(e);
    }
};

/* COLOR LIBRARY */

color = {};

color.cords = function(W)
{
    
    var W2 = W / 2, rad = (hsv.H / 360) * (Math.PI * 2), hyp = (hsv.S + (100 - hsv.V)) / 100 * (W2 / 2);
    
    $S('mCur').left = Math.round(Math.abs(Math.round(Math.sin(rad) * hyp) + W2 + 3)) + 'px';
    $S('mCur').top = Math.round(Math.abs(Math.round(Math.cos(rad) * hyp) - W2 - 21)) + 'px';
    
};

color.HEX = function(o)
{
    o = Math.round(Math.min(Math.max(0, o), 255));
    
    return ("0123456789ABCDEF".charAt((o - o % 16) / 16) + "0123456789ABCDEF".charAt(o % 16));
    
};

color.RGB_HEX = function(o)
{
    var fu = color.HEX;
    return (fu(o.R) + fu(o.G) + fu(o.B));
};

color.HSV_RGB = function(o)
{
    
    var R, G, A, B, C, S = o.S / 100, V = o.V / 100, H = o.H / 360;
    
    if (S > 0)
    {
        if (H >= 1) H = 0;
        
        H = 6 * H;
        F = H - Math.floor(H);
        A = Math.round(255 * V * (1 - S));
        B = Math.round(255 * V * (1 - (S * F)));
        C = Math.round(255 * V * (1 - (S * (1 - 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 ? R : 0,
            'G' :G ? G : 0,
            'B' :B ? B : 0,
            'A' :1
        });
        
    }
    else return ( {
        'R' :(V = Math.round(V * 255)),
        'G' :V,
        'B' :V,
        'A' :1
    });
    
};
color.RGB_HSV = function(o)
{
    
    var M = Math.max(o.R, o.G, o.B), delta = M - Math.min(o.R, o.G, o.B), H, S, V;
    
    if (M != 0)
    {
        S = Math.round(delta / M * 100);
        
        if (o.R == M) H = (o.G - o.B) / delta;
        else if (o.G == M) H = 2 + (o.B - o.R) / delta;
        else if (o.B == M) H = 4 + (o.R - o.G) / delta;
        
        var H = Math.min(Math.round(H * 60), 360);
        if (H < 0) H += 360;
        
    }
    
    return ( {
        'H' :H ? H : 0,
        'S' :S ? S : 0,
        'V' :Math.round((M / 255) * 100)
    });
    
};
color.HSV_HEX = function(o)
{
    return (color.RGB_HEX(color.HSV_RGB(o)));
};

color.IND_RGB = function(color)
{
    var rgbColors = new Object();
    
    // /////////////////////////////////
    // Handle rgb(redValue, greenValue, blueValue) format
    // ////////////////////////////////
    if (color[0] == 'r')
    {
        color = color.substring(color.indexOf('(') + 1, color.indexOf(')'));
        var pColors = color.split(',');
        rgbColors['R'] = parseInt(pColors[0], 10);
        rgbColors['G'] = parseInt(pColors[1], 10);
        rgbColors['B'] = parseInt(pColors[2], 10);
    }
    
    // //////////////////////////////
    // Handle the #RRGGBB' format
    // //////////////////////////////
    else if (color.substring(0, 1) == "#")
    {
        rgbColors[0] = color.substring(1, 3); // redValue
        rgbColors[1] = color.substring(3, 5); // greenValue
        rgbColors[2] = color.substring(5, 7); // blueValue
        
        rgbColors['R'] = parseInt(rgbColors[0], 16);
        rgbColors['G'] = parseInt(rgbColors[1], 16);
        rgbColors['B'] = parseInt(rgbColors[2], 16);
    }
    return rgbColors;
}

/* LOAD */
