var pageNum 		= 1;
var isLoading 		= false;
var selectedIndex	=-1;
var list,node;
var speed 			= 100;//100;
var isFirst			= true;
var loadedSingle	= false;
var keyboardEnabled = false;
var lastPage		= 21;
var hasReachedFeedEnd = false;

var scrollDistanceToEndOfPageBeforeReloadShouldTrigger = 1400;

function getItemMarkup(item){
	
	var description = '';
	var dateposted 	= '';
	var title 		= '';
	var comments 	= '';
	
	
	if('title' in item){
		title 			= item.title == "" ? "Untitled" : item.title;
	}
	if(item.info != 'null'){
		description = item.info.description.replace(/\n/g, '<br/>');
		dateposted  = prettyDate(item.info.dates.posted * 1000);
		comments	= item.info.comments;
		comments 	= comments == 0 ? "" : comments == 1 ? "1 comment" : comments+" comments"; 
	};
	
	var str = 
	"<li>" +
		"<div class='image'>" +
			"<a class='imglink' href='"+item.url+"' id='"+item.id+"' title='"+item.title+"'>" +
				"<img src='"+item.src+"' title='"+item.title+"'/>" +
			"</a>" +
			"<div class='caption'>" +
				"<div class='date'>"+dateposted+"</div>"+
				"<h1><a href='#/"+item.id+"'>"+title+"</a></h1>"+
				//"<div class='tooltip'>click to leave your comments in flickr.</tooltip>"+
				"<div class='description'>"+
					"<p class='body'>"+description+"</p>"+
					"<div class='info'>"+
						"<div class='comments'><a href='"+item.url+"'>"+comments+"</a></div>"+
						//"<div class='views'>"+item.info.views+" views</div>"+
					"</div>"+
				"</div"+
			"</div>"+
		"</div>" +
	"</li>";
	//console.log(str);
	return str;
}

function onData(data){
	//console.log(data);
	$('#loader').hide();
	var output = '';
	$.each( data.photos, function(i, item){
		//console.log(item);
		if(item.photo.ispublic || item.photo.visibility.ispublic){
			output+=getItemMarkup(item);
		}
	});
	//output += ("<h1>"+pageNum+"/"+lastPage+"</h1>");
	//console.log(output);
	$('#gallery').append(output);
	list = $('.image');
	//$("img").lazyload({effect:"fadeIn"});
	//$("img").lazyload({effect:"fadeIn"});
	isLoading = false;
	if(isFirst){
		isFirst = false;
		var first = data.photos[0];
		if(first && first.info != 'null'){
			$("#lastupdated").html("last updated "+prettyDate(first.info.dates.posted * 1000));
		}
	}
	if(loadedSingle){
		var first 	= data.photos[0];
		var id 		= first.id;
		var node  	= $("#"+id);
		var back 	= "<div id='back'><a href='/photos/'>more...</a></div>"
		$.scrollTo(node.parent());
		$('#gallery').append(back);
		$(".description .body").show();
		$.address.title(node.attr('title')+" : minomawari");
	}else{
		initKeyboard();
	}
};

function appendEndMark(){
		//console.log(output);
	if(!hasReachedFeedEnd){
		hasReachedFeedEnd = true;
		$('#footer').append("<div id='endmark'>&nbsp;</div>");
	}
}

function loadMoreImages() {
	if(!isLoading){// && isFirst ){
		if(pageNum >= lastPage){
			pageNum = lastPage;
			appendEndMark();	
		}else{
			isLoading = true;
			showLoader(true);
			//if(isFirst){
			//console.log('loading...');
			$.getJSON("data.php?page="+pageNum,onData);
			//console.log('loaded');
			pageNum++;
		}
		//}
	}
}

function showLoader(value){
	//var scrolltop = $(window).scrollTop();
	//$("#loader").css({top:scrolltop,left:0});
	value ? $('#loader').show() : $('#loader').hide();
}

function loadImage(id) {
	isLoading = true;
	showLoader(true);
	$.getJSON("data.php?id="+id,onData);
}

function showNavi(){
	var str = "<div>keyboard shortcuts&nbsp;&nbsp;&nbsp;&nbsp;"+
	"descriptions:<span>d</span>"+
	"view:<span>v</span>"+
	"top:<span>h</span>"+
	"prev:<span>k</span>"+
	"next:<span class='last'>j</span></div>";
	$("#navi-top").hide();
	$("#navi-top")[0].innerHTML = str;
	$("#navi-top").delay(500).fadeIn(500);
}

function init(){
	$.address.change(function(event) {  
	     var id = String(event.value).replace("/","#");
	     if(id!=null && id.length>1 && $(id)){
		     $.scrollTo($(id).parent(),speed);
		     $.address.title($(id).attr('title')+" : minomawari");
	     }else{
	     	$.address.title('minomawari');
	     }
	});
	//$.scrollTo('html');
	var address = $.address.value();
	if(address!='/'){
		var id = address.substr(1,address.length);
		$('#navi-top').hide();
		$('.image').remove();
		loadImage(id);

		loadedSingle = true;
	}else{
		//if we write html first without doing an async call, we need the following 4 lines.
		pageNum = 2;
		showLoader(false);
		list = $('.image');
		initKeyboard();

		var lastUpdated = $(".date")[0].innerHTML;
		$("#lastupdated").html("last updated "+lastUpdated);
		showNavi();
	}
	$(document).focus();
}
	 
function initKeyboard(){
	if(!keyboardEnabled){
		$(document).keypress(function(e){
			 var code = e.keyCode;
			 if(e.keyCode==0)code=e.charCode;
			 switch( code ) {
			   case 40:
			   case 106:
			      node = list[++selectedIndex];
			      if (node) {
			        $.scrollTo( node, speed);
			      }
			      else {
			        selectedIndex = list.length-1;
			        node = list[selectedIndex];
			        //$.scrollTo($("#loader"));
			      }
			      //$("#navi-top").hide();
			      //load more images when we get close to the last one.
			      if(!loadedSingle && selectedIndex == list.length-2){
					loadMoreImages();
			      }
			      if(loadedSingle && nextImageID){
			      	loadImage(nextImageID);
			      }
			      break;
			    case 38:
			    case 107:
			       node = list[--selectedIndex];
			       if (node) {
			         $.scrollTo( node, speed);
			       }
			       else {
			          selectedIndex = -1;
			          $.scrollTo('html');
			          node = null;
			        }
			       break;
			    case 100:
			    	//$("#gallery").hide();
			    	$(".description .body").toggle();
			    	if (node) {
			         	$.scrollTo( node, speed);
			       	}
			       	//$("#gallery").show();
			    	break;
			   	case 104:
			   		 selectedIndex = -1;
			    	 $.scrollTo('html');
			    	 node = null;
			    	break;
			   	case 118:
			    	if (node) {
			    	 	var url = $(node).children('a').attr('href');
			    	 	window.location = url;
			    	}
			    	break;
			    }
		
			var id = node!=null ? $(node).children('a').attr('id') : "";
			$.address.value(id);
		});
	}
	keyboardEnabled = true;
}

$(window).scroll(function(){
	var scrolltop 	= $(window).scrollTop();
	var scrollright = $(window).scrollLeft();
	var winheight 	= $(window).height();
	var shouldLoad  = scrolltop >= $(document).height() - winheight - scrollDistanceToEndOfPageBeforeReloadShouldTrigger;
	if(loadedSingle){shouldLoad = false};
    if ( shouldLoad && !isLoading ){
       loadMoreImages();
    }
});

$( init );

