jQuery(function(){
    jQuery("span.modcontrols a").live('click', function(evt){
        evt.preventDefault();
        if (jQuery(this).hasClass('confirm')) {
            if (!window.confirm(jQuery(this).attr('title'))) {
                return;
            }
        }
        
        var el = this;
        
        jQuery.get(this.href, {
            'ajax': 1
        }, function(data){
            if (data.error) {
                alert(data.error);
                return;
            }
            
            if (data.deleteComment || data.deleteMovie) {
                if (data.deleteComment) {
                    jQuery(el).parents('[id^="edit"]').remove();
                }
                else {
                    window.location = 'movieindex.php';
                }
            }
            else {
                if (data.text) {
                    jQuery(el).html(data.text);
                }
                
                if (data.href) {
                    jQuery(el).attr('href', data.href);
                }
                
                if (data.title) {
                    jQuery(el).attr('title', data.title);
                }
                
                if (data['addclass']) {
                    jQuery(el).parents('[id^="edit"]').find('[id^="td_post_"]').addClass(data['addclass']);
                }
                
                if (data['removeclass']) {
                    jQuery(el).parents('[id^="edit"]').find('[id^="td_post_"]').removeClass(data['removeclass']);
                }
            }
        }, 'json');
    });
    
    jQuery("span.thumbpopup").each(function(index, elem){
        jQuery(elem).css({
            'left': jQuery(elem).parents(".itemthumbnail").find("img.tmb").position().left +
            90
        });
    });
    
    // asign handler for link options
    jQuery("span.viewmore a").click(function(evt){
        evt.preventDefault();
        jQuery("span.viewmore a").removeClass('active');
        jQuery(this).addClass('active');
        
        jQuery("ul.tab_list li.tcat a").click();
    });
    
    jQuery('div.movietabs').scollingThumbnails({
        width: 160
    });
    
    jQuery(jQuery("div.movietabs ul li a").get(0)).click();
    
    if (jQuery('div.showmorelink').length) {
        // hide posts
        var showPostCount = 20;
        
        jQuery('div.showmorelink a').click(function(evt){
            evt.preventDefault();
            var postsToShow = showPostCount;
            jQuery("div.posts").children().not('#lastpost').each(function(index, el){
                if (postsToShow == false) {
                    return false;
                }
                if (jQuery(el).is(':hidden')) {
                    jQuery(el).show();
                    postsToShow--;
                }
            });
            if (postsToShow) {
                // no more posts to show
                jQuery('div.showmorelink').hide();
            }
        });
        
        jQuery("div.posts").children().not('#lastpost').hide();
        jQuery('div.showmorelink a').click();
    }
    if (jQuery("a#raveMovie").length) {
        jQuery("a#raveMovie").overlay({
            fixed: true,
            'left': 'center',
            'top': 'center',
            mask: {
                color: '#ebecff',
                loadSpeed: 200,
                opacity: 0.9
            },
            
            closeOnClick: false
        });
        
        jQuery('div.addReviewButton a input,div.addReviewButton a').click(function(){
            window.location = jQuery('div.addReviewButton a').attr('href');
        });
    }

    jQuery("div#raveMovieDialog input[type=button]").click(function(evt){
        evt.preventDefault();
        var submitUrl = jQuery("a#raveMovie").attr('href');
        var data = {
            'do': 'postreply',
            'securitytoken': SECURITYTOKEN,
            'message': jQuery('textarea[name=raveText]').val()
        };
        jQuery.post(submitUrl, data, function(response){
            if (jQuery(response).find('error').length) {
                jQuery("div#raveMovieDialog div.submitError").html('').fadeIn();
                jQuery(response).find('error').each(function(index, elem){
                    jQuery("div#raveMovieDialog div.submitError").html(jQuery("div#raveMovieDialog div.submitError").html() + jQuery(elem).text());
                });
                return;
            }
            jQuery("div#raveMovieDialog div.submitError").html('').fadeOut();
            jQuery('textarea[name=raveText]').val('');
            jQuery("a#raveMovie").data('overlay').close();
            jQuery('div#thankYou').remove();
            jQuery('<div></div>').attr('id', 'thankYou').appendTo('body').addClass('raveOverlay').html(jQuery("a#raveMovie").attr('data-complete')).overlay({
                fixed: true,
                'left': 'center',
                'top': 'center',
                mask: {
                    color: '#ebecff',
                    loadSpeed: 'slow',
                    opacity: 0.9
                },
                
                closeOnClick: true,
                load: true
            });
            
            setTimeout(function(){
                jQuery('div#thankYou').data('overlay').close();
            }, 1500);
            
        }, 'xml');
    });
    
    jQuery('span#rateContainer a').click(function(evt){
        evt.preventDefault();
        var elem = this;
        jQuery.get(jQuery(elem).attr('href'), function(data){
			if(!data || !data.message) {
				return;
			}
            var message = data.message;
            jQuery('div#likedMessage').remove();
            jQuery('<div id="likedMessage">' + message + '</div>').appendTo('body').css({
                'top': (jQuery(elem).offset().top-20)+'px',
                'left': (jQuery(elem).offset().left+20)+'px'
            }).fadeIn(300, function(){
				setTimeout(function(){
					jQuery('div#likedMessage').fadeOut(200);
				}, 1500);
			});
        }, 'json');
    });
});

