<?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; }

function getPath ($firstID,$firstCat,$secID,$secCat,$thirdCat){
	$catpath="";
	if (!empty($thirdCat) && $secID > 0 && !empty($secCat)) {
	$catpath.=$thirdCat;
	$catpath=$secCat." > ".$catpath;

		if ($firstID >1 && !empty($firstCat)) {
			$catpath=$firstCat." > ".$catpath;
		}
	}
	
	if (empty($thirdCat) && $secID > 0 && !empty($secCat)) {
	$catpath.=$secCat;
		if ($firstID >1 && !empty($firstCat)) {
			$catpath=$firstCat." > ".$catpath;
		}
	}
	
	return $catpath;
}

    function ago($datefrom,$dateto=-1)
    {
        // Defaults and assume if 0 is passed in that
        // its an error rather than the epoch
   
        if($datefrom==0) { return "A long time ago"; }
        if($dateto==-1) { $dateto = time(); }
       
        // Make the entered date into Unix timestamp from MySQL datetime field

        $datefrom = strtotime($datefrom);
   
        // Calculate the difference in seconds betweeen
        // the two timestamps

        $difference = $dateto - $datefrom;

        // Based on the interval, determine the
        // number of units between the two dates
        // From this point on, you would be hard
        // pushed telling the difference between
        // this function and DateDiff. If the $datediff
        // returned is 1, be sure to return the singular
        // of the unit, e.g. 'day' rather 'days'
   
        switch(true)
        {
            // If difference is less than 60 seconds,
            // seconds is a good interval of choice
            case(strtotime('-1 min', $dateto) < $datefrom):
                $datediff = $difference;
                $res = ($datediff==1) ? $datediff.' second ago' : $datediff.' seconds ago';
                break;
            // If difference is between 60 seconds and
            // 60 minutes, minutes is a good interval
            case(strtotime('-1 hour', $dateto) < $datefrom):
                $datediff = floor($difference / 60);
                $res = ($datediff==1) ? $datediff.' minute ago' : $datediff.' minutes ago';
                break;
            // If difference is between 1 hour and 24 hours
            // hours is a good interval
            case(strtotime('-1 day', $dateto) < $datefrom):
                $datediff = floor($difference / 60 / 60);
                $res = ($datediff==1) ? $datediff.' hour ago' : $datediff.' hours ago';
                break;
            // If difference is between 1 day and 7 days
            // days is a good interval               
            case(strtotime('-1 week', $dateto) < $datefrom):
                $day_difference = 1;
                while (strtotime('-'.$day_difference.' day', $dateto) >= $datefrom)
                {
                    $day_difference++;
                }
               
                $datediff = $day_difference;
                $res = ($datediff==1) ? 'yesterday' : $datediff.' days ago';
                break;
            // If difference is between 1 week and 30 days
            // weeks is a good interval           
            case(strtotime('-1 month', $dateto) < $datefrom):
                $week_difference = 1;
                while (strtotime('-'.$week_difference.' week', $dateto) >= $datefrom)
                {
                    $week_difference++;
                }
               
                $datediff = $week_difference;
                $res = ($datediff==1) ? 'last week' : $datediff.' weeks ago';
                break;           
            // If difference is between 30 days and 365 days
            // months is a good interval, again, the same thing
            // applies, if the 29th February happens to exist
            // between your 2 dates, the function will return
            // the 'incorrect' value for a day
            case(strtotime('-1 year', $dateto) < $datefrom):
                $months_difference = 1;
                while (strtotime('-'.$months_difference.' month', $dateto) >= $datefrom)
                {
                    $months_difference++;
                }
               
                $datediff = $months_difference;
                $res = ($datediff==1) ? $datediff.' month ago' : $datediff.' months ago';

                break;
            // If difference is greater than or equal to 365
            // days, return year. This will be incorrect if
            // for example, you call the function on the 28th April
            // 2008 passing in 29th April 2007. It will return
            // 1 year ago when in actual fact (yawn!) not quite
            // a year has gone by
            case(strtotime('-1 year', $dateto) >= $datefrom):
                $year_difference = 1;
                while (strtotime('-'.$year_difference.' year', $dateto) >= $datefrom)
                {
                    $year_difference++;
                }
               
                $datediff = $year_difference;
                $res = ($datediff==1) ? $datediff.' year ago' : $datediff.' years ago';
                break;
               
        }
        return $res;
	}

