/*
*  jury Class
*  generates all neccessarry GUI elements
*  keeps track of icon movement
*/

var ajax_url = "/jury/ajax.php"
function _jury()
{
}

_jury.prototype._contentContainer;
_jury.prototype._set1;
_jury.prototype._set2;
_jury.prototype._set1Container;
_jury.prototype._set2Container;
_jury.prototype._juryDraggableContainer;
_jury.prototype._juryDraggable;
_jury.prototype._draggableImageId;
_jury.prototype._draggablePath;
_jury.prototype._draggableResX;
_jury.prototype._draggableResY;
_jury.prototype._selectedSet;
_jury.prototype._selectedSlot;
_jury.prototype._setColor;
_jury.prototype._set1Lock;
_jury.prototype._set2Lock;
_jury.prototype._set1LockR;
_jury.prototype._set2LockR;
_jury.prototype._isOwner;
_jury.prototype._userId;
_jury.prototype._updateLockSet;
_jury.prototype._updateLockVal;

_jury.prototype.init = function(set1, set2, setColor, set1Lock, set2Lock, isOwner, userId)
{
    this._contentContainer = $('content');         
    this._set1Container = $('jury_image_set1');
    this._set2Container = $('jury_image_set2');
    this._juryDraggableContainer = $('jury_image_upload_preview_draggable');
    Droppables.add(this._set1Container, { 
      accept: ['jury_image_upload_preview_draggable', 'drop_spot_draggable'],
      onDrop: function(draggable, set){ jury.onDrop(draggable, set, 1); }
    });
    Droppables.add(this._set2Container, { 
      accept: ['jury_image_upload_preview_draggable', 'drop_spot_draggable'],
      onDrop: function(draggable, set){ jury.onDrop(draggable, set, 2); }
    });
    
    this._set1 = set1;
    this._set2 = set2;
    this._set1Lock = this._set1LockR = set1Lock;
    this._set2Lock = this._set2LockR = set2Lock;
    isOwner = 0;
    this._isOwner = isOwner;
    if(isOwner == 1)  this._set1Lock = this._set2Lock = 0;
    this._userId = userId;
    
    for(var i = 1; i < 3; i++)
    {
        if(i == 1 && this._set1Lock == 1/* && this._isOwner == 0*/) continue;
        if(i == 2 && this._set2Lock == 1/* && this._isOwner == 0*/) continue;
        for(var j = 0; j < 10; j++)
        {
            new Draggable($("set_" + i + "_drop_" + j + "_draggable"), { onStart: function(draggable){ jury.onDragExisting(draggable); }, onEnd: function(draggable){ jury.onDragExistingEnd(draggable); }, revert: false});
        }
    }
    
    this.rebuildSet(1, false);
    this.rebuildSet(2, false);
    
    this._setColor = setColor;
    this.page_swapColor(setColor, false);
    
    this._draggableImageId = 0;
}
               
