
  // class.bgallery.js
  // Copyright (c) 2005,2006 Kevin Kaiser / Data Resolutions

  try {

    if (typeof(Basis) == 'undefined') {

      throw "";

    } // end if

  } catch (e) {

    throw "Basis.bgallery depends on Basis!";

  } // end try
  
  if (typeof(Basis.bgallery) == 'undefined') {

    Basis.bgallery = {};

  } // end if
  
  Basis.bgallery.NAME    = 'Basis.bgallery';
  Basis.bgallery.VERSION = '0.1';
  
  Basis.bgallery.__repr__ = function () {

    return '[' + this.NAME + ' ' + this.VERSION + ']';

  }; // end __repr__()
  
  Basis.bgallery.toString = function () {

    return this.__repr__();

  }; // end toString()

  Basis.bgallery.gallery = function () {

    this.__init__();

  }; // end gallery()

  Basis.bgallery.gallery.prototype = {
  
    __init__: function () {

      this.gallery_element         = 'gallery_images';
      this.preview_element         = 'preview_pane';
      this.preview_handle_element  = 'preview_handle';

      this.slideshow               = {};

      this.gallery_images          = new Object();
      this.image_ids               = new Object();

      this.num_images              = 0;

      this.current_preview         = '';
      this.inext                   = '';
      this.iprev                   = '';
      this.variable_name           = '';
      this.sid                     = '';
      this.default_comment         = 'Click to Add Comment';
      this.root_path               = '';

      document.twg_upload_completed = function () {
  
        var obj = MochiKit.DOM.getElement("uploader_container");

        if (obj) {

          MochiKit.DOM.removeElement(obj);

        } // end if

        Basis.misc_vars.build_gallery_popup = Basis.popup({"id"           : "build_gallery_popup",
                                                           "window_title" : "Resizing Images",
                                                           "html"         : '<div>Please wait while we process and resize any newly uploaded images.</div>\
                                                                             <div style="text-align: center; padding: 10px;"><img src="images/ajax_loading.gif"></div>'
                                                          });

        var as   = new Basis.ajax_scaffold;
        as.alias = "twg_upload_completed";
        as.sid   = "null";
        as.url   = (window.location+"");

        if (as.url.indexOf("?") == -1) {

          as.url = as.url+"?ajax_load=true";

        } else {

          as.url = as.url+"&ajax_load=true";

        } // end if

        as.pvar  = this;

        as.on_success = function (req) {

          var response = req.responseText;

          if (response == "true") {

            var obj = MochiKit.DOM.getElement("build_gallery_popup");
    
            if (obj) {
    
              MochiKit.DOM.removeElement(obj);
    
            } // end if

            Basis.misc_vars.build_gallery_popup = Basis.popup({"id"           : "build_gallery_popup",
                                                               "window_title" : "Resizing Images",
                                                               "html"         : "<div>Resizing completed! Reloading page in 3 seconds...</div>"
                                                              });

            MochiKit.Async.callLater("3",function () {

              window.location = (window.location+"");

            });

          } // end if

        };

        as.post();

/*
        Basis.confirm({"window_title"       : "Confirm",
                       "variable_title"     : "Would you like to upload more files?",
                       "button_ok_text"     : "Yes",
                       "button_cancel_text" : "No",
                       "on_false"           : MochiKit.Base.bind(function () {

                                                var obj = MochiKit.DOM.getElement("uploader_container");
                                        
                                                if (obj) {
                                        
                                                  MochiKit.DOM.removeElement(obj);
                                      
                                                  window.location.reload(false);
                                        
                                                } // end if

                                              },this)
                     });
*/
  
      }; // end twg_upload_completed()

    }, // end __init__()

    archive_selected_images: function() {

      var folder_name = prompt('Name of Archive:');

      if (folder_name) {

        var ul          = MochiKit.DOM.getElement(this.gallery_element);
        var to_archive  = new Array();
        var to_send     = new Object();
  
        window.status   = "Archiving selected images...";
  
        if (!ul.childNodes || ul.childNodes.length==0) { return false; } // end if
    
        for (var itemi=0; itemi<ul.childNodes.length; itemi++) {
    
          var item = ul.childNodes[itemi];
    
          if (item.nodeName == "LI") {
  
            if (MochiKit.DOM.getElement(item.id+'_selected').checked) { 
  
              var hash                      = MochiKit.DOM.getElement(item.id+'_selected').value;
              to_archive[to_archive.length] = hash;
  
            } // end if
  
          } // end if
    
        } // end for

        if (to_archive.length>0) {

          to_send["folder_name"] = folder_name;
          to_send["files"]       = to_archive;
  
          AjaxRequest.post({
    
            'url'         : 'ajax/gallery_archive_selected_images.php?PHPSESSID='+this.sid,
            'queryString' : 'array='+urlencode(encodeBase64(MochiKit.Base.serializeJSON(to_send))),
            'onSuccess'   : function(req) {
    
                              window.status   = "Done";
                              window.location = window.location;
    
                            }
          });           
  
        } else {
  
          window.status = "Done";
  
        } // end if

      } // end if

    }, // end archive_selected_images()

    delete_selected_images: function() {

      var ul        = MochiKit.DOM.getElement(this.gallery_element);
      var to_delete = new Array();

      window.status = "Deleting selected images...";

      if (!ul.childNodes || ul.childNodes.length==0) { return false; } // end if
  
      for (var itemi=0; itemi<ul.childNodes.length; itemi++) {
  
        var item = ul.childNodes[itemi];
  
        if (item.nodeName == "LI") {

          if (MochiKit.DOM.getElement(item.id+'_selected').checked) { 

            var hash                    = MochiKit.DOM.getElement(item.id+'_selected').value;
            to_delete[to_delete.length] = hash;

          } // end if

        } // end if
  
      } // end for

      if (to_delete.length>0) {

        AjaxRequest.post({
  
          'url'         : 'ajax/gallery_delete_selected_images.php?PHPSESSID='+this.sid,
          'queryString' : 'array='+urlencode(encodeBase64(MochiKit.Base.serializeJSON(to_delete))),
          'onSuccess'   : function(req) {
  
                            window.status   = "Done";
                            window.location = window.location;
  
                          }
        });           

      } else {

        window.status = "Done";

      } // end if

    }, // end delete_selected_images()

    gallery_order: function () {

      var temp = new Object();
      var ul   = MochiKit.DOM.getElement(this.gallery_element);
      var x    = 0;
  
      if (!ul.childNodes || ul.childNodes.length==0) { return false; } // end if
  
      for (var itemi=0; itemi<ul.childNodes.length; itemi++) {
  
        var item = ul.childNodes[itemi];
  
        if (item.nodeName == "LI") {

          var hash   = item.id.substr(5);
          temp[hash] = item.value;
          x++;

        } // end if
  
      } // end for
 
      this.num_images = x;

      return temp;

    }, // end gallery_order()

    gallery_update_order: function () {

      to_send = new Object();
      x       = 0;

      for (var hash in this.gallery_images) {

        to_send[this.image_ids[hash]]  = x;
        this.gallery_images[hash]      = x;
        x++;

      } // end for

      this.num_images = x;

      return {'to_send':to_send};

    }, // end gallery_update_order()

    nav_buttons: function (url_md5) {

      var iprev   = '';
      var inext   = '';
      var rank    = eval(this.gallery_images[url_md5]);
      var gl_flip = Basis.array_flip(this.gallery_images);

      if (rank > 0)                         { iprev = gl_flip[rank-1]; } // end if
      if (rank < Basis.array_size(gl_flip)) { inext = gl_flip[rank+1]; } // end if

      return {'iprev':iprev, 'inext':inext};

    }, // end nav_buttons()

    ondrop: function (element,dropElt) {

      var gallery_object = eval(this.gallery);

      if (element.className=='celldiv') {

        var source       = { 'obj'       : MochiKit.DOM.getElement(element.id),
                             'innerHTML' : MochiKit.DOM.getElement(element.id).innerHTML,
                             'id'        : element.id,
                             'name'      : element.name,
                             'value'     : element.value
                           };

        var dest         = { 'obj'       : MochiKit.DOM.getElement(dropElt.id),
                             'innerHTML' : MochiKit.DOM.getElement(dropElt.id).innerHTML,
                             'id'        : dropElt.id,
                             'name'      : dropElt.name,
                             'value'     : dropElt.value
                           };

        var temp                      = new Object;
        temp.innerHTML                = source.innerHTML;
        temp.id                       = source.id;
        temp.name                     = source.name;
        temp.value                    = source.value;

        var schecked = false;
        var dchecked = false;

        if (MochiKit.DOM.getElement(source.id+'_selected').checked) { schecked = true; } // end if
        if (MochiKit.DOM.getElement(dest.id+'_selected').checked)   { dchecked = true; } // end if

        source.obj.innerHTML          = dest.innerHTML;
        source.obj.id                 = dest.id;
        source.obj.name               = dest.name;
        if (source.obj.value && dest.value) {
          source.obj.value              = dest.value;
        } // end if

        dest.obj.innerHTML            = temp.innerHTML;
        dest.obj.id                   = temp.id;
        dest.obj.name                 = temp.name;
        if (dest.obj.value && temp.value) {
          dest.obj.value              = temp.value;
        } // end if

        if (schecked) { 

          MochiKit.DOM.getElement(source.id+'_selected').checked = true;

        } // end if

        if (dchecked) { 

          MochiKit.DOM.getElement(dest.id+'_selected').checked = true;

        } // end if

        MochiKit.DOM.getElement(dest.id+'_selected').onchange();
        MochiKit.DOM.getElement(source.id+'_selected').onchange();

        gallery_object.gallery_images = gallery_object.gallery_order();

        var to_send                   = gallery_object.gallery_update_order();
        to_send                       = to_send.to_send;

        window.status = "Auto-saving gallery rankings...";
    
        AjaxRequest.gallery = this.gallery;

        AjaxRequest.post({

          'url'         : 'ajax/gallery_save_image_rankings.php?PHPSESSID='+gallery_object.sid,
          'queryString' : 'array='+urlencode(encodeBase64(MochiKit.Base.serializeJSON(to_send))),
          'onSuccess'   : function(req) { 

                            gallery_object = eval(AjaxRequest.gallery);
              
                            if (MochiKit.DOM.getElement(gallery_object.preview_element).style.display == '') {
              
                              gallery_object.gallery_update_order();
              
                              var ibuttons = gallery_object.nav_buttons(gallery_object.current_preview);
                              var iprev    = ibuttons.iprev;
                              var inext    = ibuttons.inext;
              
                              if (iprev) { 
              
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_prev_button').onclick = function () { MochiKit.DOM.getElement('cell_'+iprev+'_img').onclick(); }; 
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_prev_button').value        = 'Back';
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_prev_button').style.border = '';
              
                              } else {
              
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_prev_button').value        = ' ';
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_prev_button').style.border = '0px';
              
                              } // end if
              
                              if (inext) { 
              
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_next_button').onclick = function () { MochiKit.DOM.getElement('cell_'+inext+'_img').onclick(); };
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_next_button').value        = 'Next';
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_next_button').style.border = '';
              
                              } else {
              
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_next_button').value        = ' ';
                                MochiKit.DOM.getElement('cell_'+gallery_object.current_preview+'_next_button').style.border = '0px';
              
                              } // end if
              
                            } // end if    

                            window.status = "Done";

                          }
        });        

      } // end if
    
    }, // end ondrop()

    position_preview: function() {

      var screend  = MochiKit.Style.getViewportDimensions();
      var previewd = MochiKit.Style.getElementDimensions(this.preview_element);
    
      var to_pos   = new Object;
      to_pos.x     = ((screend.w / 2)-(previewd.w / 2));
      to_pos.y     = ((screend.h / 2)-(previewd.h / 2));

      var scroll;            
      scroll       = Basis.scroll_coords();

      to_pos.x    += scroll.x;
      to_pos.y    += scroll.y;

      if (this.slideshow.control_element && MochiKit.DOM.getElement(this.slideshow.control_element)) {

        controlsd = MochiKit.Style.getElementDimensions(this.slideshow.control_element);
  
        to_pos.y   -= ((controlsd.h / 2) + (this.slideshow.control_padding / 2));
  
        if (to_pos.y < this.slideshow.control_padding) { to_pos.y = this.slideshow.control_padding; } // end if

      } // end if

      if (to_pos.y < 0) { to_pos.y = 0; } // end if

      MochiKit.Style.setElementPosition(this.preview_element, to_pos);

    }, // end position_preview()

    preview_image: function (url,url_md5,finfo,fdims) {

      var title       = 'Image Preview';
      var link_url    = url;
      var display_url = url;

      if (url.substr((url.length-7)) == '.medium') { 

        display_url = display_url.substr(0,(display_url.length-7));
        link_url    = display_url;
        finfo      += '<p><i>Click image below to enlarge</i></p>';

      } // end if

      var ibuttons    = this.nav_buttons(url_md5);
      var iprev       = ibuttons.iprev;
      var inext       = ibuttons.inext;

      if (!this.slideshow.slideshow_on && !this.slideshow.slideshow_paused) {

        var preview_html = ' \
\
<div class="win32_container_outer"> \
<div class="win32_container_inner"> \
\
  <div class="win32_window_header" id="preview_handle" style="cursor: pointer;"> \
    <span class="win32_window_text_header">'+title+'</span> \
  </div> \
\
  <div class="win32_white_block" style=""> \
    <span class="win32_text_header">'+display_url+'</span> \
    <div class="win32_text_block">'+finfo+'</div> \
  </div> \
\
  <div class="win32_hr"><span style="display:none;">hr</span></div> \
\
  <div class="win32_block"> \
    <div class="win32_text_block"> \
\
      <a href="'+link_url+'" target="_blank"><img border="0" width="'+fdims.w+'" height="'+fdims.h+'" style="border: 1px solid #404040;" src="'+url+'"></a> \
\
    </div> \
  </div> \
\
  <div style="padding: 0px; padding-left: 15px; padding-right: 15px;"> \
    <div class="win32_hr"><span style="display:none;">hr</span></div> \
  </div> \
\
  <div class="win32_block" style="text-align: right;"> \
';

      if (iprev) { preview_html += '        <input id="cell_'+url_md5+'_prev_button" type="button" class="win32_button" style="margin-right: 0px;" value="Back" onClick="MochiKit.DOM.getElement(\'cell_'+iprev+'_img\').onclick();"> '; }
            else { preview_html += '        <input id="cell_'+url_md5+'_prev_button" type="button" class="win32_button" style="border: 0px;" value=" ">'; } // end if
      if (inext) { preview_html += '        <input id="cell_'+url_md5+'_next_button" type="button" class="win32_button" value="Next" onClick="MochiKit.DOM.getElement(\'cell_'+inext+'_img\').onclick();"> ';                    } 
            else { preview_html += '        <input id="cell_'+url_md5+'_next_button" type="button" class="win32_button" style="border: 0px;" value=" ">'; } // end if

      preview_html     += ' \
    <input type="button" class="win32_button" value="Cancel" onClick="toggle_object(\''+this.preview_element+'\')"> \
  </div> \
\
\
</div>   \
</div> \
';

      } else {


        preview_html  = '';
        preview_html += '<img border="0" width="'+fdims.w+'" height="'+fdims.h+'" style="border: 1px solid #404040;" src="'+url+'">';

      } // end if

      MochiKit.DOM.getElement(this.preview_element).style.display = 'none';
      MochiKit.DOM.getElement(this.preview_element).innerHTML     = preview_html;

      if ((MochiKit.DOM.getElement(this.preview_element).style.display == 'none') || (this.slideshow.slideshow_on) || (!this.slideshow.slideshow_on && this.slideshow.slideshow_paused)) {

        this.position_preview();

      } // end if

      if (this.current_preview != url_md5) { 

        MochiKit.DOM.getElement(this.preview_element).style.display = '';

      } else {

        toggle_object(this.preview_element);

      } // end if

      this.current_preview = url_md5;

      if (!this.slideshow.slideshow_on) {

        new MochiKit.DragAndDrop.Draggable(this.preview_element, {

          'revert'       : false,
          'ghosting'     : false,
          'handle'       : this.preview_handle_element,
          'starteffect'  : null,
          'reverteffect' : null,
          'endeffect'    : null

        });

      } // end if

    }, // end preview_image()

    rotate_selected_images: function (angle) {

      var ul           = MochiKit.DOM.getElement(this.gallery_element);
      var to_rotate    = new Array();

      window.status = "Rotating selected images...";

      if (!ul.childNodes || ul.childNodes.length==0) { return false; } // end if
  
      for (var itemi=0; itemi<ul.childNodes.length; itemi++) {
  
        var item = ul.childNodes[itemi];
  
        if (item.nodeName == "LI") {

          if (MochiKit.DOM.getElement(item.id+'_selected').checked) { 

            var hash                    = MochiKit.DOM.getElement(item.id+'_selected').value;
            to_rotate[to_rotate.length] = {"hash":hash,"angle":angle};

          } // end if

        } // end if
  
      } // end for

      if (to_rotate.length>0) {

        AjaxRequest.post({
  
          'url'         : 'ajax/gallery_rotate_selected_images.php?PHPSESSID='+this.sid,
          'queryString' : 'array='+urlencode(encodeBase64(MochiKit.Base.serializeJSON(to_rotate))),
          'onSuccess'   : function(req) {
  
                            window.status = "Done";
                            window.location.reload();
  
                          }
        });

      } else {

        window.status = "Done";

      } // end if

    }, // end rotate_selected_images()

    set_image_comment: function (comment_element,hash) {

      comment_element    = MochiKit.DOM.getElement(comment_element);
      var md5            = comment_element.id.substring(5,37);

      if (comment_element) {

        window.status = "Saving image comment...";

        var to_post = {"hash":hash,
                       "comment":comment_element.value};

        AjaxRequest.gallery = this;

        AjaxRequest.post({

          'url'         : 'ajax/gallery_save_image_comment.php?PHPSESSID='+this.sid,
          'queryString' : 'array='+urlencode(encodeBase64(MochiKit.Base.serializeJSON(to_post))),
          'onSuccess'   : function(req) {

                            if (comment_element.value) {

                              MochiKit.DOM.getElement('cell_'+md5+'_comment_static_div').innerHTML = comment_element.value;

                            } else {

                              MochiKit.DOM.getElement('cell_'+md5+'_comment_static_div').innerHTML = AjaxRequest.gallery.default_comment;

                            } // end if

                            AjaxRequest.gallery.toggle_edit_comment(comment_element);

                            window.status = "Done";

                          }
        });                

      } // end if

    }, // end set_image_comment()

    toggle_edit_comment: function (comment_element) {

      comment_element = MochiKit.DOM.getElement(comment_element);

      if (comment_element) {

        var md5            = comment_element.id.substring(5,37);
        var edit_div       = MochiKit.DOM.getElement('cell_'+md5+'_comment_edit_div');
        var edit_div_input = MochiKit.DOM.getElement('cell_'+md5+'_comment');
        var static_div     = MochiKit.DOM.getElement('cell_'+md5+'_comment_static_div');

        if (edit_div && static_div && edit_div_input) {

          if (edit_div.style.display == '') {

            edit_div.style.display   = 'none';
            static_div.style.display = '';

            edit_div_input.blur();

          } else {

            edit_div.style.display   = '';
            static_div.style.display = 'none';

            edit_div_input.focus();

          } // end if

        } // end if

      } // end if

    }, // end toggle_edit_comment()

    toggle_uploader: function () {

      var obj = MochiKit.DOM.getElement("uploader_container");

      if (!obj) {

        var uploader = new MochiKit.DOM.DIV({"id":"uploader_container","style":"display:none; width:650px; height:340px; position: absolute;"}," ");

        document.body.appendChild(uploader);

        var obj      = MochiKit.DOM.getElement("uploader_container");

        var screend  = MochiKit.Style.getViewportDimensions();
        var previewd = MochiKit.Style.getElementDimensions(obj);

        var to_pos   = new Object;
        to_pos.x     = ((screend.w / 2)-(previewd.w / 2));
        to_pos.y     = ((screend.h / 2)-(previewd.h / 2));

        var scroll;
        scroll       = Basis.scroll_coords();

        to_pos.x    += scroll.x;
        to_pos.y    += scroll.y;

        if (to_pos.y < 0) { to_pos.y = 0; } // end if

        MochiKit.Style.setElementPosition(obj, to_pos);

        obj.style.display = "inline";

        var so = new SWFObject("twg_flash_uploader2.swf", "mymovie", "650", "340", "8", "#ffffff");
        so.addVariable("basis_root",escape(decodeBase64(this.root_path)));
        so.addVariable("PHPSESSID",this.sid);
        so.write("uploader_container");

      } else {

        MochiKit.DOM.removeElement("uploader_container");

      } // end if

    } // end toggle_uploader()

  }; // end class Basis.bgallery.gallery

  Basis.bgallery.slideshow = function () {

    this.__init__();

  }; // end slideshow()
  
  Basis.bgallery.slideshow.prototype = {
  
    __init__: function () {

      this.background_element         = 'slideshow';
      this.control_element            = 'slideshow_controls';
      this.table_element              = 'slideshow_controls_table';
      this.variable_name              = '';
      this.gallery                    = {};
      this.slideshow_on               = false;
      this.slideshow_paused           = false;
      this.slideshow_controls_visible = false;
      this.curr_slide                 = 0;
      this.control_padding            = 20;
      this.timeout                    = false;
      this.speed_val                  = 3000;
      this.speed_text                 = '';

    }, // end __init__()
  
    cancel: function () {
  
      if (this.slideshow_paused) {

        this.toggle_pause('off');

      } // end if

      clearTimeout(this.timeout);

      this.slideshow_on            = false;
      document.body.style.overflow = '';
  
      toggle_object(this.background_element,'off');
      toggle_object(this.control_element,'off');
      toggle_object(eval(this.gallery).preview_element,'off');
  
    }, // end cancel()

    compile: function (x) {

      eval(this.gallery).slideshow = this;
      this.slideshow_on            = true;

      this.speed(this.speed_val);

      if (MochiKit.DOM.getElement(this.background_element).style.display == 'none') {

        document.body.style.overflow = 'hidden';
  
        screend   = MochiKit.Style.getViewportDimensions();
      
        to_pos    = new Object;
        to_pos.x  = 0;
        to_pos.y  = 0;
  
        var scroll;
        scroll    = Basis.scroll_coords();
  
        to_pos.x += scroll.x;
        to_pos.y += scroll.y;
  
        MochiKit.DOM.getElement(this.background_element).style.width  = screend.w;
        MochiKit.DOM.getElement(this.background_element).style.height = screend.h;
        MochiKit.Style.setElementPosition(this.background_element, to_pos);
  
        toggle_object(this.background_element,'on');
  
        this.gl_flip    = Basis.array_flip(eval(this.gallery).gallery_images);
        this.curr_slide = 0;

        if (x) {

          this.curr_slide = x;

        } // end if

        toggle_object(eval(this.gallery).preview_element,'on');
        this.show_slide();
  
      } // end if
  
    }, // end compile()

    on_resize: function() {

      this.size_background_and_controls();
      eval(this.gallery).position_preview();

    }, // end on_resize()
  
    show_slide: function (x) {
  
      if ((this.slideshow_on && !this.slideshow_paused)||(!this.slideshow_on && this.slideshow_paused)) {
  
        if (x || (x==0)) { 

          this.curr_slide = x;

          if (this.curr_slide>=eval(eval(this.gallery).num_images)) { this.curr_slide = 0;                               } // end if
          if (this.curr_slide<0)                                    { this.curr_slide = eval(this.gallery).num_images-1; } // end if

          clearTimeout(this.timeout);

        } // end if

        if (this.curr_slide>=eval(eval(this.gallery).num_images)) { this.curr_slide = 0;                               } // end if
        if (this.curr_slide<0)                                    { this.curr_slide = eval(this.gallery).num_images-1; } // end if

        var comment         = MochiKit.DOM.getElement('cell_'+this.gl_flip[this.curr_slide]+'_comment_static_div').innerHTML;
        var comment_element = MochiKit.DOM.getElement('slideshow_controls_comment');

        if (comment && (comment != eval(this.gallery).default_comment)) {

          comment_element.innerHTML        = '<b>'+comment+'</b>';
          comment_element.style.padding    = '10px';
          comment_element.style.paddingTop = '0px';
          comment_element.style.color      = '#ffffff';

        } else {

          comment_element.innerHTML        = '';
          comment_element.style.padding    = '0px';

        } // end if

        this.size_background_and_controls();
  
        if (this.slideshow_on && !this.slideshow_paused) {

          MochiKit.DOM.getElement('cell_'+this.gl_flip[this.curr_slide]+'_img').onclick();
          this.curr_slide++;
          this.timeout = setTimeout(this.variable_name+'.show_slide();',this.speed_val);

        } else {

          MochiKit.DOM.getElement('cell_'+this.gl_flip[this.curr_slide]+'_img').onclick();

        } // end if
  
      } // end if
  
    }, // end show_slide()

    size_background_and_controls: function () {

      if ((this.slideshow_on && !this.slideshow_paused)||(!this.slideshow_on && this.slideshow_paused)) {

        screend   = MochiKit.Style.getViewportDimensions();
        controlsd = MochiKit.Style.getElementDimensions(this.control_element);
  
        to_pos    = new Object;
        to_pos.x  = 0;
        to_pos.y  = 0;
  
        var scroll;
        scroll    = Basis.scroll_coords();
  
        to_pos.x += scroll.x;
        to_pos.y += scroll.y;
  
        MochiKit.DOM.getElement(this.background_element).style.width  = screend.w;
        MochiKit.DOM.getElement(this.background_element).style.height = screend.h;
  
        MochiKit.Style.setElementPosition(this.background_element, to_pos);
  
        to_pos      = new Object;
        to_pos.x    = (this.control_padding);
        to_pos.y    = ((screend.h)-(controlsd.h)-(this.control_padding));
  
        MochiKit.DOM.getElement(this.control_element).style.display = '';
        MochiKit.DOM.getElement(this.control_element).style.width   = screend.w-(this.control_padding*2);
  
        scroll    = Basis.scroll_coords();
  
        to_pos.x += scroll.x;
        to_pos.y += scroll.y;
  
        MochiKit.Style.setElementPosition(this.control_element, to_pos);

      } // end if

    }, // end size_background_and_controls()

    speed: function (speed) {

      if (speed=='slower') {

        this.speed_val += 1000;

      } else if (speed=='faster') {

        this.speed_val -= 1000;

      } // end if

      if (this.speed_val < 1000) { this.speed_val = 1000; } // end if

      this.speed_text = (this.speed_val/1000)+" second";

      if (this.speed_val > 1000) { this.speed_text += "s"; } // end if

      MochiKit.DOM.getElement('slideshow_controls_speed_text').innerHTML = this.speed_text;

    }, // end speed()
  
    toggle_controls: function () {
  
      if (this.slideshow_controls_visible==false) {
  
        this.slideshow_controls_visible = 'in process';
  
        MochiKit.Visual.appear(this.table_element, {
  
          afterFinish: function () {
  
            this.slideshow_controls_visible = true;
  
          }
  
        });
  
      } else if (this.slideshow_controls_visible==true) {
  
        this.slideshow_controls_visible = 'in process';
  
        MochiKit.Visual.fade(this.table_element, {'to': 0.01,
  
          afterFinish: function () {
  
            this.slideshow_controls_visible = false;
  
          }
  
        });
  
      } // end if
  
    }, // end toggle_controls()

    toggle_pause: function (specific) {
  
      if (this.slideshow_on || (specific=='on')) {
  
        this.slideshow_on     = false;
        this.slideshow_paused = true;
        MochiKit.DOM.getElement(this.control_element+'_pause').value   = 'Unpause';
        MochiKit.DOM.getElement(this.control_element+'_back').disabled = false;
        MochiKit.DOM.getElement(this.control_element+'_next').disabled = false;

        this.curr_slide--;
        clearTimeout(this.timeout);
  
      } else if (!this.slideshow_on || (specific=='off')){
  
        this.slideshow_on     = true;
        this.slideshow_paused = false;
        MochiKit.DOM.getElement(this.control_element+'_pause').value   = 'Pause';
        MochiKit.DOM.getElement(this.control_element+'_back').disabled = true;
        MochiKit.DOM.getElement(this.control_element+'_next').disabled = true;

        this.curr_slide++;
        this.show_slide(this.curr_slide);
  
      } // end if
  
    } // end toggle_pause()
  
  } // end class Basis.bgallery.slideshow

