/*******************************************************************
 ** Frontend Slideshows
 **   - v2011.05.17

 *** Dependencies:
 *** Jquery > 1.4 
 *** Jcarousel Lite 1.0.1
 *** nyroModal v2.0.0

 ******************************************************************/
(function ($) { // protect the lemmings

$.widget( "ui.frontendSlideshow", {

    options: {
        nyro_params : {
			resizable: false,
			autoSizable: false,
			windowResize: false,
			closeButton: true,
			beforeResize: function(obj){
				alert('beforeResize.');
			}
        },
        jscroll_pane_params : {
            showArrows : false
        }
    },

    _create: function () {
	var self = this;
        self._setOption( 'lightbox_initialized', false );

        var gallery = self.element;

    gallery.find(" .slide li img").css("display","block");//don't show it until gallery starts setting up
        
    // Get element surrounding current page # and get total page count
	var active;
	var span = $('div.switcher > ul > li > strong', gallery ).find('span:eq(0)');
	var count = $('div.gallery > ul.slide > li', gallery ).length;
    //console.log(this);
    //var button_list_holder = $(this.element).find(".frontend-slideshow .button-list");
    var button_list_holder = $(this.element).find(".button-list.fe-button-list");
    //console.log(self.options.button_list_holder);
    var button_list = [];
    var button_list_arr = $(button_list_holder.find("button"));
    var button_list_holder_class = button_list_holder.selector;
    //console.log("button_list_holder: " +button_list_holder_class);
    //console.log($($(self.options.button_list_holder).find("button")));
    //for(var i=0 ; i< self.options.button_list_holder.find("button"); i++){
    $(button_list_holder.find("button")).each(function(i,e){
        button_list[i]=button_list_holder_class+" ."+$(e).attr("class");
        //console.log(button_list);
    });
    //console.log("button_list",button_list);
        $(button_list_arr[0]).addClass("active");
        // Setup jCarouselList and update page # after each slide

	// vertically center images
	$("ul.slide li").each(function(idx, liEl) {
		var imageEl = $('img', $(liEl));
		if ( imageEl && !( typeof imageEl === 'undefined' )) {
			var top_margin = $(liEl)[0].offsetHeight > $(imageEl)[0].offsetHeight 
								? (($(liEl)[0].offsetHeight-$(imageEl)[0].offsetHeight)/2 + "px") 
								: "0";
		 	$(imageEl).css('marginTop', top_margin);
		}
	});

    $( '.gallery-holder', gallery ).jCarouselLite({
	    btnNext: $( '.btn-next', gallery ),
	    btnPrev: $( '.btn-prev', gallery ),
        btnGo: button_list,
	    speed: 800,
		beforeStart : function(el) {
			// vert center images
			$(el).each(function(idx, liEl) {
				var imageEl = $('img', $(liEl));
				var top_margin = $(liEl)[0].offsetHeight > $(imageEl)[0].offsetHeight 
									? (($(liEl)[0].offsetHeight-$(imageEl)[0].offsetHeight)/2 + "px") 
									: "0";
			 	$(imageEl).css('marginTop', top_margin);
			});
		},
	    afterEnd: function (el){
    		active = $('ul.slide > li', gallery).index(el);
            var temp_index = active;

            //console.log(active);
		if (active < 3) {
            span.text(active+(count-2));
            temp_index = active+(count-2); 
        }
		if (active >= 3 && active < count+3) {
            span.text(active-2);
            temp_index = active-2;
        }
		if (active >= count+3){
            span.text(active-(count+2));
            temp_index = active-(count+2);
        }
		$('.txt.viewable', gallery).html($('ul.slide > li > .txt:eq(' + active + ')', gallery).html());
            
            //console.log(temp_index);
            $(button_list_arr).removeClass("active");
            $(button_list_arr[temp_index-1]).addClass("active");
	    }
	});
        // Setup hover action for frontened slideshow
        $(self.element).find(".gal-wrap").bind("mouseover",function(){
            $(self.element).find(".txt-content, #txt-content").show();
        });
        $(self.element).find(".gal-wrap").bind("mouseleave",function(){
            $(self.element).find(".txt-content, #txt-content").hide();
        });

        // Setup full screen button to trigger lightbox

        //hardcode the height and width of the gallery-full
        var temp_full_gal = $(gallery).next(".gal-full-wrapper").find(".gallery-full" );
        $(gallery).next(".gal-full-wrapper").show();
            var nyro_height = $(temp_full_gal).find(".slide li").height()
            var nyro_width  = $(temp_full_gal).find(".slide li").width()
        $(gallery).next(".gal-full-wrapper").hide();
        $(gallery).next(".gal-full-wrapper").find(".gallery-full" ).css({
            height: nyro_height + "px",
            width: nyro_width + "px"
        });

        var nyroParams = {
            endShowContent : function (elts) { self._initLightbox(elts); 
            }
        };
        $.extend( nyroParams, self.options.nyro_params );

        // Seems like there is no other way to transform an existing div into a LB
        /*
        $( 'a.btn-full', gallery ).bind( 
            'click.frontendSlideshow',
            function (e) {
                e.preventDefault();
            
                // Except for doing it this way
                var fullscreenGallery = gallery.next( '.gal-full-wrapper' );

                nyroParams.forceType = fullscreenGallery;
                fullscreenGallery.nyroModalManual( nyroParams );
            }
        );
        */
        $( 'a.btn-full', gallery ).nyroModal({
            callbacks:{
				// beforeResize: function(elts) {
				// 	resizeModalImages(elts.contentWrapper.find( '.gal-holder' ));
				// 	verticallyCenterModalImages($('div.gallery > ul.slide > li', elts.contentWrapper.find( '.gal-holder' )));
				// },
                beforeShowCont: function(elts){
					elts.elts.cont.addClass("slideshow-nyro");
                },
                afterShowCont: function(elts){
                    elts.contentWrapper = $(".nyroModalDom");
                    self._initLightbox(elts);
                    //$(".nyroModalCont").addClass("slideshow-nyro");
                }
            }
        }); 
        

        return;
    }, // _create

    _initLightbox : function (elts) {
        var self = this;

        if( !self.options.lightbox_initialized ) {
            self._initScrollPane(elts);
            self._initFullGallery(elts);

            self._setOption( 'lightbox_initialized', true );
        }
        // some ie6 hacks
        if($.browser.msie && $.browser.version == '6.0'){
                setTimeout( function(){
                    // need to trigger position to get the the slideshow to show up
                    $(".nyroModalCont .gal-wrap").css("position", "relative");
                    $(".nyroModalCont .gal-wrap").css("position", "absolute");
                }, 250);
            /*
            setTimeout(function(){
                $(".nyroModalCont .gal-wrap").css("position", "absolute");
                alert("galwrap manipulation");
            }, 1000);
            */
        }
        
        return;
    }, // _initLightbox

    _initScrollPane : function(elts) {
        var self = this;
        var gallery = self.element;

        //$('#txt-pane', gallery).jScrollPane( self.options.jscroll_pane_params );
        
        return;
    }, // _initScrollPane

    _initFullGallery : function(elts) {
        var self = this;

        var fullGallery = elts.contentWrapper.find( '.gal-holder' );
        
	    	resizeModalImages(fullGallery);
    		verticallyCenterModalImages($('div.gallery > ul.slide > li', fullGallery));
		
    //var button_list_holder = $(".gallery-full .button-list");
    var button_list_holder = $(fullGallery).find(".button-list.full-button-list");
    var button_list = [];
    var button_list_arr = $(button_list_holder.find("button"));
    var button_list_holder_class = button_list_holder.selector;
    //console.log("button_list_holder: " +button_list_holder_class);
    //console.log($($(self.options.button_list_holder).find("button")));
    //for(var i=0 ; i< self.options.button_list_holder.find("button"); i++){
    $(button_list_holder.find("button")).each(function(i,e){
        button_list[i]=button_list_holder_class+" ."+$(e).attr("class");
        //console.log(button_list);
    });
        $(button_list_arr[0]).addClass("active");//don't activate the first button until after we collcted the button list;

	// Full screen gallery
        var curspan = $('.num-info, #num-info', fullGallery).find('span:eq(0)');
        var count = $('div.gallery > ul.slide > li', fullGallery).length;
        // kinda hacky, I used css to hide the images to prevent flash of image 
        // we couldve also set overflow hidden, but that would hide the return to previous button
        // So here we show the first item to get the gallery initialized properly   


	
    $($("#nyroModalFull .gallery-holder-full li")[0]).show();
    $(".gallery-holder-full", fullGallery).jCarouselLite({
	    btnNext: $( '.btn-next', fullGallery ),
	    btnPrev: $( '.btn-prev', fullGallery ),
        btnGo: button_list,
	    speed: 400,
		beforeStart : function(el) {
			$(el).each(function(idx, liEl) {
				var imageEl = $('img', $(liEl));
				var top_margin = $(liEl)[0].offsetHeight > $(imageEl)[0].offsetHeight 
									? (($(liEl)[0].offsetHeight-$(imageEl)[0].offsetHeight)/2 + "px") 
									: "0";
			 	$(imageEl).css('marginTop', top_margin);
			});
		},
	    afterEnd: function (el){
			active = $('ul.slide > li', fullGallery).index(el);
            //console.log("active");
            //console.log(active);
        /*
		$("#txt-pane", fullGallery).html(
                    $( 'ul.slide > li .txt:eq(' + active + ')', fullGallery).html()).jScrollPane({scrollbarWidth:10, scrollbarMargin:10});
        */
		$(".txt-pane, #txt-pane", fullGallery).html(
                    $( 'ul.slide > li .txt:eq(' + active + ')', fullGallery).html());
		if (active < 3) active = active+(count-2);
		if (active >= 3 && active < count+3) active = active-2;
		if (active >= count+3) active = active-(count+2);
            //console.log(active);
            $(button_list_arr).removeClass("active");
            $(button_list_arr[active-1]).addClass("active");
	    }


	});
        $("#nyroModalFull .gallery-holder-full li").show();

        return;
    }, // _initFullGallery

    destroy: function () {
	var self = this;
        var gallery = self.element;

        $( 'a.btn-full', gallery ).unbind( '.frontendSlideshow' );

        // jCarousellite does not have a destroy that unbind and removes added stuff, etc

	$.Widget.prototype.destroy.apply( this, arguments );
    } // destroy

}); // $.widget

function resizeModalImages(fullGallery) {
	// resize images if window is too short
	var naturalHeightOfImages = 720;
	var minWindowHeightBeforeResize = 795;
	var naturalWidthOfImages = 920;
	var minWindowWidthBeforeResize = 995;
	var windowImageHeightDiff = Math.abs(minWindowHeightBeforeResize - naturalHeightOfImages);
	var windowImageWidthDiff = Math.abs(minWindowWidthBeforeResize - naturalWidthOfImages);
	var aspect = 4.0/3.0;
	if ( $(window).height() < minWindowHeightBeforeResize ) {
		console.log("Needs to be resized (height).");
		var newHeight = $(window).height() - windowImageHeightDiff;
        if($.browser.msie && $.browser.version == '6.0'){
		    newHeight -= 100; // solution to shrink the height even a little more for ie6
        }

		$('div.gallery > ul.slide > li', fullGallery).each(function(idx, liEl) {
			console.log("\n\nSetting for idx " + idx);
			// resize parent
			$(liEl).css('height', newHeight + 'px');
			
			// resize child
			var imageEl = $('img', $(liEl));
			if ( imageEl && !( typeof imageEl === 'undefined' )) {
				var imageAspect = $(imageEl).width() / $(imageEl).height();
				
				var newImageHeight = newHeight < $(imageEl).height() ? newHeight : $(imageEl).height();
				var newImageWidth = newHeight < $(imageEl).height() ? newImageHeight * imageAspect : $(imageEl).width();

				console.log("h newImageHeight " + newImageHeight);
				console.log("h newImageWidth " + newImageWidth);
				
				$(imageEl).css('height', newImageHeight + 'px');
				$(imageEl).css('width', newImageWidth + 'px');
			}
		});
	}
	if ( $(window).width() < minWindowWidthBeforeResize ) {
		console.log("Needs to be resized (width).");
		var newWidth = $(window).width() - windowImageWidthDiff;

		$('.gal-wrap').css('width', (newWidth - 10) + 'px'); 

		$('div.gallery > ul.slide > li', fullGallery).each(function(idx, liEl) {
			console.log("\n\nSetting width for idx " + idx);
			// resize parent
			$(liEl).css('width', newWidth + 'px');
			
			// resize child
			var imageEl = $('img', $(liEl));
			if ( imageEl && !( typeof imageEl === 'undefined' )) {
				var imageAspect = $(imageEl).width() / $(imageEl).height();

				var newImageWidth = newWidth < $(imageEl).width() ? newWidth : $(imageEl).width();
				var newImageHeight = newWidth < $(imageEl).width() ? newImageWidth / imageAspect : $(imageEl).height();

				console.log("w newImageHeight " + newImageHeight);
				console.log("w newImageWidth " + newImageWidth);
				
				$(imageEl).css('height', newImageHeight + 'px');
				$(imageEl).css('width', newImageWidth + 'px');
			}
		});
	}

}
function verticallyCenterModalImages(selectedArray) {
	$(selectedArray).each(function(idx, liEl) {
		var imageEl = $('img', $(liEl));
		if ( imageEl && !( typeof imageEl === 'undefined' )) {
			var top_margin = $(liEl)[0].offsetHeight > $(imageEl)[0].offsetHeight 
								? (($(liEl)[0].offsetHeight-$(imageEl)[0].offsetHeight)/2 + "px") 
								: "0";
		 	$(imageEl).css('marginTop', top_margin);
		}
	});
}

})(jQuery); // function($)



