// Copyright 2009-2011 Kathleen van der Spek.  All rights reserved.

function ImagePreloader(images, whileLoading, afterLoaded) {
    ImagePreloader.preloadedImages = ImagePreloader.preloadedImages || {};
    var preloadImages = [],
        imageCount = images.length,
        imagesLoaded = 0,
        loaded;

    images.each(function(img) {
        var src = img.src;
        if (ImagePreloader.preloadedImages[src]) { imageCount--; return; }
        
        var preloadImage = new Image();
        preloadImages.push(preloadImage);
        // any sort of load is okay..
        // we could extend this to provide some place-holder on abort/error.. ?
        preloadImage.onload = preloadImage.onabort = preloadImage.onerror = function() {
            ImagePreloader.preloadedImages[src] = true;
            whileLoading && whileLoading(++imagesLoaded, imageCount);
            if (imagesLoaded == imageCount && !loaded) {
                loaded = true;
                afterLoaded && afterLoaded();
            }
        };
        preloadImage.src = src;
    });
    
    if (imageCount == imagesLoaded && !loaded) {
        loaded = true;
        afterLoaded && afterLoaded();
    }
    return this;
}

function Preloader(element, whileLoading, afterLoaded) {
  element = $(element);

  // get the set of all images that will be visible 
  this.imagePreloader = new ImagePreloader(Array.prototype.without.apply(element.select('img'), 
                                                               element.select('.preload>img')),
                                                               whileLoading, afterLoaded);
}

function GalleryControl(galleryId) {
    var gallery = $(galleryId);
    
    // undo any extra image tags we added from using this gallery b4     
    gallery.select('.duplicate').each(Element.remove);
    var galleryWidth = gallery.getWidth(),
        images = gallery.select('img'),
        currentIndex = 0,
        maxIndex = images.length - 1,
        visibleWidth = gallery.ancestors()[0].getWidth(),
        x = 0, 
        img;
    
    if (visibleWidth < galleryWidth) {
        
        // clone extra images to pull off infinite scrolling effect.
        while ((img = images[x++]) && (visibleWidth > 0)) {
            visibleWidth -= img.getWidth();
            gallery.appendChild(img.cloneNode(true).addClassName('.duplicate'));
        }
        this.needNavigation = !!img;
    } else {
        this.needNavigation = false;
    }
    
    this.moveRight = function() {
        if (currentIndex < maxIndex) {
            new Effect.Move(gallery, { x: -images[currentIndex++].getWidth(), y: 0, queue: 'end' } );
        } else {                     
            currentIndex = 0;
            new Effect.Move(gallery, { x: -images[maxIndex].getWidth(), y: 0, queue: 'end', 
                                      afterFinish: function() { gallery.setStyle({left: '0px', top: '0px'}); }
            });
        }
    };
    this.moveLeft = function() {
        if (currentIndex > 0) {
            new Effect.Move(gallery, { x: images[--currentIndex].getWidth(), y: 0, queue: 'end' });  
        } else {
            currentIndex = maxIndex;
            new Effect.Move(gallery, { x: images[0].getWidth(), y: 0, queue: 'end',
                                      beforeSetup: function() { gallery.setStyle({left: -galleryWidth+"px", top: "0px"}); }
            });
        }
    };
}

function NavigationButtons(leftButtonId, rightButtonId) {
    var left = $(leftButtonId),
        right = $(rightButtonId),
        that = this;
        
    function setupButton(div, click) {
        var img = div.select('img')[0],
            src = img.src;
        fixPNG(img);
        div.observe('mouse:leave', function() { 
            img.src = src; 
            fixPNG(img);
        }).observe('mouse:enter', function() {
            img.src = src.replace('.png', '_hover.png');
            fixPNG(img); 
        }).observe('click', click);
    }
    setupButton(right, function() { 
        that.rightClicked && that.rightClicked();
    });

    setupButton(left, function() {
        that.leftClicked && that.leftClicked();
    });
}

