var ELHtml5VideoGalleryTabScrollbar = {};

var ELHtml5VideoGallery = Class.create({ 
  initialize :  function(options){
    this.feed_url =       options.feed_url || "gallery.json";
	  this.is_video_popup = options.video_popup || false;
    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);
		self.detect_video_support();
      } else if (self.feed_url === "data") { // Use direct data input without the need to parse
		self.detect_video_support();
      } 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+"' name='"+video.title+"'></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) {
  	  var self = this;
  	  
  	  self.launch_default_video();
  	  
      $$(".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");
    }
    
  , launch_default_video: function() {
  		// launch video specififed in querystring, defined by param launch_video, with a value of the video title 
			var videoToLaunch = decodeURI(brx.getQuerystringValue('launch_video'));
			if (typeof(videoToLaunch) != 'undefined'){
				var videoLaunchLink = $$('[name='+videoToLaunch+']')[0];
				if (typeof(videoLaunchLink) != 'undefined'){
					videoLaunchLink.simulate('click');
				}
			}
  }
    
  , 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);
        
      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
    },
    
    
  firstPlay: true
    
    
  , insert_video_player: function(video, player_element) {
      var self = this;
      self.firstPlay = true;
      // 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 (video.youtube_embed_source){
      	 $("ELHtml5VideoGalleryVideoContainer").addClassName('embedded_player');
      	 player_container.addClassName('embedded_player');
      	 Element.insert(player_container,
          {'top': video.youtube_embed_source 
         });
      } else if (self.video_tag_support && self.video_h264_support) {
        // HTML5 Video
	 var video_style = "";
	 if(self.is_video_popup){
	    video_style = " style='margin-left: -6px'";
	 }
       	 
         $("ELHtml5VideoGalleryVideoContainer").removeClassName('embedded_player');
      	 player_container.removeClassName('embedded_player');

         var previous_video_player = player_container.down('video');
         if (previous_video_player) {
	     previous_video_player.remove();
         }

        Element.insert(player_container,
          {'top': "<video src='"+video.source+"' width='610' height='370'"+video_style+" autobuffer autoplay controls></video>"});
          
        player_container.down('video').addEventListener('play', function(){
          if (self.firstPlay === true) {
            self.metricsTag(player_container, 0, video.title);
            self.firstPlay = false;
          }
          self.metricsTag(player_container, 2, video.title);
        }, true);
        player_container.down('video').addEventListener('pause', function(){
          self.metricsTag(player_container, 1, video.title);
        }, true);
        player_container.down('video').addEventListener('ended', function(){
          self.metricsTag(player_container, 3, video.title);
        }, true);
        player_container.down('video').addEventListener('error', function(event){
          console.log('Video Error');
        }, true);
          
      } else {  
        // Flash
         var flashContainer = $("ELHtml5VideoGalleryVideoContainer");
         if (flashContainer) flashContainer.removeClassName('embedded_player');
      	 player_container.removeClassName('embedded_player');
      	 player_container.setStyle({'outline': 'none'});
        Element.insert(player_container,
          {'top': "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' width='617' height='366' 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+"&videoWidth=610&videoHeight=332' />	\
				<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='366'>	\
					<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+"&videoWidth=610&videoHeight=332' />	\
					<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>"});
      
      }
  
    },
    
  
  metricsTag: function(player_container, status, tag, category) {
    var attributes;
    if (tag == null) {
      tag = this.default_element_id;
    }
    if (category == null) {
      category = this.default_element_category || "VideoGallery:ViewVideo";
    }
    
    var current_time = player_container.down('video').currentTime;
    var duration = player_container.down('video').duration;
    
    if (typeof cmCreatePageElementTag === 'function') {
      attributes = "-_--_--_--_--_--_--_--_--_--_--_--_-" + [status, Math.floor(current_time), Math.floor(duration)].join("-_-");
      //console.log(attributes);

      return cmCreatePageElementTag(tag.substring(0, 49), category.substring(0, 49), attributes);
    }
  },
    
    
/*
  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"}]}}); 
		    }
      }
    }
  }

});

