ps.jcarousel = {}
ps.jcarousel.initialize = function(id,scroll,itemsPerPage) {
    
   // Setup jCarousel
    
    // This sets up the external controls binds and watch behavior
    var totalJCarouselLIs;
    function jCarouselExternalSetup(carousel){
    	
		// Build the LI's for the circle pager
		// Get the count of total LI's, dividing by itemsPerPage, and rounding up
		totalJCarouselLIs = $(carousel.list[0]).children().size();
		var totalPages = Math.ceil(totalJCarouselLIs / carousel.itemsPerPage);

		// Now create the LIs
		var pagerEle = $(carousel.list[0]).parents('.jCarouselOuterWrapper').find('.jcarouselPager');
		$(pagerEle).empty();
		for (var i = 1; i <= totalPages; i++)
		{    
			pagerEle.append('<li class="page'+i+'"><a href="#page'+i+'">'+i+'</a>');
			if(i == 1){
				$('#'+id+' li.page'+i).bind('click', function(){carousel.scroll(1)});
			} else {
				$('#'+id+' li.page'+i).bind('click', function(){
					var pageNumber =  $(this).text();
					carousel.scroll( parseFloat( pageNumber * carousel.itemsPerPage - (carousel.itemsPerPage - 1) ) );
					$('#'+id+' .jcarouselPager li').removeClass('selected');
					$(this).addClass('selected');
				});			
			}
		}
		
		$(pagerEle).find('a').bind('click', function(e){e.preventDefault();});
		
    	$('#'+id+' .jCarouselLeft').bind('click', function(){
    		carousel.prev();
    		return false;
    	});
    	
    	$('#'+id+' .jCarouselRight').bind('click', function(){
    		carousel.next();
    		return false;
    	});

        var scroll_to = function(d) {
                if (d.id != id) return;
                carousel.scroll(d.pos);
        }
        ps.message.add({'carousel-scrollto': scroll_to});
        ps.message.add({'carousel-unbind': function(d) {
                if (typeof(d.id) == "undefined" || d.id == id) {
                        $(window).unbind('resize', carousel.funcResize);
                }
                ps.message.remove({'carousel-scrollto': scroll_to});
        }});
    } // end jCarouselExternalSetup()
    
    function jCarouselPageWatch(carousel, liObject, position, carouselAction){
    	
    	var currentLeft = parseFloat($(liObject).parent('.jcarousel').css('left').replace('px', ''));

    	var pageWidth = $(liObject).width();
        ['padding-right', 'padding-left', 'margin-right', 'margin-left'].forEach(function(d) {
            var fl = parseFloat($(liObject).css(d).replace('px', ''));
            pageWidth += isNaN(fl) ? 0 : fl;
         });
        pageWidth = pageWidth * carousel.itemsPerPage;


	    var page = parseFloat(-(currentLeft) / pageWidth + 1);
	    	
	    if( page == Math.ceil(page) || position == totalJCarouselLIs) {
			
			$('#'+id+' .jcarouselPager li').removeClass('selected');
			$('#'+id+' .jcarouselPager li.page'+Math.ceil(page)).addClass('selected');
				    	
	    } 

	    /*
	    // this might not be the best place to do this ... plus this functionality should already be included 
    	if(position == 1) {
    		$('#'+id+' .jCarouselLeft').addClass('disabled');
    	} else if(position == totalJCarouselLIs) {
    		$('#'+id+' .jCarouselRight').addClass('disabled');
    		$('#'+id+' .jCarouselLeft').removeClass('disabled');
    	} else {
    		$('#'+id+' .jCarouselRight').removeClass('disabled');
    		$('#'+id+' .jCarouselLeft').removeClass('disabled');
    	}
    	*/
    } // end jCarouselPageWatch() 
    
    // This sets up the actual carousel.
    jQuery('#'+id+' .jcarousel').jcarousel({
//        buttonNextHTML: '', // if this is empty callbacks won't work
//        buttonPrevHTML: '', // if this is empty callbacks won't work
        scroll: scroll,
        initCallback: jCarouselExternalSetup,
        itemVisibleInCallback: jCarouselPageWatch,
        itemsPerPage: itemsPerPage,
        
        buttonNextCallback:   jCarousel_buttonNextCallback,
        buttonPrevCallback:   jCarousel_buttonPrevCallback
        
    });
}


// call back functions for jcarousel ... 

