/*******************************************************************
 ** 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", {
    current_pane: 0,
    options: {
        resize_largest: true,
        nyro_params : {
			resizable: false,
			autoSizable: false,
			windowResize: false,
			closeButton: true,
			beforeResize: function(obj){
				alert('beforeResize.');
			}
        },
        jscroll_pane_params : {
            showArrows : false
        }
    },
    _resizeLi : function(gallery_holder){
        var self = this;
        if(self.options.resize_largest){
            var li = $("li", gallery_holder);
            var max_height = 0;
            li.each(function(i,e){
                var img = $("img", e);
                
                if($(img).innerHeight() > max_height){max_height = $(img).innerHeight()};
            });
            //console.log(max_height, li);
            li.css("height", max_height+"px");
            gallery_holder.css("height", max_height+"px");
        } 

    },
    _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

    //* find largest OR smallest image height;
    self._resizeLi($(".gallery-holder", gallery));

        var fullGallery = self.element.next( '.gal-full-wrapper' );
        fullGallery.show();
        //console.log("fullGallery", fullGallery);
        //* find largest OR smallest image height;
        self._resizeLi($(".gallery-holder-full",fullGallery));
        //fullGallery.hide();
        
    // 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");
        if($(e).attr("class") > 9){
            $(e).addClass("wide");
        }
        //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");
            self.current_pane = temp_index-1;
	    }
	});
        // Setup hover action for frontened slideshow
        $(self.element).find(".gal-wrap").bind("mouseover",function(){
            if(jQuery.trim($(self.element).find(".txt-content .frontend-slideshow-slide-title, .txt-content .frontend-slideshow-slide-desc, #txt-content .frontend-slideshow-slide-desc, #txt-content .frontend-slideshow-slide-title").text()).length > 0){
                $(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 ).unbind('click');
        $( '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 );
                */
                return false;
            }
        );
        $( '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' )));
				// },
                beforeShowBg: function(){
                    if( self.options.lightbox_initialized ) {
                    }

                },
                beforeShowCont: function(elts){
					elts.elts.cont.addClass("slideshow-nyro");
                    if( !self.options.lightbox_initialized ) {
                        $(".nyroModalCont .gallery-holder-full").css("visibility","hidden");
                    }
                        //* we need to hide it cause we want to trigger the positioning of the slideshow
                        //* AFTER the content is shown
                        //* there were issues with positioning it before ShowBg when
                        //* the amount of images were > a few
                        $(".nyroModalCont .gallery-holder-full").css("opacity","0.0");
                },
                afterShowCont: function(elts){
                    elts.contentWrapper = $(".nyroModalDom");
                    self._initLightbox(elts);
                    //$(".nyroModalCont").addClass("slideshow-nyro");
                        $($('.gallery-full .full-button-list button')[self.current_pane]).trigger('click');
                        setTimeout(function(){ 
                            $(".nyroModalCont .gallery-holder-full").animate({opacity : "1.0"}, 200);
                        }, 400); //* 400 == the speed of jCarouselLite

                    //* msie 7 fix for close button
                    if($.browser.msie && $.browser.version == "7.0"){
                        $(".nyroModalClose").unbind('click').click(function(){
                            $.nmTop().close();
                            return false;
                        });
                        
                    }
                    
                }
            }
        }); 
        

        return;
    }, // _create

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

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

            self._setOption( 'lightbox_initialized', true );
        }
            //$($('.gallery-full .full-button-list button')[self.current_pane]).trigger('click'); //jump to start here
        
        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' );
        var fullGallery_wrap = $(".gal-wrap", fullGallery);
        if($.browser.msie){
            //* fixing issue where the buttons get hidden by ie
            //* overflow:hidden is on, but the inline nature of the buttons should keep it shown
            fullGallery_wrap.css("height", fullGallery.height() + 80);
        }
        //* find largest OR smallest image height;
        //self._resizeLi($(".gallery-holder-full",fullGallery));
        
	    	//resizeModalImages(fullGallery); //* TODO: 
    		//verticallyCenterModalImages($('div.gallery > ul.slide > li', fullGallery)); 
                //* TODO: right now for some reason, after jCarouselLite is called, the li's get resized to 500px in height,
                //* we don't want that, we want to do it ourselves. If the centering and the size of the lightbox is dynamic
                //* then we have to probably call _resizeLi, resizeModalImages, AND verticallyCenterModalImages in jCarouselLite.beforeStart
                //* and we need to check if an 'interrupt' flag has been set to call on those methods cause we dont want to call them on every 
                //* turn
		
    //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");
        if($(e).attr("class") > 9){
            $(e).addClass("wide");
        }
        //console.log(button_list);
    });
        $(button_list_arr[self.current_pane]).addClass("active");//don't activate the first button until after we collcted the 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,
        //start: self.current_pane,
		beforeStart : function(el) {
            return;
			$(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);
            if($.browser.msie && ( $.browser.version == "8.0" || $.browser.version == "7.0" ) ){
                //* rt#11827 have to hide-show the fullgallery to trigger the ie renderer to update
                fullGallery.hide();
                fullGallery.show(); 
            }
            //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();
        $(".nyroModalCont .gallery-holder-full").css("visibility","visible");

        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 || $('div.gallery > ul.slide > li', fullGallery).height() > minWindowHeightBeforeResize) {
		console.log("Needs to be resized (height).");
		var newHeight = $(window).height() - windowImageHeightDiff;

		$('div.gallery > ul.slide > li', fullGallery).each(function(idx, liEl) {
			console.log("\n\nSetting for idx " + idx);
			// resize parent
			$(liEl).css('height', newHeight + 'px');
            $(".gallery-full").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 || $('div.gallery > ul.slide > li', fullGallery).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($)



