<?
if ( $user_auth && $user_level <= -1 )
{
 $blq1 ="ide, nombre, comentario, cache, equipoSonidoLuces, estadisticas, croquiMusicos, sugerenciasGrupo, contratacion";
 $list = true;

 if ( isset( $sins ) )
 {
	displayForm( "./?dgo=adm/grupos.php&ins=new" );
	$list = false;
 }
 if( isset( $ins ) )
 {
	if ( !empty($imgData_name) && $imgData_size > 0 )
		  {
			$img_prop = GetImageSize($imgData);
			$db_Foto_w = $img_prop[0];
			$db_Foto_h = $img_prop[1];
			$addsql_p1 = ",Foto, Foto_w, Foto_h";
			$addsql_p2 = ",'$imgData_name', '$db_Foto_w', '$db_Foto_h'";
		  }		

	$sql = "INSERT INTO grupos (FAlta, $blq1 $addsql_p1) VALUES (NOW(), '$db_ide','$db_nombre','".urlencode($db_comentario)."','$db_cache','$db_equipoSonidoLuces', '$db_estadisticas', '$db_croquiMusicos', '$db_sugerenciasGrupo', '".urlencode($db_contratacion)."' $addsql_p2)";
	$res = @mysql_query( $sql, $conexion ) OR die( "Error<br>".@mysql_error($conexion) );
	$last_id = @mysql_insert_id($conexion);

	if ( !empty($imgData_name) && $imgData_size > 0 )
	{
		$file_size = filesize($imgData);
		fwrite( fopen("db/grupos/".$last_id."_i001@".$imgData_name, "wb"),
			fread(fopen($imgData,"rb"),$file_size), $file_size);
		
	}
        echo "<h1>Grupo insertado</h1><br><br><br>";
        echo "<p class=remark>ID asignado = ".$last_id."<br>Agrege ahora los componentes del Grupo</p>";

	displayForm( "./?dgo=adm/grupos.php&mod=$smod" );
	$list = false;
 }

 if ( isset( $insc ) )
 {
 
 	if ( isset( $db_ida ) && !empty( $db_ida ) )
 	{
 	 $res = @mysql_query( "SELECT id FROM artistas WHERE id='$db_ida'", $conexion );
 	 if ( @mysql_num_rows( $res ) > 0 )
 	 	@mysql_query( "INSERT INTO componentesGrupo (idg, idp) VALUES ('$insc','$db_ida')", $conexion );
 	}
 	$smod = $insc;
 }

 if ( isset( $smod ) ) 
 {	
	$res = @mysql_query( "SELECT id,$blq1  FROM grupos WHERE id=$smod", $conexion );
	$datos = @mysql_fetch_array( $res );

	list( $db_id, $db_ide, $db_nombre, $db_comentario, $db_cache,
		 $db_equipoSonidoLuces, $db_estadisticas, $db_croquiMusicos,
		 $db_sugerenciasGrupo, $db_contratacion ) = $datos;

	echo "<a href='./?dgo=adm/grupos.php'>Listado de Grupos</a>-&gt;<a href='./?dgo=adm/discos.php&filter=$smod'>Sus Discos</a>-&gt;[<a href='./?dgo=adm/grupos.php&smod=$smod'>Refrescar</a>]";

	displayForm( "./?dgo=adm/grupos.php&mod=$smod" );
	displayListC( $conexion, $smod, "./?dgo=adm/grupos.php&insc=$smod" );
	$list = false;
 }
 
 if ( isset( $mod ) )
 {
	if ( !empty($imgData_name) && $imgData_size > 0 )
		  {
			$img_prop = GetImageSize($imgData);
			$db_Foto_w = $img_prop[0];
			$db_Foto_h = $img_prop[1];
			$addsql_p1 = ",Foto='$imgData_name', Foto_w='$db_Foto_w', Foto_h='$db_Foto_h'";
		  }		

	$sql = "UPDATE grupos SET ".
		"nombre='$db_nombre' ".
		",comentario='".urlencode($db_comentario)."' ".
		",cache='$db_cache'".
		",equipoSonidoLuces='$db_equipoSonidoLuces'".
		",estadisticas='$db_estadisticas'".
		",croquiMusicos='$db_croquiMusicos'".
		",sugerenciasGrupo='$db_sugerenciasGrupo'".
		",contratacion='".urlencode($db_contratacion)."'".
		" $addsql_p1".
		" WHERE id=$mod";
	$res = @mysql_query( $sql, $conexion );
	
	if ( !empty($imgData_name) && $imgData_size > 0 )
	{
		$file_size = filesize($imgData);

		fwrite( fopen("db/grupos/".$mod."_i001@".$imgData_name, "wb"),
			fread(fopen($imgData,"rb"),$file_size), $file_size);
	}
	$list = true;
 }
 if( isset( $del ) )
 {
	if ( !unlink( "grupos/".$del."_i001*" ) )
		echo "<h1>No he podido eliminar la imagen asociada:</h1><br><p class=remark>Borre el fichero: grupos/$del"."_i001 manualmente por favor...<br>";
	else
		echo "<li>Ficheros asociados eliminados</li>";

	$res = @mysql_query( "UPDATE grupos SET parent='0' WHERE parent=$del", $conexion );
	echo "<li>grupos heredados, descompuestos</li>";
	$res = @mysql_query( "DELETE FROM grupos WHERE id=$del", $conexion );
	echo "<li>Estilo $del, ELIMINADO</li><br>";
	$list = true;
 }

 if ( isset( $list ) && $list )
 {
   if ( !isset($orderBy) ) $orderBy ="id";
   if ( !isset($orderDir) ) $orderDir ="ASC";

   echo "Listado de grupos >> Ver listado<br><br>";
   displayList($conexion, $orderBy, $orderDir);
 }
 displayMenu();
}

