// replace this function with the implementation that loads the comments AJAX panel
//function InitiateAsyncRequest(arg){
    // alert('function InitiateAsyncRequest('+ arg +') {\r\n\tneeds to implemented by Tennis Channel to load comments for ' + arg + '\r\n}');
//}

// begin Microgroove state management

/**
 * Microgroove namespace to make variables available to external javascript functions
 */
var Microgroove = Microgroove || {};

/**
 * The GUID of the movie currently loaded into the flash movie player
 */
Microgroove.currentMovieGUID = '';

/**
 * the queue of item GUIDs in the whats new playlist, not including the first item 
 */
Microgroove.whatsNewQueue = [];

/**
 * Whether or not the flash embed has been added to the dom
 */
Microgroove.flashAdded = false;

/**
 * Whether or not the flash player is ready
 */
Microgroove.flashReady = false;

Microgroove.options = {
    flashVarsConfig: 'http://r.unicornmedia.com/embed/e3bbe92d-f857-429d-9a4c-bc1239fad8bb?view=item%26view_id=',
    flashPath: 'http://r.unicornmedia.com/content.aspx?uid=944323b8-db67-4623-b9bf-63069fd5dc37&at=6189f705-f508-4164-b3c3-b5b3d632baf8',
    flashDiv: 'flashplayer',
    flashWidth: '640',
    flashHeight: '360',
    flashVersion: '9.0.115',
    scrollSpeed: 0.07,
    autoPlay: true,
    flashObject: 'flashobject',
    guidQueryParam: 'guid'
};

Microgroove.embedFlash = function(defaultMovieGuid) {

    var script = document.createElement('script');

    script.type = 'text/javascript';

    var scriptContent = 'var flashvars = {\r' +
    '  config: "' + Microgroove.options.flashVarsConfig + defaultMovieGuid + '"\r';
    scriptContent += '};\r\r';

    scriptContent += 'var params = { \r' +
    '  quality: "high", \r' +
    '  allowNetworking: "all", \r' +
    '  allowFullScreen: "true", \r' +
    '  allowScriptAccess: "always", \r' +
    '  movie: "' + Microgroove.options.flashPath + '" \r' +
    '};\r\r';

    scriptContent += 'var attributes = {  \r' +
    '  id: "' + Microgroove.options.flashObject + '",\r' +
    '  name: "' + Microgroove.options.flashObject + '", \r' +
    '  allowNetworking: "all", \r' +
    '  allowFullScreen: "true", \r' +
    '  allowScriptAccess: "always" \r' +
    '};\r\r';

    scriptContent += ' swfobject.embedSWF("' + Microgroove.options.flashPath + '", "' + Microgroove.options.flashDiv + '", "' + Microgroove.options.flashWidth + '", "' + Microgroove.options.flashHeight + '", "' + Microgroove.options.flashVersion + '", "expressInstall.swf", flashvars, params, attributes);';

    // IE hack, use .text because script cannot have appendChild in IE
    script.text = scriptContent;

    jQuery(script).appendTo('#unicorn');
};

Microgroove.loadMovie = function(guid) {
    if (! guid)
        return;

    // if the selected move guid is already playing, just return, no state change
    if (guid === Microgroove.currentMovieGUID) {
        return;
    }

    // go to top of page
    window.scrollTo(0,0);

    // if the flash has not been added yet, add it now with the default/initial load movie GUID set
    if(! Microgroove.flashAdded) {
        if (Microgroove.options.autoPlay === false) {
            Microgroove.embedFlash("");
        } else {
            Microgroove.embedFlash(guid);
        }
        Microgroove.flashAdded = true;
        return;
    }

    // else we just call the Unicorn method to change the playing movie
    thisMovie(Microgroove.options.flashObject).UMIExt_JS_LoadMediaItemInQueueAndPlay(guid);
};


/**
 * Gets a query string parameter value from the current URL
 * @param name
 */
Microgroove.getQueryStringParameterByName = function(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );

    if( results == null )
        return "";

    return results[1];
};

Microgroove.isGUID = function (arg) {
    if (! arg)
        return;

    var guidRegex = /^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/;
    
    return guidRegex.test(arg);
};

// end Microgroove state management


// begin Unicorn Output helpers

