/*******************************************************************************
 *  Author: Adam Kusmierz vel Raistlin Majere
 *  E-mail: <adam@kusmierz.be>
 *  WWW: kusmierz.be
 *  Create: 2006-01-28
 *  Last modifications: 15:50 2011-02-14
 ******************************************************************************/

$(function() {
	var url = 'http://images.ucomics.com/comics/ga/';
	var currentDate = new Date();
	var minDate = new Date(1978, 6 - 1, 19);
	var maxDate = new Date();
	var currentImg = null;
	var oldImage = null;
	var direction = -1;

	var dateSelector = $("#calendarFilterBox").calendarPicker({
		//monthNames:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
		//dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
		useWheel: true,
		callbackDelay: 100,
		years: 2,
		months: 6,
		days: 7,
		showDayArrows: true,
		callback: function(cal) {
			$.fancybox.showActivity({
				onCancel: function() {}
			});
			
			if (currentDate) {
				if (currentDate > cal.currentDate) {
					direction = -1;
				} else if (currentDate < cal.currentDate) {
					direction = +1;
				}
			}
			
			currentDate = cal.currentDate;
			if (currentDate < minDate) {
				dateSelector.changeDate(new Date(minDate.getTime()));
				return;
			}
			if (currentDate > maxDate) {
				direction = -1;
				dateSelector.changeDate(new Date(maxDate.getTime()));
				return;
			}

			if (null != oldImage) {
				oldImage.remove();
			}

			if (null != currentImg) {
				oldImage = currentImg;
				oldImage.css('zIndex', '100');
			}

			window.location = $.datepicker.formatDate('#yy/mm/dd', currentDate);
			var src = url + $.datepicker.formatDate('yy/\'ga\'ymmdd.\'gif\'', currentDate);

			var aimg = $('<a href="' + src + '" class="img"><img src="' + src + '" alt="" title="' + $.datepicker.formatDate('dd/mm/yy', currentDate) + '" /></a>');
			aimg.css('zIndex', '500').fancybox({
				centerOnScroll: true,
				overlayOpacity: 1,
				overlayColor: '#fff'
			}).hide();

			aimg.find('img').load(function(event) {
				// głupi Chrome/Safari
				aimg.show(10, function() {
					var imgPos = Math.round((aimg.parent().innerHeight() - aimg.outerHeight()) / 2);
					if (imgPos < 0) {
						imgPos = 0;
					}
					aimg.css('top', imgPos + 'px');
				}).hide().fadeIn();
				
				if (null != oldImage) {
					oldImage.fadeOut('slow', function() {
						$(this).remove();
					});
				}
				$.fancybox.hideActivity();
			}).error(function(event) {
				$.fancybox.hideActivity();
				$('#error').clearQueue().stop().html('Image for day <b>' + $.datepicker.formatDate('dd/mm/yy', currentDate) + '</b> doesn\'t exist!').fadeIn('fast').effect('pulsate', {times: 2}, 300, function() {
					$(this).delay(5000).fadeOut('slow');
				});
				if (null != oldImage) {
					oldImage.fadeOut('slow', function() {
						$(this).remove();
					});
				}
				// wybierz poprzednią datę
				dateSelector.changeDate(new Date(currentDate.setDate(currentDate.getDate() + (direction <= 0 ? -1 : 1))));
				return;
			});

			$('#browser').append(aimg);
			$.fancybox.close();
			currentImg = aimg;
		}
	});

	$(window).bind('hashchange', function(event) {
		var parsedDate = null;
		if (null == event.fragment || event.fragment.length == 0) {
			currentDate = new Date();
			dateSelector.changeDate(currentDate);
			return;
		}
		try {
			parsedDate = $.datepicker.parseDate('yy/mm/dd', event.fragment.replace('-', '/'))
		} catch(e) {
			window.location = $.datepicker.formatDate('#yy/mm/dd', currentDate);
		}
		if (currentDate.getFullYear() != parsedDate.getFullYear() || currentDate.getMonth() != parsedDate.getMonth() || currentDate.getDate() != parsedDate.getDate()) {
			currentDate = parsedDate;
			dateSelector.changeDate(currentDate);
		}
	}).trigger('hashchange');

	$('html').keyup(function(event) {
		// 0 space - random
		direction = -1;
		if (event.keyCode == 36) { // Home
			direction = +1;
			dateSelector.changeDate(new Date(1978, 6 - 1, 19));
		} else if (event.keyCode == 35) { // End
			direction = -1;
			dateSelector.changeDate(new Date());
		} else if (event.shiftKey && event.keyCode == 33) { // Shift + Page Up
			direction = -1;
			dateSelector.changeDate(new Date(currentDate.setFullYear(currentDate.getFullYear() - 1)));
		} else if (event.shiftKey && event.keyCode == 34) { // Shift + Page Down
			direction = +1;
			dateSelector.changeDate(new Date(currentDate.setFullYear(currentDate.getFullYear() + 1)));
		} else if (event.keyCode == 33) { // Page Up
			direction = -1;
			dateSelector.changeDate(new Date(currentDate.setMonth(currentDate.getMonth() - 1)));
		} else if (event.keyCode == 34) { // Page Down
			direction = +1;
			dateSelector.changeDate(new Date(currentDate.setMonth(currentDate.getMonth() + 1)));
		} else if (event.keyCode == 37) { // Left
			direction = -1;
			dateSelector.changeDate(new Date(currentDate.setDate(currentDate.getDate() - 1)));
		} else if (event.keyCode == 38) { // Up
			direction = +1;
			dateSelector.changeDate(new Date(currentDate.setDate(currentDate.getDate() + 7)));
		} else if (event.keyCode == 39) { // Right
			direction = +1;
			dateSelector.changeDate(new Date(currentDate.setDate(currentDate.getDate() + 1)));
		} else if (event.keyCode == 40) { // Down
			direction = -1;
			dateSelector.changeDate(new Date(currentDate.setDate(currentDate.getDate() - 7)));
		}
		if (event.keyCode >= 33 && event.keyCode <= 40) {
			event.preventDefault();
		}
	});
	
	$('#datepicker > .today').button();
});

