//
// $Id: chars.js 57321 2008-08-19 10:25:21Z rdw $
//

var Chars = new Class({
    'initialize':
    function(character) {
      this.character = character;
      this.selectedCredits = { };
      if (window.ie && !document.documentElement.clientHeight) {
        // mootools really wants strict mode - fix things for IE quirk-smode
        Event.prototype.fixRelatedTarget = function() 
          { this.page.y += document.body.scrollTop; Event.fix.relatedTarget() };
      }
    },
    'xhrComplete':
    function(ajax, text, action, success) {
      $('spin').removeClass('busy');
      if (window.console) eval(ajax.getHeader("X-L4P"));
      if (success) { 
        var complete = this[action+'Complete'];
        complete = complete.bind(this);
        if (complete) complete(text);
      }
      if (!success) $('error').removeClass('hide');
    },
    'xhr': 
    function(data, action) {
      $('spin').addClass('busy');
      data.character = this.character;
      var ajax = new Ajax
        ( '/swiki/character/select-'+this.url, 
          { method: 'post',
            postBody: Object.toQueryString(data),
            headers: {'X-L4P': 1},
            onFailure: function(text) { this.xhrComplete(ajax, text, action, false) }.bind(this),
            onSuccess: function(text) { this.xhrComplete(ajax, text, action, true)  }.bind(this) 
        }).request();
    },
    'initMatch': 
    function(m) {
      var index = m.id.substr('match.'.length);
      var l = $('list.' + index);
      var s = this.match[index] = 
        { match: m, list: l, 
          closed: m.hasClass('closed'),
          slide: new Fx.Slide
          (l, { duration: 250,
               onComplete: function() { 
               if ((s.closed = !s.closed)) m.addClass('closed');
               if (!s.closed) l.getParent().style.height = '';
             } } ) };
      if (index != 'additional') {
        $A(l.getElementsByClassName('credit')).each
          (function(cr) {
            this.toggleCredit(cr.id.substr('credit.'.length));
          }, this);
        var count = 0;
        $A(m.getElementsByClassName('check')).each
          (function(ch) {
            if (ch.checked) {
              m.removeClass('closed');
              s.closed = false;
              count++;
            }
          }, this);
        var countE = $('count.'+index);
        if (countE) {
          countE.setHTML(count);
          if (count) {
            // countE.getParent().removeClass('hide');
            if (index > 0) this.secondary = true;
          }
          else {
            countE.getParent().addClass('hide');
          }
        }
        if (s.closed) s.slide.hide();
      }
    },
    'credits':
    function() {
      this.url = 'credits';
      this.match = {};
      $A($('credits').getElementsByClassName('match')).each
        (function(m) { this.initMatch(m); }, this);
      var additional = this.match['additional'];
      if (additional && this.secondary) {
        additional.match.removeClass('closed');
        additional.closed = false;
      }
      else if (additional) {
        additional.slide.hide();
      }
    },
    'toggleMatch':
    function(index) {
      var m = this.match[index];
      m.match.removeClass('closed'); 
      if (m.closed) {
        m.slide.slideIn();
      }
      else {
        m.slide.slideOut();
      }
    },
    'toggleCredit': 
    function(id, set, value) {
      if (set) $('check.'+id).checked = value;
      var index = id.replace(/\..*/, '');
      var key = $('check.'+id).value;
      if ($('check.'+id).checked) {
        $('credit.'+id).addClass('selected');
        this.selectedCredits[key] = 1;
      }
      else {
        $('credit.'+id).removeClass('selected');
        this.selectedCredits[key] = 0;
      }
    },
    'creditAll':
    function(index, value) {
      $A(this.match[index].list.getElementsByClassName('credit')).each
        (function(e) {
          this.toggleCredit(e.id.substr('credit.'.length), true, value);
        }, this);
    },
    'removeSearch':
    function(search) {
      $('search.'+search).remove();
      $('count').addClass('hide');
    },
    'addSearch':
    function(search) {
      var search = [];
      $A($('credits').getElementsByClassName('search-name')).each
        (function(e) {
          search.push(e.getValue());
        });
      this.xhr({ 'search': search.join('|') }, 'search', 
               '/character/select-credits');
    },
    'searchComplete': 
    function(text) {
      var create = new Element('div').setHTML(text);
      var search = (create.getElementsByClassName('search'))[0];
      search.injectBefore('marker');
      $A(search.getElementsByClassName('match')).each
        (function(m) { this.initMatch(m) }, this);
      if (this.match['additional'] && 
          this.match['additional'].closed) this.toggleMatch('additional');
      $('count').addClass('hide');
    },
    'saveCredits': 
    function(button) {
      if (button) {
        $(button).disabled = true;
        $(button).addClass('disabled');
      }
      var search = [];
      $A($('credits').getElementsByClassName('search-name')).each
        (function(e) {
          search.push(e.getValue());
        });
      var credits = [];
      $A($('credits').getElementsByClassName('check')).each
        (function(e) {
          if (e.checked) credits.push(e.value);
        });
      this.xhr({ 'search': search.join('|'),
                'credits': credits.join('|') }, 'save');
    },
    'photos': 
    function(data, multi, url) {
      this.url = url;
      this.photos = data;
      this.multi = multi;
    },
    'togglePhoto': 
    function(img) {
      if (this.multi) {
        $(img).toggleClass('selected');
      }
      else {
        if (!$(img).hasClass('selected')) {
          $A($('photos').getElementsByClassName('selected')).each
            (function(e) {
              e.removeClass('selected');
            });
          $(img).addClass('selected');
        }
      }
    },
    'hoverPhoto': 
    function(img, over) {
      var id = img.id.substr('photo.'.length);
      var info = this.photos[id];
      if (over) {
        var win;
        if (window.innerWidth) win = window.innerWidth;
        else if (document.documentElement && 
                 document.documentElement.clientWidth) 
          win = document.documentElement.clientWidth;
        else if (document.body) win = document.body.clientWidth;
        var shim = $('shim.'+id);
        var diff = win - (shim.getParent().getPosition().x - info[2] + info[3]);
        shim.style.left = ((diff < 0) ? (diff - (info[2] + 22)) : -(info[2] + 10)) + 'px';
        var inner = $('inner.'+id);
        var slide = info[4];
        if (!slide) { 
          slide = info[4] = new Fx.Slide(inner, { duration: 250 });
          inner.getParent().style.width = (2 + parseInt(inner.style.width)) + 'px';
          slide.hide();
          shim.removeClass('hide');
        }
        $('image.'+id).src = info[1];
        if (info[5]) $clear(info[5]);
        info[5] = function() { slide.stop().slideIn() }.delay(1000);
      }
      else {
        if (info[5]) $clear(info[5]);
        if (info[4]) info[4].stop().slideOut();
      }
    },
    'savePhotos':
    function() {
      var photos = [];
      $A($('photos').getElementsByClassName('photo')).each
        (function(i) {
          if (i.hasClass('selected')) photos.push(this.photos[i.id.substr('image.'.length)][0]);
        }, this);
      this.xhr({ 'photos': photos.join('|') }, 'save');
    },
    'saveComplete': 
    function(text) {
      $('congrats').setHTML(text);
      $('congrats').scrollIntoView(true);
      document.body.style.marginBottom = '0px';
    },
    'addAka': 
    function() {
      var aka = $('aka-input').getValue().trim();
      if (!aka.length) return;
      var clone = $('aka-blank').clone();
      $('aka-list').adopt(clone);
      clone.id = 'aka-'+$('aka-list').getChildren().length;
      $A(clone.getElementsByClassName('aka'))[0].setText(aka);
      $('aka-input').value = '';
    },
    'removeAka': 
    function(element) {
      var walk = element;
      while (walk && walk.tagName != 'LI') {
        walk = walk.getParent();
      }
      if (!walk) return;
      walk.remove();
    },
    'saveAkas':
    function() {
      var akas = [];
      this.url = 'akas';
      $A($('akas').getElementsByClassName('aka')).each
        (function(i) { akas.push(i.getText()) });
      this.xhr({ 'akas': akas.join('|') }, 'save');
    }
});

function toggleHelp(id) {
  if (!document.getElementById) return;
  var e = document.getElementById('help-'+id);
  e.style.display = e.style.display.length ? '' : 'block';
}
