function Frame(source)
{
    this.source = source;
    this.media = source.find('a').not('.control');
    this.pause = false;
    
    this.tools = $('<div class="tools"/>').appendTo(source);
    
    this.edit_photo = $('<a class="edit-photo"/>')
        .appendTo(this.tools)
        .attr('target', '_blank');
    
    var frame_pk = source.attr('pk');
    if (frame_pk !== undefined)
    {
        this.edit_frame = $('<a class="edit-frame"/>')
            .appendTo(this.tools)
            .attr('href', '/admin/mediate/frame/' + frame_pk + '/')
            .attr('target', '_blank');
    }
    
    if (this.source.attr('caption'))
    {
        this.caption = $('<div class="caption">').appendTo(source);
    }
    else
    {
        this.caption = $('<div>');
    }
    
    this.media.hide().removeClass('active');
    this.activate(this.getIndex(0));
    
    if (this.source.hasClass('rotate')) {
        this.rotateTimeout = setTimeout($.proxy(this.rotate, this), 2000 + Math.random() * 8000);
    }
    
    if (PAGE != 'gallery') {
        source.css('opacity', 0);
        setTimeout(function()
        {
            source.animate({'opacity': 1}, 1000);
        }, Math.random() * 2000);
    }
}

Frame.prototype.getIndex = function(index)
{
    if (index < 0) index = this.media.length - 1;
    if (index >= this.media.length) index = 0;
    
    this.index = index;
    return this.media.eq(index);
}

Frame.prototype.activate = function(item)
{
    if (item == null || item == undefined) return;
    
    this.active = item;
    
    if (!this.active.hasClass('active')) {
        this.media.filter('.active').removeClass('active').fadeOut("slow");
        this.active.addClass('active').fadeIn('slow');
    } else {
        this.media.filter('.active').not(this.active).removeClass('active').hide();
        this.active.addClass('active').show();
    }
    
    if (this.source.hasClass('slide')) {
        setTimeout($.proxy(this.crossSlide, this), 10);
    }
    
    if (this.active.hasClass('movie'))
    {
        var active = this.active;
        if (active[0].play) return;
        
        var play = $('<div class="play-overlay">').hide().appendTo(active);
        active[0].play = play;
        
        var self = this;
        active.click(function()
        {
            self.caption.hide();
            play.hide();
            self.pause = true;
        })
        
        setTimeout(function()
        {
            play.css({
                top: active.height() / 2 - 36,
                left: active.width() / 2 - 36
            }).fadeIn();
        }, 800);
        
        /*this.active.click(function()
        {
            console.log("Opening movie...");
            try {
                self.openMovie($(this).attr('href'));
            } catch(e) {
                console.error(e);
            }
            return false;
            
        });*/
    }
    
    var pk = this.active.attr('pk');
    if (this.active.attr('editable'))
        this.edit_photo.attr('href', '/admin/mediate/media/' + this.active.attr('pk') + '/');
    else
        this.edit_photo.hide();
        
    var caption = this.active.find('img').attr('title');
    if (caption && caption.length)
        this.caption.html( caption ).show();
    else
        this.caption.html( '' ).hide();
}

Frame.prototype.rotate = function()
{
    if (this.pause) return;
    
    var index = this.index ;
    var next = null;
    for(var i = 0; i < this.media.length; i++)
    {
        index = index + 1;
        next = this.getIndex(index);
        if (this.isUnique(next))
            break;
    }
    this.activate(next);
    setTimeout($.proxy(this.rotate, this), 10000 + Math.random() * 6000);
}

Frame.prototype.isUnique = function(self)
{
    var active = $('a.active');
    for(var i = 0; i < active.length; i++)
    {
        if (self[0] == active[i]) continue;
        if (self.attr('pk') == active.eq(i).attr('pk'))
            return false;
    }
    
    return true;
}

Frame.prototype.crossSlide = function(focus)
{
    var focus = this.active.attr('focusId');
    var start, stop;
    var img = this.active.find('img');
    var width = img.width();
    var height = img.height();
    var f_width = this.active.width();
    var f_height = this.active.height();
    
    var d_width = f_width - width;
    var d_height = f_height - height;
    
    if (focus == 0) {
        var start = FOCUSES[Math.floor(Math.random()*9)].start;
    } else {
        var start = FOCUSES[focus].start;
    }
    var stop = FOCUSES[focus].stop;
    
    img.css({
        'left': start[0] * d_width,
        'top': start[1] * d_height
    })
    
    img.animate({
        'left': stop[0] * (d_width / 2),
        'top': stop[1] * (d_height / 2)
    }, 3000);
}

MoviePlayer = function(uri, size)
{
    this.size = size;
    this.uri = uri;
    
    this.screen = $('<div id="screen">').appendTo(document.body);
    this.frame = $('<div class="frame"/>').appendTo(this.screen);
    this.movie = $('<div id="movie_box"/>').appendTo(this.frame);
    
    flowplayer("movie_box", "/media/js/flowplayer-3.2.0.swf", uri);
    
    var self = this;
    self.resize();
    $(window).resize(function() {
        self.resize()
    });
}

Frame.prototype.openMovie = function(uri)
{
    new MoviePlayer(uri, this.active.attr('size').split('x'));
}

MoviePlayer.prototype.resize = function()
{
    var lim_w = this.screen.width() - 160;
    var lim_h = this.screen.height() - 100;
    
    var w = parseInt(this.size[0]);
    var h = parseInt(this.size[1]);
    var d = 1;
    
    if (w > lim_w) {
        d = lim_w / w;
        w *= d;
        h *= d;
    }
    if (h > lim_h) {
        d = lim_h / h;
        w *= d;
        h *= d;
    }
    
    this.movie.width(w);
    this.movie.height(h);
    
    var top = this.screen.height() - h;
    this.frame.css('margin-top', top / 2);
    
    var left = this.screen.width() - w;
    this.frame.css('margin-left', left / 2);
}

$(function()
{   
    $('div.media').each(function() {
        new Frame($(this));
    });
})

FOCUSES = {
    '0': {start: [0, 0],  stop: [.5, .5]},
    '1': {start: [.5, 1], stop: [.5, 0]},
    '2': {start: [0,  1], stop: [1,  0]},
    '3': {start: [0, .5], stop: [1, .5]},
    '4': {start: [0,  0], stop: [1,  1]},
    '5': {start: [.5, 0], stop: [.5, 1]},
    '6': {start: [1,  0], stop: [0,  1]},
    '7': {start: [1, .5], stop: [0, .5]},
    '8': {start: [1,  1], stop: [0,  0]}
}