/***

MochiKit.Iter 1.4

See <http://mochikit.com/> for documentation, downloads, license, etc.

(c) 2005 Bob Ippolito.  All rights Reserved.

***/

if (typeof(dojo) != 'undefined') {
    dojo.provide('MochiKit.Iter');
    dojo.require('MochiKit.Base');
}

if (typeof(JSAN) != 'undefined') {
    JSAN.use("MochiKit.Base", []);
}

try {
    if (typeof(MochiKit.Base) == 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Iter depends on MochiKit.Base!";
}

if (typeof(MochiKit.Iter) == 'undefined') {
    MochiKit.Iter = {};
}

MochiKit.Iter.NAME = "MochiKit.Iter";
MochiKit.Iter.VERSION = "1.4";
MochiKit.Base.update(MochiKit.Iter, {
    __repr__: function () {
        return "[" + this.NAME + " " + this.VERSION + "]";
    },
    toString: function () {
        return this.__repr__();
    },

    /** @id MochiKit.Iter.registerIteratorFactory  */
    registerIteratorFactory: function (name, check, iterfactory, /* optional */ override) {
        MochiKit.Iter.iteratorRegistry.register(name, check, iterfactory, override);
    },

    /** @id MochiKit.Iter.iter */
    iter: function (iterable, /* optional */ sentinel) {
        var self = MochiKit.Iter;
        if (arguments.length == 2) {
            return self.takewhile(
                function (a) { return a != sentinel; },
                iterable
            );
        }
        if (typeof(iterable.next) == 'function') {
            return iterable;
        } else if (typeof(iterable.iter) == 'function') {
            return iterable.iter();
        /*
        }  else if (typeof(iterable.__iterator__) == 'function') {
            //
            // XXX: We can't support JavaScript 1.7 __iterator__ directly
            //      because of Object.prototype.__iterator__
            //
            return iterable.__iterator__();
        */
        }

        try {
            return self.iteratorRegistry.match(iterable);
        } catch (e) {
            var m = MochiKit.Base;
            if (e == m.NotFound) {
                e = new TypeError(typeof(iterable) + ": " + m.repr(iterable) + " is not iterable");
            }
            throw e;
        }
    },

    /** @id MochiKit.Iter.count */
    count: function (n) {
        if (!n) {
            n = 0;
        }
        var m = MochiKit.Base;
        return {
            repr: function () { return "count(" + n + ")"; },
            toString: m.forwardCall("repr"),
            next: m.counter(n)
        };
    },

    /** @id MochiKit.Iter.cycle */
    cycle: function (p) {
        var self = MochiKit.Iter;
        var m = MochiKit.Base;
        var lst = [];
        var iterator = self.iter(p);
        return {
            repr: function () { return "cycle(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                try {
                    var rval = iterator.next();
                    lst.push(rval);
                    return rval;
                } catch (e) {
                    if (e != self.StopIteration) {
                        throw e;
                    }
                    if (lst.length === 0) {
                        this.next = function () {
                            throw self.StopIteration;
                        };
                    } else {
                        var i = -1;
                        this.next = function () {
                            i = (i + 1) % lst.length;
                            return lst[i];
                        };
                    }
                    return this.next();
                }
            }
        };
    },

    /** @id MochiKit.Iter.repeat */
    repeat: function (elem, /* optional */n) {
        var m = MochiKit.Base;
        if (typeof(n) == 'undefined') {
            return {
                repr: function () {
                    return "repeat(" + m.repr(elem) + ")";
                },
                toString: m.forwardCall("repr"),
                next: function () {
                    return elem;
                }
            };
        }
        return {
            repr: function () {
                return "repeat(" + m.repr(elem) + ", " + n + ")";
            },
            toString: m.forwardCall("repr"),
            next: function () {
                if (n <= 0) {
                    throw MochiKit.Iter.StopIteration;
                }
                n -= 1;
                return elem;
            }
        };
    },

    /** @id MochiKit.Iter.next */
    next: function (iterator) {
        return iterator.next();
    },

    /** @id MochiKit.Iter.izip */
    izip: function (p, q/*, ...*/) {
        var m = MochiKit.Base;
        var self = MochiKit.Iter;
        var next = self.next;
        var iterables = m.map(self.iter, arguments);
        return {
            repr: function () { return "izip(...)"; },
            toString: m.forwardCall("repr"),
            next: function () { return m.map(next, iterables); }
        };
    },

    /** @id MochiKit.Iter.ifilter */
    ifilter: function (pred, seq) {
        var m = MochiKit.Base;
        seq = MochiKit.Iter.iter(seq);
        if (pred === null) {
            pred = m.operator.truth;
        }
        return {
            repr: function () { return "ifilter(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                while (true) {
                    var rval = seq.next();
                    if (pred(rval)) {
                        return rval;
                    }
                }
                // mozilla warnings aren't too bright
                return undefined;
            }
        };
    },

    /** @id MochiKit.Iter.ifilterfalse */
    ifilterfalse: function (pred, seq) {
        var m = MochiKit.Base;
        seq = MochiKit.Iter.iter(seq);
        if (pred === null) {
            pred = m.operator.truth;
        }
        return {
            repr: function () { return "ifilterfalse(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                while (true) {
                    var rval = seq.next();
                    if (!pred(rval)) {
                        return rval;
                    }
                }
                // mozilla warnings aren't too bright
                return undefined;
            }
        };
    },

    /** @id MochiKit.Iter.islice */
    islice: function (seq/*, [start,] stop[, step] */) {
        var self = MochiKit.Iter;
        var m = MochiKit.Base;
        seq = self.iter(seq);
        var start = 0;
        var stop = 0;
        var step = 1;
        var i = -1;
        if (arguments.length == 2) {
            stop = arguments[1];
        } else if (arguments.length == 3) {
            start = arguments[1];
            stop = arguments[2];
        } else {
            start = arguments[1];
            stop = arguments[2];
            step = arguments[3];
        }
        return {
            repr: function () {
                return "islice(" + ["...", start, stop, step].join(", ") + ")";
            },
            toString: m.forwardCall("repr"),
            next: function () {
                var rval;
                while (i < start) {
                    rval = seq.next();
                    i++;
                }
                if (start >= stop) {
                    throw self.StopIteration;
                }
                start += step;
                return rval;
            }
        };
    },

    /** @id MochiKit.Iter.imap */
    imap: function (fun, p, q/*, ...*/) {
        var m = MochiKit.Base;
        var self = MochiKit.Iter;
        var iterables = m.map(self.iter, m.extend(null, arguments, 1));
        var map = m.map;
        var next = self.next;
        return {
            repr: function () { return "imap(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                return fun.apply(this, map(next, iterables));
            }
        };
    },

    /** @id MochiKit.Iter.applymap */
    applymap: function (fun, seq, self) {
        seq = MochiKit.Iter.iter(seq);
        var m = MochiKit.Base;
        return {
            repr: function () { return "applymap(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                return fun.apply(self, seq.next());
            }
        };
    },

    /** @id MochiKit.Iter.chain */
    chain: function (p, q/*, ...*/) {
        // dumb fast path
        var self = MochiKit.Iter;
        var m = MochiKit.Base;
        if (arguments.length == 1) {
            return self.iter(arguments[0]);
        }
        var argiter = m.map(self.iter, arguments);
        return {
            repr: function () { return "chain(...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                while (argiter.length > 1) {
                    try {
                        return argiter[0].next();
                    } catch (e) {
                        if (e != self.StopIteration) {
                            throw e;
                        }
                        argiter.shift();
                    }
                }
                if (argiter.length == 1) {
                    // optimize last element
                    var arg = argiter.shift();
                    this.next = m.bind("next", arg);
                    return this.next();
                }
                throw self.StopIteration;
            }
        };
    },

    /** @id MochiKit.Iter.takewhile */
    takewhile: function (pred, seq) {
        var self = MochiKit.Iter;
        seq = self.iter(seq);
        return {
            repr: function () { return "takewhile(...)"; },
            toString: MochiKit.Base.forwardCall("repr"),
            next: function () {
                var rval = seq.next();
                if (!pred(rval)) {
                    this.next = function () {
                        throw self.StopIteration;
                    };
                    this.next();
                }
                return rval;
            }
        };
    },

    /** @id MochiKit.Iter.dropwhile */
    dropwhile: function (pred, seq) {
        seq = MochiKit.Iter.iter(seq);
        var m = MochiKit.Base;
        var bind = m.bind;
        return {
            "repr": function () { return "dropwhile(...)"; },
            "toString": m.forwardCall("repr"),
            "next": function () {
                while (true) {
                    var rval = seq.next();
                    if (!pred(rval)) {
                        break;
                    }
                }
                this.next = bind("next", seq);
                return rval;
            }
        };
    },

    _tee: function (ident, sync, iterable) {
        sync.pos[ident] = -1;
        var m = MochiKit.Base;
        var listMin = m.listMin;
        return {
            repr: function () { return "tee(" + ident + ", ...)"; },
            toString: m.forwardCall("repr"),
            next: function () {
                var rval;
                var i = sync.pos[ident];

                if (i == sync.max) {
                    rval = iterable.next();
                    sync.deque.push(rval);
                    sync.max += 1;
                    sync.pos[ident] += 1;
                } else {
                    rval = sync.deque[i - sync.min];
                    sync.pos[ident] += 1;
                    if (i == sync.min && listMin(sync.pos) != sync.min) {
                        sync.min += 1;
                        sync.deque.shift();
                    }
                }
                return rval;
            }
        };
    },

    /** @id MochiKit.Iter.tee */
    tee: function (iterable, n/* = 2 */) {
        var rval = [];
        var sync = {
            "pos": [],
            "deque": [],
            "max": -1,
            "min": -1
        };
        if (arguments.length == 1 || typeof(n) == "undefined" || n === null) {
            n = 2;
        }
        var self = MochiKit.Iter;
        iterable = self.iter(iterable);
        var _tee = self._tee;
        for (var i = 0; i < n; i++) {
            rval.push(_tee(i, sync, iterable));
        }
        return rval;
    },

    /** @id MochiKit.Iter.list */
    list: function (iterable) {
        // Fast-path for Array and Array-like
        var m = MochiKit.Base;
        if (typeof(iterable.slice) == 'function') {
            return iterable.slice();
        } else if (m.isArrayLike(iterable)) {
            return m.concat(iterable);
        }

        var self = MochiKit.Iter;
        iterable = self.iter(iterable);
        var rval = [];
        try {
            while (true) {
                rval.push(iterable.next());
            }
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
            return rval;
        }
        // mozilla warnings aren't too bright
        return undefined;
    },


    /** @id MochiKit.Iter.reduce */
    reduce: function (fn, iterable, /* optional */initial) {
        var i = 0;
        var x = initial;
        var self = MochiKit.Iter;
        iterable = self.iter(iterable);
        if (arguments.length < 3) {
            try {
                x = iterable.next();
            } catch (e) {
                if (e == self.StopIteration) {
                    e = new TypeError("reduce() of empty sequence with no initial value");
                }
                throw e;
            }
            i++;
        }
        try {
            while (true) {
                x = fn(x, iterable.next());
            }
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
        }
        return x;
    },

    /** @id MochiKit.Iter.range */
    range: function (/* [start,] stop[, step] */) {
        var start = 0;
        var stop = 0;
        var step = 1;
        if (arguments.length == 1) {
            stop = arguments[0];
        } else if (arguments.length == 2) {
            start = arguments[0];
            stop = arguments[1];
        } else if (arguments.length == 3) {
            start = arguments[0];
            stop = arguments[1];
            step = arguments[2];
        } else {
            throw new TypeError("range() takes 1, 2, or 3 arguments!");
        }
        if (step === 0) {
            throw new TypeError("range() step must not be 0");
        }
        return {
            next: function () {
                if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
                    throw MochiKit.Iter.StopIteration;
                }
                var rval = start;
                start += step;
                return rval;
            },
            repr: function () {
                return "range(" + [start, stop, step].join(", ") + ")";
            },
            toString: MochiKit.Base.forwardCall("repr")
        };
    },

    /** @id MochiKit.Iter.sum */
    sum: function (iterable, start/* = 0 */) {
        if (typeof(start) == "undefined" || start === null) {
            start = 0;
        }
        var x = start;
        var self = MochiKit.Iter;
        iterable = self.iter(iterable);
        try {
            while (true) {
                x += iterable.next();
            }
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
        }
        return x;
    },

    /** @id MochiKit.Iter.exhaust */
    exhaust: function (iterable) {
        var self = MochiKit.Iter;
        iterable = self.iter(iterable);
        try {
            while (true) {
                iterable.next();
            }
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
        }
    },

    /** @id MochiKit.Iter.forEach */
    forEach: function (iterable, func, /* optional */self) {
        var m = MochiKit.Base;
        if (arguments.length > 2) {
            func = m.bind(func, self);
        }
        // fast path for array
        if (m.isArrayLike(iterable)) {
            try {
                for (var i = 0; i < iterable.length; i++) {
                    func(iterable[i]);
                }
            } catch (e) {
                if (e != MochiKit.Iter.StopIteration) {
                    throw e;
                }
            }
        } else {
            self = MochiKit.Iter;
            self.exhaust(self.imap(func, iterable));
        }
    },

    /** @id MochiKit.Iter.every */
    every: function (iterable, func) {
        var self = MochiKit.Iter;
        try {
            self.ifilterfalse(func, iterable).next();
            return false;
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
            return true;
        }
    },

    /** @id MochiKit.Iter.sorted */
    sorted: function (iterable, /* optional */cmp) {
        var rval = MochiKit.Iter.list(iterable);
        if (arguments.length == 1) {
            cmp = MochiKit.Base.compare;
        }
        rval.sort(cmp);
        return rval;
    },

    /** @id MochiKit.Iter.reversed */
    reversed: function (iterable) {
        var rval = MochiKit.Iter.list(iterable);
        rval.reverse();
        return rval;
    },

    /** @id MochiKit.Iter.some */
    some: function (iterable, func) {
        var self = MochiKit.Iter;
        try {
            self.ifilter(func, iterable).next();
            return true;
        } catch (e) {
            if (e != self.StopIteration) {
                throw e;
            }
            return false;
        }
    },

    /** @id MochiKit.Iter.iextend */
    iextend: function (lst, iterable) {
        if (MochiKit.Base.isArrayLike(iterable)) {
            // fast-path for array-like
            for (var i = 0; i < iterable.length; i++) {
                lst.push(iterable[i]);
            }
        } else {
            var self = MochiKit.Iter;
            iterable = self.iter(iterable);
            try {
                while (true) {
                    lst.push(iterable.next());
                }
            } catch (e) {
                if (e != self.StopIteration) {
                    throw e;
                }
            }
        }
        return lst;
    },

    /** @id MochiKit.Iter.groupby */
    groupby: function(iterable, /* optional */ keyfunc) {
        var m = MochiKit.Base;
        var self = MochiKit.Iter;
        if (arguments.length < 2) {
            keyfunc = m.operator.identity;
        }
        iterable = self.iter(iterable);

        // shared
        var pk = undefined;
        var k = undefined;
        var v;

        function fetch() {
            v = iterable.next();
            k = keyfunc(v);
        };

        function eat() {
            var ret = v;
            v = undefined;
            return ret;
        };

        var first = true;
        var compare = m.compare;
        return {
            repr: function () { return "groupby(...)"; },
            next: function() {
                // iterator-next

                // iterate until meet next group
                while (compare(k, pk) === 0) {
                    fetch();
                    if (first) {
                        first = false;
                        break;
                    }
                }
                pk = k;
                return [k, {
                    next: function() {
                        // subiterator-next
                        if (v == undefined) { // Is there something to eat?
                            fetch();
                        }
                        if (compare(k, pk) !== 0) {
                            throw self.StopIteration;
                        }
                        return eat();
                    }
                }];
            }
        };
    },

    /** @id MochiKit.Iter.groupby_as_array */
    groupby_as_array: function (iterable, /* optional */ keyfunc) {
        var m = MochiKit.Base;
        var self = MochiKit.Iter;
        if (arguments.length < 2) {
            keyfunc = m.operator.identity;
        }

        iterable = self.iter(iterable);
        var result = [];
        var first = true;
        var prev_key;
        var compare = m.compare;
        while (true) {
            try {
                var value = iterable.next();
                var key = keyfunc(value);
            } catch (e) {
                if (e == self.StopIteration) {
                    break;
                }
                throw e;
            }
            if (first || compare(key, prev_key) !== 0) {
                var values = [];
                result.push([key, values]);
            }
            values.push(value);
            first = false;
            prev_key = key;
        }
        return result;
    },

    /** @id MochiKit.Iter.arrayLikeIter */
    arrayLikeIter: function (iterable) {
        var i = 0;
        return {
            repr: function () { return "arrayLikeIter(...)"; },
            toString: MochiKit.Base.forwardCall("repr"),
            next: function () {
                if (i >= iterable.length) {
                    throw MochiKit.Iter.StopIteration;
                }
                return iterable[i++];
            }
        };
    },

    /** @id MochiKit.Iter.hasIterateNext */
    hasIterateNext: function (iterable) {
        return (iterable && typeof(iterable.iterateNext) == "function");
    },

    /** @id MochiKit.Iter.iterateNextIter */
    iterateNextIter: function (iterable) {
        return {
            repr: function () { return "iterateNextIter(...)"; },
            toString: MochiKit.Base.forwardCall("repr"),
            next: function () {
                var rval = iterable.iterateNext();
                if (rval === null || rval === undefined) {
                    throw MochiKit.Iter.StopIteration;
                }
                return rval;
            }
        };
    }
});