/**
 * This is the callback function which receives notification
 * about the state of the next button.
 */
function jCarousel_buttonNextCallback(carousel, button, enabled) {
//    debug_display('Next button is now ' + (enabled ? 'enabled' : 'disabled'));
    if (enabled) {
    	$(carousel.container).parent().parent().find('.jCarouselRight').removeClass('disabled')
    } else {
    	$(carousel.container).parent().parent().find('.jCarouselRight').addClass('disabled')
    }
};

/**
 * This is the callback function which receives notification
 * about the state of the prev button.
 */
function jCarousel_buttonPrevCallback(carousel, button, enabled) {
//    debug_display('Prev button is now ' + (enabled ? 'enabled' : 'disabled'));
    if (enabled) {
    	$(carousel.container).parent().parent().find('.jCarouselLeft').removeClass('disabled')
    } else {
    	$(carousel.container).parent().parent().find('.jCarouselLeft').addClass('disabled')
    }

};

/**
 * Helper function for printing out debug messages.
 * Not needed for jCarousel.
 */
function debug_display(s) {
    // Log to Firebug (getfirebug.com) if available
    if (window.console != undefined && typeof window.console.log == 'function')
       {
       }
};

ps.peoplemover = {}
ps.peoplemover.initialize = function() {
	
	// PEOPLE MOVER for AUDIENCE MEMBERS
	var pClickCount = 0;
	function peopleMover(direction) {
			
		if (direction == 'left') {
			$('#member-scroller').animate({left: '+=85px'}, 300);
			pClickCount--;
		} else if(direction == 'right') {
			$('#member-scroller').animate({left: '-=85px'}, 300);
			pClickCount++;
		}
		
		shouldHidePMoverArrow(pClickCount);
	}
	
	function shouldHidePMoverArrow(clickCount) {
		var pMovePosition = parseFloat($('#member-scroller').css('left'));
		var pMoverTotal = $('#member-scroller').children().length;
		var pMoverEnd = (pMoverTotal - 6);
		
		if(clickCount > 0) { 
			$('#member-scroll-left').show();
			//$('#member-scroll-left').bind('click', peopleMover('left'));
		}
		if(clickCount == 0) { 
			$('#member-scroll-left').hide(); 
			//$('#member-scroll-left').unbind('click', peopleMover('left'));
		}		
		if(clickCount == pMoverEnd) { 
			$('#member-scroll-right').hide(); 
		 	//$('#member-scroll-right').unbind('click', peopleMover('right'));
		}
		if(clickCount < pMoverEnd) {
			$('#member-scroll-right').show();
		  	//$('#member-scroll-right').bind('click', peopleMover('right'));
		}
	}

	// People Mover binding
	if($('#member-scroll-wrapper').length > 0) {
	
		if($('#member-scroller').children().length > 6) { 
			$('#member-scroll-right').show() 
		} else { 
			$('#member-scroll-right').hide() 
		}
		
		$('#member-scroll-right').bind('click', function(){ peopleMover('right') } );
		$('#member-scroll-left').bind('click', function(){ peopleMover('left') } );
		
	}
}


// moved to global scope, will need to move this again for 

// Login Overlay to Lightboxing function
function loginOverlayToLightbox() {

	//quicktime plugin doesn't like the lightbox
	if (typeof(mainPlayer)!="undefined"
		&& typeof(mainPlayer.media_playing) != "undefined"
		&& typeof(mainPlayer.media_playing.media_urls.flv) == "undefined") {
		return;
	}

	// Setup Styling and show lightbox
	$('#loginOverlay').css({ left: '50%', top: '50%', margin: '-85px 0 0 -105px' });
	$('#login-lightbox').css({ height: '100%', width: '100%', position: 'fixed', top: '0px', left: '0px', 'z-index': '98', opacity: '0', display: 'block' }).fadeTo(300, 0.50);		
	
	// watch for 'off login box' clicks and shut everything down
	$('#login-lightbox').bind('click', function(){
		$(this).hide();
	});
	
	// watch for close button clicks and shut everything down
	$('#loginOverlay .close').bind('click', function() {
		$('#login-lightbox').hide()
	});
}

// rebind after_now-playing 
ps.message.add({'after_now-playing': function() {
	$('.login-link').bind('click', loginOverlayToLightbox);
	}
});

