/**
 *  Showcase page object
 */
var Showcase = new function() {
  var self = this;  // reference to itself
  /*this.picture = null;
  this.title = null;
  this.description = null;*/


  function markSelection(items, a) {
    var as = items.getElements('a');
    for (var j=0; j<as.length; j++)
      as[j].removeClass('selected');
    a.addClass('selected');
  }


  this.__onCategoryClick = function(event, xml, items) {
    event.stop(); // prevents the browser from following the link
    var a = event.target;
    /*var as = items.getElements('a');
    for (var j=0; j<as.length; j++)
      as[j].removeClass('selected');
    a.addClass('selected');*/
    markSelection(items, a);
    self.loadItems(xml, a.name);
  }


  /**
   *  loadCategories() - Loads all the categories
   *
   */
  this.loadCategories = function(xml) {
    debug('Showcase.loadCategories({xml})');
    var total = 0;
    var categories = xml.selectNodes('/portfolio/categories/category');
    total = categories.length;
    debug('Showcase.loadCategories() : var total='+ total);

    var list = $$("#categories .list")[0];
    var items = $$("#categories .list .items")[0];
    var ul = new Element('ul');
    for (var i=0; i<categories.length; i++) {
      var node = categories[i];
      var name = node.getAttribute('name');
      var title = (node.getElementsByTagName('title')[0].firstChild) ? node.getElementsByTagName('title')[0].firstChild.nodeValue : "";
      var desc = (node.getElementsByTagName('description')[0].firstChild) ? node.getElementsByTagName('description')[0].firstChild.nodeValue : "";
      var li = new Element('li');
      var a = new Element('a', {
        'href': 'javascript:void(0);',
        'html': title,
        'title': desc,
        'name': name,
        'events': {
          'click': function(event) {
            self.__onCategoryClick(event, xml, items);
          }
        }
      });

      li.adopt(a);
      ul.adopt(li);
    }
    items.innerHTML = "";
    items.adopt(ul);

    // set list slider
    setHSlider(total);

    // select the first one from the list
    if (total > 0) {
      var a = items.getElement('a');
      markSelection(items, a);
      this.loadItems(xml, a.name);
    }

    return total;
  }


  /**
   *  __onItemClick() - Triggers on item click
   *
   */
  this.__onItemClick = function(event, items, picture, title, description) {
    debug('Showcase.__onItemClick()');
    //alert(event);
    event.stop(); // prevents the browser from following the link
  //if (event.target.tagName != 'A')
    //return;
    var a = event.target;
    //alert(a);
    //debug('Showcase.__onItemClick() : var a.href='+ a.getProperty('href'));

    /*var as = items.getElements('a');
    for (var j=0; j<as.length; j++)
      as[j].removeClass('selected');
    a.addClass('selected');*/
    markSelection(items, a);
    var full = a.getProperty('href');
    var thumb = a.getProperty('thumbnail');
    //alert(full);
    //var pos = full.lastIndexOf('.');
//    var pos = full.lastIndexOf('/');
    //var ext = full.substring(pos);
//    var fileName = full.substring(pos);
    //var thumb = full.substring(0, pos) +'_thumb'+ ext;
//    var thumb = full.substring(0, pos) +'/thumbs'+ fileName;
//    debug('Showcase.__onItemClick() : var thumb='+ thumb);
    var desc = $('text');
    picture.setProperty('href', full);
//    picture.setProperty('title', a.getProperty('html'));
    picture.setProperty('title', a.getProperty('heading'));
    picture.style.backgroundImage = 'url('+ thumb +')';
//    title.setProperty('html', a.getProperty('html'));
    title.setProperty('html', a.getProperty('heading'));
    description.setProperty('html', a.getProperty('title'));
  }


  /**
   *  loadItems() - Loads items from specific category
   *
   */
  this.loadItems = function(xml, category) {
    debug('Showcase.loadItems({xml}, "'+ category +'")');
    var nodes = xml.selectNodes('/portfolio/items[@category="'+ category +'"]/item');
    var total = nodes.length;
    debug('Showcase.loadItems() : var total='+ total);

    // clean picture, title and description
    var picture = $('picture').getElement('a');
    var title = $('text').getElement('h4');;
    var description = $('text').getElement('p');;
    //alert(title);
    //alert(description);
    debug('Showcase.loadItems() : var picture='+ picture);

    picture.setStyle('backgroundImage', 'none');
    title.innerHTML = '';
    description.innerHTML = '';//setProperty('html', '');
    //alert(description);

    // build the list
    var items = $$('#portfolio .navigation .list .items')[0];
    var ul = new Element('ul');
    for (var i=0; i<nodes.length; i++) {
      var node = nodes[i];
      var tit = (node.getElementsByTagName('title')[0].firstChild) ? node.getElementsByTagName('title')[0].firstChild.nodeValue : "";
      var dsc = (node.getElementsByTagName('description')[0].firstChild) ? node.getElementsByTagName('description')[0].firstChild.nodeValue : "";
      var lnk = (node.getElementsByTagName('link')[0].firstChild) ? node.getElementsByTagName('link')[0].firstChild.nodeValue : "javascript:void();";
      //alert(tit +', '+ dsc +', '+ lnk);
      var li = new Element('li');
      var pos = lnk.lastIndexOf('/');
      var fileName = lnk.substring(pos);
      var thumb = lnk.substring(0, pos) +'/thumbs'+ fileName;
      var a = new Element('a', {
        'href': lnk,
        'title': dsc,
        /*'html': '<img onclick="javascript:void(0);" src="'+ thumb +'">',*/
        'heading': tit,
        'thumbnail': thumb,
        'events': {
          'click': function(event) {
            //alert(event.target.tagName);
            self.__onItemClick(event, items, picture, title, description);
          }
        }
      });
      var img = new Element('img', {
        'src': thumb,
        'HREF': lnk,    /* NONSENSE: Must be uppercase because of IE!!! */
        'title': dsc,
        'heading': tit,
        'thumbnail': thumb
      });
      a.adopt(img);
      li.adopt(a);
      ul.adopt(li);
    }
    items.innerHTML = '';
    items.adopt(ul);

    // set list slider
    setVSlider(total);

    // pop-hover
    TB_init();

    // select the first one from the list
    if (total > 0) {
      var a = items.getElement('a');
      markSelection(items, a);
      a.fireEvent('click', [{target: a, stop: function(){}}, items, picture, title, description], 250);
    }

    return total;
  }


  /**
   *  loadData() - Loads the data from the XML
   *
   */
  this.loadData = function() {
    debug('Showcase.loadData()');
    var total = 0;
    //var description = $$('#description')[0];
    //alert(description);

    // AJAX onFailure handler
    var __onFailure = function(transport) {
      debug("Showcase.onNavigate().__onFailure()");
      Global.onFailure(this, transport);
    }

    // AJAX onComplete handler
    var __onComplete = function(transport) {
      debug("Showcase.onNavigate().__onComplete()");
      // hide progress
      Global.setProgress(false);
    }

    // AJAX onSuccess handler
    var __onSuccess = function(response, xml) {
      debug("Showcase.onNavigate().__onSuccess()");
      // alert(transport.responseText);
      // load categories
      total = self.loadCategories(xml);
    }

    //debug('Showcase.loadData() : var item.href='+ item.href);
    new Request({
      url: "data/data.xml",
      method: 'get',
      async: false,
      evalScripts: false,
      autoCancel: true,
      onSuccess: __onSuccess,
      onComplete: __onComplete,
      onFailure: __onFailure
    }).send();

    return total;
  }


  /**
   *  setVSlider() - Creates a vertical slider if required
   *
   */
  function setVSlider(total) {
    debug('Showcase.setVSlider('+ total +')');
    var slider = $('slider');
    var up = $$('#portfolio .navigation .up')[0];
    var down = $$('#portfolio .navigation .down')[0];
    if (total == 0) {
      up.getElement('span').setStyle('visibility', 'hidden');
      down.getElement('span').setStyle('visibility', 'hidden');
      slider.setStyle('display', 'none');
      return;
    }

    //debug($('list').getStyle('height'));
    //debug($('items').getStyle('height'));
    //debug($$('#items li')[0].getStyle('height'));
    var list = $$('#portfolio .navigation .list')[0];
    var items = $$('#portfolio .navigation .list .items')[0];
    var itemHeight = (items.getElement('li')) ? items.getElement('li').getStyle('height').toInt() : -1;
    var itemSpacing = (items.getElement('li')) ? items.getElement('li').getStyle('margin-bottom').toInt() : 0;
    var listItems = Math.round(list.getStyle('height').toInt() / itemHeight);
    var hiddenItems = total-listItems;
    var knob = $('knob');
    var position = 0;

    if (hiddenItems <= 0) {
      up.getElement('span').setStyle('visibility', 'hidden');
      down.getElement('span').setStyle('visibility', 'hidden');
//      slider.setStyle('display', 'none');
      return;
    }
    else {
      up.getElement('span').setStyle('visibility', 'visible');
      down.getElement('span').setStyle('visibility', 'visible');
//      slider.setStyle('display', 'block');
    }

//    knob.setStyle('height', Math.round(list.getStyle('height').toInt() / hiddenItems) +'px');
    //debug(listItems);
    var scroller = new Fx.Scroll(items);
/*    var slider = new Slider(slider, knob, {
                              mode: 'vertical',
                              wheel: true,
                              snap: true,
                              range: [0, hiddenItems],
                              steps: hiddenItems,
                              onChange: function(step) {
                                //debug(step);
                                scroller.set(0, step*itemHeight);
                                position = step;
                                debug('position: '+ position);
                              }
                            });
*/
    // set slider for arrows

    up.addEvent('click',
                function() {
                  var oldPos = position;
                  if (position > 0) {
//                  slider.set(--position);
                    // added instead of the previous commented line
                    --position;
                    var newPos = position*itemHeight + (itemSpacing*position);
                    debug('up position: '+ oldPos +' -> '+ position +' => '+ newPos);
                    scroller.set(0, newPos);
                  }
                }
    );

    down.addEvent('click',
                function() {
                  var oldPos = position;
                  if (position < hiddenItems) {
//                  slider.set(++position);
                    // added instead of the previous commented line
                    ++position;
                    var newPos = position*itemHeight + (itemSpacing*position);
                    debug('down position: '+ oldPos +' -> '+ position +' => '+ newPos);
                    scroller.set(0, newPos);
                  }
                }
    );
  }


  /**
   *  setHSlider() - Creates a horizontal slider if required
   *
   */
  function setHSlider(total) {
    debug('Showcase.setHSlider('+ total +')');
    var slider = $('slider');
    if (total == 0) {
      slider.setStyle('display', 'none');
      return;
    }

    var list = $$('#categories .list')[0];
    var items = $$('#categories .list .items')[0];
    var ul = $$('#categories .list .items ul')[0];
    var listItems = $$('#categories .list .items li');
    var listWidth = list.getStyle('width').toInt();

    // get total width of all the items in the list
    var itemsWidth = 0;
    for (var i=0; i<listItems.length; i++) {
      itemsWidth += listItems[i].getStyle('width').toInt();
      //debug(listItems[i].getStyle('width'));
    }

    var averageWidth = Math.round(itemsWidth / total);
    debug('Showcase.setHSlider() : var itemsWidth='+ itemsWidth);
    debug('Showcase.setHSlider() : var total='+ total);
    debug('Showcase.setHSlider() : var averageWidth='+ averageWidth);

    // set the width of the div.items container to the width of all the items together
    // and calculate the position of the container to be centered within the div.list container
    items.setStyle('width', itemsWidth);
    //alert(listWidth +", "+ itemsWidth +", "+ Math.round((listWidth - itemsWidth)/2));
    var middle = Math.round((listWidth - itemsWidth)/2);
    //items.setStyle('left', middle);

    // show the arrows
    var left = $$('#categories .left')[0];
    var right = $$('#categories .right')[0];
    if (itemsWidth <= listWidth) {
      left.setStyle('visibility', 'hidden');
      right.setStyle('visibility', 'hidden');
    }
    else {
      left.setStyle('visibility', 'visible');
      left.addEvent('click',
                  function() {
                    var position = items.getStyle('left').toInt();
                    var oldPos = position;
                    position += averageWidth;
                    if (position > 0)
                      position = 0;
                    var fx = new Fx.Tween(items).start('left', oldPos, position)
                    //items.setStyle('left', position);
                  }
      );

      right.setStyle('visibility', 'visible');
      right.addEvent('click',
                  function() {
                    var position = items.getStyle('left').toInt();
                    var oldPos = position;
                    position -= averageWidth;
                    if (position < (middle*2))
                      position = middle*2;
                    debug('right position: '+ position);
                    var fx = new Fx.Tween(items).start('left', oldPos, position);
                    //items.setStyle('left', position);
                  }
      );

    }

    debug('Showcase.setHSlider() : var itemsWidth'+ itemsWidth);
    debug('Showcase.setHSlider() : var list.getStyle("width").toInt()='+ list.getStyle('width').toInt());
    debug('Showcase.setHSlider() : var items.getStyle("width").toInt()='+ items.getStyle('width').toInt());
    debug('Showcase.setHSlider() : var ul.getStyle("width").toInt()='+ ul.getStyle('width').toInt());
  }


  /**
   *  load() -
   *
   */
  this.load = function() {
    debug('Showcase.load()');
    var total = this.loadData();
  }
}