var KEY_SPACE 	= 32,
	KEY_PAGEUP 	= 33,
	KEY_PAGEDOWN = 34,
	KEY_END 	= 35,
	KEY_HOME 	= 36,
	KEY_LEFT 	= 37,
	KEY_UP 		= 38,
	KEY_RIGHT 	= 39,
	KEY_DOWN 	= 40,
	KEY_F 		= 70,
	KEY_J 		= 74,
	KEY_K 		= 75,
	KEY_W 		= 87,
	KEY_F11 	= 122;
	
t_want_to_hide = 0;
t_want_to_hide_again = 0;
t_minislide = 0;
t_throbber = 0;
allow_hide = true;
opac_scroller = t_scroller = 0;
t_scroller_fade_in = 0;
t_scrollerindicator_fade_in = 0;
t_scrollerindicator_fade_out = 0;
count_viewphoto = 0;
done_loading = false;

function is_touch_device() {  
	try {  
		document.createEvent("TouchEvent");  
		return true;  
	} catch (e) {  
		return false;  
	}  
}

hide_fixed_els = is_touch_device();

$(function() {

	// hide fixed-at-bottom elements from touch-scoll devices
	if (hide_fixed_els) {
		$('.softbottom, #scroller, #scrollerindicator, #scrollerindicator span').hide();
	}
	
	// hide scrollbars?
	if ($('.viewphotoholder a').length > 1) {
		//$('body').css({overflowY: 'hidden'});
	}
	
	function scrollDir(event, dir) {
		event.preventDefault();
		var jNearest = $('.viewphotoholder a img').nearestTo( $(window).scrollTop() );
		var currentPicture = parseInt( jNearest.attr('id').replace('img', '') );
		scrollToPic(parseInt(currentPicture + dir));
	}

	function scrollToPic(nr) {
		clearTimeout(t_scrollerindicator_fade_out);
		if (!hide_fixed_els) { $('#scrollerindicator').show(); }
		$('#img'+nr).centerInView({marginTop: (hide_fixed_els ? 0 : 44) 
			/*, onAfter: function() { 
			t_scrollerindicator_fade_out = setTimeout(function() {
				//document.title = 'hiding';
				$('#scrollerindicator').fadeOut();
			}, 1000)
		}*/
		 });
	}

	
	if ($('.viewphotoholder a').length > 1) {
		// smooth scroll to next photo
		$('.viewphotoholder a').click(function(event) {
			if (!event.ctrlKey) {
				event.preventDefault();
				var hash = this.href.split('#')[1];
				if (typeof hash === 'undefined' || !hash.length) {
					hash = 'img0';
				}
				scrollToPic(hash.replace('img', ''));
			}
		});

		// handle keypress
		$(document).keydown( handleKeyDown);
		$(document).keyup( handleKeyUp);
	}
	
	function handleKeyUp(event) {
		var k = event.which;
		var t = document.activeElement.tagName.toLowerCase();
		var noSpecialKeysPressed = !event.ctrlKey && !event.shiftKey && !event.altKey;

		// voorkom conflict met alt-left/right browser history navigatie
		// en tikken in inputvelden
		if (t == 'textarea' || t == 'input' || event.altKey || event.ctrlKey) {
			return;
		}
		
		// deactiveer scrollbar na klik op up/down-pijltjestoets in fullscreen mode
		if (noSpecialKeysPressed && (k == KEY_DOWN || k == KEY_UP )) {
			//$(document.body).css('overflowY', 'hidden');
		}
		
		// shift-spacebar, page up, k
		if (((k == KEY_SPACE && event.shiftKey) || (noSpecialKeysPressed && (k == KEY_PAGEUP || k == KEY_K)))) {
			scrollDir(event, -1);
			//document.title = 'up';
			//scrollToPic(1);

		// regular spacebar, page down, j
		} else if (noSpecialKeysPressed && (k == KEY_SPACE || k == KEY_PAGEDOWN || k == KEY_J)) {
			scrollDir(event, 1);
			//document.title = 'down';
		}
	} // handleKeyUp



	function handleKeyDown(event) {
		var k = event.which;
		var t = document.activeElement.tagName.toLowerCase(); 
		var noSpecialKeysPressed = !event.ctrlKey && !event.shiftKey && !event.altKey;

		if (t == 'textarea' || t == 'input') {
			return;
		}
		
		// klik op up/down pijltjestoetsen: toon scrollbar voor handmatige scroll
		if ((k == KEY_UP || k == KEY_DOWN) && noSpecialKeysPressed) {
			//clearTimeout(window.scrollTimer); # todo
			//$(document.body).css('overflowY', 'scroll');
		}

		if ((k == KEY_HOME || k == KEY_END) && noSpecialKeysPressed) {
			//clearTimeout(window.scrollTimer);
		}

		// klik op home: smooth scroll naar 0
		if (k == KEY_HOME && noSpecialKeysPressed) {
			scrollToPic(0);
			event.preventDefault();	
			return;
		}

		// klik op end: smooth scroll naar laatste foto
		else if (k == KEY_END && noSpecialKeysPressed) {
			scrollToPic($('.viewphotoholder a img').length - 1)
			event.preventDefault();	
			return;
		}
		
		// afvangen klik op spatiebalk en pageup/down: voorkom standaard scrollactie
		// shift-spacebar, pageup
		if (((k == KEY_SPACE && event.shiftKey) || (k == KEY_PAGEUP && noSpecialKeysPressed))) {
			event.preventDefault();
		}

		// spacebar, pagedown
		if (((k == KEY_SPACE && noSpecialKeysPressed) || (k == KEY_PAGEDOWN && noSpecialKeysPressed))) {
			event.preventDefault();
		}

	}	// handleKeyDown
	

});