/* change page colors */
_jury.prototype.page_swapColor = function(color, sync)
{
    this._setColor = color;
    switch(color)
    {
        case 0: // black
        {
            $('overlay').style.backgroundColor = "#000000";
            $('overlay').style.color = "#FFFFFF";
            $$('div.jury_box').each(function(itm)
            {
                itm.style.border = "4px solid #808080";
                itm.style.backgroundColor = "#000000";
            });
            $$('div.drop_spot').each(function(itm)
            {
                itm.style.border = "1px solid #808080";
            });
            $$('a').each(function(itm)
            {
                itm.style.color = "#FFFFFF";
            });
            
            $('jury_image_upload_preview').style.borderLeft = "1px solid #808080";
        }break;
        case 1: // grey
        {
            $('overlay').style.backgroundColor = "#808080";
            $('overlay').style.color = "#FFFFFF";
            $$('div.jury_box').each(function(itm)
            {
                itm.style.border = "4px solid #000000";
                itm.style.backgroundColor = "#808080";
            });
            $$('div.drop_spot').each(function(itm)
            {
                itm.style.border = "1px solid #000000";
            });
            $$('a').each(function(itm)
            {
                itm.style.color = "#FFFFFF";
            });
            
            $('jury_image_upload_preview').style.borderLeft = "1px solid #000000";
        }break;
        case 2: // white
        {
            $('overlay').style.backgroundColor = "#FFFFFF";
            $('overlay').style.color = "#000000";
            $$('div.jury_box').each(function(itm)
            {
                itm.style.border = "4px solid #808080";
                if(itm.getAttribute('id') == 'jury_image_upload') itm.style.backgroundColor = "#FFFFFF";
                else itm.style.backgroundColor = "#FFFFFF";
            });
            $$('div.drop_spot').each(function(itm)
            {
                itm.style.border = "1px solid #808080";
            });
            $$('a').each(function(itm)
            {
                itm.style.color = "#000000";
            });
            $('jury_image_upload_preview').style.borderLeft = "1px solid #808080";
        }break;
        /*case 3: // cafe
        {
            $('overlay').style.backgroundColor = "#FFFFFF";
            $('overlay').style.color = "#000000";
            $$('div.jury_box').each(function(itm)
            {
                itm.style.border = "4px solid #808080";
                if(itm.getAttribute('id') == 'jury_image_upload') itm.style.backgroundColor = "#FFFFFF";
                else itm.style.backgroundColor = "#000000";
            });
            $$('div.drop_spot').each(function(itm)
            {
                itm.style.border = "1px solid #808080";
            });
            $$('a').each(function(itm)
            {
                itm.style.color = "#000000";
            });
            $('jury_image_upload_preview').style.borderLeft = "1px solid #808080";
        }break;*/
        default:
        {
        }break;
    }
    if(sync == true)
    {
        this.resyncSets();
    }
}

_jury.prototype.onUploadStart = function()
{
    this._uploading = true;
    
    this.uploadCheck();
}

_jury.prototype.uploadCheck = function()
{
    if(this._uploading)
    {
        setTimeout("jury.uploadCheck();", 1200);
    }
    $('upload_progress').appear({ duration: 0.5 });
    $('upload_progress').fade({ duration: 0.5, delay: 0.5 });
}

/* assign new image and create draggable */
_jury.prototype.onUploadFinished = function(file, resp)
{
    var response = resp.evalJSON();
    if(response.response == 'success')
    {
        if(this._draggableImageId != 0) // force this item into the first open slot
        {
            var curSet = this._set1;
            var freeSlot = -1;
            
            for(var i = 0; i < 10; i++)
            {
                if(curSet[i]['imageId'] == 0)
                {
                    freeSlot = i;
                    break;
                }
            }
            if(freeSlot != -1)
            {
                curSet[freeSlot]['imageId'] = this._draggableImageId;
                curSet[freeSlot]['path'] = this._draggablePath;
                curSet[freeSlot]['resX'] = this._draggableResX;
                curSet[freeSlot]['resY'] = this._draggableResY;
                
                this._set1 = curSet;
                this.rebuildSet(1, true);
            }
            
        }
        this._draggableImageId = response.data.imageId;
        this._draggablePath = response.data.path;
        this._draggableResX = response.data.resX;
        this._draggableResY = response.data.resY;
        
        this.rebuildDraggable();
    }else
    {
        alert(response.response);
    }

    this._uploading = false;
}

_jury.prototype.rebuildDraggable = function()
{
    this._juryDraggableContainer.style.backgroundImage = "url('" + this._draggablePath + "')";
    this._juryDraggableContainer.style.width = this._draggableResX + "px";
    this._juryDraggableContainer.style.height = this._draggableResY + "px";
    this._juryDraggableContainer.setAttribute('imageId', this._draggableImageId);
    this._juryDraggableContainer.setAttribute('path', this._draggablePath);
    this._juryDraggableContainer.setAttribute('resX', this._draggableResX);
    this._juryDraggableContainer.setAttribute('resY', this._draggableResY);
    
    this._juryDraggableContainer.style.left = Math.round((181 - this._draggableResX) / 2) + "px";
    this._juryDraggableContainer.style.top = Math.round((181 - this._draggableResY) / 2) + "px";
    
    this._juryDraggable = new Draggable(this._juryDraggableContainer, { onStart: function(){ jury.onDrag(); }, onEnd: function(){ jury.onDragEnd(); }, revert: 'false'});
}

