preload('/images/menu-gradient.png');
preload('/images/menu-gradient-ie6.png');
preload('/images/menu-topcurve.png');
preload('/images/menu-topcurve-ie6.png');
preload('/images/popup-tl.png');
preload('/images/popup-tr.png');
preload('/images/popup-br.png');
preload('/images/popup-bl.png');

function enableNav() {
    var navitems = $$('.nav > ul > li');

    var timeout;

    function leavemenu() {
        for (var n in navitems) {
            var item = navitems[n];
            item.removeClass('active');
        }
    }

    for (var n in navitems) {
        var item = navitems[n];
        
        if (! item.$('ul')) continue;
        item.event('mouseenter', function() {
            clearTimeout(timeout);
            leavemenu();
            this.addClass('active');
        });
    }
    
    $('.nav').event('mouseleave', function(e) {
        timeout = setTimeout(leavemenu, 1);
    });
}

function msg(string, type, override) {
    var inf = $('.info-message');
    if (override && inf) {
        inf.remove();
        inf = null;
    }
    if (!inf) {
        var spacer = $('#sakura-spacer');
        inf = spacer.postinsert('.info-message');
    }
    if (type) type = 'p.'+type;
    else type = 'p';
    var q = inf.append(type, string);
}

function messages(dict, override) {
    if (override) {
        var inf = $('.info-message');
        if (inf) inf.remove();
    }
    for (var k in dict) {
        for (var i in dict[k]) {
            msg(dict[k][i], k);
        }
    }
}


var MovingPhoto = false;
Element.addMethod('setPos', function() {
    var over = this.overlapping($$('#photosets .thumb'));
    if (MovingPhoto || !over.length) {
        this.style.top = '0';
        this.style.left = '0';
        return;
    }
    var after = over[0];
    var aftername = after.id.substr('photo-'.length);
    var thisname = this.id.substr('photo-'.length);
    var category = over[0].getAttribute('category');
    var elem = this;
    var onsuccess = function(data) {
            var photos = $$('#photosets .thumb');
            for (var i in photos) {
                photos[i].id = 'photo-' + data['photos'][i];
            }
            messages(data['messages']);
            MovingPhoto = false;
    };
    request('photo-add?format=json&photo=' + thisname, {success:onsuccess}, {'category': category, 'after': aftername});
    $(after).postinsert(elem);
    elem.style.top = '0';
    elem.style.left = '0';
    msg("Moving '" + thisname + "' after '" + aftername + "' in '" + category + "'...", null, true);
    MovingPhoto = true;
});


Element.addMethod('drag', function(e) {
   /* Note: for some reason, you need to make sure that an element with
    * a drag() event atached has at least one space/character inside it,
    * otherwise (if it's completely empty), we get a selection dragging
    * instead of the element dragging, at least in Fx.
    */
   e.stop();
   var elem = this;                         // make sure the closures work correctly
   var start = [e.clientX, e.clientY];
   var orig = [parseInt(elem.computedStyle().left), parseInt(elem.computedStyle().top)];
   var offset = [e.clientX-this.offsetLeft, e.clientY-this.offsetTop]
   var testover = $$('.name');              // Calculating this outside the move() function is _much_ quicker
   var move = function(event) {
       event.stop();
       var over = elem.overlapping(testover);
       elem.style.left = (orig[0] + (event.clientX - start[0])) + "px";
       elem.style.top = (orig[1] + (event.clientY - start[1])) + "px";
       return over;
   };
   var up = function() {
       document.unevent('mousemove', move);
       document.unevent('mouseup', up);
       elem.trigger('drop');
    };
   $(document).event('mousemove', move);
   document.event('mouseup', up);
});

Smarts['.thumb'] = function() {
    if (this.matches('a')) var a = this;
    else var a = this.$('a');
    if (!a) a = this;

    if (LoggedIn) {
        this.event('mousedown', this.drag);
        this.event('drop', this.setPos);
    } else {
        a.event('mousedown', popupImage);
    }
    a.imgsrc = a.href;
    a.href = '#_click';
}
function popupImage() {
    var body = $('body');
    var existing = $('#_popup');
    if (existing) existing.remove();
    var popup = body.append('#_popup.popup', 'click to close X');
    popup.append('.tl');
    popup.append('.tr');
    popup.append('.br');
    popup.append('.bl');
    popup.style.position = 'absolute';
    popup.style.zIndex = 10;
    popup.hide();               // hide it until the image is loaded etc
    var image = popup.prepend('img');
    image.onload = function() { // it's important to set the .onload before the .src, or it may not fire.
        popup.show();
        var view = viewport();
        popup.style.left = view.x + (view.width/2 - popup.offsetWidth/2) + 'px';
        popup.style.top = view.y + (view.height/2 - popup.offsetHeight/2) + 'px';
    };
    image.src = this.imgsrc;
    popup.event('click', function() {
        this.remove();
    });
}
