var ap_cur_page = 1 ;
var current_artist_id = 0 ; 
var max_pages = 0 ; 
var loaded = [] ; 
var first_call = true ; 

$(document).ready(function() {
	fetch_artists() ; 
	start_artist_pager_timer() ; 
	$('#artists_home_pager').mouseenter(function (){
		stop_artist_pager_timer() ; 
	}) ; 
	$('#artists_home_pager').mouseleave(function (){
		start_artist_pager_timer() ; 
	}) ;
	
	var keyframe_img = $('#iotw_overlay_image img:first').attr('src') ;
	var kimg = new Image() ; 
	$(kimg).load(function(){
		$('#iotw_keyframe_overlay').empty().append($(this)) ; 
	}).attr('src', keyframe_img) ; 
}) ;

function start_artist_pager_timer() 
{
	var times = 100 ; 
	$(document).everyTime(4000, "artist_pager", function(i) {
	  artists_pager_move_right() ; 
	}, times) ;
}

function stop_artist_pager_timer() 
{
	$(document).stopTime("artist_pager") ;
}


function artists_pager_move_left()
{
	if (ap_cur_page > 1)
	{
		ap_cur_page-- ; 
		$('#ahp_scrollable').animate({"left": "+=303px"}, "slow", function(){}) ; 
	}
}

function artists_pager_move_right() 
{	 
	if (ap_cur_page < max_pages)
	{
		ap_cur_page++ ; 
		fetch_artists() ; 
		$('#ahp_scrollable').animate({"left": "-=303px"}, "slow", function(){}) ; 
		
	}
}


function fetch_artists()
{

	var page_to_load = 0 ; 
	
	if (first_call) {
		page_to_load = 1 ; 
	}
	else {
		page_to_load = ap_cur_page + 1 ; 
	}
	
	if (loaded[page_to_load]) {
		return ;
	} 
	
	$.getJSON("/artist_pager/", {page: page_to_load},
        function(data, textStatus) 
        {
        	var html = "" ; 
        	html += '<div class="ahp_page">' ; 
        	for (var item in data)
        	{
        		var entry = data[item] ; 
        		if (entry.count_pages)
        		{
        			var scrollable_width = entry.count_pages * 303 ;
        			$('#ahp_scrollable').css('width', scrollable_width) ; 
        			max_pages = entry.count_pages ; 
        			loaded[entry.cur_page] = "ok" ;
        		}
        		else 
        		{
        			html += '\
        			<div class="ahp_artist"> \
        				<a class="fetch_link" href="/pages/interviews/'+entry.slug+'" id="ahp_'+entry.id+'" rel="'+entry.name+'">\
        					<img src="'+entry.image+'" alt="" />\
        				</a>\
        			</div>' ;  
        		}
        	} 
        	html += '</div>' ; 
        	html = $('#ahp_scrollable').html() + html ; 
        	$('#ahp_scrollable').html(html) ; 
        	
        	
        	$('.fetch_link').each(function(){
        		$(this).hover(
        			function () {
        			  $('#ahp_statusline').html($(this).attr('rel')) ; 
        			},
        			function () {
        			  $('#ahp_statusline').html('') ; 
        			}
        		) ; 
        	}) ; 
        	
        	if (first_call)
        	{
        		first_call = false ; 
        		fetch_artists() ; 
        	}
		}
    );
}

function artist_mouse_enter(sender, id)
{
	alert("mouse_enter "+id) ; 
}

function artist_mouse_leave(sender, id)
{
	
}