_jury.prototype.rebuildSet = function(set, sync)
{
    var curSet = this._set1;
    if(set == 2) curSet = this._set2;

    for(var i = 0; i < 10; i++)
    {
        var drop = $('set_' + set + '_drop_' + i);
        var drag = $('set_' + set + '_drop_' + i + "_draggable");
        drop.setAttribute('imageId', curSet[i]['imageId']);
        drop.setAttribute('path', curSet[i]['path']);
        drop.setAttribute('resX', curSet[i]['resX']);
        drop.setAttribute('resY', curSet[i]['resY']);
        drag.style.background = "url('" + curSet[i]['path'] + "')";
        drag.style.width = curSet[i]['resX'] + "px";
        drag.style.height = curSet[i]['resY'] + "px";
        var left = Math.round((181 - curSet[i]['resX']) / 2);
        var top = Math.round((181 - curSet[i]['resY']) / 2);
        drag.style.left = left + "px";
        drag.style.top = top + "px";
        drag.setAttribute('imageId', curSet[i]['imageId']);
        drag.setAttribute('path', curSet[i]['path']);
        drag.setAttribute('resX', curSet[i]['resX']);
        drag.setAttribute('resY', curSet[i]['resY']);
        // TODO: move somewhere else as it only has to run once
        drag.setAttribute('parent', "set_" + set + "_drop_" + i);
        drag.setAttribute('slot', i);
        drag.setAttribute('set', set);
    }
    
    if(sync == true)
    {
        this.resyncSets();
    }
}

