<?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#caddPostWanted'</script>"; die;
}

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

$member_query=mysql_query("SELECT adv_countryid FROM adverts LEFT JOIN members ON (adv_userid=mem_userid) WHERE adv_userid = '$WUserID' AND adv_approved='1'") or die(mysql_error());
$sql_array = mysql_fetch_object($member_query);
?>

<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($){

$("#mainCat").change(function()
{
var id=$(this).val();
var dataString = 'catID='+ id;

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

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

$.getJSON('postAction.php?Mode=getFor', { catID: id, forGroup:2 }, function(html) {
	if (html.status=="1") {
		$("#radioFor").html(html.radioFor);
		$("#subSelect").html(html.subSelect);
	} else {
		$("#radioFor").html(html.error);
		$("#subSelect").html(html.error);
	}
});

});

$("#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();
});

var id = 1;

$('.thumb').each(
   function() { 
     $(this).attr('id', 'thumb' + id); 
	id++;

	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');
			}
		},
		onComplete: function(file, response) {
//			alert(response);
			
	  		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.lightgrey2').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'));
    }
  });
});


  $('#price').focus(function() {
  	if($(this).val()=="") $('#priceValue').html('0.00');
  	 else $('#priceValue').html($(this).val());
  });
  $('#price').blur(function() {
  	if($(this).val()=="") $('#priceValue').html('0.00');
  	 else $('#priceValue').html($(this).val());
  });


    $("#addPost").bind('submit', function() {

	 	$('#msg_content_error').html('');
   CKEDITOR.instances['description'].updateElement();

      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 remove Describe it from ' + $(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 ($(this).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;
    }
	 });

 	if ($(":input.required:checked").length == 0) {
	 
		$("#msg_content_error").fadeIn('slow');
	 	$('#msg_content_error').append('Ops! Please choose Option for Category!<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;
	}


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

	var str = 'Mode=putInfo&' + $(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');

// 		$("#msg_content_error").fadeIn('slow');
//	 	$('#msg_content_error').html('Ops! Done!');
//			$('#msg_content_error').append('<br>'+result.success);
		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">Create Wanted<sup>+</sup> </div></td>
	</tr>
	<tr>
		<td valign="top" width="100%"><div id="msg_content_error" style="display:none;"></div>
			<div id="sub_content">
				<form id="addPost" name="addPost" method="post" style="padding:0; margin:0; border:0;">
					<input name="userid" type="hidden" value="<?=$WUserID?>" />
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td><div class="left margin_r_5 p5 margin_l_20"><span class="blue_20">Title</span><br />
									<span class="grey_10"><span id="maxWord">150</span> Max<br />
									Characters</span></div>
								<div class="left p5" id="markPost">
									<input name="title" type="text" class="title required" id="title" value="<?=$_SESSION["postTitle"]?>" maxlength="150" rel="Title" />
								</div></td>
						</tr>
						<tr>
							<td><div class="left solid_line"><img src="images/spacer.gif" width="1" height="1" /></div>
								<table width="100%" border="0" cellspacing="0" cellpadding="5" class="white_back_t_xb">
									<tr>
										<td valign="top"><div class="preview"><img class="thumb" width="100" height="100" src="images/upimage.jpg" /></div>
											<div class="preview"><img class="thumb" width="100" height="100" src="images/upimage.jpg" /></div>
											<div class="preview"><img class="thumb" width="100" height="100" src="images/upimage.jpg" /></div></td>
										<td width="100%" valign="top"><div id="markPost">
												<p>
													<label for="mainCat" class="label">Category:* </label>
													<select name="mainCat" id="mainCat" class="selectMain required" rel="Category">
														<?php
																			$sql=mysql_query("select catID, catName from market_category order by catID asc");
																			while($row=mysql_fetch_array($sql))
																			{
																			$id=$row['catID'];
																			$data=$row['catName'];
																			echo '<option value="'.$id.'">'.$data.'</option>';
																			 } ?>
													</select>
													<span id="radioFor">
													<?php
																			$sql=mysql_query("select forID, forName from market_category_for where catID=1 and forGroup=2 order by forID asc");
																			$radioCount = 0;
																			while($row=mysql_fetch_array($sql))
																			{
																			$id=$row['forID'];
																			$data=$row['forName'];
																			$radioCount++;
																			if ($radioCount == 1) $check = ' checked="checked"'; else $check ='';
																			echo '<label><input type="radio" name="optionFor" id="optionFor" value="'.$id.'" class="radio required"'.$check.' />'.$data.'</label>';
																			 } ?>
													</span> </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
																			$sql=mysql_query("select dataID, dataName from market_category_data where catID=1 and parent=0 order by dataName asc");
																			while($row=mysql_fetch_array($sql))
																			{
																			$id=$row['dataID'];
																			$data=$row['dataName'];
																			echo '<option value="'.$id.'">'.$data.'</option>';
																			 } ?>
													</select>
													</span> <span id="subSelectsub"> </span> </p>
												<p>
													<label for="location" class="label">Delivery Location: </label>
													<input name="location" type="text" class="input lightgrey2" id="location" maxlength="255" rel="Service Location" title="e.g. Kuala Lumpur, Malaysia" />
												</p>
												<p>
													<label for="price" class="label">Price Budget:* </label>
													<input name="price" type="text" id="price" maxlength="10" class="price required number" rel="Min Price" />
													<span class="inputPrice">USD</span> to <img src="images/spacer.gif" width="25" /><input name="priceTo" type="text" id="priceTo" maxlength="10" class="price number" rel="Max Price" />
													<span class="inputPrice">USD</span> <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>
												<p>
													<label for="keyword" class="label">Keywords:* </label>
													<input name="keyword" type="text" class="input required lightgrey2" id="keyword" 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" class="input required lightgrey2" id="tags" 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 lightgrey2" rel="Description" title="Describe it!" ></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 colspan="2" 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>
