var photogallery = {
    scrollnumber: 4,
    //how many slides to scroll on a single click
    marginwidth: 5,
    //match right margin from css
    gallery: '#gallery',
    //id of UL holding the big images
    galleryNav: '#gallery-nav',
    //id of the slider nav
    gallerySectionInitialize: function(childId) {
        if (childId) {
            $(this.galleryNav).find('.' + childId).addClass('active');
        }
        else {
            $(this.gallery + ' li').eq(0).addClass('active').find('section').eq(0).addClass('active');
            $(this.galleryNav + ' li').eq(0).addClass('active');
        }
    },

    gallerySetClick: function() {
        $(this.galleryNav + ' li').live('click', function() {
            $(this).siblings().removeClass('active');
            $(this.gallery + ' li').removeClass('active');
            $(this).addClass('active');
            var galleryIndex = $(this).index();
            var hidden = $(this).find(':input');
            var storyId = hidden[0].value;
            var storyTitle = hidden[1].value;
            if (!($(this).find('section').hasClass("active"))) {
                $(this.gallery + '>li').eq(this.galleryIndex).addClass('active'); //.find('section').eq(0).addClass('active');
            }
            gaTrackEvent('Overlay', 'Photo Gallery Select', storyTitle, galleryIndex);
            $.ajax({
                type: "POST",
                url: "/Webservices/PublicationService.asmx/GetFeaturedPhotoControl?",
                data: "{ 'contextKey':'" + storyId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    $(photogallery.gallery).html('').html(data.d).append('<span class="galleryClose"><img src="/images/orgHome/galleryClose.png" alt="Close" /></span>');
                    $('.galleryClose').click(function() {
                        overlay.overlayClose();
                    });
                    addthis.toolbox(".addthis_toolbox");
                    audioPlayer.initializePlayer();
                }
            });

        });
    },

    // thumbnail carousel behavior
    galleryScroll: function() {
        var liwidth = $(this.galleryNav + ' li').width() + this.marginwidth; // get single li width plus 5px for margin between each (assumes all are the same width, if not see bf's carousel)
        var lilength = $(this.galleryNav + ' li').length; // count total # of li's
        var displaywidth = -(liwidth * this.scrollnumber); // set # to show n at a time
        var totalwidth = (liwidth * lilength); // get width of all li's in horizontal row
        var positionmax = totalwidth + displaywidth - 1; // get total width minus list offest (700px-1px) to test for when we've reached the end of the carousel
        var galleryNavWidth = $(photogallery.gallery).width() - 30; //get total width of gallery holder minus next/prev button size
        $(this.galleryNav).css('width', displaywidth + 'px');
        $(this.galleryNav + ' ul').css('width', totalwidth + 'px'); // set ul to width of all li's for one super-wide container
        // add pagination arrows
        $(this.galleryNav + ' ul').parent().append('<span class="prev deactivated">Previous</span>');
        $(this.galleryNav + ' ul').parent().append('<span class="next">Next</span>');

        // add components for overlay
        //$('body').append('<div id="overlay-bg"></div>');

        // next button actions
        $('.next').click(function() {
            if ($(this).hasClass('deactivated')) // if we're at the end, disable button, end function
                return;
            if ($(this.galleryNav + ' ul').hasClass('running')) // check to see if the slides are running before allowing another click
                return;
            $(photogallery.galleryNav + ' ul').addClass('running').css('position', 'absolute').animate({
                'left': '+=' + displaywidth + 'px' // slide right 700px
            }, 500, function() {
                $('.prev').removeClass('deactivated'); // if we've move, reactive the other button
                $(this).removeClass('running');
                var position = $(photogallery.galleryNav + ' ul').position().left;
                if (position < -positionmax) { // if we've reached the end (if our position is further than the max position, deactivate - 1224 vs 1225
                    $('.next').addClass('deactivated');

                }
            });
        });

        $('.prev').click(function() {
            if ($(this).hasClass('deactivated')) // if deactivated (reached the end) disable
                return;
            if ($(photogallery.galleryNav + ' ul').hasClass('running')) // check to see if the slides are running before allowing another click
                return;
            $(photogallery.galleryNav + ' ul').addClass('running').css('position', 'absolute').animate({
                'left': '-=' + displaywidth + 'px' // slide left 700px
            }, 500, function() {
                $('.next').removeClass('deactivated');
                $(this).removeClass('running');
                var position = $(photogallery.galleryNav + ' ul').position().left;
                if (position == 0) { // if at 0 we're at the beginning, disable prev button
                    $('.prev').addClass('deactivated');
                }
            });
        });
    },

    galleryOpen: function() {
        var urlvars = getUrlVars();
        var childId = urlvars["photoId"];
     
        $.ajax({
            type: "POST",
            url: "/Webservices/PublicationService.asmx/GetPhotoOfWeekControl?",
            contentType: "application/json; charset=utf-8",
            data: "{'contextKey':'" + childId + "'}",
            dataType: "json",
            success: function(data) {
                $(photogallery.galleryHolder).html('').html(data.d).append('<span class="galleryClose"><img src="/images/orgHome/galleryClose.png" alt="Close" /></span>');
                $('.galleryClose').click(function() {
                    overlay.overlayClose();
                });
                photogallery.gallerySectionInitialize(childId);
                photogallery.gallerySetClick();
                photogallery.galleryScroll();
                $(photogallery.galleryHolder).fadeIn('slow');
                addthis.toolbox(".addthis_toolbox");
                audioPlayer.initializePlayer();
            }
        });
        gaTrackEvent('Overlay', 'Photo Gallery Open', document.title, 0);

    }
}

