/**
 * @preserve Galleria Clear Channel Theme 2011-04-12
 * http://www.clearchannel.com
 *
 * Copyright (c) 2011, Aino, Clear Channel Radio Digital
 */
 
/*global jQuery, Galleria */

(function($) {


/** Modify Galleria.show() to allow for addition of mediaid in the URL **/
Galleria.prototype.show = function( index, rewind, _history ) {

    // do nothing if index is false or queue is false and transition is in progress
    if ( index === false || ( !this._options.queue && this._queue.stalled ) ) {
        return;
    }

    index = Math.max( 0, Math.min( parseInt( index, 10 ), this.getDataLength() - 1 ) );

    rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex();

    _history = _history || false;

    // do the history thing and return
    if ( !_history && Galleria.History ) {
        if (typeof(this.getData(index).mediaid) != 'undefined') {
            Galleria.History.value( index.toString() + "/" + this.getData(index).mediaid );
        } else {
            Galleria.History.value( index.toString() + "/");
        }
        return;
    }

    this._active = index;

    Array.prototype.push.call( this._queue, {
        index : index,
        rewind : rewind
    });
    if ( !this._queue.stalled ) {
        this._show();
    }

    return this;
};

//this function is to be called at a certain time after a photo loads
//if the photo hasn't changed, it'll show Facebook comments (if set), social +1 buttons
Galleria.prototype.checkSetSocial = function(mediaId) {
    
    var data = this.getData();
    if (data.mediaid == mediaId) {
        //console.log('yes: ' + mediaId);
        //change facebook/twitter buttons upon each load
        if (typeof(gallery_url) != 'undefined') {
        	var shareUrl = gallery_url + '&p=' + data.mediaid;
        	var escapedUrl = escape(shareUrl);
            jQuery('#permalinkTxt1').val(shareUrl); 
            var photoShare = $('#photoShare');
            photoShare.html('');
            photoShare.html('<iframe allowtransparency="true" frameborder="0" scrolling="no" src=\'http://platform.twitter.com/widgets/tweet_button.html?url='+escapedUrl+'&amp;text='+gallery_title_url+'&amp;via='+twitterUsername+'\' style="width:130px; height:25px;"></iframe><iframe src="http://www.facebook.com/plugins/like.php?href=' + escapedUrl + '&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="position: absolute; top: 0px; left: 120px; height: 21px;" allowTransparency="true"></iframe>');
        }
        
        if (typeof(fb_photo_comments) != 'undefined' && fb_photo_comments && this._viewcount != 0) {
            //dynamic facebook comments
            var fbc_container = $('#facebook-comments-container');
            if (typeof(fbc_container) != 'undefined') {
    			var toInsert='<fb:comments publish_feed="true" numposts="5" width="575" href="' + shareUrl + '" ></fb:comments>';
    			fbc_container.html(toInsert);
    			FB.XFBML.parse(document.getElementById('facebook-comments-container'));                    
            }
        }        
    } else {
        //console.log('no: ' + mediaId);           
    }
};

Galleria.addTheme({
    name: 'cc',
    author: 'Clear Channel Radio Digital, T2.5 Development Team',
    css: 'galleria.cc.css',
    defaults: {
        transition: 'slide',
        thumbCrop:  'height',
        _viewcount: 0, //how many photos were viewed during this session
        _leftNavStatus: 'shown',        
		// set this to false if you want to show the caption all the time:
        _toggleInfo: false
    },
    init: function(options) {
        
        //override carousel's set method with our modifications:
        var carousel = this._carousel;
        var gInstance = this;      
        this._carousel.set = function(i) { 
            i = Math.max( i, 0 );
            while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) {
                i--;
            }
            carousel.current = i;
            carousel.animate(); 
            
            //T2.5 Modifications: If 35 or more pictures, they are loaded incrementally.
            //35 and less are loaded in photos.html
            if (typeof(gInstance) == 'undefined') {
                var gInstance = Galleria.get(0);
            }
            if (gInstance._thumbnails.length > 34) {
                for (j = 0; j < 15; j++) {
                    var currentThumb = gInstance._thumbnails[i+j];
                     //if there's a thumbnail & it hasn't been updated & it has a full thumb associated with it
                    if (typeof(currentThumb) != 'undefined' && !currentThumb.updated && gInstance._data[i+j].full_thumb) {
                        $(currentThumb.image).attr('src', gInstance._data[i+j].full_thumb);
                        currentThumb.updated = true;
                        //console.log("updated: " + i + " : " + j);
                    }
                   
                }
            }
            //End T2.5 modifications of the carousel.set method
        };
        //end carousel override
        
        //THIS IS IMPORTANT!!!!!!! Don't skip this part when changing CSS. Change max-height to hide grey area in container
        this.$('stage').css("max-height", options['height']-70);
        
        //resize this, if thumbnails are disabled
        if (this.getOptions('thumbnails') === false) {
            this.$('thumbnails-container').hide();
            this.$('stage').css("top", '4px');//this is in addition to the top margin, making it 14px total
            $('#sponsorBanner').css("top", "0");
        }
        
        this.$('info-title').hide();
        this._viewcount = options._viewcount;
        
        // cache some stuff
        var info = this.$('info-text'),
            touch = Galleria.TOUCH,
            click = touch ? 'touchstart' : 'click';
        
        var container = this.$('container');
        this.append({
            'container' : ['counter']
        });
        // show loader & counter with opacity
        this.$('loader,counter').show().css('opacity', 0.8).css('z-index', 550);

        // some stuff for non-touch browsers
        if (! touch ) {
            this.addIdleState( this.get('image-nav-left'), { left:-50 });
            this.addIdleState( this.get('image-nav-right'), { right:-50 });
            this.addIdleState( this.get('counter'), { opacity:0.8 });
        }
        
		info.show();
        
        // bind some stuff
        this.bind('thumbnail', function(e) {
            
            if (! touch ) {
                // fade thumbnails
                $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() {
                    $(this).not('.active').children().stop().fadeTo(100, 1);
                }, function() {
                    $(this).not('.active').children().stop().fadeTo(400, 0.6);
                });
                
                if ( e.index === options.show ) {
                    $(e.thumbTarget).css('opacity',1);
                }
            }
        });
        
        this.bind('loadstart', function(e) {
            
            //deal with hidden left nav if thumbnails are disabled
            if (this.getOptions('thumbnails') === false) {
                if (this.getIndex() == 0) {
                    $('.galleria-image-nav-left').hide();
                    this._leftNavStatus = 'hidden'; 
                } else {
                    if (this._leftNavStatus === 'hidden') {
                         $('.galleria-image-nav-left').show();
                         this._leftNavStatus = 'shown'; 
                    }            
                }
            }
			
            if (!e.cached) {
                this.$('loader').show().fadeTo(200, 0.4);
            }
            
            this.$('info').toggle( this.hasInfo() );
            
            $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6);

        });
        
        this.bind('loadfinish', function(e) {
            if (typeof(window.prevImage) == 'undefined') window.prevImage = 'none';
            if (window.prevImage != this.getData().mediaid) {
                if (this._viewcount > 0) {
                    if (typeof(s) != 'undefined' && typeof(s.t) == 'function') {
                        s.t();
                    } 
                    if (typeof launchCCTempAd == 'function' && (this._viewcount % 3) === 0) {
                        $('#DARTad300x250').html('');
                        if (typeof(dfp_active) != "undefined" && dfp_active != "") {
                            DFP.pushAd({div: "DARTad300x250", position: "7010", size: "300x250", start: "10" });
                        } else {
                            launchCCTempAd("DARTad300x250","7010","300","250",tile300x250,counter300x250,"iframe","");    
                        }
                    }
                }
                 
                window.prevImage = this.getData().mediaid;  
                
                if (typeof(sponsorBanner) != 'undefined') {
                    sponsorBanner.showBanner();    
                }

                this.$('loader').fadeOut(200);
                var infoHeight = this.$('info');
                
                //Set container height to be set height + height of the info box. We want container to be 60 less pixels if no thumbnails
                if (this.getOptions('thumbnails') === false) {
                    container.height(this._options['height'] + Math.max(infoHeight.height(), 20) - 60);
                } else {
                    container.height(this._options['height'] + 5 + Math.max(infoHeight.height(), 20));    
                }
                
                //wait 1.75 seconds before refreshing +1, FB comments
                var gInstance = this;
                if (this._viewcount == 0) {
                    this.checkSetSocial(this.getData().mediaid);
                } else {
                    var mediaId = parseInt(gInstance.getData().mediaid);
                    setTimeout(function() {gInstance.checkSetSocial(mediaId);}, 1750);
                }
                this._viewcount++;
                                                               
            }
        });
    }
});

}(jQuery));

