// 0.6c
if (@txpinterface == 'admin') {	
	add_privs('lam_image_uploader_prefs', '1,2');
  	add_privs('handle_picture_upload_form','1,2,3,4,5');
	add_privs('picture_upload_form','1,2,3,4,5');
	register_callback("handle_picture_upload_form", "picture_upload_form");
  	register_callback("setup_picture_upload", "article");
	register_tab('extensions', 'lam_image_uploader_prefs', 'Image Uploader');
	register_callback('lam_image_uploader_prefs', 'lam_image_uploader_prefs');
}

function setup_picture_upload($event, $step) {
	global $prefs;

	echo '<script type="text/javascript">
	var parentElement = document.getElementById("';
	if($prefs['lam_image_uploader_move_sidebar'] == '1') {
		echo 'article-col-1");';
	} else { echo 'article-main");
		var p = document.createElement("p");
		var label = document.createElement("label");
		label.innerHTML = "'.gTxt('upload_image').'";
		label.setAttribute("id","pictures-upload");
		label.setAttribute("name","pictures-upload");
		p.appendChild(label);
		parentElement.appendChild(p);';
	}
	echo 'var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "lam-pictures");
	iframe.setAttribute("name","lam-pictures");
	iframe.setAttribute("border","0");
	iframe.setAttribute("frameBorder","0");
	iframe.setAttribute("src", "index.php?event=picture_upload_form");';
	echo '
	iframe.style.width = "100%";
	iframe.setAttribute("height","235px");
	iframe.style.border = "none";';
	
	if($prefs['lam_image_uploader_move_sidebar'] == '1') {
		echo 'parentElement.appendChild(iframe);';
	} else { echo 'p.appendChild(iframe);';}
	echo '
		function adjustIFrameSize(iframeWindow) {
		if (iframeWindow.document.height) {
			var iframeElement = document.getElementById ("lam-pictures");
			iframeElement.style.height = iframeWindow.document.height + 25 + "px";
			iframeElement.style.width = iframeWindow.document.width + "px";
		} else if (document.all) {
			var iframeElement = document.all["lam-pictures"];
			if (iframeWindow.document.compatMode &&
			iframeWindow.document.compatMode != "BackCompat") {
			iframeElement.style.height =
			iframeWindow.document.documentElement.scrollHeight + 5 + "px";
			iframeElement.style.width =
			iframeWindow.document.documentElement.scrollWidth + 5 + "px";
			} else {
				iframeElement.style.height =
				iframeWindow.document.body.scrollHeight + 5 + "px";
				iframeElement.style.width = iframeWindow.document.body.scrollWidth
				+ 5 + "px";
			}
		}
	}
	</script>';
}
/// Inline Picture Upload
// -------------------------------------------------------------
function handle_picture_upload_form($attr) {
	ob_start();
	ob_end_clean();
	global $prefs;
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<title>Picture Upload</title>
		<link rel="stylesheet" href="textpattern.css" type="text/css" media="screen" title="no title" charset="utf-8">
		<script type="text/javascript" src="jquery.js"></script>
		<style type="text/css" media="screen">
		body {
			background:none !important;
			background-color:inherit;
		}
      		form.upload-form {
      			text-align:left;
      			overflow:hidden;
      			width:100%;
      		}
      		input.file {
      			margin-top:0;';
      		if($prefs['lam_image_uploader_move_sidebar'] == '1') {
      			echo 'width:140px;';
      		}
      		echo '
      		}
      		input.alt {';
      		if($prefs['lam_image_uploader_move_sidebar'] == '1') {
      			echo 'width:140px;';
      		} else {
      			echo 'width:400px;';
      			}
      		echo '}
      		#image-category {';
      		if($prefs['lam_image_uploader_move_sidebar'] == '1') {
			echo 'max-width:160px;';
		} else {
			}
		echo '}
      		label {
      			clear:both;
        		display:block;
                        margin-top:10px;
      		}
      		input.smallerbox {
      			display:block;
      			clear:both;
      			margin-top:10px;
      		}
      		textarea {';
      		if($prefs['lam_image_uploader_move_sidebar'] == '1') {
      				echo 'width:140px;';
      			} else {
      				echo 'width:400px;';
      			}
      		echo '
      			height:80px;
      		}
      		.error {
      			color:#fff;
      			padding:5px 0;
      			font-size:11px;
      			background:#900;
      			width:99%;
      			clear:both;
      		}
      		input.result {
      			border: 2px solid #11aa1b;
      			margin: 20px 0;
      			width: 146px;
      		}
      		#lam-attach, #lam-append {
      			margin:20px 0;
      		}
		</style>
		
		<script type="text/javascript">
		function insertid(id, type) {
			var MyElement = parent.document.getElementById("article-image");
			if (type == "attach") {
				MyElement.value = id;
			}
			if (type == "append") {
				if(MyElement.value == "") {
					MyElement.value = id;
				} else {
					MyElement.value += ","+id;
				}
			}
			return true;
		}
		$(document).ready(function() {
			$("#lam_show_hide").click(function () {
				$("#lam_image_uploader").toggle();
   			 });
 		 });
		</script>
	</head><body style="border:0;" onload="parent.adjustIFrameSize(window);">';
	if($prefs['lam_image_uploader_move_sidebar'] == '1') {
		echo '<h3 class="plain" style="text-align:left"><a href="javascript:void(0);" id="lam_show_hide" onload>'.gTxt('upload_image').'</a></h3><div id="lam_image_uploader">';
	}
	global $file_max_upload_size;
	if (!$file_max_upload_size || intval($file_max_upload_size)==0) $file_max_upload_size = 2*(1024*1024);
	$max_file_size = (intval($file_max_upload_size) == 0) ? '': intval($file_max_upload_size);
	
	if(isset($_FILES['thefile'])) {
		global $txpcfg, $extensions, $txp_user, $img_dir, $ext;
		extract($txpcfg);
		$meta = doSlash(gpsa(array('caption', 'alt', 'category')));
		$img_result = image_data2($_FILES['thefile'], $meta);
		
		if(is_array($img_result) && isset($img_result[1])) {
			if($prefs['lam_image_uploader_auto_append'] =='1') {
				echo '<script type="text/javascript">';
				echo "insertid($img_result[1], 'attach');</script>";
			}
			if($prefs['lam_image_uploader_show_thumbnail'] == '1') {
				echo '<img src="'.hu.$img_dir.'/'.$img_result[1].'t'.$ext;
				if($prefs['lam_image_uploader_move_sidebar'] == '1') {
				echo '" width="150" />';
				} else {
					echo '" style="max-width:400px" />';
				}
			}
			if($prefs['lam_image_uploader_show_image_id'] == '1') {
				echo "<div><input type=\"text\" onfocus=\"this.select()\" name=\"show_image_id\" class=\"edit result\" value='<txp:image id=\"$img_result[1]\" />' /></div>";
			}		
			if($prefs['lam_image_uploader_show_attach_image'] == '1') {
				echo "<div id=\"lam-attach\"><a href=\"javascript:void(0);\" onclick=\"insertid('$img_result[1]','attach');\">".lam_image_uploader_gTxt('attach_image')."</a></div>";
			}
			if($prefs['lam_image_uploader_show_append_image'] == '1') {
				echo "<div id=\"lam-append\"><a href=\"javascript:void(0);\" onclick=\"insertid('$img_result[1]','append');\">".lam_image_uploader_gTxt('append_image')."</a></div>";
			}
		} else {
			echo '<div class="error"><p>'.$img_result.'</p></div>';
		}
	}
	echo upload_form_for_page('picture','file_insert','picture_upload_form', '',$max_file_size);
echo'</div></body></html>';
	exit;
}
// -------------------------------------------------------------
function image_data2($file , $meta = '', $id = '', $uploaded = true) {
	global $txpcfg, $extensions, $txp_user, $prefs, $file_max_upload_size;
	extract($txpcfg);

	$name = $file['name'];
	$error = $file['error'];
	$file = $file['tmp_name'];
	if ($uploaded) {
		$file = get_uploaded_file($file);
		if ($file_max_upload_size < filesize($file)){
			unlink($file);
			return upload_get_errormsg(UPLOAD_ERR_FORM_SIZE);
		}
	}
	list($w, $h, $extension) = getimagesize($file);
	global $extensions;
	$extensions = array(0,'.gif','.jpg','.png','.swf');
	define("IMPATH",$prefs['path_to_site'].'/'.$prefs['img_dir'].'/');
	include txpath.'/lib/class.thumb.php';
	
	if (($file !== false) && @$extensions[$extension]) {
		global $ext;
		$ext = $extensions[$extension];
		$name = doSlash(substr($name, 0, strrpos($name, '.')).$ext);
		if ($meta == false){
			$meta = array('category' => '','caption' => '','alt' => '');
		}

		extract($meta);
		$q ="name = '$name', ext = '$ext', w = $w, h = $h, alt = '$alt', caption = '$caption', category = '$category', date = now(), author = '$txp_user'";

		if (empty($id)) {
			$rs = safe_insert('txp_image',$q);
			$id = $GLOBALS['ID'] = mysql_insert_id();
		} else {
			$id = assert_int($id);
			$rs = safe_update('txp_image',$q,"id = $id");
		}

		if(!$rs) {
			return gTxt('image_save_error');
		} else {
			$newpath = IMPATH.$id.$ext;

			if (shift_uploaded_file($file, $newpath) == false) {
				$id = assert_int($id);
				safe_delete('txp_image',"id = $id");
				safe_alter('txp_image',"auto_increment = $id");

				if (isset($GLOBALS['ID'])) {
					unset( $GLOBALS['ID']);
				}
				return $newpath.sp.gTxt('upload_dir_perms');
			} else {
				@chmod($newpath, 0644);

				// Auto-generate a thumbnail using the last settings
				if (isset($prefs['thumb_w'], $prefs['thumb_h'], $prefs['thumb_crop'])) {
					$t = new txp_thumb( $id );
					$t->crop = ($prefs['thumb_crop'] == '1');
					$t->hint = '0';
					if (is_numeric($prefs['thumb_w'])) $t->width = $prefs['thumb_w'];
					if (is_numeric($prefs['thumb_h'])) $t->height = $prefs['thumb_h'];
					$t->write();
				}
				$message = gTxt('image_uploaded', array('{name}' => $name));
				return array($message, $id);
			}
		}
	} else {
		if ($file === false) {
			return upload_get_errormsg($error);
		} else {
			return gTxt('only_graphic_files_allowed');
		}
	}
}
// -------------------------------------------------------------
function upload_form_for_page($pophelp, $step, $event, $id = '', $max_file_size = '1000000', $label_id = '', $class = 'upload-form') {
	global $sort, $dir, $page, $search_method, $crit, $prefs;
	$class = ($class) ? ' class="'.$class.'"' : '';
	$categories = getTree("root","image");
	$label_id = ($label_id) ? $label_id : $event.'-upload';
	$lam_image_file = ($prefs['lam_image_uploader_move_sidebar'] == '1') ? fInput('file','thefile','','file edit','','','11') : fInput('file','thefile','','file edit','','','15');
	$lam_image_alt = ($prefs['lam_image_uploader_move_sidebar'] == '1') ? fInput('text', 'alt', '', 'alt edit','','','22') : fInput('text', 'alt', '', 'alt edit');
	$lam_image_caption = ($prefs['lam_image_uploader_image_caption'] == '1') ? '<label for="caption">'.gTxt('caption').'</label>'.
	'<textarea id="caption" name="caption" cols="18" rows="5"></textarea>' : '';
	$lam_image_categories = ($prefs['lam_image_uploader_image_categories'] == '1') ? '<label for="category">'.gTxt('image_category').'</label>'.treeSelectInput('category', $categories, '', 'image-category') : '';
	
	return n.n.'<form'.$class.' method="post" enctype="multipart/form-data" action="index.php">'.
	n.'<div>'.
	(!empty($max_file_size)? n.hInput('MAX_FILE_SIZE', $max_file_size): '').
	n.eInput($event).n.sInput($step).n.hInput('id', $id).n.hInput('sort', $sort).n.hInput('dir', $dir).n.hInput('page', $page).
	n.hInput('crit', $crit).
	$lam_image_file.$lam_image_categories.'<label for="alt">'.gTxt('alt_text').'</label>'.
	$lam_image_alt.$lam_image_caption.
	fInput('submit', '', gTxt('upload'), 'smallerbox').
	n.'</div>'.
	n.'</form>';
}
// -------------------------------------------------------------
function lam_image_uploader_prefs($event, $step) {
	global $prefs;
	switch ($step) {
	case 'remove':
		$lam_status = lam_image_uploader_gTxt('preferences_removed');
		break;
	case 'install':
		$lam_status = lam_image_uploader_gTxt('preferences_installed');
		break;
	case 'update':
		$lam_status = gTxt('preferences_saved');
		break;
	default:
		$lam_status = '';
	}
	
      	pagetop(lam_image_uploader_gTxt('prefs'), $lam_status);
	$checkInstalled = fetch('event','txp_prefs','name','lam_image_uploader_show_thumbnail');
	
      	if ($step == 'update') {
      		extract(doSlash(psas(array(
      			'show_thumbnail', 'show_image_id', 'image_caption', 'show_attach_image', 'show_append_image', 'auto_append', 'image_categories', 'move_sidebar'
      		))));
      		$show_thumbnail  = ($show_thumbnail == '1') ? $show_thumbnail : '0';
      		$show_image_id = ($show_image_id == '1') ? $show_image_id : '0';
      		$image_caption = ($image_caption == '1') ? $image_caption : '0';
      		$show_attach_image  = ($show_attach_image == '1') ? $show_attach_image : '0';
      		$show_append_image = ($show_append_image == '1') ? $show_append_image : '0';
      		$auto_append  = ($auto_append == '1') ? $auto_append : '0';
      		$image_categories = ($image_categories == '1') ? $image_categories : '0';
      		$move_sidebar = ($move_sidebar == '1') ? $move_sidebar : '0';
      		safe_update('txp_prefs', "val = '$show_thumbnail'", "name = 'lam_image_uploader_show_thumbnail'");
      		safe_update('txp_prefs', "val = '$show_image_id'", "name = 'lam_image_uploader_show_image_id'");
      		safe_update('txp_prefs', "val = '$image_caption'", "name = 'lam_image_uploader_image_caption'");
      		safe_update('txp_prefs', "val = '$show_attach_image'", "name = 'lam_image_uploader_show_attach_image'");
      		safe_update('txp_prefs', "val = '$show_append_image'", "name = 'lam_image_uploader_show_append_image'");
      		safe_update('txp_prefs', "val = '$auto_append'", "name = 'lam_image_uploader_auto_append'");
      		safe_update('txp_prefs', "val = '$image_categories'", "name = 'lam_image_uploader_image_categories'");
      		safe_update('txp_prefs', "val = '$move_sidebar'", "name = 'lam_image_uploader_move_sidebar'");
      		$prefs = get_prefs();
      	}
      	if($step == 'remove') {
      		lam_image_uploader_install('remove');
      		$checkInstalled = fetch('event','txp_prefs','name','lam_image_uploader_show_thumbnail');
      	} else if($step == 'install') {
      		lam_image_uploader_install('install');
      		$checkInstalled = fetch('event','txp_prefs','name','lam_image_uploader_show_thumbnail');
      	}
	if($checkInstalled) {
      	echo n.n.'<div style="margin: 3em auto auto auto; width: 30em;">'.
      	n.n.hed(lam_image_uploader_gTxt('prefs'), '1').
      	n.n.form(
      		n.eInput('lam_image_uploader_prefs').
      		n.sInput('update').
      		n.n.tag(
      			n.n.tag(gTxt('edit_preferences'), 'legend').
      			n.n.graf(
      				lam_image_uploader_gTxt('show_thumbnail').br.
      				n.yesnoRadio('show_thumbnail', $prefs['lam_image_uploader_show_thumbnail'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('show_image_id').br.
      				n.yesnoRadio('show_image_id', $prefs['lam_image_uploader_show_image_id'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('image_caption').br.
      				n.yesnoRadio('image_caption', $prefs['lam_image_uploader_image_caption'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('show_attach_image').br.
      				n.yesnoRadio('show_attach_image', $prefs['lam_image_uploader_show_attach_image'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('show_append_image').br.
      				n.yesnoRadio('show_append_image', $prefs['lam_image_uploader_show_append_image'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('auto_append').br.
      				n.yesnoRadio('auto_append', $prefs['lam_image_uploader_auto_append'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('image_categories').br.
      				n.yesnoRadio('image_categories', $prefs['lam_image_uploader_image_categories'])
      			).
      			n.n.graf(
      				lam_image_uploader_gTxt('move_sidebar').br.
      				n.yesnoRadio('move_sidebar', $prefs['lam_image_uploader_move_sidebar'])
      			)
      		, 'fieldset').
      		n.n.fInput('submit', 'update', 'Update', 'smallerbox')
	).n.n.'</div>';
	}
	echo n.n.'<div style="margin: 3em auto auto auto; width: 30em;">'.
      	n.n.hed(lam_image_uploader_gTxt('install'), '1');
      	echo '<form method="post" action="index.php">';
      	echo hInput('event','lam_image_uploader_prefs');
      	if(empty($checkInstalled)) {  
      		echo fInput('submit', 'step', 'install', 'smallerbox');
      	} else {
      		echo fInput('submit', 'step', 'remove', 'smallerbox');
      		}
      	echo '</form>';
}
// -------------------------------------------------------------
function lam_image_uploader_install($install) {
      	global $prefs;
      	$updated = false;
      	$settings = "prefs_id = 1, type = 2, event = 'admin', position = 0";
	if($install == 'install') {
        	if (!isset($prefs['lam_image_uploader_show_thumbnail'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_show_thumbnail', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_show_image_id'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_show_image_id', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_image_caption'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_image_caption', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_show_attach_image'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_show_attach_image', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_show_append_image'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_show_append_image', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_auto_append'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_auto_append', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_image_categories'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_image_categories', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if (!isset($prefs['lam_image_uploader_move_sidebar'])) {
        		safe_insert('txp_prefs', "name = 'lam_image_uploader_move_sidebar', val = '1', html = 'yesnoradio', $settings");
        		$updated = true;
        	}
        	if ($updated) {
        		$GLOBALS['prefs'] = get_prefs();
        	}
      	}
      	if($install == "remove") {
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_show_thumbnail'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_show_image_id'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_image_caption'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_show_attach_image'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_show_append_image'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_auto_append'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_image_categories'");
      		safe_delete('txp_prefs',"name = 'lam_image_uploader_move_sidebar'");
      	}
}
// -------------------------------------------------------------
function lam_image_uploader_gTxt($what, $atts = array()) {
	$lang = array(
		'attach_image'						=> 'Attach Article Image',
		'append_image'						=> 'Append Article Image',
		'prefs'							=> 'lam_image_uploader Preferences',
		'preferences_removed'					=> 'Preferences removed from database!',
		'preferences_installed'					=> 'Preferences added to database!',
		'image_caption'						=> 'Image caption?',
		'remove'						=> 'remove',
		'auto_append'						=> 'Automatically append article image id?',
		'show_attach_image'					=> 'Show "Attach Article Image" link?',
		'show_append_image'					=> 'Show "Append Article Image" link?',
		'show_image_id'						=> 'Show &lt;txp:image id /&gt; text?',
		'show_thumbnail'					=> 'Show Thumbnail?',
		'image_categories'					=> 'Allow image category assignment on upload?',
		'move_sidebar'						=> 'Move to left sidebar?',
		'install'						=> 'lam_image_uploader Install/Remove',
	);
	return strtr($lang[$what], $atts);
}