<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 
?>
<?php
/* =========================================================
   cargar_fotonoticia.php (PHP 8.2) — DE CERO, PERO IGUAL FLUJO
   - Reemplaza el recortador viejo (imgAreaSelect) por Cropper.js
   - GUARDA SIEMPRE:
       upload_pic/resize_<KEY>.jpg
       upload_pic/thumbnail_<KEY>.jpg
   - Respeta tamaños por $cu3er:
       1) 1920x1080
       2) 960x320
       3) 960x180
   - Mantiene: subir -> recortar -> texto -> guardar
   ========================================================= */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

/* ===== Idioma ===== */
if (!isset($lang_actual)) {
  $lang_actual = '';
}

if ($lang_actual == 'es' || $lang_actual == '') {
  include 'lang_es_no_panel.php';
}

if ($lang_actual == 'pt') {
  include 'langes_pt_no_panel.php';
}

/* ===== Inputs ===== */
$ID   = (int)($_GET['ID'] ?? 0);
$foto = (string)($_GET['foto'] ?? '');

if (!$ID) {
  $ID = (int)($_POST['ID'] ?? 0);
}

if ($foto === '') {
  $foto = (string)($_POST['foto'] ?? '');
}

/* ===== Session random_key ===== */
if (!isset($_SESSION['random_key']) || strlen((string)$_SESSION['random_key']) == 0) {
  $_SESSION['random_key'] = (string)strtotime(date('Y-m-d H:i:s'));
}

$keyy = (string)$_SESSION['random_key'];

/* ===== DB / config ===== */
include 'concha.php';

/* ===== Tamaños por $cu3er ===== */
$cu3er = (int)($cu3er ?? 1);

if ($cu3er == 2) {
  $max_width    = 960;
  $thumb_width  = 960;
  $thumb_height = 320;
} elseif ($cu3er == 3) {
  $max_width    = 960;
  $thumb_width  = 960;
  $thumb_height = 180;
} else {
  $max_width    = 1920;
  $thumb_width  = 1920;
  $thumb_height = 1080;
}

/* ===== Constantes ===== */
$upload_dir          = "upload_pic";
$upload_path         = $upload_dir . "/";
$large_image_prefix  = "resize_";
$thumb_image_prefix  = "thumbnail_";

/* ===== Rutas: SIEMPRE .jpg ===== */
$large_image_location = $upload_path . $large_image_prefix . $keyy . ".jpg";
$thumb_image_location = $upload_path . $thumb_image_prefix . $keyy . ".jpg";

/* ===== Permitidos ===== */
$allowed_image_types = array(
  'image/pjpeg' => "jpg",
  'image/jpeg'  => "jpg",
  'image/jpg'   => "jpg",
  'image/png'   => "png",
  'image/x-png' => "png",
  'image/gif'   => "gif"
);

$image_ext = "JPG PNG GIF";

/* ===== Crear carpeta si no existe ===== */
if (!is_dir($upload_dir)) {
  @mkdir($upload_dir, 0777, true);
  @chmod($upload_dir, 0777);
}

/* ===== Helpers ===== */
function self_url_keep_qs(): string {
  $qs = $_SERVER['QUERY_STRING'] ?? '';
  return ($_SERVER['PHP_SELF'] ?? '') . ($qs ? ('?' . $qs) : '');
}

function self_url_clean_delete(): string {
  $params = $_GET ?? array();

  unset($params['a']);
  unset($params['t']);

  $qs = http_build_query($params);

  return ($_SERVER['PHP_SELF'] ?? '') . ($qs ? ('?' . $qs) : '');
}

function img_from_upload(string $tmp, string $mime) {
  switch ($mime) {
    case 'image/pjpeg':
    case 'image/jpeg':
    case 'image/jpg':
      return @imagecreatefromjpeg($tmp);

    case 'image/png':
    case 'image/x-png':
      return @imagecreatefrompng($tmp);

    case 'image/gif':
      return @imagecreatefromgif($tmp);
  }

  return null;
}