MochiKit.Iter.EXPORT_OK = [
    "iteratorRegistry",
    "arrayLikeIter",
    "hasIterateNext",
    "iterateNextIter",
];

MochiKit.Iter.EXPORT = [
    "StopIteration",
    "registerIteratorFactory",
    "iter",
    "count",
    "cycle",
    "repeat",
    "next",
    "izip",
    "ifilter",
    "ifilterfalse",
    "islice",
    "imap",
    "applymap",
    "chain",
    "takewhile",
    "dropwhile",
    "tee",
    "list",
    "reduce",
    "range",
    "sum",
    "exhaust",
    "forEach",
    "every",
    "sorted",
    "reversed",
    "some",
    "iextend",
    "groupby",
    "groupby_as_array"
];

MochiKit.Iter.__new__ = function () {
    var m = MochiKit.Base;
    // Re-use StopIteration if exists (e.g. SpiderMonkey)
    if (typeof(StopIteration) != "undefined") {
        this.StopIteration = StopIteration;
    } else {
        /** @id MochiKit.Iter.StopIteration */
        this.StopIteration = new m.NamedError("StopIteration");
    }
    this.iteratorRegistry = new m.AdapterRegistry();
    // Register the iterator factory for arrays
    this.registerIteratorFactory(
        "arrayLike",
        m.isArrayLike,
        this.arrayLikeIter
    );

    this.registerIteratorFactory(
        "iterateNext",
        this.hasIterateNext,
        this.iterateNextIter
    );

    this.EXPORT_TAGS = {
        ":common": this.EXPORT,
        ":all": m.concat(this.EXPORT, this.EXPORT_OK)
    };

    m.nameFunctions(this);

};

