<?php
include("includes/site_info.php");
include('session_handler.inc');

if(!preg_match("/\/home.php/",$_SERVER['HTTP_REFERER'])){
	echo "<script>location.href='" . $CONST_LINK_ROOT . "/home.php#ccover'</script>"; die;
}


$option_manager = new OptionManager();
$currencysym = $option_manager->GetValue('currency_symbol');
$currency = $option_manager->GetValue('currency');
$currencypoint = $option_manager->GetValue('currency_point');

$WUserID = $_SESSION['Sess_UserId'];
$WUsername = $_SESSION['Sess_UserName'];

if ($_REQUEST['postID']) { $postID = $_REQUEST['postID']; }
else { $postID = 0; }
$active_query=mysql_query("SELECT title, why, description, price, DATE_FORMAT(postDate, '%M %d, %Y at %h:%i %p') as postDate, DATE_FORMAT(expDate, '%M %d, %Y at %h:%i %p') as expDate, forName, forGroup, location, Country, mainCat, optionFor, subCat, subCatsub, mem_userid, price2, delivery, keyword, tags, commision FROM market_Post LEFT JOIN market_category_for on (optionFor=forID) where mem_userid=$WUserID and postID=$postID limit 1",$link) or die(mysql_error());
$activeTotal = mysql_num_rows($active_query);
if($activeTotal>0) {
	$sql = mysql_fetch_object($active_query);

	$forID = $sql->optionFor;

$photo_query=mysql_query("SELECT photoID, photoURL, photoThumb, photoMed FROM market_PostPhoto where mem_userid=$WUserID and postID=$postID order by photoID asc",$link) or die(mysql_error());
$photoTotal = mysql_num_rows($photo_query);

$price = number_format(ceil($sql->price/$currencypoint),0);
$price2 = number_format(ceil($sql->price2/$currencypoint),0);
?>

<div id="top_panel" class="submenu">
	<?php include ("panel_top.php"); ?>
</div>
<script type="text/javascript" src="js/ajaxupload.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){

$('.datetimepicker > pre').each(function(i){
	eval($(this).text());
});

$("#subCat").live('change', function()
{
var id=$(this).val();

$("#msg_content_error").fadeOut('slow');
$('#msg_content_error').html('');

$("#subSelectsub").html('<img src="images/loader1.gif" border="0" align="absmiddle">');

$.getJSON('postAction.php?Mode=getsubSelect', { dataID: id }, function(html) {
	if (html.status=="1") {
		$("#subSelectsub").html(html.subSelect);
	} else {
		$("#subSelectsub").html(html.error);
	}
});

});

$("span.remove").live('click', function() {
	var targetid = $(this).attr('id').replace("remove", "");
	$('img#thumb'+targetid).attr('src','images/upimage.jpg');
	$('input#imagefield'+targetid).remove();
	$('input#imagefield'+targetid+'med').remove();
	$('input#imagefield'+targetid+'ori').remove();
	$('span#remove'+targetid).remove();
});

$('.thumb').each(
   function() { 

	new AjaxUpload($(this).attr('id'), {
		action: 'postAction.php',
		name: 'image'+$(this).attr('id'), // name: 'image'+$(this).attr('id'),
		responseType: 'json',
		data: {Mode : 'uploadPic', userid : '<?=$WUserID?>', fieldname: 'image'+$(this).attr('id')},
		onSubmit: function(file, extension) {
		
			var targetid = this._settings.name.replace("imagethumb", "");
		
			if (!(extension && /^(jpg|png|jpeg|gif)$/i.test(extension))){
                        // extension is not allowed
                        alert('Error: invalid file extension');
                        // cancel upload
                        return false;
                }
			else {
				
				$('img#thumb'+targetid).closest('div.preview').addClass('loading');
				this.disable();
			}
		},
		onComplete: function(file, response) {
//			alert(response);
			
	  		this.enable(); 
			
			if(response.status == '1') { 

			var targetid = this._settings.name.replace("imagethumb", "");
			
			$('img#thumb'+targetid).load(function(){
				$('img#thumb'+targetid).closest('div.preview').removeClass('loading');
				$('img#thumb'+targetid).unbind();
				$('img#thumb'+targetid).closest('div.preview').append('<span class="remove" id="remove'+targetid+'"></span>');
			});
			$('img#thumb'+targetid).attr('src', response.thumb);
			$('input#imagefield'+targetid).remove();
			$('input#imagefield'+targetid+'med').remove();
			$('input#imagefield'+targetid+'ori').remove();
			$('img#thumb'+targetid).after('<input type="hidden" name="imagefield'+targetid+'" id="imagefield'+targetid+'" value="'+response.thumb+'" /><input type="hidden" name="imagefield'+targetid+'med" id="imagefield'+targetid+'med" value="'+response.med+'" /><input type="hidden" name="imagefield'+targetid+'ori" id="imagefield'+targetid+'ori" value="'+response.ori+'" />');
			
			} else {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').html('Ops! Error, please try again!');
		if ($.isArray(response.error)==true){
			$.each(response.error, function(key, value) { 
 			$('#msg_content_error').append('<br>'+value);
				});
		} else {
 			$('#msg_content_error').append('<br>'+response.error);
		}
			}
			
		}
	});
});	
 
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#999'; // Colour of default text

$(':input.checkEmpty').each(function() {
  var $this = $(this);
  if($this.val() === '') {
    $this.val($this.attr('title'));
  }
  $this.focus(function() {
    if($this.val() === $this.attr('title')) {
      $this.val('');
      this.style.color = active_color;
    }
  });
  $this.blur(function() {
    if($this.val() === '') {
        this.style.color = inactive_color;
      $this.val($this.attr('title'));
    }
  });
});
  
<?php if ($sql->forGroup==1) {?>
  $('#price').focus(function() {
  	if($(this).val()=="") $('#priceValue').html('0');
  	 else {
	 var newnumber = Math.ceil($(this).val()/<?=$currencypoint?>);
	 $('#priceValue').html(parseInt(newnumber));
  		if($('#commision').val()!="") {
	 		var newnumber2 = Math.ceil($(this).val()/<?=$currencypoint?>);
	 		var comm = Math.ceil((newnumber2 - (newnumber2*7/100) - 1/<?=$currencypoint?>) * $('#commision').val() / 100);
	 		$('#priceComm').html(parseInt(comm));
		}
	 }
  });
  $('#price').blur(function() {
  	if($(this).val()=="") $('#priceValue').html('0');
  	 else {
	 var newnumber = Math.ceil($(this).val()/<?=$currencypoint?>);
	 $('#priceValue').html(parseInt(newnumber));
  		if($('#commision').val()!="") {
	 		var newnumber2 = Math.ceil($(this).val()/<?=$currencypoint?>);
	 		var comm = Math.ceil((newnumber2 - (newnumber2*7/100) - 1/<?=$currencypoint?>) * $('#commision').val() / 100);
	 		$('#priceComm').html(parseInt(comm));
		}
	 }
  });

  $('#commision').focus(function() {
  if($('#price').val()=="") {  
  	$('#priceComm').html('0');
  } else {
  	if($(this).val()=="") $('#priceComm').html('0');
  	 else {
	 var newnumber = Math.ceil($('#price').val()/<?=$currencypoint?>);
	 var comm = Math.ceil((newnumber - (newnumber*7/100) - 1/<?=$currencypoint?>) * $(this).val() / 100);
	 $('#priceComm').html(parseInt(comm));
	 }
  }
  });
  $('#commision').blur(function() {
  if($('#price').val()=="") {  
  	$('#priceComm').html('0');
  } else {
  	if($(this).val()=="") $('#priceComm').html('0');
  	 else {
	 var newnumber = Math.ceil($('#price').val()/<?=$currencypoint?>);
	 var comm = Math.ceil((newnumber - (newnumber*7/100) - 1/<?=$currencypoint?>) * $(this).val() / 100);
	 $('#priceComm').html(parseInt(comm));
	 }
  }
 });

<?php } ?>
 
    $("#editPost").bind('submit', function() {

   CKEDITOR.instances['description'].updateElement();

	 	$('#msg_content_error').hide();
	 	$('#msg_content_error').html('');

      var isValid;
		$(":input.required").each(function (index) {
    if (this.value.match(/(Describe it)/i)) {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! Please fill in ' + $(this).attr('rel') + '!<br>');
      isValid = false;
    }
	 
	  if(($(this).val() === $(this).attr('title')) && ($(this).val() != '')) {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! Please fill in ' + $(this).attr('rel') + '!<br>');
      isValid = false;
    }

	if ($(":input.required").val().length < 1)
    {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! Please fill in ' + $(this).attr('rel') + ' with correct data!<br>');
      isValid = false;
    }
	 });

		$("select.required").each(function (index) {
//	 	$('#msg_content_error').append('Ops! Please select ' + $(this).val() + '!<br>');
		if ($(this).val()== 0) {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! Please select ' + $(this).attr('rel') + '!<br>');
      isValid = false;
		}
	 });
 
		$(":input.number").each(function (index) {
     if (($(this).val().length > 0) && ($(this).val().match(/[^0-9.]/))){
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! ' + $(this).attr('rel') + ' limit to digits only and no space!<br>');
      isValid = false;
   	}
	 });

	if (isValid == false) {
      return isValid;
	}


	$('input[type=submit]').attr("disabled","disabled");
	 $('#loading').show();
//	 $('#right_loading_c').show();

	var str = 'Mode=editInfo&' + $(this).serialize();
	var that = this;

   		$.ajax({
   		type: "POST",
   		url: "postAction.php",
   		data: str,
			dataType: "json",
   		success: function(result){
		$('#loading').hide();	
//	 	$('#right_loading_c').hide();

 		if(result.status == '1') { 
		$(':input','#addPost')
		 .not(':button, :submit, :reset, :hidden')
		 .val('')
		 .removeAttr('checked')
		 .removeAttr('selected');

		window.location.href='<?=$CONST_LINK_ROOT?>/home.php#cshowPost?tab=active&postID='+result.postID;
		} else {
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').html('Ops! Error, please try again!');
		$('input[type=submit]').removeAttr("disabled");
		if ($.isArray(result.error)==true){
			$.each(result.error, function(key, value) { 
 			$('#msg_content_error').append('<br>'+value);
				});
		} else {
// 		$('#msg_content_error').append('<br>'+result);
			$('#msg_content_error').append('<br>'+result.error);
		}
		}
		}

 });
return false;

    });

    });