function save_as_jpg($im, string $dest, int $quality = 90): bool {
  if (!$im) {
    return false;
  }

  $ok = @imagejpeg($im, $dest, $quality);

  if ($ok) {
    @chmod($dest, 0777);
  }

  return $ok;
}

function resize_max_width_jpg(string $srcJpg, int $maxW): void {
  $info = @getimagesize($srcJpg);

  if (!$info) {
    return;
  }

  $w = (int)$info[0];
  $h = (int)$info[1];

  if ($w <= 0 || $h <= 0) {
    return;
  }

  if ($w <= $maxW) {
    return;
  }

  $scale = $maxW / $w;
  $newW  = (int)round($w * $scale);
  $newH  = (int)round($h * $scale);

  $src = @imagecreatefromjpeg($srcJpg);

  if (!$src) {
    return;
  }

  $dst = imagecreatetruecolor($newW, $newH);

  imagecopyresampled(
    $dst,
    $src,
    0,
    0,
    0,
    0,
    $newW,
    $newH,
    $w,
    $h
  );

  @imagejpeg($dst, $srcJpg, 90);

  @imagedestroy($src);
  @imagedestroy($dst);

  @chmod($srcJpg, 0777);
}

function crop_to_fixed_jpg(
  string $srcJpg,
  string $dstJpg,
  int $x,
  int $y,
  int $w,
  int $h,
  int $dstW,
  int $dstH
): bool {
  $info = @getimagesize($srcJpg);

  if (!$info) {
    return false;
  }

  $srcW = (int)$info[0];
  $srcH = (int)$info[1];

  if ($w <= 0 || $h <= 0) {
    return false;
  }

  if ($x < 0) {
    $x = 0;
  }

  if ($y < 0) {
    $y = 0;
  }

  if ($x + $w > $srcW) {
    $w = max(1, $srcW - $x);
  }

  if ($y + $h > $srcH) {
    $h = max(1, $srcH - $y);
  }

  $src = @imagecreatefromjpeg($srcJpg);

  if (!$src) {
    return false;
  }

  $dst = imagecreatetruecolor($dstW, $dstH);

  imagecopyresampled(
    $dst,
    $src,
    0,
    0,
    $x,
    $y,
    $dstW,
    $dstH,
    $w,
    $h
  );

  $ok = @imagejpeg($dst, $dstJpg, 90);

  @imagedestroy($src);
  @imagedestroy($dst);

  if ($ok) {
    @chmod($dstJpg, 0777);
  }

  return (bool)$ok;
}

/* =========================================================
   1) UPLOAD
   ========================================================= */
$error = "";

if (isset($_POST['upload'])) {
  $tmp  = $_FILES['image']['tmp_name'] ?? '';
  $size = (int)($_FILES['image']['size'] ?? 0);
  $mime = (string)($_FILES['image']['type'] ?? '');
  $name = (string)($_FILES['image']['name'] ?? '');
  $err  = (int)($_FILES['image']['error'] ?? 0);

  if ($name === '' || $err !== 0 || $tmp === '') {
    $error = "Seleccione una imagen para cargar";
  } else {
    if (!isset($allowed_image_types[$mime])) {
      $error = "Solo <strong>$image_ext</strong> imagenes soportadas para subir<br />";
    }

    if ($size > (3 * 1048576)) {
      $error .= "La imagen debe ser menor de 3MB";
    }
  }

  if (strlen($error) === 0) {
    $im = img_from_upload($tmp, $mime);

    if (!$im) {
      $error = "No se pudo procesar la imagen. Verifique que GD esté instalado.";
    } else {
      $w = imagesx($im);
      $h = imagesy($im);

      $rgb = imagecreatetruecolor($w, $h);
      $white = imagecolorallocate($rgb, 255, 255, 255);

      imagefilledrectangle($rgb, 0, 0, $w, $h, $white);
      imagecopy($rgb, $im, 0, 0, 0, 0, $w, $h);

      save_as_jpg($rgb, $large_image_location, 90);

      @imagedestroy($im);
      @imagedestroy($rgb);

      resize_max_width_jpg($large_image_location, (int)$max_width);

      if (file_exists($thumb_image_location)) {
        @unlink($thumb_image_location);
      }

      header("Location: " . self_url_keep_qs());
      exit();
    }
  }
}

