jQuery(function( $ ){
    $("#prev").live("click",function(){
        // determine position of clicked thumbnail
        var $items = $("#sections ul li");
        var max = ($items.length)-1;
        var pos = parseInt($("#pos").html());
        switch(pos) {
            case 0:
                var pos = max;
                break;
            case max:
            default: 
                var pos = pos-1;
                break;
        }
        // fill vars with content
        var pic = $($items[pos]).find("span").html();
        var text = $($items[pos]).find(".caption").html();
        // set all thumbs inactive - then the clicked one active
        var pc = $($items[pos]).parents('ul:first');
        $(pc[0]).find('.gallery-element img').removeClass('active');
        //$(this).addClass('active');
        $($items[pos]).find("img").addClass('active');
        // update stage
        srcFadeInOut($("#stage-picture"),pic);
        htmlFadeInOut($("#caption"),text);
        $("#pos").html(pos);
    });
    
    $("#next").live("click",function(){
        // determine position of clicked thumbnail
        var $items = $("#sections ul li");
        var max = ($items.length)-1;
        var pos = parseInt($("#pos").html());
        switch(pos) {
            case max:
                var pos = 0;
                break;
            case 0:
            default: 
                var pos = pos+1;
                break;
        }
        // fill vars with content
        var pic = $($items[pos]).find("span").html();
        var text = $($items[pos]).find(".caption").html();
        // set all thumbs inactive - then the clicked one active
        var pc = $($items[pos]).parents('ul:first');
        $(pc[0]).find('.gallery-element img').removeClass('active');
        //$(this).addClass('active');
        $($items[pos]).find("img").addClass('active');
        // update stage
        srcFadeInOut($("#stage-picture"),pic);
        htmlFadeInOut($("#caption"),text);
        $("#pos").html(pos);
    });
    
});

/**
 * Fade-Out of an image
 * Fade--In of an image after it is loaded (ie wait 250ms)
 *
 */
function srcFadeInOut(el,pic){ 
    /*el.fadeOut(1000,function(){
        el.attr("src",pic);
        if ( $.browser.msie ) {
            //pause(250);
            el.fadeIn(1000);
        } else {
            el.load(function(){
	            $(this).fadeIn(1000);
	        });
        }
    });          
    */  
    
    el.attr("src",pic);
    
    return false;
}

/**
 * Fade-Out of text
 * Fade--In of text (ie wait 250ms)
 *
 */
function htmlFadeInOut(el,text){ 
    el.fadeOut(1000,function(){
        el.html(text);
        if ( $.browser.msie ) {
            //pause(250);
            el.fadeIn(1000);
        } else {
            el.fadeIn(1000);
        }
    });            
    return false;
}

/**
 * Initialize serialScroll and thumbnail functions for gallery
 *
 */
function initGallery(){    
    /**
     * Most jQuery.serialScroll's settings, actually belong to jQuery.ScrollTo, check it's demo for an example of each option.
     * @see http://flesler.demos.com/jquery/scrollTo/
     * You can use EVERY single setting of jQuery.ScrollTo, in the settings hash you send to jQuery.serialScroll.
     */
    
    /**
     * The plugin binds 6 events to the container to allow external manipulation.
     * prev, next, goto, start, stop and notify
     * You use them like this: $(your_container).trigger('next'), $(your_container).trigger('goto', [5]) (0-based index).
     * If for some odd reason, the element already has any of these events bound, trigger it with the namespace.
     */     
    
    /**
     * IMPORTANT: this call to the plugin specifies ALL the settings (plus some of jQuery.ScrollTo)
     * This is done so you can see them. You DON'T need to specify the commented ones.
     * A 'target' is specified, that means that #screen is the context for target, prev, next and navigation.
     */
    $('#screen').serialScroll({
    //$('#screen').live("serialScroll",function({
        target:'#sections',
        items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
        prev:'img.prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
        next:'img.next',// Selector to the 'next' button (absolute too)
        axis:'x',// The default is 'y' scroll on both ways
        navigation:'#navigation li a',
        duration:700,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
        force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
        
        exclude:5,
        event:'mouseover',
        
        //queue:false,// We scroll on both axes, scroll both at the same time.
        //event:'click',// On which event to react (click is the default, you probably won't need to specify it)
        //stop:false,// Each click will stop any previous animations of the target. (false by default)
        //lock:true, // Ignore events if already animating (true by default)        
        //start: 0, // On which element (index) to begin ( 0 is the default, redundant in this case )       
        //cycle:true,// Cycle endlessly ( constant velocity, true is the default )
        //step:1, // How many items to scroll each time ( 1 is the default, no need to specify )
        //jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
        //lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
        //interval:1000, // It's the number of milliseconds to automatically go to the next
        //constant:true, // constant speed
        
        onBefore:function( e, elem, $pane, $items, pos ){
            /**
             * 'this' is the triggered element 
             * e is the event object
             * elem is the element we'll be scrolling to
             * $pane is the element being scrolled
             * $items is the items collection at this moment
             * pos is the position of elem in the collection
             * if it returns false, the event will be ignored
             */
             //those arguments with a $ are jqueryfied, elem isn't.
            e.preventDefault();
            if( this.blur )
                this.blur();
        },
        onAfter:function( elem ){
            //'this' is the element being scrolled ($pane) not jqueryfied
        }
    });

	$(".gallery-element").each(function(){
		var pic  = $(this).find(".thumbpath");
        var text = $(this).find(".caption").html();
		
		$(this).find("img").not(".thumbpath").click(function(){

			var pc = $(this).parents('ul:first');
            $(pc[0]).find('.gallery-element img').removeClass('active');
            $(this).addClass('active');
            // update stage
			$("#pos").html($(this).parents('li:first').prevAll().length);
			// fade out stage picture, replace and fade in again
			$('#stage-picture').fadeOut(1000,function(){
				//debug("fadeout","fadeout");
				// (hide picture and) replace it
				//$("#stage-picture").hide();
				$("#stage-picture").attr("src",pic.attr('src'));
				// hide caption and replace it
				$("#caption").fadeOut(500,function(){
					$("#caption").html(text);
				});
				// stage resize
	            // resize stage and image container
                var paddingleft = Math.round((707-pic.attr('width'))/2);
				var margintop   = Math.round((408-pic.attr('height'))/2);
				
				$("#stage-picture-container").animate({ 
		        	width: pic.attr('width')+"px"
		    	}, 1500, function(){
					$("#stage-inner").animate({
						paddingLeft:paddingleft+"px",
						width:(707-paddingleft)+"px"
					});
					$("#caption").css('top',(465-margintop)+'px');
				}).animate({
					top:(margintop+52)+"px",
					height: pic.attr('height')+"px"
				}, 1500, function(){
					// image fadeIn
					$("#stage-picture").fadeIn(1000);
					// caption fadeIn
					$("#caption").fadeIn(1000);
				});
			});
			
		});
	});
}

/**
 * Stop the code execution from a escified time in milisecond
 *
 */
function pause(ms) {
   var date = new Date(); 
   curDate = null;
   do { var curDate = new Date(); }
   while ( curDate - date < ms);
};

/**
 * debug function
 * fires an alert if in ie - otherwise console.log
 * string	message
 * string	output
 *
 */
function debug(x,y){
    if ( $.browser.msie ) {
        alert(x);
    } else {
        console.log(y,x);
    }
}