/*jslint browser: true */
/*extern Drupal, $, jQuery, tb_show */

/**
 * This is the derbyGallery object, mainly for namespacing purposes
 */
Drupal.derbyGallery = {
	fxInSpeed: 'slow',
	fxOutSpeed: 'fast',
	delay: '8000',
	index: 0	
};

/**
 * Initialize the gallery.  This should be re-called after any ajax loading.
 */
Drupal.derbyGallery.init = function() {
	var o = Drupal.derbyGallery;
	
	// set viewport dimensions
	o.viewportHeight = $('#viewport').height();
	o.viewportWidth = $('#viewport').width();
	
	// stop rotation in case we are re-initing
	o.rotateStop();
	o.index = 0;

	// start pre-loading images
	o.preload();
	
	// append an empty img tag into the viewport
	$('#viewport').append($('<a><img /></a>'));
	$('#viewport a').click(Drupal.derbyGallery.onViewportImageClick);
   $('#viewport .protect').css('cursor', 'pointer').click(
      function(){
         $('#viewport a').click();
      }
   );
	
	// load the first image
	o.loadImage(0);
	
	// attach the click event to the thumbnails
	$('#thumbs li>a').click(Drupal.derbyGallery.onThumbClick);
	
	$('#thumbs li a.admin').click(Drupal.derbyGallery.onAdminClick);
	
	// attach the change event to the gallery select box
	$('#galleries select').change(Drupal.derbyGallery.onGalleryChange);

	Drupal.derbyGallery.initForms();

	// start image rotation
	o.rotateStart();
};

/**
 * Load an image into the viewport, by index #.  An optional callback will be 
 * called after the image has loaded.  This function takes care of incrementing
 * the internal index, changing the src of the viewport image and href of the
 * enclosing anchor, updating the active class on the thumbnails and positioning
 * and sizing the image to the viewport.
 */
Drupal.derbyGallery.loadImage = function(index, callback) {
	index = index % $('#thumbs li').size();
	var src = $('#thumbs li:eq(' + index + ') a').href();
	
  // Load image
	var img = new Image();
	img.onload = function() {
		Drupal.derbyGallery.index = index;
		$('#thumbs li').removeClass('active').eq(index).addClass('active');
		var size = Drupal.derbyGallery.sizeToViewport(this.width, this.height, Drupal.derbyGallery.viewportWidth, Drupal.derbyGallery.viewportHeight);
		$('#viewport img').css(size).src(this.src);
		$('#viewport a').href(this.src);

		if(typeof callback == 'function') {
			callback();
		}
	};
	img.src = src;
   
  // Update credentials and purchase link
  if ($('#thumbs li:eq(' + index + ') .purchase').length > 0) {
    $('#credentials .purchase').html($('#thumbs li:eq(' + index + ') .purchase').html());
  } else {
    $('#credentials .purchase').html('');
  }
  if ($('#thumbs li:eq(' + index + ') .credit').length > 0) {
    $('#credentials .owner').html($('#thumbs li:eq(' + index + ') .credit').html());
  } else {
    $('#credentials .owner').html('CDI');
  }
};

/**
 * Return a style object for resizing an image to the viewport and centering it
 * using absolute positioning.
 */
Drupal.derbyGallery.sizeToViewport = function(imgW, imgH, viewW, viewH) {
	var h, r, w;
	if(imgH > imgW) {
		h = Math.min(imgH, viewH);
		r = h / imgH;
		w = r * imgW;
	}
	else {
		w = Math.min(imgW, viewW);
		r = w / imgW;
		h = r * imgH;
	}
	var t = (viewH - h) / 2;
	var l = (viewW - w) / 2;
	
	return { width: w, height: h, top: t, left: l};
};

/**
 * onclick handler for the thumbnails.  stops the rotation, loads the image,
 * then restarts the rotation.
 */
Drupal.derbyGallery.onThumbClick = function(e) {
	this.blur();
	var i = $('#thumbs li > a').index(this);
	Drupal.derbyGallery.rotateCancel();
	Drupal.derbyGallery.gotoIndex(i);
	//Drupal.derbyGallery.rotateStart();
	return false;
};

Drupal.derbyGallery.onAdminClick = function(e) {
	this.blur();
	
	if($(this).is('.available')) {
		$(this).addClass('unavailable').removeClass('available').html('Not available for purchase');
	}
	else{
		$(this).addClass('available').removeClass('unavailable').html('Available for purchase');
	}
	
	$.get(this.href);
	
	return false;
};