/* =========================================================
   2) CROP
   ========================================================= */
if (isset($_POST['upload_thumbnail']) && file_exists($large_image_location)) {
  $x1 = (int)($_POST['x1'] ?? 0);
  $y1 = (int)($_POST['y1'] ?? 0);
  $w  = (int)($_POST['w']  ?? 0);
  $h  = (int)($_POST['h']  ?? 0);

  $ok = crop_to_fixed_jpg(
    $large_image_location,
    $thumb_image_location,
    $x1,
    $y1,
    $w,
    $h,
    (int)$thumb_width,
    (int)$thumb_height
  );

  if (!$ok) {
    $error = "No se pudo guardar el recorte. Verifique permisos en /upload_pic y extensión GD.";
  } else {
    header("Location: " . self_url_keep_qs());
    exit();
  }
}

/* =========================================================
   3) DELETE
   ========================================================= */
if (($_GET['a'] ?? '') === 'delete' && strlen((string)($_GET['t'] ?? '')) > 0) {
  $t = preg_replace('/[^0-9]/', '', (string)$_GET['t']);

  if ($t !== '') {
    @unlink($upload_path . $large_image_prefix . $t . ".jpg");
    @unlink($upload_path . $thumb_image_prefix . $t . ".jpg");
  }

  header("Location: " . self_url_clean_delete());
  exit();
}

/* ===== Exists ===== */
$large_exists = file_exists($large_image_location);
$thumb_exists = file_exists($thumb_image_location);

$large_photo_exists = $large_exists
  ? "<img class='img-fluid' src=\"" . htmlspecialchars($large_image_location, ENT_QUOTES, 'UTF-8') . "\" alt=\"Large Image\"/>"
  : "";

$thumb_photo_exists = $thumb_exists
  ? "<img class='img-fluid' src=\"" . htmlspecialchars($thumb_image_location, ENT_QUOTES, 'UTF-8') . "\" alt=\"Thumbnail Image\"/>"
  : "";

/* =========================================================
   4) INSERT notas_tapa
   - Si existe ext_img, la guarda.
   - Si NO existe ext_img, guarda igual.
   - Evita duplicados por foto.
   ========================================================= */
if ($large_exists && $thumb_exists && isset($conn) && $conn instanceof mysqli) {

  $existe      = 0;
  $extImg      = 'jpg';
  $tieneExtImg = false;

  if (isset($basedatos) && $basedatos !== '' && preg_match('/^[a-zA-Z0-9_]+$/', (string)$basedatos)) {
    $tablaNotasTapa = "`" . $basedatos . "`.`notas_tapa`";
  } else {
    $tablaNotasTapa = "`notas_tapa`";
  }

  try {

    /* Verifica si la columna ext_img existe */
    $resCol = $conn->query("SHOW COLUMNS FROM " . $tablaNotasTapa . " LIKE 'ext_img'");

    if ($resCol && $resCol->num_rows > 0) {
      $tieneExtImg = true;
    }

    if ($resCol) {
      $resCol->free_result();
    }

    /* Verifica si ya existe la foto */
    $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM " . $tablaNotasTapa . " WHERE foto = ?");

    if ($stmt) {
      $stmt->bind_param("s", $keyy);
      $stmt->execute();

      $res = $stmt->get_result();

      if ($res && ($row = $res->fetch_assoc())) {
        $existe = (int)$row['c'];
      }

      if ($res) {
        $res->free_result();
      }

      $stmt->close();
    }

    /* Inserta solo si no existe */
    if ($existe === 0) {

      if ($tieneExtImg) {

        $stmtIns = $conn->prepare(
          "INSERT INTO " . $tablaNotasTapa . "
           (`foto`, `titulo`, `texto`, `nota`, `cu3er`, `etiqueta`, `ext_img`)
           VALUES (?, '0', '0', '0', '0', '0', ?)"
        );

        if ($stmtIns) {
          $stmtIns->bind_param("ss", $keyy, $extImg);
          $stmtIns->execute();
          $stmtIns->close();
        } else {
          $error = "No se pudo preparar el INSERT con ext_img en notas_tapa: " . $conn->error;
        }

      } else {

        $stmtIns = $conn->prepare(
          "INSERT INTO " . $tablaNotasTapa . "
           (`foto`, `titulo`, `texto`, `nota`, `cu3er`, `etiqueta`)
           VALUES (?, '0', '0', '0', '0', '0')"
        );

        if ($stmtIns) {
          $stmtIns->bind_param("s", $keyy);
          $stmtIns->execute();
          $stmtIns->close();
        } else {
          $error = "No se pudo preparar el INSERT sin ext_img en notas_tapa: " . $conn->error;
        }
      }
    }

  } catch (mysqli_sql_exception $e) {
    $error = "Error en notas_tapa: " . $e->getMessage();
  }
}

