HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux aritmodecarnaval.es 5.15.0-79-generic #86-Ubuntu SMP Mon Jul 10 16:07:21 UTC 2023 x86_64
User: www-data (33)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /home/www/aritmodecarnaval/comprar/index.php
<?php
/**
 * Stuporglue's Single-File PHP Gallery
 *
 *
 * Copyright (C) 2014, Michael Moore <stuporglue@gmail.com>
 *
 * Licensed under the MIT license.
 *
 * Quick Start:
 * Place this file in the top-level directory where you want photo galleries to appear.
 *
 * For more details see https://github.com/stuporglue/InstaGallery
 */


//$path = __DIR__;      // The base directory for the photos, defaults to the current directory

$path = "./galerias";
$thumbnailSize = 500; // size in pixels
$bgcolor = '#800000'; // background color


///////////////////////////////////////////////////////////////////////////////////////////
/////   Be careful below here...
///////////////////////////////////////////////////////////////////////////////////////////

/**
 * Verify that the requested path is within the $path
 *
 * @param $path The path to check our request within
 * @return String -- The full path to the target directory
 */
function getTargetPath($path){
    // Find and validate the target path
    $targetdir = $path  . (isset($_REQUEST['d']) ? '/' . $_REQUEST['d'] : '');
    while(strpos($targetdir,'..') !== FALSE){
        die("Tratando de hackearme?");
        // Get rid of double dots and make sure that our path is a subdirectory of the $path directory
        // Can't use realpath because symlinks might make something a valid path
        preg_replace('|/.*?/../|','');
    }

    $valid = strpos(realpath($targetdir),realpath($path)) !== FALSE && is_dir($targetdir);

    if(!$valid){
        header("HTTP/1.0 404 Not Found");
        print "Comparsa no encontrada.";
        exit();
    }

    return $targetdir;
}

/**
 * Make a string pretty for printing
 * @param $name The name to pretty print
 * @return A pretty name string
 */
function prettyName($name){
    $origName = $name;
    $name = basename($name);
    $name = preg_split('/([^\w-]|[_])/u',$name);
    $name = array_map('ucfirst',$name);
    $name = implode(' ',array_filter($name));
    if($name === ''){
        return $origName;
    }
    return $name;
}

/**
 * Get the Table of Contents for the navigation
 * @param $path The base path
 * @return An html string for the nav
 */
function getNav($path,$relpath){
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
    $dots = Array('.','..');
    $wrapup = Array();
    foreach($objects as $name => $object){
    if($object->isDir() && !in_array($object->getBaseName(),$dots)){
            $name = explode('/',str_replace($path . '/','',$name));
            $wraplink = &$wrapup;
            $part = array_shift($name);
            while(@is_array($wraplink[$part])){
                $wraplink = &$wraplink[$part];
                $part = array_shift($name);
            }
            if($part[0] != '.'){ // skip hidden files/directories
                $wraplink[$part] = Array();
            }
        }
    }

    $rel = array_filter(explode('/',$relpath));
    $pathparts = Array();
    $navparts[] = "<span><a href='?d=' class='home'>Reiniciar</a></span>";

    $builtPath = Array();
    foreach($rel as $curpart){
        uksort($wrapup,function($a,$b){ return strnatcmp(prettyName($a),prettyName($b)); });
        $html = "\n<select class='navchange'>\n";
        foreach($wrapup as $pathpart => $childparts){
            $html .= "<option value='" . implode('/',$builtPath) . (count($builtPath) > 0 ? '/' : '') . $pathpart . "'". ($pathpart == $curpart ? ' selected' : '')  .">" . prettyName($pathpart) . "</option>";
        }
        $wrapup = &$wrapup[$curpart];
        $builtPath[] = $curpart;
        $html .= "</select>\n";
        $navparts[] = $html;
    }

    if(count($wrapup) > 0){
        $html = "\n<select class='navchange'>\n";
        $html .= "<option value='" . implode('/',$builtPath) ."'>Elije una opción</option>\n";
        uksort($wrapup,function($a,$b){ return strnatcmp(prettyName($a),prettyName($b)); });
        foreach($wrapup as $pathpart => $childparts){
            $html .= "<option value='" . implode('/',$builtPath) . (count($builtPath) > 0 ? '/' : '') . $pathpart . "'>" . prettyName($pathpart) . "</option>";
        }
        $html .= "</select>\n";
        $navparts[] = $html;
    }

    return "<form>" . implode('<br>',$navparts) . "</form>";
}



