<?php
if (!isset($_SESSION['nazwa'])) {
		header('Location: login.php');
		exit();
	}
	$lu = count($_SESSION['usersn']);
	$nazwa = $_SESSION['nazwa'];
?>
	<div id="wiadg_content">
	<p id="wiadg_tytul2">Wiadomości graficzne</p>
		<div id="wiadg_left">
			<div style="width: 170px; padding: 5px 0 0 0; text-align: center; color: #ffe000">
				Odbierz wiadomości<br />
				<input type="submit" id="odbierz" value="Odbierz" name="odbierz_wgraf" class="but_wgraf"><br />	
			</div>	
		<div id="wiadg_kontakt">
		
				Wybierz adresata
				<form id="kontakt" action="">
				<div style="width: 100; margin: 5px 10px; text-align: left">
				<input type="checkbox" id="cw" name="cw"/>Wszystkie
				</div>
				<div style="width: 140px; margin: 0 0 0 5px;">
					<?php
						$strona = $_SESSION['strona'].'/img/avatar/male/';
						for ($i=0; $i<$lu; $i++) {
							if (file_exists ( 'img/avatar/male/'.$_SESSION["usersn"][$i].'.jpg' )) {
								echo '<div class="dcc" style="background: url('.$strona.$_SESSION['usersn'][$i].'.jpg) no-repeat;">';
							} else {
								echo '<div class="dcc" style="background: url('.$strona.'fwa.jpg) no-repeat;">';
							}
							echo '<input type="checkbox" id="c1" name="cc" class="cc'.$i.'"/>';
							echo '<label for="c1"><span></span></label>';
							echo '</div>';
						}
					?>				
				</div>
				</form>
			</div>
		</div>
	
		<div id="wiadg_right">
			Tytuł wiadomości
			<input type="text" name="tytul" id="wiadg_tytul" maxlength="50" class="kontakty" placeholder="Do:" readonly="true"/><br />
			<input type="text" name="tytul" id="wiadg_tytul" maxlength="50" class="tytul" placeholder="Tytuł wiadomości"/><br />
			Narysuj wiadomość
			<canvas id="paint" width="640" height="480" style="border:5px ridge #420; border-bottom: 10px ridge #420; background:#030; "></canvas>
			<input type="text" id="xy" name="tekst" readonly style="width: 55px;"/>
			<select  id="wg_predkosc" name="wg_predkosc">
			<option value="op1">V - 1</option>
			<option value="op2">V - 2</option>
			<option value="op3">V - 3</option>
			<option value="op4">V - 4</option>
			<option value="op5">V - 5</option>
			<option value="op5">V - 6</option>
		</select>
			<input type="button" class="but_wgraf" id="wyczysc" value="Wyczyść"/>
			<input type="button" class="but_wgraf" id="rysuj" value="Rysuj"/>
			<input type="button" class="but_wgraf" id="stop" value="Stop"/>
			<div style="float: right; margin-right: 20px;">
			<input type="button" class="but_wgraf" id="wyslij" value="Wyślij"/>
			</div>
			<div id="wiadg_odbieranie">
<?php
			require_once('wiras_php/wa_baza/wa_polacz.php');
			$zap = "SELECT id_wgraf, id_awgraf, tytul, od, do, data_wgraf, odebrana FROM wgraf_adresaci, wgraf 
						WHERE id_wgraf=id_awgraf AND do='$nazwa'
						ORDER BY data_wgraf ASC";
				$wynik_pobierz = mysqli_query($db, $zap);
				$wynik = array();
				while ($wiersz = mysqli_fetch_row($wynik_pobierz)) 
				{
					$wynik[] = $wiersz;
				}
				echo '<p id="nag_wgraf">Odebrane</p>';
				echo '<table id="tab_wgraf">';
					echo '<tr><th>Od</th><th>Tytuł</th><th>Data</th></tr>';
				for ($i=0; $i<count($wynik); $i++) {
						if ($wynik[$i][6]==0) {
							$z1 = '<b>';
							$z2 = '</b>';
							$col = '#060';
						} else {
							$z1 = '';
							$z2 = '';
							$col = '#006';
						}
					echo '<tr onmouseover="this.style.cursor=\'pointer\'" id="tr'.$wynik[$i][0].'" class="trlink" style="color: '.$col.'">';
						echo '<td>'.$z1.$wynik[$i][3].$z2.'</td>';
						echo '<td>'.$z1.$wynik[$i][2].$z2.'</td>';
						echo '<td>'.$z1.$wynik[$i][5].$z2.'</td>';
					echo '</tr>';
				}
				echo '</table>';
			//----------------------------------------------------
			//Wyslane
			echo '<br /><p id="nag_wgraf">Wysłane</p>';
			$zap = "SELECT id_wgraf, id_awgraf, tytul, od, do, data_wgraf, odebrana FROM wgraf_adresaci, wgraf 
						WHERE id_wgraf=id_awgraf AND od='$nazwa'
						ORDER BY data_wgraf ASC";
				$wynik_pobierz = mysqli_query($db, $zap);
				$wynik = array();
				while ($wiersz = mysqli_fetch_row($wynik_pobierz)) 
				{
					$wynik[] = $wiersz;
				}
				echo '<table id="tab_wgraf">';
					echo '<tr><th>Od</th><th>Do</th><th>Tytuł</th><th>Data</th></tr>';
				for ($i=0; $i<count($wynik); $i++) {
					echo '<tr onmouseover="this.style.cursor=\'pointer\'" id="tr'.$wynik[$i][0].'" class="trlink">';
						echo '<td>'.$wynik[$i][3].'</td>';
						echo '<td>'.$wynik[$i][4].'</td>';
						echo '<td>'.$wynik[$i][2].'</td>';
						echo '<td>'.$wynik[$i][5].'</td>';
					echo '</tr>';
				}
				echo '</table>';
