var redrawing = false;
var redraw_again = null;
var last_redraw_mouse = null;
var zoomming = 2;
function redraw(e) {
  if (!picture || !picture.loaded) return;
  if (redrawing) {
    redraw_again = e;
    return;
  }
  redrawing = true;
  if (!e) e = window.event;
  var elem = getTarget(e);

  //fix illegal size values
  var w = parseInt(_w.value);
  var h = parseInt(_h.value);
  if (w <= 0)       _w.value = w = picture.width;
  if (w < min_size) _w.value = w = min_size;
  if (h <= 0)       _h.value = h = picture.height;
  if (h < min_size) _h.value = h = min_size;

  //check for locked proportions
  if (_lock.checked) {
    if (elem == _h)      _w.value = w = parseInt(h*p.lock_ratio);
    else if (elem == _w) _h.value = h = parseInt(w/p.lock_ratio);
    else {
      _w.value = w = parseInt(Math.max(w, p.lock_ratio*h));
      _h.value = h = parseInt(w/p.lock_ratio);
    }
  }

  var x = parseInt(_x.value);
  var y = parseInt(_y.value);
  var alpha = parseInt(_alpha.value);
  if (alpha > 100)    alpha = 100;
  else if (alpha < 1) alpha = 1;
  _x.value = x;
  _y.value = y;
  _alpha.value = alpha;

  _wp.value = w*100/picture.width;
  _hp.value = h*100/picture.height;

  if (_center.checked && (elem == _w || elem == _h || elem == _wp || elem == _hp)) {
    _x.value = x = x+(p.dim.w-w)/2;
    _y.value = y = y+(p.dim.h-h)/2;
  }

  p.pos.x = x;
  p.pos.y = y;
  p.dim.w = w;
  p.dim.h = h;
  p.alpha = alpha;

  resizeClip();

  if (elem == _w || elem == _h || elem == _wp || elem == _hp || elem == _x || elem == _y || elem == _alpha)
    saveUndo();

  graphics.save();
  //graphics.scale(2, 2);
  graphics.drawImage(collage_picture, 0, 0, collage_picture.width, collage_picture.height);

  graphics.save();
  graphics.translate(x, y);

  //draw clipped out (more faded)
  if (p.clip.length > 2 && showExtras) {
    graphics.save();
    graphics.globalAlpha = alpha/100/(clipSelectionMode?2:3);
    graphics.drawImage(picture, 0, 0, w, h);
    graphics.restore(); //alpha
  }

  //draw clipped in
  graphics.save();
  if (p.clip.length > 2)
    clipPolygon(p.clip)
  graphics.globalAlpha = alpha/100;
  graphics.drawImage(picture, 0, 0, w, h);
  graphics.restore(); //clip and alpha

  //draw frame
  if (showExtras) {
    graphics.lineWidth = 4;
    graphics.strokeStyle = frameColor;
    drawDashedRectangle(-2, -2, w+4, h+4, 6);
  }

  var mouse = e?getMousePos(e):null;
  if (!mouse || (mouse.x <= 0 && mouse.y <= 0))
    mouse = last_redraw_mouse;
  else
    last_redraw_mouse = mouse;
  var mouse_collage = mouse?mouse.difference(getPos(_collage)):null;
  mouse = mouse_collage?mouse_collage.difference(p.pos):null;
  if (clipSelectionMode && showExtras) {
    graphics.lineWidth = 1;
    graphics.fillStyle = blue;
    graphics.strokeStyle = black;
    drawPolygon(p.clip, mouse);
    if (mouse && getRegion(e) != outside) {
      var first = null;
      var last = null;
      if (editPoint >= 0) {
        if (p.clip.length == 2)
          first = p.clip[1-editPoint];
        else if (p.clip.length > 2) {
          first = p.clip[editPoint==0?p.clip.length-1:editPoint-1];
          last = p.clip[(editPoint+1)%p.clip.length];
        }
      } else if (p.clip.length >= 2) {
        first = p.clip[realEditLine()];
        last = p.clip[(realEditLine()+1)%p.clip.length];
      }
      if (first) {
        graphics.strokeStyle = white;
        graphics.beginPath();
        graphics.moveTo(first.x, first.y);
        graphics.lineTo(mouse.x, mouse.y);
        if (last)
          graphics.lineTo(last.x, last.y);
        graphics.stroke();
      }
    }
  }

  graphics.restore(); //translation
  graphics.restore(); //scaling

  if (mouse_collage)
    drawZoom(mouse_collage);

  redrawing = false;
  if (redraw_again) {
    e = redraw_again;
    redraw_again = null;
    redraw(e);
  }
}
function clipPolygon(pts) {
  if (pts.length < 3) return;
  graphics.beginPath();
  graphics.moveTo(pts[0].x, pts[0].y);
  for (var i = 1; i < pts.length; i++)
    graphics.lineTo(pts[i].x, pts[i].y);
  graphics.lineTo(pts[0].x, pts[0].y);
  graphics.clip();
}
function drawPolygon(pts, mouse) {
  if (pts.length == 0) return;
  var stroke = graphics.strokeStyle;
  var fill = graphics.fillStyle;
  if (pts.length == 2) {
    drawPolygonSegment(pts[1], pts[0], mouse, stroke);
  } else if (pts.length > 2) {
    for (var i = 1; i < pts.length; i++)
      drawPolygonSegment(pts[i-1], pts[i], mouse, stroke);
    drawPolygonSegment(pts[pts.length-1], pts[0], mouse, stroke);
  }
  for (var i = 0; i < pts.length; i++) {
    if (i == editPoint)
      graphics.fillStyle = green;
    else if (editPoint < 0 && mouse && mouse.distance(pts[i]) < 4)
      graphics.fillStyle = red;
    graphics.beginPath();
    graphics.arc(pts[i].x, pts[i].y, 3, 0, 2*Math.PI, true);
    graphics.fill();
    graphics.fillStyle = fill;
  }
}
function drawPolygonSegment(p1, p2, mouse, stroke) {
  if (editPoint < 0 && p1 == p.clip[realEditLine()])
    graphics.strokeStyle = green;
  else if (editPoint < 0 && mouse && mouse.distanceToLineSeg(p1, p2) < 7)
    graphics.strokeStyle = red;
  drawLine(p1, p2);
  graphics.strokeStyle = stroke;
}
function drawLine(p1, p2) {
  graphics.beginPath();
  graphics.moveTo(p1.x, p1.y);
  graphics.lineTo(p2.x, p2.y);
  graphics.stroke();
}
function drawDashedRectangle(r_x, r_y, r_w, r_h, dashLength) {
  var x, y, length, horiz;
  var c = graphics.lineWidth / 2; //this is to correct for corners not lining up
  for (var i = 0; i < 4; i++) {
    switch (i) {
      case 0: x = r_x-c;    y = r_y;     length = r_w; horiz = true;  break;
      case 1: x = r_x+r_w;  y = r_y-c;   length = r_h; horiz = false; break;
      case 2: x = r_x-c;    y = r_y+r_h; length = r_w; horiz = true;  break;
      case 3: x = r_x;      y = r_y-c;   length = r_h; horiz = false; break;
    }
    length += c*2;
    var finalx = horiz?(x+length-dashLength):x;
    var finaly = horiz?y:(y+length-dashLength);
    var dx = horiz?dashLength:0;
    var dy = horiz?0:dashLength;
    graphics.beginPath();
    graphics.moveTo(x, y);
    while (x <= finalx && y <= finaly) {
      graphics.lineTo(x+=dx, y+=dy);
      graphics.moveTo(x+=dx, y+=dy);
    }
    graphics.stroke();
  }
  graphics.beginPath();
  graphics.moveTo(r_x+r_w-c, r_y+r_h);
  graphics.lineTo(r_x+r_w+c, r_y+r_h);
  graphics.stroke();
}
var zoom_amount = 2;
function drawZoom(center) {
  var pos = new Point(Math.min(Math.max(center.x-_zoomed.width/(zoom_amount*2), 0), _collage.width-_zoomed.width/zoom_amount),
                      Math.min(Math.max(center.y-_zoomed.width/(zoom_amount*2), 0), _collage.height-_zoomed.height/zoom_amount));
  graphics_zoom.drawImage(_collage, pos.x, pos.y, _zoomed.width/zoom_amount, _zoomed.height/zoom_amount, 0, 0, _zoomed.width, _zoomed.height);
  graphics_zoom.fillStyle = black;
  graphics_zoom.beginPath();
  graphics_zoom.arc(zoom_amount*(center.x-pos.x), zoom_amount*(center.y-pos.y), 3, 0, 2*Math.PI, true);
  graphics_zoom.fill();
}

