if(!window.console) window.console.log = function() {}

var categories = $A(['concept', 'overview', 'lighting', 'bollards', 'litterbins',
                     'seating', 'signage', 'cyclestands', 'shelters',
                     'otherfurniture']);

// Hash Kategorie-Bilder
var layerImages = $H({});

// Referenz auf Popup-Layer
var popup = null;

// Referenz auf momentanen Key-Event-Listener
var currentKeypressObserver = null;

// Momentane Mauskoordinaten
var mouseX = null;
var mouseY = null;

// Queue Thumbnails
var thumbsQueue = $A([]);

// Caches Thumbnails und Popups
var thumbsCache = $H(); // Referenzen auf die einzelnen Layer
var popupsCache = $H(); // HTML-Codes Popup

var ProductThumbnail = Class.create();
ProductThumbnail.prototype = {

  options: null,


  fade:         true,

  area:           null,
  container:      null,
  hasContent:     null,
  contentLoading: false,

  mouseInArea:  false,

  mouseObserver: null,

  //----------------------------------------------------------------------

  initialize: function(area) {

        this.area = $(area);

    this.options = Object.extend({
      id:         'thumbnail_' + this.area.id,
      className:  'thumbnail',
      fade:       true,
      offsetY:    50
    }, arguments[1] || {});

    this.fade = this.options.fade;

    // "Nacktes" div in Dokument rein
        this.container    = $(document.createElement('div'));
        this.container.id = this.options.id;
        this.container.addClassName(this.options.className);
        this.container.setStyle({ position: 'absolute', display: 'none', zIndex: 5000 });

      // In DOM-Tree rein
      document.body.appendChild(this.container);

        this.area.onmouseover = function(event) {
          //console.log('MOUSEIN');

          var coords = this.getMouseCoords(event);
          this.mouseInArea = true;

          if(this.hasContent) {

                this.placeAt(coords[0], coords[1]);
            this.show();

          } else if(!this.contentLoading) {

            this.contentLoading = true;

            var url = '/index.php?area=products&show=popup&name=' + this.area.id + '&image_only=1';
            new Ajax.Request(url, {
                onSuccess: function(t, json) {

                  //console.log('SET HEADLINE ' + json.name);

                var headline = document.createElement('h3');
                headline.innerHTML = json.name;
                this.container.appendChild(headline);

                //console.log('SET IMAGE');

                // Bild
                if(json.src && json.width > 0 && json.height > 0) {
                    var image = $(document.createElement('img'));
                    image.addClassName('thumbnail_image');
                    image.src    = json.src;
                    image.width  = json.width;
                    image.height = json.height;
                    image.alt    = json.name;
                    image.border = 0;
                    this.container.appendChild(image);
                } //else alert('NO IMAGE');

                //console.log('SET SUB');

                // Bildunterschrift
                this.container.appendChild(document.createElement('br'));
                this.container.appendChild(document.createTextNode('Click for more details'));

                //console.log('HC TRUE');
                this.hasContent = true;

                if(this.mouseInArea) {
                      this.placeAt(coords[0], coords[1]);
                    this.show();
                }
                }.bind(this)
            });
          }
        }.bind(this);

      this.area.onmouseout = function() {
        //console.log('MOUSEOUT');
        this.mouseInArea = false;
        this.hide();
      }.bind(this);
  },

  //----------------------------------------------------------------------

  show: function() {

        this.mouseObserver = (this.followMouse).bindAsEventListener(this);
        Event.observe(document, 'mousemove', this.mouseObserver);

    if(this.fade) {
      new Effect.Appear(this.container, { duration: 0.5 });
    } else {
      this.container.show();
    }
    },

    //----------------------------------------------------------------------

  hide: function() {
    if(this.fade) {
      new Effect.Fade(this.container, { duration: 0.5 });
    } else {
      this.container.hide();
    }

    Event.stopObserving(document, 'mousemove', this.mouseObserver);
  },

  //----------------------------------------------------------------------

  followMouse: function(event) {

        var coords = this.getMouseCoords(event);
        var mouseX = coords[0];
        var mouseY = coords[1];

        if(mouseX && mouseY)
        this.placeAt(mouseX, mouseY);
  },

  //----------------------------------------------------------------------

  getMouseCoords: function(event) {
        if(!event)
        event = window.event;

        var mouseX = null;
        var mouseY = null;

         // Standard
        if (event.pageX || event.pageY) {

            mouseX = event.pageX;
            mouseY = event.pageY;

        }  else if (event.clientX || event.clientY) {

            mouseX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            mouseY = event.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
        }

    return new Array(mouseX, mouseY);
  },

    //----------------------------------------------------------------------

    placeAt: function(mX, mY) {

      // Thumbnail
      var x = mX - (this.container.getWidth() / 2);
      var y = mY - (this.container.getHeight() + this.options.offsetY);

        this.container.setStyle({
            left: x, // - (this.container.getWidth() + 5),
            top:  y // - (this.container.getHeight() + 5)
        });
    }
};

