<?php

$errorMsg = "";
//Load Wordpress
require('../../../../../wp-load.php');

if (count($_FILES) > 0) {

    // SOLO SE PERMITE EL FORMATO JPG
    $size=$_FILES['file']['size'];
    $mime=$_FILES['file']['type'];
    if ($_FILES['file']['tmp_name']) $tam=getimagesize($_FILES['file']['tmp_name']);

    // Filename
    $tmp_filename="tmp_avatar_".time().".jpeg"; //.substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], "."));
    $filename = str_replace("tmp_","",$tmp_filename);
    
    //FILESIZE
    $filesize = $_FILES['file']['size'];

    // CHEQEOS
    $validMimes = array(
        "image/jpeg",
        "image/pjpeg",
        "image/png",
        "image/gif",
    );

    if ($size<2500000 && in_array($mime, $validMimes)) {
        $result=0;
    } else {

        $errorMsg =  sprintf(__("Formato de imagen no aceptado : %s", 'buddypress'),$mime);
        $result=2;
    }
    
    // SI PASA LOS CHEQEOS, SUBIMOS LA IMAGEN
    if ($result==0){
        
        global $bp;

        // Ruta a uploads
        $path= str_replace("\\","/", getcwd())."/../../../../uploads/avatars/signups";
        // Si no existe la carpeta /tmp la crea
        if (!file_exists($path)) {
            // chmod
            mkdir($path, 0777, true);
            chmod($path, 0777);

            //echo "creando carpeta : ".$path;
        }

        // Rutas completas
        $tmp_dest_path = $path."/".$tmp_filename;

        //Resize Avatar thumnail
        $dest_path = $path."/".str_replace(".jpeg","",$filename)."-bpfull.jpeg";

        if(move_uploaded_file($_FILES['file']['tmp_name'], $dest_path)) {
            $result = 1;
        }

        if ($tam[0]>"150" || $tam[1]>"150") {

            ImgResize($dest_path, $dest_path, 150,150);

        } else {
            
            ImgResize($dest_path, $dest_path, $tam[0], $tam[1]);
        }
        chmod($dest_path, 0777);

        //Create avatar thumnail
        $dest_path_thumb = $path."/".str_replace(".jpeg","",$filename)."-bpthumb.jpeg";
        copy($dest_path, $dest_path_thumb);
        chmod($dest_path, 0777);

        if ($tam[0]>"50" || $tam[1]>"50") {
            
            ImgResize($dest_path_thumb, $dest_path_thumb, 50, 50);
        }

        if (file_exists($tmp_dest_path)) {
            unlink($tmp_dest_path);
        }
    }

    // This is to avoid caching of the avatar image
    $rnd=rand(1465,57892);

    // Display the uploaded image
    if ($errorMsg == "") {
    ?>
    <html>
        <head>
            <script type='text/javascript' src='<?php echo site_url(); ?>/wp-includes/js/jquery/jquery.js?ver=3.1.2-alpha'></script>
        </head>
        <body >

            <img src="<?php echo site_url(); ?>/wp-content/uploads/avatars/signups/<?php echo str_replace(".jpeg","",$filename)."-bpfull.jpeg" ?>?key=<?php echo $rnd ?>"
            style="display: block; margin: 15px auto; width:90px;" alt="Tu Avatar" title="<?php _e( 'Tu Avatar', 'buddypress' ) ?>" />

            <script type="text/javascript">

                (function(jQuery) {
                    var $ = jQuery;

                    $("#userAvatar",parent.document);
                    $("#userAvatar",parent.document).attr("value", '<?php echo str_replace(".jpeg","",$filename)."-bpfull.jpeg"; ?>');
                    $("#userAvatarMime",parent.document).attr("value", "<?php echo $mime; ?>");
                    $("#userAvatarSize",parent.document).attr("value", "<?php echo $filesize; ?>");

                })(jQuery);
        
            </script>
        </body>
    </html>
    <?php
    }

    // Add some sleep to let the file upload correctly
    sleep(1);
}

