var ytplayer;

var ytplaylist;

var ytplayer_index = 0;

var previous_ajax_requests = {};

var debugging = true;

$(document).ready
(
	function()
	{
		$('body > section details.profile dl.character-profile-list #character-profile').hide();

		$('body > section details.profile dl.character-profile-list dt.show-button a').live
		(
			'click',
			function(e)
			{
				e.preventDefault();

				$(this).parent().siblings('#character-profile').stop(true,true);

				$('body > section details.profile dl.character-profile-list #character-profile dl').css('opacity', 0);

				$(this).parent().siblings('#character-profile').slideToggle
				(
					500,
					function()
					{

						if ($('body > section details.profile dl.character-profile-list dt.show-button a').html() == '+ Show Character Profile')
						{
							$('body > section details.profile dl.character-profile-list dt.show-button a').html('- Hide Character Profile');

							$('body > section details.profile dl.character-profile-list #character-profile dl').css('opacity', 1);
						}
						else
						{
							$('body > section details.profile dl.character-profile-list dt.show-button a').html('+ Show Character Profile');
						}
					}
				);
			}
		);
		
        $('.ajax-load-more').bind
		(
            'click',
            function(e)
            {
                e.preventDefault();
                
                debug('loading more '+$(this).parent().attr('data')+' posts, older than ID = '+$(this).attr('data'))
            
		        // bind form to form plugin instance and post data
                previous_ajax_requests.tv = $.ajax
                (
                	{
                        type: 'POST',
                        
                		url: usAjax.url,
                		
                		data:
                		{
                            action : 'load-more',
                            
                            page : 'tv',
                     
                            // send the nonce along with the request
                            nonce : usAjax.nonce,
                            
                            emotion : $(this).parent().attr('data'),
                            
                            // load-more buttons keep track of the current offset index in their data attribute
                            start : $(this).attr('data')
                        },
                        
                        context: $(this).parent(),
    
    			        cache: false,
                
                		dataType: 'json',
                
                		success: $.ajaxLoaded,
                
                		error: $.errorWarning,
                		
                		complete: $.ajaxComplete
                	}
                );
            }		
		);

		$.abortPreviousAjaxRequests = function(field)
		{
			if (field == 'all')
			{
				for (var f in previous_ajax_requests)
				{
					if (typeof previous_ajax_requests[f].abort == 'function')
					{
						previous_ajax_requests[f].abort();
					}
				}
			}
			else
			{
				if (previous_ajax_requests[field] != undefined)
				{
					if (typeof previous_ajax_requests[field].abort == 'function')
					{
						previous_ajax_requests[field].abort();
					}
				}
			}
		}
		
		$.ajaxErrorWarning = function(XMLHttpRequestObject, textStatus, errorThrown)
        {
        	debug('XMLHttpRequestObject:'+XMLHttpRequestObject.responseText);
        
        	debug('errorstatus:'+textStatus);
        
        	debug('errorthrown:'+errorThrown);
        }
        
        $.ajaxLoaded = function(response, textStatus, XMLHttpRequest)
        {
            debug('ajaxloaded for page:'+response.page);
            
            debug('response:'+response.message);
        
        	debug('status:'+textStatus);
        	
        	debug('end:'+response.end);
        	
        	switch (response.page)
        	{
                case 'tv':

                    var v = false;
                    
                    var emotion = $(this).attr('data');
                    
                    for (var i in response.message)
                    {
                        v = response.message[i];

                        $(this).before
                        (
                            '<li class="tv-playlist-thumb" id="'+v.clip_id+'"><a class="play-clip" data="'+v.ID+'" href="tv/#p_'+v.ID+'" title="'+v.post_title+'"><img src="http://img.youtube.com/vi/'+v.clip_id+'/2.jpg" /><img src="http://img.youtube.com/vi/'+v.clip_id+'/3.jpg" /></a><hgroup><h2><a rel="bookmark" href="'+v.permalink+'">'+v.post_title+'</a></h2><h4>posted while feeling <a class="emotion" href="filter/'+emotion+'" title="view all posts made while feeling '+emotion+'">'+emotion+'</a></h4></hgroup></li>'
                        );
                    }
        	        
        	        if (response.end)
        	        {
        	            $('.ajax-load-more', this).hide();
        	        }
        	        else if (v)
        	        {
                        $('.ajax-load-more', this).show().attr('data', v.ID);
                    }
        	       
                break;
        	}
        }
        
        $.ajaxComplete = function()
        {
            //$.resetMoreButton();
            debug('ajax complete');
        }


	}

);

function onYouTubePlayerReady(playerId)
{
	debug('player ready:'+playerId);
	
	ytplayer = document.getElementById(playerId);
	
	//debug('player ready:'+ytplayer);
    
    initYouTubePlaylist();
    
    if (ytplayer)
    {
        ytplayer.addEventListener("onStateChange", "onYouTubePlayerStateChange");
      
        ytplayer.addEventListener("onError", "onYoutubePlayerError");
      
        $('#play-next-clip a').bind
        (
            'click',
            function(e)
            {
                e.preventDefault();
                
                e.stopPropagation();
                
                ytPlaylistPlayNextClip();
            }
		);
		
		$('#play-prev-clip a').bind
        (
            'click',
            function(e)
            {
                e.preventDefault();
                
                e.stopPropagation();
                
                ytPlaylistPlayPrevClip();
            }
		);
		
		$(window).bind
		(
		    'keyup',
		    function(e)
		    {
		        debug(e.keyCode);
		        
		        switch(e.keyCode)
		        {
		        case 80:
		        case 37:
                    ytPlaylistPlayPrevClip();
                break;
                case 78:
                case 39:
                    ytPlaylistPlayNextClip();
                break;
		        }
		    }
        );
    }
}