?><!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />

  <title><?php echo htmlspecialchars($lang_100088 ?? 'SUBI TU FOTO', ENT_QUOTES, 'UTF-8'); ?></title>

  <style>
    body {
      background: #f4f7fb;
    }

    .wrap {
      max-width: 1200px;
      margin: 18px auto;
      padding: 0 12px;
    }

    .card-soft {
      background: #fff;
      border: 1px solid rgba(0,0,0,.06);
      border-radius: 14px;
      box-shadow: 0 10px 28px rgba(0,0,0,.06);
    }

    .crop-stage {
      width: 100%;
      background: #0b1220;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 10px 28px rgba(0,0,0,.10);
    }

    .crop-stage img {
      display: block;
      width: 100%;
      height: auto;
      max-height: 70vh;
      object-fit: contain;
    }

    .preview-box {
      width: 100%;
      border: 1px solid rgba(0,0,0,.10);
      border-radius: 12px;
      overflow: hidden;
      background: #0b1220;
      box-shadow: 0 10px 22px rgba(0,0,0,.08);
    }

    .preview {
      width: 100%;
      height: 220px;
      overflow: hidden;
    }

    .btn-xl {
      padding: 14px 18px;
      font-size: 1.05rem;
      font-weight: 700;
      border-radius: 12px;
    }
  </style>
</head>