// Called from Flex when Player is completely loaded and ready
function UMOExt_JS_PlayerReady() {
    jQuery(Microgroove.whatsNewQueue).each(function(i, guid) {
        thisMovie(Microgroove.options.flashObject).UMIExt_JS_LoadMediaItemInQueue(guid);
    });
}

// Called from Flex when Media Item Starts playing
function UMOExt_JS_MediaItemDescription(arg) {
    jQuery('#moviedescription').html(jQuery('<p></p>').html(arg));
}

// Called from Flex when Media Item Starts playing
function UMOExt_JS_MediaItemTitle (arg) {
    jQuery('#movietitle').html(jQuery('<h3></h3>').html(arg));
}

// Called from Flex when Media Item Starts playing
function UMOExt_JS_MediaItemGuid(guid) {
    if (guid === Microgroove.currentMovieGUID) {
        return;
    }

    // a new movie started playing, load info and comments panels
    // this is the Tennis Channel's AJAX commenting control call to load the comments for the movie identified by GUID
    // we call the comments before loading the info because it's an async call
    InitiateAsyncRequest(guid);

    Microgroove.currentMovieGUID = guid;
}

function thisMovie(movieName) {
    var winobj = undefined;
    var docobj = undefined;

    if (navigator.appName.indexOf("Microsoft") != -1) {
        winobj = window[movieName];
        if (winobj != undefined) {
            return winobj;
        } else {
            docobj = document[movieName];
            if (docobj != undefined)
                return docobj;
        }

    } else {
        docobj = document[movieName];
        if (docobj != undefined)
            return docobj;
    }

    docobj = document.getElementById(movieName);

    return docobj;
}

// end Unicorn Output helpers


/**
 * Microgroove+Unicornmedia jQuery Plugin 1.0
 *
 * 2010-01-18 17:30 PST
 *
 * @package microgroove.unicornmedia
 * @author Michael Hanney <mike@microgroove.com>
 * @copyright (c) 2009, Microgroove all rights reserved.
 *
 * Depends on jQuery 1.3.2, jQuery UI, jQuery Tabs
 *
 */
