var MediaPlayer = Class.create();
MediaPlayer.prototype = 
{
	initialize : function(element, o)
    {
        element = $(element);
        this.currentTimeout = null;

        this.options = Object.extend({ 
          element:     element,
          viewURL:     null
        }, arguments[1] || {});

        try
        {
            element.addModelListener('STATE', 'playerStateChange');
        } catch (e) {}
    },
    stateChange: function(newstate, oldstate)
    {
        if (this.currentTimeout)
        {
            clearTimeout(this.currentTimeout);
            this.currentTimeout = null;
        }
        if (newstate == 'PLAYING')
            this.currentTimeout = setTimeout(this.registerView.bind(this), 3000);

    },
    registerView: function()
    {
        if (this.options.viewURL)
            new Ajax.Request(this.options.viewURL, {
                method: 'post',
                parameters: {},
                onSuccess: function(transport) {
                    // alert('response: ' + transport.responseText);
                }
            });
    }
}

function playerStateChange(e)
{
    MediaPlayerObject = MediaPlayers.get(e.id);
    MediaPlayerObject.stateChange(e.newstate, e.oldstate)
}


MediaPlayers = {
    players: [],
    listeners: [],
    addListener: function(id, listenerCallback)
    {
        if (!this.listeners[id])
            this.listeners[id] = [];

        this.listeners[id].push(listenerCallback);
    },
    registerLoad: function(obj)
    {
        id = obj['id'];

        if (!id)
        {
            throw new Error('The element must have an id value');
        }

        // Add the slideshow with the id to the current list of slideshows
        this.players[id] = new MediaPlayer(id);

        if (!this.listeners[id])
            this.listeners[id] = [];

        listeners = this.listeners[id];

        if (listeners.length > 0)
            listeners.each(function(l) {
                l(obj);
            }.bind(this));
    },
    get: function(element)
    {
        return this.players[$(element).id];
    }
}

function playerReady(obj) 
{
    try
    {
        MediaPlayers.registerLoad(obj);
    }
    catch (e)
    {
        // alert('playerReady - ' + Object.inspect($H(e)));
    }
};
