var pagestart=0;
var pageend=0;
var gallery = null;
var pages = 0;
var path = '';
var pics = 0;
var thispage = 0;
var firstload = false;
$(document).ready(function(){
	$('.opt6').addClass('active');    
	$.ajax({
		type: "GET",
		url: 'gallery.xml',
		dataType: "xml",
		success:function(data){
		  gallery = gallery = data.firstChild;
	    path = $(gallery).attr('path');
	    pics = $(gallery).find('image').length;
	    pages = Math.ceil(pics / 6);
		  showgallery(0);
		}
	});
	
  showgallery = function(page){
    firstload = false;
    thispage = page;
	  pagestart = thispage*6;
	  pageend= thispage*6+5;
	  var firstload = 0;
	  $('#thumbnails').html('');
	  for (i=thispage*6; i<=thispage*6+5;i++){
	    showth($(gallery).find('image')[i],i);
	  }
  }

  showth = function(e,i){
    
	  th = path + $(e).attr('th');						
	  id = $(e).attr('id');
	  title = $(e).attr('title');
	  src = path + $(e).attr('src');
	  $('#thumbnails').append(' <li class="thumbnail" style="display:none" rel="'+src+'"> '
								  +'<a href="'+src+'" style="border:none;" id="im-'+id+'">'
								  +'		<img id="th-'+id+'" src="'+th+'" alt="'+title+'" /></a>'
								  +'	</li>');
	  $('a#im-'+id).click(function(){
		  var imgPath = $(this).attr('href');
		  $('#image').fadeOut(100,function(){
			  $(this).html('<img src="'+imgPath+'" />').find('img').load(function(){
				  $(this).rotateLeft(2.1);
				  $('#image').fadeIn('400');
			  });
		  });
		  return false;
	  }).children('img').load(function(){
		  var angle = Math.random()*16-8;
		  $(this).parents('li.thumbnail').fadeIn('slow');
		  $(this).rotate(angle);
	  });
	  if (! firstload ){
		  firstload = 1;
		  $('a#im-'+id).click();
	  }
  }
  $('#linkmorepictures').click(function(){
    nextpage = thispage+1;
    if (nextpage >= pages){
      nextpage = 0;
    }
    showgallery(nextpage);
    return false;
  })
});
