var frame_border = 2;
var IMG_MIN_W = 30;
var IMG_MIN_H = 30;

function normalizeVal(minval, val, maxval){
    return Math.min(Math.max(minval, val), maxval);
}


function flickrserach(){
    new Ajax.Request(
            'fsearch', {
            method:'post',
            postBody: 'user=' + escape($('flickr_user').value) + '&tags=' + escape($('flickr_tags').value),
            onSuccess: function(xmlHttp){
                if(xmlHttp.responseText){
                    var f = $('flickrform');
                    var ow = f.getWidth();
                    var oh = f.getHeight();
                    var co = f.cumulativeOffset();
                    f.style.width  = '700px';
                    f.style.left = (co.left - (f.getWidth() - ow) / 2) + 'px';
                    $('fres').innerHTML = xmlHttp.responseText;
                }
            }
        });
}

function flickrselect(src, id){
    if(src.style.borderTopColor == 'red'){
        src.style.border = '2px solid white';
        $('fsel' + id).value = '';
    }else{
        src.style.border = '2px solid red';
        $('fsel' + id).value = src.src;
    }
}

function showDialog(e, dialogid){
    var d = $(dialogid);
    d.absolutize();
    //d.show();
    d.style.left = Math.round((Event.pointerX(e) - d.getWidth() / 2)) + 'px';
    d.style.top = Math.round((Event.pointerY(e) -  d.getHeight() / 2)) + 'px';
    Effect.SlideDown(dialogid);
}

function hideDialog(src){
    while(src){
        if(Element.extend(src).match('.modaldialog')){
            src.hide();
            return;
        }
        src = src.parentNode;
    }
}

function selectSize(custom){
    var v = $('selsize').value;
    if(v == custom){
        $('customsize').show();
    }else{
        $('customsize').hide();
        $('apply').click();
    }
}

function save_frame(){
    var div = $('imgdiv');
    var w = $('watermark');
    div = div ? {
                id: $('idx').value,
                size: $('selsize').value,
                w: div.getWidth(),
                h: div.getHeight(),
                l: div.positionedOffset().left,
                t: div.positionedOffset().top,
                tr: $('tr').value =='on' ? 1 : 0,
                bg: $('bg').value,
                r: null
            } : ($('idx') ? {
                id: $('idx').value,
                size: $('selsize').value,
                tr: $('tr').value =='on' ? 1 : 0,
                bg: $('bg').value,
                r: null
                } : {});

    $('frame_data').value = Object.toJSON({
        mark: w ? (w.checked ? 1 : 0) : 1,
        morph: $('morph').checked ? 1 : 0,
        order: Sortable.sequence('flist'),
        opts: div
        });
}

function center_frame_image(){
    var img = $('imgdiv');
    img.style.top = '0px';
    img.style.left = '0px';
    img.style.width = Element.extend(img.parentNode).getWidth();
    img.style.height = Element.extend(img.parentNode).getHeight();
}

function showWhileLoad(){
    var w = $('whileload');
    var i = $('whileloadimg');
    var p = Element.extend(w.parentNode);
    w.show();
    w.style.left = '0px';
    w.style.top = '0px';
    w.style.width = p.getWidth() + 'px';
    w.style.height = p.getHeight() + 'px';
    i.style.left = '0px';
    i.style.top = '0px';
    i.style.width = p.getWidth() + 'px';
    i.style.height = p.getHeight() + 'px';
}

function select_frame(id){
    showWhileLoad();
    save_frame();

    new Ajax.Request(
            '/getframe',
            {
                method:'post',
                postBody: 'get='+id+'&frame_data=' + $('frame_data').value,
                onSuccess: function(xmlHttp){
                    var td = $('frametd');
                    td.update(xmlHttp.responseText);
                    var sel = $$('.selected')[0];
                    if(sel) sel.removeClassName('selected')
                    $('sf_' + id).addClassName('selected');
                    $('whileload').hide();
            }
        });
}

function set_selected(idx){
    var f = $('sf_' + idx);
    //var f = $('flist').select('.framepreviev')[idx];
    if(!f) f = $('flist').select('.framepreviev')[0];
    if(!f) return;
    f.addClassName('selected');
    var s = $('flscroll');
    if(!s) return;
    var l = parseInt(f.offsetLeft) + f.getWidth();
    if(l > s.getWidth()){
        s.scrollLeft = l;
    }
}

