<?php
unset($view);
$view = $_GET['view'];
$admin_page = $_GET['admin-page'];
include("admin_globals.php");
// if ($_SESSION['FirstName'] == "") {
// 	echo 'You are not authorized to view this blog. <br><br>You may <a href="index.php">log in here.</a>';
// 	exit;
// }
include "sessionchecklink.php";
?>
<style type="text/css">
	#assigned-categories {
		margin-bottom: 10px;
	}
	#categories .category-wrapper {
		margin-bottom: 8px;
	}
	#categories .category {
		cursor: pointer;
	}
	#category-buttons button {
		margin-bottom: 8px;
	}
</style>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckfinder/ckfinder_v1.js"></script>
<?php


//function to build seo-friendly url link
setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $replace=array(), $delimiter='-') {
	if( !empty($replace) ) {
		$str = str_replace((array)$replace, ' ', $str);
	}

	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}
 //require_once ('mysql_connect.php');
$action          = $_GET["a"];
$delete          = $_GET["delete"];
$approve          = $_GET["approve"];

//delete or approve any comments as selected
if($view=="comments"){
//echo "checkpoint 1";
	if(!empty($delete)){
		$query = "Delete from blogComments where commentid='" . $delete . "'";
		//echo "checkpoint 1";
	}
	if(!empty($approve)){
		$query = "Update blogComments set approved=1 where commentid='" . $approve . "'";
		//echo "checkpoint 1";
	}
	if(!empty($query)){
		//echo "qry=" . $query;
		mysql_query($query);
		//echo "checkpoint 1";
	}
}


//set specific post ID based on editing in progress or on selected blog
$editblog          = $_POST["blog"];
if(empty($editblog)){
$editblog          = $_GET["key"];
}


if (!empty($_POST["chkDelete"])) {
     $query = "delete from blog WHERE postid = '" . $_GET['key'] ."'";
     mysql_query($query);
     echo "<font color=red>blog deleted successfully.</font>";
     unset($action);
}
	//echo 'Action = ' . $action; (for testing)
if ($action == "add") {
         
         $query = "Insert into blog (title) values('" . $_POST["newblog"] . "')";
         mysql_query($query);
         echo "<font color=red>New blog added successfully.</font>";
		 $editblog=mysql_insert_id();
}


                      //******************make any updates
if ($action == "update") {
	// check for blog image
	$sql = "SELECT blog_image
			FROM blog 
			WHERE postid = '".$_GET['key']."'";
	$result = mysql_query($sql) or die(mysql_error());
	if (mysql_num_rows($result) > 0) {
		$row = mysql_fetch_assoc($result);
		$currentBlogImage = $row['blog_image'];
	} else {
		$currentBlogImage = '';
	}

	// remove blog image
	if (isset($_POST['remove_blog_image']) && $_POST['remove_blog_image'] == 'true') {
		removeBlogImage($currentBlogImage);
		$currentBlogImage = '';
	}

	$blogImage = saveBlogImage($currentBlogImage);
	
	//update blog_tags table
	$tagwords= strtolower(mysql_real_escape_string($_POST['tags']));
	$tagword_array = (explode(",",$tagwords));
	foreach($tagword_array as $key) {    		
		$word = strtolower(trim($key));
		//echo '"'.$word.'"<br/>';
		$select = "select tags from blog_tags where tags = '$word'";
		$result=mysql_query($select);
		if(mysql_num_rows($result)>0){
			//do nothing, already exists in table
		} else {
			//add tag to table
			$sql="insert into blog_tags (tags) values ('$word')";
			mysql_query($sql);
		}
		
		
	}
	
	
	
		$query = "UPDATE blog SET title = '" . mysql_real_escape_string($_POST['title']) . "', tags = '".strtolower($tagwords)."', content = '" . mysql_real_escape_string($_POST['body']) . "', blog_image = '".mysql_real_escape_string($blogImage)."'";
	//echo $query;
    if(!empty($_POST['chkArchive'])){
      $query .= ", Archive ='1'";
      }else{
        //if($_POST['blogname']!=="HOME"){  //can only turn to inArchive if not the main home blog
            $query .= ", Archive ='0'";
      //}
    }
	if(!empty($_POST['chkComments'])){
		$query .= ", allow_comments ='1'";
      }else{
        $query .= ", allow_comments ='0'";
    }
	if (isset($_POST['preview_length'])){
		$query.=", preview_length = '".mysql_real_escape_string($_POST['preview_length'])."'";
	}
	
	if (isset($_POST['category'])){
		$query.=", category_name = '".mysql_real_escape_string($_POST['category'])."'";
	}
	
	if (isset($_POST['seo_description'])){
		$query.=", meta_description = '".mysql_real_escape_string($_POST['seo_description'])."'";
	}
	if (isset($_POST['seo_keywords'])){
		$query.=", meta_keywords = '".mysql_real_escape_string($_POST['seo_keywords'])."'";
	}
	
	if (isset($_POST['postdate'])){
		$postdate = ($_POST['postdate']);
		$newDate = date("Y-m-d", strtotime($postdate));
		#date("Y-m-d")
		$query.=", postdate = '$newDate'";
	}
	
	//echo $_POST['postdate'];
	
	//add user friendly URL to point to this page
			if(empty($_POST['permalink'])){
				$dirty=$_POST['title'];
				$clean = toAscii($dirty);
				$query .= ", permalink ='". $clean ."'";
			} else {
				$dirty=$_POST['permalink'];
				$clean = toAscii($dirty);
				$query .= ", permalink ='".$clean ."'";
			}
		$query = $query . " WHERE postid = '" . $_GET['key'] ."'" ;
		//echo $query;
		mysql_query($query) or die(mysql_error());   //execute query

		//confirmation message that update worked...
		echo "<font color=red>blog content updated successfully.</font>";

	}	 //*******************end of update query

