<?php
error_reporting(E_ALL);

require('includes/user_data.php');
require_once('includes/functions.php');
if(isset($_POST['Edit']))

{

	if(empty($_POST['name']))

		$validation[] = 'You did not enter your name.';

	elseif(!ereg("^[A-Za-z][a-zA-Z[:space:]\.\-]*[A-Za-z\.]$",$_POST['name'], $matches))

		$validation[] = 'Your name contains illegal charactors.';

	else {
		$first_name = ucfirst(trim(substr($_POST['name'],0,strpos($_POST['name'],' '))));
		$last_name = ucfirst(trim(substr($_POST['name'],strpos($_POST['name'],' '))));
	}

	if(empty($_POST['email']))

		$email = NULL;

	elseif(!preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/i",$_POST['email']))

		$validation[] = 'Your email is invalid.';

	else

		$email = $_POST['email'];

	if(empty($_POST['zip']))

		$validation[] = 'You did not enter a zip code.';

	else

		$zip = zip_string_to_integer($_POST['zip']);

	if(empty($_POST['phone']))

		$validation[] = 'You did not enter a phone number.';

	else

	{

		$phone = phone_string_to_integer($_POST['phone']);

	}


	$city = $_POST['city'];
	$state = strtoupper(substr($_POST['state'],0,2));
	$email = $_POST['email'];





	if(!isset($validation))

	{

		$query = sprintf("UPDATE `Users` SET `first_name`='%s',`last_name` = '%s',`email` = '%s',`zip` = %s,`phone` = %s,`city` = '%s',`state` = '%s' WHERE `ID`=%s",
			mysql_real_escape_string($first_name),
			mysql_real_escape_string($last_name),
			mysql_real_escape_string($email),
			mysql_real_escape_string($zip),
			mysql_real_escape_string($phone),
			mysql_real_escape_string($city),
			mysql_real_escape_string($state),
			mysql_real_escape_string($user_data['ID']));
						
		print $query;
						
		if(!mysql_query($query))

			$errors[] = 'Your profile was not updated, probably because you entered some aspect of your information incorrectly. Please review and try again.';
		else
			$success = 'Your profile has been updated.';


		require('includes/user_data.php'); //Overwrite data with new data

	}

}

$query = "SELECT photo_URL FROM `Users` WHERE `ID`=".$user_data['ID'];
$extension = mysql_result(mysql_query($query),0);


$upload_path = 'images/profiles/'; 				// The directory for the images to be saved in

$large_image_name = 'resize_'.(int)$_COOKIE['ID'];     // New name of the large image (append the timestamp to the filename)

$thumb_image_name = 'thumbnail_'.(int)$_COOKIE['ID'];     // New name of the thumbnail image (append the timestamp to the filename)

$max_file = '4'; 							// Maximum file size in MB

$max_width = '500';							// Max width allowed for the large image

$thumb_width = '64';						// Width of thumbnail image

$thumb_height = '64';						// Height of thumbnail image
$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");

$allowed_image_ext = array_unique($allowed_image_types); // do not change this

$image_ext = '';	// initialise variable, do not change this.

foreach ($allowed_image_ext as $mime_type => $ext)

    $image_ext.= strtoupper($ext)." ";



require_once('includes/image_resize.php');



//Image Locations

$large_image_location = $upload_path.$large_image_name;
$thumb_image_location = $upload_path.$thumb_image_name;

if(isset($extension)) {
	$large_image_location .= '.'.$extension;
	$thumb_image_location .= '.'.$extension;
}
if (isset($_POST['upload'])) { 

	$userfile_name = $_FILES['image']['name'];

	$userfile_tmp = $_FILES['image']['tmp_name'];

	$userfile_size = $_FILES['image']['size'];

	$userfile_type = $_FILES['image']['type'];

	$filename = basename($_FILES['image']['name']);

	$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

	

	if((!empty($_FILES['image'])) && ($_FILES['image']['error'] == 0)) {

		foreach ($allowed_image_types as $mime_type => $ext)

			if($file_ext==$ext && $userfile_type==$mime_type) {
				$validation = null;

				break;
			}
			else

				$validation = 'Only <strong>'.$image_ext.'</strong> images accepted for upload<br />';

		if ($userfile_size > ($max_file*1048576))

			$validation[] = 'Images must be under '.$max_file.'MB in size';


		

	}
	else

		$validation[] = 'Select an image for upload';


	if(!isset($validation)) {

		if (isset($_FILES['image']['name'])){
			$large_image_location = $large_image_location.'.'.$file_ext;
			
			$query = sprintf("UPDATE `Users` SET `photo_URL`='%s' WHERE `ID`='%s'",
			mysql_real_escape_string($file_ext),
			mysql_real_escape_string($_COOKIE['ID']));
			mysql_query($query);

			
			move_uploaded_file($userfile_tmp, $large_image_location);

			

			$width = getWidth($large_image_location);

			$height = getHeight($large_image_location);

			//Scale the image if it is greater than the width set above

			if ($width > $max_width){

				$scale = $max_width/$width;

				$uploaded = resizeImage($large_image_location,$width,$height,$scale);

			}else{

				$scale = 1;

				$uploaded = resizeImage($large_image_location,$width,$height,$scale);

			}

		}

	}

}

elseif (isset($_POST['upload_thumbnail'])) {
	$x1 = $_POST["x1"];

	$y1 = $_POST["y1"];

	$x2 = $_POST["x2"];

	$y2 = $_POST["y2"];

	$w = $_POST["w"];

	$h = $_POST["h"];

	$scale = $thumb_width/$w;
	$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);

	if (file_exists($large_image_location))

		unlink($large_image_location);
}