// closure

 $(document).ready(function() {

   // Setup Clicks

	// Info Links
	if($('#producer_more_text').length > 0)
	{
		$('#producer_more_link').bind('click', function(event){$('#producer_more_text').show(); $('#producer_more_close').show(); $('#producer_more_link').hide();});
		$('#producer_more_close').bind('click', function(event){$('#producer_more_text').hide(); $('#producer_more_close').hide(); $('#producer_more_link').show();});
	}
	if($('#channel_desc_text').length > 0)
	{
		$('#channel_desc_link').bind('click', function(event){$('#channel_desc_text').show()});
		$('#channel_desc_close').bind('click', function(event){$('#channel_desc_text').hide()});
	}
	
	// Sort
	if($('#show-sort').length > 0) {
		$('#sortlatest').bind('click', function(event){ sortEpisodeMedia(event, 'latest') });
		$('#sortpop').bind('click', function(event){sortEpisodeMedia(event, 'pop')});
		$('#sortrec').bind('click', function(event){sortEpisodeMedia(event, 'rec')});
		
	}

	// Login Overlay Link
	if($('.login-link').length > 0) {
		$('.login-link.close').removeClass('login-link');
		$('.login-link').bind('click', loginOverlayToLightbox);
	}
	
	// Collapsers
	if($('.toggle-box').length > 0) {
		$('.toggle-header').live('click', function(){
			$(this).next('').slideToggle(300);
			$(this).parent().toggleClass('closed');
			$(this).parent().toggleClass('open');
		});
	}
	
	// Become a Member Sidebar Items
	if($('#subscribe-to-show').length > 0) {
		$('#subscribe-to-show').bind('click', lighboxMemberCollection);
	}
	
	if($('#subscribe-to-podcast').length > 0) {
		$('#subscribe-to-podcast').bind('click', lightboxMemberItunes);
	}
	
	if($('#closeLink-Members').length > 0) {
		$('#closeLink-Members').bind('click', killLightboxMembers);	
	}
	
	// New Menu
	if($('.dropdown-link').length > 0) {
		$('.dropdown').hide();
		
		$('.dropdown-link').hover(function(){
			var dropdown = $('.dropdown-link').children('.dropdown');
			$(dropdown).show();	
		},
		
		function(){
			var dropdown = $('.dropdown-link').children('.dropdown');
			$(dropdown).hide();
		});
	}
	
	// Episode Page Image and Title toggle check
	// Had to be dropped on the page because of how TPL.js works
	 
	//  function expandNPCheck(){
	//  	if($('#nowPlayingContent').css('display') == 'none'){
	//  		$('#current-episode-comments-wrapper').slideToggle(300);
	//			$('#post-comment-form').toggle();
	//  	}
	//  }
	
	
	// Episode Sort and Collapse Binds
	if($('#nowPlayingToggle').length > 0) {
		$('#nowPlayingToggle').live('click', function(){
			$('#current-episode-comments-wrapper').slideToggle(300);
			$('#post-comment-form').toggle();
			$('#nowPlayingToggle').parents(".now-playing").toggleClass('open');
		});
		
		$('#show-sort li').live('click', function(){
			if($('#current-episode-comments-wrapper').css('display') != 'none') {
				$('#current-episode-comments-wrapper').slideToggle(300, function(){ $.scrollTo( $('#channelItemsWrapper') , 300); } );
				$('#post-comment-form').toggle();
				$('#nowPlayingToggle').parents(".now-playing").toggleClass('open');
			} else { 
				$.scrollTo( $('#channelItemsWrapper') , 300); 
			}
		});
	}
	
	// paging scrolltos
	
	if($('#channelItemsWrapper .ps-pager').length > 0) {
		
		$('#channelItemsWrapper .page-numbers a').live('click', function(){
			$.scrollTo( $('#channelItemsWrapper') , 300);
		});
		
	}
	
	// Functions
	
	function killLightboxMembers() {
		$('#overlay-becomeAMember').hide();
		$('#overlayContentWrapper').hide();
		$('#collectionResponse').hide();
		$('#itunesResponse').hide();
	}
	
	function lightboxMemberCollection(){
		$('#overlay-becomeAMember').show();
		$('#overlayContentWrapper').show();
		$('#collectionResponse').show();
		$('#subscribe-to-show').update('Subscribed');
	}
	
	function lightboxMemberItunes() {
		$('#overlay-becomeAMember').show();
		$('#overlayContentWrapper').show();
		$('#itunesResponse').show();
		$('#subscribe-to-podcast').update('Subscribed');
	}
	
/// login lightboxfunction
			
	ps.message.add({'login': function(){
    if (ps.dom.gbi('login-lightbox')){
                    ps.dom.gbi('login-lightbox').style.display = 'none';
            }
    }});

	//ps.message.add({'login': function(d){ps.tpls.render('show-subscribe', d,'show-subscribe');}});
	//ps.message.add({'login': function(d){ps.tpls.render('show-personalize', d,'personalize');}});
});