//------------------------------------------------------------------------------

/**
 * Initialisiert die Seite
 */
function init() {


    Event.observe(window, 'load', function() {

        //alert('init buttons');
        initButtons();

        //alert('init maps');
        initMaps();

        //alert('init layers');
        initLayerImages();

        //alert('init popup layer');
        initPopupLayer();

        //initBasket();

        // Produktmatrix anzeigen
        $('container').show();

        swapMainImage('overview');
    });

    // Quit mainloop if page gets unloaded
    Event.observe(window, 'unload', destroy);



}

//------------------------------------------------------------------------------


//------------------------------------------------------------------------------
function initButtons() {

    var click = function(event) {

        if(!event)
        event = window.event;

        var clickedButton = Event.element(event);
        var clickedName = clickedButton.id.split('_')[1];

        $$('.category_button').each(function(button) {
            var name = button.id.split('_')[1];

            if(button != clickedButton) {
                button.src = '/images/buttons/' + name + '_p.gif';
                button.onmouseover = function() { button.src = '/images/buttons/' + name + '_a.gif' };
                button.onmouseout  = function() { button.src = '/images/buttons/' + name + '_p.gif' };
            }
        });

        clickedButton.src = '/images/buttons/' + clickedName + '_a.gif';
        clickedButton.onmouseover = null;
        clickedButton.onmouseout  = null;

        swapMainImage(clickedName);
    }

    var containerCell = $$('#products_buttons td').first();
    categories.each(function(category) {

      var buttonStyle = {
            border: '1px solid white',
            marginRight: '3px'
        };

        if(category == categories.last())
        buttonStyle.marginRight = '18px';

      var pButton = $(new Image());
      pButton.src = '/images/buttons/' + category + '_p.gif';
      //pButton.width  = 82;
        pButton.height = 22;
      pButton.border = 0;
      pButton.id     = 'button_' + category;

      pButton.addClassName('category_button');
      pButton.setStyle(buttonStyle);

        var aButton = $(new Image());
        aButton.src = '/images/buttons/' + category + '_a.gif';
        //aButton.width  = 82;
        aButton.height = 22;
        aButton.border = 0;
        aButton.id     = 'button_' + category;

        aButton.addClassName('category_button');
        aButton.setStyle(buttonStyle);

      var button = (category == 'overview') ? aButton : pButton;

      if(button != aButton) {
            button.onmouseover = function() { button.src = '/images/buttons/' + category + '_a.gif' };
            button.onmouseout  = function() { button.src = '/images/buttons/' + category + '_p.gif' };
      }
      button.onclick = click;

      containerCell.appendChild(button);

        layerImages[category] = null;
    });
}

//------------------------------------------------------------------------------