MochiKit.Iter.__new__();

//
// XXX: Internet Explorer blows
//
if (MochiKit.__export__) {
    reduce = MochiKit.Iter.reduce;
}

MochiKit.Base._exportSymbols(this, MochiKit.Iter);

/***

MochiKit.Color 1.4

See <http://mochikit.com/> for documentation, downloads, license, etc.

(c) 2005 Bob Ippolito and others.  All rights Reserved.

***/

if (typeof(dojo) != 'undefined') {
    dojo.provide('MochiKit.Color');
    dojo.require('MochiKit.Base');
    dojo.require('MochiKit.DOM');
    dojo.require('MochiKit.Style');
}

if (typeof(JSAN) != 'undefined') {
    JSAN.use("MochiKit.Base", []);
    JSAN.use("MochiKit.DOM", []);
    JSAN.use("MochiKit.Style", []);
}

try {
    if (typeof(MochiKit.Base) == 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Color depends on MochiKit.Base";
}

try {
    if (typeof(MochiKit.DOM) == 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Color depends on MochiKit.DOM";
}

try {
    if (typeof(MochiKit.Style) == 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Color depends on MochiKit.Style";
}

if (typeof(MochiKit.Color) == "undefined") {
    MochiKit.Color = {};
}

MochiKit.Color.NAME = "MochiKit.Color";
MochiKit.Color.VERSION = "1.4";

MochiKit.Color.__repr__ = function () {
    return "[" + this.NAME + " " + this.VERSION + "]";
};

MochiKit.Color.toString = function () {
    return this.__repr__();
};


/** @id MochiKit.Color.Color */
MochiKit.Color.Color = function (red, green, blue, alpha) {
    if (typeof(alpha) == 'undefined' || alpha === null) {
        alpha = 1.0;
    }
    this.rgb = {
        r: red,
        g: green,
        b: blue,
        a: alpha
    };
};


// Prototype methods

MochiKit.Color.Color.prototype = {

    __class__: MochiKit.Color.Color,

    /** @id MochiKit.Color.Color.prototype.colorWithAlpha */
    colorWithAlpha: function (alpha) {
        var rgb = this.rgb;
        var m = MochiKit.Color;
        return m.Color.fromRGB(rgb.r, rgb.g, rgb.b, alpha);
    },

    /** @id MochiKit.Color.Color.prototype.colorWithHue */
    colorWithHue: function (hue) {
        // get an HSL model, and set the new hue...
        var hsl = this.asHSL();
        hsl.h = hue;
        var m = MochiKit.Color;
        // convert back to RGB...
        return m.Color.fromHSL(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.colorWithSaturation */
    colorWithSaturation: function (saturation) {
        // get an HSL model, and set the new hue...
        var hsl = this.asHSL();
        hsl.s = saturation;
        var m = MochiKit.Color;
        // convert back to RGB...
        return m.Color.fromHSL(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.colorWithLightness */
    colorWithLightness: function (lightness) {
        // get an HSL model, and set the new hue...
        var hsl = this.asHSL();
        hsl.l = lightness;
        var m = MochiKit.Color;
        // convert back to RGB...
        return m.Color.fromHSL(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.darkerColorWithLevel */
    darkerColorWithLevel: function (level) {
        var hsl  = this.asHSL();
        hsl.l = Math.max(hsl.l - level, 0);
        var m = MochiKit.Color;
        return m.Color.fromHSL(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.lighterColorWithLevel */
    lighterColorWithLevel: function (level) {
        var hsl  = this.asHSL();
        hsl.l = Math.min(hsl.l + level, 1);
        var m = MochiKit.Color;
        return m.Color.fromHSL(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.blendedColor */
    blendedColor: function (other, /* optional */ fraction) {
        if (typeof(fraction) == 'undefined' || fraction === null) {
            fraction = 0.5;
        }
        var sf = 1.0 - fraction;
        var s = this.rgb;
        var d = other.rgb;
        var df = fraction;
        return MochiKit.Color.Color.fromRGB(
            (s.r * sf) + (d.r * df),
            (s.g * sf) + (d.g * df),
            (s.b * sf) + (d.b * df),
            (s.a * sf) + (d.a * df)
        );
    },

    /** @id MochiKit.Color.Color.prototype.compareRGB */
    compareRGB: function (other) {
        var a = this.asRGB();
        var b = other.asRGB();
        return MochiKit.Base.compare(
            [a.r, a.g, a.b, a.a],
            [b.r, b.g, b.b, b.a]
        );
    },

    /** @id MochiKit.Color.Color.prototype.isLight */
    isLight: function () {
        return this.asHSL().b > 0.5;
    },

    /** @id MochiKit.Color.Color.prototype.isDark */
    isDark: function () {
        return (!this.isLight());
    },

    /** @id MochiKit.Color.Color.prototype.toHSLString */
    toHSLString: function () {
        var c = this.asHSL();
        var ccc = MochiKit.Color.clampColorComponent;
        var rval = this._hslString;
        if (!rval) {
            var mid = (
                ccc(c.h, 360).toFixed(0)
                + "," + ccc(c.s, 100).toPrecision(4) + "%"
                + "," + ccc(c.l, 100).toPrecision(4) + "%"
            );
            var a = c.a;
            if (a >= 1) {
                a = 1;
                rval = "hsl(" + mid + ")";
            } else {
                if (a <= 0) {
                    a = 0;
                }
                rval = "hsla(" + mid + "," + a + ")";
            }
            this._hslString = rval;
        }
        return rval;
    },

    /** @id MochiKit.Color.Color.prototype.toRGBString */
    toRGBString: function () {
        var c = this.rgb;
        var ccc = MochiKit.Color.clampColorComponent;
        var rval = this._rgbString;
        if (!rval) {
            var mid = (
                ccc(c.r, 255).toFixed(0)
                + "," + ccc(c.g, 255).toFixed(0)
                + "," + ccc(c.b, 255).toFixed(0)
            );
            if (c.a != 1) {
                rval = "rgba(" + mid + "," + c.a + ")";
            } else {
                rval = "rgb(" + mid + ")";
            }
            this._rgbString = rval;
        }
        return rval;
    },

    /** @id MochiKit.Color.Color.prototype.asRGB */
    asRGB: function () {
        return MochiKit.Base.clone(this.rgb);
    },

    /** @id MochiKit.Color.Color.prototype.toHexString */
    toHexString: function () {
        var m = MochiKit.Color;
        var c = this.rgb;
        var ccc = MochiKit.Color.clampColorComponent;
        var rval = this._hexString;
        if (!rval) {
            rval = ("#" +
                m.toColorPart(ccc(c.r, 255)) +
                m.toColorPart(ccc(c.g, 255)) +
                m.toColorPart(ccc(c.b, 255))
            );
            this._hexString = rval;
        }
        return rval;
    },

    /** @id MochiKit.Color.Color.prototype.asHSV */
    asHSV: function () {
        var hsv = this.hsv;
        var c = this.rgb;
        if (typeof(hsv) == 'undefined' || hsv === null) {
            hsv = MochiKit.Color.rgbToHSV(this.rgb);
            this.hsv = hsv;
        }
        return MochiKit.Base.clone(hsv);
    },

    /** @id MochiKit.Color.Color.prototype.asHSL */
    asHSL: function () {
        var hsl = this.hsl;
        var c = this.rgb;
        if (typeof(hsl) == 'undefined' || hsl === null) {
            hsl = MochiKit.Color.rgbToHSL(this.rgb);
            this.hsl = hsl;
        }
        return MochiKit.Base.clone(hsl);
    },

    /** @id MochiKit.Color.Color.prototype.toString */
    toString: function () {
        return this.toRGBString();
    },

    /** @id MochiKit.Color.Color.prototype.repr */
    repr: function () {
        var c = this.rgb;
        var col = [c.r, c.g, c.b, c.a];
        return this.__class__.NAME + "(" + col.join(", ") + ")";
    }

};

// Constructor methods

MochiKit.Base.update(MochiKit.Color.Color, {
    /** @id MochiKit.Color.Color.fromRGB */
    fromRGB: function (red, green, blue, alpha) {
        // designated initializer
        var Color = MochiKit.Color.Color;
        if (arguments.length == 1) {
            var rgb = red;
            red = rgb.r;
            green = rgb.g;
            blue = rgb.b;
            if (typeof(rgb.a) == 'undefined') {
                alpha = undefined;
            } else {
                alpha = rgb.a;
            }
        }
        return new Color(red, green, blue, alpha);
    },

    /** @id MochiKit.Color.Color.fromHSL */
    fromHSL: function (hue, saturation, lightness, alpha) {
        var m = MochiKit.Color;
        return m.Color.fromRGB(m.hslToRGB.apply(m, arguments));
    },

    /** @id MochiKit.Color.Color.fromHSV */
    fromHSV: function (hue, saturation, value, alpha) {
        var m = MochiKit.Color;
        return m.Color.fromRGB(m.hsvToRGB.apply(m, arguments));
    },

    /** @id MochiKit.Color.Color.fromName */
    fromName: function (name) {
        var Color = MochiKit.Color.Color;
        // Opera 9 seems to "quote" named colors(?!)
        if (name.charAt(0) == '"') {
            name = name.substr(1, name.length - 2);
        }
        var htmlColor = Color._namedColors[name.toLowerCase()];
        if (typeof(htmlColor) == 'string') {
            return Color.fromHexString(htmlColor);
        } else if (name == "transparent") {
            return Color.transparentColor();
        }
        return null;
    },

    /** @id MochiKit.Color.Color.fromString */
    fromString: function (colorString) {
        var self = MochiKit.Color.Color;
        var three = colorString.substr(0, 3);
        if (three == "rgb") {
            return self.fromRGBString(colorString);
        } else if (three == "hsl") {
            return self.fromHSLString(colorString);
        } else if (colorString.charAt(0) == "#") {
            return self.fromHexString(colorString);
        }
        return self.fromName(colorString);
    },


    /** @id MochiKit.Color.Color.fromHexString */
    fromHexString: function (hexCode) {
        if (hexCode.charAt(0) == '#') {
            hexCode = hexCode.substring(1);
        }
        var components = [];
        var i, hex;
        if (hexCode.length == 3) {
            for (i = 0; i < 3; i++) {
                hex = hexCode.substr(i, 1);
                components.push(parseInt(hex + hex, 16) / 255.0);
            }
        } else {
            for (i = 0; i < 6; i += 2) {
                hex = hexCode.substr(i, 2);
                components.push(parseInt(hex, 16) / 255.0);
            }
        }
        var Color = MochiKit.Color.Color;
        return Color.fromRGB.apply(Color, components);
    },


    _fromColorString: function (pre, method, scales, colorCode) {
        // parses either HSL or RGB
        if (colorCode.indexOf(pre) === 0) {
            colorCode = colorCode.substring(colorCode.indexOf("(", 3) + 1, colorCode.length - 1);
        }
        var colorChunks = colorCode.split(/\s*,\s*/);
        var colorFloats = [];
        for (var i = 0; i < colorChunks.length; i++) {
            var c = colorChunks[i];
            var val;
            var three = c.substring(c.length - 3);
            if (c.charAt(c.length - 1) == '%') {
                val = 0.01 * parseFloat(c.substring(0, c.length - 1));
            } else if (three == "deg") {
                val = parseFloat(c) / 360.0;
            } else if (three == "rad") {
                val = parseFloat(c) / (Math.PI * 2);
            } else {
                val = scales[i] * parseFloat(c);
            }
            colorFloats.push(val);
        }
        return this[method].apply(this, colorFloats);
    },

    /** @id MochiKit.Color.Color.fromComputedStyle */
    fromComputedStyle: function (elem, style) {
        var d = MochiKit.DOM;
        var cls = MochiKit.Color.Color;
        for (elem = d.getElement(elem); elem; elem = elem.parentNode) {
            var actualColor = MochiKit.Style.getStyle.apply(d, arguments);
            if (!actualColor) {
                continue;
            }
            var color = cls.fromString(actualColor);
            if (!color) {
                break;
            }
            if (color.asRGB().a > 0) {
                return color;
            }
        }
        return null;
    },

    /** @id MochiKit.Color.Color.fromBackground */
    fromBackground: function (elem) {
        var cls = MochiKit.Color.Color;
        return cls.fromComputedStyle(
            elem, "backgroundColor", "background-color") || cls.whiteColor();
    },

    /** @id MochiKit.Color.Color.fromText */
    fromText: function (elem) {
        var cls = MochiKit.Color.Color;
        return cls.fromComputedStyle(
            elem, "color", "color") || cls.blackColor();
    },

    /** @id MochiKit.Color.Color.namedColors */
    namedColors: function () {
        return MochiKit.Base.clone(MochiKit.Color.Color._namedColors);
    }
});


// Module level functions

MochiKit.Base.update(MochiKit.Color, {
    /** @id MochiKit.Color.clampColorComponent */
    clampColorComponent: function (v, scale) {
        v *= scale;
        if (v < 0) {
            return 0;
        } else if (v > scale) {
            return scale;
        } else {
            return v;
        }
    },

    _hslValue: function (n1, n2, hue) {
        if (hue > 6.0) {
            hue -= 6.0;
        } else if (hue < 0.0) {
            hue += 6.0;
        }
        var val;
        if (hue < 1.0) {
            val = n1 + (n2 - n1) * hue;
        } else if (hue < 3.0) {
            val = n2;
        } else if (hue < 4.0) {
            val = n1 + (n2 - n1) * (4.0 - hue);
        } else {
            val = n1;
        }
        return val;
    },

    /** @id MochiKit.Color.hsvToRGB */
    hsvToRGB: function (hue, saturation, value, alpha) {
        if (arguments.length == 1) {
            var hsv = hue;
            hue = hsv.h;
            saturation = hsv.s;
            value = hsv.v;
            alpha = hsv.a;
        }
        var red;
        var green;
        var blue;
        if (saturation === 0) {
            red = 0;
            green = 0;
            blue = 0;
        } else {
            var i = Math.floor(hue * 6);
            var f = (hue * 6) - i;
            var p = value * (1 - saturation);
            var q = value * (1 - (saturation * f));
            var t = value * (1 - (saturation * (1 - f)));
            switch (i) {
                case 1: red = q; green = value; blue = p; break;
                case 2: red = p; green = value; blue = t; break;
                case 3: red = p; green = q; blue = value; break;
                case 4: red = t; green = p; blue = value; break;
                case 5: red = value; green = p; blue = q; break;
                case 6: // fall through
                case 0: red = value; green = t; blue = p; break;
            }
        }
        return {
            r: red,
            g: green,
            b: blue,
            a: alpha
        };
    },

    /** @id MochiKit.Color.hslToRGB */
    hslToRGB: function (hue, saturation, lightness, alpha) {
        if (arguments.length == 1) {
            var hsl = hue;
            hue = hsl.h;
            saturation = hsl.s;
            lightness = hsl.l;
            alpha = hsl.a;
        }
        var red;
        var green;
        var blue;
        if (saturation === 0) {
            red = lightness;
            green = lightness;
            blue = lightness;
        } else {
            var m2;
            if (lightness <= 0.5) {
                m2 = lightness * (1.0 + saturation);
            } else {
                m2 = lightness + saturation - (lightness * saturation);
            }
            var m1 = (2.0 * lightness) - m2;
            var f = MochiKit.Color._hslValue;
            var h6 = hue * 6.0;
            red = f(m1, m2, h6 + 2);
            green = f(m1, m2, h6);
            blue = f(m1, m2, h6 - 2);
        }
        return {
            r: red,
            g: green,
            b: blue,
            a: alpha
        };
    },

    /** @id MochiKit.Color.rgbToHSV */
    rgbToHSV: function (red, green, blue, alpha) {
        if (arguments.length == 1) {
            var rgb = red;
            red = rgb.r;
            green = rgb.g;
            blue = rgb.b;
            alpha = rgb.a;
        }
        var max = Math.max(Math.max(red, green), blue);
        var min = Math.min(Math.min(red, green), blue);
        var hue;
        var saturation;
        var value = max;
        if (min == max) {
            hue = 0;
            saturation = 0;
        } else {
            var delta = (max - min);
            saturation = delta / max;

            if (red == max) {
                hue = (green - blue) / delta;
            } else if (green == max) {
                hue = 2 + ((blue - red) / delta);
            } else {
                hue = 4 + ((red - green) / delta);
            }
            hue /= 6;
            if (hue < 0) {
                hue += 1;
            }
            if (hue > 1) {
                hue -= 1;
            }
        }
        return {
            h: hue,
            s: saturation,
            v: value,
            a: alpha
        };
    },

    /** @id MochiKit.Color.rgbToHSL */
    rgbToHSL: function (red, green, blue, alpha) {
        if (arguments.length == 1) {
            var rgb = red;
            red = rgb.r;
            green = rgb.g;
            blue = rgb.b;
            alpha = rgb.a;
        }
        var max = Math.max(red, Math.max(green, blue));
        var min = Math.min(red, Math.min(green, blue));
        var hue;
        var saturation;
        var lightness = (max + min) / 2.0;
        var delta = max - min;
        if (delta === 0) {
            hue = 0;
            saturation = 0;
        } else {
            if (lightness <= 0.5) {
                saturation = delta / (max + min);
            } else {
                saturation = delta / (2 - max - min);
            }
            if (red == max) {
                hue = (green - blue) / delta;
            } else if (green == max) {
                hue = 2 + ((blue - red) / delta);
            } else {
                hue = 4 + ((red - green) / delta);
            }
            hue /= 6;
            if (hue < 0) {
                hue += 1;
            }
            if (hue > 1) {
                hue -= 1;
            }

        }
        return {
            h: hue,
            s: saturation,
            l: lightness,
            a: alpha
        };
    },

    /** @id MochiKit.Color.toColorPart */
    toColorPart: function (num) {
        num = Math.round(num);
        var digits = num.toString(16);
        if (num < 16) {
            return '0' + digits;
        }
        return digits;
    },

    __new__: function () {
        var m = MochiKit.Base;
        /** @id MochiKit.Color.fromRGBString */
        this.Color.fromRGBString = m.bind(
            this.Color._fromColorString, this.Color, "rgb", "fromRGB",
            [1.0/255.0, 1.0/255.0, 1.0/255.0, 1]
        );
        /** @id MochiKit.Color.fromHSLString */
        this.Color.fromHSLString = m.bind(
            this.Color._fromColorString, this.Color, "hsl", "fromHSL",
            [1.0/360.0, 0.01, 0.01, 1]
        );

        var third = 1.0 / 3.0;
        /** @id MochiKit.Color.colors */
        var colors = {
            // NSColor colors plus transparent
            /** @id MochiKit.Color.blackColor */
            black: [0, 0, 0],
            /** @id MochiKit.Color.blueColor */
            blue: [0, 0, 1],
            /** @id MochiKit.Color.brownColor */
            brown: [0.6, 0.4, 0.2],
            /** @id MochiKit.Color.cyanColor */
            cyan: [0, 1, 1],
            /** @id MochiKit.Color.darkGrayColor */
            darkGray: [third, third, third],
            /** @id MochiKit.Color.grayColor */
            gray: [0.5, 0.5, 0.5],
            /** @id MochiKit.Color.greenColor */
            green: [0, 1, 0],
            /** @id MochiKit.Color.lightGrayColor */
            lightGray: [2 * third, 2 * third, 2 * third],
            /** @id MochiKit.Color.magentaColor */
            magenta: [1, 0, 1],
            /** @id MochiKit.Color.orangeColor */
            orange: [1, 0.5, 0],
            /** @id MochiKit.Color.purpleColor */
            purple: [0.5, 0, 0.5],
            /** @id MochiKit.Color.redColor */
            red: [1, 0, 0],
            /** @id MochiKit.Color.transparentColor */
            transparent: [0, 0, 0, 0],
            /** @id MochiKit.Color.whiteColor */
            white: [1, 1, 1],
            /** @id MochiKit.Color.yellowColor */
            yellow: [1, 1, 0]
        };

        var makeColor = function (name, r, g, b, a) {
            var rval = this.fromRGB(r, g, b, a);
            this[name] = function () { return rval; };
            return rval;
        };

        for (var k in colors) {
            var name = k + "Color";
            var bindArgs = m.concat(
                [makeColor, this.Color, name],
                colors[k]
            );
            this.Color[name] = m.bind.apply(null, bindArgs);
        }

        var isColor = function () {
            for (var i = 0; i < arguments.length; i++) {
                if (!(arguments[i] instanceof Color)) {
                    return false;
                }
            }
            return true;
        };

        var compareColor = function (a, b) {
            return a.compareRGB(b);
        };

        m.nameFunctions(this);

        m.registerComparator(this.Color.NAME, isColor, compareColor);

        this.EXPORT_TAGS = {
            ":common": this.EXPORT,
            ":all": m.concat(this.EXPORT, this.EXPORT_OK)
        };

    }
});

MochiKit.Color.EXPORT = [
    "Color"
];

MochiKit.Color.EXPORT_OK = [
    "clampColorComponent",
    "rgbToHSL",
    "hslToRGB",
    "rgbToHSV",
    "hsvToRGB",
    "toColorPart"
];

MochiKit.Color.__new__();

MochiKit.Base._exportSymbols(this, MochiKit.Color);

// Full table of css3 X11 colors <http://www.w3.org/TR/css3-color/#X11COLORS>

MochiKit.Color.Color._namedColors = {
    aliceblue: "#f0f8ff",
    antiquewhite: "#faebd7",
    aqua: "#00ffff",
    aquamarine: "#7fffd4",
    azure: "#f0ffff",
    beige: "#f5f5dc",
    bisque: "#ffe4c4",
    black: "#000000",
    blanchedalmond: "#ffebcd",
    blue: "#0000ff",
    blueviolet: "#8a2be2",
    brown: "#a52a2a",
    burlywood: "#deb887",
    cadetblue: "#5f9ea0",
    chartreuse: "#7fff00",
    chocolate: "#d2691e",
    coral: "#ff7f50",
    cornflowerblue: "#6495ed",
    cornsilk: "#fff8dc",
    crimson: "#dc143c",
    cyan: "#00ffff",
    darkblue: "#00008b",
    darkcyan: "#008b8b",
    darkgoldenrod: "#b8860b",
    darkgray: "#a9a9a9",
    darkgreen: "#006400",
    darkgrey: "#a9a9a9",
    darkkhaki: "#bdb76b",
    darkmagenta: "#8b008b",
    darkolivegreen: "#556b2f",
    darkorange: "#ff8c00",
    darkorchid: "#9932cc",
    darkred: "#8b0000",
    darksalmon: "#e9967a",
    darkseagreen: "#8fbc8f",
    darkslateblue: "#483d8b",
    darkslategray: "#2f4f4f",
    darkslategrey: "#2f4f4f",
    darkturquoise: "#00ced1",
    darkviolet: "#9400d3",
    deeppink: "#ff1493",
    deepskyblue: "#00bfff",
    dimgray: "#696969",
    dimgrey: "#696969",
    dodgerblue: "#1e90ff",
    firebrick: "#b22222",
    floralwhite: "#fffaf0",
    forestgreen: "#228b22",
    fuchsia: "#ff00ff",
    gainsboro: "#dcdcdc",
    ghostwhite: "#f8f8ff",
    gold: "#ffd700",
    goldenrod: "#daa520",
    gray: "#808080",
    green: "#008000",
    greenyellow: "#adff2f",
    grey: "#808080",
    honeydew: "#f0fff0",
    hotpink: "#ff69b4",
    indianred: "#cd5c5c",
    indigo: "#4b0082",
    ivory: "#fffff0",
    khaki: "#f0e68c",
    lavender: "#e6e6fa",
    lavenderblush: "#fff0f5",
    lawngreen: "#7cfc00",
    lemonchiffon: "#fffacd",
    lightblue: "#add8e6",
    lightcoral: "#f08080",
    lightcyan: "#e0ffff",
    lightgoldenrodyellow: "#fafad2",
    lightgray: "#d3d3d3",
    lightgreen: "#90ee90",
    lightgrey: "#d3d3d3",
    lightpink: "#ffb6c1",
    lightsalmon: "#ffa07a",
    lightseagreen: "#20b2aa",
    lightskyblue: "#87cefa",
    lightslategray: "#778899",
    lightslategrey: "#778899",
    lightsteelblue: "#b0c4de",
    lightyellow: "#ffffe0",
    lime: "#00ff00",
    limegreen: "#32cd32",
    linen: "#faf0e6",
    magenta: "#ff00ff",
    maroon: "#800000",
    mediumaquamarine: "#66cdaa",
    mediumblue: "#0000cd",
    mediumorchid: "#ba55d3",
    mediumpurple: "#9370db",
    mediumseagreen: "#3cb371",
    mediumslateblue: "#7b68ee",
    mediumspringgreen: "#00fa9a",
    mediumturquoise: "#48d1cc",
    mediumvioletred: "#c71585",
    midnightblue: "#191970",
    mintcream: "#f5fffa",
    mistyrose: "#ffe4e1",
    moccasin: "#ffe4b5",
    navajowhite: "#ffdead",
    navy: "#000080",
    oldlace: "#fdf5e6",
    olive: "#808000",
    olivedrab: "#6b8e23",
    orange: "#ffa500",
    orangered: "#ff4500",
    orchid: "#da70d6",
    palegoldenrod: "#eee8aa",
    palegreen: "#98fb98",
    paleturquoise: "#afeeee",
    palevioletred: "#db7093",
    papayawhip: "#ffefd5",
    peachpuff: "#ffdab9",
    peru: "#cd853f",
    pink: "#ffc0cb",
    plum: "#dda0dd",
    powderblue: "#b0e0e6",
    purple: "#800080",
    red: "#ff0000",
    rosybrown: "#bc8f8f",
    royalblue: "#4169e1",
    saddlebrown: "#8b4513",
    salmon: "#fa8072",
    sandybrown: "#f4a460",
    seagreen: "#2e8b57",
    seashell: "#fff5ee",
    sienna: "#a0522d",
    silver: "#c0c0c0",
    skyblue: "#87ceeb",
    slateblue: "#6a5acd",
    slategray: "#708090",
    slategrey: "#708090",
    snow: "#fffafa",
    springgreen: "#00ff7f",
    steelblue: "#4682b4",
    tan: "#d2b48c",
    teal: "#008080",
    thistle: "#d8bfd8",
    tomato: "#ff6347",
    turquoise: "#40e0d0",
    violet: "#ee82ee",
    wheat: "#f5deb3",
    white: "#ffffff",
    whitesmoke: "#f5f5f5",
    yellow: "#ffff00",
    yellowgreen: "#9acd32"
};

/***

MochiKit.Visual 1.4

See <http://mochikit.com/> for documentation, downloads, license, etc.

(c) 2005 Bob Ippolito and others.  All rights Reserved.

***/

if (typeof(dojo) != 'undefined') {
    dojo.provide('MochiKit.Visual');
    dojo.require('MochiKit.Base');
    dojo.require('MochiKit.DOM');
    dojo.require('MochiKit.Style');
    dojo.require('MochiKit.Color');
    dojo.require('MochiKit.Position');
}

if (typeof(JSAN) != 'undefined') {
    JSAN.use("MochiKit.Base", []);
    JSAN.use("MochiKit.DOM", []);
    JSAN.use("MochiKit.Style", []);
    JSAN.use("MochiKit.Color", []);
    JSAN.use("MochiKit.Position", []);
}

try {
    if (typeof(MochiKit.Base) === 'undefined' ||
        typeof(MochiKit.DOM) === 'undefined' ||
        typeof(MochiKit.Style) === 'undefined' ||
        typeof(MochiKit.Position) === 'undefined' ||
        typeof(MochiKit.Color) === 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Visual depends on MochiKit.Base, MochiKit.DOM, MochiKit.Style, MochiKit.Position and MochiKit.Color!";
}

if (typeof(MochiKit.Visual) == "undefined") {
    MochiKit.Visual = {};
}

MochiKit.Visual.NAME = "MochiKit.Visual";
MochiKit.Visual.VERSION = "1.4";

MochiKit.Visual.__repr__ = function () {
    return "[" + this.NAME + " " + this.VERSION + "]";
};

MochiKit.Visual.toString = function () {
    return this.__repr__();
};

MochiKit.Visual._RoundCorners = function (e, options) {
    e = MochiKit.DOM.getElement(e);
    this._setOptions(options);
    if (this.options.__unstable__wrapElement) {
        e = this._doWrap(e);
    }

    var color = this.options.color;
    var C = MochiKit.Color.Color;
    if (this.options.color === "fromElement") {
        color = C.fromBackground(e);
    } else if (!(color instanceof C)) {
        color = C.fromString(color);
    }
    this.isTransparent = (color.asRGB().a <= 0);

    var bgColor = this.options.bgColor;
    if (this.options.bgColor === "fromParent") {
        bgColor = C.fromBackground(e.offsetParent);
    } else if (!(bgColor instanceof C)) {
        bgColor = C.fromString(bgColor);
    }

    this._roundCornersImpl(e, color, bgColor);
};

MochiKit.Visual._RoundCorners.prototype = {
    _doWrap: function (e) {
        var parent = e.parentNode;
        var doc = MochiKit.DOM.currentDocument();
        if (typeof(doc.defaultView) === "undefined"
            || doc.defaultView === null) {
            return e;
        }
        var style = doc.defaultView.getComputedStyle(e, null);
        if (typeof(style) === "undefined" || style === null) {
            return e;
        }
        var wrapper = MochiKit.DOM.DIV({"style": {
            display: "block",
            // convert padding to margin
            marginTop: style.getPropertyValue("padding-top"),
            marginRight: style.getPropertyValue("padding-right"),
            marginBottom: style.getPropertyValue("padding-bottom"),
            marginLeft: style.getPropertyValue("padding-left"),
            // remove padding so the rounding looks right
            padding: "0px"
            /*
            paddingRight: "0px",
            paddingLeft: "0px"
            */
        }});
        wrapper.innerHTML = e.innerHTML;
        e.innerHTML = "";
        e.appendChild(wrapper);
        return e;
    },

    _roundCornersImpl: function (e, color, bgColor) {
        if (this.options.border) {
            this._renderBorder(e, bgColor);
        }
        if (this._isTopRounded()) {
            this._roundTopCorners(e, color, bgColor);
        }
        if (this._isBottomRounded()) {
            this._roundBottomCorners(e, color, bgColor);
        }
    },

    _renderBorder: function (el, bgColor) {
        var borderValue = "1px solid " + this._borderColor(bgColor);
        var borderL = "border-left: "  + borderValue;
        var borderR = "border-right: " + borderValue;
        var style = "style='" + borderL + ";" + borderR +  "'";
        el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>";
    },

    _roundTopCorners: function (el, color, bgColor) {
        var corner = this._createCorner(bgColor);
        for (var i = 0; i < this.options.numSlices; i++) {
            corner.appendChild(
                this._createCornerSlice(color, bgColor, i, "top")
            );
        }
        el.style.paddingTop = 0;
        el.insertBefore(corner, el.firstChild);
    },

    _roundBottomCorners: function (el, color, bgColor) {
        var corner = this._createCorner(bgColor);
        for (var i = (this.options.numSlices - 1); i >= 0; i--) {
            corner.appendChild(
                this._createCornerSlice(color, bgColor, i, "bottom")
            );
        }
        el.style.paddingBottom = 0;
        el.appendChild(corner);
    },

    _createCorner: function (bgColor) {
        var dom = MochiKit.DOM;
        return dom.DIV({style: {backgroundColor: bgColor.toString()}});
    },

    _createCornerSlice: function (color, bgColor, n, position) {
        var slice = MochiKit.DOM.SPAN();

        var inStyle = slice.style;
        inStyle.backgroundColor = color.toString();
        inStyle.display = "block";
        inStyle.height = "1px";
        inStyle.overflow = "hidden";
        inStyle.fontSize = "1px";

        var borderColor = this._borderColor(color, bgColor);
        if (this.options.border && n === 0) {
            inStyle.borderTopStyle = "solid";
            inStyle.borderTopWidth = "1px";
            inStyle.borderLeftWidth = "0px";
            inStyle.borderRightWidth = "0px";
            inStyle.borderBottomWidth = "0px";
            // assumes css compliant box model
            inStyle.height = "0px";
            inStyle.borderColor = borderColor.toString();
        } else if (borderColor) {
            inStyle.borderColor = borderColor.toString();
            inStyle.borderStyle = "solid";
            inStyle.borderWidth = "0px 1px";
        }

        if (!this.options.compact && (n == (this.options.numSlices - 1))) {
            inStyle.height = "2px";
        }

        this._setMargin(slice, n, position);
        this._setBorder(slice, n, position);

        return slice;
    },

    _setOptions: function (options) {
        this.options = {
            corners: "all",
            color: "fromElement",
            bgColor: "fromParent",
            blend: true,
            border: false,
            compact: false,
            __unstable__wrapElement: false
        };
        MochiKit.Base.update(this.options, options);

        this.options.numSlices = (this.options.compact ? 2 : 4);
    },

    _whichSideTop: function () {
        var corners = this.options.corners;
        if (this._hasString(corners, "all", "top")) {
            return "";
        }

        var has_tl = (corners.indexOf("tl") != -1);
        var has_tr = (corners.indexOf("tr") != -1);
        if (has_tl && has_tr) {
            return "";
        }
        if (has_tl) {
            return "left";
        }
        if (has_tr) {
            return "right";
        }
        return "";
    },

    _whichSideBottom: function () {
        var corners = this.options.corners;
        if (this._hasString(corners, "all", "bottom")) {
            return "";
        }

        var has_bl = (corners.indexOf('bl') != -1);
        var has_br = (corners.indexOf('br') != -1);
        if (has_bl && has_br) {
            return "";
        }
        if (has_bl) {
            return "left";
        }
        if (has_br) {
            return "right";
        }
        return "";
    },

    _borderColor: function (color, bgColor) {
        if (color == "transparent") {
            return bgColor;
        } else if (this.options.border) {
            return this.options.border;
        } else if (this.options.blend) {
            return bgColor.blendedColor(color);
        }
        return "";
    },


    _setMargin: function (el, n, corners) {
        var marginSize = this._marginSize(n) + "px";
        var whichSide = (
            corners == "top" ? this._whichSideTop() : this._whichSideBottom()
        );
        var style = el.style;

        if (whichSide == "left") {
            style.marginLeft = marginSize;
            style.marginRight = "0px";
        } else if (whichSide == "right") {
            style.marginRight = marginSize;
            style.marginLeft = "0px";
        } else {
            style.marginLeft = marginSize;
            style.marginRight = marginSize;
        }
    },

    _setBorder: function (el, n, corners) {
        var borderSize = this._borderSize(n) + "px";
        var whichSide = (
            corners == "top" ? this._whichSideTop() : this._whichSideBottom()
        );

        var style = el.style;
        if (whichSide == "left") {
            style.borderLeftWidth = borderSize;
            style.borderRightWidth = "0px";
        } else if (whichSide == "right") {
            style.borderRightWidth = borderSize;
            style.borderLeftWidth = "0px";
        } else {
            style.borderLeftWidth = borderSize;
            style.borderRightWidth = borderSize;
        }
    },

    _marginSize: function (n) {
        if (this.isTransparent) {
            return 0;
        }

        var o = this.options;
        if (o.compact && o.blend) {
            var smBlendedMarginSizes = [1, 0];
            return smBlendedMarginSizes[n];
        } else if (o.compact) {
            var compactMarginSizes = [2, 1];
            return compactMarginSizes[n];
        } else if (o.blend) {
            var blendedMarginSizes = [3, 2, 1, 0];
            return blendedMarginSizes[n];
        } else {
            var marginSizes = [5, 3, 2, 1];
            return marginSizes[n];
        }
    },

    _borderSize: function (n) {
        var o = this.options;
        var borderSizes;
        if (o.compact && (o.blend || this.isTransparent)) {
            return 1;
        } else if (o.compact) {
            borderSizes = [1, 0];
        } else if (o.blend) {
            borderSizes = [2, 1, 1, 1];
        } else if (o.border) {
            borderSizes = [0, 2, 0, 0];
        } else if (this.isTransparent) {
            borderSizes = [5, 3, 2, 1];
        } else {
            return 0;
        }
        return borderSizes[n];
    },

    _hasString: function (str) {
        for (var i = 1; i< arguments.length; i++) {
            if (str.indexOf(arguments[i]) != -1) {
                return true;
            }
        }
        return false;
    },

    _isTopRounded: function () {
        return this._hasString(this.options.corners,
            "all", "top", "tl", "tr"
        );
    },

    _isBottomRounded: function () {
        return this._hasString(this.options.corners,
            "all", "bottom", "bl", "br"
        );
    },

    _hasSingleTextChild: function (el) {
        return (el.childNodes.length == 1 && el.childNodes[0].nodeType == 3);
    }
};

/** @id MochiKit.Visual.roundElement */
MochiKit.Visual.roundElement = function (e, options) {
    new MochiKit.Visual._RoundCorners(e, options);
};

/** @id MochiKit.Visual.roundClass */
MochiKit.Visual.roundClass = function (tagName, className, options) {
    var elements = MochiKit.DOM.getElementsByTagAndClassName(
        tagName, className
    );
    for (var i = 0; i < elements.length; i++) {
        MochiKit.Visual.roundElement(elements[i], options);
    }
};

/** @id MochiKit.Visual.tagifyText */
MochiKit.Visual.tagifyText = function (element, /* optional */tagifyStyle) {
    /***

    Change a node text to character in tags.

    @param tagifyStyle: the style to apply to character nodes, default to
    'position: relative'.

    ***/
    tagifyStyle = tagifyStyle || 'position:relative';
    if (/MSIE/.test(navigator.userAgent)) {
        tagifyStyle += ';zoom:1';
    }
    element = MochiKit.DOM.getElement(element);
    var ma = MochiKit.Base.map;
    ma(function (child) {
        if (child.nodeType == 3) {
            ma(function (character) {
                element.insertBefore(
                    MochiKit.DOM.SPAN({style: tagifyStyle},
                        character == ' ' ? String.fromCharCode(160) : character), child);
            }, child.nodeValue.split(''));
            MochiKit.DOM.removeElement(child);
        }
    }, element.childNodes);
};

/** @id MochiKit.Visual.forceRerendering */
MochiKit.Visual.forceRerendering = function (element) {
    try {
        element = MochiKit.DOM.getElement(element);
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
    } catch(e) {
    }
};

/** @id MochiKit.Visual.multiple */
MochiKit.Visual.multiple = function (elements, effect, /* optional */options) {
    /***

    Launch the same effect subsequently on given elements.

    ***/
    options = MochiKit.Base.update({
        speed: 0.1, delay: 0.0
    }, options || {});
    var masterDelay = options.delay;
    var index = 0;
    MochiKit.Base.map(function (innerelement) {
        options.delay = index * options.speed + masterDelay;
        new effect(innerelement, options);
        index += 1;
    }, elements);
};

MochiKit.Visual.PAIRS = {
    'slide': ['slideDown', 'slideUp'],
    'blind': ['blindDown', 'blindUp'],
    'appear': ['appear', 'fade'],
    'size': ['grow', 'shrink']
};

/** @id MochiKit.Visual.toggle */
MochiKit.Visual.toggle = function (element, /* optional */effect, /* optional */options) {
    /***

    Toggle an item between two state depending of its visibility, making
    a effect between these states. Default  effect is 'appear', can be
    'slide' or 'blind'.

    ***/
    element = MochiKit.DOM.getElement(element);
    effect = (effect || 'appear').toLowerCase();
    options = MochiKit.Base.update({
        queue: {position: 'end', scope: (element.id || 'global'), limit: 1}
    }, options || {});
    var v = MochiKit.Visual;
    v[element.style.display != 'none' ?
      v.PAIRS[effect][1] : v.PAIRS[effect][0]](element, options);
};

/***

Transitions: define functions calculating variations depending of a position.

***/

MochiKit.Visual.Transitions = {};

/** @id MochiKit.Visual.Transitions.linear */
MochiKit.Visual.Transitions.linear = function (pos) {
    return pos;
};

/** @id MochiKit.Visual.Transitions.sinoidal */
MochiKit.Visual.Transitions.sinoidal = function (pos) {
    return (-Math.cos(pos*Math.PI)/2) + 0.5;
};

/** @id MochiKit.Visual.Transitions.reverse */
MochiKit.Visual.Transitions.reverse = function (pos) {
    return 1 - pos;
};

/** @id MochiKit.Visual.Transitions.flicker */
MochiKit.Visual.Transitions.flicker = function (pos) {
    return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
};

/** @id MochiKit.Visual.Transitions.wobble */
MochiKit.Visual.Transitions.wobble = function (pos) {
    return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
};

/** @id MochiKit.Visual.Transitions.pulse */
MochiKit.Visual.Transitions.pulse = function (pos) {
    return (Math.floor(pos*10) % 2 === 0 ?
        (pos*10 - Math.floor(pos*10)) : 1 - (pos*10 - Math.floor(pos*10)));
};

/** @id MochiKit.Visual.Transitions.none */
MochiKit.Visual.Transitions.none = function (pos) {
    return 0;
};

/** @id MochiKit.Visual.Transitions.full */
MochiKit.Visual.Transitions.full = function (pos) {
    return 1;
};

/***

Core effects

***/

MochiKit.Visual.ScopedQueue = function () {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls();
    }
    this.__init__();
};

MochiKit.Base.update(MochiKit.Visual.ScopedQueue.prototype, {
    __init__: function () {
        this.effects = [];
        this.interval = null;
    },

    /** @id MochiKit.Visual.ScopedQueue.prototype.add */
    add: function (effect) {
        var timestamp = new Date().getTime();

        var position = (typeof(effect.options.queue) == 'string') ?
            effect.options.queue : effect.options.queue.position;

        var ma = MochiKit.Base.map;
        switch (position) {
            case 'front':
                // move unstarted effects after this effect
                ma(function (e) {
                    if (e.state == 'idle') {
                        e.startOn += effect.finishOn;
                        e.finishOn += effect.finishOn;
                    }
                }, this.effects);
                break;
            case 'end':
                var finish;
                // start effect after last queued effect has finished
                ma(function (e) {
                    var i = e.finishOn;
                    if (i >= (finish || i)) {
                        finish = i;
                    }
                }, this.effects);
                timestamp = finish || timestamp;
                break;
            case 'break':
                ma(function (e) {
                    e.finalize();
                }, this.effects);
                break;
        }

        effect.startOn += timestamp;
        effect.finishOn += timestamp;
        if (!effect.options.queue.limit ||
            this.effects.length < effect.options.queue.limit) {
            this.effects.push(effect);
        }

        if (!this.interval) {
            this.interval = this.startLoop(MochiKit.Base.bind(this.loop, this),
                                        40);
        }
    },

    /** @id MochiKit.Visual.ScopedQueue.prototype.startLoop */
    startLoop: function (func, interval) {
        return setInterval(func, interval);
    },

    /** @id MochiKit.Visual.ScopedQueue.prototype.remove */
    remove: function (effect) {
        this.effects = MochiKit.Base.filter(function (e) {
            return e != effect;
        }, this.effects);
        if (!this.effects.length) {
            this.stopLoop(this.interval);
            this.interval = null;
        }
    },

    /** @id MochiKit.Visual.ScopedQueue.prototype.stopLoop */
    stopLoop: function (interval) {
        clearInterval(interval);
    },

    /** @id MochiKit.Visual.ScopedQueue.prototype.loop */
    loop: function () {
        var timePos = new Date().getTime();
        MochiKit.Base.map(function (effect) {
            effect.loop(timePos);
        }, this.effects);
    }
});

MochiKit.Visual.Queues = {
    instances: {},

    get: function (queueName) {
        if (typeof(queueName) != 'string') {
            return queueName;
        }

        if (!this.instances[queueName]) {
            this.instances[queueName] = new MochiKit.Visual.ScopedQueue();
        }
        return this.instances[queueName];
    }
};

MochiKit.Visual.Queue = MochiKit.Visual.Queues.get('global');

MochiKit.Visual.DefaultOptions = {
    transition: MochiKit.Visual.Transitions.sinoidal,
    duration: 1.0,  // seconds
    fps: 25.0,  // max. 25fps due to MochiKit.Visual.Queue implementation
    sync: false,  // true for combining
    from: 0.0,
    to: 1.0,
    delay: 0.0,
    queue: 'parallel'
};

MochiKit.Visual.Base = function () {};

MochiKit.Visual.Base.prototype = {
    /***

    Basic class for all Effects. Define a looping mechanism called for each step
    of an effect. Don't instantiate it, only subclass it.

    ***/

    __class__ : MochiKit.Visual.Base,

    /** @id MochiKit.Visual.Base.prototype.start */
    start: function (options) {
        var v = MochiKit.Visual;
        this.options = MochiKit.Base.setdefault(options || {},
                                                v.DefaultOptions);
        this.currentFrame = 0;
        this.state = 'idle';
        this.startOn = this.options.delay*1000;
        this.finishOn = this.startOn + (this.options.duration*1000);
        this.event('beforeStart');
        if (!this.options.sync) {
            v.Queues.get(typeof(this.options.queue) == 'string' ?
                'global' : this.options.queue.scope).add(this);
        }
    },

    /** @id MochiKit.Visual.Base.prototype.loop */
    loop: function (timePos) {
        if (timePos >= this.startOn) {
            if (timePos >= this.finishOn) {
                return this.finalize();
            }
            var pos = (timePos - this.startOn) / (this.finishOn - this.startOn);
            var frame =
                Math.round(pos * this.options.fps * this.options.duration);
            if (frame > this.currentFrame) {
                this.render(pos);
                this.currentFrame = frame;
            }
        }
    },

    /** @id MochiKit.Visual.Base.prototype.render */
    render: function (pos) {
        if (this.state == 'idle') {
            this.state = 'running';
            this.event('beforeSetup');
            this.setup();
            this.event('afterSetup');
        }
        if (this.state == 'running') {
            if (this.options.transition) {
                pos = this.options.transition(pos);
            }
            pos *= (this.options.to - this.options.from);
            pos += this.options.from;
            this.event('beforeUpdate');
            this.update(pos);
            this.event('afterUpdate');
        }
    },

    /** @id MochiKit.Visual.Base.prototype.cancel */
    cancel: function () {
        if (!this.options.sync) {
            MochiKit.Visual.Queues.get(typeof(this.options.queue) == 'string' ?
                'global' : this.options.queue.scope).remove(this);
        }
        this.state = 'finished';
    },

    /** @id MochiKit.Visual.Base.prototype.finalize */
    finalize: function () {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        this.finish();
        this.event('afterFinish');
    },

    setup: function () {
    },

    finish: function () {
    },

    update: function (position) {
    },

    /** @id MochiKit.Visual.Base.prototype.event */
    event: function (eventName) {
        if (this.options[eventName + 'Internal']) {
            this.options[eventName + 'Internal'](this);
        }
        if (this.options[eventName]) {
            this.options[eventName](this);
        }
    },

    /** @id MochiKit.Visual.Base.prototype.repr */
    repr: function () {
        return '[' + this.__class__.NAME + ', options:' +
               MochiKit.Base.repr(this.options) + ']';
    }
};

    /** @id MochiKit.Visual.Parallel */
MochiKit.Visual.Parallel = function (effects, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(effects, options);
    }

    this.__init__(effects, options);
};

MochiKit.Visual.Parallel.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Parallel.prototype, {
    /***

    Run multiple effects at the same time.

    ***/
    __init__: function (effects, options) {
        this.effects = effects || [];
        this.start(options);
    },

    /** @id MochiKit.Visual.Parallel.prototype.update */
    update: function (position) {
        MochiKit.Base.map(function (effect) {
            effect.render(position);
        }, this.effects);
    },

    /** @id MochiKit.Visual.Parallel.prototype.finish */
    finish: function () {
        MochiKit.Base.map(function (effect) {
            effect.finalize();
        }, this.effects);
    }
});

/** @id MochiKit.Visual.Opacity */
MochiKit.Visual.Opacity = function (element, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, options);
    }
    this.__init__(element, options);
};

MochiKit.Visual.Opacity.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Opacity.prototype, {
    /***

    Change the opacity of an element.

    @param options: 'from' and 'to' change the starting and ending opacities.
    Must be between 0.0 and 1.0. Default to current opacity and 1.0.

    ***/
    __init__: function (element, /* optional */options) {
        var b = MochiKit.Base;
        var s = MochiKit.Style;
        this.element = MochiKit.DOM.getElement(element);
        // make this work on IE on elements without 'layout'
        if (this.element.currentStyle &&
            (!this.element.currentStyle.hasLayout)) {
            s.setStyle(this.element, {zoom: 1});
        }
        options = b.update({
            from: s.getStyle(this.element, 'opacity') || 0.0,
            to: 1.0
        }, options || {});
        this.start(options);
    },

    /** @id MochiKit.Visual.Opacity.prototype.update */
    update: function (position) {
        MochiKit.Style.setStyle(this.element, {'opacity': position});
    }
});

/**  @id MochiKit.Visual.Move.prototype */
MochiKit.Visual.Move = function (element, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, options);
    }
    this.__init__(element, options);
};

MochiKit.Visual.Move.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Move.prototype, {
    /***

    Move an element between its current position to a defined position

    @param options: 'x' and 'y' for final positions, default to 0, 0.

    ***/
    __init__: function (element, /* optional */options) {
        this.element = MochiKit.DOM.getElement(element);
        options = MochiKit.Base.update({
            x: 0,
            y: 0,
            mode: 'relative'
        }, options || {});
        this.start(options);
    },

    /** @id MochiKit.Visual.Move.prototype.setup */
    setup: function () {
        // Bug in Opera: Opera returns the 'real' position of a static element
        // or relative element that does not have top/left explicitly set.
        // ==> Always set top and left for position relative elements in your
        // stylesheets (to 0 if you do not need them)
        MochiKit.DOM.makePositioned(this.element);

        var s = this.element.style;
        var originalVisibility = s.visibility;
        var originalDisplay = s.display;
        if (originalDisplay == 'none') {
            s.visibility = 'hidden';
            s.display = '';
        }

        this.originalLeft = parseFloat(MochiKit.Style.getStyle(this.element, 'left') || '0');
        this.originalTop = parseFloat(MochiKit.Style.getStyle(this.element, 'top') || '0');

        if (this.options.mode == 'absolute') {
            // absolute movement, so we need to calc deltaX and deltaY
            this.options.x -= this.originalLeft;
            this.options.y -= this.originalTop;
        }
        if (originalDisplay == 'none') {
            s.visibility = originalVisibility;
            s.display = originalDisplay;
        }
    },

    /** @id MochiKit.Visual.Move.prototype.update */
    update: function (position) {
        MochiKit.Style.setStyle(this.element, {
            left: Math.round(this.options.x * position + this.originalLeft) + 'px',
            top: Math.round(this.options.y * position + this.originalTop) + 'px'
        });
    }
});

/** @id MochiKit.Visual.Scale */
MochiKit.Visual.Scale = function (element, percent, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, percent, options);
    }
    this.__init__(element, percent, options);
};

MochiKit.Visual.Scale.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Scale.prototype, {
    /***

    Change the size of an element.

    @param percent: final_size = percent*original_size

    @param options: several options changing scale behaviour

    ***/
    __init__: function (element, percent, /* optional */options) {
        this.element = MochiKit.DOM.getElement(element);
        options = MochiKit.Base.update({
            scaleX: true,
            scaleY: true,
            scaleContent: true,
            scaleFromCenter: false,
            scaleMode: 'box',  // 'box' or 'contents' or {} with provided values
            scaleFrom: 100.0,
            scaleTo: percent
        }, options || {});
        this.start(options);
    },

    /** @id MochiKit.Visual.Scale.prototype.setup */
    setup: function () {
        this.restoreAfterFinish = this.options.restoreAfterFinish || false;
        this.elementPositioning = MochiKit.Style.getStyle(this.element,
                                                        'position');

        var ma = MochiKit.Base.map;
        var b = MochiKit.Base.bind;
        this.originalStyle = {};
        ma(b(function (k) {
                this.originalStyle[k] = this.element.style[k];
            }, this), ['top', 'left', 'width', 'height', 'fontSize']);

        this.originalTop = this.element.offsetTop;
        this.originalLeft = this.element.offsetLeft;

        var fontSize = MochiKit.Style.getStyle(this.element,
                                             'font-size') || '100%';
        ma(b(function (fontSizeType) {
            if (fontSize.indexOf(fontSizeType) > 0) {
                this.fontSize = parseFloat(fontSize);
                this.fontSizeType = fontSizeType;
            }
        }, this), ['em', 'px', '%']);

        this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;

        if (/^content/.test(this.options.scaleMode)) {
            this.dims = [this.element.scrollHeight, this.element.scrollWidth];
        } else if (this.options.scaleMode == 'box') {
            this.dims = [this.element.offsetHeight, this.element.offsetWidth];
        } else {
            this.dims = [this.options.scaleMode.originalHeight,
                         this.options.scaleMode.originalWidth];
        }
    },

    /** @id MochiKit.Visual.Scale.prototype.update */
    update: function (position) {
        var currentScale = (this.options.scaleFrom/100.0) +
                           (this.factor * position);
        if (this.options.scaleContent && this.fontSize) {
            MochiKit.Style.setStyle(this.element, {
                fontSize: this.fontSize * currentScale + this.fontSizeType
            });
        }
        this.setDimensions(this.dims[0] * currentScale,
                           this.dims[1] * currentScale);
    },

    /** @id MochiKit.Visual.Scale.prototype.finish */
    finish: function () {
        if (this.restoreAfterFinish) {
            MochiKit.Style.setStyle(this.element, this.originalStyle);
        }
    },

    /** @id MochiKit.Visual.Scale.prototype.setDimensions */
    setDimensions: function (height, width) {
        var d = {};
        var r = Math.round;
        if (/MSIE/.test(navigator.userAgent)) {
            r = Math.ceil;
        }
        if (this.options.scaleX) {
            d.width = r(width) + 'px';
        }
        if (this.options.scaleY) {
            d.height = r(height) + 'px';
        }
        if (this.options.scaleFromCenter) {
            var topd = (height - this.dims[0])/2;
            var leftd = (width - this.dims[1])/2;
            if (this.elementPositioning == 'absolute') {
                if (this.options.scaleY) {
                    d.top = this.originalTop - topd + 'px';
                }
                if (this.options.scaleX) {
                    d.left = this.originalLeft - leftd + 'px';
                }
            } else {
                if (this.options.scaleY) {
                    d.top = -topd + 'px';
                }
                if (this.options.scaleX) {
                    d.left = -leftd + 'px';
                }
            }
        }
        MochiKit.Style.setStyle(this.element, d);
    }
});

/** @id MochiKit.Visual.Highlight */
MochiKit.Visual.Highlight = function (element, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, options);
    }
    this.__init__(element, options);
};