function switchText(episodeId,state,area){
	return true;
}                                      
                                
function hideFull(episodeId){
        switchText(episodeId, 'close', 'details');
                        
        if(document.getElementById('episode-comments_'+episodeId)){
                // additional comments
                ps.dom.classname.add($('#episode-comments_'+episodeId), 'hidden');
                // first comment avatar
                ps.dom.classname.add($('#comment-avatar_'+episodeId), 'hidden'); 
                // comment reply section
                ps.dom.classname.add($('#comment-new_' + episodeId), 'hidden');
        }               
        // additional episode details
        ps.dom.classname.kill($('#episode-summary_'+episodeId), 'hidden');
        ps.dom.classname.add($('#episode-full-details_'+episodeId), 'hidden');
                        
        return false;           
}                               

function showFull(episodeId){
        switchText(episodeId, 'open', 'details');
        // show this episode's details
        // additional comments
        if(document.getElementById('episode-comments_'+episodeId)){
		switchText(episodeId, 'open', 'comments');

                ps.dom.classname.kill($('#episode-comments_'+episodeId), 'hidden');
                // first comment avatar 
                ps.dom.classname.kill($('#comment-avatar_'+episodeId), 'hidden');
                // comment reply section
                ps.dom.classname.kill($('#comment-new_' + episodeId), 'hidden');
        }
        // additional episode details
        ps.dom.classname.add($('#episode-summary_'+episodeId), 'hidden');
        ps.dom.classname.kill($('#episode-full-details_'+episodeId), 'hidden');

        return false;
}

function updateNowPlaying(showName, mediaName, episodeId){
	if($('#now-playing-tag').length > 0){
		
		// Get the currently displayed array
		if(currentlySortedBy == 'latest'){
			var modeArray = sortedEpisodes.latest;
		} else if(currentlySortedBy == 'pop') {
			var modeArray = sortedEpisodes.pop;
		} else if(currentlySortedBy == 'rec') {
			var modeArray = sortedEpisodes.rec;
		}
			
		// find the image position based on the currently displayed array
		var clickedArrayPosition = null;
		
		var passedInEpisodeId = episodeId;		
		for (var i = 0; i < modeArray.length; i++)
		{    
		    var currentEpisodeID = modeArray[i].episode_id;
		    
		    if( currentEpisodeID == passedInEpisodeId) { clickedArrayPosition = i; } 
		}	
		
		var nowPlayingObject = '<div id="now-playing-tag" style="display: none;"><h3>Now Playing</h3></div>'; // the html to shuffle around (our now playing object we're about to destroy)	
		
		if ( clickedArrayPosition != null ) {
			$('#now-playing-tag').fadeOut(300);
			$('#now-playing-tag').remove(); 
			
			// now, go grab the LI with the position number of our above grabbed image and shove a now playing object in it
			$('#position'+(clickedArrayPosition + 1)).prepend(nowPlayingObject);	
			$('#now-playing-tag').fadeIn(300);
			
			
			// This scrolls the page up nice and tweeny. This doesn't work because the player action href moves you to the top. 
			//var playerOffset = $('#player-wrapper').offset();
			//$('body').animate({ scrollTop: playerOffset.top }, 700);
		}
		
		ps.dom.gbi("now-playing").innerHTML =  showName+' : '+mediaName; 
	}
}

//meh...get showid from the url, but i think it is stored in a js object somewhere, sick of looking for it
function getFromURL(varName){
  var varValue = '';
  var urlpre = String(document.location).split('?');
  if(urlpre[1]){
    var urlVars = urlpre[1].split('&');
    for (i=0; i<(urlVars.length); i++){
      if(urlVars[i]){
        var urlVarKeyVal = urlVars[i].split('=');
        if(urlVarKeyVal[0] && urlVarKeyVal[0] == varName){
                varValue = urlVarKeyVal[1];
        }
      }
    }
  }
  return varValue;
}