elseif(isset($_GET['delete'])) {
	$query = sprintf("UPDATE `Users` SET `photo_URL`=NULL WHERE `ID`='%s'",
			mysql_real_escape_string($_COOKIE['ID']));
			mysql_query($query);
	if (file_exists($thumb_image_location))

		unlink($thumb_image_location);
}
//Check to see if any images with the same name already exist

if(file_exists($large_image_location))

   	$large_photo_exists = '<img src="'.$large_image_location.'" alt="Large Image"/>';

elseif(file_exists($thumb_image_location))

	$thumb_photo_exists = '<img src="'.$thumb_image_location.'" alt="Thumbnail Image"/>';


include_once('includes/header.php');

$user = $user_data;
?>
<?php

if(file_exists($large_image_location) > 0){

	$current_large_image_width = getWidth($large_image_location);

	$current_large_image_height = getHeight($large_image_location);?>
<script type="text/javascript" src="js/jquery/jquery.imgareaselect-0.6.1.min.js"></script>

<script type="text/javascript">

function preview(img, selection) { 

	var scaleX = <?php echo $thumb_width;?> / selection.width; 

	var scaleY = <?php echo $thumb_height;?> / selection.height; 

	

	$('#thumbnail + div > img').css({ 

		width: Math.round(scaleX * <?php echo $current_large_image_width;?>) + 'px', 

		height: Math.round(scaleY * <?php echo $current_large_image_height;?>) + 'px',

		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 

		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 

	});

	$('#x1').val(selection.x1);

	$('#y1').val(selection.y1);

	$('#x2').val(selection.x2);

	$('#y2').val(selection.y2);

	$('#w').val(selection.width);

	$('#h').val(selection.height);

} 



$(document).ready(function () { 

	$('#save_thumb').click(function() {

		var x1 = $('#x1').val();

		var y1 = $('#y1').val();

		var x2 = $('#x2').val();

		var y2 = $('#y2').val();

		var w = $('#w').val();

		var h = $('#h').val();

		if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){

			alert("You must make a selection first");

			return false;

		}else{

			return true;

		}

	});

}); 



$(window).load(function () { 

	$('#thumbnail').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview }); 

});



</script>

<?php }?>

