var previously_selected_item = '';
var page = 1, maxpage = 0, amount_col = -1, amount_row = -1;
var debug = 0;
var current_selected_picture_id = -1;
var has_been_warned = false;
var slideshow_active = false, slideshow_active_on_next_page = false;
var slideshow_timeout = 5000;
var slideshow_timeout_container = null;
var select_last_pic_at_new_page = false;

function xmlhttpPost(divName,ifile)
{
  if ( debug ) alert( "xmlhttpPost('"+divName+"', '"+ifile+"');" );

  var xmlHttpReq = false;
  if (window.XMLHttpRequest) // Mozilla/Safari
  {
    xmlHttpReq = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) // IE
  {
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else
  {
    if ( !has_been_warned )
      alert( "Your browser is not AJAX compatible!" );

    has_been_warned = true;

    return;
  }
  
  xmlHttpReq.open('POST', divName + ".php", true);
  xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttpReq.onreadystatechange =
    function()
    {
      if (xmlHttpReq.readyState == 4)
      {
        updatepage(divName, xmlHttpReq.responseText);
      }
    }
  xmlHttpReq.send(getquerystring(ifile));
}


function get_child_node_with_name( parent, tagName )
{
  tagName = tagName.toLowerCase();

  for ( var child = parent.firstChild; child; child = child.nextSibling )
  {
    if ( child.tagName && child.tagName.toLowerCase() == tagName )
      return child;
  }

  return null;
}


function refresh(linkName, ifile, automatic)
{
  if ( debug )
    alert( "refresh('"+linkName+"', '"+ifile+"');" );

  if ( !automatic )
    stop_slideshow();

  var obj = document.getElementById(linkName);
  if ( !obj || obj.className == 'redcellborder' )
    return;

  obj.className   = 'redcellborder';
  obj.onmouseover = 'null';
  obj.onmouseout  = 'null';

  xmlhttpPost( 'photo_container', ifile );

  if ( previously_selected_item != '' && previously_selected_item != linkName )
  {
    obj = document.getElementById(previously_selected_item);

    if ( obj )
    {
      obj.className   = 'cellborder';
      obj.onmouseover = function() { this.className='cellover'; } ;
      obj.onmouseout  = function() { this.className='cellborder'; } ;
    }
  }
  previously_selected_item = linkName;

  if ( linkName.substr(0, 2) == 'a_' )
  {
    current_selected_picture_id = parseInt(linkName.substr(2), 10);

    if ( isNaN(current_selected_picture_id) )
      current_selected_picture_id = -1;
  }

  preload_around(current_selected_picture_id);
}

function getquerystring(ifile)
{
  if ( debug ) alert( "getquerystring('"+ifile+"');" );

  qstr = 'ifile=' + escape(ifile) + '&page=' + page + '&category=' + escape(category);  // NOTE: no '?' before querystring
  return qstr;
}

function nextpage()
{
  if ( debug ) alert('nextpage');

  if ( slideshow_active )
  {
    stop_slideshow();
    slideshow_active_on_next_page = true;
  }

  page++;
  firstLoad();
}

function prevpage()
{
  if ( debug ) alert('prevpage');

  if ( slideshow_active )
  {
    stop_slideshow();
    slideshow_active_on_next_page = true;
  }

  page--;
  firstLoad();
}

function firstpage()
{
  if ( debug ) alert('firstpage');

  if ( slideshow_active )
  {
    stop_slideshow();
    slideshow_active_on_next_page = true;
  }

  page = 1;
  firstLoad();
}

function lastpage()
{
  if ( debug ) alert('lastpage');

  if ( slideshow_active )
  {
    stop_slideshow();
    slideshow_active_on_next_page = true;
  }

  page = maxpage;
  firstLoad();
}

function firstLoad()
{
  if ( debug ) alert('firstLoad');

  xmlhttpPost( 'thumb_container', '' );
}

function previousPic(throw_on_error)
{
  if ( debug ) alert( 'previousPic' );

  try
  {
    next_selected_idx = find_previous_selected_index(current_selected_picture_id);

    img = find_image_for_id(next_selected_idx);
    
    refresh( 'a_' + next_selected_idx, img, true );
  }
  catch( e )
  {
    
    if ( e instanceof RangeError )
    { // no pictures...
    }
    else if ( page > 1 )
    { // last page
      select_last_pic_at_new_page = true;
      prevpage();
    }
    else
    {
      select_last_pic_at_new_page = true;
      lastpage();
    }

    if ( throw_on_error )
      throw e;
  }
}

function nextPic(throw_on_error)
{
  if ( debug ) alert( 'nextPic' );

  try
  {
    next_selected_idx = find_next_selected_index(current_selected_picture_id);

    img = find_image_for_id(next_selected_idx);
    
    refresh( 'a_' + next_selected_idx, img, true );
  }
  catch( e )
  {
    
    if ( e instanceof RangeError )
    { // no pictures...
    }
    else if ( page != maxpage )
    { // last page
      nextpage();
    }
    else
    {
      firstpage();
    }

    if ( throw_on_error )
      throw e;
  }
}

function updatepage(divName, str)
{
  if ( divName == 'thumb_container' )
  {
  	var data = str.split('|', 5);
  	if ( data.length != 5 )
  	{
  		alert( 'Invalid AJAX return!' );
  		return;
  	}
    
    amount_col = data[0];
    amount_row = data[1];
    maxpage    = data[2];
    page       = data[3];
    str 			 = data[4];
  }


  if ( debug )
    alert( "divName: " + divName + "\nstr: " + str );

  document.getElementById(divName).innerHTML = str;


  if ( divName == 'thumb_container' )
  {
    if ( debug )
    {
      alert(
             'slideshow_active_on_next_page: ' + (slideshow_active_on_next_page ? 1 : 0) + '\n' +
             'select_last_pic_at_new_page: ' + (select_last_pic_at_new_page ? 1 : 0) + '\n' +
             'slideshow_active: ' + (slideshow_active ? 1 : 0) + '\n' +
             'current_selected_picture_id: ' + current_selected_picture_id
           );
    }
    
    current_selected_picture_id = -1;

    if ( slideshow_active_on_next_page )
    {
      slideshow_active_on_next_page = false;
      start_slideshow();
    }
    else if ( select_last_pic_at_new_page )
    {
      select_last_pic_at_new_page = false;
      try
      {
        var idx = find_last_index();
        var img = find_image_for_id(idx);
        if ( img != '' )
          refresh( 'a_' + idx, img, true );
      } catch( e ) { }
    }
    
    if ( current_selected_picture_id == -1 )
    { // select first picture
      try
      {
        var idx = find_first_index();
        var img = find_image_for_id(idx);
        if ( img != '' )
          refresh( 'a_' + idx, img, true );
      }
      catch( e )
      {
        if ( debug )
          alert('Got error: ' + e.message + ' (' + e.name + ')');
      }
    }

  }
}

function preload_around( index )
{
  try
  {
    var nn = find_next_selected_index(index);
    var img = find_image_for_id(nn);
    if ( img != '' ) preload_image( 'category/' + category + '/photos/' + img );
  } catch( e ) { }

  try
  {
    var np = find_previous_selected_index(index);
    img = find_image_for_id(np);
    if ( img != '' ) preload_image( 'category/' + category + '/photos/' + img );
  } catch( e ) { }
}

// Pre load an image
function preload_image( img_filename )
{
  if ( img_filename == '' )
    return;

  try
  {
    var img = new Image();
        img.src = img_filename;
  } catch( e ) { }
}


function find_image_for_id( id )
{
  var obj = document.getElementById( 'a_' + id );
  if ( obj )
  {
    var img_path = obj.src;
    var pos      = img_path.lastIndexOf('/');
    if ( pos != -1 )
      img_path = img_path.substr(pos + 1, img_path.length);

    return img_path;
  }

  return '';
}


// Returns the first index with a picture
// Throws if no first image found.
function find_first_index( )
{
  var v;

  for ( var i = 0; i < (amount_col * amount_row); ++i )
  {
    v = find_image_for_id(i);
    if ( v != '' )
      return i;
  }

  throw new RangeError();
}

// Returns the last index with a picture
// Throws if no last image found.
function find_last_index( )
{
  var v;

  for ( var i = (amount_col * amount_row)-1; i >= 0; --i )
  {
    v = find_image_for_id(i);
    if ( v != '' )
      return i;
  }

  throw new RangeError();
}

// Returns next index
// Throws on page change
function find_next_selected_index( current_index )
{
  if ( current_index == -1 ) current_index = 0;

  for ( var i = current_index + 1; i < (amount_col * amount_row); ++i )
  {
    v = find_image_for_id( i );
    if ( v != '' ) return i;
  }

  if ( page <= 1 && maxpage <= 1 )
    return find_first_index();

  throw new Error("last_of_page");
}

// Returns previous index
// Throws on page change
function find_previous_selected_index( current_index )
{
  if ( current_index == -1 ) current_index = 0;

  for ( var i = current_index - 1; i >= 0; --i )
  {
    v = find_image_for_id( i );
    if ( v != '' ) return i;
  }

  if ( page <= 1 && maxpage <= 1 )
    return find_last_index();

  throw new Error("last_of_page");
}

function slide( )
{
  if ( !slideshow_active ) return;

  var next_selected_idx;
  try
  {
    nextPic(true);
    slideshow_timeout_container = setTimeout( 'slide()', slideshow_timeout );
  }
  catch( e )
  {
    
    stop_slideshow( );
    if ( e instanceof RangeError )
    { // no pictures...
    }
    else if ( page != maxpage )
    { // last page
      slideshow_active_on_next_page = true;
    }
    else
    {
      slideshow_active_on_next_page = true;
    }

    return;
  }
}

function startstop_slide( )
{
  if ( debug )
    alert( 'startstop_slide' );

  slideshow_active = !slideshow_active;
  if ( debug ) alert ( slideshow_active ? 'active' : 'non active' );
  
  if ( slideshow_active )
    start_slideshow( true );
  else
    stop_slideshow( );
}

function stop_slideshow( )
{
  if ( debug )
    alert( 'stop_slideshow' );

  slideshow_active = false;
  slideshow_active_on_next_page = false;

  if ( slideshow_timeout_container )
    clearTimeout(slideshow_timeout_container);

  var ss_activ = document.getElementById( 'slideshow_activator_image' );
  if ( ss_activ )
  {
    ss_activ.style.backgroundImage = "url('images/knopslide.gif')";
    ss_activ.style.backgroundPosition = "right -14px";
  }
}

function start_slideshow( start_now )
{
  if ( debug )
    alert( 'start_slideshow' );
  
  slideshow_active = true;

  var ss_activ = document.getElementById( 'slideshow_activator_image' );
  if ( ss_activ )
  {
    ss_activ.style.backgroundImage = "url('images/knopslideanimated.gif')";
    ss_activ.style.backgroundPosition = "right 0px";
  }	

  if ( slideshow_timeout_container )
    clearTimeout(slideshow_timeout_container);

  if ( start_now )
  {
    slide();
  }
  else
  {
    slideshow_timeout_container = setTimeout( 'slide()', slideshow_timeout );
  }
}
//-->