function vbpmi_submit_rating(value){
    if (value) {
        jQuery("span.currentrating").html(value);
    }
    jQuery.get('ajax.php', {
        'do': 'ratemovie',
        'movieid': movieid,
        'value': value
    });
    
    jQuery("a#raveMovie").data('overlay').close();
}

function vbpmi_update_display(value){
    // jQuery("span.currentrating").html(value);
}

function vbpmi_reset_default(value, link){
    // console.log(value, link);
}

// scrolling thumbnails plugin
(function(jQuery){

    jQuery.fn.scollingThumbnails = function(options){
        var defaults = {
            width: 150
        };
        var options = jQuery.extend(defaults, options);
        
        return this.each(function(){
        
            if (jQuery(this).data('scollingThumbnails')) {
                return this;
            }
            
            var obj = this;
            
            jQuery(this).data('scollingThumbnails', {
                'target': obj,
                'options': options
            });
            
            if (jQuery(obj).is(':hidden')) {
                jQuery(obj).show();
                var hideAfter = true;
            }
            else {
                var hideAfter = false;
            }
            
            jQuery("div.scrollarrow.left", obj).click(function(evt){
                evt.preventDefault();
                methods.scrollRight.apply(obj);
            });
            jQuery("div.scrollarrow.right", obj).click(function(evt){
                evt.preventDefault();
                methods.scrollLeft.apply(obj);
            });
            
            jQuery('div.latestbit_container', obj).live('mouseover', function(evt){
                var width = jQuery(obj).data('scollingThumbnails').options.width;
                var currentPosition = jQuery("div.scrollingbits", obj).position();
                var currentItemPosition = jQuery(this).position();
                
                var containerWidth = jQuery("div.scrollingcotnainer", obj).width();
                
                var relativePosition = currentItemPosition.left + currentPosition.left;
                
                if (relativePosition < -5) {
                    // methods.scrollRight.apply(obj);
                }
                else 
                    if (relativePosition < containerWidth && relativePosition + width > containerWidth + 5) {
                    // methods.scrollLeft.apply(obj);
                    }
            });
            
            jQuery("ul.tab_list li a", obj).click(function(evt){
            
                evt.preventDefault();
                
                jQuery("div.movietabs ul.tab_list li").each(function(index, el){
                    jQuery(el).removeClass('tcat').addClass('thead');
                    jQuery(el).addClass('thead');
                });
                
                jQuery(jQuery(this).parents("li").get(0)).addClass('tcat').removeClass('thead');
                
                jQuery.post(jQuery(this).attr('href'), {
                    options: jQuery("span.viewmore a.active").attr('data-value'),
                    'securitytoken': SECURITYTOKEN
                }, function(data){
                    jQuery("div.content div.scrollingbits", obj).html(data);
                    if (jQuery(obj).is(':hidden')) {
                        jQuery(obj).show();
                        var isHidden = true;
                    }
                    else {
                        var isHidden = false;
                    }
                    // scroll to start
                    methods.scrollToStart.apply(obj);
                    
                    if (methods.requiresScroll.apply(obj)) {
                        jQuery("div.scrollarrow").show();
                    }
                    else {
                        jQuery("div.scrollarrow").hide();
                    }
                    
                    // register tooltips
                    jQuery("div.enhancedthumb").each(function(index, el){
                        var tooltipPosition = 'topMiddle';
                        var targetPosition = 'bottomMiddle';
                        jQuery(el).qtip({
                            content: jQuery('span.popupcontent', el).html(),
                            position: {
                                corner: {
                                    tooltip: tooltipPosition,
                                    target: targetPosition
                                }
                            },
                            adjust: {
                                scroll: true
                            },
                            hide: {
                                fixed: true // Make it fixed so it can be
                                // hovered over
                            },
                            scroll: {
                                type: 'fade',
                                length: 1000
                            },
                            style: {
                                padding: '5px 15px'
                            }
                        });
                    });
                    
                    if (isHidden) {
                        jQuery(obj).hide();
                    }
                });
            });
            
            if (hideAfter) {
                jQuery(obj).hide();
            }
        });
    };
    
    var methods = {
        requiresScroll: function(){
            var containerWidth = jQuery("div.scrollingcotnainer", this).width();
            
            var itembitTotalWidth = methods.getItemsWidth.apply(this);
            
            return itembitTotalWidth - containerWidth > 5;
        },
        preventNewEvent: function(){
        
            if (!this.lastEventDate) {
                this.lastEventDate = (new Date()).getTime();
                return false;
            }
            if (this.lastEventDate > (new Date()).getTime() - 300) {
                return true;
            }
            
            this.lastEventDate = (new Date()).getTime();
            return false;
        },
        scrollLeft: function(){
        
            if (methods.preventNewEvent.apply(this)) {
                return;
            }
            
            var containerWidth = jQuery("div.scrollingcotnainer", this).width();
            
            var itembitTotalWidth = methods.getItemsWidth.apply(this);
            
            var currentPosition = jQuery("div.scrollingbits", this).position();
            
            var nextPosition = currentPosition.left - jQuery(this).data('scollingThumbnails').options.width;
            
            if (nextPosition + itembitTotalWidth < containerWidth) {
                nextPosition = containerWidth - itembitTotalWidth;
            }
            
            if ((nextPosition + containerWidth) % jQuery(this).data('scollingThumbnails').options.width) {
                nextPosition = nextPosition - (nextPosition + containerWidth) % jQuery(this).data('scollingThumbnails').options.width;
            }
            
            jQuery("div.scrollingbits", this).animate({
                'left': nextPosition - 15
            }, 100);
        },
        scrollRight: function(){
        
            if (methods.preventNewEvent.apply(this)) {
                return;
            }
            
            var containerWidth = jQuery("div.scrollingcotnainer").width();
            
            var itembitTotalWidth = methods.getItemsWidth.apply(this);
            
            var currentPosition = jQuery("div.scrollingbits", this).position();
            
            var nextPosition = currentPosition.left + jQuery(this).data('scollingThumbnails').options.width;
            
            if (nextPosition > 0) {
                nextPosition = 0;
            }
            
            if (Math.abs(nextPosition) % jQuery(this).data('scollingThumbnails').options.width > 5) {
                nextPosition = nextPosition - nextPosition % jQuery(this).data('scollingThumbnails').options.width - jQuery(this).data('scollingThumbnails').options.width;
            }
            
            console.log(nextPosition);
            
            jQuery("div.scrollingbits", this).animate({
                'left': nextPosition
            }, 100);
        },
        getItemsWidth: function(){
            return jQuery("div.latestbit_container", this).length * jQuery(this).data('scollingThumbnails').options.width;
        },
        scrollToStart: function(){
            jQuery("div.scrollingbits", this).animate({
                'left': 0
            }, 100);
        }
    };
})(jQuery);