<body>
<div class="wrap">

  <?php if (strlen($error) > 0) { ?>
    <div class="alert alert-danger card-soft p-3 mb-3">
      <strong>Error</strong><br><?php echo $error; ?>
    </div>
  <?php } ?>

  <?php
  /* =========================================================
     ESTADO 3: large + thumb => TEXTO
     ========================================================= */
  if ($large_exists && $thumb_exists) {
    echo $large_photo_exists . "<br><br>" . $thumb_photo_exists;
  ?>

    <div class="card-soft p-3 p-md-4 mt-3">
      <span class="Estilo6"><?php echo $lang_100089 ?? '¡LA IMAGEN FUE CARGADA CORRECTAMENTE!'; ?></span><br><br>

      <span class="Estilo6"><?php echo $lang_100086 ?? ''; ?></span>

      <form action="form_texto_fotonoticias.php" method="post" class="mt-3">
        <input name="keyy" type="hidden" value="<?php echo htmlspecialchars($keyy, ENT_QUOTES, 'UTF-8'); ?>" />

        <?php echo $lang_100090 ?? 'TITULO'; ?>
        <input name="titulo" type="text" class="form-control form-control-lg mb-2" value="" />

        <?php echo $lang_100091 ?? 'TEXTO'; ?><br>
        <textarea name="texto" class="form-control mb-2" rows="5"></textarea>

        <?php echo $lang_100092 ?? 'NOTA RELACIONADA'; ?>

        <select name="nota" class="form-control mb-3">
          <option value="" selected="selected"><?php echo $lang_100093 ?? 'Ninguna'; ?></option>

          <?php
          $sql = "SELECT ID, titulo, d, m, a FROM notas WHERE ver = 'si' ORDER BY ID DESC LIMIT 100";

          if (isset($conn) && $conn instanceof mysqli) {
            try {
              $consulta = $conn->query($sql);

              if ($consulta) {
                while ($row = $consulta->fetch_assoc()) {
                  $ID_N       = (int)$row["ID"];
                  $tituloNota = (string)$row["titulo"];
                  $d          = (string)$row["d"];
                  $m          = (string)$row["m"];
                  $a          = (string)$row["a"];

                  echo '<option value="' . $ID_N . '">' .
                    $ID_N . ' - ' .
                    htmlspecialchars($d, ENT_QUOTES, 'UTF-8') . ' / ' .
                    htmlspecialchars($m, ENT_QUOTES, 'UTF-8') . ' / ' .
                    htmlspecialchars($a, ENT_QUOTES, 'UTF-8') . ' - ' .
                    htmlspecialchars($tituloNota, ENT_QUOTES, 'UTF-8') .
                  '</option>';
                }

                $consulta->free_result();
              }
            } catch (mysqli_sql_exception $e) {
              echo '<option value="">Error cargando notas</option>';
            }
          }
          ?>
        </select>

        <button name="button" type="submit" class="btn btn-outline-primary btn-xl btn-block" id="button">
          <?php echo htmlspecialchars($lang_guardar ?? 'Guardar', ENT_QUOTES, 'UTF-8'); ?>
        </button>
      </form>

      <div class="text-center mt-3">
        <a class="btn btn-primary" href="panel/fotonoticias.php">
          <?php echo htmlspecialchars($lang_volver ?? 'Volver', ENT_QUOTES, 'UTF-8'); ?>
        </a>
      </div>

      <?php
      $_SESSION['random_key'] = "";
      $_SESSION['user_file_ext'] = "";
      ?>
    </div>

  <?php
  /* =========================================================
     ESTADO 2: large existe, thumb NO => RECORTAR
     ========================================================= */
  } elseif ($large_exists) {
    $aspect = $thumb_width / $thumb_height;
  ?>

    <div class="card-soft p-3 p-md-4 mb-3">
      <h2 class="Estilo4">
        <?php echo $lang_100094 ?? 'RECORTE UNA MINIATURA DE LA IMAGEN'; ?>
      </h2>

      <div class="row">
        <div class="col-12 col-lg-8 mb-3">
          <div class="crop-stage">
            <img id="cropImage" src="<?php echo htmlspecialchars($large_image_location, ENT_QUOTES, 'UTF-8'); ?>" alt="Create Thumbnail" />
          </div>
        </div>

        <div class="col-12 col-lg-4">
          <div class="preview-box mb-3">
            <div class="preview" id="previewBox"></div>
          </div>

          <form id="cropForm" name="thumbnail" action="<?php echo htmlspecialchars(self_url_keep_qs(), ENT_QUOTES, 'UTF-8'); ?>" method="post">
            <input type="hidden" name="x1" value="" id="x1" />
            <input type="hidden" name="y1" value="" id="y1" />
            <input type="hidden" name="x2" value="" id="x2" />
            <input type="hidden" name="y2" value="" id="y2" />
            <input type="hidden" name="w"  value="" id="w" />
            <input type="hidden" name="h"  value="" id="h" />

            <input name="ID" type="hidden" value="<?php echo (int)$ID; ?>" />
            <input name="foto" type="hidden" value="<?php echo htmlspecialchars($foto, ENT_QUOTES, 'UTF-8'); ?>" />

            <button name="upload_thumbnail" type="submit" class="btn btn-success btn-xl btn-block" id="save_thumb">
              <?php echo htmlspecialchars($lang_cargar ?? 'Cargar', ENT_QUOTES, 'UTF-8'); ?>
            </button>
          </form>
        </div>
      </div>
    </div>

    <div class="card-soft p-3 p-md-4 mb-3">
      <h2 class="Estilo4">
        <?php echo $lang_100087 ?? 'SELECCIONE LA IMAGEN DESDE SU COMPUTADORA'; ?><br>
        <?php echo $lang_100095 ?? ''; ?>
      </h2>

      <form name="photo" enctype="multipart/form-data" action="<?php echo htmlspecialchars(self_url_keep_qs(), ENT_QUOTES, 'UTF-8'); ?>" method="post">
        <input name="ID" type="hidden" value="<?php echo (int)$ID; ?>" />
        <input name="foto" type="hidden" value="<?php echo htmlspecialchars($foto, ENT_QUOTES, 'UTF-8'); ?>" />

        <p class="Estilo4"><?php echo $lang_100096 ?? ''; ?></p>

        <input name="image" type="file" class="form-control mb-3" />

        <input name="upload" type="submit" class="btn btn-primary btn-xl btn-block" value="SUBIR" />
      </form>
    </div>

  <?php
  /* =========================================================
     ESTADO 1: UPLOAD
     ========================================================= */
  } else {
  ?>

    <div class="card-soft p-3 p-md-4 mb-3">
      <h2 class="Estilo4">
        <?php echo $lang_100087 ?? 'SELECCIONE LA IMAGEN DESDE SU COMPUTADORA'; ?><br>
        <?php echo $lang_100095 ?? ''; ?>
      </h2>

      <form name="photo" enctype="multipart/form-data" action="<?php echo htmlspecialchars(self_url_keep_qs(), ENT_QUOTES, 'UTF-8'); ?>" method="post">
        <input name="ID" type="hidden" value="<?php echo (int)$ID; ?>" />
        <input name="foto" type="hidden" value="<?php echo htmlspecialchars($foto, ENT_QUOTES, 'UTF-8'); ?>" />

        <p class="Estilo4">
          <?php echo $lang_100096 ?? 'Seleccione una imagen para cargar'; ?>
        </p>

        <input name="image" type="file" class="form-control mb-3" />

        <input name="upload" type="submit" class="btn btn-primary btn-xl btn-block" value="SUBIR" />

        <div class="text-muted mt-2" style="font-size:.95rem;">
          Máximo 3MB. Tipos: <?php echo htmlspecialchars($image_ext, ENT_QUOTES, 'UTF-8'); ?>
        </div>
      </form>
    </div>

  <?php } ?>

  <hr>

  <p>
    <a href="panel/config_fotonoticias.php" class="btn btn-outline-primary">
      <?php echo htmlspecialchars($lang_100097 ?? 'CONFIGURAR FOTONOTICIAS', ENT_QUOTES, 'UTF-8'); ?>
    </a>
  </p>

  <hr>

  <p>
    <a class="btn btn-primary" href="panel/index.php">
      <?php echo htmlspecialchars($lang_volver ?? 'Volver', ENT_QUOTES, 'UTF-8'); ?>
    </a>
  </p>