function hide_scroller()
{
  $('#scroller').hide();
  if (el_scrollerindicator = document.getElementById('scrollerindicator'))
  {
    el_scrollerindicator.style.display = 'block';

    // fade in scrollerindicator ( . . . in lower-left)
    if (!t_scrollerindicator_fade_in)
    {
      opac_scrollerindicator = 0;
      clearTimeout(t_scrollerindicator_fade_in);
      el_scrollerindicator.style.opacity = opac_scrollerindicator;

      t_scrollerindicator_fade_in = setInterval(function() {
        if (opac_scrollerindicator < 1) { opac_scrollerindicator += .1; }
        else { clearTimeout(t_scrollerindicator_fade_in); t_scrollerindicator_fade_in = 0; }
        el_scrollerindicator.style.opacity = opac_scrollerindicator;
        }, 25);
    }
  }
}

function show_scroller()
{
  document.getElementById('scroller').style.display = 'block';

  // fade in scroller
  if (!t_scroller_fade_in)
  {
    opac_scroller = 0;
    clearTimeout(t_scroller_fade_in);
    document.getElementById('scroller').style.opacity = opac_scroller;

    t_scroller_fade_in = setInterval(function() {
      if (opac_scroller < 1) { opac_scroller += .15; }
      else { clearTimeout(t_scroller_fade_in); t_scroller_fade_in = 0; }
      document.getElementById('scroller').style.opacity = opac_scroller;
      }, 25);
  }
  
  // hide . . . dots in lower-left
  if (el_scrollerindicator = document.getElementById('scrollerindicator'))
  {
    el_scrollerindicator.style.display = 'none';
  }
}

function want_to_hide() {
  if (allow_hide) { hide_scroller(); }
}

function align_scroller()
{
  // adjust position of scroller if there is space for it to fit below the single photo view
  el_scroller = document.getElementById('scroller');
  el_scrollerindicator = document.getElementById('scrollerindicator');
  if (count_viewphoto == 1 && el_scroller)
  {
    // vertical position
    img_edge = document.getElementById('img0').offsetTop + document.getElementById('img0').height;
    gap_height = window.innerHeight - img_edge;
    scroller_height = 2 + el_scroller.offsetHeight;
    if (gap_height > scroller_height)
    {
      el_scroller.style.bottom = (gap_height - scroller_height) + 'px';
    }
    else if (false && gap_height > 0) /* test */
    {
      el_scroller.style.bottom = gap_height + 'px';
    }
    else
    {
      el_scroller.style.bottom = 0 + 'px';
    }
  }
  
  // horizontal position
  if (el_scroller)
  {
    if (window.innerWidth < 1024)
    {
      el_scroller.style.marginLeft = (15 + Math.floor(-.5 * window.innerWidth)) + 'px';
    }
    else
    {
      el_scroller.style.marginLeft = '-512px';
    }
  }

  if (el_scrollerindicator)
  {
    if (window.innerWidth < 1024)
    {
      el_scrollerindicator.style.marginLeft = (15 + Math.floor(-.5 * window.innerWidth)) + 'px';
    }
    else
    {
      el_scrollerindicator.style.marginLeft = '-512px';
    }
  }
}