function getTotalPrice($targetdir){
    $precio = 0;
    
    $pricefile = $targetdir.'/precio.txt';
    
    $fh = fopen($pricefile,'r');
    if(filesize($pricefile) > 0){
        $precio = fgets($fh);
    }
    
    fclose($fh);
    
    return $precio;
}



/**
 * Get an array of all media in the target directory, with titles if available
 * @param $targetdir The directory to get media from
 *
 * Get titles for each photo. Titles are in a file named "titles.csv" in each directory.
 * The first column is the file name, the second column is the title/caption to use
 *
 * Return an array where the key is the filename and the value is the title. If no
 * title is found the filename is used.
 */
function getMedia($targetdir){
    $media = Array();
    $html = "";
    $globby = "$targetdir/*.*";
    $files = glob($globby);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    foreach($files as $filename){
        if(preg_match('/(.*)_thumb\.([A-Za-z0-9]{3})/',$filename)){
            continue;
        }

        $mime = finfo_file($finfo,$filename);

        if(strpos($mime,'image') === 0 || strpos($mime,'video') === 0){
			if ( strpos( $mime, 'x-canon-cr2' ) !== false ) {
				continue;
			}
            $media[] = $filename;
        }
    }

    $titles = Array();

    if(is_file($targetdir . '/titles.csv')){
        $fh = fopen($targetdir . '/titles.csv','r');
        while(!feof($fh)){
            $line = fgetcsv($fh);
            if(count($line) >= 2 && file_exists($line[0])){
                $titles[$line[0]] = $line[1];
            }
        }
        fclose($fh);
    }

    foreach($media as $filename){
        $filename = basename($filename);
        if(!isset($titles[$filename])){
            $titles[$filename] = $filename;
        }
    }

    return $titles;
}

/**
 * Get the list of files from the target directory and generate the appropriate html
 *
 * @param $targetdir The target directory to get media from
 * @param $relpath The relative link for images
 */