</script>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="white_back_t_xb">
	<tr>
		<td><div class="grey_12 blue_row_back solid_line_separator padding_5">Edit Post </div></td>
	</tr>
	<tr>
		<td valign="top" width="100%"><div id="msg_content_error" style="display:none;"></div>
			<div id="sub_content">
				<form id="editPost" name="editPost" method="post" style="padding:0; margin:0; border:0;">
					<input name="userid" type="hidden" value="<?=$WUserID?>" />
					<input name="postID" type="hidden" id="postID" value="<?=$postID?>" />
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td><table width="100%" border="0" cellspacing="0" cellpadding="5" class="white_back_t_xb">
									<tr>
										<td valign="top"><?php if($photoTotal>0) {
													$j=1;
													while ($sqlPhoto = mysql_fetch_object($photo_query) ) {
													?>
											<div class="preview" id="Pic<?=$j?>"> <img src="<?=$sqlPhoto->photoThumb?>" name="thumb<?=$j?>" width="100" height="100" class="thumb" id="thumb<?=$j?>" />
												<input type="hidden" name="imagefield<?=$j?>" id="imagefield<?=$j?>" value="<?=$sqlPhoto->photoThumb?>" />
												<input type="hidden" name="imagefield<?=$j?>med" id="imagefield<?=$j?>med" value="<?=$sqlPhoto->photoMed ?>" />
												<input type="hidden" name="imagefield<?=$j?>ori" id="imagefield<?=$j?>ori" value="<?=$sqlPhoto->photoURL ?>" />
												<span class="remove" id="remove<?=$j?>"></span></div>
											<?php 
														$j++;
														}
														for ($i=$photoTotal+1; $i<=3; $i++){
													?>
											<div class="preview" id="Pic<?=$i?>"><img src="images/upimage.jpg" name="thumb<?=$i?>" width="100" height="100" class="thumb" id="thumb<?=$i?>" /></div>
											<?php
													}
													} else {
														for ($i=1; $i<=3; $i++){
													?>
											<div class="preview" id="Pic<?=$i?>"><img src="images/upimage.jpg" name="thumb<?=$i?>" width="100" height="100" class="thumb" id="thumb<?=$i?>" /></div>
											<?php
													}
													} ?>
										</td>
										<td width="100%" valign="top"><div id="markPost">
												<p>
													<label for="title" class="label">Title:* </label>
													<input name="title" type="text" class="input required" id="title" value="<?=$sql->title;?>" maxlength="150" rel="Title" />
												</p>
												<p>
													<label for="mainCat" class="label">Category: </label>
													<input type="text" value="<?=$sql->forName;?>" class="input" disabled="disabled" />
												</p>
												<p>
													<label for="subCat" class="label"> Subcategory:* </label>
													<span id="subSelect">
													<select name="subCat" id="subCat" class="select required" rel="Subcategory">
														<option value="0">Select a Subcategory</option>
														<?php
																			$sqlq=mysql_query("select dataID, dataName from market_category_data where catID=$sql->mainCat and parent=0 order by dataName asc");
																			while($row=mysql_fetch_array($sqlq))
																			{
																			$id=$row['dataID'];
																			$data=$row['dataName'];
																			echo '<option value="'.$id.'"';
																			if($id==$sql->subCat){ echo " selected='selected'";}
																			echo '>'.$data.'</option>';
																			 } ?>
													</select>
													</span> <span id="subSelectsub">
													<?php
