var Bw = Bw || { };

$(document).observe('dom:loaded', function(event) {
    // setup cufon fonts

    Cufon.replace('ul.lang-menu li a, ul.main-menu li a, ul.sub-menu li a, div#photo div.controls a.gallery-btn',
                  { hover: { color: '#44246b' } });
    Cufon.replace('ul.top-menu li a', { hover: { color: '#6e6e6e' } });

    // different background for mobile safari
    
    if (Prototype.Browser.MobileSafari) {
        $(document.body).addClassName('mobile');
    } else {
        $(document.body).addClassName('regular');
    }

    // setup tabs and tab animation

    Bw.tabs = { };
    $$('.tabs').each(function(element, index) {
        var name = element.up().readAttribute('id');
        name = name.substr(0, name.lastIndexOf('-'));

        var tabs = new S2.UI.Tabs(element);
        tabs.anchors.invoke('observe', 'click', function(event) {
            window.location.hash = name + '/' + this.readAttribute('href').substr(1);
            Cufon.replace('ul.sub-menu li a', { hover: { color: '#44246b' } });
        });

        element.observe('ui:tabs:change', function(event) {
            var from = event.memo.from;
            var fromIndex = from.tab.readAttribute('tabIndex');

            var to = event.memo.to;
            var toIndex = to.tab.readAttribute('tabIndex');

            var options = {
                duration: 0.5,
                transition: 'sinusoidal'
            };

            if (fromIndex < toIndex) {
                from.panel.morph('left: -840px;', Object.extend({ }, options));
                to.panel.morph('left: 0px', Object.extend({
                    before: function() {
                        to.panel.setStyle({ left: '840px' });
                    }
                }, options));
            } else if(fromIndex > toIndex) {
                from.panel.morph('left: 840px;', Object.extend({ }, options));
                to.panel.morph('left: 0px', Object.extend({
                    before: function() {
                        to.panel.setStyle({ left: '-840px' });
                    }
                }, options));
            }
        });
        Bw.tabs[name] = tabs;
    });

    // setup navigation
    
    $$('ul.main-menu a, ul.top-menu a, ol.album-listing li a').each(function(element, index) {
        if (element.href.lastIndexOf('#') == -1) return;

        var hash = element.href.substr(element.href.lastIndexOf('#'));
        element.observe('click', (function(event, hash) {
            event.stop();
            Bw.navigateTo(hash);
        }).bindAsEventListener(this, hash));
    });

    var target = window.location.hash;
    if (target == "" && document.viewport.getDimensions().height < 600) {
        target = '#home';
    }
    Bw.navigateTo(target);

    // initialize slideshows
    
    $$('.slideshow').each(function(element, index) {
        new Bw.Slideshow(element, {
            duration: 1,
            interval: 3
        });
    });

    // initialize gallery

    new Bw.Gallery();

    // setup order forms
    $$('div.order-form').each(function(container, index) {
        function attachFormMessage(parent, message, type) {
            var messageBox = parent.down('.message');
            if (!messageBox) {
                messageBox = new Element('div', {
                    'class': 'message ' + type
                });

                var content = new Element('div', {
                    'class': 'msg-text'
                });

                var button = new Element('div', {
                    'class': 'close-button ' + type
                }).update('OK');
                button.observe('click', function(event) {
                    messageBox.hide();
                });

                messageBox.appendChild(content);
                messageBox.appendChild(button);
                parent.appendChild(messageBox);
            }

            $w(messageBox.className).each(function(className) {
                if (className != 'message') {
                    messageBox.removeClassName(className);
                }
            });
            messageBox.addClassName(type);

            messageBox.down('.msg-text').update(message);
            messageBox.show();
        }

        function setupForm(form) {
            form.observe('submit', function(event) {
                event.stop();
                $(this).request({
                    onComplete: (function(transport) {
                        var parent = $(this).up();
                        var response = transport.responseJSON;
                        parent.update(response.form);
                        setupForm(parent.down('form'));
                        attachFormMessage(parent, response.message, response.status);
                    }).bind(form)
                });
                $(this).disable();
                var parent = form.up();

                var message = '<img src="/images/form-processing-'+Bw.culture+'.gif" alt="Form processing" />';
                attachFormMessage(parent, message, 'regular');
            });
        }

        var form = container.down('form');
        setupForm(form);
    });

    // setup color choice

    $('color-choice').observe('change', function(event) {
        var value = this.getValue().toLowerCase();
        $('tee-img').setAttribute('src', '/images/tee-'+value+'.jpg');
    });
});