function cambiaProporciones()
{
 global $db_Foto_w, $db_Foto_h;
 $W = 150; $H=150; 

 // Las proporciones correctas seran de 100x100
// $db_Foto_w=50;
// $db_Foto_h=50;

 if ( $db_Foto_w > 0 )
 {
  if ( $db_Foto_w > $db_Foto_h )
  {
	  $db_Foto_h = intval(($db_Foto_h/$db_Foto_w)*$W); $db_Foto_w=$W;
  } else {
	  $db_Foto_w = intval(($db_Foto_w/$db_Foto_h)*$H); $db_Foto_h=$H;
  }
 }

}

function displayListC( $cnx, $idg, $url_form )
{
 $res = @mysql_query( "SELECT a.id, CONCAT(a.nombre, ' ', a.apellido) AS Artista FROM componentesGrupo AS c LEFT JOIN artistas a ON( a.id=c.idp ) WHERE c.idg = " . $idg, $cnx );
 
 echo "<br><br><br>";
 echo "<a name=\"componentes\"></a><form name='comp' method=POST action=$url_form"."#componentes><table width=100% cellpadding=0 cellspacing=0 class=\"td_lista\"><tr>";
 echo "<td class=menuL>id</td>";
 echo "<td class=menuL>Nombre del Artista</td>";
 echo "<td class=menuL>Borrar</td>";
 echo "</tr>";
 
 while( $datos=@mysql_fetch_array($res) )
 {
   list ( $db_ida, $db_nomb ) = $datos;
   echo "<tr><td><a href=\"./?dgo=adm/artistas.php&smod=$db_ida\">$db_ida</a></td>";
   echo "<td>$db_nomb</td>";
   echo "<td><a href=\"./?dgo=adm/grupos.php$delc=$db_id\"><img src=\"images/actions/cancel.gif\" border=0></a></td>";
   echo "</tr>";
 }
 echo "<tr><td><br><br></td><td></td><td></td></tr>";
 echo "<tr><td>&nbsp</td><td><input type=submit value=\"Nuevo artista\"> -= ID: <input type=text name=\"db_ida\" value=\"\"></td><td></td></tr>";
 echo "</table></form>";
 
 
}