//display main admin link at top	
echo '<div style="margin-top:-8px;margin-bottom:14px;">
<h1>Manage Your Blog</h1>
<div id="single-admin-button">
<ul>
<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
</ul>
</div></div>';

	//show comments to approve or delete, if selected as current view
	if ($view=="comments"){
	echo "<a href='".$_SERVER['PHP_SELF']."?admin=blog'><div align='right'><font color='blue'><u>Back to Blog Homepage</u></font></div></a>";		

		//select any pending comments
		$commentqry ="Select * from blogComments where approved<>1";
		$cq=mysql_query($commentqry);
		echo"<div align='center'><table cellpadding=10 cellspacing=10><tr><td valign='top'><b><u>Contributor</b></u><td valign='top'><b><u>Comment</b></u><td valign='top'><b><u>Posted</b></u><td valign='top'><b><u>Action</b></u>";
		while($ncq=mysql_fetch_array($cq)){
			echo"<tr><td valign='top'>".$ncq[posterAlias]."<br>".$ncq[email]."<td width=250 valign='top'><div align='justify'>".$ncq[comment]."</div><td valign='top'>".$ncq[date]."<td valign='top'><a href='". $_SERVER['PHP_SELF']."?admin=blog&view=comments&approve=".$ncq[commentid]."'><font color='red'>Approve</font></a> | <a href='". $_SERVER['PHP_SELF']."?admin=blog&view=comments&delete=".$ncq[commentid]."'><font color='red'>Delete</font></a><td>";
			echo "<tr bgcolor=black><td height=1 colspan=4>";
		}
		echo "</table></div>";
	} else {
	
//if unapproved blog comments exist, show link to view them
if ($unapproved==1){
	echo "<a href='".$_SERVER['PHP_SELF']."?admin=blog&view=comments'><div align='right'><font color='red'><b><u>View Pending Blog Comments</u></b></font></div></a>";		
}

echo '<div style="margin-top:-30px;"><form action="index.php?admin-page='.$admin_page.'&a=add" method="post">Add new blog (title): <br /><input type="text" name="newblog" size=30>
	<input id="save-button" type="submit" name="save" value="Add blog">&nbsp; &nbsp; - OR - </form></div>';


 //create selector to choose page to edit
// echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=select&admin=blog" method="post">';
  echo '<form id="form-select-blog" action="" method="post">';
 echo'Choose blog post to edit: <br /><select name="blog">';
 $pages="Select postid, title from blog";
 $pg=mysql_query($pages);
  while($pnt=mysql_fetch_array($pg)){
   echo '<option value='. $pnt[postid];
   if($pnt[postid]==$editblog){echo ' selected="selected"';}
   echo'>' .$pnt[title] . '</option>';
}

mysql_close;
echo '</select> <input id="save-button" type="submit" name="select" value="Edit"></form><br><br>';
//end of selector

if(!empty($editblog)){	//determine which record to display
	$query = "SELECT * from blog where postid=$editblog";
	$rt=mysql_query($query);          // query executed 
	//echo mysql_error();                    // if any error is there that will be printed to the screen
} else{
	$query= "Select min(postid) as postid from blog";
	$rt=mysql_query($query);          // query executed
	while($nt=mysql_fetch_array($rt)){
		$editblog=$nt[postid];
	}
	mysql_close;
	$query = "SELECT * from blog where postid=$editblog";
	$rt=mysql_query($query);          // query executed 
}		
		
echo '<div align="center"><table border=0 cellpadding=0 cellspacing=4>';
if(isset($_GET['addcat'])&& isset($_GET['article'])){
	//add category to blog article
	$update="insert into blog_cat_ref (catkey, blogkey) values ('".$_GET['addcat']."','".$_GET['article']."')";
	mysql_query($update);
}
if(isset($_GET['remcat'])&& isset($_GET['article'])){
	//add category to blog article
	$update="delete from blog_cat_ref where catkey='".$_GET['remcat']."' && blogkey='".$_GET['article']."'";
	mysql_query($update);
}
while($nt=mysql_fetch_array($rt)){
	$blog_id = $nt['postid'];
	//$blog_url = 'http://'.$_SERVER['HTTP_HOST'].'/blog?article='.$nt[permalink];
	$blog_url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$nt[permalink];
	echo '<tr><td><input type="hidden" name="postid" value="' . $nt[postid] . '"><form action="index.php?admin-page='.$admin_page.'&a=update&key=' . $nt[postid] . '" method="post" enctype="multipart/form-data">';
	echo '<tr><td valign="top"><div align=left>Post title: </div><td valign="top"><div align=left><textarea id="blogtitle" name="title" cols="85">' .  $nt[title] . '</textarea><br><span>Characters: <span class=charcount></span></span></div>';
	if($nt[postdate]=="0000-00-00"){
		$postdate = date("m/d/Y");
	} else {
		//$postdate = date("m/d/Y", strtotime($nt[postdate]));	
		$postdate = date("m/d/Y",strtotime($nt[postdate]));		
	}
	echo '<tr><td valign="top"><div align=left>Post date: </div><td valign="top"><div align=left><input type="text" id="datepicker" name="postdate" value="'.$postdate.'"></div>';
	
	/*echo '<tr><td valign="top"><div align=left>Category: </div><td valign="top"><div align=left><select name="category">';
	$catqry = "Select category_name from blog_categories order by category_name";
	$catrt=mysql_query($catqry); 
	while($catnt=mysql_fetch_array($catrt)){
		$option = $catnt[category_name];
		$selected_option = $nt[category_name];
		echo "<option value='$option'";
		if($option==$nt[category_name]){echo " selected='selected'";}
		echo ">$option</option>";
	}
	
	echo "</select>";
	*/
	echo '<tr><td valign="top"><div align=left>Categories: </div><td valign="top"><div align=left><div id="assigned-categories">';
	//show selected categories
	$select = "select * from blog_cat_ref where blogkey='$nt[postid]'";
	$rt2=mysql_query($select);
	$catstring="";
	while($nt2=mysql_fetch_array($rt2)){
		if($catstring==""){
			$catstring=$nt2['catkey'];
		} else {
			$catstring.=",".$nt2['catkey'];
		}
	}
	if(isset($_GET['admin-page'])){
		$admin_page="admin-page=".$_GET['admin-page'];
	}
	if(!empty($catstring)){
		$select="select * from blog_categories where recordkey in($catstring)";
		$rt2=mysql_query($select);
		while($nt2=mysql_fetch_array($rt2)){
			//echo "<br>Selected categories:";
			echo $nt2['category_name']."<a href='".$_SERVER['PHP_SELF']."?$admin_page&remcat=".$nt2['recordkey']."&article=".$nt['postid']."' title='remove'><font color='red'><bold>(X)</bold></font></a><br>";
		}
	}
	echo "</div><!-- /#assigned-categories -->";

	echo '<div id="category-buttons">';
	echo '<div>';
	echo '<button class="create-category-button popup" data-popup-id="create_category" type="button" id="save-button">Create Category</button> &nbsp; ';
	echo '<button class="add-category-button popup" data-popup-id="add_category" type="button" id="save-button">Assign to Categories</button>';
	echo '</div>';
	echo '</div>';
	echo '<tr><td valign="top"><div align=left>Tags: </div><td valign="top"><div align=left><textarea style="margin-bottom:8px;" id="tags" name="tags" cols="85" rows="2">' .  $nt[tags] . '</textarea>
	<br /><a class="view-tags-button popup" data-popup-id="tags" id="save-button" href="#">View tag list</a> &nbsp; <font size="1"><i>Use commas between tags. (ex: word1, word2, word3)</i></font></div>';
	

    echo '<tr><td valign="top"><div align=left style="margin-top:10px;">Permalink: </div><td valign="top"><div align=left><input type="text" name="permalink" size="80" value="' .  $nt[permalink] . '"><br>
	<font color="blue"><i><a href="'.$blog_url.'" target="blank"><font color="blue">'.$blog_url.'</font></a></i></font></div>';

	echo '<tr>';
	echo '<td valign="top"><div style="margin-top:5px;" align=left>Blog Image: </div></td>';
	echo '<td align="left">';
	if (!empty($nt['blog_image'])) {
		echo '<p>Current Blog Image:</p>';
		echo '<img src="/custom/images/blog/'.$nt['blog_image'].'" /><br />';
		echo '<label><input type="checkbox" name="remove_blog_image" value="true" /> Remove Image</label>';
		echo '<br />';
		echo '<br />';
	}
	echo '<p>Upload New Blog Image:
	<br><font color="red"><i>(Browse to photo, then click "Save Image".)</i></font></p>';
	echo '<input id="blog-image" type="file" name="blog_image" />';
	echo ' <input id="blog-image-save-button" type="submit" name="save" value="Save Image" />';
	echo '<br />';
	echo '<br />';
	echo '</td>';
	echo '</tr>';

	echo '<tr><td valign="top"><div align=left>Content: </div><td valign="top"><div align=left><textarea class="ckeditor" name="body" id="blogbody" cols=60 rows=25>' . $nt[content] . '</textarea></div>';
    echo '<tr><td valign="top"><div align=left>Preview length: </div><td valign="top"><div align=left><input type="text" name="preview_length" size="6" value="' .  $nt[preview_length] . '">';  
	echo '<tr><td><div align=left>Allow Comments: </div><td valign="top"><div align=left><input type="checkbox" name="chkComments"';
    if(!empty($nt[allow_comments])) {
      echo ' checked=checked';
    }
    echo '"></div>';
	echo '<tr><td valign="top" colspan="2"><div align=left>Meta keywords: 
	<tr><td><td><div><textarea name="seo_keywords" id="seo_keywords" rows=2 style="width:540px;">' . mysql_real_escape_string($nt[meta_keywords]) . '</textarea><br><span>Characters: <span class=charcount></span></span>&nbsp;<span>Keywords: <span class=keywordcount></span></span></div>
	<tr><td><td></div>
	<tr><td colspan="2">Meta description:<tr><td><td><div><textarea name="seo_description" id="seo_description" rows=2 style="width:540px;">' . mysql_real_escape_string($nt[meta_description]) . '</textarea><br><span>Characters: <span class=charcount></span></span></div>
	<tr><td><td>';

				
			
			
	echo '<tr><td><div align=left>Archive: </div><td valign="top"><div align=left><input type="checkbox" name="chkArchive"';
    if(!empty($nt[archive])) {
      echo ' checked=checked';
    }
    echo '"></div>';
   
  
	echo '<tr><td><td valign=top><div align=left><input id="save-button" type="submit" name="save" value="Save"></div>';
	

	//display delete checkbox if blog is not a locked, built-in blog
	if(empty($nt[locked])) {
    echo '<tr><td valign="top"><div align=left>Delete: </div><td valign="top"><div align=left><input type="checkbox" name="chkDelete"><font color=red> <i><br>Be sure you mean to delete this blog (and all related comments) if you check this box<br> before saving. You will not be prompted again.</i></font></div>';
  }
  
  echo '</form>';
//}
}
echo '</table><br>';

	echo '</div>';
	
}
	

