/**
  Austereo Now Playing Functionality
    CHANGELOG:
      20090327 - Born from fd.austereo.mediaplayer.js.
      20090605 - Disabling media player tab link (tab name) - so that clicking on tabs will not trigger an update on the parent window.
      20090702 - Adding logic to refresh the up coming show on the player.
      20090708 - Updating refresh action paths to include the uriPrefix.
      20090720 - Updating logic for links on the player page.
      20090722 - Updating logic for buy now links on the player page for IE.
      20090810 - Updating refresh time delay for refreshing promos, show information and ads.
      20091102 - Updating refresh time for Nielsen session tracking.
      20091116 - Removing wmp detection and play and stop functions.
      20091119 - Updating with logic to initialise the flash player after the preroll ends.
      20100114 - Updating refresh time for Nielsen session tracking.
      20100128 - Fixed pre-roll ad pause when clicked.
 **/

if(window['FD']) {
    /* Now Playing Media Player
     ------------------------------------------------------------------------------------------- */
    FD.MediaPlayer = function(fdOptions) {
        /**
         * Default options for a <code>FD.ChallengeSecurity</code>.
         *
         * @private
         */
        var defaultOptions = {
            promoRefreshDelay: eval(1000*60*15), // 15 mins
        onAirNowRefreshDelay: eval(1000*60*15), // 15 mins
        onAirNextRefreshDelay: eval(1000*60*15), // 15 mins
        advertRefreshDelay: eval(1000*60*15), // 15 mins
        refreshSessionDelay: eval(1000*60*10), // 20 mins
        contentPromosPath: "/action/displayNowPlayingPromos",
        contentTabsPath: "/action/displayNowPlayingTabs",
        contentOnAirNowPath: "/action/displayNowPlayingOnAirNow",
        contentOnAirNextPath: "/action/displayNowPlayingOnAirNext",
        sessionRefreshCount: 0
        };
        /**
         * The final, merged version of the toggle text definition.
         * <p/>
         * This toggle text definition is the result of extending the <code>defaultOptions</code> object with our custom
         * parameters passed in via <code>fdOptions</code>.
         *
         * @private
         */
        var options = $.extend(true, defaultOptions, fdOptions);

        var refreshIntervalId = 0;

        /**
         *
         * @constructor
         * @private
         */
        (function() {
            _initPreroll();
            _initMediaPlayer();
            _initTabs();
            _initLinks();
            _initStream();
        })();

      /* Bind functions to the preroll events */
      function _initPreroll() {
        $('body').bind("prerollComplete", hidePreroll);
        $('body').bind("prerollHidden", handlePrerollHidden);
      }

      /* Starts the ajax coundown timer and bind to some events */
      function _initMediaPlayer() {
        /* NBF - 20081014 - Commented - disabled ajax polling.*/
        setInterval(refreshPromos, options.promoRefreshDelay);
          setInterval(refreshOnAirNow, options.onAirNowRefreshDelay);
          setInterval(refreshOnAirNext, options.onAirNextRefreshDelay);
          setInterval(refreshAds, options.advertRefreshDelay);
          $('body').bind("tabSwapped", handleTabSwapped);
      }


      /* TABS FUNCTIONS */
      function _initTabs() {
        // find all <ul> which have class 'cN-tabBox':
        var tabid = 'ul.cN-tabBox';
        var tabs = $(tabid);

        if(tabs.length) {
          // For all <ul> found, add 'click' event (which extends to its child elements too):
            /**tabs.each(function(idx, ttab){
                var tab = $(ttab);
                tab.bind("click", _swapTab);
                // Remove class which makes tab box accessible if JS is disabled:
                tab.removeClass("accessibleTab");
            });**/
            /**
             * $('#menu').delegate('div', 'click', function() {
                //code of your handler - 'this' refers to clicked element
             });

             */
            tabs.delegate('a', "click", {tabid: tabid}, _swapTab);
            tabs.delegate('li', "click", {tabid: tabid}, _swapTab);
            tabs.removeClass("accessibleTab");

        }
      }

      function _swapTab(event) {
          var tabid = 'ul.cN-tabBox';
            if (event.data && event.data.tabid) {
                tabid = event.data.tabid
            }
          var tabs = $(tabid);

          var tab = $(this);
          var a = event.target;
          var ja = $(a);

          if (a.tagName == "a") {
            if (a.href.match(/#$/)) { // String ends with '#' => abort event
                FD.stopEvent(event);    
            }
          }

          // If user clicked on <li>, but not on <a>, get first child of <li> (= <a>):
          if(a.tagName == "li") {
              var as = ja.find("a");
              ja = as.first();  // Gets first child
              a = ja.get(0);
          }
          if ((ja.length == 0) || ja.parent().get(0).tagName != 'H2' ) return;

          // Now we're sure user clicked on a tab => stop following the link:
          //new Event(e).stop();
          // Get all direct children of the element which was clicked on (i.e. the <li>)
          // and remove any 'selected' class:
          tabs.children().removeClass("selected");
          // Add the class to the <li> clicked on (which is the 2nd level parent element).
          // CSS takes care of the rest:
          ja.parent().parent().addClass("selected");
          //determine which is the newly selected tab

          var newTabIndex = 0;
          var lis = $(this).find('li');
          lis.each(function(idx, tli) {
              if (tli == ja.parent().parent()) {
                  newTabIndex = idx;
                  return;
              }
          });

          /* Check if the clicked tab was not the active one */
          if (selectedTabIndex != newTabIndex) {
            //record the change and update the adds
            prevSelectedTabIndex = selectedTabIndex;
            selectedTabIndex = newTabIndex;
            $.event.trigger('tabSwapped');
          }

      }

      /* bind to the click event of all links in the page (excluding for the plugin required section). */
      function _initLinks() {
        initLinks($("#promosWrapper"));
        initLinks($("#nowPlayingWrap"));
      }

      /* Starts the streaming if there is no preroll */
      function _initStream() {
        var preroll = $("#mediaPlayerPreroll");
        if (preroll.length == 0) {
          initMediaFlashPlayer();
        }
      }

      /* Binds to the click event of all anchor tags that are decendants of the element provided.  if window.opener
         is undefined, invoking this function has no effect */
      function initLinks(element) {
          if (element.length) {
                if (window.opener) {
                    var anchors = element.find("a");
                    anchors.each(function(idx,tanchor) {
                        var a = $(tanchor);
                        var tabberNavParents = a.parent(".tabbernav");
                        if (tabberNavParents.length == 0) { /* i.e. 'a' is not a nav link */
                            if (tanchor.id.substr(0,7) == ("tabName")) {
                                tanchor.href = "javascript:void(null);";
                            } else {
                                a.bind("click", openLink);
                            }
                        }
                    });
                }
            }

      }

      /* Hide the preroll to reveal player */
      function hidePreroll() {
        var ele = $("#mediaPlayerPreroll");
        if(ele.length) {
          ele.fadeTo(1500, 0, firePrerollHiddenEvent);
        }
        initMediaFlashPlayer();
      }

      /* Fires an event to notify that the preroll has been hidden */
      function firePrerollHiddenEvent() {
        //$('body').trigger("prerollHidden");
          $.event.trigger('prerollHidden');
      }

      /* Invoked after the preroll has been hidden to start the media player and gc the preroll content */
      function handlePrerollHidden() {
        var ele = $("#mediaPlayerPreroll");
        if(ele.length) {
          ele.remove();
        }
      }

      /* Invoked when a tab is swapped. */
      function handleTabSwapped() {
        // swap the 300x60 ad
        FD.refreshAd("adSpot-300x60");
        // swap the island ad
        FD.refreshAd("adSpot-island");
      }

      function refreshSession() {
        if (options.sessionRefreshCount < 3) {
            FD.doNielsonImpression(location.href);
            options.sessionRefreshCount++;
        }
      }

      /* Refreshes the content in the media player */
      function refreshContent() {
        refreshTabs();
      }

      /* Makes a request to retrieve the new content for the now playing media player tabs */
      function refreshTabs() {
        var params = "?selectedTabIndex=" + selectedTabIndex + "&reqTime=" + new Date().getTime();
        var url = options.contentTabsPath
            var subBrand = getSubBrand();
            if (subBrand) {
                params = params + "&subBrand=" + subBrand;
                url = subBrand + url;
            }

            $.ajax({
                type: "GET",
                dataType: "text",
                data: params,
                statusCode: {200:handleRefreshTabsResponse},
                //success: handleRefreshTabsResponse,
                timeout: 1500,
                url: url
            });

      }

      /* Refreshes the tabs content with the response from the server.
         Note: Element.getElementById cannot be used to retrieve elements from the response as the elements we're
         looking for aren't actually in the document. */
      function handleRefreshTabsResponse(response) {
        if (response) {

             var responseParent = $('<div/>', {
                    html: response
                });


          //loop through and set any cN-tabBoxes in the ul
          var ulsInResponse = responseParent.find("ul");
            ulsInResponse.each(function(idx, tul){
               var ul = $(tul);
                var ulId = ul.attr("id");
                if (ulId) {
                    var tabSetId = idx+1;
                    var currentTabSet = $("#cN-tabBox"+tabSetId);
                    if (currentTabSet.length) {
                        currentTabSet.html(ul.html());
                        // rebind to all links in response
                        initLinks(currentTabSet);
                    }
                }
            });
        }
      }

      /* Makes a request to retrieve the new content for the media player promos */
      function refreshPromos() {
        var params = "reqTime=" + new Date().getTime();
          var url = options.contentPromosPath
            var subBrand = getSubBrand();
            if (subBrand) {
                params = params + "&subBrand=" + subBrand;
                url = subBrand + url;
            }

            $.ajax({
                type: "GET",
                dataType: "text",
                data: params,
                statusCode: {200:handleRefreshPromosResponse},
                //success: handleRefreshPromosResponse,
                timeout: 1500,
                url: url
            });

      }

      /* Refreshes the promos content with the response from the server. */
      function handleRefreshPromosResponse(response) {
        var wrapperElem = $("#promosWrapper");
        if (wrapperElem.length && response) {
          wrapperElem.html(response);
          initLinks(wrapperElem);
        }
      }

      /* Makes a request to retrieve the new content for the on air now show. */
      function refreshOnAirNow() {
        var params = "reqTime=" + new Date().getTime();
        var subBrand = getSubBrand();
        var url = options.contentOnAirNowPath;
        if (subBrand) {
                params = params + "&subBrand=" + subBrand;
                url = subBrand + url;
            }

            $.ajax({
                type: "GET",
                dataType: "text",
                data: params,
                statusCode: {200:handleRefreshOnAirNowResponse},
                //success: handleRefreshOnAirNowResponse,
                timeout: 1500,
                url: url
            });

      }

      /* Refreshes the on air now content with the response from the server. */
      function handleRefreshOnAirNowResponse(response) {
        var wrapperElem = $("#onairWrapper");
        if (wrapperElem.length && response) {
          wrapperElem.html(response);
          initLinks(wrapperElem);
        }
      }

      /* Makes a request to retrieve the new content for the the up coming show. */
     function refreshOnAirNext() {
        var params = "reqTime=" + new Date().getTime();
         var subBrand = getSubBrand();
        var url = options.contentOnAirNextPath;
        if (subBrand) {
                params = params + "&subBrand=" + subBrand;
                url = subBrand + url;
            }

            $.ajax({
                type: "GET",
                dataType: "text",
                data: params,
                statusCode: {200:handleRefreshOnAirNextResponse},
                //success: handleRefreshOnAirNextResponse,
                timeout: 1500,
                url: url
            });
      }

      /* Refreshes the up coming show content with the response from the server. */
      function handleRefreshOnAirNextResponse(response) {
            var wrapperElem = $("#comingUpShow");
             var html = findOnAirNextDetails(response);
        if (wrapperElem.length && html) {
          wrapperElem.html(html);
          initLinks(wrapperElem);
        }
      }

      /*
      Determines the up coming show details based on the html response from the server.
      Note: the contents of the ul is extracted, to avoid nested uls in the response.
      */
      function findOnAirNextDetails(response) {
        var html = "";
        if (response) {
            var ul = $('<ul/>', {
                    html: response
                });


            var ulChildren = ul.find("li");
            ulChildren.each(function(idx, tli) {
               var li = $(tli);
               if (tli.id && (tli.id == "comingUpShow")) {
                 html = li.html();
               }
            });

        }
        return html;
      }

      function refreshAds(response) {
          // swap the 300x60 ad
          FD.refreshAd("adSpot-300x60");
          // swap the island ad
          FD.refreshAd("adSpot-island");
      }

      /*
      Open the link in the parent window if it exists.
      This is used by the openLink function, to determine which window to open when a link in the player is clicked on.
      */
      function openLinkInParentWindow(event, opener, location) {
        if (opener) {
            FD.stopEvent(event);
            opener.location = location;
            opener.focus();
        }
      }

      /*
      Open the link in a new window and returns the window object.
      This is used by the openLink function, to open a new window when the Parent is closed
      or by IE when opening an external link.
      */
      function openLinkInNewWindow(event, target, anchor) {
        FD.stopEvent(event);
        // We might not want this on focus, so its not set
        return window.open(anchor.href, target);
      }

      /*
      Invoked when an anchor is clicked.  The href of the anchor is used to open the link in the opener.
      A link will open in:
      - Parent window - if the class on the anchor is "nowplayingParentTarget".
      If the parent window is closed, open a new window with target name "nowplayingParentTarget".
      Or if there is no class associated, the parent window gets updated.
      Of if the browser is IE and the anchor's class is "nowplayingBuyTarget"
      - Always in a new window - if the class on the anchor is "nowplayingExternalTarget".
      - In a new window which gets updated - if the browser is the class on the anchor is "nowplayingBuyTarget".
      When other links with the same class are clicked, this window will be updated (e.g. buy links).
      */
      function openLink (event) {
          var anchor = $(this);
        var opener = window.opener;
        var isParentOpen = false;

        if (opener) {
          isParentOpen = true;
          try {
            //is IE parent window open
            if (opener.closed || !opener.open) {
              isParentOpen = false;
            }
          } catch (e) {
            isParentOpen = false;
          }
        }

        var anchorClass = this.className;
        var location = this.href;

        // If its an invalid href
        if (location == "javascript:void(null);" || location == "#" || location == "") {
          FD.stopEvent(event);
          return;
        }

        if (anchorClass == "nowplayingParentTarget") {
          if (isParentOpen) {
            //check if link should open in the parent
            try {
              // This is because there are two event calls when updating a window.
              // If the parent was closed, then the first call opens the window,
              // sets the location and saves it as the parent. The second call is
              // still pointing to the old opener and therefore throws an error
              // - doesn't change anything, just stops errors from being thrown
              //   on the second lot of calls on the opener...best to just catch
              //   it and be on our way.
              openLinkInParentWindow(event, opener, location);
            } catch(e) {}
          } else {
            //open the link in a new window and save it as the parent
            opener = openLinkInNewWindow(event, "nowplayingParentTarget", this);
            window.opener = opener;
            opener.focus();
          }
        } else if (anchorClass == "nowplayingExternalTarget") {
          // Always open this in a new window
          var newWin = openLinkInNewWindow(event, "nowplayingExternalTarget", this);
          newWin.focus();
        } else if (anchorClass == "nowplayingBuyTarget") {
          // Always open this in a new window
          openLinkInNewWindow(event, "nowplayingBuyTarget", this);
        } else {
          openLinkInNewWindow(event, "nowplayingExternalTarget", this);
        }
      }
    }

    /* Invoked when building an ajax request (used for triplem)*/
    function getSubBrand() {
        pathArray = window.location.pathname.split( '/' );
        // if there is a sub brand in the path
        if (pathArray.length > 2) {
            // return the sub brand name
            return pathArray[1];
        }
    }

    /* Hook for Ooyala */
    function receiveOoyalaEvent(playerId, eventName, parameters) {
        if (eventName == "playComplete") {
            onMediaComplete();
        }
    }

    /* Invoked when the BrightCove player has completed its playback */
    function onMediaComplete() {
      //$('body').trigger("prerollComplete");
        $.event.trigger('prerollComplete');
    }

    function onMediaStop()
    {
      // continue playing the advert
      callFlash('pauseAd');
    }
    /* Init objects
    ------------------------------------------------------------------------------------------- */
    $(function() {
        var mediaPlayer = new FD.MediaPlayer();
    });

    /* Init Tabs
   ------------------------------------------------------------------------------------------- */

    var prevSelectedTabIndex = -1;
    var selectedTabIndex = 0;

}