function getSlides($targetdir,$relpath,$thumbnailSize){
    $media = getMedia($targetdir);
    $html = '';
    $path = "./galerias/";

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $html .= "<section class=\"layout\">";
    
    $num_fotos=count($media);
    //$precio = getTotalPrice($targetdir);
    
    if ($num_fotos > 60){
        
       
        $porcentaje = round(10 + ($num_fotos/10));
        if ($porcentaje > 50){
            $porcentaje = 50;
        }

        
        $html .= "<div id='TODAS' class='thumbnailwrapouter'>";
    
        $html .= "<span class='thumbnailinner' style='height: calc(500px * 0.4662109375)'><img data-mime='image/jpeg' src='TODAS.jpg' class='thumbnail'></span>";
        $html .= "<div class='filename'>TODAS LAS FOTOS ($num_fotos)</div><br>";
        $html .= "<div class='marcoseleccion'><span class='textoseleccion'>Todas con un $porcentaje% de descuento</span> <input class='seleccion' type='checkbox' name='TODAS-$num_fotos.jpg' value='TODAS-$num_fotos.jpg'></div>";
        $html .= "</div>";
    
    }

    
    foreach($media as $filename => $title){
      $thumbname = $relpath . '/' . preg_replace('/(.*)\.([A-Za-z0-9]{3})/',"$1" . "_thumb." . "$2",$filename);
      if(!is_file($thumbname)){
          $thumbname = "?d=$relpath&amp;t=$filename";
      }

      $filepath = preg_replace('#/+#','/', ($relpath == '' ? '' : $relpath . '/') . $filename);

      $filepath = $path . $filepath;

  	  $mime = finfo_file($finfo,$filepath);
      $image_info = getimagesize($filepath);


      $relacion_aspecto = $image_info[1] / $image_info[0];

      $nueva_altura = 0.7 * $relacion_aspecto;

      $html .= "<div id='$filename' class='thumbnailwrapouter'>";


      //print_r($mime);

			if(strpos($mime,'video') === 0){

				if ( filesize( $filepath ) > 5000000 ) {
					$preload_and_poster = 'poster="' . $thumbname . '" preload="none"';
				} else {
					$preload_and_poster = '';
				}
        $html .= "<span class='thumbnailinner'>";

        $mime = finfo_file($finfo, $filepath);

				$html .= '<video data-mime="' . $mime . '" width="' . ( $thumbnailSize * 0.7 ) . '" height="' . ( $thumbnailSize * 0.7 ). '" controls loop ' . $preload_and_poster . '>';
				$html .= '<source src="' . $filepath . '" type="' . $mime . '">';
				$html .= ' Your browser does not support the video tag.</video>';
			} else {
				//$html .= "<a href='$filepath' title='".htmlentities($title)."' class='swipebox thumbnaillink' rel='album' >";
        $html .= "<span class='thumbnailinner' style='height: calc(".$thumbnailSize."px * $nueva_altura)'>";

        $mime = finfo_file($finfo, $filepath);
				$html .= "<img data-mime='$mime' src='$thumbname' class='thumbnail'/>";

				//$html .= "</a>";
			}

      $html .= "</span>";

      $html .= "<div class='filename'>". $title ."</div><br>";
      $html .= "<div class='marcoseleccion'><span class='textoseleccion'>Selecciona tocando esta bolita</span> <input class='seleccion' type='checkbox' name='$title' value='$title'/></div></div>";
    }
    $html .= "</section>";
    if(count($media) === 0){
        return "<div class='error'>El selector de arriba sirve para elegir año, desfile y comparsa. Una vez hayas seleccionado año, desfile y comparsa podrás ver las miniaturas aquí.</div>";
    }
    return $html;

}

/**
 * Print and possibly save a thumbnail image
 */