function locking(e) {
  if (p == null) return false;
  if (_lock.checked == null)
    _lock.checked = false;
  _lock.checked = !_lock.checked;
  changeClass(_lock, 'down', _lock.checked);
  p.lock_ratio = p.dim.w / p.dim.h;
  p.lock_ratio_perc = (p.dim.w*picture.height) / (p.dim.h*picture.width);
  p.locked = _lock.checked;
  return false;
}

function centering(e) {
  if (p == null) return false;
  if (!_center.checked)
    _center.checked = false;
  _center.checked = !_center.checked;
  changeClass(_center, 'down', _center.checked);
  p.centered = _center.value;
  return false;
}

function changeSizePerc(e) {
  if (!e) e = window.event;
  if (_lock.checked) {
    var elem = getTarget(e);
    if (elem == _hp)      _wp.value = parseFloat(_hp.value)*p.lock_ratio_perc;
    else if (elem == _wp) _hp.value = parseFloat(_wp.value)/p.lock_ratio_perc;
    else {
      _wp.value = Math.max(parseFloat(_wp.value), p.lock_ratio_perc*parseFloat(_hp.value));
      _hp.value = parseFloat(_wp.value)/p.lock_ratio_perc;
    }
  }
  _w.value = picture.width*parseFloat(_wp.value)/100;
  _h.value = picture.height*parseFloat(_hp.value)/100;
  redraw(e);
}

function resizeClip() {
  if (p.clip.length > 0) {
    if (p.clipWidth && p.clipWidth != p.dim.w) {
      var ratio = p.dim.w/p.clipWidth;
      for (var i = 0; i < p.clip.length; i++)
        _clip.rows[i].x.value = (p.clip[i].x *= ratio);
    }
    if (p.clipHeight && p.clipHeight != p.dim.h) {
      var ratio = p.dim.h/p.clipHeight;
      for (var i = 0; i < p.clip.length; i++)
        _clip.rows[i].y.value = (p.clip[i].y *= ratio);
    }
  }
  p.clipWidth = p.dim.w;
  p.clipHeight = p.dim.h;
}


function switchClipSelectionMode(e) {
  if (p == null) return false;
  clipSelectionMode=!clipSelectionMode;
  changeClass(_clipButton, 'down', clipSelectionMode);
  frameColor = clipSelectionMode?white:black;
  redraw(e);
  return false;
}

function addIt() {
  _form.action='collage.php';
  _form.target='_self';
  var clip = $('clipValue');
  clip.value = '';
  for (var i = 0; i < p.clip.length; i++)
    clip.value += p.clip[i].x+','+p.clip[i].y+((i!=p.clip.length-1)?':':'');
  _form.submit();
  return false;
}
