/**
 * ajax autoloading on page scrolling
 *
 * @requires functions.js
 * 
 */

// variables for false alarm
jQuery.extend({
    waitUpdate: 250, // wait between page scroll updates
    onUpdate: false,
    firstImage: null,
    onPage: 2,
    category: null,
    fullInfo: false,
	without: null,
    
    defaultHeight: null,
    container: null,
    
    imageRow: null,
    imageDiv: null,
    
    getScroll: function(row, div, container, cat){
	jQuery.imageRow = row;
	jQuery.imageDiv = div;
	jQuery.container = container;
	jQuery.category = parseInt(cat);
	
	jQuery.defaultHeight = parseInt($(window).height());
	jQuery.onPage = parseInt(jQuery.defaultHeight/jQuery.imageDiv);
	
	jQuery.bindScroll();
    },
    
    bindScroll: function() {
	$(window).scroll(function() {
		if(!jQuery.onUpdate && $('#gallery').length>0) {
			
			jQuery.onUpdate = true;
			var height = parseInt($(document).height());
			
			var max = height-jQuery.defaultHeight-jQuery.imageDiv/2;
			
			if($(document).scrollTop() >= max ) {
				getData(
					$(jQuery.container).children().length>0?$(jQuery.container).children().length:0,
					(jQuery.onPage)*jQuery.imageRow
				);
			} else
				jQuery.onUpdate = false;
		}
	});
    }
    
});

// write image data to page
function getData(start, count) {
	$.getJSON(
		'/modules/mod_works/ajax/title.php?count='+count+'&start='+start+'&sort='+(jQuery.category==null||isNaN(jQuery.category)?false:jQuery.category)+'&not='+(jQuery.without==null?'':jQuery.without)+'&full='+jQuery.fullInfo+rand(),
		function(data){
			if(data) {
				var html = '';
				$.each(data, function(i,item) {
					html += makeView(item)
				});
				$('#gallery').append(html);
				setTimeout("jQuery.onUpdate = false;", jQuery.waitUpdate);
			}
		}
	);
}

makeView = function(item) {
    return '<div>'+
		    '<figure>'+
			'<a href="/portfolio/work'+item.id+'.html"><img src="/images/photos/'+item.file+'" alt="'+item.name+'" /></a>'+
			'<figcaption><a href="javascript: void(0)" rel="'+item.album_id+'">'+item.album+'</a></figcaption>'+
		    '</figure>'+
		    '<dl><dt>'+(item.name!=null?item.name:'')+'</dt>'+
			'<dd>'+(item.text!=null?item.text:'')+'</dd>'+
		    '</dl>'+
		'</div>';
}
