	
	// some global vars.
	$pageLinks = null;		// maintain link for $ collection of page links
	$current = 0;			// open first page by default
	$WRONG_LOGIN = false;		// this thing is responsible for showing login error message ($('.login_error'));

	
	jQuery(function($) {
		$('.gallery').addClass('gallery_demo'); // adds new class name to maintain degradability
		
		$('ul.gallery').galleria({
			history   : false, // activates the history object for bookmarking, back-button etc.
			clickNext : false, // helper for making the image clickable
			insert    : '#main_image', // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				
				// fade in the image & caption
				if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
					image.css('display','none').fadeIn(1000);
				}
				caption.css('display','none').fadeIn(1000);
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500,0.3);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title','Next image >>');
			},
			onThumb : function(thumb) { // thumbnail effects goes here
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.3';
				
				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
				
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast',1); },
					function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
				)
			}
			
		});
		
		$pageLinks = $('.chapters li div.thumb > a');
		
		var i= 0;
		$pageLinks.click(function (event) {
			event.preventDefault();
			$.historyLoad($pageLinks.index(this)+1);
			//location.href = location.href.split('#')[0] + "#" + ($pageLinks.index(this)+1);
			//openPage(event.target);
		});
		
		// fade out thumbs
        $pageLinks.each(function(i, e){
            if (!$(e).is('.active')) 
                $(e).css({opacity: 0.3});

        });
		
		// bind hovers
        $pageLinks.hover(function(e){
            if (!$(e.currentTarget).is('.active')) {
                $(e.currentTarget).fadeTo('fast', 1);
            }
        }, function(e){
            if (!$(e.currentTarget).is('.active')) {
                $(e.currentTarget).fadeTo('fast', 0.3);
            }
        });
		
		// bind page hider
		$('.chapters h1').click(function (evt){
			if (!$('.chapters').attr('hidden') || $('.chapters').attr('hidden') == 'false') {
				$('.chapters').attr('hidden', true)
					.children('ul')
						.hide()
					.end()
					.animate( {top: -50}, {queue: false});
				// change label
				$('.chapters h1 a').empty().html('[+]');

			} else {
				$('.chapters').attr('hidden', false)
					.animate( {top: 0}, {queue: false})
					.children('ul')
						.slideDown()
					.end()
				// change label
				$('.chapters h1 a').empty().html('[-]');
			}
		});
		
		
		$.galleria.onLoad = function () {
			// bind image click
			$('#main_image img').click (function (evt) {
				evt.preventDefault();
				nextPage();
			})
		}

		// bind Left and Right arrow keys
		/*$(document).keydown (function (key) {
			if (key.keyCode == 39) nextPage();
			if (key.keyCode == 37) prevPage();
		})
		*/
		// open first page
		openPage($pageLinks[0]);
		// start history handling
		$.historyInit(handleHistory);
	});
	
	function openPage (link) {
		$.galleria.activate(link.href);
		$pageLinks.removeClass('active');
		$(link).addClass('active');		
		$current = $pageLinks.index(link);

		// fade out thumbs
        $pageLinks.each(function(i, e){
            if (!$(e).is('.active')) 
                $(e).css({opacity: 0.3});			
			else 
				$(e).css({opacity: 1});
        });
		
		$('.title').empty().html(link.title);
		
		// MEGACHEAT! GRABS COMMENTS :)))
		$("#comments").load("/comics/stripes/comments/" + link.name + ' #comments', {}, function () {bindPaginators});
		
		// Another cheat :) Show description which is hiding in the page ^_^ (<div class="desc-<id>")
		$('.info .desc').empty().html($('.desc-' + link.name).html());		
		
		// move to top
		window.scrollTo(0, 0);
		
		// preload next and previous images:
		if ($current > 0) {
			var prevUrl = $pageLinks.get($current-1).href;
			$(new Image()).attr('src', prevUrl);
		}
		
		if ($current < $pageLinks.length -1) {
			var nextUrl = $pageLinks.get($current+1).href;
			$(new Image()).attr('src', nextUrl);
		}
	}
	
	function nextPage(){
		if ($current < $pageLinks.length-1) {
			$current++;
			//location.href = location.href.split('#')[0] + "#" + ($current+1);//openPage($pageLinks.get(ind+1));
			$.historyLoad($current+1);
		} else {
			//location.href = location.href.split('#')[0] + "/next";
		}
	}
	
	function prevPage() {
		if ($current > 0) {
			$current--;
			//location.href = location.href.split('#')[0] + "#" + ($current+1);
			$.historyLoad($current+1);
		} else {
			//location.href = location.href.split('#')[0] + "/prev";
		}
	}
	
	function handleHistory (hash) {
		// if hash is number and we have such a page
		if (Number(hash) > 0 && Number(hash) <= $pageLinks.length) {
			// display it
			openPage($pageLinks.get(Number(hash)-1))
		} else {
			// hash is not a number, but if hash == 'last',
			if (hash == "last") 
				// show last page
				openPage($pageLinks.get($pageLinks.length-1));
			else
				//show first page
				openPage($pageLinks.get(0));
		}
	}
	
	/**
	 * The magic trick function to load ajaxy comments
	 */
	function bindPaginators() {
		// and rebind buttons :)
		$('.paginator a').click(function (f){
			f.preventDefault();
			// perform ajax trick:
			showPreloader();
			$('#comments').load(f.target.href + " #comments", {}, function () {
				bindPaginators()
			});
		});		
			
		if ($WRONG_LOGIN) {
			$('.leave_comment .login_error').show();
		}
	}
	
	function showPreloader () {
		$('#spinner').show();
	}
	
	function hidePreloader () {
		$('#spinner').hide();
	}	

	/**
	 * submits comment form
	 */
	function submitComment () {
		showPreloader();
		$.ajaxSetup({
			scriptCharset: 'utf-8'
		});
		$('.comment_form form').ajaxSubmit({
			iframe: true,
			dataType: 'text',
		    beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Aber", "cadaber");
				//console.debug(arguments);
				return xhrObj;
	        },
			success: function () {
				hidePreloader();
				// yay! another cheat to get current ajax-page
				var first_page_ajax_url = $('.first_page_ajax_url')[0].href;
				
				// refresh page on success
				$('#comments').load(first_page_ajax_url + " #comments", {}, function () {
					bindPaginators()
				});
			}
		});
		
		return false;
	}
	
	function submitLogin () {
		showPreloader();
		$.ajaxSetup({
			scriptCharset: 'utf-8'
		});
		$('.leave_comment form.login').ajaxSubmit({
			iframe: true,
		    success: function () {
				hidePreloader();
				// yay! another cheat to get current ajax-page
				var current_ajax_url = $('.current_ajax_url')[0].href;
				
				// refresh page on success
				$('#comments').load(current_ajax_url + " #comments", {}, function () {
					bindPaginators();
				});
				
				// show wrong login message (the form hides otherwise anyway)
				$WRONG_LOGIN = true;
			}
		});
	}	