/* handle image dropped on a set */
_jury.prototype.onDrop = function(draggable, setObj, set)
{
    var oldSlot = -1;
    if(draggable.getAttribute('slot') != 'undefined' && draggable.getAttribute('set') == set)
    {
        oldSlot = draggable.getAttribute('slot');
    }
    // adjust offsets
    if(draggable.getAttribute('set'))
    {
        var offsetX = draggable.offsetLeft - setObj.offsetLeft - this._contentContainer.offsetLeft;
        var offsetY = draggable.offsetTop - setObj.offsetTop;
    }else
    {
        var offsetX = this._juryDraggableContainer.offsetLeft - setObj.offsetLeft - this._contentContainer.offsetLeft;
        var offsetY = this._juryDraggableContainer.offsetTop - setObj.offsetTop;
    }
    
    // calculate slot position
    var row = Math.floor(offsetY / 175);
    var pos = Math.floor(offsetX / 175); if(pos < 0) pos = 0;
    var slot = pos + row * 5;
    if(slot > 9) slot = 9;
    
    var curSet = this._set1;
    if(set == 2) curSet = this._set2;
    
    // update set positions
    if(oldSlot == -1) // either new image or image from the other set
    {
        if(curSet[slot]['imageId'] != 0)
        {
            var freeSlot = -1;
            for(var i = slot; i < 10; i++)
            {
                if(curSet[i]['imageId'] == 0)
                {
                    freeSlot = i;
                    break;
                }
            }
            if(freeSlot == -1) freeSlot = 9;
            for(var i = freeSlot; i > slot; i--)
            {
                curSet[i]['imageId'] = curSet[i - 1]['imageId'];
                curSet[i]['path'] = curSet[i - 1]['path'];
                curSet[i]['resX'] = curSet[i - 1]['resX'];
                curSet[i]['resY'] = curSet[i - 1]['resY'];
            }
        }
        curSet[slot]['imageId'] = draggable.getAttribute('imageId');
        curSet[slot]['path'] = draggable.getAttribute('path');
        curSet[slot]['resX'] = draggable.getAttribute('resX');
        curSet[slot]['resY'] = draggable.getAttribute('resY');
        
        if(draggable.getAttribute('id') == "jury_image_upload_preview_draggable")
        {
            this._draggableImageId = this._draggableResX = this._draggableResY = 0;
            this._draggablePath = "";
            this.rebuildDraggable();
        }
    }else // we have to move an image within a set
    {
        if(curSet[slot]['imageId'] != 0)
        {
            if(slot > oldSlot)
            {
                var freeSlot = -1;
                for(var i = slot; i < 10; i++)
                {
                    if(curSet[i]['imageId'] == 0)
                    {
                        freeSlot = i;
                        break;
                    }
                }
                if(freeSlot == -1) freeSlot = 9;
            
                for(var i = freeSlot; i > slot; i--)
                {
                    curSet[i]['imageId'] = curSet[i - 1]['imageId'];
                    curSet[i]['path'] = curSet[i - 1]['path'];
                    curSet[i]['resX'] = curSet[i - 1]['resX'];
                    curSet[i]['resY'] = curSet[i - 1]['resY'];
                }
                
                curSet[oldSlot]['imageId'] = 0;
                curSet[oldSlot]['path'] = "";
                curSet[oldSlot]['resX'] = 0;
                curSet[oldSlot]['resY'] = 0;
            }else if(slot < oldSlot)
            {
                var freeSlot = -1;
                for(var i = slot; i < oldSlot; i++)
                {
                    if(curSet[i]['imageId'] == 0)
                    {
                        freeSlot = i;
                        break;
                    }
                }
                if(freeSlot == -1) freeSlot = oldSlot;
                var hit = false;
                
                for(var i = freeSlot; i > slot; i--)
                {
                    //if(curSet[i]['imageId'] == 0) break;
                    curSet[i]['imageId'] = curSet[i - 1]['imageId'];
                    curSet[i]['path'] = curSet[i - 1]['path'];
                    curSet[i]['resX'] = curSet[i - 1]['resX'];
                    curSet[i]['resY'] = curSet[i - 1]['resY'];
                    if(i == oldSlot) hit = true;
                }
                
                if(hit == false)
                {
                    curSet[oldSlot]['imageId'] = 0;
                    curSet[oldSlot]['path'] = "";
                    curSet[oldSlot]['resX'] = 0;
                    curSet[oldSlot]['resY'] = 0;
                }
            }
        }else
        {
            curSet[oldSlot]['imageId'] = 0;
            curSet[oldSlot]['path'] = "";
            curSet[oldSlot]['resX'] = 0;
            curSet[oldSlot]['resY'] = 0;
        }
        curSet[slot]['imageId'] = draggable.getAttribute('imageId');
        curSet[slot]['path'] = draggable.getAttribute('path');
        curSet[slot]['resX'] = draggable.getAttribute('resX');
        curSet[slot]['resY'] = draggable.getAttribute('resY');
    }

    // as we attached this image to the other slot, we have to simply remove it from this set
    if(draggable.getAttribute('slot') && draggable.getAttribute('set') != set)
    {
        if(set == 1)
        {
            curSet2 = this._set2;
            set2 = 2;
        }else
        {
            curSet2 = this._set1;
            set2 = 1;
        }
        slt = draggable.getAttribute('slot');
        curSet2[slt]['imageId'] = curSet2[slt]['resX'] = curSet2[slt]['resY'] = 0;
        curSet2[slt]['path'] = "";
        
        if(set == 1) this._set2 = curSet2;
        else this._set1 = curSet2;
        
        this.rebuildSet(set2);
    }
    if(set == 1) this._set1 = curSet;
    else this._set2 = curSet;
    
    this.rebuildSet(set, true);
    this.selectImage(-1, -1);
}

_jury.prototype.onDrag = function()
{
    $('overlay').appendChild(this._juryDraggableContainer);
}