function printThumbnail($targetdir,$thumbnailSize){
    $orig = $targetdir . '/' . $_GET['t'];

    if(!is_file($orig)){
        header("HTTP/1.0 404 Not Found");
        exit();
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
	$mime = finfo_file($finfo,$orig);
	if(strpos($mime,'video') === 0){
		$playButton = 'iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAYAAAA4qEECAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACbAAAAmwByAA4aQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAApzSURBVHic7Z1/TJT3Hcdfdx54HMVjFUEBAXGuSF3abskS61zS1rKsnVvMkg5IO6bJ2FYbTZZuWaym1C2x/WfAnDOYLf6gG11iTbqUSRN6xFRr8QeenPSkQokKOtEpCBwHd/d898fD6XG94349Pw7llXwC9zzf5/P98L4vz/N9ns/3+30MJBcpwErgG1NWAnwdeARIB7429RNgDLgz9XME6AG6gS+mfl4EPBrGPiMGneufBzwJfBdYA5QBVoV8u4BPgRPAceAYSSS8VjwOvA3cAIRGdhtoQP5SH2iswO+Az9FO3HD2OfBbYIGqf7HGZAE1yC1Kb4GD7S5QDyxW64/XggzgHWAU/QWNZCPALuSL7qxiPXAZ/QWM1QaAn6m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76iLKyshnLTExMUFtby+HDhxFCKFm9kgiPx/OKw+H4x0yFohWvHtiSeEz3ycnJwWazUVpaGnJ/T08P27Zt+8qYimRDkqR9drv9l5HKzYvSnw14HshPKKoAxsbGeP/997FYLOTl5d3LTgwMDNDY2Mhbb70VTXZZV3w+X4fX6/3JzZs3I17dYzkdZCGnZRSdmF9QUEBWVta9edoul0tJ96ohhLjscrme7u7uDpkoDCaW0Xq3kFv1lbgiC0N/fz9utxuXyzWbRB4UQjwfrcgQm9Agrxz2IvKCeoogSRJ9fX2aPZRPFCHEsNvt/oHdbr8Uy3HxjI++AKxFXqhbEcbHx8Ol6pMKIcTNycnJMqfT2RG59HTiHYj+ObLYF+M8/isMDg4yPDyslDs1+NJgMDzd1dV1Kp6DExnxfxlZ7JMJ+JjGlStXglP1SYHP5zs3OTn5dEdHR/hRjxGItnsXDhdwEHl96TUkeFMjSRLj4+OBWWS9EZIkHRgbG9tw8eLFhP7dlLzb+xGwH0hYpfz8/EQm5iiCEGLU5/O91tnZeVAJf4m26EC6gX8hv1lzRSKORkZGyMzMjGWgt6L4fL42r9f7osPhaFPKp1rr3awH/kwCLxwwm82UlJRounadEGLQ4/HUXLhwYa/SvpVs0YF8Afxt6vcnkc/hMeH1evH5fLHOFYmXMUmS/pqenr7h7Nmzqjwi1GIFpwXAr5Hfzhnz+Xv58uWqiS2EGPP5fAfT0tJ2tre331Clkim0fLnvAqAa+Dnym4miwmQysXLlSkXP10KIHo/H867JZKoPzlarhV5vUX4cefG9KqJ4DWlGRgYrViR0fUUIMez1epu9Xu9+p9PZmpCzOND7ddVG5PeArwHWMcPrqvPy8sjJif79MkKIcSHEOUmS2nw+39Gurq6TTA041AO9hQ7GhLwijt/8XcVHDAZDRklJyUKLxWKZyra4DAbDCDDm8XjGjEbjl8AXBoOh2+12X3A6nZ1A0txm/h/m0xSyouKIwwAAAABJRU5ErkJggg==';
		header('Content-Type: image/png');
		print base64_decode($playButton);
		exit();
	}

    // This is going to slow down the user experience...
    if (!extension_loaded('gd') || !function_exists('gd_info')) {
        readfile($orig);
        exit();
    }

    try {
        $image_info = getimagesize($orig);
        /*switch($image_info[2]){
        case IMAGETYPE_JPEG:
            header('Content-Type: image/jpeg');
            $img = imagecreatefromjpeg($orig);
            $outfunc = 'imagejpeg';
            break;
        case IMAGETYPE_GIF:
            header('Content-Type: image/gif');
            $img = imagecreatefromgif($orig);
            $outfunc = 'imagegif';
            break;
        case IMAGETYPE_PNG:
            header('Content-Type: image/png');
            $img = imagecreatefrompng($orig);
            $outfunc = 'imagepng';
            break;
        default:
			header('Content-Type: ' . $mime);
            readfile($orig);
            exit();
        }*/
        header('Content-Type: ' . $mime);
        readfile($orig);
        exit();

        /*
        $width = $image_info[0];
        $height = $image_info[1];

        if ($width > $height) {
            // The actual minimum dimension to match the CSS
            $resizeFactor = $thumbnailSize / 1.0;
            $newwidth = $resizeFactor;
            $newheight = floor($height / ($width / $resizeFactor));
        } else {
            // The actual minimum dimension to match the CSS
            $resizeFactor = $thumbnailSize / 1.0;
            $newheight = $resizeFactor;
            $newwidth = floor($width / ($height / $resizeFactor) );
        }

        $newwidth = $image_info[0];
        $newheight = $image_info[1];

        $tmpimg = imagecreatetruecolor( $newwidth, $newheight );
        imagecopyresampled($tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
        if(function_exists('imagecrop')){
            $tmpimg = imagecrop($tmpimg,Array(
                'x' => $newwidth / 2 - ($thumbnailSize * 1.0) / 2,
                'y' => $newheight / 2 - ($thumbnailSize * 1.0) / 2,
                'width' => $thumbnailSize * 1.0,
                'height' => $thumbnailSize * 1.0
            ));
        }
        $outfunc($tmpimg, $thumb);

        if(file_exists($thumb)){
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$thumb_mime = finfo_file($finfo,$thumb);
			header('Content-Type: ' . $thumb_mime);
            readfile($thumb);
        }else{
            $outfunc($tmpimg);
        }
        */
    } catch (Exception $e){
        error_log($e);
		    header('Content-Type: ' . $mime);
        readfile($orig);
    }

}

$targetdir = getTargetPath($path);
$relpath = trim(str_replace($path,'',$targetdir),'/');

/**
 * Include any addons
 */
$moreHtml = Array();
/*foreach(glob("instaGallery_*.inc") as $plugin){
    include($plugin);
}*/

/**
 * Print the thumbnail and exit
 */
if(isset($_GET['t'])){
    printThumbnail($targetdir,$thumbnailSize);
    exit();
}

$nav = getNav($path,$relpath);
$slides = getSlides($targetdir,$relpath,$thumbnailSize);

//////////////////////
// HTML Page
$title = "Elige una colección de miniaturas - aritmodecarnaval.es";

if($relpath !== './'){
    $title = explode('/',trim($relpath,'/'));
    $title = array_map('prettyName',$title);
    $title = implode(' | ',$title);
}
?>
<!DOCTYPE HTML>
<html><head>
  <meta charset='UTF-8'>

  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">

  <title><?=$title?> - aritmodecarnaval.es</title>
  <link rel='stylesheet' type='text/css' href='style.css'>


<link href='//fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>
<link href='//cdn.rawgit.com/brutaldesign/swipebox/master/src/css/swipebox.min.css' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style type='text/css'>
html,body {
    margin: 0;
    padding: 0;
    height: 100%;
    color: #444;
    text-align: center;
    font-family:arial;
}

#nav {

  background: rgba(255,255,255,0.3);

  text-align: center;
  margin: 0 auto;
}

