 /*
  AGORA_IMAGES.JS - Javascript for remote scripting support in T.A.O. Agora image plugin.

  Dependencies: jQuery

  Copyright©2007,2008 Eugene Arenhaus (http://chiseledrocks.com) for T.A.O. LLC
 */

function cuttermouseup(event) { cutter.MouseUp(event); }
function cuttermousemove(event) { cutter.MouseMove(event); }
function cuttersubmit(event) { cutter.SubmitCutter(event); }

function ThumbnailCutter(form_id) {
 this.Move = function(x,y) {
  this.X = x; this.Y = y;
  this.frame.css('left', x + 'px');
  this.frame.css('top',  y + 'px');
 }

 this.Resize = function(w,h) {
  if (this.W != w) {
   this.W = w;
   var iw = w-this.fL-this.fR;
   this.frame.css('width', w + 'px');
   this.divLMR.css('width', w + 'px');
   this.divTransparency.css('width', w + 'px');
   this.divM.css('width', iw + 'px');
   this.divTransparency.css('width', iw + 'px');
  }
  if (this.H != h) {
   this.H = h;
   var ih = h-this.fT-this.fB;
   this.frame.css('height', h + 'px');
   this.divLMR.css('height', ih+2 + 'px');
   this.divL.css('height', ih+2 + 'px');
   this.divR.css('height', ih+2 + 'px');
   this.divM.css('height', ih + 'px');
   this.divTransparency.css('height', ih + 'px');
  }
 }

 this.UpdatePreview = function() {
  var x = this.X-this.minL; var y = this.Y-this.minT;
  var w = this.divM.width(); var h = this.divM.height();

  var srcw = this.srcimageW; var srch = this.srcimageH;

  var scalex = this.thumbW / w; var scaley = this.thumbH / h;

  var imgx = -Math.round(x * scalex); var imgy = -Math.round(y * scaley);
  var imgw = Math.round(srcw * scalex); var imgh = Math.round(srch * scaley);

  var clipx = -imgx; var clipy = -imgy;
  var clipw = Math.round(w * scalex); var cliph = Math.round(h * scaley);

  var clipL = clipx; var clipT = clipy; var clipR = clipx+clipw; var clipB = clipy+cliph;

  this.imgPreview.css( { 'left': (this.X+this.fL+imgx)+'px', 'top': (this.Y+this.fT+imgy)+'px', 'width': imgw+'px', 'height': imgh+'px', 
    'clip': 'rect('+(clipT)+'px '+(clipR)+'px '+(clipB)+'px '+(clipL)+'px)'  } );
 }

 this.UpdateForm = function() {
  this.form_source_x.val(this.X-this.minL);
  this.form_source_y.val(this.Y-this.minT);
  this.form_source_width.val(this.W-this.fL-this.fR);
  this.form_source_height.val(this.H-this.fT-this.fB);
 }

 this.MouseDown = function(actn, e) {
  this.dragging = actn;
  if (actn) {
   this.dragOriginX = e.clientX;
   this.dragOriginY = e.clientY;

   $('body').mouseup(   cuttermouseup );
   $('body').mousemove( cuttermousemove );
  }
 }

 this.MouseMove = function(e) {
 if (this.dragging) {
  var dx = e.clientX-this.dragOriginX; var dy = e.clientY-this.dragOriginY;
  var offset = this.frame.offset();
  var x = offset.left; var y = offset.top;
  var w = this.frame.width(); var h = this.frame.height();
  var resize = false;
  var newx = 0; var newy = 0; var neww = 0; var newiw = 0; var newih = 0; var newh = 0;
  switch (this.dragging) {
   case "move":
    newx = x + dx; newy = y + dy;
    // constraints
    if (newx < this.minL) newx = this.minL;
    if (newx+this.W > this.maxR) newx = this.maxR - this.W;
    if (newy < this.minT) newy = this.minT;
    if (newy+this.H > this.maxB) newy = this.maxB - this.H;
    this.Move(newx, newy);
    break;
   case "sizeL":
    resize = true;
    newx = x + dx;
    newy = y;
    neww = w - dx;
    newiw = neww-this.fL-this.fR;
    newih = Math.round(newiw * this.q);
    newh = newih+this.fT+this.fB;
    break;
   case "sizeR":
    resize = true;
    newx = x;
    newy = y;
    neww = w + dx;
    newiw = neww-this.fL-this.fR;
    newih = Math.round(newiw * this.q);
    newh = newih+this.fT+this.fB;
    break;
   case "sizeT":
    resize = true;
    newx = x;
    newy = y + dy;
    newh = h - dy;
    newih = newh-this.fT-this.fB;
    newiw = Math.round(newih / this.q);
    neww = newiw+this.fL+this.fR;
    break;
   case "sizeB":
    resize = true;
    newx = x;
    newy = y;
    newh = h + dy;
    newih = newh-this.fT-this.fB;
    newiw = Math.round(newih / this.q);
    neww = newiw+this.fL+this.fR;
    break;
  }

  if (resize) {
   // find the possible fit
   var delta = 0;
   // horizontal size constraint
   if ( (delta = neww - this.maxW) > 0) { newiw -= delta; neww -= delta; x += delta; } // if it is too big, measure by the outer sizes
   if ( (delta = this.thumbW - newiw) > 0) { newiw += delta; neww += delta; x -= delta; } // if it is too small, measure by the inner sizes
   newih = (newiw) * this.q;
   newh = newih+this.fT+this.fB;
   // vertical size constraint
   if ( (delta = neww - this.maxW) > 0) { newiw -= delta; neww -= delta; x += delta; } // if it is too big, measure by the outer sizes
   if ( (delta = this.thumbW - newiw) > 0) { newiw += delta; neww += delta; x -= delta; } // if it is too small, measure by the inner sizes
   newiw = (newih) / this.q;
   neww = newiw+this.fL+this.fR;
   // positional constraint
   if (newx < this.minL) newx = this.minL;
   if (newx+neww > this.maxR) newx = this.maxR - neww;
   if (newy < this.minT) newy = this.minT;
   if (newy+newh > this.maxB) newy = this.maxB - newh;

   this.Move(newx, newy);
   this.Resize(neww, newh);
  }

  this.UpdatePreview();
  this.UpdateForm();

  this.dragOriginX = e.clientX;   this.dragOriginY = e.clientY;
 }
}

 this.MouseUp = function(e) {
  this.dragging = false;
  $('body').unbind('mouseup',   cuttermouseup );
  $('body').unbind('mousemove', cuttermousemove );
 }

 this.GetRealXY = function(obj) { // gets the actual page-related coordinates of a DOM object
  // to do: use clientLeft, clientTop when available
  var currLeft = currTop = 0;
  if (obj.offsetParent) do { // fall back to PPK (www.quirksmode.org) technique in browsers that do not implement clientX/Y (Firefox)
   currLeft += obj.offsetLeft;
   currTop += obj.offsetTop;
  } while (obj = obj.offsetParent);
  return [ currLeft, currTop];
 }


 this.SubmitCutter = function(e) { $("form#"+this.host_form_id+' input[type="submit"][name="agora_thumbnail_generate"]').click(); }

 var main_image = $("img#MainImage").get(0);
 if (main_image) {
  // image position
//  var ix = main_image.x; var iy = main_image.y;
  var ix = iy = 0; [ix,iy] = this.GetRealXY(main_image);
  var iw = main_image.width; var ih = main_image.height;
  this.srcimageW = iw; this.srcimageH = ih;
  //
  this.host_form_id = form_id;
  var host_form = $("form#"+form_id);
  //
  var ft = 20; var fb = 6; var fl = 6; var fr = 6; // frame widths
  this.fL = fl; this.fT = ft; this.fR = fr;this.fB = fb;
  this.minL = this.X = ix-fl; this.minT = this.Y = iy-ft;
  this.maxR = ix+iw+fr; this.maxB = iy+ih+fb;
  this.maxW = iw+fl+fr; this.maxH = ih+ft+fb;
  //
  this.thumbW = parseInt( host_form.find('input[name="agora_thumbnail_width"]').val() );
  this.thumbH = parseInt( host_form.find('input[name="agora_thumbnail_height"]').val() );
//  this.thumbW = 120; this.thumbH = 90; //...
  this.minW = this.thumbW+fl+fr; this.minH = this.thumbH+ft+fb;
  //
  if (this.thumbW >= this.thumbH) ih = Math.round(iw * ( this.thumbH / this.thumbW ));
  else iw = Math.round(ih * ( this.thumbW / this.thumbH ));
  this.q = this.thumbH / this.thumbW; // quotient for resizing constraint
  this.W = fl+iw+fr; this.H = ft+ih+fb;

  var btnY = ft+this.thumbH;

  //
  this.dragging = false;
  this.form_source_x = host_form.find('input[name="source_x"]');
   this.form_source_x.val(ix);
  this.form_source_y = host_form.find('input[name="source_y"]');
   this.form_source_y.val(iy);
  this.form_source_width = host_form.find('input[name="source_width"]');
   this.form_source_width.val(iw);
  this.form_source_height = host_form.find('input[name="source_height"]');
   this.form_source_height.val(ih);
  //
  var cutter_text = 'Drag or resize this frame to define thumbnail area. Then click <a href="#" onClick="return cuttersubmit(event);">Generate</a>.';
  //
  var spacer = '<img src="spacer.gif" width="2" height="2" border="0" />';
  var transparency = '';
  var transp_color = 'background-color: Gray;';
  var transp_opacity = 0.4;
  if ($.browser.msie) transparency = transp_color+' filter:alpha(opacity='+Math.round(transp_opacity*100)+');' // IE hack
  else transparency = transp_color+' opacity: '+transp_opacity+';' // CSS3 standard supported by most other things
  //

  var cutterhtml = '<div style="outline: 1px solid Black; position: absolute; z-index: 1000; left: '+this.minL+'px; top: '+this.minT+'px; width: '+(this.W)+'px; height: '+(this.H)+'px;">'
   +'<div name="T" onMouseDown="cutter.MouseDown('+"'sizeT'"+', event);" style="cursor: n-resize; border: none; margin: 0px; background-color: Yellow; text-align: center; overflow: hidden; line-height: '+(ft)+'px; font-size: 10px; height: '+(ft-1)+'px;">'+cutter_text+'</div>'
   +'<div name="LMR" style="width: '+(this.W)+'px; height: '+(ih+2)+'px;">'
    +'<div name="L" onMouseDown="cutter.MouseDown('+"'sizeL'"+', event);" style="float: left; cursor: w-resize; border: none; margin: 0px; background-color: Yellow; width: '+(fl-1)+'px; height:'+(ih+2)+'px;">'+spacer+'</div>'
    +'<div name="M" onMouseDown="cutter.MouseDown('+"'move'"+', event);" style="cursor: move; float: left; border: 1px solid Black; width: '+(iw)+'px; height:'+(ih)+'px;">'
     +'<div name="Transparency" style="position: absolute; '+transparency+' left: '+fl+'px; top: '+ft+'px; width: '+(iw)+'px; height: '+(ih)+'px;">'+spacer+'</div>'
     +'<div name="PreviewFrame" style="position: absolute; left: '+fl+'px; top: '+ft+'px; width:'+this.thumbW+'px; height:'+this.thumbH+'px; outline: 1px solid Black;">'+spacer+'</div>'
    +'</div>'
    +'<div name="R" onMouseDown="cutter.MouseDown('+"'sizeR'"+', event);" style="float: left; cursor: e-resize; border: none; margin: 0px; background-color: Yellow; width: '+(fr-1)+'px; height:'+(ih+2)+'px;">'+spacer+'</div>'
   +'</div>'
   +'<div name="B" onMouseDown="cutter.MouseDown('+"'sizeB'"+', event);" style="clear: both; cursor: s-resize; border: none; margin: 0px; background-color: Yellow; height:'+(fb-1)+'px;">'+spacer+'</div>'
   +'</div>'
   ;
  this.frame = $( cutterhtml );

  console.log (this.frame.html());

  this.divT = this.frame.find('div[name="T"]'); // components for manipulation
  this.divLMR = this.frame.find('div[name="LMR"]');
  this.divL = this.frame.find('div[name="L"]');
  this.divM = this.frame.find('div[name="M"]');
  this.divR = this.frame.find('div[name="R"]');
  this.divB = this.frame.find('div[name="B"]');
  this.divTransparency = this.frame.find('div[name="Transparency"]');
  this.imgPreview = $('<img name="Preview" style="position: absolute; z-index: 2000; left: '+fl+'px; top: '+ft+'px; outline: 1px solid Black;" src="'+main_image.src+'" />');
  this.imgPreview.appendTo('body');
  this.frame.appendTo('body');
  this.UpdatePreview();
  this.UpdateForm();
  window.scrollTo(0,ft-10);
 }

}/*ThumbnailCutter*/