function addFileUpload(){
    var f = $('uploadfiles');
    var d = new Element('DIV', { 'class': 'addframefrom'});
    d.update($('filetpl').innerHTML);
    f.appendChild(d);
    $('fileupload').show();
}

function addRefUpload(){
    var f = $('uploadfiles');
    var d = new Element('DIV', { 'class': 'addframefrom'});
    d.update($('reftpl').innerHTML);
    f.appendChild(d);
    $('fileupload').show();
}

function addEmptyUpload(){
    var f = $('uploadfiles');
    var d = new Element('DIV', { 'class': 'addframefrom'});
    d.update($('emptytpl').innerHTML);
    f.appendChild(d);
    $('fileupload').show();
}

function removeFrameUpload(src){
    Element.remove(src.parentNode);
    if($('uploadfiles').select('.addframefrom').length < 1) $('fileupload').hide();
}
//*******************************
//*** move frames
function moveImage(e){
    if (!e) e = window.event;
    var obj = $('imgdiv');
    var oldx = Event.pointerX(e);
    var oldy = Event.pointerY(e);

    var cursorwas = obj.style.cursor;
    obj.style.cursor="move";
    document.onmousemove = function (e){
            if (!e) e = window.event;
            e = Event.extend(e);

            setImageXPos(parseInt(obj.style.left) + e.pointerX() - oldx);
            setImageYPos(parseInt(obj.style.top)  + e.pointerY() - oldy);

            oldx = e.pointerX();
            oldy = e.pointerY();

            if (e.preventDefault) e.preventDefault();
            else e.returnValue = false;
        }
    document.onmouseup =  function (e){
            obj.style.cursor= cursorwas;
            document.onmousemove = null;
            document.onmouseup = null;
            document.ondragstart= null;
            document.onselectstart = null;
        }

    document.ondragstart = null;
    document.onselectstart = null;

    if (e.preventDefault) e.preventDefault();
    else e.returnValue = false;
    return true;
}

function setImageXPos(newX){
    var obj = $('imgdiv');
    newX = Math.max(0, Math.min(newX,  $('frame').getWidth() - $('imgdiv').getWidth()));

    obj.style.left = newX + 'px';
    var editx = $('posx');
    if(editx.value != newX)  editx.value = newX;
}

function setImageYPos(newY){
    var obj = $('imgdiv');
    newY = Math.max(0, Math.min(newY,  $('frame').getHeight() - $('imgdiv').getHeight()));

    obj.style.top = newY + 'px';
    var edity = $('posy');
    if(edity.value != newY)  edity.value = newY;
}

function setPosX(){
    var src = $('posx');
    var newX = parseInt(src.value);
    if(isNaN(newX)) newX = 0;
    setImageXPos(newX);
}

function setPosY(){
    var src = $('posy');
    var newY = parseInt(src.value);
    if(isNaN(newY)) newY = 0;
    setImageYPos(newY);
}
//*** move frames
//***************************