function hideNavButtons()
{
    $('#play-prev-clip a').hide();
    $('#play-next-clip a').hide();
}

function hideNavButtons()
{
    $('#play-prev-clip a').show();
    $('#play-next-clip a').show();
}

function initYouTubePlaylist()
{
	ytplaylist = [];
	
	ytplayer_index = 0;
	
	var counter = 0;
	
	var start_index;
	
	$('#tv-playlist li').each
	(
		function()
		{
			if ($(this).attr('class') == 'current_player_index')
			{
				start_index = true;
				
				ytplayer_index = counter;
			}
			
			debug($(this).attr('id'));
			
			clip = {id: $(this).attr('id'), start: start_index};
			
			ytplaylist.push(clip);
			
			counter++;
		}
	);
	
	debug(ytplaylist);
	
	ytPlaylistPlayClipById('u5um8QWWRvo');
}

function onYouTubePlayerStateChange(newState)
{
	debug('player state:'+newState);
	//debug(ytplayer);
	//debug(this);
	   
	//debug(e.srcElement+':'+e.target)
	//if (state == -1){ ytplayer.loadVideoById('mKe3QKcta-8');}
	
	if (newState == 1)
	{
	   lightsDown();
	}
	
	switch (newState)
	{
		case 0:
		
			debug('playing next');
		
			ytPlaylistPlayNextClip();
			
		break;
		case 2:
		
            lightsUp();
		
		break;
		case 5:
		
			ytplayer.playVideo();
			
		break;
	}
}

function lightsDown()
{
    if ($('#lights-down-blind').length == 0)
    {
        $('body').prepend('<div id="lights-down-blind" style="height:'+ $(document).height() +'px; width:'+ $(document).width() +'px;"></div>');
    }
}

function lightsUp()
{
    $('#lights-down-blind').remove();
}

function ytPlaylistPlayNextClip()
{
	ytplayer_index++;
			
	ytplayer_index %= ytplaylist.length;
	
	ytplayer.cueVideoById(ytplaylist[ytplayer_index].id);
}

function ytPlaylistPlayPrevClip(id)
{
	ytplayer_index--;
			
	ytplayer_index = (ytplayer_index < 0)? ytplaylist.length - 1 : ytplayer_index;
	
	ytplayer.cueVideoById(ytplaylist[ytplayer_index].id);
}

function ytPlaylistPlayClipById(id)
{
	var counter = 0;
	
	$.each
	(
		ytplaylist,
		
		function(index, value)
		{
			if (value.id == id)
			{
				ytplayer_index = counter;
				
				debug(value.id); 
				
				counter++;
			}
		}
	);
	
	debug('playing by id:'+ytplaylist[ytplayer_index].id)
	
	ytplayer.cueVideoById(ytplaylist[ytplayer_index].id);
}

function ytPlaylistPlayClipByIndex(index)
{
	ytplayer_index = index;
	
	ytplayer.cueVideoById(ytplaylist[index]);
}

function onYouTubePlayerError(error)
{
	debug('Error:'+error);
}

// ===========================================================

function renderMap(lat, lon, zoom, post_id, scrollwheel_enabled)
{
    var latlon = new google.maps.LatLng(lat, lon);
    
    var myOptions =
    {
    	zoom: zoom,
    	center: latlon,
    	mapTypeId: google.maps.MapTypeId.SATELLITE,
    	streetViewControl: true,
    	scrollwheel: scrollwheel_enabled
    };
    
    var map = new google.maps.Map(document.getElementById('map-canvas'+post_id), myOptions);
    
    google.maps.event.addListener
    (
        map,
        'click',
        function()
        {
            map.setOptions({scrollwheel: true});
        }
    );
    
    google.maps.event.addListener
    (
        map,
        'zoom_changed',
        function()
        {
            if (this.getZoom() < 3) this.setZoom(3);
        }
    ); 
    
    return map;
}

function add_marker(lat, lon, title, map)
{
    var latlon = new google.maps.LatLng(lat, lon);
    
    var marker = new google.maps.Marker({
    	position: latlon,
    	map: map,
    	title: title
    });
}

function add_custom_marker(lat, lon, title, map, icon, shadow)
{
    var latlon = new google.maps.LatLng(lat, lon);
    
    var marker = new google.maps.Marker({
    	position: latlon,
    	map: map,
    	title: title,
    	icon: icon,
    	shadow: shadow
    });
}

function add_info_window(map, marker, title)
{
    var infowindow = new google.maps.InfoWindow({
        content: title
    });
    
    google.maps.event.addListener
    (
        marker,
        'click',
        function()
        {
            infowindow.open(map,marker);
        }
    );
}

function show_streetview(post_id)
{
    var panoramaOptions =
    {
        position: latlon,
        pov: 
        {
            heading: 34,
            pitch: 10,
            zoom: 1
        }
    };
    
    var panorama = new  google.maps.StreetViewPanorama(document.getElementById('sv-canvas'+post_id), panoramaOptions);
    
    map.setStreetView(panorama);
}

function checkScrollBottom()
{
    return ($(document).scrollTop() + $(window).height() >= $(document).height());
}

function debug(msg)
{
	if (debugging)
	{
		if ((typeof console) == 'object')
		{
			// use firebug for debug output
			console.log(msg);
		}
		else
		{
			if ($('body #debugger').length < 1)
			{
				$('body').append('<div class="debugger"> </div>');
			}

			$('body #debugger').append('<p class="debug message">'+msg+'</p>');
		}
	}
};