$active_query=mysql_query("SELECT postID, A.title, why, description, price, postDate, repostDate, DATE_FORMAT(expDate, '%M %d, %Y at %h:%i %p') as expDate, forTitle, forGroup, D.dataID as SubID, D.dataName as SubCat, E.dataID as SubIDSub, E.dataName as SubCatSub, location, C.Title as servFrom, mainCat, catName, mem_userid, IFNULL(clickTotal,'0') as clickTotal2, IFNULL(ImpTotal,'0') as ImpTotal2, price2, delivery, keyword, tags, commision FROM market_Post A LEFT JOIN market_category on (mainCat=catID) LEFT JOIN market_category_for on (optionFor=forID) LEFT JOIN market_category_data D on (subCat=D.dataID) LEFT JOIN market_category_data E on (subCatsub=E.dataID) LEFT JOIN Geo_Countries C on (A.Country=C.CountryId) LEFT JOIN market_Post_click USING ( postID ) where mem_userid=$WUserID and postID=$postID limit 1",$link) or die(mysql_error());
$activeTotal = mysql_num_rows($active_query);

if($activeTotal>0) {
$photo_query=mysql_query("SELECT photoID, photoURL, photoThumb 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);
}

?>

<div id="top_panel" class="submenu">
	<?php include ("panel_top.php"); ?>
</div>
<?php if($photoTotal>0) {?>
<link rel="stylesheet" href="galleriffic.css" type="text/css" />
<script type="text/javascript" src="js/jquery.galleriffic.js"></script>
<?php } ?>
<script type="text/javascript">
			jQuery(document).ready(function($) {
				<?php if($photoTotal>0) {?>
				// We only want these styles applied when javascript is enabled
				$('div.navigation').css({'width' : '140px', 'float' : 'left'});
				$('div.photoPic').css('display', 'block');

				// Initially set opacity on thumbs and add
				var onMouseOutOpacity = 0.5;
				$('#thumbs ul.thumbs li').fadeTo('fast', onMouseOutOpacity).end();
				
				// Initialize Advanced Galleriffic Gallery
				var gallery = $('#thumbs').galleriffic({
					delay:                     2500,
					numThumbs:                 3,
					preloadAhead:              3,
					enableBottomPager:         false,
					maxPagesToShow:            1,
					imageContainerSel:         '#slideshow',
					controlsContainerSel:      '#controls',
					captionContainerSel:       '#caption',
					loadingContainerSel:       '#loading1',
					renderSSControls:          true,
					renderNavControls:         false,
					playLinkText:              '<span class="green_b">Play Slideshow</span> <img src="images/play.gif" border="0" align="absbottom" >',
					pauseLinkText:             '<span class="red_b">Pause Slideshow</span> <img src="images/stop.gif" border="0" align="absbottom" >',
					prevLinkText:              '&lsaquo; Previous Photo',
					nextLinkText:              'Next Photo &rsaquo;',
					autoStart:                 false,
					syncTransitions:           true,
					enableKeyboardNavigation:  false,
					defaultTransitionDuration: 900,
					onSlideChange:             function(prevIndex, nextIndex) {
						// 'this' refers to the gallery, which is an extension of $('#thumbs')
						this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('fast', 1.0);
					},
					onPageTransitionOut:       function(callback) {
						this.fadeTo('fast', 0.0, callback);
					},
					onPageTransitionIn:        function() {
						this.fadeTo('fast', 1.0);
					}
				});
				<?php } ?>

				/****************************************************************************************/

				$("#reply").click(function(){
					if ($(this).val()=="Please type in your message!")
					$(this).val('');
				});

				/****************************************************************************************/

			});

function submit_form (postID, userID, userName) {

	var comment = jQuery("#reply").val();
    var dataString = 'userID='+ userID + '&postID=' + postID + '&userName='+ userName + '&comment=' + comment + '&Submit=addMarketComment';
	
	if(comment=='')
     {
    jQuery("#reply").val("Please type in your message!");
     }
	else if(comment=='Please type in your message!')
     {
    jQuery("#reply").val("Please type in your message!");
     }
	else
	{
	jQuery("#load").html('<img src="images/loader1.gif">');
jQuery.ajax({
		type: "POST",
  url: "comments_action.php",
   data: dataString,
  cache: false,
  success: function(html){
 
   jQuery("#reply").val("");
	jQuery("#load").html('');
   jQuery("#CommentAll").prepend(html);
  }
 });
}
	}

function showmore(comment_id) {
	
	jQuery("#more"+comment_id).html('');
	jQuery("#Seemore"+comment_id).show();

	return false;
}

function deleteComment(comment_id, postID) {

    var dataString = 'Submit=deleteMarketComment&postID='+ postID + '&comment_id=' + comment_id;
//	 alert (dataString);
	
jQuery.ajax({
		type: "POST",
  url: "comments_action.php",
   data: dataString,
	dataType: 'json',
  cache: false,
  success: function(result){
//	 alert (result.status);
	if (result.status=="1") {
	jQuery("#contentBox"+comment_id).html(result.result);
	jQuery("#commentBox"+comment_id).fadeOut(500);
	}else {
	jQuery("#contentBox"+comment_id).prepend(result.result);
	}
  }
 });
	}
		</script>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
	<tr>
		<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="5" class="white_back_t_xb">
				<?php if($activeTotal>0) {
						$sql = mysql_fetch_object($active_query);
						$price = number_format(ceil($sql->price/$currencypoint),0);
						$price2 = number_format(ceil($sql->price2/$currencypoint),0);
						?>
				<tr>
					<td><div class="grey_12 blue_row_back solid_line_separator padding_5"> <?php echo getPath($sql->mainCat,$sql->catName,$sql->SubID,$sql->SubCat,$sql->SubCatSub); ?> </div></td>
				</tr>
				<tr>
					<td><div class="light_orang_h">
							<div style="width:10px; height:10px; float:left; margin-top:3px; margin-right:5px; background: #6600FF;"><img src="images/spacer.gif" width="10" height="10" /></div>
							<?=$sql->forTitle?>
						</div>
						<div class="right white_back padding_tb_5"><a class="button" title="All Listings" href="#ceditPost?tab=post&postID=<?=$sql->postID?>" onclick="javascript: callpage(this.href);" rel="subpage_link">Edit</a> <a class="button" href="javascript: void(null)" onclick="javascript: jQuery.facebox({ajax:'<?=$CONST_LINK_ROOT?>/postDeletepage.php?postID=<?=$sql->postID?>'}, 'Delete&nbsp;Post', 'deletePost'); return false;" rel="facebox">Delete</a></div>
						<div class="dot_line"><img src="images/spacer.gif" width="1" height="1" /></div>
						<div class="solid_line"><img src="images/spacer.gif" width="1" height="1" /></div></td>
				</tr>
				<tr>
					<td><table width="100%" border="0" cellpadding="10" cellspacing="0">
							<tr>
								<td><div id="marketContent">
										<p class="blue_20"><?php echo ucwords($sql->title);?></p>
										<?php if($photoTotal>0) {?>
										<!-- Start Advanced Gallery Html Containers -->
										<div id="gallery" class="photoPic">
											<div class="slideshow-container">
												<div id="loading1" class="loader"></div>
												<div id="slideshow" class="slideshow"></div>
											</div>
											<div id="caption" class="caption-container"></div>
										</div>
										<div id="thumbs" class="navigation">
											<div id="controls" class="controls"></div>
											<ul class="thumbs noscript">
												<?php	
				$urlArray=array();
				while ($sqlPhoto = mysql_fetch_object($photo_query) ) { 
				?>
												<li> <a class="thumb" href="<?=$sqlPhoto->photoURL?>"> <img src="<?=$sqlPhoto->photoThumb?>" border="0" /> </a>
													<!--															<div class="caption">
																<div class="image-desc">Description</div>
															</div>
-->
												</li>
												<?php } ?>
											</ul>
										</div>
										<!-- End Advanced Gallery Html Containers -->
										<div style="clear: both;"><img src="images/spacer.gif" height="10" /></div>
										<?php }?>
										<p>
										<div class="description">
											<?=html_entity_decode($sql->description,ENT_QUOTES)?>
										</div>
										</p>
										<div style="clear: both;"><img src="images/spacer.gif" height="10" /></div>
										<?php if(!empty($price)) {?>
										<p><span class='lightgrey'>Price<?php if ($sql->forGroup==2) {?>
													Budget
													<?php } ?>:</span> <img src="images/iconPA_o.gif" border="0" align="absmiddle" />
											<?=$price?> <?php if($sql->forGroup==2){?> <span class='lightgrey'>&nbsp;&nbsp;to&nbsp;&nbsp;</span> <img src="images/iconPA_o.gif" border="0" align="absmiddle" /><?=$price2?><?php } ?>
										</p>
										<?php }?>
										<?php if ($sql->forGroup==1){?>
										<p><span class='lightgrey'> Commision Offered: </span> <img src="images/iconPA_o.gif" border="0" align="absmiddle" />
											<?=number_format(abs(ceil(($price - ($price*7/100) - (1/$currencypoint)) * $sql->commision / 100)),0)?>
											(
											<?=$sql->commision?>
											%) </p>
										<?php }?>
										<?php if (($sql->forGroup==1) && (!empty($sql->servFrom))){?>
										<p><span class='lightgrey'> Service From: </span>
											<?=$sql->servFrom?>
										</p>
										<?php }?>
										<?php if(!empty($sql->location)) {?>
										<p><span class='lightgrey'>
											<?php if ($sql->forGroup==1) {?>
											Service Location:
											<?php } ?>
											<?php if ($sql->forGroup==2) {?>
											Delivery Location:
											<?php } ?>
											</span>
											<?=$sql->location?>
										</p>
										<?php }?>
										<?php if ($sql->forGroup==1) {?>
										<p><span class='lightgrey'> Delivery Details: </span>
											<?=$sql->delivery?>
										</p>
										<?php } ?>
										<p>
											<?php if (!empty($sql->repostDate)){?>
											<span class='lightgrey'>Reposted: </span>
											<?=ago($sql->repostDate)?>
											<?php } else { ?>
											<span class='lightgrey'>Posted: </span>
											<?=ago($sql->postDate)?>
											<?php } ?>
										</p>
										<p> <span class='lightgrey'>Clicks: </span>
											<?=$sql->clickTotal2?>
										</p>
										<p> <span class='lightgrey'>Impressions: </span>
											<?=$sql->ImpTotal2?>
										</p>
										<?php if (!empty($sql->tags)){?>
										<p><span class='lightgrey'> Searches Tags: </span>
											<?=$sql->tags?>
										</p>
										<?php } ?>
									</div></td>
							</tr>
							<tr>
								<td>&nbsp;</td>
							</tr>
							<tr>
								<td><div class="light_orang_h">
										<div style="width:10px; height:10px; float:left; margin-top:3px; margin-right:5px; background: #0000FF;"><img src="images/spacer.gif" width="10" height="10" /></div>
										Comment </div>
									<div class="dot_line"><img src="images/spacer.gif" width="1" height="1" /></div>
									<div class="solid_line"><img src="images/spacer.gif" width="1" height="1" /></div></td>
							</tr>
							<tr>
								<td><div id="commentLeft">
										<div id="comment">
											<div id="replyBox">
												<form name="commentForm" id="commentForm" action="javascript: submit_form(<?=$postID?>, <?=$WUserID?>, '<?=$WUsername?>')">
													<?php 
 $myhahaper_query=mysql_query("SELECT mem_userid, mem_username, mem_profileid FROM members LEFT JOIN adverts ON (mem_userid=adv_userid) where mem_userid='$WUserID' AND mem_confirm='1' AND adv_approved='1'",$link);
 $check_count=mysql_num_rows($myhahaper_query);
 if ($check_count > 0) { 
 $ret_pic = mysql_fetch_object($myhahaper_query);
if ($WUserID==$ret_pic->mem_userid) {
$photo_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$ret_pic->mem_userid' and pic_default='Y'") or die(mysql_error()); 
} else {
$photo_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$ret_pic->mem_userid' and pic_default='Y' and pic_private='N'") or die(mysql_error()); 
}
$pics_count = mysql_num_rows($photo_query);
$aPicture = mysql_fetch_object($photo_query);
if ($pics_count > 0) {
	$medium = $aPicture->pic_picture."_ps.".$aPicture->ext;
	$male1_picture1 = "$SITE_MAIN_WWW_ROOT/members/$ret_pic->mem_username/picture/$medium";
             }else{
$male1_picture1=$CONST_LINK_ROOT."/".$picture->GetProfilePicture($ret_pic->mem_userid);
}
if ($ret_pic->mem_profileid != null) { $male1_name1= $ret_pic->mem_profileid; }
else { $male1_name1= $ret_pic->mem_username; }
?>
													<div class="left w65_h58"><a href="<?=$CONST_LINK_ROOT?>/<?=$male1_name1?>"<?php /*?> onclick="javascript: callprofileInfo(<?=$ret_pic->mem_userid?>);"<?php */?>><img src="<?=$male1_picture1?>" border="0" title="Name:&nbsp;<?=ucwords($ret_pic->mem_username)?>" class="img_b_p3_white"/></a></div>
													<div align="right">
														<textarea name="reply" class="textarea" id="reply"></textarea>
														<span id="load"></span>
														<input name="comment" type="submit" value="Comment" class="button" />
													</div>
													<?php 
				} ?>
												</form>
											</div>
											<div id="CommentAll">
												<?php
						$comments_query=mysql_query("SELECT * FROM market_Post_comment WHERE postID = '$postID' and com_approved='1' ORDER BY com_time desc") or die(mysql_error());
						$comments_TOTAL = mysql_num_rows($comments_query);
						if ($comments_TOTAL >0) {
						while ($comments = mysql_fetch_object($comments_query) ) {
if ($WUserID==$comments->com_memid) {
$photo_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$comments->com_memid' and pic_default='Y'") or die(mysql_error()); 
} else {
$photo_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$comments->com_memid' and pic_default='Y' and pic_private='N'") or die(mysql_error()); 
}
$pics_count = mysql_num_rows($photo_query);
$aPicture = mysql_fetch_object($photo_query);
if ($pics_count > 0) {
	$medium = $aPicture->pic_picture."_ps.".$aPicture->ext;
	$male1_picture1 = "$SITE_MAIN_WWW_ROOT/members/$comments->com_mem_username/picture/$medium";
             }else{
$male1_picture1=$CONST_LINK_ROOT."/".$picture->GetProfilePicture($comments->com_memid);
}
						?>
												<div id="commentBox<?=$comments->comment_id?>" class="comment_reply">
													<div class="left w65_h58"><a href="<?=$CONST_LINK_ROOT?>/<?=$comments->com_mem_username?>"<?php /*?> onclick="javascript: callprofileInfo(<?=$comments->com_memid?>);"<?php */?>><img src="<?=$male1_picture1?>" border="0" title="Name:&nbsp;<?=ucwords($comments->com_mem_username)?>" class="img_b_p3_white"/></a></div>
													<div class="comment_reply_text">
														<?php if (($WUserID==$comments->com_memid) || ($WUserID==$sql->mem_userid)) {?>
														<div class="delete"><a href="javascript:;" onclick="javascript: deleteComment(<?=$comments->comment_id?>, <?=$postID?>);">x</a></div>
														<?php } ?>
														<span id="contentBox<?=$comments->comment_id?>">
														<?php 
				$short_msg_text=strip_tags(stripslashes(substr($comments->comment,0,300)));
				echo $short_msg_text;
				if (strlen (strip_tags($comments->comment))>300) echo "<span id=\"more".$comments->comment_id."\">... <a href=\"javascript:;\" onclick=\"javascript: showmore(".$comments->comment_id.");\">more</a></span><span id=\"Seemore".$comments->comment_id."\" class=\"none\">".strip_tags(stripslashes(substr($comments->comment,300)))."</span>";
				?>
														</span> </div>
												</div>
												<?php 
						}
						}
						?>
											</div>
										</div>
									</div></td>
							</tr>
						</table></td>
				</tr>
				<?php } else {?>
				<tr>
					<td><?php  print(NO_RECORDS_SECTION_NAME); ?>
						!</td>
				</tr>
				<?php }?>
				<tr>
					<td>&nbsp;</td>
				</tr>
				<tr>
					<td>&nbsp;</td>
				</tr>
			</table></td>
	</tr>
</table>
