<?php
include('../config/config.php');
include(ADMIN_HTML.'html.inc.php');
include(ADMIN_INCLUDES.'functions.php');
checkLoginAdmin();

// Query to get the details of the event to be edited
$eventId = base64_decode($_GET['event']);
$qryRes = mysql_fetch_array(mysql_query("SELECT Name, Description, Logo, Party FROM tbl_candidate WHERE Id = '".$eventId."'"));
$eventFile = $qryRes['Logo'];

// update record
if ( isset($_POST['submit']) )
{
	// If new file is uploaded
	if ( !empty($_FILES['partyImage']['name']) ){
		$fileName = time().str_replace(' ', '_', $_FILES['partyImage']['name']); // replace the space with '_'
		move_uploaded_file($_FILES['partyImage']['tmp_name'],UPLOADS_PATH.'partylogo/'.$fileName);
		
		// Generate Images thunmnails		
		generate_image_thumbnail(UPLOADS_PATH.'partylogo/'.$fileName, UPLOADS_PATH.'partylogo/thumbs/thumb_'.$fileName,80,60);
		deleteFile(UPLOADS_PATH.'partylogo/', $eventFile); // Delete the file
		deleteFile(UPLOADS_PATH.'partylogo/thumbs/', 'thumb_'.$eventFile); // Delete the thumbnail of the file
		
		// Now update the record
		$updateQry = "UPDATE tbl_candidate
				SET
					Name = '".clean($_POST['candi_title'])."',
					Description = '".clean($_POST['candiDes'])."',
					Logo = '".$fileName."',
					Party = '".clean($_POST['candi_party'])."'
				WHERE Id = '".$eventId."'";
		mysql_query($updateQry);
	}
	else
	{
		$updateQry = "UPDATE tbl_candidate
				SET
					Name = '".clean($_POST['candi_title'])."',
					Description = '".clean($_POST['candiDes'])."',
					Party = '".clean($_POST['candi_party'])."'
				WHERE Id = '".$eventId."'";
		mysql_query($updateQry);
	}
	$redirectUrl = 'view-candidates.php';
	$_SESSION['succesMessage'] = 5;
	header("Location: $redirectUrl");
}


startHtml($title = "Edit Candidate");
tophead($title);
leftNav();

?>
<script type="text/javascript">
	tinyMCE.init({
		mode : "textareas",
		theme : "simple",
		// update validation status on change
		onchange_callback: function(editor) {
			tinyMCE.triggerSave();
			$("#" + editor.id).valid();
		}
	});
	
	jQuery.validator.addMethod("imageExt", function(value, element) { 
		return this.optional(element) || /^.*\.(jpg|jpeg|gif|JPG|png|PNG)$/.test(value);
	 }, ("Only [jpeg, gif, JPG, PNG] formats are allowed."));
	 
	// Form validation
	$(function() {
		var validator = $("#editEventForm").submit(function() {
			// update underlying textarea before submit validation
			tinyMCE.triggerSave();
		}).validate({
			ignore: "",
			rules: {
				event_title: "required",
				eventDes: "required",
				eventImage: "imageExt"
			},
			messages: {
				event_title: "Enter event title.",
				eventDes: "Enter event description."
			},
			errorPlacement: function(label, element) {
				// position error label after generated textarea
				if (element.is("textarea")) {
					label.insertAfter(element.next());
				} else {
					label.insertAfter(element)
				}
			}
		});
		validator.focusInvalid = function() {
			// put focus on tinymce on submit validation
			if( this.settings.focusInvalid ) {
				try {
					var toFocus = $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []);
					if (toFocus.is("textarea")) {
						tinyMCE.get(toFocus.attr("id")).focus();
					} else {
						toFocus.filter(":visible").focus();
					}
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		}
	});

</script>

<section id="main" class="column">
    <article class="module width_full">
        <header>
            <h3>Edit Candidate</h3>
        </header>
        <form name="editCandiForm" id="editCandiForm" action="" method="post" enctype="multipart/form-data">
            <fieldset style="margin:15px">
                <table width="100%">
                	<tr>
                    	<td>
                            <label>Candidate Name</label>
                            <input type="text" name="candi_title" id="candi_title" value="<?php echo $qryRes['Name'];?>" />
                        </td>
                    </tr>
                    <tr>
                    	<td>
                            <label>Party</label>
                            <input type="text" name="candi_party" id="candi_party" value="<?php echo $qryRes['Party'];?>" />
                        </td>
                    </tr>
                    <tr>
                    	<td>
                        	<label>Event Description</label>
                            <span class="tinyMCE"><textarea id="candiDes" name="candiDes" rows="15" cols="80" style="width: 99%;float:left;"><?php echo $qryRes['Description'];?></textarea></span>
                			<label for="candiDes" class="error" style="display:none;">Enter event description.</label>
                        </td>
                    </tr>
                    <tr>
                    	<td>
                        	<label>Event Image</label>
                            <input type="file" name="partyImage" id="partyImage" />
                            <a href="<?php echo UPLOADS_URL.'partylogo/'.$eventFile;?>" class="lightbox"><img src="<?php echo UPLOADS_URL.'partylogo/thumbs/thumb_'.$eventFile;?>" style="margin-top:-20px;" /></a>
                        </td>
                    </tr>
                    <tr>
                    	<td>
                        	<input type="submit" name="submit" id="submit" value="Update" />
                    		<input type="button" name="cancel" id="cancel" value="Cancel" onclick="window.location='<?php echo ADMIN_URL;?>view-candidates.php'" />
                        </td>
                    </tr>
                </table>
            </fieldset>
        </form>
    </article>
    <div class="spacer"></div>
</section>

<script type="text/javascript" src="<?php echo LIGHTBOX;?>js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo LIGHTBOX;?>themes/default/jquery.lightbox.css" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="<?php echo LIGHTBOX;?>themes/default/jquery.lightbox.ie6.css" /><![endif]-->
<script type="text/javascript" src="<?php echo LIGHTBOX;?>js/jquery.lightbox.js"></script>
<script type="text/javascript">
	jQuery.noConflict();
	jQuery(document).ready(function(){
		jQuery('.lightbox').lightbox();
	});
</script>
<?php
endHtml();
?>