<form method="post" id="account">

	<h3>Your Profile</h3>


		<label>Full Name:</label>
		<input type="text" name="name"<?php print 'value="'.$user['first_name'].' '.$user['last_name'].'" ';?>/>

		<label>Email Address:</label>
		<input type="text" name="email"<?php print 'value="'.$user['email'].'" ';?>/><br />

		<label>Zip (5 or 9 Digits):</label>
		<input type="text" name="zip" size="11" value="<?=zip_integer_to_string($user['zip']);?>"/>

		<label>Phone Number:</label>
		<input type="text" name="phone" maxlength="14" size="14" value="<?=phone_integer_to_string($user['phone']);?>"/>
		
		<label>City:</label>
		<input type="text" name="city" size="50"<?php print 'value="'.$user['city'].'" ';?>/>

		<label>State:</label>
		<select name="state" id="state">
			<option value='AL' class='AL'>Alabama</option>
			<option value='AK' class='AK'>Alaska</option>
			<option value='AZ' class='AZ'>Arizona</option>
			<option value='AR' class='AR'>Arkansas</option>
			<option value='CA' class='CA'>California</option>
			<option value='CO' class='CO'>Colorado</option>
			<option value='CT' class='CT'>Connecticut</option>
			<option value='DC' class='DC'>District of Columbia</option>
			<option value='DE' class='DE'>Delaware</option>
			<option value='FL' class='FL'>Florida</option>
			<option value='GA' class='GA'>Georgia</option>
			<option value='HI' class='HI'>Hawaii</option>
			<option value='ID' class='ID'>Idaho</option>
			<option value='IL' class='IL'>Illinois</option>
			<option value='IN' class='IN'>Indiana</option>
			<option value='IA' class='IA'>Iowa</option>
			<option value='KS' class='KS'>Kansas</option>
			<option value='KY' class='KY'>Kentucky</option>
			<option value='LA' class='LA'>Louisiana</option>
			<option value='ME' class='ME'>Maine</option>
			<option value='MD' class='MD'>Maryland</option>
			<option value='MA' class='MA'>Massachusetts</option>
			<option value='MI' class='MI'>Michigan</option>
			<option value='MN' class='MN'>Minnesota</option>
			<option value='MS' class='MS'>Mississippi</option>
			<option value='MO' class='MO'>Missouri</option>
			<option value='MT' class='MT'>Montana</option>
			<option value='NE' class='NE'>Nebraska</option>
			<option value='NV' class='NV'>Nevada</option>
			<option value='NH' class='NH'>New Hampshire</option>
			<option value='NJ' class='NJ'>New Jersey</option>
			<option value='NM' class='NM'>New Mexico</option>
			<option value='NY' class='NY'>New York</option>
			<option value='NC' class='NC'>North Carolina</option>
			<option value='ND' class='ND'>North Dakota</option>
			<option value='OH' class='OH'>Ohio</option>
			<option value='OK' class='OK'>Oklahoma</option>
			<option value='OR' class='OR'>Oregon</option>
			<option value='PA' class='PA'>Pennsylvania</option>
			<option value='RI' class='RI'>Rhode Island</option>
			<option value='SC' class='SC'>South Carolina</option>
			<option value='SD' class='SD'>South Dakota</option>
			<option value='TN' class='TN'>Tennessee</option>
			<option value='TX' class='TX'>Texas</option>
			<option value='UT' class='UT'>Utah</option>
			<option value='VT' class='VT'>Vermont</option>
			<option value='VA' class='VA'>Virginia</option>
			<option value='WA' class='WA'>Washington</option>
			<option value='WV' class='WV'>West Virginia</option>
			<option value='DC' class='DC'>Washington D.C.</option>
			<option value='WI' class='WI'>Wisconsin</option>
			<option value='WY' class='WY'>Wyoming</option>
		</select>	
		<input type="submit" name="Edit" class="submit" value="Save Changes" />
	</form>

	<script type="text/javascript">
		$("#state option.<?=$user_data['user_state'];?>").attr({selected:'selected'});
	</script>


<?php if(isset($thumb_photo_exists)):

	echo $thumb_photo_exists;

	echo '<p><a href="?delete">Delete Image and Upload Another</a></p>';

else:

	if(isset($large_photo_exists)){?>

	<h3>Create Thumbnail by Dragging a Box Around an Area</h3>

	<img src="<?php echo $large_image_location;?>" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" />

	<div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:<?php echo $thumb_width;?>px; height:<?php echo $thumb_height;?>px;">

		<img src="<?php echo $large_image_location;?>" style="position: relative;" alt="Thumbnail Preview" />

	</div>

	<br style="clear:both;"/>

	<form name="thumbnail" action="<?php echo $_SERVER["PHP_SELF"];?>" 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 type="submit" name="upload_thumbnail" class="submit" value="Save Thumbnail" id="save_thumb" />

	</form>

	<hr />

	<?php 	} else { ?>
	<h3>Upload Photo for Profile Image</h3>

	<form name="photo" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">

	Photo <input type="file" name="image" size="30" /> <input type="submit" class="submit" name="upload" value="Upload" />

	</form>

<?php } 
endif;
include_once("includes/footer.php");

?>