/**
 * onclick handler for the viewport image.  stops the rotation, loads the image
 * in a thickbox and registers an unload handler for thickbox, which will goto
 * the next image in the gallery and restart the rotation once the thickbox is 
 * closed.
 */
Drupal.derbyGallery.onViewportImageClick = function(e) {
	var o = Drupal.derbyGallery;
  o.rotateCancel();
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  $('#TB_window').bind('unload', 
  	function() {
  		o.gotoIndex(null);
  	}
  );
  this.blur();
  return false;
};

/**
 * Preload all the full-size images into the browser cache.
 */
Drupal.derbyGallery.preload = function() {
	$('#thumbs li > a').each(
		function() {
			var img = new Image();
			img.src = this.href;
		}
	);
};

/**
 * Wrapper for loadImage, which handles fade out/in
 */
Drupal.derbyGallery.gotoIndex = function(index) {
	index = (index !== null && index !== undefined) ? index : Drupal.derbyGallery.index + 1;
	$('#viewport img').fadeOut(Drupal.derbyGallery.fxOutSpeed, 
		function() { 
			var img = this;
			Drupal.derbyGallery.loadImage(index,
				function() {
					$(img).fadeIn(Drupal.derbyGallery.fxInSpeed);
					Drupal.derbyGallery.rotateNext();
				}
			);
		}
	);
};

Drupal.derbyGallery.rotateNext = function() {
	var o = Drupal.derbyGallery;

	// always try to clear an existing timeout before setting a new one!
	if(o._timeout) {
		window.clearTimeout(o._timeout);
	}

	if(! o.paused) {
		o._timeout = window.setTimeout(o.gotoIndex, o.delay, null);
	}
};

Drupal.derbyGallery.rotateStart = function() {
  Drupal.derbyGallery.paused = false;
  Drupal.derbyGallery.rotateNext();
};

Drupal.derbyGallery.rotateCancel = function() {
	window.clearTimeout(Drupal.derbyGallery._timeout);
};

Drupal.derbyGallery.rotateStop = function() {
	//window.clearInterval(Drupal.derbyGallery._interval);
	Drupal.derbyGallery.paused = true;
	Drupal.derbyGallery.rotateCancel();
};

/**
 * Start the gallery rotation.
 */
Drupal.derbyGallery._rotateStart = function() {
	var o = Drupal.derbyGallery;
	// make sure to pass null as the parameter for goto!
	o._interval = window.setInterval(o.gotoIndex, o.delay, null); 
};

/**
 * Stop the gallery rotation.
 */
Drupal.derbyGallery._rotateStop = function() {
	window.clearInterval(Drupal.derbyGallery._interval);
};

/**
 * onchange handler for the gallery select box.
 */
Drupal.derbyGallery.onGalleryChange = function(e) {
	$(this).attr('disabled', 'disabled');
	$('#thumbs').empty();
	$('#viewport img').hide();
	Drupal.derbyGallery.loadGallery($(this).val());
	return false;
};

/**
 * load a new gallery from the specified url.
 */
Drupal.derbyGallery.loadGallery = function(href) {
   if ($.browser.msie) {
      // MSIE fails to call our $.getJSON callback, so we'll just navigate OLD SCHOOL
      location.href = href;
   }
   else {
      $.getJSON(href + '/js', 
   		function(data) {
   			$('h1').html(data.title);
   			$('#ajax-content').html(data.content);
   			Drupal.derbyGallery.init();
   			$(this).removeAttr('disabled');
   			Drupal.derbyGallery.rotateCancel();			
   		}
   	);
   }
};

Drupal.derbyGallery.initForms = function() {
	if($('#thumbs .quick-edit').size == 0) {
		return;
	}
	
  $('#thumbs .quick-edit').click(
  	function() {
  		$('#thumbs .quick-edit form').hide();
  		$('form', this).show();
  	}
  );
  
  if($.fn.ajaxForm) {
	  $('#thumbs .quick-edit form').ajaxForm(
	  	{
	  		beforeSubmit: function(data, form, options) {
	  			$(form).css('opacity', 0.5);
	  		},
	  		success: function() {
		  		$('#thumbs .quick-edit form').hide();
	  		}
	  	}
	  );
	}
};

$(document).ready(Drupal.derbyGallery.init);