?>

<div class='loader'></div>
<div id='backgroundPopup'></div>
<!-- Create Category Popup -->
<div class='toPopDiv' id='popup_create_category'> 
	<div class='close'></div>
	<span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
	<div id='popup_content'> <!--your content start-->
		<h2>Create Category</h2>
		<form>
			<label>Name:</label>
			<input id="category-name" type="text" name="category_name" value="" />
			<input class="save-category" id="save-button" type="submit" name="create_category" value="Save">
		</form>
		<br />
	</div> <!--your content end-->
</div> <!--toPopup end-->

<!-- Assign Categories Popup -->
<div class='toPopDiv' id='popup_add_category'> 
	<div class='close'></div>
	<span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
	<div id='popup_content'> <!--your content start-->
		<h2>Assign Categories</h2>
		<div id="categories">

		</div>
		<br />
	</div> <!--your content end-->
</div> <!--toPopup end-->

<!-- Tags Popup -->
<div class='toPopDiv' id='popup_tags'> 
	<div class='close'></div>
	<span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
	<div id='popup_content'> <!--your content start-->
		<h2>Select Tags</h2>
		<div id="tags-list">

		</div>
		<br />
	</div> <!--your content end-->
</div> <!--toPopup end-->


<script type="text/javascript" src="js/counter.js"></script>
<script type="text/javascript" >
CKEDITOR.replace( 'blogbody',
{
	filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
	filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
	filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
	filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
	filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
	filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
	toolbarGroups: [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'mode' },

	],
    uiColor: '#499ED7'
});
function saveCategory() {
	var name = $('#category-name').val();
	if (name.length < 1) {
		alert('Please enter a category name.');
		return false;
	}

	$.ajax({
		type: 'post',
		url: 'save_category.php',
		data: {name: name}
	}).done(function(data) {
		if (data == 1) {
			disablePopup();
		} else {
			alert('Error adding category.');
		}
	});
}

