﻿var videos = {
	myYouTubeFeed: new Ajax("/en/experience/feeds/yt_videos.xml", {method: 'get'}).request(),
	youTubeVideo : [],
	playerSettings: {"community":false,"events":true,"actionsports":true,"legacy":true},
	playerToggle:true,
	nowPlaying: '',
	videoCount: 0,
	videoIndex: 0,
	objectCount: 0,
	firstVideo: '',
	//maxVideos: 4,
	maxVideos: 10,
	autoPlay: 0,
	//viewableVidWidth: 0,
	//thumbWidth: 0,
	overlayImg1: "jeep_youtube_thumb_overlay1.png", //play btn
	overlayImg2: "jeep_youtube_thumb_overlay2.png", //generic arrow button
	isObjectLoaded: false,
	videoArray: new Array(),
	videoViewsArray: new Array(),
    
    //Takes in player switch of Widget
	read : function() {
	    
	    //Set the Player toggle based on what section you are in.
	    this.playerToggle = this.playerSettings[global.cur_page];
	    
	  
		// This is going to read the videos Array
		var youTubeXMLDoc = this.myYouTubeFeed.response.xml;
        var videoList = youTubeXMLDoc.getElementsByTagName('video_list')[0];
        var videos = videoList.getElementsByTagName('video');
        
        /*LOOP THRU YOU TUBE FEED AND MAKE ARRAY*/
        for(i=0; videos.length > i; i++){
            var nodeCount = videos[i].childNodes.length;
            this.youTubeVideo["video" + i] = new Array();
                for(n=0; nodeCount > n; n++){
                    if(videos[i].childNodes[n].nodeType == 1){
                        if(videos[i].childNodes[n].nodeName == "tags"){
                            var cur_tags = videos[i].childNodes[n].firstChild.nodeValue.split(" ");
                            this.youTubeVideo["video" + i][videos[i].childNodes[n].nodeName] = cur_tags;
                         }else{
                        this.youTubeVideo["video" + i][videos[i].childNodes[n].nodeName] = videos[i].childNodes[n].firstChild.nodeValue;
                    }
                }
            }
        }
	},
	
	//Find what video to show based on Global filtering. 
	find : function() {
	 // This will build out thumbs from XML array
       for(i in this.youTubeVideo){
            if(typeof(this.youTubeVideo[i]) == 'object'){
                var curVideo = this.youTubeVideo[i];
				
                if(global.filtersArray != '' && global.filtersArray != 'undefined' && global.filtersArray != null){
                     for(i=0; curVideo['tags'].length > i; i++){
                        for(j=0; global.filtersArray.length > j; j++){
                            //Limit video output to 4 videos.
                            if(curVideo['tags'][i] == global.filtersArray[j] && this.videoIndex < this.maxVideos){  
								//console.log("tag matches filter");
								//console.log(curVideo['tags'][i] + " == " + global.filtersArray[j]);
								
                                var thisVideoJSON = "http://gdata.youtube.com/feeds/api/videos/"+curVideo['id']+"?alt=json-in-script&callback=videos.jsonVideoBuild";
                                new Asset.javascript(thisVideoJSON, {id: 'video'+this.videoCount});
                                
                                this.videoArray.include(curVideo);
                                this.videoIndex++;
                            }
                        }
                    }
                }else{
                    var thisVideoJSON = "http://gdata.youtube.com/feeds/api/videos/"+curVideo['id']+"?alt=json-in-script&callback=videos.jsonVideoBuild";
                    new Asset.javascript(thisVideoJSON, {id: 'video'+this.videoCount});
                    this.videoArray.include(curVideo);
                }
            }
            
        }  
	},
	
	
	//Set up X domin JSON objects for realtime data consumption. 
	jsonVideoBuild : function(argObject){
        this.videoViewsArray.push(argObject.entry.yt$statistics.viewCount);
        
        if(this.videoViewsArray.length == this.videoIndex){
            this.parse();
        }
	},
	
	
	//Parse out data collected from the find filtering 
	parse : function(){
	
       var thumbLayout = '';
        
       for(i=0; this.videoArray.length > i; i++){
       
            this.videoArray[i]['view_count'] = this.videoViewsArray[i];
            
            thumbLayout += this.build(this.videoArray[i]);
            
            this.videoCount++;
            
       }
  
      $('video_thumbs').setHTML(thumbLayout);
          
      /* Set up Tool Tips For Video Thumbs */
      global.makeTips({x:-25,y:-110},'.video_link','video-tool');
      
      if (window.ie6){iePngFix();}
      
      //Find and play first video if player is set tp true.
      if(this.playerToggle){
          videos.play(0);
       }
       
   },
    
    //Build out individual thumbs for navigation.
	build : function(argItem) {
	    var itemLayout = '';
	    
	    /*This code it to filter out " and ' and convert 
	    them to ASCII set so they wont break title tages.*/
		
	    var catchQuote = '&#34;';
	    var catchSingleQuote = '&#39;';
	    var curTitle = "<strong>" + argItem['title'] + ': </strong><br />Length:' + argItem['length_seconds'] + '&nbsp;&nbsp;&nbsp;&nbsp;Views:' + argItem['view_count'] + '<br />' + argItem['description'];
	    var filterTitle1 = curTitle.replace(/"/g, catchQuote);
	    var filterTitle2 = filterTitle1.replace(/'/g, catchSingleQuote);
	    curTitle = filterTitle2;
	    
	    var titleArray = argItem['title'].split(" ");
	    var cutDownTitle = "";
	    
	    //for(j=0; 3 > j; j++){
		for(j=0; 2 > j; j++){
	       if(titleArray[j]){
	        cutDownTitle += titleArray[j] + " ";
	       }
	    }
	    
	    cutDownTitle += "...";
		
        itemLayout += '<div id="video'+this.videoCount+'" class="video_thumb_link"><a class="video_link" href="javascript:void(0);" style="background:url(\''+argItem['thumbnail_url']+'\') no-repeat top left;" title="' + curTitle + '" name="&amp;lid='+argItem['title']+' Video&amp;lpos=Video Thumb Nav"onClick="videos.play('+this.videoCount+');"><img class="main_thumb" src="/shared/images/experience/'+this.overlayImg1+'" /></a>';
		itemLayout += '<div class="videoThumbTitle">' + cutDownTitle + '</div>';
        itemLayout += '<div class="videoThumbLength">Length:' + argItem['length_seconds'] + '</div>';
        itemLayout += '<div class="videoThumbViews">Views:' + argItem['view_count'] + '</div>';
        itemLayout += '</div>';
        
	    return itemLayout;
	},
	
	//Play video that is defuled or selected. 
	play : function(argVideo) {
    
    if(this.playerToggle){
        var FO = {
			//movie:'http://www.youtube.com/v/'+ this.videoArray[argVideo].id +'&rel=0&color1=fff6e5&color2=888f64&border=0&autoplay='+this.autoPlay,
			movie:'http://www.youtube.com/v/'+ this.videoArray[argVideo].id +'&rel=0&color1=dddddd&color2=eeeeee&border=0&autoplay='+this.autoPlay,
	        width:        "100%",
	        height:       "100%",
	        name:	  	   "youtube_video",
	        id:		       "youtube_video",
	        allowscriptaccess:"always",
	        bgcolor:      "#FFFFFF",
	        scale:        "noscale",
	        wmode:        "transparent",
	        play:         "true",
	        quality:      "high",
	        menu:         "false",
	        majorversion: "8",
	        build:        "0",
	        xi:           "false"
	    };
	    
	    UFO.create(FO, 'feature_video');
		
		//youtube logo
        var youTubeLogo = new Asset.image('/shared/images/experience/events/youtube_logo.gif', {id: 'youTubeLogo'});
				
	    $('video_title').setHTML(this.videoArray[argVideo]['title']);
		//only inject youtube logo on events sub pages
		if(global.cur_page == 'events') {
			youTubeLogo.injectTop($('video_title'));
		}
        $('video_length').setHTML("LENGTH: " + this.videoArray[argVideo]['length_seconds']);
        $('video_views').setHTML("VIEWS: " + this.videoArray[argVideo]['view_count']);
        $('video_copy').setHTML(this.videoArray[argVideo]['description']); //need to re-add this div
		
       }else{
       
          var thisURL = escape("http://www.youtube.com/watch?v="+this.videoArray[argVideo].id+"&eurl="+location.href);
        
          flexWin('/en/experience/bounce.html?item='+thisURL,'yes','1024','768','youTubeWin','all');
       
       }
        
        this.nowPlaying = argVideo;
		this.autoPlay = 1;
	}
}