?>
				<input type="button" class="but_wgraf" id="zamknij_wiadomosc" value="Zamknij"/>
			</div>
		</div>		
	</div>

	

<script type="text/javascript">
   $(document).ready(function(){
		var cName = "paint";
		var iv;
		var vrys = 1;
		var rysunek = true;
		var tx = [];
		var ty = [];
		var lp = 0;
		var kontakty = [];
		var limit = 5000;
		var canvas = document.getElementById("paint");
		var ctx = canvas.getContext("2d");
		ctx.strokeStyle = "#eee";
		ctx.lineWith = 1;
<?php
		echo 'var users = [];';
		for ($i=0; $i<$lu; $i++) {
			echo "users[".$i."]='".$_SESSION['usersn'][$i]."';";
		}
		echo "var uid = ".$_SESSION['id'].";";
		echo "var nazwa = '".$_SESSION['nazwa']."';";
?>

	var drawing = false;
	var mousePos = { x:0, y:0 };
	var lastPos = mousePos;
	canvas.addEventListener("mousedown", function (e) {
			drawing = true;
	  lastPos = getMousePos(canvas, e);
	}, false);
	
	canvas.addEventListener("mouseup", function (e) {
	  drawing = false;
	}, false);
	
	canvas.addEventListener("mousemove", function (e) {
	  mousePos = getMousePos(canvas, e);
	}, false);

	function getMousePos(canvasDom, mouseEvent) {
	  var rect = canvasDom.getBoundingClientRect();
	  return {
		x: mouseEvent.clientX - rect.left,
		y: mouseEvent.clientY - rect.top
	  };
	}
	
	window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || 
           window.webkitRequestAnimationFrame ||
           window.mozRequestAnimationFrame ||
           window.oRequestAnimationFrame ||
           window.msRequestAnimaitonFrame ||
           function (callback) {
        window.setTimeout(callback, 1000/60);
           };
	})();
	

	function renderCanvas() {
		if (rysunek) {
			if (lp<limit) {
			  if (drawing) {
				ctx.moveTo(lastPos.x, lastPos.y);
				ctx.lineTo(mousePos.x, mousePos.y);		
				ctx.stroke();
				tx[lp] = lastPos.x;
				ty[lp] = lastPos.y;
				lp++;
				tx[lp] = mousePos.x;
				ty[lp] = mousePos.y;
				lp++;
				$('#xy').val(' lp: ' +(limit-lp));
				lastPos = mousePos;
			  }
			}
		}
	}

	
	(function drawLoop () {
	  requestAnimFrame(drawLoop);
	  renderCanvas();
	})();
	
	
	
	canvas.addEventListener("touchstart", function (e) {
			mousePos = getTouchPos(canvas, e);
	  var touch = e.touches[0];
	  var mouseEvent = new MouseEvent("mousedown", {
		clientX: touch.clientX,
		clientY: touch.clientY
	  });
	  canvas.dispatchEvent(mouseEvent);
	}, false);
	
	canvas.addEventListener("touchend", function (e) {
	  var mouseEvent = new MouseEvent("mouseup", {});
	  canvas.dispatchEvent(mouseEvent);
	}, false);
	
	canvas.addEventListener("touchmove", function (e) {
	  var touch = e.touches[0];
	  var mouseEvent = new MouseEvent("mousemove", {
		clientX: touch.clientX,
		clientY: touch.clientY
	  });
	  canvas.dispatchEvent(mouseEvent);
	}, false);

	
	function getTouchPos(canvasDom, touchEvent) {
	  var rect = canvasDom.getBoundingClientRect();
	  return {
		x: touchEvent.touches[0].clientX - rect.left,
		y: touchEvent.touches[0].clientY - rect.top
	  };
	}
	
	//--------------------------------------------------

		$( "#wyczysc" ).on( "click", function() {
			$('#stop').val('Stop');
			clearTimeout(iv);
			gumka();
			zeruj_tablice();
		});
		
		
		function gumka() {
			var c=document.getElementById("paint");
			ctx.beginPath();
			ctx.save();
			ctx.setTransform(1, 0, 0, 1, 0, 0);
			ctx.clearRect(0, 0, c.width, c.height);
			ctx.restore();
		}
		
		function zeruj_tablice() {
			lp=0;
			tx.splice(0, tx.length);
			ty.splice(0, ty.length);
		}

		
		$( "#wyslij" ).on( "click", function() {
		var sx = '';
		var sy = '';
		var i = 0;
		var dt = tx.length;
		for (i=0; i<dt; i++) {
			sx+=tx[i]+',';
			sy+=ty[i]+',';
		}
		
		var w3 = $('.tytul').val();
		var w4 = kontakty;
			if (kontakty.length>0) {
				if (lp>5) {
					$.ajax({
						type:"POST", 
						url:"wiras_php/wa_baza/wa_zapisz_wgraf.php", 
						data: {k1:sx, k2:sy, k3:w3, k4:w4, k5:uid, k6:nazwa},						 
							success:function(st) {
								gumka();
							},
							error: function(blad) {
							console.log("Błąd-Problem z wysłaniem wiadomości graficznej"); 
						}
					});
				}	else {
					alert("Narysuj wiadomość...");
				}
			} else {
				alert("Dodaj adresatów wiadomości...");
			}
		});
		
		
		//------------------------------------------------------
		/*POBRANIE DANYCH Z BAZY*/
    $( ".trlink" ).on( "click", function() { 
		$('#wiadg_odbieranie').fadeToggle('slow');
		var col = $( this ).css( "color" );
		var cr=0;
		if ( col == 'rgb(0, 0, 102)') {
			cr=1;
		}
		var tid = $(this).attr('id');
		var id = tid.slice(2, tid.length);
        $.ajax({
            type:"POST",
            url:"wiras_php/wa_baza/wa_pobierz_wgraf.php", 
            dataType:'json',
			async: false,
			data: {k1:id, k2:cr},
                success: function(json) {
					gumka();
					zeruj_tablice();
                    for (var klucz in json)
                        {
                            var wiersz = json[klucz];   
                        } 
						 tx = wiersz[0].split(',');
                             ty = wiersz[1].split(',');
							 $("#wyslij").attr("disabled", false);
							 clearTimeout(iv);
							 rysuj();
                     
                    $("#pobierz").attr("disabled", true);
                    setTimeout(function(){
                        $("#pobierz").attr("disabled", false); 
                    }, 5000); 
                 
                },
		});
	});
	
	
		function rysuj() {
			rysunek = false;
			ctx.moveTo(tx[lp], ty[lp]);
			ctx.lineTo(tx[lp+1], ty[lp+1]);
			ctx.strokeStyle = '#eee';
			ctx.stroke();
			if (lp<tx.length || lp<limit) {
				lp+=2;
			} else {
				clearTimeout(iv);
				rysunek=true;
				$('#xy').val(' lp: ' +(limit-lp));
			}
			iv = setTimeout(rysuj, vrys);
		}
		
		$('#stop').click(function() {
			if ($('#stop').val()=='Start') {
				clearTimeout(iv);
				rysuj();
				$('#stop').val('Stop');
			} else {
				rysunek=true;
				clearTimeout(iv);
				$('#stop').val('Start');
			}
		})
		
		$('#rysuj').click(function() {
			$('#stop').val('Stop');
			clearTimeout(iv);
			gumka();
			lp=0;
			$("#wyslij").attr("disabled", false);
			rysuj();
		})
	
	
	$("#odbierz").on("click", function() {
		$('#wiadg_odbieranie').fadeToggle('slow');
	});
	
	$("#zamknij_wiadomosc").on("click", function() {
		$('#wiadg_odbieranie').fadeToggle('slow');
	});
	

	$('#cw').change(function() { 
		var t='';
		 var checkbox = this.form.cc;
		 var x=0;
		if ($(this).is(':checked')) {
			for (x=0; x<checkbox.length; x++) {
				checkbox[x].checked=true;
			}
			for (x=0; x<users.length; x++) {
				kontakty[x] = users[x];
				t+=users[x]+'; ';
			}
			$('.kontakty').val(t);
		} else {
			for (var x=0; x<checkbox.length; x++) {
				checkbox[x].checked=false;
			}
			kontakty.splice(0, kontakty.length);
			$('.kontakty').val('');
		}

	});
	
	$('input[type="checkbox"]').change(function() {
		var t = '';
		var cc = this.form.cc;
		kontakty.splice(0, kontakty.length);
		for (var i=0; i<cc.length; i++) {
			if (cc[i].checked) {
				kontakty.push(users[i]);
				t+=users[i]+'; ';
			}
		}
		$('.kontakty').val(t);
	});
	
	
	$('#wg_predkosc').change(function() { 
	var opcja = $('#wg_predkosc').val();
		switch (opcja) {
					case 'op1':
						vrys=1;
						break;
					case 'op2':
						vrys=5;
						break;
					case 'op3':
						vrys=10;
						break;
					case 'op4':
						vrys=20;
						break;
					case 'op5':
						vrys=35;
						break;
					case 'op6':
						vrys=50;
						break;
					}
	});

});
</script>