MochiKit.Visual.Highlight.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Highlight.prototype, {
    /***

    Highlight an item of the page.

    @param options: 'startcolor' for choosing highlighting color, default
    to '#ffff99'.

    ***/
    __init__: function (element, /* optional */options) {
        this.element = MochiKit.DOM.getElement(element);
        options = MochiKit.Base.update({
            startcolor: '#ffff99'
        }, options || {});
        this.start(options);
    },

    /** @id MochiKit.Visual.Highlight.prototype.setup */
    setup: function () {
        var b = MochiKit.Base;
        var s = MochiKit.Style;
        // Prevent executing on elements not in the layout flow
        if (s.getStyle(this.element, 'display') == 'none') {
            this.cancel();
            return;
        }
        // Disable background image during the effect
        this.oldStyle = {
            backgroundImage: s.getStyle(this.element, 'background-image')
        };
        s.setStyle(this.element, {
            backgroundImage: 'none'
        });

        if (!this.options.endcolor) {
            this.options.endcolor =
                MochiKit.Color.Color.fromBackground(this.element).toHexString();
        }
        if (b.isUndefinedOrNull(this.options.restorecolor)) {
            this.options.restorecolor = s.getStyle(this.element,
                                                   'background-color');
        }
        // init color calculations
        this._base = b.map(b.bind(function (i) {
            return parseInt(
                this.options.startcolor.slice(i*2 + 1, i*2 + 3), 16);
        }, this), [0, 1, 2]);
        this._delta = b.map(b.bind(function (i) {
            return parseInt(this.options.endcolor.slice(i*2 + 1, i*2 + 3), 16)
                - this._base[i];
        }, this), [0, 1, 2]);
    },

    /** @id MochiKit.Visual.Highlight.prototype.update */
    update: function (position) {
        var m = '#';
        MochiKit.Base.map(MochiKit.Base.bind(function (i) {
            m += MochiKit.Color.toColorPart(Math.round(this._base[i] +
                                            this._delta[i]*position));
        }, this), [0, 1, 2]);
        MochiKit.Style.setStyle(this.element, {
            backgroundColor: m
        });
    },

    /** @id MochiKit.Visual.Highlight.prototype.finish */
    finish: function () {
        MochiKit.Style.setStyle(this.element,
            MochiKit.Base.update(this.oldStyle, {
                backgroundColor: this.options.restorecolor
        }));
    }
});

