/*
Opendots Image Control

controls/image.js

Copyright (c) Gareth Hadfield 2008
*/

function init_image_control(aDot){
  init_image_control_main(aDot);
}

function init_image_control_main(aDot){
  var IMAGE_PREFIX = "image_";

  aDot.adjust_size = bind(aDot, function(){
    this.setCSSAttribute("width", this.sizeImage.width+"px");
    this.setCSSAttribute("height", this.sizeImage.height+"px");
  });

  aDot.init_image = bind(aDot, function(){
    // create image
    var aSrc = this.getAttributeText(IMAGE_PREFIX + "src");
    var aAlt = this.getAttributeText(IMAGE_PREFIX + "alt");

    if(aSrc==undefined){
      aSrc="";
    }

    if(aAlt==undefined){
      aAlt="";
    }

    if((aSrc != "") && (aSrc != undefined)){
      this.sat("content", "<img src='"+aSrc+"' alt='"+aAlt+"' style='width:100%;height:100%;'>");
    }
  });

  aDot.init_image();

  // custom set attribute function
  aDot.setImageAttribute = bind(aDot, function(aName, aValue){
    this.init_image();
  });

  aDot.setImage = bind(aDot, function(aUrl){
    this.setAttributeText(IMAGE_PREFIX+"src", aUrl);
  });

  // add custom attributes
  aDot.addCustomAttribute(IMAGE_PREFIX+"alt", aDot.setImageAttribute);
  aDot.addCustomAttribute(IMAGE_PREFIX+"src", aDot.setImageAttribute);

  aDot.selectImage = bind(aDot, function(){
    this.imageDlg = new TImageDialog("Select Image ("+this.id+")", this.OnOk, "images", undefined, undefined, "*");
    this.imageDlg.execute();
  });

  aDot.doImageSize = bind(aDot, function(aFilename){
    if(aFilename==undefined){
      aFilename = this.gat(IMAGE_PREFIX+"src");
    }

    var aImage = new Image();
    this.sizeImage = aImage;
    aImage.onload = this.adjust_size;
    aImage.src = aFilename;
  });

  aDot.resetSize = bind(aDot, function(){
    this.doImageSize();
  });

  aDot.OnOk = bind(aDot, function(aFilename){
    this.doImageSize(HTTP_RMD+aFilename);

    this.setImage(HTTP_RMD+aFilename);

    delete this.imageDlg;
  });

  aDot.addCustomMenuItem("Select Image", bind(aDot, function(){aDot.selectImage();}), "Browse for image file");
  aDot.addCustomMenuItem("Reset Size", bind(aDot, function(){aDot.resetSize();}), "Set the image size to the size of the original.");

}