(function(jQuery) {

    jQuery.fn.unicornmedia = function(options) {


        var catalogs = [];

        var catalogMovies = {};
		
		

        var defaults = {
            whatsNewRssUrl: 'http://rfs.unicornmedia.com/custom/tennisch/new',
            channelRssUrl:  'http://rfs.unicornmedia.com/custom/tennisch/tabs',
            whatsnewdiv: '#whatsnew',
            movieInfoPrefix: 'Now playing: ',
            ajaxRequestTimeout: 30000, //milliseconds
            debug: true
        };

        options = jQuery.extend(defaults, options);

        // Iterate and make each matched element a unicornmedia object
        return this.each(function() {

            // Create a variable for the current unicornmedia container
            var $unicorn = jQuery(this);

            $unicorn.permalinkGuid = "";

            /**
             * executes once when window has finished loading
	         * This loads the XML/RSS feeds
             */
            jQuery(window).one("load", function() {

                var guid = "";

                // attempt to get a movie guid from the URL # value
                if (window.location.hash) {
                    // removes the leading #
                    guid = window.location.hash.substring(1);
                }

                // if no # value found, attempt to get guid parameter from query string
                if (! guid) {
                    guid =  Microgroove.getQueryStringParameterByName(Microgroove.options.guidQueryParam);
                }

                if (guid && Microgroove.isGUID(guid)) {
                    $unicorn.permalinkGuid = guid;
                }

                loadWhatsNewPlaylist(options.whatsNewRssUrl);
                loadChannel(options.channelRssUrl);
            });

            /**
             * logs debug messages to the firefox firebug console log if available
             * @param s
             */
            function log(s) {
                if (options.debug && window.console && window.console.log) {
                    window.console.log(s);
                }
            }

            /**
             * dumps the settings object to the logger
             */
            function debug() {
                jQuery.each(options, function(x, y) {
                    log(x + ":" + y);
                });

                jQuery.each(Microgroove, function(x, y) {
                    log(x + ":" + y);
                });
            }

            /**
             * Loads the RSS feed from the feedUrl going via the AjaxHttpAsyncHandler
             * on the same domain that is serving this javascript.
             *
             * @param feedUrl
             */
            function loadWhatsNewPlaylist(feedUrl) {
                // log(encodeURIComponent(feedUrl));
                jQuery.ajax({
                    url: '/AjaxHttpAsyncHandler.axd?url=' + encodeURIComponent(feedUrl),
                    //url: feedUrl,
                    type: 'GET',
                    dataType: 'xml',
                    timeout: options.ajaxRequestTimeout,

                    error: function(data, mssg) {
                        log(mssg);

                        // failed to get "what's new" feed, fall back on permalink, if set
                        if ($unicorn.permalinkGuid) {
                            Microgroove.loadMovie($unicorn.permalinkGuid);
                        }                    
                    },

                    success: function(xml) {
                        if (!xml)
                            return;

                        //var playlistname = jQuery(xml).find('playlistname').text();

                        var playlistname = "What's New";

                        jQuery('<div class="items" id="whatsnew-playlist"></div>').html('<h3>' + playlistname + '</h3><ul id="whatsnew-items" class="whatsnew">').appendTo(options.whatsnewdiv);

                        var firstGuid = "";

                        jQuery('item', xml).each(function() {
                            $item = jQuery(this);
                            var mediaItemGuid = $item.find('guid').text();
                            var mediaItemName = $item.find('title').text();
                            var mediaItemDescription = $item.find('description').text();
                            var mediaItemThumbnailURL = $item.find('thumbnail').attr('url');

                            if(! firstGuid) {
                                firstGuid = mediaItemGuid;

                                // if we already have a 'first' movie guid from the permalink URL, and this mediaItemGuid is not
                                // already in the queue, add it now
                                if($unicorn.permalinkGuid && jQuery.inArray(mediaItemGuid, Microgroove.whatsNewQueue) === -1) {
                                    Microgroove.whatsNewQueue.push(mediaItemGuid);
                                }
                                
                            } else {
                                // push into the temp queue, we will iterate over this array when UMOExt_JS_PlayerReady gets called
                                if (jQuery.inArray(mediaItemGuid, Microgroove.whatsNewQueue) === -1) {
                                    Microgroove.whatsNewQueue.push(mediaItemGuid);
                                }
                            }

                            jQuery('<li id="' + mediaItemGuid + '"></li>').html('<img src=' + mediaItemThumbnailURL + ' width="30px" height="20px" /></a><span class="title">' + mediaItemName + '</span>').appendTo('#whatsnew-items');
                        });

                        // if we detected a permalink in the URL, load the flash player now
                        if ($unicorn.permalinkGuid) {
                            Microgroove.loadMovie($unicorn.permalinkGuid);
                        } else {
                            // otherwise, load the first item in the whats new playlist, if there is one
                            Microgroove.loadMovie(firstGuid);
                        }

                        jQuery('</ul>').appendTo('#whatsnew-playlist');

                        // Bubble up the click event on any child of the unordered list elem.
                        // Locate the elem that was clicked.
                        // Get mediaItemGuid from LI outer node (target, or target parent).
                        // This is *much* faster than binding every IMG or SPAN, and *much,much* faster
                        // than using A HREF click events.
                        jQuery('#whatsnew-items').bind('click', function(e) {

                            // e.target grabs the node that triggered the event.
                            var target = e.target;
                            var $target = jQuery(target);
                            var guid = "";

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    guid = $target.parent().attr('id');
                                    break;

                                case('LI'):
                                    guid = $target.attr('id');
                                    break;
                            }

                            Microgroove.loadMovie(guid);
                            return false;
                        });

                        // bubble up mouseover events
                        jQuery('#whatsnew-items').bind('mouseover', function(e) {
                            var target = e.target;
                            var $target = jQuery(target);

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    $target.parent().addClass('hover');
                                    break;

                                case('LI'):
                                    $target.addClass('hover');
                                    break;
                            }
                        });

                        // bubble up mouseout events
                        jQuery('#whatsnew-items').bind('mouseout', function(e) {
                            var target = e.target;
                            var $target = jQuery(target);

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    $target.parent().removeClass('hover');
                                    break;

                                case('LI'):
                                    $target.removeClass('hover');
                                    break;
                            }
                        });
                    }
                })
            }

            function loadChannel(feedUrl) {
                //log(encodeURIComponent(feedUrl));
                jQuery.ajax({
                    url: '/AjaxHttpAsyncHandler.axd?url=' + encodeURIComponent(feedUrl),
                    //url: feedUrl,
                    type: 'GET',
                    dataType: 'xml',
                    timeout: options.ajaxRequestTimeout,
                    error: function(data, mssg) {
                        log(mssg);
                    },
                    success: function(xml) {
                        if (!xml)
                            return;

                        jQuery('item', xml).each(function() {
                            var $item = jQuery(this);
                            var catalog = $item.find('catalog').text();
                            var mediaItemGuid = $item.find('guid').text();
                            var mediaItemName = $item.find('title').text();
                            var mediaItemDescription = $item.find('description').text();
                            var mediaItemThumbnailURL = $item.find('thumbnail').text();

                            if (jQuery.inArray(catalog, catalogs) === -1) {
                                catalogs.push(catalog);
                            }

                            var movies = catalogMovies[catalog] || [];

                            movies.push({
                                title: mediaItemName,
                                guid: mediaItemGuid,
                                thumbnailURL: mediaItemThumbnailURL,
                                description: mediaItemDescription
                            });

                            catalogMovies[catalog] = movies;
                        });

                        var $tabitems = jQuery('#tab-items');

                        var $panelitems = jQuery('#panel-items');

                        for (var i = 0; i < catalogs.length; i++) {

                            // creates the tab heading
                            jQuery('<li id="tab_' + i + '" class="' +  (i==0 ? "first-tab" : "") + (i==catalogs.length-1 ? "last-tab" : "") + '"></li>').html(jQuery('<a href="#panel_' + i + '"></a>').html(jQuery('<span></span>').html(catalogs[i]))).appendTo($tabitems);

                            // creates the inner grid of thumbs
                            var $ul = jQuery('<ul id="grid_' + i + '" class="grid"></ul>');

                            for (var j = 0; j < catalogMovies[catalogs[i]].length; j++) {
                                var movie = catalogMovies[catalogs[i]][j];
                                jQuery('<li id="' + movie.guid + '"></li>').html('<img src="' + movie.thumbnailURL + '"><span>' + movie.title + '</span>').appendTo($ul);
                            }

                            // creates the switchable panels
                            jQuery('<div id="panel_' + i + '"></div>').html($ul).appendTo($panelitems);
                        }

                        // Bubble up the click event on any child of any child of the tab panels
                        // Locate the elem that was clicked.
                        // Get mediaItemGuid from LI outer node (target, or target parent).
                        // This is *much* faster than binding every IMG or SPAN, and *much,much* faster
                        // than using A HREF click events.
                        $panelitems.find("ul").bind('click', function(e) {

                            // e.target grabs the node that triggered the event.
                            var target = e.target;
                            var $target = jQuery(target);
                            var guid = "";

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    guid = $target.parent().attr('id');
                                    break;

                                case('LI'):
                                    guid = $target.attr('id');
                                    break;
                            }

                            Microgroove.loadMovie(guid);
                            return false;
                        });

                        // bubble up mouseover events
                        $panelitems.find("ul").bind('mouseover', function(e) {
                            var target = e.target;
                            var $target = jQuery(target);

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    $target.parent().addClass('hover');
                                    break;

                                case('LI'):
                                    $target.addClass('hover');
                                    break;
                            }
                        });

                        // bubble up mouseout events
                        $panelitems.find("ul").bind('mouseout', function(e) {
                            var target = e.target;
                            var $target = jQuery(target);

                            switch (target.nodeName) {
                                case('IMG'):
                                case('SPAN'):
                                    $target.parent().removeClass('hover');
                                    break;

                                case('LI'):
                                    $target.removeClass('hover');
                                    break;
                            }
                        });

                        jQuery("#tabs").tabs({
                            select: function(event, ui) {
                                // resets overlap effect by removing ui-tabs-under-next class from all tabs first
                                jQuery("#tab-items li").each(function(){
                                    jQuery(this).removeClass("ui-tabs-under-next");
                                });

                                if(ui.index === 0)
                                    return;

                                jQuery('#tab_' + (ui.index -1) ).addClass("ui-tabs-under-next");
                            }
                        });
                    }
                });
            }
        });
    };
})(jQuery);
