var sb_lock;
var didInitSideBars;

Event.observe(window, 'load', function() {
  $$('.sidebarimage a').each(function(el){
    el.observe('mouseover', sbMouseOver);
  });

  if($('sblogon')) {
    $('sblogon').observe('submit', logonFormQuickCheck);
    initSBFields();
  }

  $$('.fpsection').each(function(sec){
    var s = sec.getAttribute('id').replace('^section_', '');
    sec.select('a').each(function(anc) {
      anc.observe('mouseover', function(ev) { setOp(s, 1); })
         .observe('mouseout',  function(ev) { setOp(s, 0); });
    });
  });

  $$('.sclvm').invoke('observe', 'viewmore:show', readjustMain)
              .invoke('observe', 'viewmore:hide', readjustMain);

  // Match the length of the sidebars:
  setTimeout('balanceSidebars', 500);

  sb_lock = new Hash();
  initSideBars();
});

// {{{ balanceSidebars()
function balanceSidebars() {
  var mheight = 0;
  $R(1,3).each(function(r) {
    var h = $('fpc' + r);
    if(h) {
      var hx = $('fpc' + r).getHeight();
      $('fpc' + r).setStyle({height: 'auto'});
      h = $('fpc' + r).getHeight();
      if(h && h > mheight) {
        mheight = h;
      }
    }
  });

  $R(1,3).each(function(r) {
    var o = $('fpc' + r);
    if(o)
      o.setStyle({height: mheight + 'px'});
  });
}; // }}}

// {{{ sbMouseOver(ev)
function sbMouseOver(ev) {
  var img = Event.element(ev);
  if(img.nodeName === 'A')
    img = img.down('img');

  var imgsrc = img.getAttribute('src');
      // Browser may fully-qualify image URL:
      imgsrc = imgsrc.replace(/^https?:\/\/[^\/]+/, '');

  for(var i=0; i<imgdata.length; i+=2) {
    if(imgdata[i][0] === imgsrc && imgdata[i+1][0]) {
      new Tip(img, '<img src="'         + imgdata[i+1][0] + '" '
                 +    'width="'         + imgdata[i+1][1] + '" '
                 +   'height="'         + imgdata[i+1][2] + '"/>'
                 + '<h1 id="sidebarpopup-caption">'
                 +   Element.up(img, 'a').getAttribute('title').replace(/^View [^0-9]+/, '')
                 + '</h1>');
      break;
    }
  }

}; // }}}

// {{{ logonFormQuickCheck(ev)
function logonFormQuickCheck(ev) {
  var errors = new Array();
  var un = $('auth_user_name');
  if(un && un.value) {
    if(!un.value.match(/^[a-z0-9_A-Z]{1,20}$/))
      errors.push('An Invalid Username was entered.');
  } else {
    errors.push('No Username was entered.');
  }

  var pw = $('auth_password');
  if(!pw || !pw.value) {
    errors.push('No Password was entered.');
  }

  if(errors.length) {
    ev.stop();
    var txt = '';
    errors.each(function(e){ if(txt) txt += "\n"; txt += '* ' + e; });
    alert(txt);
  }
} // }}}

// {{{ initSBFields()
function initSBFields() {
 inputAsLabel('auth_user_name');
 inputAsLabel('auth_password');

 if(GetCookie('remember_login')) {
   if($('auth_user_name') && GetCookie('username'))
     $('auth_user_name').value = GetCookie('username');

   if($('auth_password') && GetCookie('password'))
     $('auth_password').value = GetCookie('password');

   if($('admin_button') && GetCookie('admin_button'))
     $('admin_button').checked = true;
 }
} // }}}

// {{{ setOp(which, opaque)
// TODO: Replace with :hover CSS selector?
function setOp(which, opaque){
  if(opaque) {
    $(which).addClassName('opacity2');
  } else {
    $(which).removeClassName('opacity2');
  }
} // }}}

// {{{ fixup_sidebars()
function fixup_sidebars(col_id){
  if(!col_id) return;

  var asortable = $(col_id);
  if(!asortable) return;

  if(typeof(Sortable) !== 'undefined') {
    Sortable.create(asortable, {
      tag:'div',
      only:'sidebaritem',
      constraint:'vertical',
      onChange: function(){ SBPos.save(); }
    });
  }

  asortable.select('.sidebaritem .boxbutton').each(function(minbutton) {
    minbutton.observe('click', opencloseSBW);
  });
} // }}}

