 /*
 * ELHhtml5VideoGallery 1.5.3
 *
 * Copyright 2010 Estee Lauder - www.esteelauder.com
 * Lovingly crafted By Nick Warner - www.nwarner.com
*/

var ELHtml5VideoGalleryTabScrollbar = {};

var ELHtml5VideoGallery = Class.create({ 
  initialize :  function(options){
    this.feed_url =       options.feed_url || "gallery.json";
    this.content =        options.content || undefined;
    this.show_tabs =      options.show_tabs || false;
    this.current_tab =    options.current_tab || 0;
    this.video_tag_support =  undefined;
    this.video_h264_support = undefined;
    this.track_metrics = options.track_metrics || true;
    this.load_feed();
  }

  , load_feed: function(){
      var self = this;
      if (self.feed_url === "direct") { // Use direct data input
        self.parse_json(self.feed_content);
      } else if (self.feed_url === "data") { // Use direct data input without the need to parse
        //self.parse_json(self.feed_content);
      } else {
        new Ajax.Request(self.feed_url, { // or fetch a feed
          method: 'get',
          onFailure: function(){console.log("Load Feed Failure.");},
          onSuccess: function(response) {          
            self.content = response.responseText.evalJSON();
            self.detect_video_support();
            self.build_gallery();
          }
        });
      }
    }

  , detect_video_support: function() {
      var self = this;
      var v = document.createElement("video");    
      self.video_tag_support = (!!v.canPlayType);
      if (self.video_tag_support) {
        self.video_h264_support = v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
      }
    }    
    
  , build_gallery: function() {
      var self = this;
      var tabs = self.content.tabs;
      var tab_names = ["All Videos"];
    
      // Create thumbnails
      self.build_tab_html(0);   // build the ALL VIDEOS tab
      if (self.content.headline) {
        self.build_tab_headline(0, self.content.headline);
      }
      tabs.each(function(tab, index){
        self.add_thumbnails_to_tab(0, index, tab.videos);            // add to ALL tab
        if (tabs.length > 1) {
          self.show_tabs = true;
          tab_names.push(tab.title);      
          self.build_tab_html(index + 1);
          if (tab.headline) {
            self.build_tab_headline(index + 1, tab.headline);
          }
          self.add_thumbnails_to_tab(index + 1, index, tab.videos);  //add to it's own tab
        } 
        if ( tab.videos.length < 10 ) {
          ELHtml5VideoGalleryTabScrollbar[index+1] = undefined;
        }
      });
    
      // Create Tab buttons
      if (self.show_tabs === true) {
        tab_names.each(function(tab_name, index) {
          Element.insert($("ELHtml5VideoGalleryTabButtonContainer"), 
            {'bottom': "<div id='video_gallery_tab_button_"+index+"' class='ELHtml5VideoGalleryTabButton'>"+tab_name+"</div>"});
          $("video_gallery_tab_button_"+index).observe('click', function(){ self.show_tab(index); });
        });
        $("ELHtml5VideoGalleryTabButtonContainer").show();
        $("ELHtml5VideoGalleryTabContainer").addClassName('show_buttons');     
      }
      
      // Setup Video player
      $("ELHtml5VideoGalleryOverlay").observe('click', function(){ self.hide_video(); });
      $$("#ELHtml5VideoGalleryVideoContainer .close .button")[0].observe('click', function(){ self.hide_video(); });

      self.show_tab(self.current_tab);
    }
  
  , build_tab_html: function(index){
      var self = this;
      
      // Tab Container
      Element.insert($("ELHtml5VideoGalleryTabContainer"), 
        {'top': "<div id='video_gallery_tab_"+index+"' class='ELHtml5VideoGalleryTab'></div>"});
        
      // Tab Scrollbar
      Element.insert($("ELHtml5VideoGalleryTabContainer"), 
        {'top': "<div id='video_gallery_scroll_container_"+index+"' class='ELHtml5VideoGalleryTabScrollContainer'><div id='video_gallery_scroll_button_"+index+"' class='ELHtml5VideoGalleryTabScrollbutton'></div></div>"});

      // Setup Scrollbar
      ELHtml5VideoGalleryTabScrollbar[index] = new Control.Slider( "video_gallery_scroll_button_"+index, "video_gallery_scroll_container_"+index,  {
        axis:'vertical',
        range: $R(0, $("video_gallery_scroll_container_"+index).getHeight())
      });

      ELHtml5VideoGalleryTabScrollbar[index].options.onChange = function(value) {
        self.scroll_tab(index, value);
      };
      ELHtml5VideoGalleryTabScrollbar[index].options.onSlide = function(value) {
        self.scroll_tab(index, value);
      };

      var mousewheel_event = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
      Event.observe($("video_gallery_scroll_container_"+index), mousewheel_event, function(event) {
        var delta = (event.wheelDelta) ? event.wheelDelta : event.detail*-1;
        if (event.wheelDelta) {
          ELHtml5VideoGalleryTabScrollbar[index].setValue(ELHtml5VideoGalleryTabScrollbar[index].value - (delta / 100));
        } else {
          ELHtml5VideoGalleryTabScrollbar[index].setValue(ELHtml5VideoGalleryTabScrollbar[index].value - (delta * 2));
        }
      }, false);
      Event.observe($("video_gallery_tab_"+index), mousewheel_event, function(event) {
        var delta = (event.wheelDelta) ? event.wheelDelta : event.detail*-1;
        if (event.wheelDelta) {
          ELHtml5VideoGalleryTabScrollbar[index].setValue(ELHtml5VideoGalleryTabScrollbar[index].value - (delta / 100));
        } else {
          ELHtml5VideoGalleryTabScrollbar[index].setValue(ELHtml5VideoGalleryTabScrollbar[index].value - (delta * 2));
        }
      }, false);     
    }
   
  , build_tab_headline: function(index, headline){
      Element.insert($("ELHtml5VideoGalleryTabContainer"),
        {'top': "<div id='video_gallery_tab_headline_"+index+"' class='ELHtml5VideoGalleryTabHeadline'>"+headline+"</div>"});
  }
   
  , add_thumbnails_to_tab: function(tab, tab_index, videos) {
      var self = this;
      
      videos.each(function(video, index){      
        Element.insert($("video_gallery_tab_"+tab), 
          {'bottom': "<div class='ELHtml5VideoGalleryThumbnailContainer'><div class='ELHtml5VideoGalleryThumbnail'><img src='"+video.thumbnail+"' alt='"+video.title+"' /></div><div class='overlay' id='video_gallery_thumbnail_"+tab+"_"+tab_index+"_"+index+"'></div><div class='title'>"+video.title+"</div></div>"});
          
        $("video_gallery_thumbnail_"+tab+"_"+tab_index+"_"+index).observe('click', function(){ self.show_video(tab_index, index); });
        $("video_gallery_thumbnail_"+tab+"_"+tab_index+"_"+index).observe('mouseover', function(){ self.mouseover_thumb(this); });
        $("video_gallery_thumbnail_"+tab+"_"+tab_index+"_"+index).observe('mouseout', function(){ self.mouseout_thumb(this); });
      });
    }
    
    
    
  , scroll_tab: function (index, value) {    
      var tab = $("video_gallery_tab_"+index);
      var scrollto = (value / $("video_gallery_scroll_container_"+index).getHeight()) * tab.getHeight();
      tab.scrollTop = scrollto;
  }
    
    
  , mouseout_thumb: function($thumb) {
      if (/Firefox/i.test(navigator.userAgent)) {
        $thumb.up().down('img').setOpacity(0.5);
      }
      $thumb.up().down('.title').removeClassName("hover");
      $thumb.up().down('img').removeClassName("hover");
    }
  
  , mouseover_thumb: function($thumb) {
      if (/Firefox/i.test(navigator.userAgent)) {
        $thumb.up().down('img').setOpacity(1.0);
      }
      $thumb.up().down('.title').addClassName("hover");
      $thumb.up().down('img').addClassName("hover");
    }


  , show_tab: function(tab_index) {
      $$(".ELHtml5VideoGalleryTabHeadline").each(function(tab){ tab.hide(); });
      $("video_gallery_tab_headline_"+tab_index).show();
      
      $$(".ELHtml5VideoGalleryTab").each(function(tab){ tab.hide(); });
      $("video_gallery_tab_"+tab_index).show();
      
      $$(".ELHtml5VideoGalleryTabScrollContainer").each(function(tab){ tab.hide(); });
      if (ELHtml5VideoGalleryTabScrollbar[tab_index]) {
        $("video_gallery_scroll_container_"+tab_index).show();
      }
      
      $$(".ELHtml5VideoGalleryTabButton").each(function(tab){ tab.removeClassName("current"); });
      $("video_gallery_tab_button_"+tab_index).addClassName("current");
      
    }
    
  
  , show_video: function(tab_index, index) {
      var self = this;
      var video = self.content.tabs[tab_index].videos[index];

      $$("#ELHtml5VideoGalleryVideoContainer .title")[0].update(video.title);
      $$("#ELHtml5VideoGalleryVideoContainer .description")[0].update(video.description);
      
      $$("#ELHtml5VideoGalleryVideoContainer .link")[0].update();
      if (video.link !== undefined) {      
        Element.insert($$("#ELHtml5VideoGalleryVideoContainer .link")[0], 
            {'top': "<a href='"+video.link.url+"'>"+video.link.title+"</a>"});
      }
      
      self.insert_video_player(video);
      
      self.metrics_videoview(video.title);
  
      new Effect.Appear($("ELHtml5VideoGalleryOverlay"), { duration: 1 });
      new Effect.Appear($("ELHtml5VideoGalleryVideoContainer"), { duration: 1.1 });  
    }
  
  
  , hide_video: function() {
      new Effect.Fade($("ELHtml5VideoGalleryOverlay"), { duration: 0.6 });
      new Effect.Fade($("ELHtml5VideoGalleryVideoContainer"), { duration: 0.5 });
      $$("#ELHtml5VideoGalleryVideoContainer .player")[0].update(); // clear the player
    }
    
    
  , insert_video_player: function(video, player_element) {
      var self = this;
      // now that generic overlay / clip.tmpl code uses this for video pop-ups, we need to be able to specify
	  // the player container element since there may be more than one.
      var player_container = (player_element) ? player_element : $$("#ELHtml5VideoGalleryVideoContainer .player")[0];
	  //return if no player container found
	  if(!player_container)return null;
		  
      player_container.update();
      
      if (self.video_tag_support && self.video_h264_support) {
        // HTML5 Video
        Element.insert(player_container,
          {'top': "<video width='610' height='370' autoplay controls><source src='"+video.source+"' type='video/mp4' /></video>"});
      } else {  
        // Flash
        player_container.setStyle({'outline': 'none'});
        Element.insert(player_container,
          {'top': "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' width='617' height='376' id='Untitled-1' type='application/x-shockwave-flash' data='/media/flash/video/flash/videoplayerDemo.swf'>	\
				<param name='movie' value='/media/flash/video/flash/videoplayerDemo.swf' />	\
				<param name='quality' value='high' />	\
				<param name='bgcolor' value='#ffffff' />	\
				<param name='play' value='true' />	\
				<param name='loop' value='true' />	\
				<param name='wmode' value='window' />	\
				<param name='scale' value='showall' />	\
				<param name='menu' value='true' />	\
				<param name='FlashVars' value='videoName="+video.source+"' />	\
				<param name='devicefont' value='false' />	\
				<param name='salign' value='' />	\
				<param name='allowScriptAccess' value='sameDomain' />	\
				<!--[if !IE]>-->	\
				<object type='application/x-shockwave-flash' data='/media/flash/video/flash/videoplayerDemo.swf' width='617' height='376'>	\
					<param name='movie' value='/media/flash/video/flash/videoplayerDemo.swf' />	\
					<param name='quality' value='high' />	\
					<param name='bgcolor' value='#ffffff' />	\
					<param name='play' value='true' />	\
					<param name='FlashVars' value='videoName="+video.source+"' />	\
					<param name='loop' value='true' />	\
					<param name='wmode' value='window' />	\
					<param name='scale' value='showall' />	\
					<param name='menu' value='true' />	\
					<param name='devicefont' value='false' />	\
					<param name='salign' value='' />	\
					<param name='allowScriptAccess' value='sameDomain' />	\
				<!--<![endif]-->	\
					<a href='http://www.adobe.com/go/getflash'>	\
						<img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' />	\
					</a>	\
				<!--[if !IE]>-->	\
				</object>	\
				<!--<![endif]-->	\
			</object>"});
      
      }
  
    },
    
    
  metrics_videoview: function(name) {
    this.metrics_element_tag("VideoGallery:ViewVideo", name );
  },
  
  metrics_element_tag: function(who, what) {
    if (this.track_metrics === true) {
      if (typeof cmCreatePageElementTag === "function") { 
        if (typeof Analytics =='object') { 
			Analytics.addPendingTags({"Analytics::CoreMetrics":{"dom:loaded":[{"params":[who,what],"tag":"cmCreatePageElementTag"}]}}); 
		}
      }
    }
  }

});