function disablePopup() {
	if(popupStatus == 1) {
		var popDivs = $(".toPopDiv");
		
		$.each(popDivs,function(){
			$(this).fadeOut("normal");
		});
		
		//$("#toPopup_"+idNum[0]).fadeOut("normal");  
		$("#backgroundPopup").fadeOut("normal");
		popupStatus = 0;  // and set value to 0
	}
}
function loadCategories() {
	$.ajax({
		url: 'get_categories.php',
		dataType: 'json',
		data: {blog_id: '<?php echo $blog_id; ?>'}
	}).done(function(data) {
		if (data.hasOwnProperty('categories')) {
			$('#categories').html('');
			$.each(data.categories, function() {
				var category = '<div class="category-wrapper"><span class="category" data-category-id="'+this.recordkey+'" data-category-name="'+this.category_name+'">'+this.category_name+'</span></div>';
				$('#categories').append(category);
			});
		} else {
			alert('Error loading categories.');
			console.log(data);
		}
	});
}
function assignCategory(categoryId, categoryName) {
	$.ajax({
		type: 'post',
		url: 'assign_category.php',
		data: {blog_id: '<?php echo $blog_id; ?>', category_id: categoryId}
	}).done(function(data) {
		if (data == 1) {
			addAssignedCategory(categoryName, categoryId);
			disablePopup();
		} else {
			alert('Error assigning category: ' + data);
		}
	});
}
function addAssignedCategory(categoryName, categoryId) {
	var assignedCategory = categoryName+"<a href='<?php echo $_SERVER['PHP_SELF']."?{$admin_page}&remcat="; ?>"+categoryId+"<?php echo "&article=".$blog_id ?>' title='remove'><font color='red'><bold>(X)</bold></font></a><br>";
	$('#assigned-categories').append(assignedCategory);
}