/** @id MochiKit.Visual.ScrollTo */
MochiKit.Visual.ScrollTo = function (element, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, options);
    }
    this.__init__(element, options);
};

MochiKit.Visual.ScrollTo.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.ScrollTo.prototype, {
    /***

    Scroll to an element in the page.

    ***/
    __init__: function (element, /* optional */options) {
        this.element = MochiKit.DOM.getElement(element);
        this.start(options || {});
    },

    /** @id MochiKit.Visual.ScrollTo.prototype.setup */
    setup: function () {
        var p = MochiKit.Position;
        p.prepare();
        var offsets = p.cumulativeOffset(this.element);
        if (this.options.offset) {
            offsets.y += this.options.offset;
        }
        var max;
        if (window.innerHeight) {
            max = window.innerHeight - window.height;
        } else if (document.documentElement &&
                   document.documentElement.clientHeight) {
            max = document.documentElement.clientHeight -
                  document.body.scrollHeight;
        } else if (document.body) {
            max = document.body.clientHeight - document.body.scrollHeight;
        }
        this.scrollStart = p.windowOffset.y;
        this.delta = (offsets.y > max ? max : offsets.y) - this.scrollStart;
    },

    /** @id MochiKit.Visual.ScrollTo.prototype.update */
    update: function (position) {
        var p = MochiKit.Position;
        p.prepare();
        window.scrollTo(p.windowOffset.x, this.scrollStart + (position * this.delta));
    }
});