// {{{ opencloseSBW(ev)
function opencloseSBW(ev) {
  ev.stop();
  var el = Event.element(ev);

  // Although the event is hooked on the A we the IMG overlays is so we
  // get the IMG instead, so pass up tree to parent (A element)
  if(el.tagName === 'IMG');
    el = el.up('A');

  var sb_box = el.up('.sidebaritem');
  var div_content = sb_box.select('.sidebarcontent')[0];
  var div_bottom  = sb_box.select('.sidebarbottom')[0];

  // Check if we're busy:
  if(sb_lock.get(el.id)) return;

  // {{{ If hidden, blinddown to display:
  if(div_content.getStyle('display') === 'none'){
    Effect.BlindDown(div_content, {
     afterUpdate: function() {
       if(balanceSidebars)
         balanceSidebars();
     },

     beforeStart: function() {
       sb_lock.set(el.id, 1);
     },

     afterFinish: function() {
       sb_lock.unset(el.id);
       var img = el.down('img');
       if(!img.src.match(/\/graphics\/minimize.gif/))
         img.src = '/graphics/minimize.gif';
       SBPos.save();
     }
    });

    Effect.BlindDown(div_bottom);
  } // }}}

  // {{{ Otherwise blindup to hide:
  else {
    Effect.BlindUp(div_bottom, {
     afterUpdate: function() {
       if(balanceSidebars)
         balanceSidebars();
     },

     beforeStart: function() {
       sb_lock.set(el.id, 1);
     }
    });

    Effect.BlindUp(div_content, {
     afterFinish: function() {
       sb_lock.unset(el.id);
       var img = el.down('img');
       if(!img.src.match(/\/graphics\/maximize.gif/))
         img.src = '/graphics/maximize.gif';
       SBPos.save();
     }
    });
  } // }}}

  return true;
} // }}}

// {{{ SBPos
var SBPos = {

  // {{{ save()
  save: function(){
    var pos= new Hash();
    var hidden= new Hash();

    [1, 3].each(function(col) {
      var i=1;
      $$('#fpc' + col +' .sidebaritem').each(function(el){
        pos.set(el.id, i++);
        var content = el.select('.sidebarcontent');
        if(content && content[0] && content[0].getStyle('display') === 'none')
          hidden.set(el.id, 1);
      });
    });

    // Only save if saving something :p
    if(pos.size()) {
      Cookie.set('position', Object.toJSON(pos));
    } else {
      Cookie.erase('position');
    }

    if(hidden.size()) {
      Cookie.set('hidden', Object.toJSON(hidden));
    } else {
      Cookie.erase('hidden');
    }
  }, // }}}

  // {{{ load()
  load: function(){
    var hpos = Cookie.get('position');
    var hhid = Cookie.get('hidden');

    SBPos.hpos = new Hash(hpos ? hpos.evalJSON() : {});
    SBPos.hhid = new Hash(hhid ? hhid.evalJSON() : {});

  }, // }}}

  // {{{ process()
  process: function() {
    [1, 3].each(function(col_id) {

      var arr = new Array(10);
      var col = $('fpc' + col_id);

      // Column may have been administratively hidden
      if(!col) return;

      col.select('.sidebaritem').each(function(el){
        var pos = SBPos.hpos.get(el.id);
        el = el.remove();
        if(pos)
          arr[pos] = el;
        else
          arr.push(el);
      });

      arr.each(function(el) {
        if(el){

          var ishidden = SBPos.hhid.get(el.id);
          var cont = el.select('.sidebarcontent')[0];
          var bot  = el.select('.sidebarbottom')[0];
          var boxbut = el.select('.boxbutton img');
          if(boxbut && boxbut.length) boxbut = boxbut[0];

          if(ishidden) {
            if(bot)   bot.hide();
            if(cont) cont.hide();
            if(boxbut && !boxbut.src.match(/\/maximize.gif/))
              boxbut.src = '/graphics/minimize.gif';
          } else {
            if(bot)   bot.show();
            if(cont) cont.show();
            if(!boxbut) alert(el.id);
            if(boxbut && !boxbut.src.match(/\/minimize.gif/))
              boxbut.src = '/graphics/maximize.gif';
          };

          col.appendChild(el);
        }
      });
    });

  } // }}}

}; // }}}

// {{{ initSideBars()
function initSideBars(){
  if(didInitSideBars) return;
    didInitSideBars = 1;

  if(!$('fpbody')) return;
  fixup_sidebars('fpc1');
  fixup_sidebars('fpc3');
  SBPos.load();
  SBPos.process();
  if(balanceSidebars)
    balanceSidebars();
} // }}}

/* readjustMain(ev) */
function readjustMain(ev) {
  var el = $('fpc2');
  el.setStyle({ height: 'auto' });
  var nHeight = parseInt(el.getHeight());
  el.setStyle({ height: nHeight + 'px'});
  balanceSidebars();
} /* }}} */

balanceSidebars();