function displayList($cnx, $orderBy, $orderDir, $filter)
{
 $thisLOCATION = "./?dgo=adm/grupos.php";
 $res = @mysql_query( "SELECT g.id, g.nombre, e.titulo FROM grupos AS g LEFT JOIN estilos AS e ON (g.ide=e.id) $filter ORDER BY e.$orderBy $orderDir", $cnx ) OR die( "Error<br>".@mysql_error($cnx) );

 $parity = true;

 echo "<br><br><br><table width=100% cellpadding=0 cellspacing=0 class=td_lista><tr>";

 echo "<td class=menuL>id <a href=\"$thisLOCATION&oderBy=id&orderDir=DESC\"><img src=\"images/actions/down.gif\" border=0></a><a href=\"$thisLOCATION&oderBy=id&orderDESC=ASC\"><img src=\"images/actions/up.gif\" border=0></a></td>".
      "<td class=menuL>Nombre del Grupo <a href=\"$thisLOCATION&oderBy=nombre&orderDir=DESC\"><img src=\"images/actions/down.gif\" border=0></a><a href=\"$thisLOCATION&oderBy=nombre&orderDESC=ASC\"><img src=\"images/actions/up.gif\" border=0></a></td>".
      "<td class=menuL>Estilo <a href=\"$thisLOCATION&oderBy=ide&orderDir=DESC\"><img src=\"images/actions/down.gif\" border=0></a><a href=\"$thisLOCATION&oderBy=ide&orderDESC=ASC\"><img src=\"images/actions/up.gif\" border=0></a></td>".
      "<td class=menuL>Borrar</td></tr>";

 while( $datos=@mysql_fetch_array($res) )
 {
  list ( $db_id, $db_nombre, $db_estilo )= $datos;
  $parity = !$parity;
  
  echo "<tr><td><a href=\"$thisLOCATION&smod=$db_id\">$db_id</a></td>" .
       "<td>$db_nombre</td>".
       "<td>$db_estilo</td>".
       "<td><a href=\"javascript::deleteID($db_id)\"><img src=\"images/actions/cancel.gif\" border=0></a></td></tr>";
      
 }

 echo "</table>";
 echo '<script language="JavaScript"> 
	function deleteID( which )
	{
	  var submitOK = confirm("Atencion: Esta a punto de eliminar el grupo.");
	  if ( submitOK )
		  document.location.href = "'.$thisLOCATION.'&orderBy='.$orderBy.'&orderDir='.$orderDir.'&del="+which;
	}
	</script>';
}

function displayMenu()
{
 echo '<hr noshade color="#800000">';
 echo '<p align="center"><a href="./?dgo=adm/grupos.php&sins=new">Insertar nuevo grupo</a></p>';
 echo '<hr noshade color="#800000">';
}