MochiKit.Visual.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

MochiKit.Visual.Morph = function (element, options) {
    var cls = arguments.callee;
    if (!(this instanceof cls)) {
        return new cls(element, options);
    }
    this.__init__(element, options);
};

MochiKit.Visual.Morph.prototype = new MochiKit.Visual.Base();

MochiKit.Base.update(MochiKit.Visual.Morph.prototype, {
    /***

    Morph effect: make a transformation from current style to the given style,
    automatically making a transition between the two.

    ***/
    __init__: function (element, /* optional */options) {
        this.element = MochiKit.DOM.getElement(element);
        this.start(options || {});
    },

    /** @id MochiKit.Visual.Morph.prototype.setup */
    setup: function () {
        var b = MochiKit.Base;
        var style = this.options.style;
        this.styleStart = {};
        this.styleEnd = {};
        this.units = {};
        var value, unit;
        for (var s in style) {
            value = style[s];
            s = b.camelize(s);
            if (MochiKit.Visual.CSS_LENGTH.test(value)) {
                var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
                value = parseFloat(components[1]);
                unit = (components.length == 3) ? components[2] : null;
                this.styleEnd[s] = value;
                this.units[s] = unit;
                value = MochiKit.Style.getStyle(this.element, s);
                components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
                value = parseFloat(components[1]);
                this.styleStart[s] = value;
            } else {
                var c = MochiKit.Color.Color;
                value = c.fromString(value);
                if (value) {
                    this.units[s] = "color";
                    this.styleEnd[s] = value.toHexString();
                    value = MochiKit.Style.getStyle(this.element, s);
                    this.styleStart[s] = c.fromString(value).toHexString();

                    this.styleStart[s] = b.map(b.bind(function (i) {
                        return parseInt(
                            this.styleStart[s].slice(i*2 + 1, i*2 + 3), 16);
                    }, this), [0, 1, 2]);
                    this.styleEnd[s] = b.map(b.bind(function (i) {
                        return parseInt(
                            this.styleEnd[s].slice(i*2 + 1, i*2 + 3), 16);
                    }, this), [0, 1, 2]);
                }
            }
        }
    },

    /** @id MochiKit.Visual.Morph.prototype.update */
    update: function (position) {
        var value;
        for (var s in this.styleStart) {
            if (this.units[s] == "color") {
                var m = '#';
                var start = this.styleStart[s];
                var end = this.styleEnd[s];
                MochiKit.Base.map(MochiKit.Base.bind(function (i) {
                    m += MochiKit.Color.toColorPart(Math.round(start[i] +
                                                    (end[i] - start[i])*position));
                }, this), [0, 1, 2]);
                this.element.style[s] = m;
            } else {
                value = this.styleStart[s] + Math.round((this.styleEnd[s] - this.styleStart[s]) * position * 1000) / 1000 + this.units[s];
                this.element.style[s] = value;
            }
        }
    }
});