// http://benalman.com/news/2010/03/jquery-special-events/#add-and-remove-hashchange
// hashchange
(function($){

  // Store the initial location.hash so that the event isn't triggered when
  // the page is first loaded.
  var last_hash = location.hash,

	// An id with which the polling loop can be canceled.
	timeout_id;

  // Special event definition.
  $.event.special.hashchange = {
	setup: function() {
	  // If the event is supported natively, return false so that jQuery
	  // will bind to the event using DOM methods instead of using the
	  //  polling loop.
	  if ( 'onhashchange' in window ) { return false; }

	  // Start the polling loop if it's not already running.
	  start();
	},
	teardown: function() {
	  // If the event is supported natively, return false so that jQuery
	  // will bind to the event using DOM methods instead of using the
	  // polling loop.
	  if ( 'onhashchange' in window ) { return false; }

	  // Stop the polling loop. Since this event is only evern bound to
	  // the `window` object, multiple-element tracking is unnecessary.
	  stop();
	},
	add: function( handleObj ) {
	  // Save a reference to the bound event handler.
	  var old_handler = handleObj.handler;

	  // This function will now be called when the event is triggered,
	  // instead of the bound event handler.
	  handleObj.handler = function(event) {

		// Augment the event object with the location.hash at the time
		// the event was triggered.
		event.fragment = location.hash.replace( /^#/, '' );

		// Call the originally-bound event handler, complete with modified
		// event object! The result from this call doesn't need to be
		// returned, because there is no default action to prevent, and
		// nothing to propagate to.
		old_handler.apply( this, arguments );
	  };
	}
  };

  // Start (or continue) the polling loop.
  function start() {
	// Stop the polling loop if it has already started.
	stop();

	// Get the current location.hash. If is has changed since the last loop
	// iteration, store that value and trigger the hashchange event.
	var hash = location.hash;
	if ( hash !== last_hash ) {
	  $(window).trigger( 'hashchange' );
	  last_hash = hash;
	}

	// Poll, setting timeout_id so the polling loop can be canceled.
	timeout_id = setTimeout( start, 100 );
  };

  // Stop the polling loop.
  function stop() {
	clearTimeout( timeout_id );
  };

})(jQuery);