#nav a {
  color: white;
}

#nav form {
  padding-top:15px;
}

#slides {
    padding-top: 25px;
    max-width: 100%;
    border: 2px beveled black;
}

input[type='checkbox'] {

    -webkit-appearance: none;
    width: 40px;
    height: 40px;
    background: white;
    border-radius: 21px;
    border: 2px solid #000;
}
input[type='checkbox']:checked {
    background: #f80;
}

.marcoseleccion {
  position: relative;
  bottom: 102px;
  right: 7px;
  float: right;
  background-color: rgba(0,0,0,0.5);
  border-radius: 25px;
  padding: 2px 2px 0px 5px;
}

.textoseleccion {
  position: relative;
    bottom: 15px;
    color: white;
    font-weight: bold;

}

.seleccion{
    position: relative;
      bottom: 0px;
      left: 0px;
}



#logout a{
    color: white;
      background-color: rgba(0,0,0,0.3);
      padding: 8px;
      border-radius: 20px;
      position: relative;
      top: 15px;

}

.error {
    margin: 50px calc(25% - 25px/2);
    padding: 25px;
    border: 5px groove #ccc;
    background-color: rgba(255,255,255,0.6);
}

.thumbnailwrapouter {
    width: calc(<?=$thumbnailSize?>px * 0.7);
}

.thumbnailinner {
    display: inline-block;
    height: calc(<?=$thumbnailSize?>px * 0.8);
    width: calc(<?=$thumbnailSize?>px * 0.7);
    overflow: hidden;

  margin: 0px 0px !important;
  background-color:#000;
  border-radius: 36px !important;
  border-style: solid !important;
  border-width: 2px 2px 2px 2px !important;
  border-color: #ffffff !important;
  box-shadow: 3px 3px 4px 0px #000000 !important;
}

img.thumbnail {
	width: 100%;
}

.filename {
  position: relative;
  border-radius: 10px;
  padding: 5px 10px 0px 10px;
  bottom: -4px;
  background-color: rgba(0,0,0,0.5);
    margin: 0 10px;
    color:white;
    font-family: 'Arial', cursive;
    font-size: 20px;
    /*overflow: hidden;*/
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: calc(100% - 30px);
}

