$.fn.rotateBanners = function(delay) {
    var getNextIndex = function (index, total) {
        return index == total - 1 ? 0 : index + 1;
    }
    var showBanner = function (div, banners, index) {
        scheduleBanner (div, banners, getNextIndex(index, banners.length));
        div.animate({opacity:0}, {
            duration: 'fast',
            complete: function () {
                div.find('a.the-banner')
                    .prop('href', banners[index].href)
                    .prop('target', banners[index].new_tab != 0 ? '_blank' : '_self')
                    .data('popupWidth', banners[index].popup_width)
                    .data('popupHeight', banners[index].popup_height)
                    .find('img').prop('src', banners[index].src);
                div.find('.banner-selector a').each(function () {
                    $(this).toggleClass('current', $(this).data('bannerIndex') == index);
                });
                div.animate({opacity:1}, 'fast');
            }
        });
    }
    var scheduleBanner = function (div, banners, index) {
        window.clearTimeout(div.data('rotatorTimeoutId'));
        div.data('rotatorTimeoutId', window.setTimeout(function () {
            showBanner(div, banners, index);
        }, delay));
    }
    this.each(function () {
        var $this = $(this);
        var $selector = $('<div>').addClass('banner-selector');
        var banners = $this.data('banners');
        $this.mouseover(function () {
            window.clearTimeout($this.data('rotatorTimeoutId'));
        });
        $this.mouseout(function () {
            scheduleBanner($this, banners, getNextIndex($this.find('.banner-selector a.current').data('bannerIndex'), banners.length));
        });
        var index = 0;
        $.each(banners, function (i, v) {
            $('<img/>')[0].src = v.src;
            var $a = $('<a>').prop('href', '#').data('bannerIndex', index).appendTo($selector).click(function () {
                showBanner($this, banners, $(this).data('bannerIndex'));
                return false;
            });
            if (index++ == 0) $a.addClass('current');
        });        
        $selector.appendTo($this).css('margin-left', -$selector.outerWidth(true)/2);
        scheduleBanner ($this, banners, 1);
    });
};

$.fn.highlight = function(highlightColor, duration) {
    var originalBgColor = this.css("background-color");
    //this.stop().css("background-color", "#ff5");
    this.animate({
        backgroundColor: "#ff0",
        boxShadow: '0 0 30px #ff0'}, 
    {duration: 0, queue: true});
    this.animate({
        backgroundColor: originalBgColor,
        boxShadow: '0 0 0px'
    }, {duration : 1000, queue: false, complete: function () {
        $(this).removeAttr('style');
    }});

};

$.fn.updateChanged = function(newDOM) {
    this.each(function () {
        var newElement = newDOM.find('#' + this.id);
        if (newElement.html() != $(this).html()) {
            $(this).replaceWith(newElement);
            (newElement.hasClass('updatable-highlight') ? newElement : newElement.find('.updatable-highlight')).highlight();
        }
    });
};

$.fn.trackUpdate = function(events, postpone) {
    this.each(function () {
        $form = $(this);
        var changed = function () {
            window.clearTimeout($form.data('ajaxTimeoutId'));
            $form.data('ajaxTimeoutId', window.setTimeout(function () {
                var $disabled = $form.find(':disabled');
                $disabled.prop('disabled', false);
                var newRequestedData = $form.serialize();
                $disabled.prop('disabled', true);
                if ($form.data('lastRequestedData') == newRequestedData) return;
                $form.data('lastRequestedData', newRequestedData);
                //$form.find('.updatable :input').attr('disabled', true);
                $.ajax({
                    url: location.pathname,
                    type: 'POST',
                    data: newRequestedData,
                    success: function (html) {
                        if ($form.data('lastRequestedData') != newRequestedData) return;
                        $('.updatable').updateChanged($(html));
                        $form.trigger('updated');
                    }                                                                          
                });
            }, postpone));
        };
        for (selector in events) {
            $form.find(selector).live(events[selector], changed);
        }
        $form.data('lastRequestedData', $form.serialize());
    });
}

$('.rollover-button').live('mouseenter', function () {
    this.src = this.src.replace('.normal.png', '.hover.png');
}).live('mouseleave', function () {
    this.src = this.src.replace('.hover.png', '.normal.png');}
);

function popup() {
    if ($(this).data('popupWidth') && $(this).data('popupHeight')) {
        window.open(
            this.href,
            '_blank',
            'width=' + $(this).data('popupWidth') + ',height=' + $(this).data('popupHeight') + ',left=350,top=200,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no'
        );
        return false;
    }
}

$(function () {
    $(':text, textarea').filter(':visible:first').focus();
    $('.popup-window').click(popup);
});

$(window).load(function() {
    if (!$.fontAvailable('Arial Rounded MT Bold')) {
        Cufon.replace('.font-amtr', { fontFamily: 'Arial Rounded MT Bold' });
        Cufon.replace('.font-din1451', { fontFamily: 'DIN 1451 Std' });
    }
    $('.message .close').live('click', function () {
        $('.message').animate({ opacity: 0 }, 'normal', function () { $(this).remove(); });
        //{ opacity: 0, padding: 0, margin: 0, border: 0, height: 0 }
        return false;
    });
    window.setTimeout(function () {
        $('.autohide .close').click();
    }, 2000);
    $('.rotated-banner').rotateBanners(7000);
    $('.confirm').click(function () {
        if (!confirm($(this).data('confirm'))) {
            return false;
        }
    });
});