function GalleryController(navButtons) {
    var galleries = $$('.gallery'),
        gallery, 
        preloader;
    
    navButtons.leftClicked = function() { galleryControl.moveLeft(); };
    navButtons.rightClicked = function() { galleryControl.moveRight(); };

    this.switchGallery = function(newGallery) {
        // ensure we have some default.
        newGallery = newGallery?$(newGallery):galleries[0];
        
        if (gallery == newGallery) { return; }
        var oldGallery = gallery;
        gallery = newGallery;
        
        preloader = new ImagePreloader(gallery.select('img'), function() { spinner.start(); }, function() {
            spinner.stop();
            if (oldGallery) {
                new Effect.Fade(oldGallery, {duration: 1});
            }
            gallery = newGallery;
            // reset to start of gallery.
            gallery.setStyle({left: '0px', top: '0px'});
            new Effect.Appear(gallery, {
                duration: 1, 
                afterSetup: function() { 
                    gallery.removeClassName('preload'); 
                }, 
                afterFinish: function() {
                    galleryControl = new GalleryControl(gallery);

                    if (galleryControl.needNavigation) {
                        new Effect.Appear($('nav_strip'));
                    } else { 
                        new Effect.Fade($('nav_strip'));
                    }
                }
            });
        });
    };
    this.getCurrentGallery = function() {
        return gallery;
    };
    this.switchGallery(galleries[0]);
}

function TextController() {
    var textArea;
        
    this.switchText = function(newTextArea) {
        if (textArea) {
            new Effect.Fade(textArea, {duration: 1});
        }
        textArea = newTextArea && $(newTextArea);
        if (textArea) {
            new Effect.Appear(textArea, {duration: 1});
        }
    };           
}
        
function MenuControl(menuId) {
    var menu = $(menuId),
        normalWidth = 'width: 15%;',
        maxWidth = 'width: 25%',
        selectedWidth = 'width: 20%',
        selectedElement,
        selectedSubMenu,
        selectedSubMenuElement;
     
     function selectSubMenu(target, element, afterFinish) {
         afterFinish = afterFinish || function() { };
         
         var subMenu = $('menu_' + target);
         if (subMenu == selectedSubMenu) { return; }
         
         if (selectedSubMenu) {
             new Effect.Morph(selectedSubMenuElement, {
                 style: normalWidth,
                 queue: { scope: 'menumouse' },
                 duration: 0.3
             });
             new Effect.BlindUp(selectedSubMenu, { duration: 1 });
         }
         selectedSubMenuElement = element;
         new Effect.BlindDown(selectedSubMenu = subMenu, { 
             duration: 1, 
             afterFinish: 
                 function() {
                     // select the first item in our menu, if it exists.
                     var a = subMenu.select('a')[0];
                     if (a) selectMenuItem(a);
                     afterFinish();
                 }
             } );
     }
     
     function selectMenuItem(element) {
         if (selectedElement == element) return;
         trackVisit();
         if (selectedElement) {
             new Effect.Morph(selectedElement, {
              style: (selectedElement == selectedSubMenuElement)?selectedWidth:normalWidth,
              queue: { scope: 'menumouse' },
              duration: 0.3
            });
         }
         new Effect.Morph(element, {
             style: selectedWidth,
             queue: { scope: 'menumouse' },
             duration: 0.3
         });
         var target = element.getAttribute('href').replace(/^.*?#/,'');
         selectedElement = element;

         switch(target) {   
            case 'collections':
                selectSubMenu(target, element);
                break;
			case 'fallwinter2010':
            case 'springsummer2010':
            case 'fall2009':
                galleryController.switchGallery(target + '_gallery');
                textController.switchText();
                break;
            case 'about':
                selectSubMenu(target, element);
                // continue;
            case 'bio':
//            case 'manufacturing':
                galleryController.switchGallery();
                textController.switchText(target);
                break;
            case 'stores':
                selectSubMenu(target, element, function() { 
                    galleryController.switchGallery();
                    textController.switchText(target);
                });
                break;
            case 'contact':
                selectSubMenu(target, element, function() { 
                    galleryController.switchGallery();
                    textController.switchText(target);
                });
                break;
         }
     }                           
    $$('.menuselection,.menuheading').each(function(element) {
        
        element.setStyle(normalWidth);
        element.observe('mouse:enter', function() {
            collapseEffects('menumouse');
            var isSelected =  (element == selectedElement || element == selectedSubMenuElement);       
            new Effect.Morph(element, {
                style: isSelected?selectedWidth:maxWidth,
                queue: { position: 'end', scope: 'menumouse' },
                duration: 0.3
            });       
        }).observe('mouse:leave', function() {
            collapseEffects('menumouse');                                                
            var isSelected =  (element == selectedElement || element == selectedSubMenuElement);
            new Effect.Morph(element, {
                style: isSelected?selectedWidth:normalWidth,
                queue: { position: 'end', scope: 'menumouse' },
                duration: 0.3
            });
        }).observe('click', function() {
            element.blur && element.blur(); // fix dotted border in IE6.
            selectMenuItem(element);
        });
    });
}

function showHideInfo() {
    var info = galleryController.getCurrentGallery().id + '_info';
    textController.switchText(info);    
}


