/** @file
 *
 *  Media handler to present audio or video in a single media container element
 *      <div id='media'>
 *
 *  Will also present information about the related sermon in:
 *      <div id='sermon_info'>
 *
 *  IFF sermon data can be found in a hidden div:
 *      <div id='message_'+ sermonId>
 *
 */
(function ($) {

var addthis_url = 'http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a8a09b6105dk56c7';

var hubnub_html = '<object type="application/x-shockwave-flash" '
                +        'width="400" height="300" '
                +        'data="http://vimeo.com/hubnut/?'
                +                 'user_id=lifepointchurch&amp;'
                +                 'color=00adef&amp;'
                +                 'background=000000&amp;'
                +                 'fullscreen=1&amp;'
                +                 'slideshow=1&amp;'
                +                 'stream=channel&amp;'
                +                 'id=41603&amp;'
                +                 'server=vimeo.com">'
                +  '<param name="quality" value="best" />'
                +  '<param name="allowfullscreen" value="true" />'
                +  '<param name="wmode"           value="transparent" />'
                +  '<param name="scale" value="showAll" />'
                +  '<param name="movie" value="http://vimeo.com/hubnut/?'
                +                             'user_id=lifepointchurch&amp;'
                +                             'color=00adef&amp;'
                +                             'background=000000&amp;'
                +                             'fullscreen=1&amp;'
                +                             'slideshow=1&amp;'
                +                             'stream=channel&amp;'
                +                             'id=41603&amp;'
                +                             'server=vimeo.com" />'
                +   '<embed src="http://vimeo.com/hubnut/?'
                +                             'user_id=lifepointchurch&amp;'
                +                             'color=00adef&amp;'
                +                             'background=000000&amp;'
                +                             'fullscreen=1&amp;'
                +                             'slideshow=1&amp;'
                +                             'stream=channel&amp;'
                +                             'id=41603&amp;'
                +                             'server=vimeo.com" '
                +         'type="application/x-shockwave-flash" '
                +         'wmode="opaque" '
                +         'allowfullscreen="true" '
                +         'allowscriptaccess="always" '
                +         'width="400" '
                +         'height="300">'
                +  '</embed>'
                + '</object>';

// Use the Ekklesia360 Audio player
var audio_jukebox_url =
                  'http://my.ekklesia360.com/Clients/sermonaudioplayer.php'
                +       '?CMSCODE=EKK'
                +       '&siteid=1500'
                +       '&sermonid=%sermonid%'
                +       '&useSkin=skin_plain.xml'
                +       '&CMS_LINK=http://my.ekklesia360.com'
                +       '&width=350'
                +       '&height=140';

// Ekklesia360 Video Player
var video_player_html =
                  '<p>Play video @%url%, autoplay=?</p>';


/** @brief  Included in the data returned for a sermon/sermon list
 *          (via __videopopup__ in ekk_sermonpage.php, sermlnlist_query.php)
 *
 *  sermonFix for video player
 *
function waspPopup(filename, width, height)
{
    window.open('http://my.ekklesia360.com/Clients/waspPopup.php?theFile='+
                                        filename+'&w='+width+'&h='+height,
                '_mediaplayer',
                'width='+width+',height='+height);

}
 */


/** @brief  Format a date.
 *  @param  date    The date string (or date object).
 *
 *  @return A string of the form 'YYYY.mm.dd'
 */
function formatDate(date)
{
    var dateStr = '';
    if (Date.format)
    {
        // EXT changes the Date object completely...
        if (! (date instanceof Date))
        {
            date = new Date(date);
        }

        dateStr = date.format('Y.m.d');
    }
    else
    {
        if (! (date instanceof Date))
        {
            var nDate   = new Date();
            nDate.setTime(Date.parse(date));
            date = nDate;
        }

        var month   = date.getMonth() + 1;
        var day     = date.getDate();
        var dateStr = date.getFullYear()               + '.'
                    + (month < 10 ? '0'+month : month) + '.'
                    + (day   < 10 ? '0'+day   : day);
    }

    return dateStr;
}

/** @brief  Retrieve sermon information given a sermon id.
 *  @param  sermonId    The sermon identifier.
 *
 *  sermonInfo is a DOM element containing divs of class:
 *      title
 *      slug
 *      url
 *      summary
 *      preview
 *      passage
 *      series
 *      date
 *      notes
 *      preacher
 *      preacherImgThumb
 *
 *  @return A sermon information object (null if not found).
 */
function get_sermonInfo(sermonId)
{
    var $sermonInfo_src = $('#message_'+ sermonId);

    if ($sermonInfo_src.length < 1)
        return null;

    if (false)
    {
    // Convert the sermon information to a javascript object
    var json    = $sermonInfo_src.html()
                                 .replace(/^\s*<\!-- <\!\[CDATA\[\s*/, '')
                                 .replace(/\]\]> -->/, '');
    var sermon  = JSON.parse(json);

    sermon.date = sermon.dateTwo;
    }
    else
    {
    // Sermon data
    var sermon  = {
        'title':    $sermonInfo_src.find('div.title').html(),
        'slug':     $sermonInfo_src.find('div.slug').text(),
        'url':      $sermonInfo_src.find('div.url').html(),
        'preview':  $sermonInfo_src.find('div.preview').html(),
        'date':     $sermonInfo_src.find('div.date').text()
    };
    }

    return sermon;
}


/** @brief  Present descriptive information about the sermon being presented.
 *  @param  sermonId    The sermon identifier.
 *  @param  mediaEl     The jQuery/DOM element that is the actual media player.
 */
function show_sermonInfo(sermonId, $mediaEl)
{
    var $sermonInfo_dst = $('#sermon_info');
    var id_dst          = $sermonInfo_dst.find('div.id');

    if (id_dst.text() == sermonId)
    {
        // No change!
        return;
    }

    if ($sermonInfo_dst.length < 1)
        return;

    // Retrieve sermon information
    var sermon  = get_sermonInfo(sermonId);

    if (sermon === null)
        return;

    // Destination...
    var title_dst       = $sermonInfo_dst.find('div.title');
    var date_dst        = $sermonInfo_dst.find('div.date');
    var text_dst        = $sermonInfo_dst.find('div.text');

    /* Remember which sermon we're presenting by setting the text of the hidden
     * div.id
     */
    id_dst.text(   sermonId );  // id_dst.text(   sermon.id );

    title_dst.html('<a href="'+ sermon.url +'">'+ sermon.title +'</a>');
    date_dst.text( sermon.date);
    text_dst.html( '<div class="summary">'+ sermon.preview +'</div>');


    /***********************************************************************
     * addthis
     *
     */
    $.media.addthis.show(sermonId);


    /***********************************************************************
     * If scrollTo is available, scroll up to the player.
     *
     */
    if ($.fn.scrollTo)
    {
        /* Instead of just scrolling to the top of the player, scroll to the
         * top of the body -- it just looks nicer...
         *  $(window).scrollTo($playerEl, 800, {offset:{top:-100}} );
         */
        $(window).scrollTo($('body'), 800);
    }
}


$.media = {
    vimeo:      {},
    audio:      {},
    video:      {},
    addthis:    {}
};

/** @brief  (Re)write the vimeo player object to present the identified video
 *          from Vimeo
 *  @param  sermonId    The Sermon ID.
 *  @param  videoId     The Vimeo ID of the desired video.
 *  @param  autoPlay    Should auto play be enabled? [ true ]
 *
 *  This will update the DOM element '#media' if it exists.
 */
$.media.vimeo.show = function(sermonId, videoId, autoPlay)
{
    var $playerEl   = $('#media');
    if ($playerEl.length < 1)
        return;

    if (autoPlay === undefined)
        autoPlay = true;

    /* IE 8 in compatability mode (thus <= IE7) cannot hide/remove at least
     * the $vimeo object, although it is able to hide the $hubnumb object...
     *
     * I have no idea why, so let's just punt and completely empty the player
     * area...
     */
    $playerEl.empty();


    // Include the Vimeo Moogaloop video player
    var  so     = new SWFObject('http://vimeo.com/moogaloop.swf',
                                'vimeoPlayer',
                                '400', '300',  // width, height
                                '8',           // Flash version
                                '#000000',     // background-color
                                true);
    so.useExpressInstall('expressinstall.swf');

    so.addParam('allowfullscreen',   'true');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('wmode',             'transparent');

    so.addVariable('clip_id',        videoId);
    so.addVariable('server',         'vimeo.com');
    so.addVariable('autoplay',       (autoPlay ? 1 : 0));
    so.addVariable('show_title',     1);
    so.addVariable('show_byline',    1);
    so.addVariable('show_portrait',  1);
    so.addVariable('bgcolor',        '000000');
    so.addVariable('color',          '00adef');
    so.addVariable('js_api',         1);
    so.addVariable('fullscreen',     1);

    so.write('media');

    var $vimeo  = $playerEl.find('#vimeoPlayer');


    /* Present information about this sermon and, if possible, scroll the
     * player into view.
     */
    show_sermonInfo(sermonId, $vimeo);
};

/** @brief  (Re)write the media area to present the identified audio clip.
 *  @param  sermonId    The Sermon ID.
 *  @param  audioUrl    The URL of the audio to present.
 *  @param  showJukebox Should we show the jukebox or single player [false]?
 *
 *  This will update the DOM element '#media' if it exists.
 */
$.media.audio.show = function(sermonId, audioUrl, showJukebox)
{
    var $playerEl   = $('#media');
    if ($playerEl.length < 1)
        return;

    /* IE 8 in compatability mode (thus <= IE7) cannot hide/remove at least
     * the $vimeo object, although it is able to hide the $hubnumb object...
     *
     * I have no idea why, so let's just punt and completely empty the player
     * area...
     */
    $playerEl.empty();

    var $audio  = null
    
    if (showJukebox)
    {
        // Use the Ekklesia360 Audio Jukebox
        var html = '<iframe src="'
                 +     audio_jukebox_url.replace(/%sermonid%/g, sermonId) +'">'
                 +  'Your browser does not support iframes.'
                 + '</iframe>';

        $audio   = $(html).hide()
                          .attr('id',          'audioPlayer')
                          .css('width',        '350px')
                          .css('height',       '140px')
                          .css('margin',       '25px');

        // Append the audio player
        $playerEl.append($audio);

        try
        {
            $audio.show();
        } catch(e) { }
    }
    else
    {
        // Use the Gooble Reader Audio player
        var  so     = new SWFObject('/includes/audio-player.swf',
                                    'audioPlayer',
                                    '350', '27',   // width, height
                                    '8',           // Flash version
                                    '#000000',     // background-color
                                    true);
        so.useExpressInstall('expressinstall.swf');

        so.addParam('allowfullscreen',   'true');
        so.addParam('allowscriptaccess', 'never');
        so.addParam('wmode',             'transparent');

        so.addVariable('audioUrl',       audioUrl);
        so.addVariable('autoplay',       1);
        so.addVariable('bgcolor',        '000000');
        so.addVariable('color',          '00adef');

        so.write('media');

        $audio = $playerEl.find('#audioPlayer')
                          .css('width',        '350px')
                          .css('height',       '27px')
                          .css('margin-top',   '125px')
                          .css('margin-left',  '25px')
                          .css('margin-right', '25px');
    }

    /* Present information about this sermon and, if possible, scroll the
     * player into view.
     */
    show_sermonInfo(sermonId, $audio);
};

/** @brief  Generate the HTML representing the local flash player object.
 *  @param  url         The URL of the flash video.
 *  @param  autoPlay    Should auto play be enabled? [ true ]
 *
 *  @return The HTML representing the local flash player object.
 */
$.media.video.html = function(url, autoPlay)
{
    return video_player_html.replace(/%url%/g, url)
                            .replace(/autoplay=./g,
                                     'autoplay='+ (autoPlay === false
                                                    ? '0'
                                                    : '1'));
}

/** @brief  (Re)write the local flash player object to present the identified video.
 *  @param  sermonId    The Sermon ID.
 *  @param  url         The URL of the flash video.
 *  @param  autoPlay    Should auto play be enabled? [ true ]
 *
 *  This will update the DOM element '#media' if it exists.
 */
$.media.video.show = function(sermonId, url, autoPlay)
{
    var $playerEl   = $('#media');
    if ($playerEl.length < 1)
        return;

    if (autoPlay === undefined)
        autoPlay = true;

    /* IE 8 in compatability mode (thus <= IE7) cannot hide/remove at least
     * the $video object, although it is able to hide the $hubnumb object...
     *
     * I have no idea why, so let's just punt and completely empty the player
     * area...
     */
    $playerEl.empty();

    // Use the Ekklesia360 Video player (wasp)
    var  so     = new SWFObject('http://my.ekklesia360.com/Library/Wimpy/wasp.swf',
                                'videoPlayer',
                                //'400', '300',  // width, height
                                '390', '290',  // width, height
                                '8',           // Flash version
                                '#000000',     // background-color
                                true);
    so.useExpressInstall('expressinstall.swf');

    so.addParam('allowfullscreen',   'true');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('wmode',             'transparent');

    so.addVariable('f',              url);
    so.addVariable('r',              'MzAlMkZkc0UlMkZvbyU3RVJXJTJGJTJDaWUlM0QwcHRDY2glNUJham83SGM0OE1p');
    so.addVariable('a',              1);
    so.addVariable('bgcolor',        '000000');
    so.addVariable('color',          '00adef');

    so.write('media');

    var $video = $playerEl.find('#videoPlayer')
                          .css('margin', '5px');


    /* Present information about this sermon and, if possible, scroll the
     * player into view.
     */
    show_sermonInfo(sermonId, $video);
};


/** @brief  Update and show the addthis item with the url and title of the
 *          sermon with theh given identifier.
 *  @param  sermonId    The sermon identifier.
 */
$.media.addthis.show = function(sermonId)
{
    var $sermonInfo_dst = $('#sermon_info');

    if ($sermonInfo_dst.length < 1)
        return;

    // Retrieve sermon information
    var sermon  = get_sermonInfo(sermonId);

    if (sermon === null)
        return;


    var share_dst       = $sermonInfo_dst.find('div.share');
    var url             = document.location.href;
    var baseUrl         = url.substr(0, url.indexOf('/',10));
    var $tools          = share_dst.find('.tools');

    url = baseUrl + sermon.url;

    var config  = {url:     url,
                   title:   sermon.title
                  };

    $tools.hide();  //'normal');

    /* :NOTE: All the meta-data needed by 'addthis' is included via
     *        new_header2.php (IFF $sermon is an Array) via
     *        Sermon_Header:generate_metadata()
     */
    $tools.html(  '<a id="addthis" class="addthis_button">'
                +   '<img src="/images/sm-share-en.gif" '
                +        'alt="Bookmark and Share" />'
                + '</a>');
    addthis.button('#addthis', {ui_click:       true,
                                ui_use_flash:   false},
                               config);

    $tools.show('normal');
}


})(jQuery);