function displayForm( $form_action )
{
 global $db_ide, $db_nombre, $db_comentario, $db_cache,
	$db_equipoSonidoLuces, $db_estadisticas, $db_croquiMusicos, 
	$db_sugerenciasGrupo, $db_contratacion;

 global $imgData;

 echo '<form action="'.$form_action.'" method="POST" name="register"  enctype="multipart/form-data" onsubmit="return validateform( this.form )">';
 echo '<p align="center">&nbsp;</p><div align="center"><center><table border="0" cellpadding="0" cellspacing="0" width="100%">';
 echo '<tr>
            <td><h1>Datos del grupo</h1>
            <p>&nbsp;</p>
            <table border="0" cellpadding="0" cellspacing="0"
            width="100%" bgcolor="#800000">
                <tr>
                    <td>&nbsp;</td>
                </tr>
            </table>
            <table border="0" width="100%">
                <tr>
                    <td width="30%">Grupo:</td>
                    <td width="20%"><input type="text" size="15"
                    name="db_nombre"
                    value="'.$db_nombre.'"></td>
                    <td valign="top" rowspan="3" width="50%"
                    bgcolor="#B4CCE9" class="tdSuave"><strong>Informaci�n
                    del grupo</strong><p>Aqui van el nombre del grupo y descripci�n del mismo. <br>
Tambien puede agregar una imagen que represente a este grupo. Recuerde que deberia ser JPG con un tama�o de 50x50 m�ximo. <br><br>No se olvide de asociar un estilo al grupo para que este pueda ser clasificado.</p>
                    <p>ATENCION: �� Se admiten controles HTML
                    !!, por lo que aconsejamos sea muy cuidadoso
                    con los mismos.</p>
                    </td>
                </tr>
                <tr>
                    <td width="30%">Estilo:</td>
                    <td width="20%"><select name="db_ide" size="1">
			<option value="0">ninguno</option>';

		 global $conexion;
		 $resp = @mysql_query( "SELECT id, titulo FROM estilos WHERE parent ='0' Order By titulo", $conexion );
		 while( $datos=@mysql_fetch_array($resp) )
		 {
			list ( $epid, $eptit ) = $datos;
			echo "<option value=\"$epid\"";
			if ( $epid == $db_ide ) echo " SELECTED";
			echo ">$eptit</option>";
		 }
echo '</select></td>
                </tr>
                <tr>
                    <td colspan="2" width="30%">Comentarios
                    adicionales:<p><textarea name="db_comentario" rows="5"
                    cols="20">'.urldecode($db_comentario).'</textarea></p>
                    </td>
                </tr>
                <tr>
                    <td width="30%"> Foto:</td>
                    <td width="70%" colspan="2">
			<input type="file" size="15" name="imgData"></td>
		    <td></td>
                </tr>            
                <tr>
                    <td width="30%"> Cache:</td>
                    <td width="70%" colspan="2">
			<input type="text" size="30" name="db_cache" value="'.$db_cache.'"></td>
                </tr>            
                <tr>
                    <td width="30%"> Equipo de sonido y luces:</td>
                    <td width="70%" colspan="2">
			<input type="text" size="30" name="db_equipoSonidoLuces" value="'.$db_equipoSonidoLuces.'"></td>
                </tr>            
                <tr>
                    <td width="30%"> Estadisticas:</td>
                    <td width="70%" colspan="2">
			<input type="text" size="30" name="db_estadisticas" value="'.$db_estadisticas.'"></td>
                </tr>            
                <tr>
                    <td width="30%"> Croquis Musicos:</td>
                    <td width="70%" colspan="2">
			<input type="text" size="30" name="db_croquiMusicos" value="'.$db_croquiMusicos.'"></td>
                </tr>            

                <tr>
                    <td width="30%"> Sugerencias del Grupo:</td>
                    <td width="70%" colspan="2">
			<input type="text" size="30" name="db_sugerenciasGrupo" value="'.$db_sugerenciasGrupo.'"></td>
                </tr>        

                <tr>
                    <td width="30%"> Contratacion:</td>
                    <td width="70%" colspan="2">
			<textarea name="db_contratacion" rows="5" cols="30">'.urldecode($db_contratacion).'</textarea>   
		    </td>
                </tr>        


	</table>

            <hr noshade color="#800000">
            <p align="center"><input type="button" name="btCancelar" value="Cancelar"><input
            type="submit" name="B2" value="Enviar &gt;&gt;"></p>

            <p><script language="JavaScript"><!--

function validateform(wf)
{

if (document.register.db_nombre.value=="")
{
	window.alert ("Por favor, introduce el nombre del grupo")
	return false;
}
if (document.register.db_comentario.value=="")
{
	window.alert ("Por favor, introduce algun comentario sobre este grupo")
	return false;
}
}
// --></script><br>
            </p>
            </td>
        </tr>
    </table>
    </center></div>
</form>';
}
?>