/**
 * Gallery
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

    $.widget('ui.gallery', {
        options: {
            origElement : "",
            pages : [],
            fullscreenmode:false,
            zoom: "",
            close: "",
            comment: "",
            like: "",
            share: "",
            backbtn1: "",
            backbtn2: "",
            //listview: "",
            slideview: "",
            moreinfo: "",
            lessinfo: "",
            listmore: "",
            basePath: "",
            language: ""
        },

        _create: function() {

            var opt = this.options,
                elem = this.element,
                widget = this,
                pagesArr = opt.pages,
                pagesArrLen = pagesArr.length,
                catArrLen = 0,
                catItemNumArr = [],
                aniTime = 600,
                pageWidth = 850,
                pageMargin = 0,
                p, pPosX,
                checkscrollid,
                catpos,
                mouseX, endX,
                dragging = false,
                listInitialized = false,
                listPosX,
                listRow,
                itemsPerRow = 3,
                posXListItem, posYListItem,
                stateChanging = false,
                initialized = false,
                i = 0,
                initialPage = 0,
                featureHeadline = "",
                myGallery = '#' + elem.attr('id') + ' ',
                myPageCont = '#' + elem.attr('id') + ' .galleryPageCont';
                //myListView = '#' + elem.attr('id') + ' .galleryListView';

            // variables that are needed in multiple functions of widget
            this.currPage = 0;
            this.currCategory = 0;
            this.pagesArr = pagesArr;
            this.pagesArrLen = pagesArrLen,
            this.aniTime = aniTime;
            this.pageWidth = pageWidth;
            this.pageMargin = pageMargin;
            this.catArr = [];
            // state is either list, slide, or detail
            this.state = "slide";

            this.regularColor = '#124047';
            this.hoverColor = '#136d7b';


            // Facebook language chooser
            var language = "";
            if("en" == opt.language) {
                language = opt.language+"_US";
            }else {
                language = opt.language+"_"+opt.language.toUpperCase();
            }


            // build all gallery items
            for (var k=0; k<pagesArrLen; k++){
               p = pagesArr[k];
               pPosX = k*(pageWidth + pageMargin);
               var pageId = k+1;

               if(p.subcategory){
                   featureHeadline = p.category + ' | ' + p.subcategory;
               }else{
                   featureHeadline = p.category;
               }

                // add page
                $(myPageCont).append(
                    '<div class="galleryPage" style="position:absolute; left:' + pPosX + 'px;">' +
                        '<img src="' + p.imgurl + '" class="galimg" />' +
                        '<div class="zoom"><p>' + opt.zoom.toUpperCase() + '</p></div>' +
                        '<div class="textArea">' +
                            '<div class="scroll-pane">' +
                                '<p class="categories">' + featureHeadline + '</p>' +
                                '<h1 class="headline">' + p.headline + '</h1>' +
                                '<p class="descript">' + p.description + '</p>' +
                            '</div>' +
                            //'<script type="text/javascript" src="http://connect.facebook.net/'+language+'/all.js#xfbml=1"></script>'+
                            
                            '<div class="socialMedia">' +
                                '<div class="comment socialbtn" style="float:left;">'+
                                    '<div class="commentImg"></div>' +
                                    '<div id="fb-root"></div>'+
                                    '<a href="/layer/layerFacebookComments?ajax=true&width=500&height=400&category='+opt.basePath+'&page='+pageId+'" id="fbComments">' + opt.comment + '</a> / ' +
                                    '<fb:comments-count href='+opt.baseUrl+'/go/'+opt.language+'/'+opt.basePath+'/'+pageId+'></fb:comments-count>'+
                                '</div>'+
                                '<div class="facebook_like_button_holder" style="float:left;">'+
                                    '<iframe src="http://www.facebook.com/plugins/like.php?locale='+language+'&amp;href='+opt.baseUrl+'/go/'+opt.language+'/'+opt.basePath+'/'+pageId+'&amp;send=false&amp;layout=button_count&amp;width=600&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:600px; height:21px;" allowTransparency="true"></iframe>'+
                                    '<div class="fake_facebook_button"><span class="likeText">' + opt.like + '</span></div>'+
                                '</div>'+
                            '</div>'+
                            '<div class="share socialbtn"><a href="/layer/layerShare?ajax=true&width=500&height=400&title='+p.headline+'&description='+p.description+'&category='+opt.basePath+'&page='+pageId+'" id="shareLayer">' + opt.share + '</a></div>' +
                            
                        '</div>' +
                    '</div>');



                // add category if necessary
                // if(catArr.indexOf(p.category) === -1){ // doesn't work in IE8!
                if(jQuery.inArray(p.category, this.catArr) === -1){
                    this.catArr.push(p.category);
                    $(myGallery + '.galleryFooter .categories').append('<li><a class="getCat" href="javascript:;" data-tracking="' + opt.basePath +'|' + p.category + '">' + p.category.toUpperCase() + '</a></li>');
                }


            }
            catArrLen = this.catArr.length;

            // generate scrollpanes
            checkscrollid = window.setInterval(function(){
                if($(myGallery + '.galleryPage .scroll-pane').length === pagesArrLen){
                    $(myGallery + '.galleryPage .scroll-pane').jScrollPane();
                    //$(myGallery + '.galleryContent .jspDrag').css('background', 'url("/public/images/slider_drag_bg_offwhite.png") repeat-y');
                    clearInterval(checkscrollid);
                }
            }, 10);


            // add event listeners
            $(myGallery + '.galleryContent .arrLeft').click(function(){getPrevPage();});
            $(myGallery + '.galleryContent .arrRight').click(function(){getNextPage();});
            //$(myGallery + '.galleryContent .closeDetail').click(function(){setState('list');});

            $(myGallery + '.galleryFooter .getCat').click(jumpToCategory);


            // enable touch functionality for Slide View
            if(Modernizr.touch){
                $('.galimg').bind('touchstart', function(event){
                    event.preventDefault();
                    dragging = true;
                    mouseX = event.originalEvent.targetTouches[0].pageX;

                    $('html').bind('touchmove', function(event){
                       // iOS can not animate anything while there is touch interaction
                       // save position and start an action on 'touchend'
                       endX = event.originalEvent.targetTouches[0].pageX;
                    });
                });

                $('html').bind('touchend', function(event){
                    if(dragging){
                        var tol = 20;
                        dragging = false;

                       if(endX < mouseX-tol){
                          getNextPage();
                       }else if(endX > mouseX+tol){
                           getPrevPage();
                       }
                    }
                });
            }


            //////////////////////
            /// List View  /////
            //////////////////
            /*
            $(myGallery + '.galleryFooter .listview').click(function(){
                if(widget.state === 'list' || widget.state === 'detail'){
                    setState('slide');
                }else if(widget.state === 'slide'){
                    setState('list');
                }
            });
            */

            $(myGallery + '.galleryFooter .closeBtn').click(function(){widget.closeGallery();});


            $(myGallery + '.galleryContent .zoom').each(function(){
                var zoomWidth = $(this).css('width').split('px')[0],
                    zoomPosX = 513 - zoomWidth;

                $(this).css({'left' : zoomPosX + 'px'});
            });


            ////////////////////////
            /// Fullscreen  //////
            ////////////////////
            if(opt.fullscreenmode){
                $(myGallery + '.galleryContent .zoom').show();
                $(myGallery + '.galleryContent .zoom').click(function(){
                    /**
                     * var conf, configuration array
                     * ~~~~~~~~~~~~~~~~~~~
                     * conf.showDescription: true if user clicked 'More Information', keeps the description field opened
                     * conf.initialPage:     unused, keeps the starting page (from which supersized got started)
                     * conf.currentPage:     supersized's current slide (needed to display correct slide after closing supersized)
                     * conf.numPages:        number of slides
                     * conf.initialscroll:   scrolling position on enter (when opening supersized, browser jumps to top of the page,
                     *                       so we have to jump to the starting position on close)
                     * conf.gallerySlides:   array with the images and the description to show in fullscreen
                     *
                     */
                    var conf = [];
                    conf.showDescription = false;
                    conf.initialPage     = widget.currPage + 1;
                    conf.currentPage     = conf.initialPage;
                    conf.numPages        = pagesArr.length;
                    conf.initialScroll   = $(window).scrollTop();
                    conf.gallerySlides   = [];

                    // generate Array for supersized
                    for (i=0; i < pagesArr.length; i++) {
                        if(pagesArr[i].subcategory){
                           featureHeadline = pagesArr[i].category + ' | ' + pagesArr[i].subcategory;
                       }else{
                           featureHeadline = pagesArr[i].category;
                       }

                        conf.gallerySlides.push({
                             image: pagesArr[i].imglargeurl,
                             title: '<h2 class="categories">' + featureHeadline + '</h2>\n\
                                     <h3 class="headline">' + pagesArr[i].headline + '</h3>\n\
                                     <div id="showMore"><span>' + opt.moreinfo + '</span></div>\n\
                                     <div id="supersized-description"><p class="descript">' + pagesArr[i].description + '</p>\n\
                                        <div id="showLess"><span>' + opt.lessinfo + '</span></div>\n\
                                     </div>'
                        })
                    }


                    // build supersized object
                    $.supersized({
                        // Functionality
                        autoplay:         0,                  // no automatic slideshow
                        start_slide:      widget.currPage + 1,       // image to start with
                        transition:       6,                  // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                        transition_speed: 400,                // Speed of transition
                        fit_portrait:     true,
                        // Components
                        slide_links:      0,                  // Individual links for each slide (Options: false, 'number', 'name', 'blank')
                        slides:           conf.gallerySlides  // array with images and text
                    });

                   // append bottom overlay div only
                    $('body').append('<div id="supersized-fullscreen-overlay">\n\
                          <div id="supersized-fullscreen-content">\n\
                              <div id="kill_supersized" class="zoom"><p>' + opt.close + '</p></div>\n\
                              <div id="slidecaption"></div>\n\
                          </div>\n\
                          <div id="counterbox"></div>\n\
                          <div class="counter">\n\
                              <span class="counter1">' + $(myGallery + '.galleryFooter .counter1').html() + '</span>\n\
                              <span class="counter2">' + $(myGallery + '.galleryFooter .counter2').html() + '</span>\n\
                          </div>\n\
                    </div>');

                    // build own prevslide and nextslide buttons
                    // remove handler added by supersized
                    $('#prevslide, #nextslide').remove();
                    if(widget.state !== "detail"){
                        $('body').append('<a id="prevslide"></a><a id="nextslide"></a>');
                    }

                    // disable back button if we start with first page & disable next button if we start with last page
                    if (conf.currentPage == 1) {
                        window.setTimeout(function() {
                            $('#prevslide').css('display', 'none');
                        }, 200);
                    } else if (conf.currentPage == conf.numPages) {
                        window.setTimeout(function() {
                            $('#nextslide').css('display', 'none');
                        }, 200);
                    }


                    $(window).bind('resize', function() {
                      checkZoomArrows();
                    });

                    // check if arrows need to be moved to not disappear behind panel
                    function checkZoomArrows(){
                        //console.log($('#prevslide').css('opacity'));
                        var space = ($(window).height() - $('#supersized-fullscreen-overlay').height())/2;

                        $('#prevslide').stop().animate({top:space}, 400);
                        $('#nextslide').stop().animate({top:space}, 400);
                    }



                    // add own handler to prevslide and nextslide (arrows to navigate left/right in fullscreen)
                    $('#prevslide').bind('click', function() {
                        getPrevSlide();
                    });
                    $('#nextslide').bind('click', function() {
                        getNextSlide();
                    });



                    function getNextSlide(){
                        // check description state
                        if ($('#supersized-description').css('display') === 'block') {
                            conf.showDescription = true;
                        } else {
                            conf.showDescription = false;
                        }
                        // supersized api: move to next slide
                        api.nextSlide();
                        conf.currentPage++;
                        setPage(conf.currentPage-1, 0); // Image counter
                        // disable next button on last slide
                        if (conf.currentPage == conf.numPages) {
                            window.setTimeout(function() {
                                $('#nextslide').css('display', 'none');
                            }, 200);
                        }
                        // check if moreinfo has been opened earlier, if so, keep it opened and display close link
                        if (conf.showDescription) {
                            $('#supersized-description').css('display', 'block');
                            $('#showMore').css('visibility', 'hidden');
                            $('#showLess').css('visibility', 'visible');
                        }
                        // if there has been a next slide, there should be a prev slide enable control
                        $('#prevslide').css('display', 'block');
                    }


                    function getPrevSlide(){
                        // check description state
                        if ($('#supersized-description').css('display') === 'block') {
                            conf.showDescription = true;
                        } else {
                            conf.showDescription = false;
                        }
                        // supersized api: move to previous slide
                        api.prevSlide();
                        conf.currentPage--;
                        setPage(conf.currentPage-1, 0); // Image counter
                        // disable back button if on first page
                        if (conf.currentPage == 1) {
                            window.setTimeout(function() {
                                $('#prevslide').css('display', 'none');
                            }, 200);
                        }
                        // check if moreinfo has been opened, change css if so
                        if (conf.showDescription) {
                            $('#supersized-description').css('display', 'block');
                            $('#showMore').css('visibility', 'hidden');
                            $('#showLess').css('visibility', 'visible');
                        }
                        // if there has been a prev slide, there should be a next slide enable control
                        $('#nextslide').css('display', 'block');
                    }

                    // showMore and showLess open and close the description on click
                    $('#showMore').live('click', function() {
                            $('#showMore').css('visibility', 'hidden');
                            $('#supersized-description').slideDown(500, function() {
                                $('#showLess').css('visibility', 'visible');
                                checkZoomArrows();
                            });
                    })
                    $('#showLess').live('click', function() {
                        $('#supersized-description').slideUp(500, function() {
                            $('#showMore').css('visibility', 'visible');
                            $('#showLess').css('visibility', 'hidden');
                            checkZoomArrows();
                        });
                    })

                    // show supersized and supersized controls
                    $('#supersized-loader').show();
                    $('#supersized, #prevslide, #nextslide').fadeIn(1000);

                    /**
                     * Enable touch functionality for Zoom View
                     */
                    if(Modernizr.touch){
                        var initialTouchPosX = null;
                        var endTouchPosX;

                        $('#supersized').live('touchmove', function(event){
                            event.preventDefault();
                            if (null===initialTouchPosX) {
                                initialTouchPosX = event.originalEvent.targetTouches[0].pageX;
                            }
                            endTouchPosX = event.originalEvent.targetTouches[0].pageX;
                        });

                        $('#supersized').live('touchend', function(event){
                            // Check for direction of touchmove
                            if (endTouchPosX >= initialTouchPosX) {
                                // First Slide?
                                if (conf.currentPage != 1) {
                                    getPrevSlide();
                                }
                            } else {
                                // Last Slide?
                                if (conf.currentPage != conf.numPages) {
                                    getNextSlide();
                                }
                            }
                            initialTouchPosX = null;
                            
                            // Debug:
                            //alert('body.width:' + $('body').css('width')); // 1024
                            //alert('#supersized.width:' + $('#supersized').css('width')); // 1024
                            //alert('#supersized.html:' + $('#supersized').html());
                        });

                        // Prevent swiping on transparent overlay of text box
                        $('#supersized-fullscreen-overlay, #nextslide, #prevslide').live('touchmove', function(event){
                            event.preventDefault();
                        });

                    }

                    // invisibilize the whole page
                    $('#panels').css('visibility','hidden')
                    // and disable the navigation, the footer and disturbing elements
                    $('#navpanel, #footer, #Page1TopRightElements').hide();

                    // "disable" scrolling
                    $('body').css('overflow','hidden');

                    // jump to top of page
                    //$(window).scrollTop(0);




                    // add functionality to close button
                    $('#kill_supersized').click(function(){
                        //setPage(--conf.currentPage, 0);
                        $('#supersized-fullscreen-overlay').remove();
                        // don't remove div, just empty it (else supersized won't work again)
                        $('#supersized').html('').css('display', 'none');
                        // remove navigation arrows
                        $('#prevslide, #nextslide').remove();
                        // show the page
                        $('#panels').css('visibility','visible');
                        // enable scrolling again and set scrollingPosition to old value
                        $('body').css('overflow','');
                        $(window).scrollTop(parseInt(conf.initialScroll));
                        // reneable
                        $('#navpanel, #footer, #Page1TopRightElements').slideDown(500);

                        $(window).unbind('resize');
                    });
                });
            }
            
            

            /*
            function initListView(){
                for (var p=0; p < catArrLen; p++){
                    // generate page with scrollpane for each category
                    listPosX = p*(pageWidth + pageMargin);

                    $(myGallery + '.listViewPageCont').append(
                        '<div class="lvGalleryPage" style="position:absolute; left:' + listPosX + 'px;">' +
                           '<div class="scroll-pane"><div class="scrollcontent"></div></div>' +
                        '</div>'
                    );

                    // reset rows for every page
                    listRow = -1;

                    // fill scroll-pane with thumbs
                    var cnt = 0;
                    for(var q=0; q<pagesArrLen; q++){
                        var it = pagesArr[q];

                        if( it.category === widget.catArr[p]){
                            if(cnt%itemsPerRow === 0){
                                // go to next row
                                listRow++;
                            }

                            posXListItem = (cnt%itemsPerRow)*$('.galListItem').width();
                            posYListItem = listRow*$('.galListItem').height();



                            if(it.subcategory){
                                $(myGallery + '.listViewPageCont .scrollcontent').last().append(
                                    '<div class="galListItem" style="position:absolute; left:' + posXListItem + 'px; top:' + posYListItem + 'px;">' +
                                           '<img src="' + it.imgthumburl + '" class="galListItemImg" />' +
                                           '<div class="galListItemTxt">' +
                                               '<p class="categories">' + it.subcategory + '</p>' +
                                               '<p class="lvheadline">' + it.headline + '</p>' +
                                               '<a href="javascript:;" class="lvmore">' + opt.listmore + '</a>' +
                                           '</div></div>'
                                );
                            }else{
                                $(myGallery + '.listViewPageCont .scrollcontent').last().append(
                                    '<div class="galListItem" style="position:absolute; left:' + posXListItem + 'px; top:' + posYListItem + 'px;">' +
                                           '<img src="' + it.imgthumburl + '" class="galListItemImg" />' +
                                           '<div class="galListItemTxt">' +
                                               '<p class="lvheadline">' + it.headline + '</p>' +
                                               '<a href="javascript:;" class="lvmore">' + opt.listmore + '</a>' +
                                           '</div></div>'
                                );
                            }

                            cnt++;
                        }
                    }

                    catItemNumArr.push(cnt);

                    // calculate height of scrollcontent, will not be set automatically
                    $(myGallery + '.listViewPageCont .scrollcontent').last().css({"height":(listRow+1)*$('.galListItem').height()});
                }

                // generate scrollpanes
                checkscrollid = window.setInterval(function(){
                    if($('.lvGalleryPage .scrollcontent').height() !== 0){
                        $('.lvGalleryPage .scroll-pane').jScrollPane();
                        $(myListView + ' .jspDrag').css('background', 'url("/public/images/slider_drag_bg.png") repeat-y');
                        clearInterval(checkscrollid);
                    }
                }, 10);


                // click event "more"-button"
                $('.galListItemTxt .lvmore, .galListItemImg').click(function(event){
                    var elemIndex;
                    if($(event.target).attr('class') === "lvmore"){
                        elemIndex = $(event.target).parent().parent().index();
                    }else{
                        elemIndex = $(event.target).parent().index();
                    }
                    if(widget.currCategory !== 0){
                        // add items of previous pages
                        var catcounter = widget.currCategory;
                       while(catcounter > 0){
                           catcounter--;
                           var previtems = catItemNumArr[catcounter];
                           elemIndex = elemIndex + previtems;
                       }
                    }

                    widget.currPage = elemIndex;
                    setState('detail');
                });

                listInitialized = true;
            }
            */


            function setState(desiredState){

                if(!stateChanging){
                    stateChanging = true;

                    switch(desiredState){
                        case 'slide':
                            // switch to slide view

                            // see if arrows are showing
                            if(widget.currPage-1 < 0){
                                // hide left arrow
                                $(myGallery + '.galleryContent .arrLeft').hide();
                            }else{
                                //show left arrow
                                $(myGallery + '.galleryContent .arrLeft').show();
                            }
                            if(widget.currPage+1 >= pagesArrLen){
                                // hide right arrow
                                $(myGallery + '.galleryContent .arrRight').hide();
                            }else{
                                //show right arrow
                                $(myGallery + '.galleryContent .arrRight').show();
                            }

                            $(myGallery + '.galleryContent .closeDetail').hide();
                            $(myGallery + '.galleryFooter .getCat').css('cursor', 'pointer');

                            $(myGallery + '.galleryContent').show().animate({opacity:1}, 400);
                            /*
                            $(myListView).animate({opacity:0}, 400, function(){
                                $(myListView).hide();
                                stateChanging = false;
                            });
                            */

                            catpos = $(myGallery + '.galleryFooter .catline').position().left - $(myGallery + '.galleryFooter .counter').width() + 7;
                            $(myGallery + '.galleryFooter .catline').css({'left':catpos});

                            $(myGallery + '.galleryFooter .counter').show();
                            $(myGallery + '.galleryFooter .footerRight').css({'padding-top':'41px'});
                            //$(myGallery + '.galleryFooter .listview').css({'padding-left':'20px', 'background':'url("/public/images/gallery/misc_img/icon_listview.png") no-repeat left center'});
                            //$(myGallery + '.galleryFooter .listview').html(opt.listview.toUpperCase());

                            widget.state = 'slide';
                            break;
                        case 'list':
                            // switch to list view
                            /*
                            if(!listInitialized){
                                initListView();
                            }

                            $(myGallery + '.galleryFooter .getCat').css('cursor', 'pointer');
                            $(myGallery + '.galleryContent').animate({opacity:0}, 400, function(){
                                $(myGallery + '.galleryContent').hide();
                                stateChanging = false;
                            });
                            $(myListView).show().animate({opacity:1}, 400);

                            if(widget.state === 'slide'){
                                catpos = $(myGallery + '.galleryFooter .catline').position().left + $(myGallery + '.galleryFooter .counter').width() - 7;
                                $(myGallery + '.galleryFooter .catline').css({'left':catpos});
                            }
                            $(myGallery + '.galleryFooter .counter').hide();

                            $(myGallery + '.galleryFooter .footerRight').css({'padding-top':'47px'});
                            $(myGallery + '.galleryFooter .listview').css({'padding-left':'22px', 'background':'url("/public/images/gallery/misc_img/icon_slideview.png") no-repeat left center'});
                            $(myGallery + '.galleryFooter .listview').html(opt.slideview.toUpperCase());

                            widget.state = 'list';
                            */
                            break;

                        case 'detail':
                            // switch to detail view

                            // get relevant image first
                            setPage(widget.currPage, 0);

                            $(myGallery + '.galleryContent .arrLeft').hide();
                            $(myGallery + '.galleryContent .arrRight').hide();
                            $(myGallery + '.galleryContent .closeDetail').show();
                            $(myGallery + '.galleryFooter .getCat').css('cursor', 'default');

                            $(myGallery + '.galleryContent').show().animate({opacity:1}, 400);
                            /*
                            $(myListView).animate({opacity:0}, 400, function(){
                                $(myListView).hide();
                                stateChanging = false;
                            });
                            */
                            widget.state = 'detail';
                            break;
                        default:
                            alert('error: gallery is in an undefined state');
                            stateChanging = false;
                    }
                }
            }






            function getPrevPage(){
                if(widget.currPage-1 >= 0){
                    setPage(widget.currPage-1, aniTime);
                }
            }

            function getNextPage(){
                if(widget.currPage+1 < pagesArrLen){
                    setPage(widget.currPage+1, aniTime);
                }
            }


            function setPage(pageNum, time){
                widget.setPage(pageNum, time);
            }

            function jumpToCategory (event){
                if(widget.state !== 'detail'){
                    for(var m=0; m < pagesArrLen; m++){
                        if(pagesArr[m].category === event.target.innerHTML){
                            setPage(m, 600);
                            break;
                        }
                    }
                }
            }

            // set first page
            setPage(initialPage, 0);

            // slide in gallery
            $(elem).animate({opacity:1, left:'50%'}, 600, 'easeOutCubic');
        },

        setPage:function(pageNum, time){
            // sometimes pages is set to -1
            if(pageNum < 0)pageNum = 0;

            var elem = this.element,
                widget = this,
                myGallery = '#' + elem.attr('id') + ' ',
                myPageCont = '#' + elem.attr('id') + ' .galleryPageCont',
                pagesArrLen = this.pagesArrLen;

            var contPos = -1 * pageNum * (this.pageWidth + this.pageMargin),
                cpt = pageNum+1,
                apt = pagesArrLen,
                counterTxt2, pn;

                // slide to relevant page
                $(myPageCont).stop().animate({left:contPos}, time, 'easeOutCubic');

                // see if arrows are showing
                if(pageNum-1 < 0 || this.state === 'detail'){
                    // hide left arrow
                    $(myGallery + '.galleryContent .arrLeft').hide();
                }else{
                    //show left arrow
                    $(myGallery + '.galleryContent .arrLeft').show();
                }

                if(pageNum+1 >= pagesArrLen || this.state === 'detail'){
                    // hide right arrow
                    $(myGallery + '.galleryContent .arrRight').hide();
                }else{
                    //show right arrow
                    $(myGallery + '.galleryContent .arrRight').show();
                }


                // update counter text
                if (cpt < 10){pn = pageNum + 1;cpt = '0' + pn;}
                if (apt < 10) apt = '0' + pagesArrLen;
                counterTxt2 = '/ ' + apt;

                $(myGallery + '.galleryFooter .counter1').html(cpt);
                $(myGallery + '.galleryFooter .counter2').html(counterTxt2);

                $('#supersized-fullscreen-overlay .counter1').html(cpt);
                $('#supersized-fullscreen-overlay .counter2').html(counterTxt2);


               // highlight selected category
               $(myGallery + '.galleryFooter .categories li a').each(function(){
                   var regCol = widget.regularColor,
                       hovCol = widget.hoverColor;

                   if(widget.pagesArr[pageNum].category === $(this).html()){
                        // highlight cat
                        $(this).unbind('mouseenter');
                        $(this).unbind('mouseleave');
                        $(this).css({'color':hovCol});
                        $(myGallery + '.galleryFooter .catline').animate({width:$(this).css("width"), left:$(this).position().left}, 400, 'easeOutCubic');
                    }else{
                        // don't highlight cat
                        $(this).css({'color':regCol});
                        $(this).bind('mouseenter', function(){ $(this).css({'color':hovCol}); });
                        $(this).bind('mouseleave', function(){ $(this).css({'color':regCol}); });
                    }
               });

               var catIndex = jQuery.inArray(this.pagesArr[pageNum].category, this.catArr),
                   catContPos = -1 * catIndex * (this.pageWidth + this.pageMargin);

               //$(myGallery + '.listViewPageCont').stop().animate({left:catContPos}, this.aniTime, 'easeOutCubic');

               this.currCategory = catIndex;
               this.currPage = pageNum;

        },
        
        closeGallery : function(){
            var elem = this.element,
                opt = this.options;
            
            $(elem).animate({opacity:0, left:'150%'}, 600, 'easeOutCubic', function(){ $(elem).hide(); });
            $(opt.origElement).animate({opacity:1, left:'50%'}, 600, 'easeOutCubic');

            
        }

    });
})(jQuery);