function init() 
{
  done_loading = true;
  
  el_scroller = document.getElementById('scroller');
  el_scroller = document.getElementById('scroller');
  if (el_scroller && count_viewphoto > 1)
  {
    setTimeout(function() { hide_scroller(); el_scroller.className = 'loaded'; }, 1500);
  }

  if (window.addEventListener && (true || count_viewphoto == 1))
  {
    align_scroller();
    window.addEventListener('resize', align_scroller, false);
    window.addEventListener('mousemove', align_scroller, false);
  }
  
  if (document.getElementById('mailto'))
  {
    document.getElementById('mailto').setAttribute('href', ['gmail.com','vermeulen@',':milo','mailto'].reverse().join(''));
  }

  // set mouseover/mouseout events for minislides
  if (!hide_fixed_els && location.href.indexOf('debug') > -1)
  {  
    all_li = document.getElementsByTagName('li');
    c = 0;
    for (i = 0; i < all_li.length; i++)
    {
      if (all_li[i].className && all_li[i].className.indexOf('multiple') > -1)
      {
        all_li_alternates = all_li[i].getElementsByTagName('li');
        c += all_li_alternates.length;
        
        e_id = all_li[i].getElementsByTagName('img')[0].getAttribute('id').replace('eimg', '');
        //document.title += '' + e_id + ':';
        
        alt_src[e_id] = [];
        for (j = 0; j < all_li_alternates.length; j++)
        {
          alt_src[e_id].push(all_li_alternates[j].firstChild.getAttribute('href'));
        }
        
        el_a = all_li[i].getElementsByTagName('a')[0].parentNode; // using .parentNode to apply to <div> instead of <a>
        el_a.onmouseover = function() { 
          e_id = this.getElementsByTagName('img')[0].getAttribute('id').replace('eimg', '');
          clearTimeout(t_minislide);
          clearTimeout(t_minislide_step);
          t_minislide = setTimeout(function() { minislide(e_id); }, 1500);
          //clearTimeout(t_throbber);
          //animate_throbber(e_id, 0);
          };
        
        el_a.onmouseout = function() {
          clearTimeout(t_minislide);
          clearTimeout(t_minislide_step);
          //clearTimeout(t_throbber);
          //reset_throbber(e_id);
          //document.title = Math.random();
          };

        el_a.onclick = function() {
          clearTimeout(t_minislide);
          clearTimeout(t_minislide_step);
          };
      }
    }
    //document.title = c;
  }
  
  if (self.countviewphoto) { triggerShowScrollerText(); }

} // init


function reset_throbber(e_id)
{
  document.getElementById('throbber'+e_id).firstChild.nodeValue = '...';
}

function animate_throbber(e_id, step)
{
  el_throbber = document.getElementById('throbber'+e_id);
  dots = '.';
  for (i = 0; i < (step % 3); i++) { dots += '.'; }
  el_throbber.firstChild.nodeValue = dots;
  t_throbber = setTimeout(function() { animate_throbber(e_id, step + 1); }, 400);
}


function jiggle()
{
}

window.onload = init;




if (window.addEventListener && !hide_fixed_els)
{
  window.addEventListener('mousemove', mousemoved, false); 
}

function mousemoved(e)
{
  if (!done_loading) { return; }

  // show or hide thumbs depending on mouse proximity to bottom edge of window
  if (el_scroller = document.getElementById('scroller'))
  {
    count_thumbs = el_scroller.getElementsByTagName('img').length;
    count_thumbrows = Math.ceil(count_thumbs / 9);
    
    est_height_of_scroller = count_thumbrows * 90 + 75;
    if (self.count_viewphoto && self.count_viewphoto == 1) { est_height_of_scroller += 120; }
    
    if (count_viewphoto > 1)
    {
      do_show_thumbs = (window.innerHeight - e.clientY < est_height_of_scroller)
        && (Math.abs(e.clientX -.5 * window.innerWidth) < .5 * 1100);
      
      old_display = el_scroller.style.display;
      new_display = do_show_thumbs ? 'block' : 'none';
      if (old_display != new_display)
      {
        if (do_show_thumbs) { show_scroller(); } else { hide_scroller(); }
      }
    }
  }
  
  // hide soft bottom edge when mouse near bottom of window, so it doesn't overlap any clickable links,
  /*
  el_windowbottom = document.getElementById('windowbottom');
  old_display = el_windowbottom.style.display;
  new_display = window.innerHeight - e.clientY > 20 ? 'block' : 'none';
  if (old_display != new_display)
  {
    el_windowbottom.style.display = new_display;
  }
  */
  
}

timers = [];

function fade_el(el_id, opac, from, to, step)
{
  el = document.getElementById(el_id);
  if (!el) { return; }
  
  el.style.opacity = opac;
  
  old_opac = opac;
  if (from < to && opac < to)
  {
    opac += step;
  }
  else if (from > to && opac > to)
  {
    opac -= step;
  }
  
  if (old_opac != opac)
  {
    timers[el_id] = setTimeout(function() { fade_el(el_id, opac, from, to, step); }, 100);
  }
}


/* MINISLIDE */

t_minislide = 0;
t_minislide_step = 0;
t_fade = 0;
alt_src = [];
slidepos = [];
el_fader = document.createElement('img');