var showId = getFromURL('sId');

function sortEpisodeMedia(event, sortOrder){
	var orders = {latest:'latest',pop:'popular',rec:'viewed'};
	for (var i in orders) {
		if (sortOrder == i) {
			$('#sort'+i).addClass('current');
		        $('#channelItemsWrapper-'+orders[i]).show();
		} else {
			$('#sort'+i).removeClass('current');
		        $('#channelItemsWrapper-'+orders[i]).hide();
		}
	}
}


ps.message.add({'postComment': function(d){
	ps.dom.gbi('post-comment-form').style.display = 'none';
}});
ps.message.add({'postComment': function(d){
		ps.tpls.render('episode-comments.tpl', {'comment_data':d.comments}, 'current-episode-comments-wrapper');
}});

// dupe?
ps.message.add({'login': function(){
if (ps.dom.gbi('login-lightbox')){
                ps.dom.gbi('login-lightbox').style.display = 'none';
        }
}});
		
(function() {
	var registerLink = '';
	var currentShow;
	ps.actions.add(function(a, params, e) {
		a.className.match('login-link')
		&& ps.message.broadcast('post_register-action', {
			postReg: a.className.match('msg-get-notified')
				&& (currentShow = ps.tpls.get_from_globals('show'))
				&& ("getNotified-"+currentShow.id)
			});
	});
	var setShowIsNotifying = function(d) {
		if(!(currentShow = ps.tpls.get_from_globals('show'))) return;
		if(d.current_user.email_settings && d.current_user.email_settings.active_shows[currentShow.id]) {
			ps.tpls.add_to_globals('showIsNotifying', 1);
		} else {
			ps.tpls.add_to_globals('showIsNotifying', 0);
		}
	};
	ps.message.add({'before_gotNotified': setShowIsNotifying});
	ps.message.add({'before_login': setShowIsNotifying});
	ps.message.add({'getNotified': function(d) {
		if(!(currentShow = ps.tpls.get_from_globals('show'))) return;
		if(d.current_user.email_settings && d.current_user.email_settings.active_shows[currentShow.id]) {
			ps.tpls.add_to_globals('showIsNotifying', 1);
		} else {
			ps.tpls.add_to_globals('showIsNotifying', 0);
			ps.json.remote('get', {url:'/actions/shows/', vars:'format=json&showId='+currentShow.id, onsuccess:function(data) {
				if(data.shows && data.shows.email_settings) {
					d.current_user.email_settings = data.shows.email_settings;
					ps.message.broadcast('gotNotified', d);
				}
			}});
		}
	}});
	ps.actions['getNotified'] = function(a, params, e) {
		if (!['showId'].every(function(x) {return x in params}))
			return;
		params['format'] = 'json';
		ps.json.remote('get', {url: a.href.replace(/\?.*/, ''), vars: params, onsuccess: function(data) {
			if(data.shows && data.shows.email_settings) {
				var d = {current_user: ps.tpls.get_from_globals('current_user')};
				d.current_user.email_settings = data.shows.email_settings;
				ps.message.broadcast('gotNotified', d);
			}
		}});
		return true;
	};
})();
function episode_highlighter(m,highlight_id,container,seektag)
{
  var nptag = ps.dom.gbi(highlight_id);
  if (nptag) nptag.parentNode.removeChild(nptag);
  var ul = ps.dom.gbi(container);
  if (!ul) return;

  var lis = ps.dom.gbt(seektag,ul);
  var found = false;
  var index = 0;
  ps.to_array(lis).forEach(function(d){
    index++;
    var re = new RegExp("media-item-"+m.media.id);
    if (!found && re.test(d.className)) {
      found = true;
      var el = document.createElement("DIV");
      el.id = highlight_id;
      ps.dom.classname.add(el,'now-playing-highlight');
      el.innerHTML = "<h3>Now Playing</h3>";
      d.insertBefore(el,d.firstChild);
    }
  });
};
ps.message.add({'highlight-playing': function(m) { episode_highlighter(m,'now-playing-tag','episode-carousel-ul','LI'); }});
ps.message.add({'highlight-playing': function(m) { episode_highlighter(m,'episodes-now-playing','channelItems','DIV'); }});
ps.message.add({'highlight-playing': function(m) { episode_highlighter(m,'search-now-playing','searchResults','DIV'); }});
ps.message.add({play: function(m) { ps.message.broadcast('highlight-playing', m); }});