#ctrlbox {
    z-index: 1000;
    position: absolute;
    top: 0;
    right: 50px;
    height: 50px;
    width: 120px;
    text-align: right;
    color: white;
    font: larger bold;
    cursor: pointer;
}

#ctrlbox i {
    padding: 15px;
}
#footer {
    margin: 30px;
    color: white;
    padding-bottom:10px;
}

#footer a {
  font-family: Arial;
    text-decoration: none;
    color: #fff;
    font-weight: bold;
}

.layout {
  width: 100%;

  display: flex;
  gap: 16px;
  flex-wrap: wrap;

  justify-content: center;
  align-items: center;
  margin-left: -3px;
}

select {
    font-size:20px;
    padding:3px;
    margin: 10px;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    border: solid 1px #999;
    background: #fff;
    color:#000;
    outline:none;
    display: inline-block;
    cursor:pointer;
}

.formulario {
  font-size:24px;
  width: 360px;
  border-radius: 15px;
}

.formulario_text {
  font-size:16px;
  width: 360px;
  border-radius: 15px;
}

.titulos_formulario{
  color:#fff;
  font-size:20px;
}

#botonflotante {
  position:fixed;
  bottom: 20px;
      right: 10px;
      width: 300px;
}

#mensaje{
  color:#fff;
  font-size:16px;
  max-width:900px;
  margin: 0 auto;
  text-align:left;
}


.home {
  color: white;
    background-color: rgba(0,0,0,0.3);
    padding: 8px;
    border-radius: 20px;
  font-size: 20px;
  font-family: sans-serif;
    text-decoration: none;
    color: #000
}
.home:hover {
    text-decoration: underline;
}

</style>
    <script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='//cdn.rawgit.com/brutaldesign/swipebox/master/src/js/jquery.swipebox.js'></script>

    
</head>
<body>

  <div id='contenedor'>
    <p><br><br></p>
    <img id='logo' class='center' src='https://www.aritmodecarnaval.es/wp-content/uploads/2018/03/cropped-A-Ritmo-de-Carnaval-Mosca-1.png'>

    <div id='nav'>
        <?=$nav?>
    </div>
    <div id='slides'>
        <?=$slides?>
    </div>
    <div id='mensaje'>
        <p style="padding-left:10px;"><b>IMPORTANTE: POR FAVOR, LEER</b></p>
        <ul>
        <li>1- Las fotografías son archivos JPG, no son impresas en papel, que se descargarán a través de un enlace web.</li>
        <li>2- El pago será por adelantado, y se realizará justo después de hacer el pedido, indicandose un teléfono al que hacer dicho pago. Si no se realiza el pago por adelantado, el pedido no será tenido en cuenta.</li>
        <li>3- Se prefiere BIZUM, pero si se quiere utilizar otro método de pago, coméntelo por whatsapp en el telefono que se le pasará para el pago.</li>
        <li>4- En un pedido de comparsa, se pueden añadir fotografías de una misma comparsa y mismo desfile.</li>
        <li>5- Si es un pedido individual, se pueden añadir fotografías de una misma persona de distintos desfiles.</li>
        <li>6- Una comparsa puede hacer varios pedidos indicando mismo nombre y contacto. Será considerado un único pedido y se beneficiará de los descuentos por cantidad. En este caso, un responsable de la comparsa tendría que ponerse en <a href="https://www.aritmodecarnaval.es/contacto" style="color:white">contacto</a> con nosotros una vez hecho todos los pedidos para que le indiquemos el precio final y proceder al pago.</li>
        <li>7- Los pedidos serán atendidos con un plazo máximo de 15 días desde la fecha del pago. Si ya ha pasado ese tiempo y no tiene noticias nuestras, póngase en <a href="https://www.aritmodecarnaval.es/contacto" style="color:yellow">contacto</a> con nosotros.</li>
        <li>8- Si las fotos de tu comparsa no están, puedes solicitarlas en el siguiente enlace: <a href="https://forms.gle/6Qym5AMYPAoFYn249" style="color:yellow">Solicitud de revelado</a>. Daremos prioridad a las comparsas que realicen dicha solicitud dado al gran volumen de pedidos.</li>
        </ul>
        
    </div>
    <div id='formulario'>
        <form name="pedido" action="mailsender.php" method="POST" enctype="multipart/form-data" onsubmit="return validateAndConfirmForm();">
          <p><span class='titulos_formulario'>Nombre</span><br>
          <input class='formulario' type='text' name='client_name' id='client_name' value='' size="20"></p>
          <p><span class='titulos_formulario'>Contacto<br> <small><small>(instagram/whatsapp/email) Puedes poner más de uno. Comprueba frecuentemente tu carpeta de SPAM si pones tu correo.</small></small></span><br>
          <input class='formulario' type='text' name='client_contact' id='client_contact' value='' size="20"></p>
          <p><span class='titulos_formulario'>Fotos seleccionadas <small><small>(se rellena automáticamente)</small></small></span><br>
          <textarea class='formulario_text' id="client_selection" name="client_selection" rows="12" cols="20" readonly>