_jury.prototype.onDragEnd = function()
{
    $('jury_image_upload_preview').appendChild(this._juryDraggableContainer);
    this._juryDraggableContainer.style.left = Math.round((181 - this._draggableResX) / 2) + "px";
    this._juryDraggableContainer.style.top = Math.round((181 - this._draggableResY) / 2) + "px";
}

_jury.prototype.onDragExisting = function(draggable)
{
    $('overlay').appendChild(draggable.element);
}

_jury.prototype.onDragExistingEnd = function(draggable)
{
    $(draggable.element.getAttribute('parent')).appendChild(draggable.element);
    this.rebuildSet($(draggable.element).getAttribute('set'), false);
}

/* resync both sets */
_jury.prototype.resyncSets = function()
{
    var request = {
      action: 'sync',
      setColor: this._setColor,
      userId: this._userId,
      data: []
    };
    request.data[0] = Array();
    request.data[1] = Array();
    
    for(var i = 0; i < 10; i++)
    {
        request.data[0][i] = this._set1[i]['imageId'];
        request.data[1][i] = this._set2[i]['imageId'];
    }
    
    new Ajax.Request(ajax_url + "?action=sync", {
      method: 'post',
      parameters: 'json=' + Object.toJSON(request),
      onSuccess: function(transport){
      }
    });
}

_jury.prototype.selectImage = function(i, j)
{
    var oldObj = $('set_' + this._selectedSet + '_drop_' + this._selectedSlot + '_draggable');
    if(oldObj)
    {
        oldObj.style.border = "none";
        oldObj.style.marginLeft = "0px";
    }
    this._selectedSet = i;
    this._selectedSlot = j;
    
    var newObj = $('set_' + this._selectedSet + '_drop_' + this._selectedSlot + '_draggable');
    if(newObj)
    {
        if(newObj.getAttribute('imageId') != 0)
        {
            newObj.style.border = "2px solid #454545";
            newObj.style.marginLeft = "-2px";
        }
    }
}

_jury.prototype.deleteSelectedImage = function()
{
    if(this._selectedSet == 1 && this._set1Lock == 1) return;
    if(this._selectedSet == 2 && this._set2Lock == 1) return;
    var conf = confirm("Are you sure you want to delete this image?");
    if(!conf)
    {
        return;
    }
    
    var curSet;
    if(this._selectedSet == 1) curSet = this._set1;
    else if(this._selectedSet == 2) curSet = this._set2;
    else return;
    
    curSet[this._selectedSlot]['imageId'] = curSet[this._selectedSlot]['resX'] = curSet[this._selectedSlot]['resY'] = 0;
    curSet[this._selectedSlot]['path'] = "";
    
    if(this._selectedSet == 1) this._set1 = curSet;
    else if(this._selectedSet == 2) this._set2 = curSet;
    
    this.rebuildSet(this._selectedSet, true);
    
    this.selectImage(-1, -1);
}

_jury.prototype.copySelectedImage = function()
{
    var curSet;
    if(this._selectedSet == 1) curSet = this._set1;
    else if(this._selectedSet == 2) curSet = this._set2;
    else return;
    
    destSet = this._set2;
    var freeSlot = -1;
    for(var i = 0; i < 10; i++)
    {
        if(destSet[i]['imageId'] == 0)
        {
            freeSlot = i;
            break;
        }
    }
    if(freeSlot != -1)
    {
        destSet[i]['imageId'] = curSet[this._selectedSlot]['imageId'];
        destSet[i]['path'] = curSet[this._selectedSlot]['path'];
        destSet[i]['resX'] = curSet[this._selectedSlot]['resX'];
        destSet[i]['resY'] = curSet[this._selectedSlot]['resY'];
        
        this._set2 = destSet;
    
        this.rebuildSet(2, true);
    }
}
                