//***************************
//*** resize frames
function resizeImage(e, byx, byy){
    if (!e) e = window.event;
    e = Event.extend(e);

    var obj = $('imgdiv');
    var frame = $('frame');

    oldx = e.pointerX();
    oldy = e.pointerY();

    var cursorwas = obj.style.cursor;
    obj.style.cursor="move";
    document.onmousemove = function (e){
            if (!e) e = window.event;
            e = Event.extend(e)
            var imgdiv = $('imgdiv');

            var maxw = Math.min(frame.getWidth(), (byx > 0 ? imgdiv : frame).getWidth()  + byx * parseInt(imgdiv.style.left));
            var maxh = Math.min(frame.getHeight(), (byy > 0 ? imgdiv : frame).getHeight() + byy * parseInt(imgdiv.style.top));

            var nx = e.pointerX();
            var ny = e.pointerY();
            var oldh = imgdiv.getHeight();
            var oldw = imgdiv.getWidth();

            var nw = normalizeVal(IMG_MIN_W, imgdiv.getWidth()  + byx*(oldx - nx), maxw);
            var nh = normalizeVal(IMG_MIN_H, imgdiv.getHeight() + byy*(oldy - ny), maxh);

            //$('log').innerHTML += byy +' '+imgdiv.getHeight() + ' ' + parseInt(imgdiv.style.top) + ' '+ maxh +' '+nh +'<br/>';

            imgdiv.style.width = nw + 'px';
            imgdiv.getElementsByTagName('IMG')[0].style.height = nh + 'px';//ie trouble
            if(byx > 0) imgdiv.style.left = (parseInt(imgdiv.style.left) - (nw - oldw)) + 'px';
            $('width').value = nw;
            $('posx').value = parseInt(imgdiv.style.left);

            imgdiv.style.height = nh + 'px';
            imgdiv.getElementsByTagName('IMG')[0].style.height = nh + 'px';//ie trouble
            if(byy > 0) imgdiv.style.top = (parseInt(imgdiv.style.top) - (nh - oldh)) + 'px';
            $('height').value = nh;
            $('posy').value = parseInt(imgdiv.style.top);

            oldx = nx;
            oldy = ny;

            if (e.preventDefault) e.preventDefault();
            else e.returnValue = false;
        }
    document.onmouseup = function (e){
            obj.style.cursor = cursorwas;
            document.onmousemove = null;
            document.onmouseup = null;
            document.ondragstart= null;
            document.onselectstart = null;
            if (!e) e = window.event;
            if (e.preventDefault) e.preventDefault();
            else e.returnValue = false;
        }

    if (e.preventDefault) e.preventDefault();
    else e.returnValue = false;
}

function setWidth(){
    var field = $('width');
    var w = parseInt(field.value);
    if(isNaN(w)) return;
    var nw = normalizeVal(IMG_MIN_W, w, $('frame').getWidth() - parseInt($('imgdiv').style.left));
    if(w == nw) $('imgdiv').style.width = nw + 'px';
}

function setHeight(){
    var field = $('height');
    var h = parseInt(field.value);
    if(isNaN(h)) return;
    var nh = normalizeVal(IMG_MIN_H, h, $('frame').getHeight() - parseInt($('imgdiv').style.top));
    if(h == nh){
        imgdiv.getElementsByTagName('IMG')[0].style.height = nh + 'px';//ie trouble
        $('imgdiv').style.height = nh + 'px';
    }
}
//*** resize frames
//***************************

//***************************
//*** rotate image
var posx;
var posy;
var obj;
var cursorwas;

function rotateImage(src, e){
    if (!e) e = window.event;
    e = Event.extend(e);
    obj = Element.extend(src);
    cursorwas = src.style.cursor;
    src.style.cursor="move";
    document.onmousemove = onRotateImage;
    document.onmouseup = onRotateImageStop;
}

var wide = 2;
var lastcorner;
var dot_free = new Array();
var dot_used = new Array();
function onRotateImage(e){
    if (!e) e = window.event;
    e = Event.extend(e);

    var a = - calculateA(e) - Math.PI / 2;

    var ocx = $('imgdiv').positionedOffset().left + Math.round($('imgdiv').getWidth() /2);
    var ocy = $('imgdiv').positionedOffset().top + Math.round($('imgdiv').getHeight() /2);

    var h2 = Math.round(obj.getHeight() / 2);
    var w2 = Math.round(obj.getWidth()  / 2);
    var r = Math.sqrt(h2 * h2 + w2 * w2);
    var alpha  = Math.acos(w2 / r) + a;
    var alpha2 = Math.acos(h2 / r) + a + Math.PI / 2;

    var dx1 = Math.abs(r * Math.cos(alpha + a));
    var dy1 = Math.abs(r * Math.sin(alpha + a));
    var dx2 = Math.abs(r * Math.sin(alpha2 + a));
    var dy2 = Math.abs(r * Math.cos(alpha2 + a));

    var dx1 = parseInt(r * Math.cos(alpha));
    var dy1 = parseInt(r * Math.sin(alpha));
    var dx2 = parseInt(r * Math.cos(alpha2));
    var dy2 = parseInt(r * Math.sin(alpha2));
    var x1 = ocx + dx1;
    var y1 = ocy + dy1;
    var x2 = ocx + dx2;
    var y2 = ocy + dy2;
    var x3 = ocx - dx1;
    var y3 = ocy - dy1;
    var x4 = ocx - dx2;
    var y4 = ocy - dy2;

    var pos = 0;
    dot_free = dot_free.concat(dot_used);
    dot_used = new Array();

    drawLine(obj.parentNode, x1,y1,x2,y2, 'red');
    drawLine(obj.parentNode, x2,y2,x3,y3);
    drawLine(obj.parentNode, x3,y3,x4,y4);
    drawLine(obj.parentNode, x4,y4,x1,y1);
    for(var idx = 0; idx < dot_free.length ; idx++){
        dot_free[idx].style.display = 'none';
    }
}