var cutter = null;

function ShowThumbnailCutter(form_id) {
 if (!cutter) { cutter = new ThumbnailCutter(form_id); }
}


function RigThumbnailCutter() {
 if ($("img#MainImage")) // only show the cutter if an image is defined as MainImage
  $("form input[name='agora_thumbnail_cutter_form_placeholder']").each( function(i) {
   var e = $(this);
   var host_form = e.parents().filter('form');
   var host_form_id = host_form.attr('id');

   if (!e.find('input[type="hidden"][name="source_height"]').count) e.after('<input type="hidden" name="source_height" size="1" value="0" />');
   if (!e.find('input[type="hidden"][name="source_width"]').count) e.after('<input type="hidden" size="1" name="source_width" value="0" />');
   if (!e.find('input[type="hidden"][name="source_y"]').count) e.after('<input type="hidden" name="source_y" size="1" value="0" />');
   if (!e.find('input[type="hidden"][name="source_x"]').count) e.after('<input type="hidden" name="source_x" size="1" value="0" />');

   e_name = e.attr('value')
   e.replaceWith('<input type="button" value="'+e_name+'" onClick="javascript:ShowThumbnailCutter('+"'"+host_form_id+"'"+');" />');
  });
}

function ExtendImageUploadForm(e) {
 var frm = $('form#form_agora_new_image_attachment');
 var count = frm.data('filecount') + 1;
 frm.data('filecount', count);
 var moniker = '_' + ('000'+ count.toString()).slice(-3) ;

 var t = $(this);
 t.unbind( 'change', ExtendImageUploadForm );

 var group = t.parent().parent();
 var newgroup = group.clone();
 newgroup.find('select[name^="image_role"]').attr('name', 'image_role'+moniker );
 newgroup.attr('name', 'attachment_group'+moniker );
 var uploadfield = newgroup.find('input[name^="image_file"]');
 uploadfield.attr( 'value', '' ); // remove the filename left over from original
 uploadfield.attr( 'name', 'image_file'+moniker );
 uploadfield.bind( 'change', ExtendImageUploadForm );

 newgroup.insertAfter(group);
}

function RigUploadFormExtender() {
 $('form#form_agora_new_image_attachment input[name^="image_file"]').bind( 'change', ExtendImageUploadForm );
 $('form#form_agora_new_image_attachment').data('filecount', 1)
}

$(document).ready( function() {
 RigThumbnailCutter();
 RigUploadFormExtender();
//! ShowThumbnailCutter('form_agora_image_upload');
});