_jury.prototype.flipSelectedImage = function()
{
    var curSet;
    if(this._selectedSet == 1) curSet = this._set1;
    else if(this._selectedSet == 2) curSet = this._set2;
    else return;
    
    var imgId = curSet[this._selectedSlot]['imageId'];
    var request = {
      action: 'flip',
      imageId: imgId,
      userId: this._userId
    };
    
    new Ajax.Request(ajax_url + "?action=flip", {
      method: 'post',
      parameters: 'json=' + Object.toJSON(request),
      onSuccess: function(transport){
          var json = transport.responseText.evalJSON();
          jury.flipSelectedImageResponse(json.data);
      }
    });
}
                      
_jury.prototype.flipSelectedImageResponse = function(data)
{
    if(data.imageId == 0)
    {
        return;
    }
    
    destSet = this._set2;
    var freeSlot = -1;
    for(var i = 0; i < 10; i++)
    {
        if(destSet[i]['imageId'] == 0)
        {
            freeSlot = i;
            break;
        }
    }
    if(freeSlot != -1)
    {
        destSet[i]['imageId'] = data.imageId;
        destSet[i]['path'] = data.path;
        destSet[i]['resX'] = data.resX;
        destSet[i]['resY'] = data.resY;
        
        this._set2 = destSet;
    
        this.rebuildSet(2, true);
    }
}

_jury.prototype.enlargeSelectedImage = function()
{
    var curSet;
    if(this._selectedSet == 1) curSet = this._set1;
    else if(this._selectedSet == 2) curSet = this._set2;
    else return;
    
    var path = curSet[this._selectedSlot]['path'];
    
    var i = path.lastIndexOf('\/');
    if(i >= 0)
    {
        path = path.substr(0, i + 1) + "l_" + path.substr(i + 1);
    }
    
    var img = new Image();
    img.onload = function()
    {
        $('jury_large_view_img').style.background = "url('" + path + "')";
        $('jury_large_view_img').style.height = img.height + "px";
        $('jury_large_view_img').style.width = img.width + "px";
        $('jury_large_view_img').style.top = Math.round((710 - img.height) / 2) + "px";
        $('jury_large_view_img').style.left = Math.round((710 - img.width) / 2) + "px";
        $('jury_large_view').appear();
    }
    img.src = path;
}
    
_jury.prototype.deletePermanently = function()
{
    $('login_head').innerHTML = "Are you sure you want to delete this page?";
    $('form_submit').value = "Delete";
    $('form_submit').onclick = function(){jury.deletePermanentlySubmit();};
    $('jury_loginConfirm').show();
}

_jury.prototype.deletePermanentlySubmit = function()
{
    var email = $('login_email').value;
    var password = $('login_pass').value;
    document.location.href = "index.php?action=delete&email=" + email + "&password=" + password;
}
                 
_jury.prototype.updateLock = function(set)
{
    var confMessage = "";
    var nVal;
    if(set == 1)
    {
        if(this._set1LockR == 1)
        {
            confMessage = "Are you sure you want to unlock this set?";
            nVal = 0;
        }else
        {
            confMessage = "Are you sure you want to lock this set?";
            nVal = 1;
        }
    }else
    {
        if(this._set2LockR == 1)
        {
            confMessage = "Are you sure you want to unlock this set?";
            nVal = 0;
        }else
        {
            confMessage = "Are you sure you want to lock this set?";
            nVal = 1;
        }
    }
    $('login_head').innerHTML = confMessage;
    $('form_submit').value = "Update Lock";
    $('form_submit').onclick = function(){jury.updateLockSubmit();};
    $('jury_loginConfirm').show();
    
    this._updateLockSet = set;
    this._updateLockVal = nVal;
}

_jury.prototype.updateLockSubmit = function()
{
    var email = $('login_email').value;
    var password = $('login_pass').value;
    document.location.href = "index.php?action=lock&set=" + this._updateLockSet + "&nVal=" + this._updateLockVal + "&email=" + email + "&password=" + password;
}

function add_bookmark(url, title)
{
try{
    if(window.external)
    {
        window.external.AddFavorite(url, title);
    }
}catch(e){}
try{
    if (window.sidebar)
    {
        window.sidebar.addPanel(title, url,"");
    }
}catch(e){}
}