function drawLine(obj,x1,y1,x2,y2,color){
    var lenx = x2 -x1;
    var leny = y2 -y1;
    var len = Math.sqrt(lenx * lenx + leny * leny);
    var steps = Math.ceil(len / 10);
    var step = len / steps;
    var cos = lenx / len;
    var sin = leny / len;

    for(var s = 0; s < steps; s ++){
        var x = Math.round(x1 + step * s  * cos);
        var y = Math.round(y1 + step * s  * sin);

        var dot = dot_free.pop();
        if(!dot){
            dot = new Element('DIV', { 'class': 'rborder'});
            obj.appendChild(dot);
        }

        dot_used.push(dot);

        dot.style.left = (x - Math.round(wide/2)) + 'px';
        dot.style.top = (y - Math.round(wide/2)) + 'px';
        dot.style.backgroundColor = color ? color : 'blue';
        dot.style.display = 'block';
    }
}

function calculateA(e){
    e = Event.extend(e);
    var ex = e.pointerX();
    var ey = e.pointerY();
    var cx = $('imgdiv').cumulativeOffset().left + Math.round($('imgdiv').getWidth() /2);
    var cy = $('imgdiv').cumulativeOffset().top + Math.round($('imgdiv').getHeight() /2);

    var dx = (ex - cx);
    var dy = (-1)*(ey - cy);
    var pi = 3.14;

    var dl = Math.sqrt(dx*dx + dy*dy);
    var a = Math.acos(dx / dl);
    if(dy < 0) a = pi + (pi - a);
    return a;
}


function onRotateImageStop(e){
    if(!e) e = window.event;
    for(var idx = 0; idx < dot_free.length ; idx++){
        Element.remove(dot_free[idx]);
    }
    for(var idx = 0; idx < dot_used.length ; idx++){
        Element.remove(dot_used[idx]);
    }
    dot_free = new Array()
    dot_used = new Array();
    save_frame();

    new Ajax.Request(
        '/rotate', {
        method:'post',
        postBody: 'rotate=' +calculateA(e)+ '&frame_data=' + $('frame_data').value,
        onSuccess: function(xmlHttp){
            if(xmlHttp.responseText){
                var frame = $('frame');
                frame.innerHTML = xmlHttp.responseText;
            }
        }
    });

    if (obj) {
        obj.style.cursor = cursorwas;
        obj = null;
    }
    document.onmousemove = null;
    document.onmouseup = null;
    document.ondragstart= null;
    document.onselectstart = null;
}
//*** rotate image
//***************************
 document.ondragstart= function (){
    //alert('drag');
 };

var advPropRefColor;

function showAdvProp(idx){
    var aprop = $('advprop');
    var aref  = $('advref');
    if(aprop.style.display == 'none' || aprop.style.display == ''){
        aprop.style.display = 'block';
        advPropRefColor = aref.style.color;
        aref.style.color = 'gray';
    }else{
        aprop.style.display = 'none';
        aref.style.color = advPropRefColor
    }

    //var frame = $('frame');
    //var height = frame.getHeight();
    //frame.style.height = (height + 1) + 'px';
    //frame.style.height = height + 'px';
}

function showToGallery(){
    el = $("togallery");
    el.style.display = (el.style.display != "none" ? "none" : "" );
}

function onCSFinish(result){
    hideDialog($('colorPickerDialog'));// colorPickerDialog()
    //$('colorPicker').style.display = "none";
    if(result){
        $('bg').value = result;
        $('bgb').style.background = result;
        if(!$('tr').checked) $('frame').style.background = result;
    }
}