/***

Combination effects.

***/

/** @id MochiKit.Visual.fade */
MochiKit.Visual.fade = function (element, /* optional */ options) {
    /***

    Fade a given element: change its opacity and hide it in the end.

    @param options: 'to' and 'from' to change opacity.

    ***/
    var s = MochiKit.Style;
    var oldOpacity = s.getStyle(element, 'opacity');
    options = MochiKit.Base.update({
        from: s.getStyle(element, 'opacity') || 1.0,
        to: 0.0,
        afterFinishInternal: function (effect) {
            if (effect.options.to !== 0) {
                return;
            }
            s.hideElement(effect.element);
            s.setStyle(effect.element, {'opacity': oldOpacity});
        }
    }, options || {});
    return new MochiKit.Visual.Opacity(element, options);
};

/** @id MochiKit.Visual.appear */
MochiKit.Visual.appear = function (element, /* optional */ options) {
    /***

    Make an element appear.

    @param options: 'to' and 'from' to change opacity.

    ***/
    var s = MochiKit.Style;
    var v = MochiKit.Visual;
    options = MochiKit.Base.update({
        from: (s.getStyle(element, 'display') == 'none' ? 0.0 :
               s.getStyle(element, 'opacity') || 0.0),
        to: 1.0,
        // force Safari to render floated elements properly
        afterFinishInternal: function (effect) {
            v.forceRerendering(effect.element);
        },
        beforeSetupInternal: function (effect) {
            s.setStyle(effect.element, {'opacity': effect.options.from});
            s.showElement(effect.element);
        }
    }, options || {});
    return new v.Opacity(element, options);
};

/** @id MochiKit.Visual.puff */
MochiKit.Visual.puff = function (element, /* optional */ options) {
    /***

    'Puff' an element: grow it to double size, fading it and make it hidden.

    ***/
    var s = MochiKit.Style;
    var v = MochiKit.Visual;
    element = MochiKit.DOM.getElement(element);
    var oldStyle = {
        position: s.getStyle(element, 'position'),
        top: element.style.top,
        left: element.style.left,
        width: element.style.width,
        height: element.style.height,
        opacity: s.getStyle(element, 'opacity')
    };
    options = MochiKit.Base.update({
        beforeSetupInternal: function (effect) {
            MochiKit.Position.absolutize(effect.effects[0].element);
        },
        afterFinishInternal: function (effect) {
            s.hideElement(effect.effects[0].element);
            s.setStyle(effect.effects[0].element, oldStyle);
        }
    }, options || {});
    return new v.Parallel(
        [new v.Scale(element, 200,
            {sync: true, scaleFromCenter: true,
             scaleContent: true, restoreAfterFinish: true}),
         new v.Opacity(element, {sync: true, to: 0.0 })],
        options);
};

/** @id MochiKit.Visual.blindUp */
MochiKit.Visual.blindUp = function (element, /* optional */ options) {
    /***

    Blind an element up: change its vertical size to 0.

    ***/
    var d = MochiKit.DOM;
    element = d.getElement(element);
    var elemClip = d.makeClipping(element);
    options = MochiKit.Base.update({
        scaleContent: false,
        scaleX: false,
        restoreAfterFinish: true,
        afterFinishInternal: function (effect) {
            MochiKit.Style.hideElement(effect.element);
            d.undoClipping(effect.element, elemClip);
        }
    }, options || {});

    return new MochiKit.Visual.Scale(element, 0, options);
};

/** @id MochiKit.Visual.blindDown */
MochiKit.Visual.blindDown = function (element, /* optional */ options) {
    /***

    Blind an element down: restore its vertical size.

    ***/
    var d = MochiKit.DOM;
    var s = MochiKit.Style;
    element = d.getElement(element);
    var elementDimensions = s.getElementDimensions(element);
    var elemClip;
    options = MochiKit.Base.update({
        scaleContent: false,
        scaleX: false,
        scaleFrom: 0,
        scaleMode: {originalHeight: elementDimensions.h,
                    originalWidth: elementDimensions.w},
        restoreAfterFinish: true,
        afterSetupInternal: function (effect) {
            elemClip = d.makeClipping(effect.element);
            s.setStyle(effect.element, {height: '0px'});
            s.showElement(effect.element);
        },
        afterFinishInternal: function (effect) {
            d.undoClipping(effect.element, elemClip);
        }
    }, options || {});
    return new MochiKit.Visual.Scale(element, 100, options);
};

/** @id MochiKit.Visual.switchOff */
MochiKit.Visual.switchOff = function (element, /* optional */ options) {
    /***

    Apply a switch-off-like effect.

    ***/
    var d = MochiKit.DOM;
    element = d.getElement(element);
    var oldOpacity = MochiKit.Style.getStyle(element, 'opacity');
    var elemClip;
    options = MochiKit.Base.update({
        duration: 0.3,
        scaleFromCenter: true,
        scaleX: false,
        scaleContent: false,
        restoreAfterFinish: true,
        beforeSetupInternal: function (effect) {
            d.makePositioned(effect.element);
            elemClip = d.makeClipping(effect.element);
        },
        afterFinishInternal: function (effect) {
            MochiKit.Style.hideElement(effect.element);
            d.undoClipping(effect.element, elemClip);
            d.undoPositioned(effect.element);
            MochiKit.Style.setStyle(effect.element, {'opacity': oldOpacity});
        }
    }, options || {});
    var v = MochiKit.Visual;
    return new v.appear(element, {
        duration: 0.4,
        from: 0,
        transition: v.Transitions.flicker,
        afterFinishInternal: function (effect) {
            new v.Scale(effect.element, 1, options);
        }
    });
};

/** @id MochiKit.Visual.dropOut */
MochiKit.Visual.dropOut = function (element, /* optional */ options) {
    /***

    Make an element fall and disappear.

    ***/
    var d = MochiKit.DOM;
    var s = MochiKit.Style;
    element = d.getElement(element);
    var oldStyle = {
        top: s.getStyle(element, 'top'),
        left: s.getStyle(element, 'left'),
        opacity: s.getStyle(element, 'opacity')
    };

    options = MochiKit.Base.update({
        duration: 0.5,
        distance: 100,
        beforeSetupInternal: function (effect) {
            d.makePositioned(effect.effects[0].element);
        },
        afterFinishInternal: function (effect) {
            s.hideElement(effect.effects[0].element);
            d.undoPositioned(effect.effects[0].element);
            s.setStyle(effect.effects[0].element, oldStyle);
        }
    }, options || {});
    var v = MochiKit.Visual;
    return new v.Parallel(
        [new v.Move(element, {x: 0, y: options.distance, sync: true}),
         new v.Opacity(element, {sync: true, to: 0.0})],
        options);
};

/** @id MochiKit.Visual.shake */
MochiKit.Visual.shake = function (element, /* optional */ options) {
    /***

    Move an element from left to right several times.

    ***/
    var d = MochiKit.DOM;
    var v = MochiKit.Visual;
    var s = MochiKit.Style;
    element = d.getElement(element);
    options = MochiKit.Base.update({
        x: -20,
        y: 0,
        duration: 0.05,
        afterFinishInternal: function (effect) {
            d.undoPositioned(effect.element);
            s.setStyle(effect.element, oldStyle);
        }
    }, options || {});
    var oldStyle = {
        top: s.getStyle(element, 'top'),
        left: s.getStyle(element, 'left') };
        return new v.Move(element,
          {x: 20, y: 0, duration: 0.05, afterFinishInternal: function (effect) {
        new v.Move(effect.element,
          {x: -40, y: 0, duration: 0.1, afterFinishInternal: function (effect) {
        new v.Move(effect.element,
           {x: 40, y: 0, duration: 0.1, afterFinishInternal: function (effect) {
        new v.Move(effect.element,
          {x: -40, y: 0, duration: 0.1, afterFinishInternal: function (effect) {
        new v.Move(effect.element,
           {x: 40, y: 0, duration: 0.1, afterFinishInternal: function (effect) {
        new v.Move(effect.element, options
        ) }}) }}) }}) }}) }});
};

/** @id MochiKit.Visual.slideDown */
MochiKit.Visual.slideDown = function (element, /* optional */ options) {
    /***

    Slide an element down.
    It needs to have the content of the element wrapped in a container
    element with fixed height.

    ***/
    var d = MochiKit.DOM;
    var b = MochiKit.Base;
    var s = MochiKit.Style;
    element = d.getElement(element);
    if (!element.firstChild) {
        throw "MochiKit.Visual.slideDown must be used on a element with a child";
    }
    d.removeEmptyTextNodes(element);
    var oldInnerBottom = s.getStyle(element.firstChild, 'bottom') || 0;
    var elementDimensions = s.getElementDimensions(element);
    var elemClip;
    options = b.update({
        scaleContent: false,
        scaleX: false,
        scaleFrom: 0,
        scaleMode: {originalHeight: elementDimensions.h,
                    originalWidth: elementDimensions.w},
        restoreAfterFinish: true,
        afterSetupInternal: function (effect) {
            d.makePositioned(effect.element);
            d.makePositioned(effect.element.firstChild);
            if (/Opera/.tes