No ha seleccionado ninguna foto.
          </textarea>
          <input type='hidden' value='0' name='precio_final'>
          </p>
          <p><input class="myButton" type="submit" value="Hacer pedido" style="width:200px" onsubmit="aviso();"></p>

        </form>
    </div>
    <div id='botonflotante'>
        <a id="fotos_pedidas" onclick="window.scrollTo(0, document.body.scrollHeight); return false;" class="myButton">Ver resumen pedido: 0 fotos (0€)</a>
    </div>
    <div id='footer'>
        <!--<a href='https://www.aritmodecarnaval.es'>A Ritmo de Carnaval</a>-->

    </div>
    <?php print implode("\n",$moreHtml); ?>
  </div>
  <script>

  $(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() + 600 >= $(document).height()) {
       document.getElementById('fotos_pedidas').style.display='none';
    }else{
       document.getElementById('fotos_pedidas').style.display='block';
    }
  });

    var fotos_pedidas = 0;

    function getPrecio(cantidad){
      var precio = 0.0;
      if (cantidad <= 10){
        precio = cantidad * 1.99;
      }
      else if (cantidad > 10 && cantidad <= 20){
        precio = 19.90 + (cantidad-10) * 1.49;
      }
      else if (cantidad > 20 && cantidad <= 50){
        precio = 19.90 + 14.90 + (cantidad-20) * 1.19;
      }
      else if (cantidad > 50){
        precio = 19.90 + 14.90 + 11.90*3 + (cantidad-50) * 0.99;
      }
      return precio;
    }


    
    
    function validateAndConfirmForm() {
      if (fotos_pedidas<=0){
        alert("No has seleccionado ninguna fotografía.");
        return false;
      }


      var a = document.forms["pedido"]["client_name"].value;
      var b = document.forms["pedido"]["client_contact"].value;
      
      /*if (b == "lorena_albaladejo@hotmail.com"){
        alert ("Ha sido baneada por hacer múltiples pedidos. Póngase en contacto con nosotros para solucionar el problema y quitar el baneo. Un saludo");
        return false;
          
      }*/
      

      if (a == null || a == "", b == null || b == "") {
        alert("Falta por poner tu nombre y forma de contacto.");
        return false;
      }
      
      return confirm('¿Has leido el texto importante con los 7 puntos? Si es así puedes continuar con el envío. Sino, cancela y léelos, por favor. Continuar implica la aceptación de los 7 puntos mencionados.');
    }



      $('a.swipebox').swipebox({
          hideBarsDelay: -1,
          afterOpen: function(){
              var ui = $.swipebox.extend();
              var close = $('#swipebox-close');
              var fs = $('<i class="fa fa-arrows-alt"></i>');
              fs.on('click',function(){
                  var elem = $('#swipebox-overlay')[0];
                  if (elem.requestFullscreen) {
                      elem.requestFullscreen();
                  } else if (elem.msRequestFullscreen) {
                      elem.msRequestFullscreen();
                  } else if (elem.mozRequestFullScreen) {
                      elem.mozRequestFullScreen();
                  } else if (elem.webkitRequestFullscreen) {
                      elem.webkitRequestFullscreen();
                  }
              });

              var pp = $('<i id="ppbutton" class="fa fa-play"></i>');
              pp.on('click',function(e){
                  var button = $(e.target);
                  if(button.hasClass('fa-play')){
                      button.removeClass('fa-play').addClass('fa-pause');
                      button.attr('data-intid',window.setInterval(function(){ui.getNext()},5000));
                  }else{
                      button.removeClass('fa-pause').addClass('fa-play');
                      window.clearInterval(button.attr('data-intid'));
                      button.attr('data-intid','');
                  }
              });
              var ctrlbox = $("<div id='ctrlbox'>");
              ctrlbox.append(pp);
              ctrlbox.append(fs);
              close.after(ctrlbox);

              // Play/pause button
              // Spacebar/Enter advances
              // big Fullscreen
          },
          afterClose: function(){
              window.clearInterval($('#ppbutton').attr('data-intid'));
          }
      });

      $('.navchange').on('change',function(e){
          if(('d=' + e.target.value) != document.location.search){
              document.location.search = 'd=' + e.target.value;
          }
      });


      $('.seleccion').on('change',function(e){
          if (e.target.checked){
            fotos_pedidas++;
          }
          else {
            fotos_pedidas--;
          }
          
          seleccion = "Estas son las fotografías elegidas:\nColección:";

          $('.navchange option:selected').each(function()
          {
            seleccion = seleccion + "\n   /" + $(this).text();
          });

          seleccion = seleccion + "\nListado de fotografías:";

          var todas = false;
          var descuento_todas = 0;
          var precio_todas = 0;
          var cantidad_todas = 0;
          var porcentaje_descuento = 0;
          $('input:checkbox:checked').each(function()
          {
            
            if ($(this).val().startsWith("TODAS")){
                var primera_div = $(this).val().split(".");
                var segunda_div = primera_div[0].split("-");
                
                cantidad_todas = segunda_div[1];
                
                porcentaje_descuento = ( 10 + (cantidad_todas / 10) ).toFixed(0);
            
                if (porcentaje_descuento > 50){
                    porcentaje_descuento = 50;
                }
                    
                
                precio_todas = getPrecio(cantidad_todas);
                descuento_todas = (precio_todas * porcentaje_descuento/100).toFixed(2);
                precio_todas = (precio_todas - descuento_todas).toFixed(2);
                todas = true;
                seleccion = seleccion + "\n   Todas las fotografías ("+cantidad_todas+")";
            }
            else {
                seleccion = seleccion + "\n   " + $(this).val();
            }

          });
          
          if (todas){
              $('#fotos_pedidas').html("Ver resumen pedido: " + cantidad_todas + " fotos por " + precio_todas + "€ descontado el "+porcentaje_descuento+"% ("+ getPrecio(cantidad_todas).toFixed(2) +"€ - "+ descuento_todas +"€)");

              seleccion = seleccion + "\n\nNumero de fotos: " + cantidad_todas + " fotos por " + precio_todas + "€ descontado el "+porcentaje_descuento+"% ("+ getPrecio(cantidad_todas).toFixed(2) +"€ - "+ descuento_todas +"€)\n";

              $('#client_selection').val( seleccion );
              
              document.forms["pedido"]["precio_final"].value = precio_todas;
          }
          else {
              $('#fotos_pedidas').html("Ver resumen pedido: " + fotos_pedidas + " fotos (" + getPrecio(fotos_pedidas).toFixed(2) + "€)");

              seleccion = seleccion + "\n\nNumero de fotos: " + fotos_pedidas + " fotos (" + getPrecio(fotos_pedidas).toFixed(2) + "€)\n";

              $('#client_selection').val( seleccion );
              
              document.forms["pedido"]["precio_final"].value = getPrecio(fotos_pedidas);             
              
              
          }

      });

      $(document).on('keyup',function(e){
          if((e.keyCode == 32 || e.keyCode == 13) && $('#swipebox-overlay').length > 0){
              $.swipebox.extend().getNext();
          }
      });
  </script>

  </body>
</html>