(function($){"use strict";


var templates = {
    flash: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{{width}}" height="{{height}}"><param name="wmode" value="{{wmode}}" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{{path}}?fs=1" /><embed src="{{path}}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{{width}}" height="{{height}}" wmode="{{wmode}}"></embed></object>',
    iframe: '<iframe src ="{{path}}" width="{{width}}" height="{{height}}" frameborder="no"></iframe>',
    image: '<img src="{{path}}" />'
};

var sourceRegex = {
    youtube: /youtube\.com\/watch\?v=([^&]+)/,
    vimeo: /vimeo\.com\/([^?&]+)/,
    image: /\.(jpg|gif|png)$/
};

function determineSource(url) {
    var source, id;

    for (source in sourceRegex) {
        var match = sourceRegex[source].exec(url);
        if (match) {
            id = match[1];
            break;
        }
    }

    if (id != undefined) {
        return {
            source: source,
            id: id
        };
    }
    
    return null;
}


window.shiftpress.media_player = function($player, options) {
    var defaults = {
        url: null,
        width: 640,
        height: 480,
        autoplay: false,
        finish: null
    };

    options = $.extend(defaults, options);

    if (!options.url) {
        return;
    }

    $player.empty();

    var source_data = determineSource(options.url);
    if (!source_data) {
        $player.append('<div class="sp-error">Cannot determine source</div>');
        return;
    }

    var player = null;
    switch (source_data.source) {
        case "youtube":
            movie = 'http://www.youtube.com/v/' + source_data.id + '&amp;fs=1&amp;autohide=1';

            if (options.autoplay) {
                movie += '&amp;autoplay=1';
            }

            player = templates.flash.replace(/{{path}}/g, movie);
            break;

        case "vimeo":
            var movie = 'http://player.vimeo.com/video/'+ source_data.id +'?title=0&amp;byline=0&amp;portrait=0';

            if (options.autoplay) {
                movie += '&amp;autoplay=1';
            }

            player = templates.iframe.replace(/{{path}}/g, movie);
            break;

        case "image":
            player = templates.image.replace(/{{path}}/g, options.url);
            break;
    }

    if (!player) {
        $player.append('<div class="sp-error">Cannot determine player</div>');
        return;
    }

    player = player.replace(/{{width}}/g, options.width).replace(/{{height}}/g, options.height);

    $player.append(player);
};

})(jQuery);

