<?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'];
//$_SESSION['startPost'] = "new";
		
$active_query=mysql_query("SELECT postID, case when char_length(A.title) > 150 then concat(LEFT(A.title,150), '...') else A.title end as title, forTitle, forGroup, price, IFNULL(repostDate,postDate) as postDate, DATE_FORMAT(expDate, '%M %d, %Y') as expDateNew, why, description, IFNULL(clickTotal,'0') as clickTotal, IFNULL(ImpTotal,'0') as ImpTotal, mem_userid, mem_username, status, IF(expDate< now(),'Expired',NULL) AS expired, price2 FROM market_Post A LEFT JOIN market_category_for on (optionFor=forID) LEFT JOIN members USING (mem_userid) LEFT JOIN Geo_Countries C on (A.Country=C.CountryId) LEFT JOIN market_Post_click USING ( postID ) where mem_userid=$WUserID order by expDate desc",$link) or die(mysql_error());
$active_total = mysql_num_rows($active_query);

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

?>

<div id="top_panel" class="submenu">
	<?php include ("panel_top.php"); ?>
</div>
<script type="text/javascript" src="http://cdn.socialtwist.com/2010091044975-2/script.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
<?php if($_SESSION['startPost']=="new"){?>
$.facebox({ajax:'<?=$CONST_LINK_ROOT?>/postPop.php'}, 'Create&nbsp;Post', 'newPost');
<?php } ?>


 
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#999'; // Colour of default text

$('#postTitle').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'));
    }
  });
});

});