el_fader.style.opacity = 0;
el_fader.style.position = 'absolute';
el_fader.style.top = '0px';
el_fader.style.left = '2px';

function fade(e_id, opac, src_from, src_to, w, h)
{
  if (opac == 0)
  {
    document.getElementById('eimg'+e_id).parentNode.appendChild(el_fader);
    document.getElementById('eimg'+e_id).src = src_from;
    document.getElementById('eimg'+e_id).style.width = w + 'px';
    document.getElementById('eimg'+e_id).style.height = h + 'px';
    el_fader.style.width = w + 'px';
    el_fader.style.height = h + 'px';
    el_fader.src = src_to;
  }
  
  el_fader.style.opacity = .01 * opac;
  
  if (opac < 100)
  {
    t_fade = setTimeout(function() { fade(e_id, opac + 15, src_from, src_to, w, h); }, 35);
  }
  else
  {
    document.getElementById('eimg'+e_id).src = src_to;
    
    slidepos[e_id]++;
    if (slidepos[e_id] == alt_src[e_id].length) { slidepos[e_id] = 0; }
    
    wait = 4000;
    if (document.getElementsByTagName('body')[0].className.indexOf('size-l') > -1) { wait = 8000; 
      //document.title = 'waiting ' + wait;
       }
    t_minislide_step = setTimeout(function() { minislide(e_id); }, wait);
  }
}

function minislide(e_id)
{
  if (typeof slidepos[e_id] === 'undefined') { slidepos[e_id] = 1; }
  
  img_new = new Image();
  img_new.onload = function()
  {
    fade(e_id, 0, document.getElementById('eimg'+e_id).src, this.src, this.width, this.height);

    // force jump to correct big #img3 subphoto when clicking during minislide
    el_link = document.getElementById('elink'+e_id);
    href = el_link.getAttribute('href').split('#')[0];
    if (slidepos[e_id]) { href += '#img' + slidepos[e_id]; }
    // el_link.setAttribute('href', href); // DISABLED.. always link to top photo
  }
  img_new.src = alt_src[e_id][slidepos[e_id]];
  
  //document.title = "minisliding e_id " + e_id + " slidepos[e_id] " + slidepos[e_id]; 
}


// calc big img top positions and compare with scroll position
function triggerShowScrollerText()
{
  for (i = 0; i < count_viewphoto; i++)
  {
    if (Math.abs(document.getElementById('img'+i).offsetTop - window.pageYOffset) < 300) 
    {
      scrollertext_to_show = i;
      break;
    }
  }
  
  showScrollerText(scrollertext_to_show);
}

function showScrollerText( i_to_show )
{  
  if (count_viewphoto < 1) { return; }
  
  for (i = 0; i < count_viewphoto; i++)
  {
    // change the text shown above thumbnails in fixed scroller
    document.getElementById('scrollertext' + i).style.display = i_to_show == i ? 'block' : 'none';
    
    // change the active highlighted thumbnail in fixed scroller
    if (el_thumb = document.getElementById('scrollerthumb' + i))
    {
      if (i_to_show == i) { el_thumb.className += ' scrollerthumbactive'; }
      else { el_thumb.className = el_thumb.className.replace(/scrollerthumbactive/g, ''); }
    }

    // change the active highlighted dot, shown in lower-left when scroller is not visible
    if (!hide_fixed_els) {
		if (document.getElementById('scrollerindicator'))
		{
		  if (el_dot = document.getElementById('scrollerindicator').getElementsByTagName('span')[i])
		  {
			el_dot.className = i_to_show == i ? 'active' : '';
		  }
		}
	}
  }
} // showScrollerText


function detectMissingImg()
{
  // fix src for flickr uploads without _b.jpg version, use _o.jpg instead
  imgs = document.getElementById('content').getElementsByTagName('img');
  for (i = 0; i < imgs.length; i++)
  {
    tmp = new Image();
    tmp.orig_img = imgs[i];
    tmp.onload = function()
    {
      tmp_w = this.width;
      tmp_h = this.height;
      if (tmp_w == 500 && tmp_h == 375)  // dimensions of flickr 'not found' placeholder img
      {
        new_img = document.createElement('img');
        new_img.src = tmp.orig_img.src.replace('_b.', '_o.');
        new_img.style.maxWidth = '1024px';
        tmp.orig_img.style.display = 'none';
        tmp.orig_img.parentNode.appendChild(new_img);
      }
    };
    tmp.src = imgs[i].src;
  }
}


// adjust position of anchor jump point slightly, because of top navigation bar being in the way
setTimeout(function() {
    if (location.hash.length)
    {
      ot = document.getElementById(location.hash.replace('#', '')).offsetTop;
      scrollTo(0, ot - 44);
      triggerShowScrollerText();
    }
  }, 200);