function animSC(event){
    //fnShowChooseColorDlg(); return;
    var value = $('bg').value;
    new Ajax.Request(
        '/color/color_dialog.php',
        {
            method:'get',
            onSuccess: function(xmlHttp){
                $('coloddialogcontainer').update(xmlHttp.responseText);
                showColorChooserDialog('colorPicker', value, onCSFinish);
        }});
    showDialog(event, 'colorPickerDialog');
    //$('colorPickerDialog'),show();
    //showColorChooserDialog(event, 'colorPicker', value, onCSFinish);
}
/*
function onBGColor(){
    value = $('bg').value;
    $('bgb').style.background = value;
    if(!$('tr').checked) $('frame').style.background = value;
}*/

function onTRChange(event){
    if($('tr').value == 'on'){
        $('frame').style.background = '#ffffff';
        $('bgb').hide();
    }else{
        $('frame').style.background = $('bg').value;
        $('bgb').show();;
    }
}


/**from index.php**/

function blockShowHide(src){
        var par = src.parentNode;
        var show = par.getElementsByTagName('DIV')[0];
        if(show.style.display == 'none'){
            par.style.border = '1px solid #d3d3d3';
            show.style.display = 'block';
        }else{
            par.style.border = '0px';
            show.style.display = 'none';
        }
    }

    function updateGallery(src){
        var els = src.parentNode.parentNode.getElementsByTagName('input');
        var gid = els[0].value;
        var hidden = els[1].checked;
        var name = els[2].value;
        var descr = src.parentNode.parentNode.getElementsByTagName('textarea')[0].value;
        var ref = '/agallery?ajax&updatecomment'
            + '&gid=' + encodeURIComponent(gid)
            + '&hidden=' + encodeURIComponent(hidden)
            + '&picname=' + encodeURIComponent(name)
            + '&comment=' + encodeURIComponent(descr);
        src = src.parentNode.parentNode;
        src.innerHTML = 'saving...';

        callAjaxPost(ref, onUpdateGallery, src, '');
    }

    function onUpdateGallery(http, src){
        src.innerHTML = http.responseText;

    }

    function callAjaxPost(urlData, onGetResult, src, data){
        var http;
        if (window.ActiveXObject){
            try {
                http = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }else if (window.XMLHttpRequest){
            http = new XMLHttpRequest();
            if (http.overrideMimeType) {
                http.overrideMimeType('text/html');
            }
        }

        http.resultFunc = onGetResult;

        http.onreadystatechange = function (){
            if(http && http.readyState == 4 && http.status == 200){
                http.resultFunc(http, src);
            }
        };

        http.open("POST", urlData, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length",data.length);
        http.setRequestHeader("Connection", "close");
        http.send(data);
    }

    function tabselect(src){
        var i;
        var childs = src.parentNode.parentNode.getElementsByTagName('DIV')[1].childNodes;

        var menu = src.parentNode.getElementsByTagName('A');
        var pages = new Array();
        var idx;

        for(i = 0; i < childs.length; i ++){
            if(childs[i].tagName == 'DIV')
                pages[pages.length] = childs[i];
        }

        for(i = 0; i < menu.length; i ++){
            if(menu[i] == src){
                menu[i].className = 'tabselected';
                idx = i;
            }else menu[i].className = '';
        }

        for(i = 0; i < pages.length; i ++){
            if( i == idx) pages[i].style.display = 'block';
            else pages[i].style.display = 'none';
        }
    }

    function tabSelect2(src){
        var i;
        var tab = $(src.parentNode.parentNode);

        var menu = Selector.findChildElements(tab, ['.tabmenu a']);
        var pages = Selector.findChildElements(tab,['.page']);

        for(i = 0; i < menu.length; i ++){
            var cname = 'tabselected';
            if(menu[i] == src){
                Element.addClassName(menu[i], cname);
                pages[i].show();
            }else{
                Element.removeClassName(menu[i], cname);
                pages[i].hide();
            }
        }               
    }

    function commentsPage(src, ref){
        while(src.className != 'pages'){
            src = src.parentNode;
        }
        src = src.parentNode;

        callAjaxPost(ref,
            function (http, com){
                src.innerHTML = http.responseText;
            },
            src, '');

    }





//************


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;
}
