
// a list of playlists in a player
VIEWS.List = {
       
    currPlayer: '', // string representation of currently active player in list view
	token: null,
	carloaded: false,
	thethumb:0,
	new_car: false,
    max_thumbs:5,
	cant_thumbs:0,
	loadCheckout: false,
    init: function(args) {
        //this.buttons = this.buttonsStopped;
        this.menuType = "thumbsMenu";
		this.menuPos = "googleCheckoutButton";
        // start loading
        this.stopLoading();
        AMOSTV.startLoading();
		
		
		var fromPlay = false;
        if ( args ) {
            this.currPlayer = args.player;
			if(args.fromPlay) {
				fromPlay = true;
			}
			if(args.loadCheckout != null && args.loadCheckout == true) 
			{
				this.loadCheckout = true;
			}
			else
			{
				this.loadCheckout = false;
			}
        }
        $('descriptionImage').src = 'img/labels/' + this.currPlayer + '-1080.png';
        $('previewGoogle').hide();
		$('googleCheckoutContainer').hide();
		$('previewOverlay').hide();
		$('listBackButton').show();
		$('previewVideoArea').show();
		$('playButton').show();
		jQuery("#List .carousel").css("display","none");
		this.new_car = false;
		this.cant_thumbs = 0;
		curr_carousel_id = '#List #carousel_'+this.currPlayer;
		if(jQuery('#List #carousel_'+this.currPlayer).length == 0)
		{
			this.new_car = true;
			jQuery("#List").prepend('<div class="carousel" id="carousel_'+this.currPlayer+'"></div>');
		}
		this.removeOpacityOnThumbs();
		
		_gaq.push(['_trackPageview', '/amosgtv/listView/'+this.currPlayer]);
		AMOSTV.players[this.currPlayer].cant = 0;
		
        // if asking to load a specific player, and player data has not been loaded
        if ( args && args.player && AMOSTV.players[args.player].player == null || fromPlay == true) {
            this.loadPlayer(args.player);
        // if asking to load last opened player
        } else {
				
				this.loadPlayer(this.currPlayer);
			
        }
		
		$('prevArrow').show();
		$('nextArrow').show();
		$('playButton').show();			
		
    },
    
    exit: function() {
        //this.stopPreview();
    },
    
    keyHandler: function(key) {
        if ( key == KEYS.RIGHT ) {
			if(this.menuType == "thumbsMenu" && this.menuPos != "listBackButton"){
				jQuery("#nextArrow").mouseup();
			} 
        }
        
        if ( key == KEYS.LEFT  && this.menuPos != "listBackButton") {
			if(this.menuType == "thumbsMenu"){
				jQuery("#prevArrow").mouseup();
			} 
        }
        
		if( key == KEYS.UP ) {
		// let's focus the thumbs area so we show the arrows and playbutton
			if(this.menuType == "thumbsMenu"){ 
				$(this.menuPos).removeClassName("focused");
				this.menuPos = "curr";
				$('prevArrow').show();
				$('nextArrow').show();
				$('playButton').show();
				//preview view is currently showing
			} else if(this.menuType == "previewMenu" && $('previewVideoArea').hasClassName('previewDone')){ 
				if(this.menuPos == "googleCheckoutBackButton"){
					this.setMenuPos(this.menuPos, "googleCheckoutButton");
				}
				//checkout view is currenly showing
			} else if(this.menuType == "checkoutMenu" && this.menuPos == "checkoutBack"){ 
				this.setMenuPos(this.menuPos, "checkoutCheckout");
			}
		}
		
		if( key == KEYS.DOWN ) {
		// let's focus back button so we hide the arrows and playbutton
			if(this.menuType == "thumbsMenu"){ 
				$('prevArrow').hide();
				$('nextArrow').hide();
				$('playButton').hide();
				this.setMenuPos(this.menuPos, "listBackButton");
				//preview view is currently showing
			} else if(this.menuType == "previewMenu" && $('previewVideoArea').hasClassName('previewDone')){ 
				if(this.menuPos == "googleCheckoutButton"){
					this.setMenuPos(this.menuPos, "googleCheckoutBackButton");
				}
				//checkout view is currenly showing
			} else if(this.menuType == "checkoutMenu" && this.menuPos == "checkoutCheckout"){ 
				this.setMenuPos(this.menuPos, "checkoutBack");
			}
		}
                
        if ( key == KEYS.OK ) {
				if(this.menuType == "thumbsMenu" ){
					if(this.menuPos != "listBackButton") {
						var that2 = this;
						jQuery("#List #carousel_"+this.currPlayer+" img").each(function()
						{
							if(this.lang == "current")
							{
								that2.playListChoosen(this.id);
							}
						});						
					} else {
						//make sure thumbsarea is focused if we come back to this view
						 this.setMenuPos(this.menuPos, "curr"); 
						 AMOSTV.loadView('Menu');
					}
					//preview has finished playing
				} else if(this.menuType == "previewMenu" && $('previewVideoArea').hasClassName('previewDone')){ 
					switch(this.menuPos){
					// we move to googlecheckout view to confirm that the user wants to buy. before we throw  them to google.checkout.com
						case "googleCheckoutButton": 
							this.googleCheckout();
						break;
							
						case "googleCheckoutBackButton": // let's go back to thumbslist view
//                            $('googlePreview').remove();
							brightcove.removeExperience("googlePreview");
							this.removeOpacityOnThumbs();
							$('listBackButton').show();
							$('previewGoogle').hide();
							moveImages();
						break;
							
						/*case "previewVideoArea":
							if(!modVP.isPlaying()){
								modVP.play();
							} else {
								modVP.pause();
							}
						break;*/
							
					}
				} else if(this.menuType == "checkoutMenu"){ 
					switch(this.menuPos){
						case "checkoutCheckout": //user clicks the access/login google checkout account button so we sumbit the form
							this.googleSubmitForm();
						break;
						
						case "checkoutBack": // user clicks back button so we go back to thumbsarea view
							this.googleCheckoutBack();
							moveImages();
						break;
					}
				} 
        }
        
        if ( key == KEYS.BACK ) {
            AMOSTV.loadView('Menu');
        }
	
		if( key == KEYS.ESC ) {
			if(this.menuType == "thumbsMenu" ){
				 this.setMenuPos(this.menuPos, "curr"); //make sure thumbsarea is focused if we come back to this view
				 AMOSTV.loadView('Menu');
			} else if(this.menuType == "previewMenu" && $('previewVideoArea').hasClassName('previewDone')){ //preview has finished playing
//                $('googlePreview').remove();
				brightcove.removeExperience("googlePreview");
				this.removeOpacityOnThumbs();
				$('listBackButton').show();
				$('previewGoogle').hide();	
				moveImages();
				
			}					
		}
		
		if ( key == KEYS.GOOGLESTOP || key == KEYS.ESC) {
			if(!$('previewVideoArea').hasClassName('previewDone') && this.menuType == "previewMenu"){
				modVP.pause(true);
				previewDone(); // function in Player.js
			}
		}
		
		/*if ( key == KEYS.GOOGLEPAUSE ) {
			if(!$('previewVideoArea').hasClassName('previewDone')){
				modVP.pause(true);
				previewDone();
			}
		}*/
		
        if ( key == KEYS.PAUSE || key == KEYS.GOOGLEPAUSE ) {
            //AMOSTV.Video.pause();
			if(!modVP.isPlaying()){
				modVP.play();
			} else {
				modVP.pause(modVP.isPlaying());
			}
        }
        
        if ( key == KEYS.PLAY  ) {
			if(!modVP.isPlaying()){
				modVP.play();
			}
        }
		
    },
    
    move: function(direction) {
        var newPosition = null;
        
        if ( direction == 'left' ) {
            // check current position in current playlist
            // if position is 0
            if ( AMOSTV.players[this.currPlayer].positions.curr == 0 ) {
                // use the second last
                newPosition = AMOSTV.players[this.currPlayer].playlists.length - 1;
                
            // if position is bigger than 0
            } else if ( AMOSTV.players[this.currPlayer].positions.curr > 0 ) {
                // use the previous one
                newPosition = AMOSTV.players[this.currPlayer].positions.curr - 1;
            }
        }
        
        if ( direction == 'right' ) {
            // check current position in current playlist
            // if position is the second last one
            if ( AMOSTV.players[this.currPlayer].positions.curr == AMOSTV.players[this.currPlayer].playlists.length - 1 ) {
                // use position 0
                newPosition = 0;
            
            // if position is less than the second last one
            } else if ( AMOSTV.players[this.currPlayer].positions.curr < AMOSTV.players[this.currPlayer].playlists.length - 1 ) {
                // use the next one
                newPosition = AMOSTV.players[this.currPlayer].positions.curr + 1;
            }
        }
        
        this.setPositions(newPosition);
        this.show(this);
    },
    
    /*playPreview: function() {
        if ( AMOSTV.Video.checkPlayTime() ) {
            this.startLoading();
            var url = Brightcove.chooseRendition(
                AMOSTV.players[this.currPlayer]
                    .playlists[AMOSTV.players[this.currPlayer].positions.curr]
                    .videos[0]
            , 0.5);
            AMOSTV.Video.play(url, 312, 233, 336, 189);
        }
        
        this.buttons = this.buttonsPlaying;
        AMOSTV.loadButtons();
    },
	
	stopPreview: function() {
        //AMOSTV.Video.stop();
        this.stopLoading();
        
        this.buttons = this.buttonsStopped;
        AMOSTV.loadButtons();
        
        $('currThumb').show();
        $('playButton').show();
    },
    
    bufferDone: function() {
        AMOSTV.Video.ready();
        this.stopLoading();
        $('currThumb').hide();
        //$('playButton').hide();
    },
    
    renderDone: function() {
        //this.stopPreview();
    },
    
    renderError: function() {
    },*/
    
    startLoading: function() {
        $('previewLoading').show();
    },
    
    stopLoading: function() {
        $('previewLoading').hide();
    },
    
    // load a player with its playlists (a player represents a category)
    loadPlayer: function(playerIndex) {
        
        // retrieve playlist with only video IDs, not entire video objects
        var self = this;
        Brightcove.getPlaylistsByPlayer(AMOSTV.players[playerIndex].id
        , function(player){
            
            // store player, and also its playlists separately, for convenience
            AMOSTV.players[playerIndex].player = player;
            AMOSTV.players[playerIndex].playlists = player.items;
            
            // load everything except first thnee
            var loadTheRest = function() 
			{
                for ( var i = 0 ; i < AMOSTV.players[playerIndex].playlists.length; i++ ) 
				{
                    self.loadPlaylist(playerIndex, i, function(index)
					{
                        self.show(self,index);
						AMOSTV.players[playerIndex].cant++;
						if(AMOSTV.players[playerIndex].cant == AMOSTV.players[playerIndex].playlists.length)						
						{
							if(self.loadCheckout == true)
							{
								AMOSTV.players[self.currPlayer].positions.curr = 0;
								self.googleCheckout();
								AMOSTV.stopLoading();
							}
						}
                    });
                }
            };
            var counter = 0;
			loadTheRest();
        });
    },
    
    // preload the first video in a playlist
    loadPlaylist: function(playerIndex, playlistIndex, callback) {
        // retrieve first video in playlist
        var self = this;
        Brightcove.getVideoById(
            AMOSTV.players[playerIndex].playlists[playlistIndex].videoIds[0]
        , function(playlist){
            
            // store retrieved data at position 0 in a new array in the player storage
            AMOSTV.players[playerIndex].playlists[playlistIndex].videos = [playlist];                       
            
            // called when current playlist has finished loading
            var objectLoaded = function() {
                
                // loading complete, remember loaded, and call callback
                AMOSTV.players[playerIndex].playlists[playlistIndex].loaded = true;
                if ( callback ) {
                    callback(playlistIndex);
                }
            };
            
            // if there is a preview image
            var url = AMOSTV.players[playerIndex].playlists[playlistIndex].videos[0].videoStillURL;
            if ( url ) {
                
                // preload image
                var image = new Image();
                
                // when 3 seconds pass without being cleared by image.onload
                var myTimer = setTimeout(function() {
                    // stop waiting for image to load
                    image.onload = null;
                    objectLoaded();
                }, 3000);
                
                // when image has been loaded
                image.onload = function(){
                    // clear loading timeout timer
                    clearTimeout(myTimer);
                    objectLoaded();
                };
                
                // start loading image
                image.src = url;
                
            // if there was no preview image, loading is done
            } else {
                objectLoaded();
            }
        });
    },
    
    // main entry point for showing loaded data
    show: function(self,index) 
	{
		AMOSTV.players[this.currPlayer].positions.updated = false;
		self.draw(index);
		AMOSTV.showView('List');
		AMOSTV.stopLoading();
		this.googleHighlight = 'MenuMenu';
		VIEWS.GoogleMenu.show(0);
    },
    
    // calculate previous, current, and next playlists to be shown
    setPositions: function(from) {

        AMOSTV.players[this.currPlayer].positions.updated = true;
        AMOSTV.players[this.currPlayer].positions.left = from-1;
        AMOSTV.players[this.currPlayer].positions.curr = from;
        AMOSTV.players[this.currPlayer].positions.right = from+1;
		
		AMOSTV.players[this.currPlayer].positions.rightright = from+2;
		AMOSTV.players[this.currPlayer].positions.leftleft = from-2;
     
		if(CookieHandler.getCookieValue('amosgtv' +this.currPlayer + '' + AMOSTV.players[this.currPlayer].positions.curr) == null){
			$('playButton').className = 'preview';
		} else {
			$('playButton').className = 'fullaccess';
		}
	 


    },
    
    // display image of previous, current, and next playlist
    draw: function(index) {
        
		// placeholder.png insertion has been moved to each videostillurl check to speed the navigation up.
        /*$('prevThumb').src = 'img/osd/placeholder.png';
        $('currThumb').src = 'img/osd/placeholder.png';
        $('nextThumb').src = 'img/osd/placeholder.png';
		$('nextNextThumb').src = 'img/osd/placeholder.png';
        $('prevPrevThumb').src = 'img/osd/placeholder.png';*/
		
		
		
		if ( AMOSTV.players[this.currPlayer].playlists[index] ) 
		{
			var video = AMOSTV.players[this.currPlayer]
                .playlists[index]
                .videos[0];
				
			var img = new Image();
			img.id = index;
			if ( video.videoStillURL ) 
			{
				img.src = video.videoStillURL;
            } 
			else 
			{
				img.src = 'img/osd/placeholder.png';
			}
			img.title = AMOSTV.players[this.currPlayer].playlists[index].name;
			img.className = "cloudcarousel";
			if(this.new_car == true)
			{
				jQuery("#List #carousel_"+this.currPlayer).append(img);
				this.cant_thumbs++;
			}
			
            $('prevPrev').show();
        }
		jQuery("#prev").css({display:"none"});	
		jQuery("#next").css({display:"none"});	
		jQuery("#prevPrev").css({display:"none"});	
		jQuery("#nextNext").css({display:"none"});	
		jQuery("#curr").css({display:"none"});	
		
		if(AMOSTV.players[this.currPlayer].cant == AMOSTV.players[this.currPlayer].playlists.length-1)						
		{
			var that = this;
			if(this.new_car == true)
			{
				jQuery("#List #carousel_"+this.currPlayer).CloudCarousel(		
						{			
							reflHeight: 56,
							reflGap:2,
							buttonLeft: jQuery('#prevArrow'),
							buttonRight: jQuery('#nextArrow'),
							titleBox:jQuery('#label span'),
							yRadius:150,
							xPos: 640,
							yPos: 300,
							speed:0.10,
							mouseWheel:true,
							bringToFront:false
						}
					);	
					jQuery("#List #carousel_"+this.currPlayer+" img").each(function(index)
					{
						jQuery(this).click(function()
						{
							that.playListChoosen(this.id);
						});
					});
					
			}
			jQuery("#List #carousel_"+this.currPlayer).css("display","block");
			
				
		}
		
		
		
    },
	
	//add opacity to the thumbs and add focus to google checkout button
	addOpacityToThumbs: function(){
		$('prev').addClassName('opac');
		$('next').addClassName('opac');
		$('curr').addClassName('opac');
		$('nextNext').addClassName('opac');
		$('prevPrev').addClassName('opac');
		$('descriptionImage').addClassName('opac');
		$('googleCheckoutButton').addClassName('focused');
		this.menuPos = "googleCheckoutButton";
	},
	
	//removes opacity and sets focus on thumbs
	removeOpacityOnThumbs: function(){
		$('prev').removeClassName('opac');
		$('next').removeClassName('opac');
		$('curr').removeClassName('opac');
		$('nextNext').removeClassName('opac');
		$('prevPrev').removeClassName('opac');
		$('descriptionImage').removeClassName('opac');
		this.menuType = "thumbsMenu";
		$(this.menuPos).removeClassName("focused");
	},
	
	//removes focus on the old highlighted button and highlight the new one
	setMenuPos: function(prevPos, previewPos) {
		$(prevPos).removeClassName("focused");
		this.menuPos = previewPos;
		var menuItem = $(previewPos);
		menuItem.addClassName("focused");
		DOUT('Menupos: ' + this.menuPos);
	},
	
	googleCheckout: function() 
	{
		AMOSTV.loadView('GoogleCheckout', { playerIndex: this.currPlayer });
		$('List').hide();
	},
	
	//when a user choose a playlist from the list
	playListChoosen: function(currThumb) {
		this.thethumb = currThumb;
		AMOSTV.players[this.currPlayer].positions.curr = currThumb;
		if(document.cookie.indexOf('amosgtv') == -1){
			this.menuType = "previewMenu";
			$('listBackButton').hide();
			$('previewVideoArea').className = '';
			$('previewGoogle').show();
			$('previewOverlay').hide();
			this.addOpacityToThumbs();		
			createFlashPlayer("818965027001", 
			AMOSTV.players[this.currPlayer].playlists[currThumb].videos[0].id, 
			"previewVideoArea","googlePreview");
			AMOSTV.startLoading();
		} else { //a cookie with the playerid and playerlist has been found let's load play view
			AMOSTV.loadView('Play', { playerIndex: this.currPlayer });
		}
		pauseImages();
	},
	
	/*googleSubmitForm: function() {
		brightcove.removeExperience("googlePreview");
		$('googleCheckoutContainer').hide();
		this.menuType = "checkoutDoneMenu";
		this.setMenuPos(this.menuPos, "checkoutDoneWatchNow");
		
		var cookieName = "googleCheckoutAmos"+this.currPlayer+""+AMOSTV.players[this.currPlayer].positions.curr;
		var cookieValue = "?token--"+this.token;
		CookieHandler.setCookie(cookieName, cookieValue);
		$('BB_BuyButtonForm').submit();
	},
	
	googleCheckoutBack: function(){
		//brightcove.removeExperience("googlePreview");
		$('googleCheckoutContainer').hide();
		this.removeOpacityOnThumbs();
		$('listBackButton').show();
		$('previewGoogle').hide();
	},*/
	
	mouseClicked: function(buttonClicked){
		switch(buttonClicked){
		
			case "prevThumb":
			case "prevArrow":
				if(this.menuType == "thumbsMenu" ){
					this.move('left');
				}
			break;
			
			case "nextThumb":
			case "nextArrow":
				if(this.menuType == "thumbsMenu" ){
					this.move('right');
				}
			break;
			
			case "currThumb":
            case "playButton":
				if(this.menuType == "thumbsMenu" ){
					this.playListChoosen();
				}
			break;
			
			case "listBackButton":
				this.setMenuPos(this.menuPos, "curr");
				AMOSTV.loadView('Menu');
			break;
			
			case "googleCheckoutButton":
				this.googleCheckout();
				AMOSTV.stopLoading();
			break;
			
			case "googleCheckoutBackButton":
                // Internet Explorer 8 fix
                if (navigator.userAgent.indexOf("MSIE 8.0") != -1)
                    $('googlePreview').remove();
                
				brightcove.removeExperience("googlePreview");
				this.removeOpacityOnThumbs();
				$('listBackButton').show();
				$('previewGoogle').hide();
				AMOSTV.stopLoading();
				moveImages();
			break;
			
			/*case "checkoutCheckout":
				this.googleSubmitForm();
			break;
			
			case "checkoutBack":
				this.googleCheckoutBack();
			break;*/
		}	
	}, 
	
	mouseOver: function(buttonHovered)
	{
		if(buttonHovered.indexOf('Thumb') != -1 || jQuery("#"+buttonHovered).attr("class") == "carousel" || jQuery("#"+buttonHovered).attr("class") == "cloudcarousel"){
			if(this.menuType == "thumbsMenu" ){
				$(this.menuPos).removeClassName("focused");
				this.menuPos = "curr";
				$('playButton').show();
				$('prevArrow').show();
				$('nextArrow').show();
			}
		} else if(buttonHovered.indexOf('listBackButton') != -1){
			if(this.menuType == "thumbsMenu" ){
				$('playButton').hide();
				$('prevArrow').hide();
				$('nextArrow').hide();
				this.setMenuPos(this.menuPos, "listBackButton");
			}
		} else if(buttonHovered.indexOf('googleCheckoutBackButton') != -1){
			this.setMenuPos(this.menuPos, "googleCheckoutBackButton");
		} else if(buttonHovered.indexOf('googleCheckoutButton') != -1){
			this.setMenuPos(this.menuPos, "googleCheckoutButton");
		} /*else if(buttonHovered.indexOf('checkoutCheckout') != -1){
			this.setMenuPos(this.menuPos, "checkoutCheckout");
		} else if(buttonHovered.indexOf('checkoutBack') != -1){
			this.setMenuPos(this.menuPos, "checkoutBack");
		}*/
	},
	
	keyHandlerOnLoading: function(key){
		/*if(this.menuType == "previewMenu"){
			if(key == KEYS.OK){
				AMOSTV.stopLoading();
			}
			this.keyHandler(key);
		}*/
	}
};