function initMaps() {

    var query = $H(new String(document.location.href).toQueryParams());
    var thumbOptions = { fade: false, offsetY: parseInt(query.y) || 50 };

    //console.log($H(thumbOptions).inspect());

    categories.each(function(category) {
        //console.log('init map for category ' + category);

        var url = '/imagemaps/' + category + '.html';

        var map = $('prodmap_' + category);
        map.name = map.id;
        map.addClassName('layer_imagemap');

        $$('#prodmap_' + category + ' area').each(function(area) {

            area.href = 'javascript: void(0)';
            if(category == 'concept') {
              var subConcept = area.id;

              var imageContainer = $(document.createElement('div'));
              imageContainer.setStyle({
                backgroundColor: 'white',
                display: 'none',
                position: 'absolute',
                border: '1px solid black',
                zIndex: 5001,
                padding: '10px 10px 3px 10px'
                });
                document.body.appendChild(imageContainer);

                var cImage = $(new Image());
                cImage.src = '/images/products_layers/concept/' + subConcept + '.jpg';
                cImage.id = 'image_concept_' + subConcept;
                cImage.width = 697;
                cImage.height = 329;
                cImage.border = 0;
                imageContainer.appendChild(cImage);

              var containerHeader = $(document.createElement('div'));
              containerHeader.setStyle({ textAlign: 'right', backgroundColor: 'white' })
                imageContainer.appendChild(containerHeader);

                var closeButton = $(document.createElement('a'));
              closeButton.addClassName('close');
              closeButton.href = 'javascript:void(0)';
              closeButton.update('close');
                closeButton.onclick = function() {
                     new Effect.Parallel([
                        new Effect.Unblock('container', { duration: 0.5}),
                        new Effect.Unblock('products_buttons', { duration: 0.5}),
                        new Effect.Fade(imageContainer, { duration: 0.5 })
                    ]);
                }
                containerHeader.appendChild(closeButton);

                area.onclick = function() {
                    imageContainer.centerOnScreen();

                    new Effect.Parallel([
                        new Effect.Block('container', { color: '#000000', opacity: 0.5, duration: 0.5}),
                        new Effect.Block('products_buttons', { color: '#000000', opacity: 0.5, duration: 0.5}),
                        new Effect.Appear(imageContainer, { duration: 0.5 })
                    ]);
                }

            } else {

              new ProductThumbnail(area, thumbOptions);
              area.onclick = function() { showPopup(area); }
            }
        });
    });
}

//------------------------------------------------------------------------------

/**
 * Initialisiert die Bilder der Matrix
 */
function initLayerImages() {

    layerImages.keys().each(function(key) {

        // Bild vorladen
        var image = new Image();
        image.width  = 908;
        image.height = 750;
        image.src = 'images/products_layers/' + key + '.gif';

        /* if(key == 'overview') {

            alert('OVERVIEW');

            switchTo = function() {
                alert('Switch to: ' + key);
                swapMainImage(key);
            }

            Event.observe(image, 'load', switchTo);

        } */

        // in Hash speichern
        layerImages[key] = image;
    });


}


//------------------------------------------------------------------------------

/**
 * Initialisiert den Popup-Layer
 */
function initPopupLayer() {

    // Div in Dokument rein
    new Insertion.Bottom(document.body, '<div id="popup" style="display: none" class="new"></div>');
    popup = $('popup');

    // Style setzen
    popup.setStyle({
        margin:   0,
        padding:  0,
        position: 'absolute',
        zIndex:   5001
    });
}

//------------------------------------------------------------------------------

function destroy() {

    // Alle Eventlistener killen
    Event.unloadCache();
}

//------------------------------------------------------------------------------

/**
 * Matrix-Bild tauschen
 */
function swapMainImage(navPoint) {
    // Bild aus Hash mit vorgeladenen Bildern holen
    var newImage = layerImages[navPoint];

    // neues image-tag erzeugen
    // (einfach src-attribut tauschen ginge auch, usemap aber nicht)
    var useMap    = $('prodmap_' + navPoint) ? 'usemap="#prodmap_' + navPoint +'"' : ''
    var imageHtml = '<img id="image" src="' + newImage.src + '" border="0" ' + useMap + '/>';

    // Bild im container tauschen
    container.innerHTML = imageHtml;
}

