var igalleryClass = IGClass.extend({

    init: function(options)
    {
        this.options = options;

        if(typeof jQuery('.main_images_wrapper').imagesLoaded === 'undefined')
        {
            jQuery('#ig_jquery_warning').css({'display' : 'block','color' : 'red'});
            jQuery('#ig_jquery_warning').html('Ignite Gallery Error, the javascript library jquery needs to be added at the top of the html document, and it can not be added a second time later in the doc, please see the first item on the gallery common support questions page');
        }


        this.options.slideDuration = 300;
        this.imageIndex = this.options.activeImage;
        this.firstShow = true;
        this.currentHash = '';
        this.zIndex = 0;
        this.lightboxShowCounter = 0;
        this.imageShowCounter = 0;
        this.lboxPreloadStarted = false;
        this.indexsToPreload = new Array();
        this.indexsLoaded = new Array();
        this.plusOneDelays = new Array();
        this.fbLikeDelays = new Array();
        this.fbCommentDelays = new Array();
        this.twitterDelays = new Array();
        this.pInterestDelays = new Array();
        this.lastWindowWidth = 0;
        this.lastWindowHeight = 0;
        this.lastThumbsGridWidth = -1;
        this.lboxFullHeight = 0;
        this.thumbsBelowHeight = 0;
        this.hoverLeftThumbArrow = false;
        this.hoverRightThumbArrow = false;
        this.hoverUpThumbArrow = false;
        this.hoverDownThumbArrow = false;
        this.isTouchDevice = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
        this.userAgent = navigator.userAgent.toLowerCase();
        this.iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
        this.isSafari = /^((?!chrome|android).)*safari/i.test(this.userAgent);
        this.isSafariMac = !this.iOS && this.isSafari ? true : false;
        this.isAndroid = (this.userAgent.indexOf("android") > -1);
        this.isIE8 = false;
        if(navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0){this.isIE8 = true;}
        if(jQuery('#'+this.options.reportContainer).length){this.reportContainerHeight = jQuery('#'+this.options.reportContainer).height();}


        if(this.options.main == 1)
        {
            this.initializeMain();
        }

        if(this.options.showThumbs == 1 && this.options.main == 1)
        {
            this.initializeThumbs(this.imageIndex, 0);
        }

        if( (this.options.showSlideshowControls == 1 || this.options.slideshowAutostart == 1)  && this.options.main == 1 && this.options.showLargeImage == 1)
        {
            this.initializeSlideShow();
        }

        if(this.options.showLargeImage == 0 && this.options.lightboxOn == 1 && this.options.calledFrom != 'module')
        {
            this.autoShowLbox();
        }

        //load lbox biggest image
        if(this.options.main == 0)
        {
            this.lboxTallestImageIndex = 0;
            this.lboxTallestImageHeight = 0;

            jQuery.each(this.options.jsonImagesImageType, function(index, object)
            {
                if(object.height > this.lboxTallestImageHeight)
                {
                    this.lboxTallestImageHeight = object.height;
                    this.lboxTallestImageIndex = index;
                }
            }.bind(this));

            this.loadImageNow(this.lboxTallestImageIndex, false, false);
        }
    },

    autoShowLbox: function()
    {
        if( window.location.hash.indexOf('!') != -1)
        {
            var hashVar = window.location.hash;
            var fileNameClean = hashVar.substr(2);
            if( fileNameClean.indexOf('#') != -1)
            {
                fileNameClean = fileNameClean.substr(0, fileNameClean.indexOf('#'));
            }
            if(fileNameClean.indexOf('#') != -1)
            {
                fileNameClean = fileNameClean.substring(0, fileNameClean.indexOf('#'))
            }

            jQuery.each(this.options.jsonImages.general, function(index, object)
            {
                var fileNameShort = object.filename.substring(0, object.filename.indexOf('-'))

                if( fileNameShort == fileNameClean )
                {
                    setTimeout(jQuery.proxy(this.showLightBox, this, index, false) ,200);
                }
            }.bind(this));
        }
    },

    initializeMain: function()
    {
        var exludeUlrVar = this.getUrlParamater('allow-click');
        if(this.options.disableRightClick == 1 && exludeUlrVar == 'unset')
        {
            jQuery('.large_img, .ig_thumb').on('contextmenu',function(){
                alert('Saving images is disabled');
                return false;
            });
            jQuery('.ig_thumb').on('dragstart', function(event){
                event.preventDefault();
            });
        }

        this.initializeHash();
        this.initializeSlick();

        if(this.getUrlParamater('thumb_limitstart') != 'unset')
        {
            window.location.hash = 'gallery-' + this.options.uniqueid;
        }

        this.boundAddKeyEvent = this.addKeyEvent.bind(this);
        if(this.options.showLargeImage == 1)
        {
            jQuery('body').keydown(this.boundAddKeyEvent);
        }

        this.setThumbContainerHeightPeriodical = setInterval(jQuery.proxy(this.setThumbContainerHeight, this) ,500);

        if(this.options.desPostion == 'left' || this.options.desPostion == 'right' && this.options.showLargeImage == 1)
        {
            this.setDesContainerHeightPeriodical = setInterval(jQuery.proxy(this.setDesContainerHeight, this) ,500);
        }

        if(this.options.allowRating == 2)
        {
            this.initializeRating();
        }

        if(this.options.showLargeImage == 1)
        {
            this.galleryParentWidth = jQuery('#'+this.options.mainWrapper).parent().width();
            this.checkGalleryParentSizePeriodical = setInterval(jQuery.proxy(this.checkGalleryParentSize, this) ,500);
        }
    },

    checkGalleryParentSize: function()
    {
        var galleryParentWidthNow = jQuery('#'+this.options.mainWrapper).parent().width();
        if(galleryParentWidthNow != this.galleryParentWidth)
        {
            setTimeout(jQuery.proxy(function()
            {
                jQuery('#'+this.options.largeImage).slick('slickSetOption', 'cssEase', 'ease', true);
            }, this) ,200);

            jQuery('#'+'magnifyImg').css('visibility','hidden');


            setTimeout(jQuery.proxy(function()
            {
                var slideDiv = jQuery('#'+this.options.largeImage).find('.ig-slick-image').eq(this.imageIndex);
                this.alignMagnify(slideDiv);
                jQuery('#'+'magnifyImg').css('visibility','visible');
            }, this) ,600);

            this.galleryParentWidth = galleryParentWidthNow;
        }
    },

    initializeHash: function()
    {
        if(this.options.showLargeImage == 1 && this.options.refreshMode == 'hash')
        {
            if(window.location.hash.length == 0)
            {
                if(this.getUrlParamater('thumb_limitstart') != 'unset')
                {
                    window.location.hash = 'gallery-' + this.options.uniqueid;
                }
                else
                {
                    this.addHash(this.options.jsonImagesImageType[0]);
                }
            }
        }

        this.checkHash(false);

        if(this.options.refreshMode == 'hash' && this.options.showLargeImage == 1)
        {
            this.setCheckHashPeriodical();
        }
    },

    initializeSlick: function()
    {
        if(this.options.showLargeImage == 1)
        {

            jQuery('#'+this.options.largeImage).find('.ig-slick-image').each(function(index,el)
            {
                jQuery(el).css('display','block');
            });

            //set up preloading
            this.tallestImageIndex = 0;
            this.tallestImageHeight = 0;
            jQuery.each(this.options.jsonImagesImageType, function(index, object)
            {
                if(object.height > this.tallestImageHeight)
                {
                    this.tallestImageHeight = object.height;
                    this.tallestImageIndex = index;
                }
            }.bind(this));
            this.loadImageNow(this.tallestImageIndex, false, true);

            this.loadImageNow(this.imageIndex, true, false);
            this.loadImageNow(this.imageIndex + 1, false, false);
            this.loadImageNow(this.imageIndex - 1, false, false);

            if(this.options.preload == 1 && this.options.showLargeImage == 1)
            {
                for(var i=0; i<12; i++)
                {
                    this.addToPreload(i);
                }
            }

            this.preloaderVar = setInterval(jQuery.proxy(this.preloadImages, this) ,750);

            //init slick
            if(this.isTouchDevice)
            {
                var fadeOn = this.options.transitionTouch == 'fade' ? true : false;
            }
            else
            {
                var fadeOn = this.options.transition == 'fade' ? true : false;
            }

            var transitionSpeed = this.options.transition == 'fade' ? this.options.fadeDuration : this.options.slideDuration;
            var showArrows = (this.options.showSlideshowControls && (this.options.slideshowPosition == 'left-right'))

            jQuery('#'+this.options.largeImage).on('init', function(event, slick)
            {
                jQuery('#'+this.options.largeImage).css('visibility', 'visible');
            }.bind(this));


            jQuery('#'+this.options.largeImage).slick(
                {
                    fade: fadeOn,
                    speed: transitionSpeed,
                    infinite: true,
                    initialSlide: this.imageIndex,
                    arrows: showArrows,
                    appendArrows: '#'+this.options.imageSlideshowContainer,
                    waitForAnimate: false

                });
            this.swapImage(this.options.jsonImagesImageType[this.imageIndex], 50, this.imageIndex, false);

            //add image swap behavior
            jQuery('#'+this.options.largeImage).on('beforeChange', function(event, slick, currentSlide, nextSlide)
            {


                this.loadImageNow(nextSlide, true, false);

                if(!fadeOn)
                {
                    var endClone = jQuery('#'+this.options.largeImage).find('.ig-slick-image').last();
                    endClone.imagesLoaded( function()
                    {
                        this.alignImage(endClone, false, false);

                    }.bind(this));

                    var firstClone = jQuery('#'+this.options.largeImage).find('.ig-slick-image').eq(0);
                    firstClone.imagesLoaded( function()
                    {
                        this.alignImage(firstClone, false, false);

                    }.bind(this));
                }

                this.swapImage(this.options.jsonImagesImageType[nextSlide], 50, nextSlide, true);

                var slideDiv = jQuery('#'+this.options.largeImage).find('.ig-slick-image').not('.slick-cloned').eq(currentSlide);
                var iframe = slideDiv.find('iframe');

                if(iframe.length)
                {
                    jQuery(iframe).attr('src', jQuery(iframe).attr('src'));
                }

            }.bind(this));


            if(!fadeOn)
            {
                //load 1st clone
                var slideDiv = jQuery('#'+this.options.largeImage).find('.ig-slick-image').eq(0);
                var img = slideDiv.find('.large_img');
                var imgLazySrc = img.attr('data-ig-lazy-src');
                var imgSrc = img.attr('src');
                if(typeof imgLazySrc !== 'undefined')
                {
                    if(imgSrc != imgLazySrc)
                    {
                        img.attr('src',imgLazySrc);
                    }
                }
                slideDiv.imagesLoaded( function()
                {
                    this.alignImage(slideDiv, false, false);

                }.bind(this));

                var endClone = jQuery('#'+this.options.largeImage).find('.ig-slick-image').last();
                endClone.imagesLoaded( function()
                {
                    this.alignImage(endClone, false, false);

                }.bind(this));
            }

        }
    },

    loadImageNow: function(index, magnify, tallest)
    {
        if(index < this.options.jsonImagesImageType.length && index >= 0)
        {
            var slideDiv = jQuery('#'+this.options.largeImage).find('.ig-slick-image').not('.slick-cloned').eq(index);
            var img = slideDiv.find('.large_img');

            if(img.length == 0)
            {
                return;
            }

            var imgLazySrc = img.attr('data-ig-lazy-src');
            var imgSrc = img.attr('src');

            if(typeof imgLazySrc !== 'undefined')
            {
                if(imgSrc != imgLazySrc)
                {
                    img.attr('src',imgLazySrc);
                }
            }

            slideDiv.imagesLoaded( function()
            {
                this.alignImage(slideDiv, magnify, tallest);

            }.bind(this));
        }
    },

    alignImage: function(nextSlideDiv, magnify, tallest)
    {
        if(this.options.imageAlignVert != 'top')
        {
            var nextSlideDivHeight = nextSlideDiv.height();
            if(nextSlideDivHeight < 30){return;}
            var trackHeight = jQuery('#'+this.options.largeImage).find('.slick-track').height();

            if(trackHeight > nextSlideDivHeight)
            {
                if(this.options.imageAlignVert == 'bottom')
                {
                    slideMarginTop = trackHeight - nextSlideDivHeight;
                }
                else
                {
                    slideMarginTop = (trackHeight - nextSlideDivHeight)/2;
                }

                nextSlideDiv.css('margin-top', slideMarginTop + 'px');
            }
        }

        if(magnify && this.options.main == true && this.options.magnify)
        {
            this.alignMagnify(nextSlideDiv)
        }

        if(tallest)
        {
            var currentSlide = jQuery('#'+this.options.largeImage).find('.ig-slick-image').not('.slick-cloned').eq(this.imageIndex);
            currentSlide.imagesLoaded( function()
            {
                this.alignImage(currentSlide, true, false);

            }.bind(this));
        }

    },

    alignMagnify: function(nextSlideDiv)
    {
        if(this.options.lightboxOn == 1)
        {
            if( jQuery('#magnifyImg').length )
            {
                jQuery('#magnifyImg').remove();
            }

            var nextImg = nextSlideDiv.find('.main_image_overlay_wrapper');
            if(nextImg.length == 0)
            {
                return;
            }
            var nextImgWidth = nextImg.width();
            var nextImgHeight = nextImg.height();
            var xOffset = nextImg.position().left;
            var yOffset = nextSlideDiv.css('margin-top');
            var topOffSet = parseInt(yOffset) + parseInt(nextImgHeight) - 27;
            var leftOffSet = parseInt(xOffset) + parseInt(nextImgWidth) - 28;

            var magnifyImg = jQuery('<img/>',
                {
                    'id': 'magnifyImg',
                    'src': this.options.hostRelative + '/media/com_igallery/images/magnify.png'
                });

            magnifyImg.css(
                {
                    'display': 'block',
                    'position' : 'absolute',
                    'top' : topOffSet + 'px',
                    'left' : leftOffSet + 'px'
                });

            jQuery('#'+this.options.largeImage).append(magnifyImg);
        }
    },

    initializeRating: function()
    {
        if( jQuery('#'+this.options.ratingsContainer).length )
        {
            var stars = jQuery('#'+this.options.ratingsContainer).find('a.rating_star');

            stars.each(function(index,el)
            {
                jQuery(el).on('click', function(event)
                {
                    event.preventDefault();
                    jQuery('#'+this.options.ratingsContainer).find('span.rating_loading_gif').css('visibility', 'visible');

                    var ratingUrl = this.options.hostRelative + '/index.php?option=com_igallery&task=imagefront.addRating&format=raw&rating=' + (index + 1) + '&imageid=' + this.options.idArray[this.imageIndex];

                    jQuery.ajax({url: ratingUrl,

                        error: function(request)
                        {
                            jQuery('#'+this.options.ratingsContainer).find('span.rating_message').html('Error: ' + request.responseText);
                        }.bind(this),

                        success: function(response)
                        {
                            jQuery('#'+this.options.ratingsContainer).find('span.rating_loading_gif').css('visibility', 'hidden');

                            response = response.trim();
                            if( response.indexOf('{') > 0 )
                            {
                                response  = response.substr(response.indexOf('{') );
                            }

                            responseObject = jQuery.parseJSON(response);

                            jQuery('#'+this.options.ratingsContainer).find('span.rating_message').html(responseObject.message);
                            if(responseObject.success == 1)
                            {
                                this.options.jsonImages.general[this.imageIndex].ratingAverage = responseObject.average;
                                this.options.jsonImages.general[this.imageIndex].ratingCount++;

                                this.swapRatings(this.imageIndex, false);
                            }
                        }.bind(this)});

                }.bind(this));
            }.bind(this));
        }
    },

    initializeSlideShow: function()
    {
        this.clearSlideShow();

        if(this.options.showSlideshowControls == 1 && this.options.slideshowPosition == 'below')
        {
            jQuery('#'+this.options.slideshowForward).off('click');
            jQuery('#'+this.options.slideshowForward).on('click', function(e)
            {
                e.stopPropagation();
                this.clearSlideShow();
                this.slideShowSwap(true);
            }.bind(this));

            jQuery('#'+this.options.slideshowRewind).off('click');
            jQuery('#'+this.options.slideshowRewind).on('click', function(e)
            {
                e.stopPropagation();
                this.clearSlideShow();
                this.slideShowSwap(false);
            }.bind(this));
        }

        if(this.options.slideshowAutostart == 1 && this.options.showLargeImage == 1)
        {
            this.slideShowStart(false);
        }

        if(this.options.slideshowPosition == 'left-right' && this.options.showSlideshowControls == 1 && this.isIE8 == false)
        {
            var forwardArrow = jQuery('#'+this.options.imageSlideshowContainer).find('.slick-next');
            var backArrow = jQuery('#'+this.options.imageSlideshowContainer).find('.slick-prev');
            this.leftRightSlideBaseOpacity = this.isTouchDevice ? 0.5 : 0.5;

            forwardArrow.css('opacity', this.leftRightSlideBaseOpacity);
            backArrow.css('opacity', this.leftRightSlideBaseOpacity);

            forwardArrow.on('click', function()
            {
                this.clearSlideShow();
            }.bind(this));

            backArrow.on('click', function()
            {
                this.clearSlideShow();
            }.bind(this));

            if(!this.isTouchDevice)
            {
                forwardArrow.off('mouseenter');
                forwardArrow.on('mouseenter', function()
                {
                    forwardArrow.fadeTo(250,0.9);
                }.bind(this));

                forwardArrow.on('mouseleave', function()
                {
                    forwardArrow.fadeTo(250,this.leftRightSlideBaseOpacity);
                }.bind(this));

                backArrow.off('mouseenter');
                backArrow.on('mouseenter', function()
                {
                    backArrow.fadeTo(250,0.9);
                }.bind(this));

                backArrow.on('mouseleave', function()
                {
                    backArrow.fadeTo(250,this.leftRightSlideBaseOpacity);
                }.bind(this));
            }
        }
    },

    slideShowStart : function(instant)
    {
        if(instant == true)
        {
            this.slideShowSwap(true);
        }

        this.slideShowObject = setInterval(jQuery.proxy(this.slideShowSwap, this, true) ,this.options.slideshowPause);

        if(this.options.showSlideshowControls == 1 && jQuery('#'+this.options.slideshowPlay).length  )
        {
            jQuery('#'+this.options.slideshowPlay).removeClass('ig_slideshow_play');
            jQuery('#'+this.options.slideshowPlay).addClass('ig_slideshow_pause');
            jQuery('#'+this.options.slideshowPlay).off('click');
            jQuery('#'+this.options.slideshowPlay).on('click', function()
            {
                this.clearSlideShow();
            }.bind(this));
        }
    },

    slideShowSwap : function(forward)
    {
        if(forward == true)
        {
            if(this.imageIndex == this.options.numPics - 1)
            {
                this.imageIndex = 0;
            }
            else
            {
                this.imageIndex++;
            }
        }
        else
        {
            if(this.imageIndex == 0)
            {
                this.imageIndex = this.options.numPics - 1;
            }
            else
            {
                this.imageIndex--;
            }
        }

        if(this.options.main == 1)
        {
            jQuery('#'+this.options.largeImage).slick('slickGoTo', this.imageIndex);
        }
        else
        {
            jQuery('#'+this.options.largeImage).slick('slickGoTo', this.imageIndex);
        }
    },

    clearSlideShow : function()
    {
        clearInterval(this.slideShowObject);

        if(this.options.showSlideshowControls == 1 && jQuery('#'+this.options.slideshowPlay).length )
        {
            jQuery('#'+this.options.slideshowPlay).removeClass('ig_slideshow_pause');
            jQuery('#'+this.options.slideshowPlay).addClass('ig_slideshow_play');
            jQuery('#'+this.options.slideshowPlay).off('click');
            jQuery('#'+this.options.slideshowPlay).on('click', function()
            {
                this.slideShowStart(true);
            }.bind(this));
        }
    },

    initializeThumbs: function(index, lightboxShowCounter)
    {
        var activeThumbId = this.options.prefix + '-' + this.options.uniqueid + '-' + (index + 1);
        if( jQuery('#'+activeThumbId).length )
        {
            jQuery('#'+this.options.thumbContainer).scrollTo(jQuery('#'+activeThumbId),50);
        }

        if(lightboxShowCounter == 0)
        {
            if(this.options.showThumbArrows == 1)
            {
                setTimeout(jQuery.proxy(function()
                {
                    var hasXOverflow = (jQuery('#'+this.options.thumbTable).width() > (jQuery('#'+this.options.thumbContainer).width() + 20));
                    var hasYOverflow = (jQuery('#'+this.options.thumbTable).height() > (jQuery('#'+this.options.thumbContainer).height() + 20));
                    var xScrollAmount = jQuery('#'+this.options.thumbContainer).width() - 120;
                    var yScrollAmount = jQuery('#'+this.options.thumbContainer).height() - 120;

                    if(hasXOverflow)
                    {
                        this.addArrowBehaviors(this.options.rightArrow, xScrollAmount, 'horizontal', 'right');
                        this.addArrowBehaviors(this.options.leftArrow, -xScrollAmount, 'horizontal', 'left');
                    }
                    else if(hasYOverflow)
                    {
                        this.addArrowBehaviors(this.options.upArrow, -yScrollAmount, 'vertical', 'up');
                        this.addArrowBehaviors(this.options.downArrow, yScrollAmount, 'vertical', 'down');
                    }
                }, this) ,1200);
            }

            var thumblinksArray = jQuery('#'+this.options.thumbContainer).find('a.imglink');

            thumblinksArray.each(function(index,el)
            {
                jQuery(el).on('click', function(event)
                {
                    event.preventDefault();
                    this.clearSlideShow();

                    if(this.options.showLargeImage == 0 && this.options.main == 1)
                    {
                        var imgLink = this.options.jsonImages.general[index].url;
                        var imgTargetBlank = this.options.jsonImages.general[index].targetBlank;

                        if(imgLink.length > 1)
                        {
                            jQuery(el).css('cursor', 'pointer');

                            if(imgTargetBlank == 1)
                            {
                                window.open(imgLink);
                            }
                            else
                            {
                                window.location = imgLink;
                            }
                        }
                        else
                        {
                            if(this.options.lightboxOn == 1)
                            {
                                var opentoFullscreen = this.options.fullscreen == 'open-fullscreen' ? true : false;

                                this.showLightBox(index, opentoFullscreen);

                                if(this.options.fullscreen == 'open-fullscreen')
                                {
                                    this.lboxFullscreenOn();
                                }
                            }
                        }
                    }
                    else
                    {
                        jQuery('#'+this.options.largeImage).slick('slickGoTo', index);
                    }

                }.bind(this));

            }.bind(this));
        }

        if(this.options.thumbLayout == 'grid')
        {
            if(this.options.thumbGridType == 'justified')
            {
                jQuery('#'+'main_thumb_grid' + this.options.uniqueid + ' ' + '.ig_grid_lazy_div').appendTo(jQuery('#'+'main_justified_lazy_container' + this.options.uniqueid));
            }

            this.createResponsiveGrid(true);
            this.createResponsiveGridPeriodical = setInterval(jQuery.proxy(this.createResponsiveGrid, this, false) ,800);

            if(this.options.thumbGridType != 'justified')
            {
                jQuery('#'+'main_thumb_grid' + this.options.uniqueid + ' ' + 'img.ig_grid_lazy').lazyload({
                    effect : 'fadeIn',
                    load : function(elements_left, settings)
                    {
                        var thumbDiv = jQuery(this).closest('.ig_grid_cell');
                        thumbDiv.css('height','auto');
                        thumbDiv.attr('data-lazyloadcomplete',1);
                    }
                });
            }
            else
            {
                jQuery(window).scroll(function()
                {
                    var thumbGridDiv = jQuery('#'+'main_thumb_grid' + this.options.uniqueid);
                    var thumbGridDivBottom = thumbGridDiv.offset().top + thumbGridDiv.outerHeight(true);

                    if((thumbGridDivBottom - 350) < jQuery(window).scrollTop() + jQuery(window).height())
                    {
                        var lazyThumbImages = jQuery('#'+'main_justified_lazy_container' + this.options.uniqueid + ' .ig_grid_lazy_div:lt(5)');

                        if(lazyThumbImages.length > 0)
                        {
                            lazyThumbImages.each(function(index,el)
                            {
                                jQuery(el).find('.ig_thumb').attr('src', jQuery(el).find('.ig_thumb').attr('data-original') );
                                jQuery(el).appendTo(jQuery('#'+'main_thumb_grid' + this.options.uniqueid));

                            }.bind(this));

                            jQuery('#'+'main_thumb_grid' + this.options.uniqueid).justifiedGallery('norewind');
                        }

                    }
                }.bind(this));

                jQuery(window).scroll();
            }
        }
        else
        {
            jQuery('#'+this.options.thumbContainer + ' ' + 'img.ig_scroller_lazy').lazyload({
                effect : 'fadeIn',
                container: jQuery('#'+this.options.thumbContainer),
                failure_limit : 20
            });
        }

        if(this.options.thumbHoverEffect == 'fade_to_grey' && this.isTouchDevice == false)
        {
            jQuery('#'+this.options.thumbContainer + ' ' + '.ig_thumb_cell').hover(
                function()
                {
                    var position  = jQuery(this).find('img.ig_thumb').position();

                    jQuery("<div/>", {
                        class: 'black_fade',
                        css: {
                            'position': 'absolute',
                            'top': (position.top + parseInt(jQuery(this).find('img.ig_thumb').css('padding-top')) + parseInt(jQuery(this).find('img.ig_thumb').css('margin-top')) ) +'px',
                            'left': (position.left + parseInt(jQuery(this).find('img.ig_thumb').css('padding-left')) + parseInt(jQuery(this).find('img.ig_thumb').css('margin-left')) ) +'px',
                            'background-color': '#000000',
                            'opacity': 0,
                            'width': jQuery(this).find('img.ig_thumb').width()+'px',
                            'height': jQuery(this).find('img.ig_thumb').height()+'px'
                        }
                    }).appendTo(jQuery(this).find('a.imglink'));

                    jQuery(this).find('.black_fade').fadeTo('slow', 0.3);
                },
                function()
                {
                    jQuery(this).find('.black_fade').fadeTo('slow', 0, function() {
                        jQuery(this).remove();
                    });
                }
            );
        }
    },

    createResponsiveGrid: function(firstTime)
    {
        var gridWidth = jQuery('#'+'main_thumb_grid' + this.options.uniqueid).width();

        var reloadForLazy = false;
        var lazyThumbCells = jQuery('#'+'main_thumb_grid' + this.options.uniqueid).find('.ig_grid_cell');
        lazyThumbCells.each(function(index,el)
        {
            if(jQuery(el).attr('data-lazyloadcomplete') == 1)
            {
                reloadForLazy = true;
                jQuery(el).removeAttr('data-lazyloadcomplete');
            }

        });

        if(gridWidth != this.lastThumbsGridWidth || reloadForLazy == true)
        {
            var gridCells = jQuery('#'+'main_thumb_grid' + this.options.uniqueid).find('.ig_grid_cell');
            var maxWidth = jQuery('#'+'main_thumb_grid' + this.options.uniqueid).attr('data-maxthumbwidth');

            if(this.options.thumbGridType == 'justified')
            {
                jQuery('#'+'main_thumb_container' + this.options.uniqueid).css('visibility','visible');

                jQuery('#'+'main_thumb_grid' + this.options.uniqueid).justifiedGallery({
                    margins: this.options.thumbGridSpacing
                });
            }
            else
            {
                if(gridWidth%maxWidth > maxWidth/5)
                {
                    var columns = Math.ceil(gridWidth/maxWidth);
                }
                else
                {
                    var columns = Math.floor(gridWidth/maxWidth);
                }

                var gutter = this.options.thumbGridSpacing;
                var colWidth = (gridWidth - (gutter * (columns - 1)))/columns;


                gridCells.each(function(index,el)
                {
                    jQuery(el).css('width',Math.floor(colWidth));
                });

                var layoutMode = this.options.thumbGridType == 'by_columns' ? 'masonry' : 'fitRows';

                if(firstTime)
                {
                    this.responsiveGrid = jQuery('#'+'main_thumb_grid' + this.options.uniqueid).isotope({
                        itemSelector: '.ig_grid_cell',
                        layoutMode: layoutMode,
                        masonry: {
                            gutter:gutter
                        },
                        fitRows: {
                            gutter:(gutter - 1)
                        }

                    });

                    this.thumbLoadCount=1;
                    this.responsiveGrid.imagesLoaded().progress(function()
                    {
                        this.responsiveGrid.isotope('layout');
                        if(this.thumbLoadCount == 15 || this.thumbLoadCount >= this.options.numPics)
                        {
                            jQuery('#'+'main_thumb_container' + this.options.uniqueid).css('visibility','visible');
                        }
                        this.thumbLoadCount++;
                    }.bind(this));
                }
                else
                {
                    this.responsiveGrid.isotope('layout');
                }
            }

        }
        this.lastThumbsGridWidth = gridWidth;
    },

    addArrowBehaviors: function(arrow, pixels, mode, direction)
    {
        var child = jQuery('#'+arrow).children('div').first();
        jQuery('#'+arrow).css('display', 'block');

        if(this.isIE8)
        {
            //jQuery('#'+arrow).css('max-width', 'none');
        }

        if(!this.isIE8)
        {
            jQuery('#'+arrow).css('opacity', 0.8);

            jQuery('#'+arrow).on('mouseenter', function()
            {
                jQuery('#'+arrow).fadeTo(250,0.95);
            }.bind(this));

            jQuery('#'+arrow).on('mouseleave', function()
            {
                jQuery('#'+arrow).fadeTo(250,0.8);
            }.bind(this));
        }

        jQuery('#'+arrow).on('click', function(e)
        {
            var currentScrollX = jQuery('#'+this.options.thumbContainer).scrollLeft();
            var currentScrollY = jQuery('#'+this.options.thumbContainer).scrollTop();

            if(direction == 'right')
            {
                jQuery('#'+this.options.thumbContainer).stop();

                jQuery('#'+this.options.thumbContainer).scrollTo(currentScrollX + pixels, 700, {easing:'linear',onAfter: function()
                {
                    if(this.hoverRightThumbArrow)
                    {
                        jQuery('#'+arrow).trigger('mouseenter');
                    }}.bind(this)
                });
            }

            if(direction == 'left')
            {
                jQuery('#'+this.options.thumbContainer).stop();
                jQuery('#'+this.options.thumbContainer).scrollTo(currentScrollX + pixels, 700,{easing:'linear',onAfter: function()
                {
                    if(this.hoverLeftThumbArrow)
                    {
                        jQuery('#'+arrow).trigger('mouseenter');
                    }}.bind(this)
                });
            }

            if(direction == 'up')
            {
                jQuery('#'+this.options.thumbContainer).stop();
                jQuery('#'+this.options.thumbContainer).scrollTo(currentScrollY + pixels, 700,{easing:'linear',onAfter: function()
                {
                    if(this.hoverUpThumbArrow)
                    {
                        jQuery('#'+arrow).trigger('mouseenter');
                    }}.bind(this)
                });
            }

            if(direction == 'down')
            {
                jQuery('#'+this.options.thumbContainer).stop();
                jQuery('#'+this.options.thumbContainer).scrollTo(currentScrollY + pixels, 700,{easing:'linear',onAfter: function()
                {
                    if(this.hoverDownThumbArrow)
                    {
                        jQuery('#'+arrow).trigger('mouseenter');
                    }}.bind(this)
                });

            }

        }.bind(this));

        if(!this.iOS && !this.isAndroid)
        {
            jQuery('#'+arrow).on('mouseenter', function()
            {
                if(direction == 'right')
                {
                    this.hoverRightThumbArrow = true;
                    var duration = (jQuery('#'+this.options.thumbTable).width() - (jQuery('#'+this.options.thumbContainer).scrollLeft() + jQuery('#'+this.options.thumbContainer).width())) * 3;
                    jQuery('#'+this.options.thumbContainer).scrollTo('max', duration,{easing:'linear'});
                }
                if(direction == 'left')
                {
                    this.hoverLeftThumbArrow = true;
                    var duration = jQuery('#'+this.options.thumbContainer).scrollLeft() * 3;
                    jQuery('#'+this.options.thumbContainer).scrollTo(0, duration,{easing:'linear'});
                }

                if(direction == 'down')
                {
                    this.hoverDownThumbArrow = true;
                    var duration = (jQuery('#'+this.options.thumbTable).height() - (jQuery('#'+this.options.thumbContainer).scrollTop() + jQuery('#'+this.options.thumbContainer).width())) * 3;
                    jQuery('#'+this.options.thumbContainer).scrollTo('max', duration,{easing:'linear'});
                }
                if(direction == 'up')
                {
                    this.hoverUpThumbArrow = true;
                    var duration = jQuery('#'+this.options.thumbContainer).scrollTop() * 3;
                    jQuery('#'+this.options.thumbContainer).scrollTo(0, duration,{easing:'linear'});
                }
            }.bind(this));

            jQuery('#'+arrow).on('mouseleave', function()
            {
                jQuery('#'+this.options.thumbContainer).stop();

                this.hoverLeftThumbArrow = false;
                this.hoverRightThumbArrow = false;
                this.hoverUpThumbArrow = false;
                this.hoverDownThumbArrow = false;

            }.bind(this));
        }
    },

    addKeyEvent: function(event)
    {
        if(event.keyCode == 37)
        {
            this.clearSlideShow();
            this.slideShowSwap(false);
        }

        else if(event.keyCode == 39)
        {
            this.clearSlideShow();
            this.slideShowSwap(true);
        }

        if(this.options.main == 0)
        {
            if(event.keyCode == 27)
            {
                this.mainGalleryObject.closeLightBox(this.imageIndex);
            }
        }
    },

    showLightBox : function(index, openToFullscreen)
    {
        this.lboxGalleryObject.imageIndex = index;

        this.lboxGalleryObject.checkHash(false);
        this.clearSlideShow();

        if(this.options.refreshMode == 'hash')
        {
            this.lboxGalleryObject.setCheckHashPeriodical();
            this.clearCheckHashPeriodical();
        }

        if(this.lboxGalleryObject.options.preload == 1 && this.lboxPreloadStarted == false)
        {
            this.lboxGalleryObject.lboxPreloadStarter();
            this.lboxPreloadStarted = true;
        }

        var bodyTag = jQuery('body');
        this.scrolledDown = openToFullscreen == true ? 0 : jQuery(window).scrollTop();
        var totalScrollHeight = jQuery(document).height();
        var windowWidth = jQuery(window).width();
        var windowHeight = jQuery(window).height();
        var lboxPaddingLeft = parseInt( jQuery('#'+this.options.lboxWhite).css('padding-left') )
        var lboxPaddingRight = parseInt( jQuery('#'+this.options.lboxWhite).css('padding-right') );
        var lboxPadding = (lboxPaddingLeft + lboxPaddingRight) / 2;

        if(this.lightboxShowCounter == 0)
        {
            jQuery('body').prepend( jQuery('#'+this.options.lboxWhite) );
        }

        var topSpace = this.options.phone ? 0 : 30;
        jQuery('#'+this.options.lboxWhite).css
        ({
            'top': this.scrolledDown + topSpace,
            'opacity': '0',
            'display': 'block'
        });

        totalScrollHeight = jQuery(document).height();

        jQuery('body').prepend( jQuery('#'+this.options.lboxDark) );
        jQuery('#'+this.options.lboxDark).css
        ({
            'height': totalScrollHeight,
            'opacity': '0.01',
            'display': 'block'
        });

        this.resetLboxHeightPeriodical = setInterval(jQuery.proxy(this.resetLboxHeight, this) ,750);

        if(this.lboxGalleryObject.options.thumbPostion == 'left' || this.lboxGalleryObject.options.thumbPostion == 'right')
        {
            this.lboxSetThumbContainerHeightPeriodical = setInterval(jQuery.proxy(this.lboxSetThumbContainerHeight, this) ,500);
        }

        if(this.lboxGalleryObject.options.desPostion == 'left' || this.lboxGalleryObject.options.desPostion == 'right')
        {
            this.lboxSetDesContainerHeightPeriodical = setInterval(jQuery.proxy(this.lboxSetDesContainerHeight, this) ,500);
        }

        var targetOpacity = this.options.lightboxBackOpacity/100;
        jQuery('#'+this.options.lboxDark).fadeTo(200,targetOpacity);
        jQuery('#'+this.options.lboxWhite).fadeTo(200,1);


        if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
        {
            var jcommentsClone = jQuery('#jc').clone();
            jQuery('#jc').remove();

            jQuery('#'+this.options.jCommentsLbox).prepend( jcommentsClone );

            this.totalScrollHeight = jQuery(document).height();
            jQuery('#'+this.options.lboxDark).css('height', this.totalScrollHeight);
        }

        if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
        {
            var jcforms = jQuery('#jc').find('#comments-form');
            jcforms.each(function(index,el)
            {
                if(index != 0)
                {
                    el.remove();
                }
            });
        }

        if(this.lboxGalleryObject.options.allowRating == 2 && this.lightboxShowCounter == 0)
        {
            this.lboxGalleryObject.initializeRating();
        }

        if( !(this.lboxGalleryObject.options.slideshowPosition == 'left-right' && this.lboxGalleryObject.options.showSlideshowControls == 1) )
        {
            jQuery('#'+this.lboxGalleryObject.options.largeImage).off('click');
            jQuery('#'+this.lboxGalleryObject.options.largeImage).on('click', function()
            {
                this.lboxGalleryObject.clearSlideShow();
                this.lboxGalleryObject.slideShowSwap(true);
            }.bind(this));
        }

        if(this.lboxGalleryObject.options.showThumbs == 1)
        {
            this.lboxGalleryObject.initializeThumbs(this.lboxGalleryObject.imageIndex, this.lightboxShowCounter);
        }

        jQuery('body').off('keydown', this.boundAddKeyEvent);
        this.lboxBoundAddKeyEvent = this.lboxGalleryObject.addKeyEvent.bind(this.lboxGalleryObject);
        jQuery('body').keydown(this.lboxBoundAddKeyEvent);

        if(jQuery('#'+this.lboxGalleryObject.options.closeImage).length)
        {
            jQuery('#'+this.lboxGalleryObject.options.closeImage).off('click');

            jQuery('#'+this.lboxGalleryObject.options.closeImage).on('click', function(e)
            {
                this.closeLightBox(this.lboxGalleryObject.imageIndex);
                this.lboxFullscreenOff();

            }.bind(this));
        }

        jQuery('#'+this.options.lboxDark).off('click');
        jQuery('#'+this.options.lboxDark).on('click', function(e)
        {
            this.closeLightBox(this.lboxGalleryObject.imageIndex);

            this.lboxFullscreenOff();

        }.bind(this));



        if(this.options.showLargeImage == 0 && this.options.refreshMode == 'hash')
        {
            if(window.location.hash.length == 0)
            {
                this.addHash(this.lboxGalleryObject.options.jsonImagesImageType[this.lboxGalleryObject.imageIndex]);
            }
        }

        if(this.lightboxShowCounter == 0)
        {
            this.lboxGalleryObject.initializeSlick();
        }
        else
        {
            jQuery('#'+this.lboxGalleryObject.options.largeImage).slick('slickGoTo', this.lboxGalleryObject.imageIndex);
        }

        this.lboxGalleryObject.initializeSlideShow();

        this.setLboxWidth();
        //if(this.lightboxShowCounter == 0)
        //{
        this.setLboxWidthPeriodical = setInterval(jQuery.proxy(this.setLboxWidth, this) ,600);
        //}

        if(this.lightboxShowCounter == 0)
        {
            if(this.options.fullscreen == 'show-icon')
            {
                if(jQuery('#lbox_fullscreen'+this.options.uniqueid).length)
                {
                    jQuery('#lbox_fullscreen'+this.options.uniqueid).on('click', function()
                    {
                        this.lboxFullscreenOn();
                    }.bind(this));
                }
            }

            if(this.options.fullscreen == 'show-icon' || this.options.fullscreen == 'open-fullscreen')
            {
                jQuery(document).bind("fullscreenchange", function()
                {
                    this.setLboxWidth();
                    if(!jQuery(document).fullScreen() )
                    {
                        if(this.options.lboxBackColor == 'black' && this.options.lboxFrontColor == 'none')
                        {
                            jQuery('#'+this.options.lboxWhite).css('background-color', 'transparent');
                        }
                        this.lboxFullscreenOff();
                    }
                }.bind(this));
            }
        }


        setTimeout(jQuery.proxy(function(){jQuery('#'+this.lboxGalleryObject.options.largeImage).slick('slickSetOption', 'cssEase', 'ease', true);}, this) ,100);
        setTimeout(jQuery.proxy(function(){jQuery('#'+this.lboxGalleryObject.options.largeImage).slick('slickSetOption', 'cssEase', 'ease', true);}, this) ,250);
        setTimeout(jQuery.proxy(function(){jQuery('#'+this.lboxGalleryObject.options.largeImage).slick('slickSetOption', 'cssEase', 'ease', true);}, this) ,400);

        if(this.lightboxShowCounter == 0)
        {
            this.lboxWidth = jQuery('#'+this.options.lboxWhite).width();
            this.checkLboxWidthChangePeriodical = setInterval(jQuery.proxy(this.checkLboxWidthChange, this) ,400);
        }

        this.lightboxShowCounter++;

    },

    checkLboxWidthChange: function()
    {
        var lboxWidthNow = jQuery('#'+this.options.lboxWhite).width();
        if(lboxWidthNow != this.lboxWidth)
        {
            setTimeout(jQuery.proxy(function()
            {
                jQuery('#'+this.lboxGalleryObject.options.largeImage).slick('slickSetOption', 'cssEase', 'ease', true);
            }, this) ,200);

            this.lboxWidth = lboxWidthNow;
        }
    },

    closeLightBox : function(index)
    {
        clearInterval(this.setLboxWidthPeriodical);

        if(this.options.refreshMode == 'hash')
        {
            this.lboxGalleryObject.clearCheckHashPeriodical();

            if(this.options.showLargeImage == 1)
            {
                this.setCheckHashPeriodical();
            }
        }

        this.lboxGalleryObject.clearSlideShow();
        this.lboxGalleryObject.lastImageDisplayedIndex = -1;

        if(this.lboxGalleryObject.options.allowComments == 2 && this.options.allowComments == 2)
        {
            var jcommentsClone = jQuery('#jc').clone();
            jQuery('#jc').remove();
            jQuery('#'+this.options.jCommentsMain).prepend( jcommentsClone );

            jcomments.showPage(this.options.idArray[this.imageIndex],'com_igallery',0);

            if(jQuery('#comments-form').length)
            {
                if(jQuery('#addcomments').length)
                {
                    var addCommentLink = jQuery('#addcomments');
                    addCommentLink.attr('onclick', "jcomments.showForm(" + this.options.idArray[this.imageIndex] + ",'com_igallery\', 'comments-form-link'); return false;");
                }
            }
            else
            {
                var objectIdInput = jQuery('#comments-form').find('input[name=object_id]');
                objectIdInput.attr('value', this.options.idArray[this.imageIndex]);

                var jcforms = jQuery('#jc').find('#comments-form');
                jcforms.each(function(index,el)
                {
                    if(index != 0)
                    {
                        el.remove();
                    }
                });
            }
        }

        var targetOpacity = this.options.lightboxBackOpacity/100;

        jQuery('#'+this.options.lboxDark).fadeTo(50,0,function(){
            jQuery('#'+this.options.lboxDark).css('display','none');
        }.bind(this));

        jQuery('#'+this.options.lboxWhite).fadeTo(50,0,function(){
            jQuery('#'+this.options.lboxWhite).css('display','none');
        }.bind(this));

        jQuery('body').off('keydown', this.lboxBoundAddKeyEvent);
        if(this.options.showLargeImage == 1)
        {
            this.boundAddKeyEvent = this.addKeyEvent.bind(this);
            jQuery('body').keydown(this.boundAddKeyEvent);

            jQuery('#'+this.options.largeImage).slick('slickGoTo', this.lboxGalleryObject.imageIndex);
        }

        if(this.options.showLargeImage == 0 && this.options.refreshMode == 'hash')
        {
            window.location.hash = '!';
        }

        jQuery('#'+ this.lboxGalleryObject.options.largeImage).find('.ig-slick-image').each(function(index,el)
        {
            jQuery(el).css('margin-top',0);
        });

        this.lboxGalleryObject.firstShow = true;


    },

    lboxFullscreenOn: function()
    {
        if(!this.isSafariMac)
        {
            jQuery('#'+this.options.lboxWhite).css('margin', '0 auto');
        }

        var topSpace = this.options.phone ? 0 : 30;
        jQuery('#'+this.options.lboxWhite).css('top',topSpace+'px');


        if(this.options.lboxBackColor == 'black' && this.options.lboxFrontColor == 'none')
        {
            jQuery('#'+this.options.lboxWhite).css('background-color', '#000000');
        }

        jQuery('#'+this.options.lboxWhite).fullScreen(true);
        this.setLboxWidth();

        if(this.options.fullscreen == 'show-icon')
        {
            if(jQuery('#lbox_fullscreen'+this.options.uniqueid).length)
            {
                jQuery('#lbox_fullscreen'+this.options.uniqueid).removeClass('lbox_fullscreen_open');
                jQuery('#lbox_fullscreen'+this.options.uniqueid).addClass('lbox_fullscreen_close');

                jQuery('#lbox_fullscreen'+this.options.uniqueid).off('click');

                jQuery('#lbox_fullscreen'+this.options.uniqueid).on('click', function()
                {
                    this.lboxFullscreenOff();
                }.bind(this));
            }
        }

        if(jQuery('#'+this.lboxGalleryObject.options.closeImage).length)
        {
            jQuery('#'+this.lboxGalleryObject.options.closeImage).removeClass('closeImage_not_phone');
            jQuery('#'+this.lboxGalleryObject.options.closeImage).addClass('closeImage_phone');
        }
    },

    lboxFullscreenOff: function()
    {
        if(this.options.lboxBackColor == 'black' && this.options.lboxFrontColor == 'none')
        {
            jQuery('#'+this.options.lboxWhite).css('background-color', 'transparent');
        }


        jQuery('#'+this.options.lboxWhite).css('visibility','hidden');
        jQuery('#'+this.lboxGalleryObject.options.largeImage).css('visibility','hidden');

        jQuery('#'+ this.lboxGalleryObject.options.largeImage).find('.ig-slick-image').each(function(index,el)
        {
            jQuery(el).css('margin-top',0);
        });


        if(this.options.fullscreen == 'show-icon' || this.options.fullscreen == 'open-fullscreen')
        {
            jQuery(document).fullScreen(false);
        }

        var topSpace = (this.options.phone ? 0 : 30) + this.scrolledDown;
        jQuery('#'+this.options.lboxWhite).css('top',topSpace+'px');


        setTimeout(jQuery.proxy(function()
        {
            jQuery('#'+this.options.lboxWhite).css('visibility','visible');
            jQuery('#'+this.lboxGalleryObject.options.largeImage).css('visibility','visible');
        }, this) ,50);

        if(jQuery('#'+this.lboxGalleryObject.options.closeImage).length && this.options.phone == 0)
        {
            jQuery('#'+this.lboxGalleryObject.options.closeImage).removeClass('closeImage_phone');
            jQuery('#'+this.lboxGalleryObject.options.closeImage).addClass('closeImage_not_phone');
        }

        if(jQuery('#lbox_fullscreen'+this.options.uniqueid).length)
        {
            jQuery('#lbox_fullscreen'+this.options.uniqueid).removeClass('lbox_fullscreen_close');
            jQuery('#lbox_fullscreen'+this.options.uniqueid).addClass('lbox_fullscreen_open');

            jQuery('#lbox_fullscreen'+this.options.uniqueid).off('click');

            jQuery('#lbox_fullscreen'+this.options.uniqueid).on('click', function()
            {
                this.lboxFullscreenOn();
            }.bind(this));
        }
    },

    setLboxWidth: function()
    {
        var windowWidth = jQuery(window).width();
        var windowHeight = jQuery(window).height();


        if(windowWidth != this.lastWindowWidth || windowHeight != this.lastWindowHeight)
        {
            var lboxPaddingLeft = parseInt( jQuery('#'+this.options.lboxWhite).css('padding-left') );
            var lboxPaddingRight = parseInt( jQuery('#'+this.options.lboxWhite).css('padding-right') );
            var lboxWidthNoPadding = this.options.lightboxWidth;
            var lboxWidthWithPadding = this.options.lightboxWidth + lboxPaddingLeft + lboxPaddingRight;
            var lboxMargin = this.options.phone ? 0 : 30;
            var windowHeightSpace = windowHeight - (lboxMargin * 2);
            var maxlboxImgHeight = windowHeightSpace - 30;
            var thumbContHeight = 0;
            var desContHeight = 0;

            var slideshowContHeight = jQuery('#'+this.lboxGalleryObject.options.imageSlideshowContainer).height() + 30;

            if(this.lboxGalleryObject.options.thumbPostion == 'above' || this.lboxGalleryObject.options.thumbPostion == 'below')
            {
                if(jQuery('#'+this.lboxGalleryObject.options.thumbContainer).length)
                {
                    thumbContHeight = jQuery('#'+this.lboxGalleryObject.options.thumbContainer).height();
                    var maxlboxImgHeight = maxlboxImgHeight - thumbContHeight;
                }
            }

            if(this.lboxGalleryObject.options.showDescriptions == 1)
            {
                if(this.lboxGalleryObject.options.desPostion == 'above' || this.lboxGalleryObject.options.desPostion == 'below')
                {
                    if(jQuery('#'+this.lboxGalleryObject.options.desContainer).length)
                    {
                        desContHeight =  jQuery('#'+this.lboxGalleryObject.options.desContainer).height();
                        var maxlboxImgHeight = maxlboxImgHeight - desContHeight;
                    }
                }
            }

            if(this.lboxFullHeight == 0)
            {
                this.lboxFullHeight = slideshowContHeight + 30 + thumbContHeight + 40 + desContHeight + 20;
            }

            if(lboxWidthWithPadding < (windowWidth - (lboxMargin * 2) ) )
            {
                var whiteDivWidth = lboxWidthNoPadding;
                var whiteDivLeftMargin = (windowWidth - lboxWidthWithPadding) / 2;
            }
            else
            {
                var whiteDivWidth = windowWidth - ( (lboxMargin * 2) + lboxPaddingLeft + lboxPaddingRight);
                var whiteDivLeftMargin = lboxMargin;
            }

            if(this.lboxFullHeight > windowHeightSpace )
            {
                var ratio = windowHeightSpace/this.lboxFullHeight;

                if(lboxWidthNoPadding * ratio < whiteDivWidth)
                {
                    if(whiteDivWidth < (windowWidth - (lboxMargin * 2) ) )
                    {
                        var whiteDivLeftMargin = (windowWidth - (whiteDivWidth + lboxPaddingLeft + lboxPaddingRight)) / 2;
                    }
                    else
                    {
                        var whiteDivLeftMargin = lboxMargin;
                    }
                }
            }


            if(jQuery(document).fullScreen() == null || jQuery(document).fullScreen() == false || this.isSafariMac)
            {
                var txtDirection = jQuery('html').attr('dir');
                if(txtDirection == 'rtl')
                {
                    jQuery('#'+this.options.lboxWhite).css
                    ({
                        'width': whiteDivWidth,
                        'margin-right': whiteDivLeftMargin
                    });
                }
                else
                {
                    jQuery('#'+this.options.lboxWhite).css
                    ({
                        'width': whiteDivWidth,
                        'margin-left': whiteDivLeftMargin
                    });
                }
            }
            else
            {
                jQuery('#'+this.options.lboxWhite).css
                ({
                    'width': whiteDivWidth,
                    'margin': '0 auto'
                });
            }


            jQuery('#'+this.lboxGalleryObject.options.largeImage).find('.ig-slick-image').each(function(index,el)
            {
                jQuery(el).css('max-height',maxlboxImgHeight);
                jQuery(el).find('.large_img').css('max-height',maxlboxImgHeight);
            });


            this.lastWindowWidth = windowWidth;
            this.lastWindowHeight = windowHeight;

            jQuery('#'+this.options.largeImage).resize();

        }
    },

    setThumbContainerHeight: function()
    {
        if((this.options.thumbPostion == 'above' || this.options.thumbPostion == 'below') && this.options.thumbLayout == 'scroller')
        {
            if(jQuery('#'+this.options.thumbContainer).length)
            {
                if(jQuery('#'+this.options.thumbContainer).css('max-height') == 'none')
                {
                    jQuery('#'+this.options.thumbContainer).css('height', 'auto');
                    var currentHeight = jQuery('#'+this.options.thumbContainer).height();
                    if(currentHeight != this.thumbsBelowHeight)
                    {
                        var newHeight = currentHeight + 4;
                        jQuery('#'+this.options.thumbContainer).height(newHeight);
                        this.thumbsBelowHeight = newHeight;
                    }
                }
            }
        }
        if((this.options.thumbPostion == 'left' || this.options.thumbPostion == 'right') && this.options.thumbLayout == 'scroller')
        {
            if(this.options.showLargeImage == 1)
            {
                var largeImgDivHeight = jQuery('#'+this.options.largeImage).height();

                if(largeImgDivHeight > 50)
                {
                    if(jQuery('#'+this.options.thumbContainer).length)
                    {
                        jQuery('#'+this.options.thumbContainer).css('max-height', largeImgDivHeight+'px');
                    }
                }
            }
        }
    },

    setDesContainerHeight: function()
    {
        var largeImgDivHeight = jQuery('#'+this.options.largeImage).height();

        if(largeImgDivHeight > 50)
        {
            if(jQuery('#'+this.options.desContainer).length)
            {
                jQuery('#'+this.options.desContainer).height(largeImgDivHeight);
            }
        }
    },

    lboxSetThumbContainerHeight: function()
    {
        var largeImgDivHeight = jQuery('#'+this.lboxGalleryObject.options.largeImage).height();

        if(largeImgDivHeight > 50)
        {
            if(jQuery('#'+this.lboxGalleryObject.options.thumbContainer).length)
            {
                jQuery('#'+this.lboxGalleryObject.options.thumbContainer).css('max-height', largeImgDivHeight+'px');
            }
        }
    },

    lboxSetDesContainerHeight: function()
    {
        var largeImgDivHeight = jQuery('#'+this.lboxGalleryObject.options.largeImage).height();

        if(largeImgDivHeight > 50)
        {
            if(jQuery('#'+this.lboxGalleryObject.options.desContainer).length)
            {
                jQuery('#'+this.lboxGalleryObject.options.desContainer).height(largeImgDivHeight);
            }
        }
    },

    checkHash: function(refreshImage)
    {
        var hashVar = window.location.hash;

        if(hashVar != this.currentHash && hashVar.length > 0)
        {
            var fileNameClean = hashVar.substr(2);

            if( fileNameClean.indexOf('#') >= 0 )
            {
                fileNameClean  = fileNameClean.substr(0, fileNameClean.indexOf('#') );
            }

            jQuery.each(this.options.jsonImages.general, function(index, object)
            {
                var fileNameShort = object.filename.substring(0, object.filename.indexOf('-'))

                if( fileNameShort == fileNameClean )
                {
                    this.imageIndex = index;
                }
            }.bind(this));

            if(refreshImage == true)
            {
                jQuery('#'+this.options.largeImage).slick('slickGoTo', this.imageIndex);
            }

            this.currentHash = hashVar;
        }

    },

    setCheckHashPeriodical : function()
    {
        this.checkHashPeriodical = setInterval(jQuery.proxy(this.checkHash, this, true) ,400);
    },

    clearCheckHashPeriodical : function()
    {
        clearInterval(this.checkHashPeriodical);
    },

    addHash : function(imageObject)
    {
        var slashPos = imageObject.filename.indexOf('/');
        var fileNameOnly  = imageObject.filename.substr(slashPos + 1);

        var dashPos = fileNameOnly.indexOf('-');
        var fileNameClean  = fileNameOnly.substr(0, dashPos);
        var hashToAdd = '!' + fileNameClean;

        window.location.hash = hashToAdd;
        this.currentHash = '#' + hashToAdd;
    },

    getUrlParamater : function (paramTarget)
    {
        var urlValue = 'unset';
        var url = window.location.href;

        if(url.indexOf("?") > -1)
        {
            var queryParams = url.substr(url.indexOf("?"));
            var queryParamsArray = queryParams.split("&");

            for(var i=0; i< queryParamsArray.length; i++ )
            {
                if( queryParamsArray[i].indexOf(paramTarget + "=") > -1 )
                {
                    var paramMatch = queryParamsArray[i].split("=");
                    urlValue = paramMatch[1];
                    break;
                }
            }
        }
        return unescape(urlValue);
    },

    getLegacyUrl : function(index, imageObject)
    {
        var currentUrl = window.location.href;
        if(currentUrl.indexOf("#") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("#"));
        }

        if(currentUrl.indexOf("&fb_comment_id") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("&fb_comment_id"));
        }

        if(currentUrl.indexOf("?_escaped_fragment_") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("?_escaped_fragment_"));
        }

        var urlSymbol = currentUrl.indexOf("?") > -1 ? '&' : '?';

        var slashPos = imageObject.filename.indexOf('/');
        var fileNameOnly  = imageObject.filename.substr(slashPos + 1);
        var dashPos = fileNameOnly.indexOf('-');
        var fileNameClean  = fileNameOnly.substr(0, dashPos);

        var legacyUrl = currentUrl + urlSymbol + 'image=' + fileNameClean;

        return legacyUrl;
    },

    getHashUrl : function(index, imageObject)
    {
        var currentUrl = window.location.href;
        if(currentUrl.indexOf("#") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("#"));
        }

        if(currentUrl.indexOf("&fb_comment_id") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("&fb_comment_id"));
        }

        if(currentUrl.indexOf("?_escaped_fragment_") > -1)
        {
            currentUrl = currentUrl.substr(0, currentUrl.indexOf("?_escaped_fragment_"));
        }

        var slashPos = imageObject.filename.indexOf('/');
        var fileNameOnly  = imageObject.filename.substr(slashPos + 1);
        var dashPos = fileNameOnly.indexOf('-');
        var fileNameClean  = fileNameOnly.substr(0, dashPos);
        var hashToAdd = '#!' + fileNameClean;
        var hashUrl = currentUrl + hashToAdd;

        return hashUrl;
    },

    preloadImages : function()
    {
        if(this.indexsToPreload.length > 0)
        {
            var indexToLoad = this.indexsToPreload.shift();
            this.indexsLoaded.push(indexToLoad);

            this.loadImageNow(indexToLoad, false, false);
        }
    },

    addToPreload : function(index)
    {
        if(index < this.options.jsonImagesImageType.length)
        {
            if( this.indexsToPreload.indexOf(index) == -1 )
            {
                if( this.indexsLoaded.indexOf(index) == -1 )
                {
                    if( index >= 0 )
                    {
                        this.indexsToPreload.push(index);
                    }
                }
            }
        }
    },

    lboxPreloadStarter : function()
    {
        for(var i=0; i<12; i++ )
        {
            this.addToPreload(i);
        }
        this.preloaderVar = setInterval(jQuery.proxy(this.preloadImages, this) ,750);
    },

    resetLboxHeight : function()
    {
        var totalScrollHeight = jQuery(document).height();
        jQuery('#'+this.options.lboxDark).css('height',totalScrollHeight);
    },

    swapImage : function(imageObject, fadeDuration, index, addHash)
    {
        this.imageIndex = index;

        this.loadImageNow(index,true,false);
        this.loadImageNow((index + 1),false,false);
        this.loadImageNow((index - 1),false,false);
        this.addToPreload(index + 2);
        this.addToPreload(index - 2);
        this.addToPreload(index + 3);
        this.addToPreload(index + 4);

        if(this.options.main == 1 && this.options.showLargeImage == 1)
        {
            this.addMainImageClick(this.imageIndex);
        }

        if(this.options.showThumbs == 1)
        {
            this.swapThumbs(index);
        }

        if(this.options.showDescriptions == 1)
        {
            this.swapDescription(index);
        }

        if(this.options.showSlideshowControls == 1 && this.options.slideshowPosition == 'left-right')
        {
            //this.swapSlideshowControls(index);
        }

        if(this.options.showTags == 1)
        {
            this.swapTags(index);
        }

        if(this.options.downloadType != 'none')
        {
            this.swapDownload(index);
        }

        if(this.options.facebookShare == 1)
        {
            this.swapFacebook(index, imageObject);
        }

        if(this.options.showPlusOne == 1)
        {
            this.swapPlusOne(index, imageObject);
        }

        if(this.options.twitterButton == 1)
        {
            this.swapTwitterButton(index, imageObject);
        }

        if(this.options.pinterestButton == 1)
        {
            this.swapPinterestButton(index, imageObject);
        }

        if(this.options.allowComments == 2)
        {
            this.swapJcomments(index, imageObject);
        }

        if(this.options.allowComments == 4)
        {
            this.swapFbComments(index, imageObject);
        }

        if(this.options.reportImage == 1)
        {
            this.swapReportImage(index);
        }

        if(this.options.numberingOn == 1)
        {
            this.swapNumbering(index);
        }

        if(this.options.showImageAuthor == 1)
        {
            this.swapImageAuthor(index);
        }

        if(this.options.showImageHits == 1)
        {
            this.swapImageHits(index);
        }

        if(this.options.allowRating == 2)
        {
            this.swapRatings(index, true);
        }

        if(this.options.refreshMode == 'hash' && addHash == true)
        {
            this.addHash(imageObject);
        }

        if(this.options.collectImageViews == 1)
        {
            this.addImageHit();
        }

        this.imageShowCounter++;
        this.firstShow = false;
    },

    addMainImageClick : function(index)
    {
        var imgLink = this.options.jsonImages.general[index].url;
        var imgTargetBlank = this.options.jsonImages.general[index].targetBlank;

        if(imgLink.length > 1)
        {
            jQuery('#'+this.options.largeImage).css('cursor', 'pointer');
            jQuery('#'+this.options.largeImage).off('click');

            jQuery('#'+this.options.largeImage).on('click', function()
            {
                if(imgTargetBlank == 1)
                {
                    window.open(imgLink);
                }
                else
                {
                    window.location = imgLink;
                }
            }.bind(this));
        }

        if(this.options.lightboxOn == 1 && imgLink.length < 2)
        {
            jQuery('#'+this.options.largeImage).off('click');

            jQuery('#'+this.options.largeImage).css('cursor', 'pointer');

            jQuery('#'+this.options.largeImage).on('click', function()
            {
                var opentoFullscreen = this.options.fullscreen == 'open-fullscreen' ? true : false;

                this.showLightBox(index, opentoFullscreen);

                if(this.options.fullscreen == 'open-fullscreen')
                {
                    this.lboxFullscreenOn();
                }

            }.bind(this));
        }

        else if(this.options.lightboxOn == 0 && imgLink.length < 2 && (this.options.slideshowPosition != 'left-right' || this.options.showSlideshowControls == 0))
        {
            jQuery('#'+this.options.largeImage).off('click');

            jQuery('#'+this.options.largeImage).on('click', function()
            {
                this.clearSlideShow();
                this.slideShowSwap(true);
            }.bind(this));
        }

        else if(this.options.lightboxOn == 0 && imgLink.length < 2 && this.options.slideshowPosition == 'left-right')
        {
            jQuery('#'+this.options.largeImage).off('click');
            jQuery('#'+this.options.largeImage).css('cursor', 'auto');
        }

    },

    swapThumbs : function(index)
    {
        if(this.options.thumbLayout == 'grid')
        {
            return;
        }

        var thumbCells = jQuery('#'+this.options.thumbContainer).find('.ig_thumb_cell');
        thumbCells.each(function(index)
        {
            jQuery(this).removeClass('active_thumb');
            jQuery(this).addClass('inactive_thumb');
        });

        var currentThumb = jQuery(thumbCells[index]);
        currentThumb.addClass('active_thumb');

        if(this.firstShow == false)
        {
            var hasXOverflow = (jQuery('#'+this.options.thumbTable).width() > (jQuery('#'+this.options.thumbContainer).width() + 50));
            var hasYOverflow = (jQuery('#'+this.options.thumbTable).height() > (jQuery('#'+this.options.thumbContainer).height() + 50));

            if(hasXOverflow)
            {
                var thumbPosition = currentThumb.position().left;
                var containerWidth = jQuery('#'+this.options.thumbContainer).width();
                if(thumbPosition > containerWidth)
                {
                    jQuery('#'+this.options.thumbContainer).scrollTo(currentThumb,400);
                }
                else if(thumbPosition < 0 && index != 0)
                {
                    var positionToScroll = jQuery('#'+this.options.thumbContainer).scrollLeft() - containerWidth;
                    jQuery('#'+this.options.thumbContainer).scrollTo(positionToScroll,400);
                }
                else if(index == 0)
                {
                    /* [Customized by Joomi] [789521] [1396-03-16] */
                    var scrollToPosition = 0;
                    var isRtl = jQuery('html').attr('dir') == 'rtl' ? true : false;
                    scrollToPosition = isRtl ? 'max' : 0;

                    jQuery('#'+this.options.thumbContainer).scrollTo(scrollToPosition,400);
                }

            }
            else if(hasYOverflow)
            {
                var thumbPosition = currentThumb.position().top;
                var containerHeight = jQuery('#'+this.options.thumbContainer).height();

                if(thumbPosition > containerHeight)
                {
                    jQuery('#'+this.options.thumbContainer).scrollTo(currentThumb,400);
                }
                else if(thumbPosition < 0)
                {
                    var positionToScroll = jQuery('#'+this.options.thumbContainer).scrollTop() - containerHeight;
                    jQuery('#'+this.options.thumbContainer).scrollTo(positionToScroll,400);
                }
            }
        }
    },

    swapDescription : function(index)
    {
        if( jQuery('#'+this.options.desContainer).length )
        {
            var descriptionDivs = jQuery('#'+this.options.desContainer).children('.des_div');
            descriptionDivs.each(function(index)
            {
                jQuery(this).css('display', 'none');
            });

            jQuery('#'+this.options.desContainer).scrollTop(0);
            jQuery(descriptionDivs[index]).css('display', 'block');
        }
    },

    swapSlideshowControls: function(index)
    {
        var forwardArrow = jQuery('#'+this.options.imageSlideshowContainer).find('.slick-next');
        var backArrow = jQuery('#'+this.options.imageSlideshowContainer).find('.slick-prev');

        if(index == 0)
        {
            backArrow.css('visibility','hidden');
        }
        else
        {
            backArrow.css('visibility','visible');
        }

        if(index == (this.options.jsonImagesImageType.length - 1))
        {
            forwardArrow.css('visibility','hidden');
        }
        else
        {
            forwardArrow.css('visibility','visible');
        }
    },

    swapTags : function(index)
    {
        var tagsDivs = jQuery('#'+this.options.tagsContainer).children('div.tags_div');

        tagsDivs.each(function(index)
        {
            jQuery(this).css('display', 'none');
        });

        var activeDiv = jQuery(tagsDivs[index]);
        activeDiv.css('display', 'block');

        var taglinks = activeDiv.children('a');

        if(taglinks.length == 0)
        {
            activeDiv.css('visibility', 'hidden');
        }
    },

    swapFacebook : function(index, imageObject)
    {
        var urlToShare = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent( this.getHashUrl(index, imageObject) );
        var fbContainer = jQuery('#'+this.options.facebookContainer);

        fbContainer.off('click');
        fbContainer.on('click', function(event)
        {
            window.open(urlToShare, '_blank', 'height=450, width=550, top=' + (jQuery(window).height() / 2 - 275) + ', left=' + (jQuery(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0').focus();
        }.bind(this));
    },

    swapTwitterButton : function(index, imageObject)
    {
        var urlToShare = 'http://twitter.com/share?url=' + encodeURIComponent( this.getHashUrl(index, imageObject) );
        var twitterContainer = jQuery('#'+this.options.twitterButtonDiv);

        twitterContainer.off('click');
        twitterContainer.on('click', function(event)
        {
            window.open(urlToShare, '_blank', 'height=450, width=550, top=' + (jQuery(window).height() / 2 - 275) + ', left=' + (jQuery(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0').focus();
        }.bind(this));
    },

    swapPlusOne : function(index, imageObject)
    {
        var urlToShare = 'https://plus.google.com/share?url=' + encodeURIComponent(this.getHashUrl(index, imageObject));
        var plusOneContainer = jQuery('#'+this.options.plusOneDiv);

        plusOneContainer.off('click');
        plusOneContainer.on('click', function(event)
        {
            window.open(urlToShare, '_blank', 'height=450, width=550, top=' + (jQuery(window).height() / 2 - 275) + ', left=' + (jQuery(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0').focus();
        }.bind(this));
    },

    swapPinterestButton : function(index, imageObject)
    {
        var pInterestContainer = jQuery('#'+this.options.pInterestContainer);
        var urlToShare = this.getHashUrl(index, imageObject);
        var imgUrl = this.options.resizePathAbsolute + imageObject.filename;

        var description  = '';
        if( jQuery('#'+this.options.desContainer).length )
        {
            var descriptionDivs = jQuery('#'+this.options.desContainer).children('.des_div');
            descriptionDivs.each(function(des_index)
            {
                if(des_index == index)
                {
                    description = jQuery(this).text();
                }
            });
        }
        description = description.length > 0 ? description : this.options.jsonImages.general[index].alt;

        var href = 'https://pinterest.com/pin/create/button/?url=' + encodeURIComponent(urlToShare) + '&media=' + encodeURIComponent(imgUrl) + '&description=' + description;

        pInterestContainer.off('click');
        pInterestContainer.on('click', function(event)
        {
            window.open(href, '_blank', 'height=450, width=550, top=' + (jQuery(window).height() / 2 - 275) + ', left=' + (jQuery(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0').focus();
        }.bind(this));
    },

    swapFbComments : function(index, imageObject)
    {
        if(this.options.facebookLegacy == 1)
        {
            var urlToShare = this.getLegacyUrl(index, imageObject);
        }
        else
        {
            var urlToShare = this.getHashUrl(index, imageObject);
        }

        if( jQuery('#'+this.options.facebookCommentsContainer).length )
        {
            var fbContainer = jQuery('#'+this.options.facebookCommentsContainer);
            var tempContainerId = this.options.facebookCommentsContainer + '_temp';
            var fbTempContainer = jQuery('#'+tempContainerId);
            var fbHtml = '<fb:comments href="' + urlToShare + '" num_posts="' + this.options.facebookCommentsNumPosts + '" width="100%" colorscheme="' + this.options.facebookColor + '"></fb:comments>';

            fbTempContainer.html(fbHtml);

            if(typeof(FB) != 'undefined')
            {
                FB.XFBML.parse(document.getElementById(tempContainerId));
            }

            var fbCommentToMove = fbTempContainer.children().first();
            var position = this.firstShow ? 'relative' : 'absolute';
            fbCommentToMove.css
            ({
                position: position,
                top: 0,
                left: 0,
                visibility: 'hidden'
            });
            fbContainer.prepend(fbCommentToMove);

            jQuery.each(this.fbCommentDelays, function(index, object)
            {
                clearTimeout(object);
            });
            this.fbCommentDelays = new Array();


            if(this.imageShowCounter > 0)
            {
                this.fbCommentDelays[index] = setTimeout(jQuery.proxy(this.removeFBComment, this), 1500);
            }
            else
            {
                fbCommentToMove.css('visibility', 'visible');
            }
        }

    },

    removeFBComment : function()
    {
        var fbCommentTags = jQuery('#'+this.options.facebookCommentsContainer).children();

        fbCommentTags.each(function(index)
        {
            if(index != 0)
            {
                jQuery(this).remove();
            }
            else
            {
                jQuery(this).css('visibility', 'visible');
                jQuery(this).css('position', 'relative');
            }
        });
    },

    swapJcomments : function(index, imageObject)
    {
        if(typeof(jcomments) != 'undefined')
        {
            jcomments.showPage(this.options.idArray[index],'com_igallery',0);

            if(!jQuery('#comments-form').length )
            {
                if( jQuery('#addcomments').length )
                {
                    var addCommentLink = jQuery('#addcomments');
                    addCommentLink.attr('onclick', "jcomments.showForm(" + this.options.idArray[index] + ",'com_igallery\', 'comments-form-link'); return false;");
                }
            }
            else
            {
                var objectIdInput = jQuery('#comments-form').find('input[name=object_id]').first();

                objectIdInput.attr('value', this.options.idArray[index]);

                var jcforms = jQuery('#jc').children('form#comments-form');
                jcforms.each(function(index)
                {
                    if(index != 0)
                    {
                        jQuery(this).remove();
                    }
                });
            }
        }
    },

    swapReportImage : function(index)
    {
        jQuery('#'+this.options.reportContainer).css('height',this.reportContainerHeight);
        var reportForm = jQuery('#'+this.options.reportContainer).children('form').first();
        reportForm.css('display', 'none');

        var reportUrl = this.options.hostRelative + '/index.php?option=com_igallery&task=imagefront.reportImage&id=' + this.options.idArray[index] + '&catid=' + this.options.catid;
        reportForm.attr('action', reportUrl);

        var reportLink = jQuery('#'+this.options.reportContainer).children('a').first();
        reportLink.off();
        reportLink.on('click', function(event)
        {
            event.preventDefault();
            jQuery('#'+this.options.reportContainer).css('height','auto');
            reportForm.css('display', 'block');
        }.bind(this));
    },

    swapNumbering : function(index)
    {
        if( jQuery('#'+this.options.numberingContainer).length )
        {
            jQuery('#'+this.options.numberingContainer).children('span').first().html(index + 1);
        }
    },

    swapImageAuthor : function(index)
    {
        if( jQuery('#'+this.options.imageAuthorContainer).length )
        {
            jQuery('#'+this.options.imageAuthorContainer).children('span').first().html(this.options.jsonImages.general[index].author);
        }
    },

    swapImageHits : function(index)
    {
        if( jQuery('#'+this.options.imageHitsContainer).length )
        {
            jQuery('#'+this.options.imageHitsContainer).children('span').first().html(this.options.jsonImages.general[index].hits);
        }
    },

    swapDownload : function(index)
    {
        if( jQuery('#'+this.options.downloadId).length )
        {
            var downloadLink = jQuery('#'+this.options.downloadId).children('a').first();
            var linkType = this.options.main == 1 ? 'main' : 'lbox';
            var url = this.options.hostRelative + '/index.php?option=com_igallery&task=imagefront.download&format=raw&type=' + linkType + '&id=' + this.options.idArray[index];
            downloadLink.attr('href',url);
        }
    },

    swapRatings : function(index, hideMessage)
    {
        if( jQuery('#'+this.options.ratingsContainer).length )
        {
            if(hideMessage == true)
            {
                jQuery('#'+this.options.ratingsContainer).find('span.rating_message').first().html('');
            }

            jQuery('#'+this.options.ratingsContainer).find('span.rating_loading_gif').first().css('visibility', 'hidden');
            var width = this.options.jsonImages.general[index].ratingAverage * 20;

            jQuery('#'+this.options.ratingsContainer).find('div.ratings_current').first().css('width', width + '%');

            jQuery('#'+this.options.ratingsContainer).find('span.rating_number').first().html(this.options.jsonImages.general[index].ratingAverage);

            jQuery('#'+this.options.ratingsContainer).find('span.rating_count').first().html(this.options.jsonImages.general[index].ratingCount);

            if(this.options.jsonImages.general[index].ratingCount == 1)
            {
                jQuery('#'+this.options.ratingsContainer).find('span.rating_vote_vote').first().css('display', 'inline');
                jQuery('#'+this.options.ratingsContainer).find('span.rating_vote_votes').first().css('display', 'none');
            }
            else
            {
                jQuery('#'+this.options.ratingsContainer).find('span.rating_vote_vote').first().css('display', 'none');
                jQuery('#'+this.options.ratingsContainer).find('span.rating_vote_votes').first().css('display', 'inline');
            }
        }
    },

    addImageHit : function()
    {
        var hitUrl = this.options.hostRelative + '/index.php?option=com_igallery&task=imagefront.addHit&format=raw&id=' + this.options.idArray[this.imageIndex];
        jQuery.ajax({url: hitUrl, success: function(result){}});
    }
});

var igalleryMenuClass = IGClass.extend({

    init: function(options)
    {
        this.options = options;
        this.lastMenuGridWidth = -1;
        this.isTouchDevice = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
        if( jQuery('#cat_child_wrapper'+this.options.uniqueid).length )
        {
            this.createMenuResponsiveGrid(true);
            this.createMenuResponsiveGridPeriodical = setInterval(jQuery.proxy(this.createMenuResponsiveGrid, this, false) ,800);
        }


        if(this.options.menuHoverEffect == 'fade_to_grey' && this.isTouchDevice == false)
        {
            jQuery('#cat_child_wrapper'+this.options.uniqueid + ' ' + '.cat_child').hover(
                function()
                {
                    if(jQuery(this).find('img.cat_child_img').length)
                    {
                        var position  = jQuery(this).find('img.cat_child_img').position();

                        jQuery("<div/>", {
                            class: 'black_fade',
                            css: {
                                'position': 'absolute',
                                'top': (position.top + parseInt(jQuery(this).find('img.cat_child_img').css('padding-top')) + parseInt(jQuery(this).find('img.cat_child_img').css('margin-top')) ) +'px',
                                'left': (position.left + parseInt(jQuery(this).find('img.cat_child_img').css('padding-left')) + parseInt(jQuery(this).find('img.cat_child_img').css('margin-left')) ) +'px',
                                'background-color': '#000000',
                                'opacity': 0,
                                'width': jQuery(this).find('img.cat_child_img').width()+'px',
                                'height': jQuery(this).find('img.cat_child_img').height()+'px'
                            }
                        }).appendTo(jQuery(this).find('a.cat_child_img_a'));

                        jQuery(this).find('.black_fade').fadeTo('slow', 0.3);
                    }
                },
                function()
                {
                    jQuery(this).find('.black_fade').fadeTo('slow', 0, function() {
                        jQuery(this).remove();
                    });
                }
            );
        }
    },

    createMenuResponsiveGrid: function(firstTime)
    {
        var gridWidth = jQuery('#cat_child_wrapper' + this.options.uniqueid).width();

        if(gridWidth != this.lastMenuGridWidth)
        {
            var gridCells = jQuery('#cat_child_wrapper' + this.options.uniqueid).find('.cat_child');
            var maxWidth = jQuery('#cat_child_wrapper' + this.options.uniqueid).attr('data-maxmenuwidth');

            if(gridWidth%maxWidth > maxWidth/5)
            {
                var columns = Math.ceil(gridWidth/maxWidth);
            }
            else
            {
                var columns = Math.floor(gridWidth/maxWidth);
            }

            var gutter = this.options.menuGridSpacing;
            var colWidth = (gridWidth - (gutter * (columns - 1)))/columns;

            gridCells.each(function(index,el)
            {
                jQuery(el).css('width',colWidth);
            });

            var layoutMode = this.options.menuGridType == 'by_columns' ? 'masonry' : 'fitRows';

            if(firstTime)
            {
                this.responsiveMenuGrid = jQuery('#cat_child_wrapper' + this.options.uniqueid).isotope({
                    itemSelector: '.cat_child',
                    layoutMode: layoutMode,
                    masonry: {
                        gutter:gutter
                    },
                    fitRows: {
                        gutter:(gutter - 1)
                    }
                });

                this.menuLoadCount=1;
                this.numMenuPics = jQuery('#cat_child_wrapper' + this.options.uniqueid).find('.cat_child_img').length;

                if(this.numMenuPics == 0)
                {
                    jQuery('#cat_child_wrapper' + this.options.uniqueid).css('visibility','visible');
                }

                this.responsiveMenuGrid.imagesLoaded().progress( function()
                {
                    this.responsiveMenuGrid.isotope('layout');
                    if(this.menuLoadCount == 10 || this.menuLoadCount >= this.numMenuPics)
                    {
                        jQuery('#cat_child_wrapper' + this.options.uniqueid).css('visibility','visible');
                    }
                    this.menuLoadCount++;
                }.bind(this));
            }
            else
            {
                this.responsiveMenuGrid.isotope('layout');
            }

        }
        this.lastMenuGridWidth = gridWidth;
    }
});