var mediaplayer = {
    playerOpen: function(obj) {
        var hidden = obj.find(':input');
        var childId = hidden[0].value;
        var childTitle = hidden[1].value;
        
        if (childId) {
            gaTrackEvent('Overlay', 'Media Click', childTitle, 0);
            $.ajax({
                type: "POST",
                url: "/Webservices/PublicationService.asmx/GetNewNoteworthyControl?",
                data: "{'contextKey':'" + childId + "', 'cssJSClass':'<%=cssJSClass %>'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    $(mediaplayer.galleryHolder).html('').html(data.d).append('<span class="galleryClose"><img src="/images/orgHome/galleryClose.png" alt="Close" /></span>');
                    $('.galleryClose').click(function() {
                        overlay.overlayClose();
                    });
                    $.each(['advocacyForm'], function(idx, item) {
                        var form = $('#' + item);
                        advocacyForms.formInitialize(form);
                    });
                    $(mediaplayer.galleryHolder).fadeIn('slow');
                    addthis.toolbox(".addthis_toolbox");
                }
            });
            return false;
        }
    }
}

var audioPlayer = {
    initializePlayer: function(audio_file) {
    audio_file = $(':input#audio_file').val();
        if(audio_file){
   
            $("#jquery_jplayer_1").jPlayer({
                ready: function() {
			
                    $(this).jPlayer("setMedia", {
                        mp3: audio_file
                    });
                },
             
                swfPath: "js",
                supplied: "mp3"
            })
			.bind($.jPlayer.event.play, function() {
				gaTrackEvent('Overlay', 'Audio Player Click', audio_file, 0);
			});
        } 
    }
}

var overlay = {
    galleryHolder: '#galleryHolder',
    //name of container holding your rendering
    //galleryLauncher: 'overlayLauncher', //class of elements used to open overlay
    overlayCenter: function() {

        // set overlay centered
        var galleryWindowWidth = $(window).width();
        var galleryWindowHeight = $(window).height();
        var popupWidth = $(this.galleryHolder).width();
        var popupHeight = $(this.galleryHolder).height();
        var popupTop = (galleryWindowHeight / 2) - (popupHeight / 2);
        var popupLeft = (galleryWindowWidth / 2) - (popupWidth / 2);
        if (galleryWindowHeight < popupHeight || galleryWindowWidth < popupWidth) {
            $('body').removeClass('overflowHidden');
        }
        //var popupTop = "60px";
        //var popupLeft = "60px";		
        $(this.galleryHolder).css({
            'left': popupLeft,
            'top': popupTop
        });
    },

    overlayClose: function() {
        $(document).unbind("keydown", overlay.handleEscape);
        var overlayBG = $('#overlay-bg');
        overlayBG.fadeOut('fast');
        overlayBG.hide();
        $(this.galleryHolder).fadeOut('slow');
        $(this.galleryHolder).html('');
        $('body').removeClass('overflowHidden');
    },


    overlaySetOpenFunction: function(overlayOpen) {

        $('.' + this.galleryLauncher).click(function(e) {
            e.preventDefault();
            $('html').animate({
                scrollTop: 0
            }, 'slow'); //IE, FF
            $('body').addClass('overflowHidden').animate({
                scrollTop: 0
            }, 'slow'); //chrome

            overlayOpen($(this));
            setTimeout(function() {
                var overlayBG = $('#overlay-bg');
                overlayBG.fadeIn('fast');
                overlayBG.show();
                $('.galleryClose').click(function() {
                    overlay.overlayClose();
                });
                $(document).keydown(overlay.handleEscape);
                overlay.overlayCenter();
            }, 500);

        });
    },

    //Our function that listens for escape key.
    handleEscape: function(e) {
        if (e.keyCode == 27) {
            overlay.overlayClose();
        }
    }
}

function initializePhotoGallery() {
    photogallery.galleryHolder = overlay.galleryHolder;
    overlay.galleryLauncher = "photoLauncher";
    overlay.overlaySetOpenFunction(photogallery.galleryOpen);
}

function initializeMediaGallery() {
    overlay.galleryLauncher = "mediaLauncher";
    mediaplayer.galleryHolder = overlay.galleryHolder;
    overlay.overlaySetOpenFunction(mediaplayer.playerOpen);
}

jQuery(document).ready(function() {
    // initialize
    setJS();
    overlay.overlayCenter();
    initializePhotoGallery();
    initializeMediaGallery();
    $('.showPanelTrigger').click(function() {
        $('#pnlSubscribeForm').fadeIn('fast', function() { });
    });
    //check if photo passed in
    var urlvars = getUrlVars();
    var childId = urlvars["photoId"];
    if (childId) {
        var overlayBG = $('#overlay-bg');
        overlayBG.fadeIn('fast');
        overlayBG.show();
        photogallery.galleryOpen();
    }

});

var addthis_config = {
    data_ga_property: 'UA-531016-6',
    "data_track_clickback": true
};