function checkTitle(urlJ){
	var title = document.getElementById("postTitle").value;
	if ((title=="Tell what you offer or wanted in the Marketplace") || (title.length==0)){
		jQuery.facebox('<div class="width_500 red_b" align="center">Please fill in title to create the post!</div>','Error');
		setTimeout(function() { parent.jQuery.facebox.close(); }, 2000);
	} else {

		jQuery('#loading').show();
		var str = 'Mode=storeTitle&title=' + title;
		jQuery.ajax({
   		type: "POST",
   		url: "postAction.php",
   		data: str,
			dataType: "json",
   		success: function(result){
		jQuery('#loading').hide();	
 		if(result.status == '1') { 
			callpage(urlJ);
		} else {
		jQuery.facebox('<div class="width_500 red_b" align="center">System error! Please try again later!</div>','Error');
		setTimeout(function() { parent.jQuery.facebox.close(); }, 2000);
		}
		}
 		});
	}
}
</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">
				<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="postTitle" type="text" class="lightgrey2 title" id="postTitle" title="Tell what you offer or wanted in the Marketplace" maxlength="150" />
						</div>
						<div class="left">
							<!--<a class="right buttonLarge" href="javascript: void(null)" onclick="javascript: jQuery.facebox({ajax:'<?=$CONST_LINK_ROOT?>/postPop.php'}, 'Create&nbsp;Post', 'newPost')">Insert Ads</a>-->
							<a class="margin_b_2 buttonLarge" href="javascript:;" onclick="checkTitle('caddPostOffer?tab=cover'); return false;">Offer<sup>+</sup></a> <a class="buttonLarge" href="javascript:;" onclick="checkTitle('caddPostWanted?tab=cover'); return false;">Wanted<sup>+</sup></a></div></td>
				</tr>
				<tr>
					<td><div class="light_orang_h">
							<div style="background-color:#FF0000; width:10px; height:10px; float:left; margin-top:3px; margin-right:5px;"><img src="images/spacer.gif" width="10" height="10" /></div>
							Listings</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><?php if($active_total>0) {?>
						<div id="search_result" class="result_box padding_5">
							<?php
					
						while ($sql = mysql_fetch_object($active_query) ) {
						$encode = mb_detect_encoding(strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")));
					if($encode=="UTF-8") { $desc = str_replace("&", "&amp;", mb_substr(strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")), 0, 90, "UTF-8")); if (strlen (strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")))>90) $desc.="...";
					} elseif ($encode=="ASCII") { $desc = str_replace("&", "&amp;", substr(strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")), 0, 150)); if (strlen (strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")))>150) $desc.="...";
					} else { $desc = str_replace("&", "&amp;", substr(strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")), 0, 150)); if (strlen (strip_tags(html_entity_decode($sql->description, ENT_QUOTES, "UTF-8")))>150) $desc.="...";
					} 
					
					$photo_query=mysql_query("SELECT photoThumb FROM market_PostPhoto where mem_userid=$sql->mem_userid and postID=$sql->postID order by photoID asc limit 1",$link) or die(mysql_error());
					$photoTotal = mysql_num_rows($photo_query);
					if($photoTotal>0) {
					$sqlPhoto = mysql_fetch_object($photo_query);
					if(!empty($sqlPhoto->photoThumb)) $url = $sqlPhoto->photoThumb; 
					else $url = "images/noimage.jpg";
					}
					else $url = "images/noimage.jpg";

						$comment_query = mysql_query("SELECT COUNT(comment_id) AS CommentTotal FROM market_Post_comment where postID=$sql->postID",$link) or die(mysql_error());
						$comment = mysql_fetch_object($comment_query);
						
$price = number_format(ceil($sql->price/$currencypoint),0);
$price2 = number_format(ceil($sql->price2/$currencypoint),0);

						?>
							<div class="content3 border-1px-light<?php if(!empty($sql->status) || !empty($sql->expired)) echo " redlight_row_back";?>" id="post<?=$sql->postID?>">
								<div class="sharec">
									<fb:like href="<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>" send="true" layout="box_count" show_faces="false"></fb:like>
									<a class="email" href="javascript:;" onclick="STTAFFUNC.cw(this, {id:'2010091044975-2', link: '<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>', title: '<?php echo ucwords($sql->title); if(!empty($price)) echo " for ".$price;?>' }); return false;">Email</a></div>
								<div class="content5">
									<div class="image_w100h1002"><a href="#cshowPost?tab=cover&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>" onclick="javascript: callpage(this.href);"><img src="<?=$url?>" border="0" /></a></div>
									<span class="rightContent5c"> <span class="left block red_10">
									<?php if(!empty($sql->status)) echo $sql->status; else echo $sql->expired; ?>
									</span> <span class="right block lightgrey_10">
									<?php if(!empty($sql->expired)) echo "<a href=\"javascript: void(null)\" onclick=\"javascript: jQuery.facebox({ajax:'$CONST_LINK_ROOT/postContinue.php?postID=$sql->postID'}, 'RePost', 'rePost'); return false;\" rel=\"facebox\">Repost </a>| "; ?>
									<a href="#ceditPost?tab=post&postID=<?=$sql->postID?>" onclick="javascript: callpage(this.href);">Edit </a> | <a href="javascript: void(null)" onclick="javascript: jQuery.facebox({ajax:'<?=$CONST_LINK_ROOT?>/postDelete.php?postID=<?=$sql->postID?>'}, 'Delete&nbsp;Post', 'deletePost'); return false;" rel="facebox">Delete</a></span> <span class="clear block"><strong>
									<?=$sql->forTitle?>
									:</strong> <a href="#cshowPost?tab=cover&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>" onclick="javascript: callpage(this.href);" class="blue_b"> <?php echo ucwords($sql->title); if(!empty($price)) echo " for <img src=\"images/iconPA_o.gif\" border=\"0\" align=\"absmiddle\" />".$price;?></a> <br />
									<span class="rightContent4">
									<?php echo ucfirst($desc);?>
									</span> <span class="lightgrey_10">
									<?=ago($sql->postDate)?>
									</span> </span></span>
									<div class="clear"><img src="images/spacer.gif" height="5" /></div>
									<span class="grey_10"> <span class="orangeBackp3">Clicks: <strong>
									<?=$sql->clickTotal?>
									</strong></span> <span class="orangeBackp3">Impressions: <strong>
									<?=$sql->ImpTotal?>
									</strong></span> <span class="orangeBackp3">Comments: <strong>
									<?=$comment->CommentTotal?>
									</strong></span> <span class="orangeBackp3">Expiration: <strong>
									<?=$sql->expDateNew?>
									</strong></span> <span class="orangeBackp3">Web Page: <strong>
									<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>
									</strong></span> </span> </div>
							</div>
							<?php } ?>
						</div>
						<?php } else {?>
						<?php  print(NO_RECORDS_SECTION_NAME); ?>
						!
						<?php } ?>
					</td>
				</tr>
				<tr>
					<td>&nbsp;</td>
				</tr>
			</table></td>
	</tr>
</table>
<div id="fb-root-cover"></div>
<script type="text/javascript">
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '132880206758943',
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true, // parse XFBML
          oauth: true
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root-cover').appendChild(e);
		  
      }());
</script>
<?php
unset($_SESSION['startPost']);
?>
