$(document).ready(function() {
    	
	$('div.article_body').prepend('<ul id="gallery_text"></ul>');
	
    $('ul.jcarousel-skin-gallery li div').each(function() {
     $(this).appendTo('ul#gallery_text').wrap('<li></li>');
    });
    
    $('#gallery_text > li').not('.active').hide();
    
    $('ul.jcarousel-skin-gallery').after('<div id="main_image"></div>');
    
        // Flag to determine if gallery has loaded completely
    var loadFlag = true;
    
        $('ul.jcarousel-skin-gallery').galleria({
         history   : true,
         clickNext : true,
         insert    : '#main_image', 
         onImage   : function(image,caption,thumb) {
             
             // if this is the first onImage, the gallery has finished loading
             if (loadFlag == true) {
                $('#gallery_loader').remove();
                 $('#gallery').css('height', 'auto');
                 $('#content_mainA > div.subsection:first-child').css({'visibility': 'visible', 'display': 'none'}).fadeIn(1000);
             }
             
               // set the loadFlag to false so that the above behavior does not happen on subsequent onImage callbacks
               loadFlag = false; 
               image.css('display','none').fadeIn(1000);
               
               if(!$('#gallery').hasClass('restrain')) ngsPageView();
          
               // fetch the thumbnail container
               var _li = thumb.parents('li');
          
               // fade out inactive thumbnail
               _li.siblings().children('img.selected').fadeTo(500,1);
          
               // fade in active thumbnail
               thumb.fadeTo('fast',0.3).addClass('selected');
          
               $('#main_image').trigger('image-loaded');
          
               var _index = _li.attr('jcarouselindex');
               $('#gallery_text > li').removeClass("active").eq(_index-1).addClass("active").show(1,function() {
                   
                   $('#gallery_text > li').not('.active').hide(1);
                   var next_img = {};
                   next_img.img = $($('#gallery .jcarousel-list li.active:last').next('li').children('img:first'));
                   if ( (typeof(next_img.img) != "undefined") && ( next_img.img.length > 0) ) {
                       if ($('#next_image').length == 0) {
                           $('#gallery_text').after('<div id="next_image"></div>');
                       };
                       next_img.src = next_img.img.attr('src');
                       next_img.alt = next_img.img.attr('alt');
                       $('#next_image').html(
                           '<a href="#' + '" title="' + ((next_img.alt != "") ? next_img.alt : "Go to the Next Image") + '" class="next_link">' +
                               '<img src="'+ next_img.src +'" width="100" height="75" alt="' + ((next_img.alt != "") ? next_img.alt : "Go to the Next Image") + '"/>' + 
                           '</a>' + 
                           '<p class="action">' + 
                               '<a href="#' + '">Next &raquo;</a>' + 
                           '</p>'
                       );
                   
                       $('#next_image a').click(function(){
                           try {
                               $.galleria.next();
                           }
                           catch(e) {
                               $($('#gallery .jcarousel-list li.active:last').next('li').children('img:first')).trigger('click');
                           }
                           window.scrollTo(0,0);
                           return false;
                       });
                   
                   } else {
                       $('#next_image').remove();
                   };
               });
           },
         onThumb   : function(thumb) { // thumbnail effects goes here
             // fetch the thumbnail container
             var _li = thumb.parents('li');
         
             // if thumbnail is not active, fade all the way.
             var _fadeTo = _li.is('.active') ? '0.3' : '1';
         
             // fade in the thumbnail when finnished loading
             thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
         
             // hover effects
             thumb.hover(
                 function() { thumb.fadeTo('fast',0.3); },
                 function() { _li.not('.active').children('img').fadeTo('fast',1); } // don't fade out if the parent is active
             )
         }
     });
    
    /*---- Set Carousel Functionality ----*/
    $('ul.jcarousel-skin-gallery').jcarousel({
     visible: 5,
     scroll: 5,
     initCallback: initCallbackFunction
    });
    
    /*---- Add the single arrow 'Previous' and 'Next' arrows to the carousel (for compatibility with intended UI) ----*/
    var j_prev = $('.jcarousel-prev');
    j_prev.css({'cursor':'pointer'});
    j_prev.append('<a href="#" id="prev_btn"></a>');
    var prev_btn = $('#prev_btn');
    prev_btn.click(function() {
     $.galleria.prev();
     this.blur();
     return false;
    });
    var j_next = $('.jcarousel-next');
    j_next.css({'cursor':'pointer'});
    j_next.prepend('<a href="#" id="next_btn"></a>');
    var next_btn = $('#next_btn');
    next_btn.click(function() {
     $.galleria.next();
     this.blur();
     return false;
    });
		

});	

function initCallbackFunction(carousel) {
	
	$('#main_image').bind('image-loaded', function() {
		var selectedLI = $('ul.jcarousel-list > li.active:last');
		var selectedIdx = parseInt(selectedLI.attr('jcarouselindex'));
		$(this).children('div.galleria_wrapper > img:first').attr({'alt':selectedLI.children('img:first').attr('alt'),'title':selectedLI.children('img:first').attr('alt')});
		var currSlide = Math.ceil((selectedIdx) / 5);
		carousel.scroll((currSlide * 5) -4);
	});	

}