/******************************************************************************

PROJECT:        MudSketch, Simple CANVAS Sketching tool
FILE:           com.mudcorp.MudSketch.js
VERSION:        1.0
DATE:           07/10/2007
REQUIRES:       prototype.js >= 1.5.1

Copyright (c) 2007 by the Massachusetts Institute of Technology.
All rights reserved.

Developed by Takashi Okamoto (mud) at the Media Laboratory, MIT,
Cambridge, Massachusetts.
http://plw.media.mit.edu/people/mud

For use by Physical Language Workshop.

This distribution is approved by Frank Moss,
Director of the Media Laboratory, MIT.

Permission to use, copy, or modify this software and its documentation for
educational and research purposes only and without fee is hereby granted,
provided that this copyright notice and the original authors' names appear on
all copies and supporting documentation. If individual files are separated from
this distribution directory structure, this copyright notice must be included.
For any other uses of this software, in original or modified form, including
but not limited to distribution in whole or in part, specific prior permission
must be obtained from MIT. These programs shall not be used, rewritten, or
adapted as the basis of a commercial software or hardware product without
first obtaining appropriate licenses from MIT. MIT makes no representations
about the suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
  
******************************************************************************/

///////////////////////////////////////////////////////////////////////////////
// NAMESPACE
var com;
if (!com)
  com = {};
else if (typeof com != "object")
  throw new Error("com already exists and is not an object");

if (!com.mudcorp)
  com.mudcorp = {};
else if (typeof com.mudcorp != "object")
  throw new Error("com.mudcorp already exists and is not an object");

if (com.mudcorp.MudSketch)
  throw new Error("com.mudcorp.MudSketch already exists");

///////////////////////////////////////////////////////////////////////////////
// LOAD REQUIRED - this comes from scriptaculous loader
com.mudcorp.MudSketch = {
  Version: '1.0',
  
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  
  load: function() {
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       parseFloat(Prototype.Version.split(".")[0] + "." +
                  Prototype.Version.split(".")[1] + Prototype.Version.split(".")[2][0]) < 1.51)
       throw("com.mudcorp.MudSketch requires the Prototype JavaScript framework >= 1.5.1");
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/MudSketch\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/MudSketch\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'Canvas,Encoder,Decoder,Inspector,Model/Model,Model/Brush,Model/Line,Model/Point,Tool/Tool,Tool/Brush').split(',').each(
       function(include) { com.mudcorp.MudSketch.require(path+include+'.js') });
    });
  },
  
  // Calls constructor for MudSketch.Canvas()
  create: function(canvas, drawing_id, type) {
    return new com.mudcorp.MudSketch.Canvas(canvas, drawing_id, type);
  }
}

com.mudcorp.MudSketch.load();

///////////////////////////////////////////////////////////////////////////////
// CONSTANTS
com.mudcorp.MudSketch.TOOLS = {
  Brush:     0,
  Rectangle: 1,
  Circle:    2
};

com.mudcorp.MudSketch.DEFAULT_BACKGROUND_COLOR = '#ffffff';
com.mudcorp.MudSketch.DEFAULT_BRUSH_SIZE  = 5;
com.mudcorp.MudSketch.DEFAULT_BRUSH_COLOR = {
  red:      0,
  green:    0,
  blue:     0,
  alpha:    1
}
com.mudcorp.MudSketch.MAX_BRUSH_SIZE = 20;

///////////////////////////////////////////////////////////////////////////////
// Utility Functions
com.mudcorp.MudSketch.Utility = {
  
  transform_offset: function(reference_object, position) {
    var offset = Position.cumulativeOffset(reference_object);
    return [position[0]-offset[0], position[1]-offset[1]];
  },
  
  create_status_container: function() {
    if (!$('status-wrapper')) {
      var status = this.generate_status();
      if (!$('content'))
        throw new Error("Cannot add status div since #content does not exist.");
        
      $('content').appendChild(status);

      this.draggable = new Draggable('status-wrapper', {
        handle: 'status-handle',
        starteffect: function() {},
        endeffect:   function() {}
      });
      
      Event.observe($('status-close'), 'mousedown', function(evt) {
          $('status-close').src = "/images/ui_close_down.png";
          Event.stop(evt);
      });
      Event.observe($('status-close'), 'mouseup', function(evt) {
          $('status-close').src = "/images/ui_close.png";
          Event.stop(evt);
      });
      Event.observe($('status-close'), 'mouseout', function(evt) {
          $('status-close').src = "/images/ui_close.png";
          Event.stop(evt);
      });
      Event.observe($('status-close'), 'click', function(evt) {
          com.mudcorp.MudSketch.Utility.hide_status();
      });
    }
  },
  
  generate_status: function() {
    //return com.mudcorp.MudSketch.Utility.STATUS_SNIPPET;
    var status_wrapper = document.createElement('div');
    status_wrapper.setAttribute('id', 'status-wrapper');
    status_wrapper.setStyle({position: 'absolute', display: 'none'});
    
    var status_handle = document.createElement('div');
    status_handle.addClassName('panel_handle');
    status_handle.innerHTML = '\
      <div class="panel_close"><img src="/images/ui_close.png" id="status-close" /></div>\
      <div id="status_title" class="panel_title">Status</div>\
    ';
    
    var status_content = document.createElement('div');
    status_content.setAttribute('id', 'status-content');
    status_content.addClassName('panel_content');
    
    status_wrapper.appendChild(status_handle);
    status_wrapper.appendChild(status_content);
    
    return status_wrapper;
  },
  
  status: function() {
    if (!$('status-wrapper')) {
      this.create_status_container();
    }
    return this;
  },
  
  update_status: function(content) {
    $('status-content').update(content);
    this.show_status();
  },
  
  update_status_title: function(title) {
    $('status_title').update(title);
  },
  
  hide_status: function() {
    if ($('status-wrapper').visible()) {
      new Effect.Fade('status-wrapper', {
        duration: 0.2
      })
    }
  },
  
  show_status: function() {
    if ($('status-wrapper').visible()) return;
    new Effect.Appear('status-wrapper', { duration: 0.2 });
  }
  
}