</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>
(function(){
  var img = document.getElementById('cropImage');

  if (!img) {
    return;
  }

  var aspect = <?php echo json_encode($thumb_width / $thumb_height); ?>;

  var cropper = new Cropper(img, {
    aspectRatio: aspect,
    viewMode: 1,
    dragMode: 'move',
    autoCropArea: 1,
    responsive: true,
    background: false,
    guides: true,
    center: true,
    highlight: true,
    zoomOnWheel: true,
    rotatable: false,
    scalable: false,
    preview: '#previewBox'
  });

  var form = document.getElementById('cropForm');

  if (!form) {
    return;
  }

  form.addEventListener('submit', function(e){
    var data = cropper.getData(true);

    var x = Math.round(data.x);
    var y = Math.round(data.y);
    var w = Math.round(data.width);
    var h = Math.round(data.height);

    if (!w || !h || w <= 0 || h <= 0) {
      e.preventDefault();
      alert('Seleccione el área a recortar.');
      return false;
    }

    document.getElementById('x1').value = x;
    document.getElementById('y1').value = y;
    document.getElementById('w').value  = w;
    document.getElementById('h').value  = h;

    document.getElementById('x2').value = x + w;
    document.getElementById('y2').value = y + h;

    return true;
  });
})();
</script>

</body>
</html>