/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

var SlideShowSliderValue = 0
var StepTracker
var SlideShowOn = false
var TimeOutTimer

function startImage(imgPath) {
    var eleLightbox = jQuery('#jquery-lightbox');
    var eleOverlay = jQuery('#jquery-overlay');
    // Initial Positioning of lightbox
    positionLightbox(eleLightbox, false,'', 250);
    // imgPath is the path to the image passed in
    setInterface(imgPath, 250, 250, eleLightbox, eleOverlay);
    return true;
}
function nextImage(imgPath, imgWidth, imgHeight) {
    jQuery('#jquery-lightbox').show();
    resetInterface(imgPath, imgWidth, imgHeight);
    return true;
}
function setInterface(imgPath, imgWidth, imgHeight, LightboxElement, OverlayElement) {
    LightboxElement.append("<div class='scrollControl up'/><div class='scrollControl down'/>");
    // Size overlay according to window dimensions
    resizeToWindow(OverlayElement);
    OverlayElement.fadeIn();
    // Load up the first image
    setupImage(imgPath, imgWidth, imgHeight, LightboxElement);
    // Assigning click events in elements to close overlay
    OverlayElement.click(function() {
        finish(LightboxElement,OverlayElement);
    });
    // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
    jQuery('#lightbox-loading-link,#jquery-lightbox [id$=imgClose]').click(function() {
        finish(LightboxElement,OverlayElement);
        return false;
    });
    // Assign click events to scrollers
    var dataBox = jQuery("#lightbox-container-image-data-box");
    var btnScrollUp = LightboxElement.find('.scrollControl.up');
    var btnScrollDown = LightboxElement.find('.scrollControl.down');
    var dataScrollTop = getScrollTop(dataBox, btnScrollUp, btnScrollDown);
    var scrollParams = {
        axis:'y',
        easing: 'swing',
        onAfter: function() {
            dataScrollTop = getScrollTop(dataBox,btnScrollUp,btnScrollDown);
        }
    };
    btnScrollUp.click(function() {
        if ( jQuery(this).not('.disabled') ) {
            dataBox.scrollTo(dataScrollTop-120,400,scrollParams)
        }
    });
    btnScrollDown.click(function() {
        if ( jQuery(this).not('.disabled') ) {
            dataBox.scrollTo(dataScrollTop+120,400,scrollParams)
        }
    });
    // If window is resized, calculate the new overlay dimensions
    jQuery(window).resize(function() {
        resizeToWindow(OverlayElement, true);
        positionLightbox(LightboxElement, true, 200);
    });
}
function ControlSlideshowDirect(value) {
    var eleStopSlideShow = jQuery("[id$=lblStopSlideShow]");
    var eleStartSlideShow = jQuery("[id$=lblStartSlideShow]");
    
    SetLabelValue(value);
    if (value == 0) {
        StopSlideShow();
        SetLabelValue(0);
        eleStopSlideShow.hide();
        eleStartSlideShow.show();
    } else {
        eleStopSlideShow.show();
        eleStartSlideShow.hide();
        if (!SlideShowOn) {
            SlideShowOn = true;
            SlideShowStep(value);
        }
    }
}
function SlideShowStep(Interval) {
    clearTimeout(StepTracker);
    StepTracker = setTimeout('SlideshowClickNextButton()', Interval * 1000);
}
function SlideshowClickNextButton() {
    if (GetSliderValue() != '0') {
        SlideShowClickNextButton();
    }
}
function StopSlideShow() {
    SlideShowOn = false;
}
function resetInterface(imgPath, imgWidth, imgHeight) {
    var eleLightbox = jQuery('#jquery-lightbox');
    var eleOverlay = jQuery('#jquery-overlay');
    var eleStopSlideShow = jQuery("[id$=lblStopSlideShow]");
    var eleStartSlideShow = jQuery("[id$=lblStartSlideShow]");
    var eleImageBox = jQuery('#lightbox-container-image-box');
    eleLightbox.append("<div class='scrollControl up'/><div class='scrollControl down'/>");
    
    // Resize overlay according to window dimensions
    resizeToWindow(eleOverlay);
    eleOverlay.show();
    // Load up next image
    setupImage(imgPath, imgWidth, imgHeight, eleLightbox);
    // Assigning click events in elements to close overlay
    eleOverlay.click(function() {
        finish(eleLightbox,eleOverlay);
    });
    // Assign click events to scrollers
    var dataBox = jQuery("#lightbox-container-image-data-box");
    var btnScrollUp = eleLightbox.find('.scrollControl.up');
    var btnScrollDown = eleLightbox.find('.scrollControl.down');
    var dataScrollTop = getScrollTop(dataBox,btnScrollUp,btnScrollDown);
    var scrollParams = {
        axis:'y',
        easing: 'swing',
        onAfter: function() {
            dataScrollTop = getScrollTop(dataBox,btnScrollUp,btnScrollDown);
        }
    };
    btnScrollUp.click(function() {
        if ( jQuery(this).not('.disabled') ) {
            dataBox.scrollTo(dataScrollTop-120,400,scrollParams)
        }
    });
    btnScrollDown.click(function() {
        if ( jQuery(this).not('.disabled') ) {
            dataBox.scrollTo(dataScrollTop+120,400,scrollParams)
        }
    });
    // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
    jQuery('#lightbox-loading-link, #jquery-lightbox [id$=imgClose]').click(function() {
        finish(eleLightbox,eleOverlay);
        return false;
    });
    // If window was resized, calculate the new overlay dimensions
    jQuery(window).resize(function() {
        resizeToWindow(eleOverlay, true);
        positionLightbox(eleLightbox, true, 200);
    });
    // Handle slideshow functionality
    eleStopSlideShow.hide();
    eleStartSlideShow.hide();
    if (eleStartSlideShow && eleStopSlideShow) {
        if (GetSliderPosition() == 0) {
            eleStartSlideShow.show();
            eleStopSlideShow.hide();
        }
        else {
            eleStartSlideShow.hide();
            eleStopSlideShow.show();
        }
    }
}
function setupImage(imgPath, imgWidth, imgHeight, LightboxElement) {
    var eleLightboxImage = jQuery('#lightbox-image');
    // Show the loading
    jQuery('#lightbox-container-image-box, #lightbox-loading').show();
    jQuery('#lightbox-image, #lightbox-container-image-data-box, #lightbox-image-details-currentNumber, #lightbox-nav, #jquery-lightbox .scrollControl').hide();
    positionLightbox(LightboxElement,false);
    // Image preload process
    var imgPreloader = new Image();
    imgPreloader.onload = function() {
        eleLightboxImage.attr('src', imgPath);
        // Check dimensions
        var arrayDimensions = checkDimensions(LightboxElement, imgPreloader, eleLightboxImage);
        // Resize the image container
        resizeImageBox(arrayDimensions[0],arrayDimensions[1],arrayDimensions[2]);
        // clear onLoad, IE behaves irratically with animated gifs otherwise
        imgPreloader.onload = function() {};
    };
    imgPreloader.src = imgPath;
}
function resizeImageBox(newWidth,newHeight,tempHeightAdj) {
    var eleLightbox = jQuery('#jquery-lightbox');
    var eleImageBox = jQuery('#lightbox-container-image-box');
    var eleLoading = jQuery('#lightbox-loading');
    var wDiff = (newWidth-eleImageBox.width())/2-15;
    var hDiff = (newHeight-eleImageBox.height())/2;
    eleLightbox.animate(
        {
            width: newWidth,
            minHeight: newHeight+tempHeightAdj,
            marginLeft: "-="+wDiff+"px",
            marginTop: "-="+hDiff+"px"
        },
        400,
        function(){   
            eleImageBox.animate({
                width: newWidth,
                height: newHeight
            },400);
            //positionLightbox(eleLightbox,true,'','',true);
            eleLoading.fadeOut(
                400, function() {
                    showImageData();
                }
            );
        }
    );
    if (SlideShowOn) {
        SlideShowStep(GetSliderValue());
    };
}
function showImageData() {
    var eleLightbox = jQuery('#jquery-lightbox');
    jQuery('#lightbox-container-image-box, #lightbox-container-image-data-box').fadeIn(function(){
        eleLightbox.animate(
            {minHeight: 0},
            200, function() {
                positionLightbox(eleLightbox,true);
            }
        );
    });
    jQuery('#lightbox-image').show();
    jQuery('#lightbox-image-details-caption').show();
    jQuery('#lightbox-image-details-currentNumber').show();
    showNav();
}
function showNav() {
    jQuery('#lightbox-nav').fadeIn();
    var dataHeight = jQuery('#lightbox-container-image-data-box').height();
    if (dataHeight >= 120) {
        jQuery('#jquery-lightbox .scrollControl').show();
    };
}
function finish(LightboxElement, OverlayElement) {
    LightboxElement.remove();
    OverlayElement.fadeOut(function() {
        jQuery(this).remove();
    });
}
function getBoxSize(LightboxElement) {
    var boxHeight = LightboxElement.outerHeight();
    var boxWidth = LightboxElement.outerWidth();
    var boxArray = [boxWidth, boxHeight];
    return boxArray;
}
function getPageSize() {
	var windowWidth = jQuery(window).width();
	var windowHeight = jQuery(window).height();
    var arrayPageSize = [windowWidth, windowHeight];
    return arrayPageSize;
}
function resizeToWindow(e, blnAnimate, rate) {
    var arrPageSizes = getPageSize();
    if (blnAnimate) {
        if (!rate) {
            rate = 200;
        };
        e.animate({
            width: arrPageSizes[0],
            height: arrPageSizes[1]
        }, rate)
    } else {
        e.css({
            width: arrPageSizes[0],
            height: arrPageSizes[1]
        })
    }
}
function positionLightbox(e, blnAnimate, rate, newWidth, blnShowData) {
    var eleLoading = jQuery('#lightbox-loading');
    e.show();
    var boxSize = getBoxSize(e);
    var xPos = boxSize[0]/2;
    var yPos = boxSize[1]/2;
    if (!newWidth) {
        newWidth = e.width();
    };
    if (!blnShowData) {
        blnShowData = false;
    };
    if (blnAnimate) {
        if (!rate) {
            rate = 400;
        };
        if (!blnShowData) {
            e.animate({
                marginLeft: -xPos,
                marginTop: -yPos,
                width: newWidth+'px'
            }, rate)
        } else {
            e.animate(
                {
                    marginLeft: -xPos,
                    marginTop: -yPos,
                    width: newWidth+'px'
                },
                rate,
                function(){
                    eleLoading.fadeOut(
                        rate, function() {
                            showImageData();
                            e.animate(
                                {minHeight: 0},
                                rate
                            );
                        }
                    );
                }
            )
        };
    } else {
        e.css({
            marginLeft: -xPos-15, // 30px/2 LR padding on lightbox
            marginTop: -yPos-7.5, // 15px/2 TB padding on lightbox
            width: newWidth+'px'
        })
    }
}
function checkDimensions(LightboxElement, imgPreloader, eleLightboxImage) {
    LightboxElement.show(); // neccessary so below WxH calculations can be made
    var eleSlideshowControls = jQuery('#jquery-lightbox .slideshowControls');
    var gutter = [20,20];
    var h_slideshowControls = eleSlideshowControls.outerHeight(true);
    var h_dataBox = 130; /* assume we'll always max-out height on databox + add in margin/padding/border; safest approach */
    var wAdjust = gutter[0] + LightboxElement.outerWidth() - LightboxElement.width();
    var hAdjust = h_slideshowControls+h_dataBox+gutter[1]+LightboxElement.outerHeight()-LightboxElement.height();
    var htDiffLB = h_dataBox;
    var pagesize = getPageSize();
    var x = pagesize[0] - wAdjust;
    var y = pagesize[1] - hAdjust;
    var imageWidth = imgPreloader.width;
    var imageHeight = imgPreloader.height;      
    if (imageWidth > x) {
        imageHeight = imageHeight * (x / imageWidth);
        imageWidth = x;
        if (imageHeight > y) {
            imageWidth = imageWidth * (y / imageHeight);
            imageHeight = y;
        }
    } else if (imageHeight > y) {
        imageWidth = imageWidth * (y / imageHeight);
        imageHeight = y;
        if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth);
            imageWidth = x;
        }
    };    
    var arrayDimensions = [imageWidth, imageHeight, htDiffLB];
    //alert("Adjusted img width: "+arrayDimensions[0]+", Adjusted img height: "+arrayDimensions[1]+", Ht Diff Lightbox: "+arrayDimensions[2]);
    return arrayDimensions;
}
function getScrollTop(e,scrollUp,scrollDown,rate) {
    scrollTopEle = e.scrollTop();
    if (!rate) {
        rate = 160;
    }
    scrollTotal = e.find('table').height();
    if (scrollTopEle == 0) {
        scrollUp.addClass('disabled');
        scrollUp.fadeTo(rate,.4);
    } else {
        scrollUp.removeClass('disabled');
        scrollUp.fadeTo(rate,1);
    }
    if ( (scrollTopEle+120) == scrollTotal ) {
        scrollDown.addClass('disabled');
        scrollDown.fadeTo(rate,.4);
    } else {
        scrollDown.removeClass('disabled');
        scrollDown.fadeTo(rate,1);
    }
    return scrollTopEle;
}