function loadTags() {
	var selectedTags = $('#tags').val();

	// Get tags not already selected for this post
	$.ajax({
		type: 'post',
		url: 'get_tags.php',
		data: {selected_tags: selectedTags},
		dataType: 'json'
	}).done(function(response) {
		if (response.hasOwnProperty('result') && response.result == 1 && response.hasOwnProperty('tags')) {
			var content = '';
			if (response.tags != null) {
				$.each(response.tags, function() {
					content += '<div><a class="tag" href="#">' + this + '</a></div>';
				});
			} else {
				content += '<p>No available tags found.</p>';
			}
			$('#tags-list').html(content);


		} else {
			alert('Error getting list of available tags.');
		}
	});
}

function addTag(tag) {
	var selectedTags = $('#tags').val();
	selectedTags = selectedTags.trim();
	if (selectedTags.substr(selectedTags.length - 1) == ',') {
		selectedTags = selectedTags.substr(0, selectedTags.length - 1)
	}

	if (selectedTags.length != 0) {
		selectedTags += ', ';
	}

	selectedTags += tag;

	$('#tags').val(selectedTags);
}

$(document).ready(function() {
	$('#form-select-blog').submit(function(e) {
		var selectedBlog = $('select[name="blog"]').val();
		$(this).attr('action', '<?php echo $_SERVER['PHP_SELF']; ?>?admin-page=3&key='+selectedBlog);
	});

	// $('#blog-image').change(function() {
	// 	if ($(this).val().length > 0) {
	// 		$('#blog-image-save-button').show();
	// 	} else {
	// 		$('#blog-image-save-button').hide();
	// 	}
	// });

	$('.add-category-button').click(function(e) {
		loadCategories();
	});
	$('.save-category').click(function(e) {
		e.preventDefault();
		saveCategory();
		return false;
	});
	$(document).on('click', '.category', function(e) {
		var categoryId = $(this).data('category-id');
		var categoryName = $(this).data('category-name');
		assignCategory(categoryId, categoryName);
	});

	$('.view-tags-button').click(function() {
		loadTags();
	});

	$(document).on('click', '.tag', function() {
		addTag($(this).text());
		$(this).parent('div').remove();
		return false;
	});
});
</script>
<?php
	function saveBlogImage($currentBlogImage) {
		$blogImage = $currentBlogImage;

		if (!isset($_FILES) || !isset($_FILES['blog_image']) || $_FILES['blog_image']['error'] != 0) {
			return $blogImage;
		}

		// Make sure correct file type uploaded
		$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
		$detectedType = exif_imagetype($_FILES['blog_image']['tmp_name']);
		if (!in_array($detectedType, $allowedTypes)) {
			// invalid file type
			return $blogImage;
		}


		$dir = realpath('../custom/images/blog/');
		$filenameParts = pathinfo($_FILES['blog_image']['name']);
		$filename = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $filenameParts['filename']));
		$ext = $filenameParts['extension'];

		$newFilename = $filename.'.'.$ext;
		$i = 2;
		while (file_exists($dir.'/'.$newFilename)) {
			$newFilename = $filename.'-'.$i.'.'.$ext;
		}

		$dest = $dir.'/'.$newFilename;
		if (move_uploaded_file($_FILES['blog_image']['tmp_name'], $dest)) {
			// resize image
			require_once('includes/smart_resize_image.php');

			list($width, $height) = getimagesize($dest);
			if ($width >= $height) {
				smart_resize_image($dest, 200, 0, true, $dest);
			} else{
				smart_resize_image($dest, 0, 200, true, $dest);
			}

			$blogImage = $newFilename;
		}

		return $blogImage;
	}

	function removeBlogImage($currentBlogImage) {
		if (!empty($currentBlogImage)) {
			$dir = realpath('../custom/images/blog/');
			$filePath = $dir.'/'.$currentBlogImage;

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

		return true;
	}
?>
<div style="text-align:center;"><?php echo $bottom_links; ?></div>
<script>
  $(document).ready(function() {
    $("#datepicker").datepicker();
  });
  </script>
  