//FUNCION PARA RESIZEAR LAS IMAGENES QUE SE SUBEN
//$ruta ES DONDE ESTA LA IMAGEN
//$maxx ES LA ANCHURA MAXIMA QUE VA A TENER
//$maxy ES LA ALTURA MAXIMA QUE VA A TENER
function ImgResize($nombre_logo,$ruta,$maxx,$maxy) {
    
    if ($nombre_logo!="") {
        $info=getimagesize($nombre_logo);

        $X=$info[0];
        $Y=$info[1];
        if ($maxx>$X || $maxx==0)
            $maxx=$X;
        if ($maxy>$Y || $maxy==0)
            $maxy=$Y;
        $escX=$X/$maxx;
        $escY=$Y/$maxy;
        $n=0;

        if ($info[2]==1)
            $imOrigen=imagecreatefromgif($nombre_logo);
        elseif ($info[2]==2)
            $imOrigen=imagecreatefromjpeg($nombre_logo);
        elseif ($info[2]==3)
            $imOrigen=imagecreatefrompng($nombre_logo);
        else
            $no=1;
        if ($n==0) {
            if ($escX<$escY) {
                $nX=$X/$escY;
                $nY=$Y/$escY;
            }
            else {
                $nX=$X/$escX;
                $nY=$Y/$escX;
            }
        $imDestino=imagecreatetruecolor($nX,$nY);
        imagecopyresampled($imDestino,$imOrigen,0,0,0,0,$nX,$nY,$X,$Y);
        imagejpeg($imDestino,$ruta,100);
        }
    }
}

if (count($_FILES) == 0 or $errorMsg != "") {
?>
<html>
<head>
    <script type='text/javascript' src='<?php echo site_url(); ?>/wp-includes/js/jquery/jquery.js?ver=3.1.2-alpha'></script>
    <style>
    #pic {
        margin: 0 0 0 5px;
        cursor: pointer;
        opacity: 0.7;
        -moz-transition: opacity 0.4s linear 0s;
        -o-transition: opacity 0.4s linear 0s;
        -webkit-transition: opacity 0.4s linear 0s;
        transition: opacity 0.4s linear 0s;
    }
    #pic:hover {
        opacity: 0.99;
    }
    #picInput {
       visibility: hidden;
    }
    #IMGsubmit {
    
        background-color: transparent; 
        border: 0px none;
        cursor: pointer;
        opacity: 0.6;
        -moz-transition: opacity 0.3s linear 0s;
        -o-transition: opacity 0.3s linear 0s;
        -webkit-transition: opacity 0.3s linear 0s;
        transition: opacity 0.3s linear 0s;
        
    }
    #IMGsubmit:hover {
        opacity: 0.99;
    }
    </style>
    		
<!--[if IE 8]>

<style>
#picInput {
       display:block;
    }
</style>


<![endif]-->
    
    
</head>
<body >
    <form id="uploadform" name="uploadform" method="post" enctype="multipart/form-data"
    action="">

        <div style="margin-top:21px;">
            <img src="<?php echo get_stylesheet_directory_uri() . '/_inc/images/loading.gif'; ?>"
            style="display:none;margin: 35px 0 0 35px;" />
            <?php
            if (isset($_GET['event-detail']) and isset($_GET['id'])) {
                
                $avatar_folder_dir  =  BP_AVATAR_UPLOAD_PATH . '/event-avatars/' . $_GET['id'] . '/';
                if (file_exists($avatar_folder_dir)) {
                    $av_dir = opendir( $avatar_folder_dir );
                
                    while (($full = readdir($av_dir))) {
                        if ($full == '..' or $full == '.' or substr_count($full, '-bpthumb') == '1') {
                            continue;
                        } else {
                            $img = $full;
                        }
                    }
                }
                
                if ($img) {
                    $srcEventAvatar = $bp->root_domain . '/wp-content/uploads/event-avatars/' . $_GET['id'] . '/' . $img;
                } else {
                    $srcEventAvatar = $bp->root_domain . '/wp-content/themes/cvp-irontec/_inc/images/bp_default_avatar.jpg';
                }
            }

            ?>
            <img src="<?php echo (isset($srcEventAvatar)) ? $srcEventAvatar : site_url() . '/wp-content/themes/cvp-irontec/_inc/images/avatr.png'; ?>" id="pic"/>
            <?php
                if($errorMsg != "") {
                ?>
                    <input name="file" type="file" size="2" id="picInput" />
                    <p style="color:red;font-size:12px;"><?php echo $errorMsg; ?></p>
                <?php
                } else {
                ?>
                    <input name="file" type="file" size="2" id="picInput" />
                <?php
                }
            ?>
            <center style="margin-top:10px;">
                <input id="IMGsubmit" type="submit" value="<?php echo __('Cargar Imagen' , 'buddypress'); ?>" />
            </center>
        </div>
    </form>
    <script type="text/javascript">

        (function(jQuery) {
        	var $ = jQuery;

        	$("document").ready(function () {

                $("input[type=submit]").click(function () {

                	if ($('#picInput').val() == "") {
                		$("#picInput").click();
                		return false;
                	} else {
                	    $("body form > div *").not('#picInput').toggle();
                	}
                	
                });


                $('#picInput').change(function(){
                	if ($('#picInput').val() != "") {
                		$("input[type=submit]").click();
                	}
                });
                

                $("#pic").click(function(){
                	$("#picInput").click();
                });
                
            });
        })(jQuery);

    </script>
</body>
</html>
<?php
}