var positioning = false;

function render() {
var e = document.getElementById("photo");
var f = document.getElementById("imagegen");
f.photo_left.value = e.offsetLeft;
f.photo_top.value = e.offsetTop;
f.photo_width.value = e.width;
return true;
}

function switch_tpl() {
var f = document.getElementById("imagegen");
f.photo_left.value = "";
f.photo_top.value = "";
f.photo_width.value = "";
f.submit();
return true;
}

function upload() {
erase_pos();
return true;
}

function erase_pos() {
var f = document.getElementById("imagegen");
f.photo_left.value = "";
f.photo_top.value = "";
f.photo_width.value = "";
}

function doInit() {
var e = document.getElementById("photo");
var f = document.getElementById("imagegen");
e.width_orig = e.width;
e.height_orig = e.height;
if (f.photo_left.value != "") {
set_position(e, f.photo_left.value,
f.photo_top.value,
f.photo_width.value);
}
else {
fit();
}

}

function init() {
var e = document.getElementById("photo");
  if (e.complete) {
    doInit();
  } else {
    $(e).load(function() { doInit();});
  }
}


function fit() {
var e = document.getElementById("photo");
var nw = ww;
var nh = e.height_orig*nw/e.width_orig;
if (nh < wh) {
  nh = wh;
  nw = e.width_orig*nh/e.height_orig;
}
var nx = cx - nw/2;
var ny = cy - nh/2;
set_position(e, nx, ny, nw);
return false;
}

function set_position(e, l, t, w) {
var h = w*e.height_orig/e.width_orig;
e.style.width = "" + w + "px";
e.style.height = "" + h + "px";
e.style.left = "" + l + "px";
e.style.top = "" + t + "px";
}

function do_position(dx, dy, dz) {
var e = document.getElementById("photo");
var nw = e.width;
var nh = nw*e.height_orig/e.width_orig;
if (dz) {
var fcx = ((cx - e.offsetLeft) * e.width_orig) / e.width;
var fcy = ((cy - e.offsetTop) * e.height_orig) / e.height;
nw = e.width + dz;
nh = nw*e.height_orig/e.width_orig;
var fcx2 = ((cx - e.offsetLeft) * e.width_orig) / nw;
var fcy2 = ((cy - e.offsetTop) * e.height_orig) / nh;
dx = ((fcx2-fcx) * nw) / e.width_orig ;
dy = ((fcy2-fcy) * nh) / e.height_orig ;
}
var nx = e.offsetLeft+dx;
var ny = e.offsetTop+dy;
if (dx > 0 && nx > cx+ww/2) { return false; }
else if (dx < 0 && nx < cx-ww/2-nw) { return false; }
if (dy > 0 && ny > cy+wh/2) { return false; }
else if (dy < 0 && ny < cy-wh/2-nh) { return false; }
if (dz < 0 && nw < ww/2) { return false; }
else if (dz > 0 && nw > 5*e.width_orig) { return false; }

sx =  "" + (nx) + "px";
sy = "" + (ny) + "px";
sz = "" + (nw) + "px";
sh = "" + (nh) + "px";
e.style.left =sx;
e.style.top = sy;
if (dz) { e.style.width = sz; e.style.height = sh; }
return false;
}

function position(dx, dy, dz) {
  function p() {
    if (! positioning) return;
    do_position(dx,dy,dz);
    dx *= 1.1;
    dy *= 1.1;
    dz *= 1.1;
    if (positioning) { setTimeout(p, 100); }
  }
  positioning = true;
  p();
}

function end_position() {
  positioning = false;
}


