﻿
    var hCarousel;
    var currentOAData;
    var oLastAItemData = "";
     
    function setpageOnAirItems(oaData)
    {
        doRefresh(oaData)
    }

   function doRefresh(oaData)
   {
      if (oaData != null && oaData != '')
      {
           if (currentOAData == null || currentOAData == '')
           {            
                currentOAData = oaData[0]; 
           }
           else
           {
                if (currentOAData._onAirItem._familyID != oaData[0]._onAirItem._familyID)
                {
                    currentOAData = oaData[0] ;
                    populateOAData();
                }
            }
           if (oLastAItemData == null || oLastAItemData == '')
           {
                oLastAItemData = oaData[0]._lastItemsAired ;
           }
           else
           {
                if (hasOAItemsChanged(oaData[0]))
               {
                   oLastAItemData = oaData[0]._lastItemsAired ;
                   //Refresh Carousel
                    refreshLastAired(); 
                }
           }
     }
     setTimeout("refresh()", refreshTime);
   } 
   
  function hasOAItemsChanged(uOAData)
  {
    var currentItems =  oLastAItemData ; //currentOAData._lastItemsAired;
    var newItems = uOAData._lastItemsAired;
    if (currentItems == null || newItems == null ||
        currentItems.length == 0 || newItems.length == 0 ||
        currentItems.length  != newItems.length  )
    {
        return false;
    }
    var hasChanged = false;
    
    for (var counter =0; counter < currentItems.length -1; counter ++)
    {
        if (currentItems[counter]._familyID != newItems[counter]._familyID)
        { 
            hasChanged = true;
            break;
        }
    }
    return hasChanged;
  }
    
    function populateOAData(){
        if (currentOAData != null && currentOAData != ''){
            var ai = currentOAData ; 
            if (ai != null)
            {
                try{
                    var showName = (ai._showName.truncate(14));
                    var showLink = ai._showURL;
                    if (showName != "" && showLink != "")
                    {
                        var  sh = "<a href=\"" + showLink + "\" title=\"" + ai._showName  + "\" >This Hour:" + showName + "</a>";
                        $("spanThisHour").update(sh);                        
                    }
                    var currentOA = ai._onAirItem; // currentOAData ; 
                    if (currentOA != null)
                    {
                        var prodHref = "<a href=\"" + getProductUrl(currentOA, "TV1-_-ONAIR-_-N") + "\" >";
                        var img = prodHref + getImage(currentOA, 140) ;
                        $("divOAImage").update(img);
                        var s = LMoreHref(currentOA);
                       $("divOAProduct").update(s);
                    }
                }
                catch (e){
                    //handleException ("Error populating Current OnAir Item " + e)
                    throw e;
                }
            } //if ai not null
                     
        } //if oLastAItemData not null
   } //end function 
   
   function refreshLastAired()
   {
   
  /*
        var newItems = oLastAItemData; 
       
        if (newItems != null && newItems.length > 0)
        {
            var slideDivNamePrefix = "D" ;
            var itemCounter = 0;
            var sliderDivName  ;
           
            var existing = hCarousel.container.childElements();
            if (existing != null && existing.length > 0)
            {
               for(var i = 0; i < (existing.length -1); i++)
               {   
                  sliderDivName = slideDivNamePrefix + itemCounter;  
                  var ai = newItems[i]; 
                  var sliderDiv = $(sliderDivName);
                  var uHref =  getProductUrl(ai, 'TV2-_-ONAIR-_-' + (i+1) );
                  var uTitle = ai._familyName;
                  var uSrc = 'http://images.shopnbc.com/is/image/ShopNBC/' + ai._familyID.toLowerCase() + 
                                '?hei=120&wid=120&op_sharpen=1';
                  
                  var cSliderContent = getCurrentSlideContent(sliderDiv ) ; //.down('span').innerHTML;
                  var uSliderContent = getSliderContent(ai,(itemCounter+1));
                  existing[i].down().writeAttribute('href', uHref );
                  existing[i].down().writeAttribute('title', uTitle);
                  existing[i].down(1).writeAttribute('title',uTitle ) 
                  existing[i].down(1).writeAttribute('src',uSrc );
                   
                   var nextDiv = sliderDiv.down('span');
                   nextDiv.update(uSliderContent);
                   itemCounter ++;
                }
            }
         } 
         
         */
    }
    
    function getSliderContent(ai, itemCounter)
    {
        var content = "<p>" + 
                    ai._familyID + " - " + ai._familyName + 
                    "</p><p><strong>" + 
                    getPrice(ai) + 
                    "</strong></p>" + 
                    "<p>" + (ai._isMoreColorsAvailable == "true" ? "More colors available" : "" ) + "</p>" +
                    createVURL(ai) +
                    "<p>" +
                    LearnMoreInformation(ai, ('TV2-_-ONAIR-_-' + itemCounter ), 'Learn More') + 
		            "</a></p>";
	    return content;	            
    }

    function getCurrentHref(divElement)
    {
        return divElement.down().readAttribute('href');
    }
    
    function getCurrentTitle (divElement)
    {
        return divElement.down().readAttribute('title' );
    }
    
    function getCurrentSrc(divElement)
    {
        return divElement.down(1).readAttribute('src');
    }
    
    function getCurrentSlideContent(divElement)
    {       
        return divElement.down('span').innerHTML;
    }

    function LMoreHref(currentOA)
    {
         var prodHref = "<a href=\"" + getProductUrl(currentOA, "TV1-_-ONAIR-_-N") + "\" >";
         var p = getPrice(currentOA);
         if (p != ""){p = "<br />" + p ; }
         var s = "<p>" + prodHref + currentOA._familyName + "</a></p>" + p +  "<br />" + 
            (currentOA._isMoreColorsAvailable == "true" ? "More colors available" : "" )    ;
         s += LearnMore(currentOA, "TV1-_-ONAIR-_-N");
         return s;
    }  
   
    function LearnMoreInformation(currentOA, cmre, heading)
    {
        var u = getProductUrl(currentOA, cmre);
        var s = "<p><a href=\"" + u +"\" class=\"moreInfo\" >" + heading + "</a> &nbsp;" + getCaratImage() + "</p>";
        return s;
    }    
    
    function LearnMore(currentOA, cmre)
    {
        var u = getProductUrl(currentOA, cmre);
        var s = "<p><a href=\"" + u +"\" class=\"moreInfo\" >Learn More</a> &nbsp;" + getCaratImage() + "</p>";
        return s;
    }
  
    function createVURL(item)
    {
        if (item._videoURL == null || item._videoURL == "") { return "";}
        var fn = item._familyName.strip().gsub(/\s+/, "+").replace("'", "%5C'");
        
        var v="/product/launchProductVOD2.aspx?articleID=&amp;cm_sp=Video-_-OTV-_-" + 
            item._familyID.toLowerCase() + "&videourl=" + item._videoURL +
            "&familyname=" + fn + 
            "&familyid=" + item._familyID ;
        var title =  "Watch Video - " + item._familyID + " " + item._familyName.strip() ;
        var prodContent = "<a href=" + 
            "\"javaScript:openDialogWin('" + v + "', 447, 463, '', 0,0);\"" + 
            "title=\"" + title + "\" " +
            "><img src=\"/images/global/product/" + 
            "icon_watchVideo_2008.gif\" border=\"0\" alt=\"" + title + "\" />" + 
            "</a>";
     
        return prodContent ;
    }

    function getCaratImage()
    {
        return  "<img src='/images/global/home/blueCaratRight.gif'" +
            " width='5' height='8' style=\"border:none;vertical-align:bottom\" />" ;
    }
    
    function getProductUrl(item, cTag)
    {
        var u = item._familyName.gsub(/\W+/, '_') + '/' + item._familyID + '.aspx?track=-10102&ciid=11281&cm_re=' + cTag;
        return u;
    }
    
    function getImage(item, size)    
    {
        var img = "<img src='http://images.shopnbc.com/is/image/ShopNBC/" + item._familyID.toLowerCase() + 
                                "?hei=" + size + "&wid=" + size + "&op_sharpen=1'" + 
                                " width='" + size + "' height='" + size + "' alt=\"" + item._familyName.strip() +
                                "\" style=\"border:none\"/></a>" ;
        return img ;
    }
     
    function getPrice(currentOA){
        var p = "";
        var lbl = "";
        if (currentOA._isClearance == "True")
        {
            lbl = "Clearance : ";
            if (currentOA._salePrice != null && currentOA._salePrice != "")
            {
              p = currentOA._salePrice;
            }
        }
        else{
            var bp = (currentOA._salePrice != null && currentOA._salePrice != "") ? currentOA._salePrice : "" ; 
            if (bp == "")
            {
                lbl = "ShopNBC Price : " ;
                bp = (currentOA._vvprice != null && currentOA._vvprice != "") ? currentOA._vvprice : "" ;
                p = bp;
            }
            else
            {
                lbl = "Sale Price : ";
            }
        }
        bp = lbl + bp;
        
        return bp;
    }
    
    function showVideo() {
	$('homeLivePlayer').setStyle({'display': 'block'});
	$('homePageRegular').setStyle({ 'display': 'none' });
	play();
    }

    function closeVideo() {
    pause();
	$('homeLivePlayer').setStyle({'display': 'none'});
	$('homePageRegular').setStyle({'display': 'block'});
    } 
    
    
    var divOtvFlyoutID = 'popupOTV';
    var divPhotoID = 'divOTVPhoto';
    var divOTVContentDivID = 'divOTVFlyContent';
   
    function doTimeouts()
    {
        if (defaultsLoaded == "true") return; 
        hCarousel = new UI.Carousel("horizontal_carousel");
        setTimeout("refresh()", refreshTime);
        connectOTVEvent();        
    }
    
    function connectOTVEvent()
    {
        var oDiv = $(divOTVContentDivID);
        if (oDiv && !(oDiv.innerHTML.blank()))
        {
            var d = $(divPhotoID);
            if (d)
            {
                var i = d.getElementsByTagName('a');
                if (i.length > 0)
                {
                    var iElement = $(i[0].id); 
                    if (iElement)
                    {
                        Event.observe(iElement.id, 'mouseover', getOTVOverlay);
                    }
                }
            }
        }
    }
    
    function getOTVOverlay(e){        
        var div=$(divOtvFlyoutID);
        var d = $(divPhotoID);
        var posx = e.pageX;
        var posy = e.pageY;
        var cOffset = d.cumulativeOffset();
        if (cOffset)
        {
            posx = cOffset.left;
            posy = cOffset.top;
        }
        if(!div){
            if ($(divOTVContentDivID))
            {
                var content = $(divOTVContentDivID).innerHTML;
                $(divOTVContentDivID).remove();        
                div = new Element('div', { 'class': 'otvFlyoutWrapper', 'id': divOtvFlyoutID});
                //Get the price off the OTVTextBlock
                var divPrice =  $('divOTVPrice'); 
                var price = '';
                if (divPrice)
                {
                    var ihtml = divPrice.innerHTML;
                    price = ihtml.substring(ihtml.indexOf('$')+1, ihtml.indexOf('</'));
                }
                if (content != '' && price != '')
                {
                    var startIndex = content.indexOf('Today\'s');
                    if (startIndex > -1)
                    {
                        var priceStartIndex = content.indexOf('$', startIndex);
                        if (priceStartIndex > -1)
                        {
                            var endIndex = content.indexOf('<', priceStartIndex);
                            if (endIndex > -1)
                            {
                                var existingPrice = content.substring(priceStartIndex + 1, endIndex);
                                if (existingPrice.length > 0)
                                {
                                    div.innerHTML = content.replace(existingPrice, price);
                                }
                            }   
                        }
                    }
                }
                document.getElementsByTagName('body')[0].appendChild(div);
            }
        }
        else{
            div.setStyle({display:'block'});
        }
        if (div)
        {
            div.style.top=posy+0+'px';
            div.style.left=posx+0+'px';
            div.observe('mouseleave', handleOverlayMO);
        }
      }
       
      function handleOverlayMO()
      {
        var div=$(divOtvFlyoutID);
        if(!div){return};
        div.setStyle({display:'none'});
        div.stopObserving('mouseleave', handleOverlayMO);
      } 
    
    function refresh()
    {
      makeCall( services + '/GetOnAirItems/' + numOnAir + '/setpageOnAirItems/?'); 
    }

    function InitializeShopNBCLive()
    {
      ShopNBCLive.settings.playLiveStream = true;
      ShopNBCLive.settings.topMenu = false;
      ShopNBCLive.settings.fullScreenOption = false;
      ShopNBCLive.embed("flashPlayer");
      ShopNBCLive.registerEventListener("ArticleChange", "handleArticleChange");
      ShopNBCLive.registerEventListener("Play", "handlePlay");
      ShopNBCLive.registerEventListener("Pause", "handlePause");
      ShopNBCLive.registerEventListener("ProductEvent", "handleProductEvent");
      ShopNBCLive.registerEventListener("EndOfStream", "handleEndOfStream");
      ShopNBCLive.registerEventListener("EndOfSession", "handleEndOfSession");
      ShopNBCLive.registerEventListener("DateChanged", "handleDateChanged");
      ShopNBCLive.registerEventListener("TimeZoneChanged", "handleTimeZoneChanged");
      ShopNBCLive.registerEventListener("ShowChanged", "handleShowChanged");
    }
    
      function setWeek() {
          var dropdown = document.getElementById("weeks");
          var week = dropdown.value;
          ShopNBCLive.setWeek(week);
      }

      function setDay() {
          var dropdown = document.getElementById("days");
          var day = dropdown.value;
          ShopNBCLive.setDay(day);
      }

      function setTimeZone() {
          var dropdown = document.getElementById("zones");
          var zone = dropdown.value;
          ShopNBCLive.setTimeZone(zone);
      }

      function setShow() {
          var dropdown = document.getElementById("hours");
          var show = dropdown.value;
          ShopNBCLive.setShow(show);
      }

      function play() {
          ShopNBCLive.play();
          dcsMultiTrack("DCSext.VideoView", "1", "DCSext.tabs", "Home Page Live Player", "DCSext.reTrack", "TV1-_-ONAIR-_-WatchLive", "DCSext.cm_re", "TV1-_-ONAIR-_-WatchLive");
      }

      function pause() {
          ShopNBCLive.pause();
      }

      function test2() {
          ShopNBCLive.playArticleById(337845, 30);
      }

      function handleArticleChange() {
          document.getElementById('productArea').innerHTML = "ArticleChanged";
      }

      function handlePlay() {
      }

      function handlePause() {
      }

      function handleProductEvent(event) {

          var printString = "";
          try {
              printString += "show name = " + event.product.showName + "<br />";
              printString += "id = " + event.product.id + "<br />";
              printString += "name = " + event.product.name + "<br />";
              printString += "description<br />" + event.product.description + "<br />";
              printString += "regularPrice = " + event.product.regularPrice + "<br />";
              printString += "salePrice = " + event.product.salePrice + "<br />";
              printString += "shippingPrice = " + event.product.shippingPrice + "<br />";
              printString += "imageURL = <img src='" + event.product.imageURL + "' /><br />";
              printString += "indexTime = " + event.product.indexTime + "<br />";
          } catch (e) { }
          document.getElementById('productArea').innerHTML = printString;
      }

      function handleEndOfStream() {
      }

      function handleEndOfSession() {
      }

      function handleDateChanged() {
      }

      function handleTimeZoneChanged() {
      }

      function handleShowChanged() {
          document.getElementById('productArea').innerHTML = "";
      }			