/**
 * Navigate to a place on page based on the hash. The hash is of the
 * form page/tab, where page is the name of the div to scroll the
 * document to and tab is the name of a tab within that div. The "tab"
 * part of the hash is optional.
 */
Bw.navigateTo = function(hash) {
    if (!hash) return;

    hash = hash.substr(1);
    var parts = hash.split('/');

    var page = parts[0];
    var tab = parts[1];

    var to = $(page+'-page').cumulativeOffset().top;
    var effect = new S2.FX.Scroll($(document.body), {
        to: to - 20,
        duration: 1
    });
    effect.play();

    if (tab) {
        Bw.tabs[page].setSelectedPanel($(tab));
        Cufon.refresh();
    }
    window.location.hash = hash;
}

/**
 * A simple slideshow with crossfading images. The constructor takes
 * an element containing img elements to show and an object with
 * options.
 */
Bw.Slideshow = Class.create({
    initialize: function(element, options) {
        this.position = 0;
        this.element = element;
        this.options = options;

        element.makePositioned();

        this.images = element.getElementsBySelector('img');
        this.images.each(function(img, index) {
            if (index > 0) {
                img.setStyle({ opacity: 0 });
            }
            img.setStyle({
                position: 'absolute',
                top: 0,
                left: 0
            });
        });
        this.currentItem = this.images[0];
        
        if (!Prototype.Browser.MobileSafari) {
            this.timeout = setInterval(this.next.bind(this),
                                       (this.options.interval || 2) * 1000);
        } else {
            this.element.observe('click', this.next.bind(this));
            this.element.setStyle({
                cursor: 'pointer'
            });
        }
    },

    next: function() {
        this.position = (this.position + 1) % this.images.length;
        this.showItem(this.position);
    },

    previous: function() {
        this.position = ((this.position - 1) < 0) ?
            (this.images.length - 1) : this.position - 1;
        this.showItem(this.position);
    },

    showItem: function(position) {
        var item = this.images[position];
        this.currentItem.morph('opacity: 0', {
            transition: this.options.transition || 'linear',
            duration: this.options.duration || 1
        });
        item.morph('opacity: 1', {
            transition: this.options.transition || 'linear',
            duration: this.options.duration || 1
        });
        this.currentItem = item;
    }
});

/**
 * Ajax based gallery script
 */
Bw.Gallery = Class.create({
    initialize: function() {
        new Ajax.Request('/galleries.json', {
            method: 'get',
            onSuccess: this.jsonLoaded.bind(this)
        });
    },

    jsonLoaded: function(transport) {
        this.data = transport.responseJSON;

        this.display = $('img-display');

        $('prev-img').observe('click', (function(event) {
            var prev = this.previous(this.currentIndex, 
                                     this.gallery);
            $('current-img').update(prev + 1);
            this.setImage(this.gallery[prev]);
            this.currentIndex = prev;
            Cufon.refresh();
        }).bind(this));
        $('next-img').observe('click', (function(event) {
            var next = this.next(this.currentIndex,
                                 this.gallery);
            $('current-img').update(next + 1);
            this.setImage(this.gallery[next]);
            this.currentIndex = next;
            Cufon.refresh();
        }).bind(this));

        $('concerts-gallery').observe('click', (function(event) {
            this.galleryId = 'concerts';
            this.gallery = this.data[this.galleryId];
            this.setGallery(this.gallery, this.galleryId);
        }).bind(this));
        $('studio-gallery').observe('click', (function(event) {
            this.galleryId = 'studio';
            this.gallery = this.data[this.galleryId];
            this.setGallery(this.gallery, this.galleryId);
        }).bind(this));
        
        this.galleryId = 'concerts';
        this.gallery = this.data[this.galleryId];

        this.setGallery(this.gallery, this.galleryId);
    },

    setGallery: function(gallery, galleryId) {
        $('current-img').update(1);
        $('img-total').update(gallery.length);
        
        $$('.gallery-btn').each(function(elem) {
            elem.removeClassName('active');
        });
        $(galleryId+'-gallery').addClassName('active');
        Cufon.refresh();

        this.currentIndex = 0;
        this.setImage(gallery[this.currentIndex]);
    },

    next: function(current, gallery) {
        var next = (current + 1) % gallery.length;
        return next;
    },

    previous: function(current, gallery) {
        var previous = ((current - 1) < 0) ? (gallery.length - 1) : current - 1;
        return previous;
    },

    setImage: function(img) {
        $('image-display').update('<img src="'+img.src+'" />');
        $('photo-author').update('Photo '+img.author);
    }   
});