$sqlqq=mysql_query("select dataID, dataName from market_category_data where parent=$sql->subCat order by dataName asc");
$total = mysql_num_rows($sqlqq);
if ($total > 0) {

$subSelect = '<select name="subCatsub" id="subCatsub" class="select">';
while($row=mysql_fetch_array($sqlqq))
{
$id=$row['dataID'];
$data=$row['dataName'];
$subSelect .= '<option value="'.$id.'"';
if($id==$sql->subCatsub){ $subSelect .=" selected='selected'";}
$subSelect .= '>'.$data.'</option>';
}
$subSelect .= '</select>';
} else {
$subSelect = '';
}

echo $subSelect;
																?>
													</span> </p>
												<?php if ($sql->forGroup==1) {?>
												<p>
													<label for="Country" class="label">Service From: </label>
													<select name="Country" id="Country" size="1" class="select" rel="Country">
														<option value="0">Select a Country</option>
														<?php
												$countryr=mysql_query("select * from Geo_Countries order by Country");
												while($rst= mysql_fetch_array($countryr))
												{
												?>
														<option value="<?php echo $rst["CountryId"];?>"<?php if($rst["CountryId"]==$sql->Country){ echo " selected='selected'";}?> ><?php echo $rst["Country"];?></option>
														<?php
												}
												?>
													</select>
												</p>
												<?php } ?>
												<p>
													<label for="location" class="label">
													<?php if ($sql->forGroup==1) {?>
													Service Location:*
													<?php } ?>
													<?php if ($sql->forGroup==2) {?>
													Delivery Location:
													<?php } ?>
													</label>
													<input name="location" type="text" class="input required<?php if(empty($sql->location)) { echo" lightgrey2"; }?> checkEmpty" id="location" value="<?php echo $sql->location;?>" maxlength="255" rel="Service Location" title="e.g. Kuala Lumpur, Malaysia" />
												</p>
												<?php if ($sql->forGroup==1) {?>
												<p>
													<label for="delivery" class="label">Delivery Details:* </label>
													<input name="delivery" type="text" id="delivery" value="<?=$sql->delivery?>" class="input required<?php if(empty($sql->delivery)) { echo" lightgrey2"; }?> checkEmpty" maxlength="255" rel="Delivery Details" title="e.g. Counter / Postal / Courier" />
												</p>
												<?php } ?>
												<p>
													<label for="price" class="label">Price
													<?php if ($sql->forGroup==2) {?>
													Budget
													<?php } ?>
													:*</label>
													<input name="price" type="text" id="price" value="<?=$sql->price?>" class="price required number" rel="Price" maxlength="10" />
													<span class="inputPrice">USD</span>
													<?php if($sql->forGroup==2){?>
													to <img src="images/spacer.gif" width="25" />
													<input name="price2" type="text" id="price2" value="<?=$sql->price2?>" class="price number" maxlength="100" />
													<span class="inputPrice">USD</span>
													<?php } ?>
													<a href="currencytool.html" onclick="javascript: jQuery.facebox({div:'#ConverterTable'}, 'Currency Converter'); return false;" class="blue_b">Currency Converter</a>
												<div class="none">
													<div class="none width_500" align="center" id="ConverterTable">
														<div id='oanda_ecc'>
															<!-- IF YOU ALTER OR REMOVE THE FOLLOWING CODE, THE EMBEDDED WIDGET WILL NOT WORK. -->
															<span style='color:#000; text-decoration:none; font-size:9px;'><a href='http://www.oanda.com/currency/converter/' id='oanda_cc_link'>Currency Converter</a> by OANDA</span>
															<script src='http://www.oanda.com/embedded/converter/get/b2thenVraW4vL3dhdWhhaGE=/?lang=en'></script>
														</div>
													</div>
												</div>
												</p>
												<?php if ($sql->forGroup==1) {?>
												<p>
													<label for="commision" class="label">Commision Offered:* </label>
													<img src="images/iconPA_o.gif" border="0" align="absmiddle" /><span id="priceValue"><?=$price?></span> - (7% + USD1) x
													<input name="commision" type="text" class="comm input required number" id="commision" value="<?=$sql->commision?>" maxlength="2" rel="Commision Offered" />
													<span class="inputComm">%</span> = <img src="images/iconPA_o.gif" border="0" align="absmiddle" /><span id="priceComm"><?=ceil(($price - ($price*7/100) - (1/$currencypoint)) * $sql->commision / 100)?></span>
												</p>
												<?php } ?>
												<p>
													<label for="keyword" class="label">Keywords:* </label>
													<input name="keyword" type="text" id="keyword" value="<?=$sql->keyword?>" class="input required<?php if(empty($sql->keyword)) { echo" lightgrey2"; }?> checkEmpty" maxlength="255" rel="Keywords" title="Good and unique words that associate to your post" /> <span class="grey_10">separate keywords with commas (,) </span>
												</p>
												<p>
													<label for="tags" class="label">Searches Tags:* </label>
													<input name="tags" type="text" id="tags" value="<?=$sql->tags?>" class="input required<?php if(empty($sql->tags)) { echo" lightgrey2"; }?> checkEmpty" maxlength="255" rel="Searches Tags" title="More specify your topic and content" /> <span class="grey_10">separate tags with commas (,) </span>
												</p>
												<p>
													<label for="description" class="label"> Description:* </label>
													<br />
													<br />
													<textarea name="description" id="description" class="textarea required<?php if(empty($sql->description)) { echo" lightgrey2"; }?> checkEmpty" rel="Description" title="Describe it!" ><?=html_entity_decode($sql->description,ENT_QUOTES)?></textarea>
													<script type="text/javascript">
			//<![CDATA[

				var o = CKEDITOR.instances['description'];
				if (o) CKEDITOR.remove(o);

				var editor = CKEDITOR.replace( 'description', {
					extraPlugins : 'autogrow',
					autoGrow_maxHeight : 500,
					removePlugins : 'resize',
					entities : false,
					htmlEncodeOutput : false
				});
				
				CKFinder.setupCKEditor( editor, '/ckfinder/' );

			//]]>
			</script>
												</p>
											</div></td>
									</tr>
									<tr>
										<td valign="top">&nbsp;</td>
										<td valign="top">&nbsp;</td>
									</tr>
								</table>
								<div class="left solid_line"><img src="images/spacer.gif" width="1" height="1" /></div></td>
						</tr>
						<tr>
							<td align="center"><input name="cancel" type="button" class="button" id="cancel" value="Cancel" onclick="javascript: callpage('#ccover');"/>
								<input name="reset" type="reset" class="button" id="reset" value="Reset" />
								<input name="save" type="submit" class="submit" id="save" value="Proceed"/></td>
						</tr>
						<tr>
							<td align="center">&nbsp;</td>
						</tr>
					</table>
				</form>
			</div></td>
	</tr>
</table>
<?php
} else {
?>
<div id="top_panel" class="submenu">
	<?php include ("panel_top.php"); ?>
</div>
<table width="100%" border="0" cellpadding="5" cellspacing="0" class="white_back_t_xb">
	<tr>
		<td><div class="grey_12 blue_row_back solid_line_separator padding_5">Edit Post </div></td>
	</tr>
	<tr>
		<td align="center">Ops! An Error Has Occurred! Please try again!</strong></td>
	</tr>
</table>
<?php
}
?>