var currentPopupImage = null;

/**
 * Popup anzeigen
 */
function showPopup(area) {
    var url = '/index.php?area=products&show=popup&name=' + area.id;

    // Thumbnail-Queue leeren
    thumbsQueue = $A([]);

    // ggf. noch sichtbaren Thumbs ausblenden
    /*
    $$('.thumbnail').each(function(thumbnail) {
       new Effect.Fade(thumbnail, { duration: 0.5 });
    });
    */
    thumbsCache.keys(function(key) {
      thumbsCache[key].hide();
    });

    // Sanduhr zeigen
    document.body.style.cursor = 'wait';

    // Funktion zum Einblenden
    var popupAppear = function(area) {

        // Content aus Cache updaten
        popup.innerHTML = popupsCache[area.id];

        // Close-Link mit Ausblendfunktion linken

            $$('#popup a.close').each(function(element) {
                element.href = 'javascript:void(0)';
                element.onclick = hidePopup;
            });

        // Link zum WK-adden linken
        var addBasketLink = $$('#popup a.addbasket').first();
        if(addBasketLink) {
            addBasketLink.onclick = function() {
                try {
                    basket.addBookmark(area.id);
                } catch(e) {}
            }
        }

        currentPopupImage = $$('#popup img.popup_img').first();

        // Popup zentrieren
        popup.centerOnScreen( { keepLayout: false } ); // There is no layout to keep

        new Effect.Parallel([
            // Content-Teil blocken (Hauptnavi soll funktional bleiben)
            new Effect.Block('container', { color: '#000000', opacity: 0.5, duration: 0.5}),

            // Kategorie-Navi blocken
            new Effect.Block('products_buttons', { color: '#000000', opacity: 0.5, duration: 0.5}),

            // Popup einblenden
            new Effect.Appear('popup', { duration: 0.5 })
        ]);

        // "Esc" schließt Popup
        currentKeypressObserver = function(event) { event.keyCode == 27 && hidePopup(); };
        Event.observe(document, 'keypress', currentKeypressObserver);
    }

    // Existiert HTML Popup im Cache?
    if(popupsCache[area.id]) {

        // Ja -> anzeigen
        document.body.style.cursor = 'auto'; // normalen Cursor anzeigen
        popupAppear(area);

    } else {
        if(area.id == 'selux_olivio') {
            if(false && navigator.appName == 'Microsoft Internet Explorer') {

                try {
                    var ieVersion = parseInt(((String)(navigator.userAgent.match(/MSIE [0-9]/))).substr(5, 1));
                    if(ieVersion <= 6) {

                        window.open(
                            "/selux_olivio/olivio.php",
                            "Olivio",
                            "width=640,height=710,location=no,menubar=no,resizable=no,scrollbars=no,status=no,status=no"
                        );
                        return;
                    }
                } catch(e) {}
            }

            url = '/selux_olivio/olivio.html';
        }

        // Nein, vom Server holen
        new Ajax.Request(url, {

            onSuccess: function(t) {

                // in Cache speichern
                popupsCache[area.id] = t.responseText;

                // normalen Cursor anzeigen
                document.body.style.cursor = 'auto';

                // Popup einblenden
                popupAppear(area);
            }
        });
    }
}

/**
 * Popup schließen
 */
function hidePopup() {

    new Effect.Parallel([

        // Content-Teil freigeben
        new Effect.Unblock('container', { duration: 0.5 }),

        // Kategorie-Navi freigeben
        new Effect.Unblock('products_buttons', { duration: 0.5 }),

        // Popup ausblenden
        new Effect.Fade('popup', { duration: 0.5 })
    ]);

    // Escape wieder freigeben
    if(currentKeypressObserver != null) {
        Event.stopObserving(document, 'keypress', currentKeypressObserver);
        currentKeypressObserver = null;
    }
}

init();