<?php
include("includes/site_info.php");
include('session_handler.inc');
global $SITE_MAIN_WWW_ROOT,$CONST_LINK_ROOT;

include_once __INCLUDE_CLASS_PATH."/class.Picture.php";
$picture = new Picture();

//print_r($_SERVER);

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

$WUserID = $_SESSION['Sess_UserId'];

/*$active_query=mysql_query("SELECT postID, case when char_length(A.title) > 250 then concat(LEFT(A.title,250), '...') else A.title end as title, A.title as Alltitle, forTitle, price, IFNULL(repostDate,postDate) as postDate,  CONCAT_WS(', ', NULLIF(location,''), C.Title) as Location, DATE_FORMAT(expDate, '%M %d, %Y') as expDate, case when char_length(why) > 250 then concat(LEFT(why,250), '...') else why end as why, case when char_length(description) > 250 then concat(LEFT(description,250), '...') else description end as description, IFNULL(clickTotal,'0') as clickTotal2, IFNULL(ImpTotal,'0') as ImpTotal2, mem_userid, mem_username, mem_profileid, status, IF(expDate< now(),'Expired',NULL) AS expired, IFNULL(E.dataName,D.dataName) as Category 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 ) LEFT JOIN market_category_data D on (subCat=D.dataID) LEFT JOIN market_category_data E on (subCatsub=E.dataID) where approve=1 and expDate > now() order by ImpTotal desc, clickTotal desc limit 0,10") or die(mysql_error());
*/$active_query=mysql_query("SELECT postID, case when char_length(A.title) > 250 then concat(LEFT(A.title,250), '...') else A.title end as title, A.title as Alltitle, forTitle, price, IFNULL(repostDate,postDate) as postDate,  CONCAT_WS(', ', NULLIF(location,''), C.Title) as Location, DATE_FORMAT(expDate, '%M %d, %Y') as expDate, case when char_length(description) > 250 then concat(LEFT(description,250), '...') else description end as description, IFNULL(clickTotal,'0') as clickTotal2, IFNULL(ImpTotal,'0') as ImpTotal2, mem_userid, mem_username, mem_profileid, status, IF(expDate< now(),'Expired',NULL) AS expired, IFNULL(E.dataName,D.dataName) as Category 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 ) LEFT JOIN market_category_data D on (subCat=D.dataID) LEFT JOIN market_category_data E on (subCatsub=E.dataID) where approve=1 and expDate > now() order by ImpTotal desc, clickTotal desc limit 0,10") or die(mysql_error());
$active_total = mysql_num_rows($active_query);

$myhahaper_query=mysql_query("SELECT mem_userid FROM my_friends LEFT JOIN members ON (friend_uid=mem_userid) WHERE uid='$WUserID' and approved='1'") or die(mysql_error());
$myhahaper_TOTAL = mysql_num_rows($myhahaper_query);
if( $myhahaper_TOTAL > 0) {
$friends[] = $WUserID;
while ($hahaper_pic = mysql_fetch_object($myhahaper_query)) {
$friends[] = $hahaper_pic->mem_userid;
}
$friends = implode(',', $friends);

$activeS_query=mysql_query("SELECT postID 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 ) LEFT JOIN market_category_data D on (subCat=D.dataID) LEFT JOIN market_category_data E on (subCatsub=E.dataID) where approve=1 and expDate > now() and mem_userid in ($friends) order by expDate desc") or die(mysql_error());
$activeS_total = mysql_num_rows($active_query);

$activeM_query=mysql_query("SELECT postID 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 ) LEFT JOIN market_category_data D on (subCat=D.dataID) LEFT JOIN market_category_data E on (subCatsub=E.dataID) where approve=1 and expDate > now() and mem_userid not in ($friends) order by expDate desc") or die(mysql_error());
$activeM_total = mysql_num_rows($activeM_query);
}

?>

<div id="top_panel" class="submenu">
	<?php include ("panel_top_main.php"); ?>
</div>
<script type="text/javascript" src="http://cdn.socialtwist.com/2010091044975-2/script.js"></script>
<script type="text/javascript">
jQuery.noConflict();

jQuery(document).ready(function($){
$('#loading').show();
$("#showContent").load("summaryAction.php", {mode: "hotPost"}, function(){;
$('#loading').hide();	
});
});


jQuery(".staticMenu").ready(function($) {
	$(".staticMenu dt a").click(function() {
		$(this).parents(".staticMenu").find("ul").toggle();
		$(".staticMenu dt a").not($(this)).removeClass("selected");
		if($(this).parents(".staticMenu").find("ul").css("display") == "none"){
			$(this).removeClass("selected");
		}else{
			$(this).addClass("selected");
		}
	});

	$(".staticMenu dd ul li a").click(function() {
		var text = $(this).html();
		$(".staticMenu dt a span").html(text);
		$(".staticMenu dd ul").hide();
		$(".staticMenu dt a").removeClass("selected");
		$(".staticMenu dd ul li a").not($(this)).removeClass("selected");
		$(this).addClass("selected");
	}); 

	$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("staticMenu")){
			$(".staticMenu dd ul").hide();
			$(".staticMenu dt a").removeClass("selected");
		}

	});
});

		var fetching = false;	
	
		function last_msg_funtion() 
		{ 
		   fetching = true;
			var value = jQuery("#search_result").attr("rel");
         var ID = jQuery(".content4:last").attr("id");
			jQuery('#paginate_loading').show();
			jQuery.post("summaryAction.php?mode="+value+"&lastID="+ID,
			
			function(data){
				if (data == "There are no more items to show at the moment") {
				jQuery('div#loadMore').empty();
				jQuery('div#noMore').show();
				jQuery('div#noMore').html(data);
				} 
				else if (data != "") {
				jQuery(".content4:last").after(data);			
				fetching = false;
				} 
				jQuery('#paginate_loading').hide();	
			});
		};  
		
		jQuery(window).scroll(function(){
			if  (!fetching && (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height())){
			   last_msg_funtion();
			}
		}); 
		
function hidePost(itemID) {

	jQuery("#"+itemID).fadeOut(500);
}
		
  </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="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>
							Popular by </div>
						<div class="right"><dl class="staticMenu">
                           <dt><a href="javascript:void(null)" onclick="return false;"><span>Hot Post</span> <img src="images/arrow_down.gif" border="0" align="baseline" /></a></dt>
                             <dd>
                                    <ul class="mainMenuSub">
                                        <li><a href="javascript:void(null)" onclick="javascript: callboxBottom('hotPost');">Hot Post</a></li>
                                        <li><a href="javascript:void(null)" onclick="javascript: callboxBottom('recentPost');">Recent Post</a></li>
                                        <?php if($activeS_total>0){ ?><li><a href="javascript:void(null)" onclick="javascript: callboxBottom('social');">Your Social Network</a></li><?php } ?>
                                        <?php if($activeM_total>0) {?><li><a href="javascript:void(null)" onclick="javascript: callboxBottom('marketer');">Marketers</a></li><?php } ?>
                                    </ul>
                             </dd>
                       </dl></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="showContent"><?php if($active_total>0) {?>
<div id="search_result" class="result_box padding_5" rel="hotPostLoad">
	<?php
					$i=0;
					while ($sql = mysql_fetch_object($active_query) ) {
	$i++;
					$photo_query=mysql_query("SELECT photoMed FROM market_PostPhoto where mem_userid=$sql->mem_userid and postID=$sql->postID order by photoID asc limit 1") or die(mysql_error());
					$photoTotal = mysql_num_rows($photo_query);
					if($photoTotal>0) {
					$sqlPhoto = mysql_fetch_object($photo_query);
					if(!empty($sqlPhoto->photoMed)) $url = $sqlPhoto->photoMed; 
					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") or die(mysql_error());
						$comment = mysql_fetch_object($comment_query);
						
if ($WUserID==$sql->mem_userid) {
$pic_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$sql->mem_userid' and pic_default='Y'") or die(mysql_error()); 
} else {
$pic_query=mysql_query("SELECT * FROM pictures WHERE pic_userid = '$sql->mem_userid' and pic_default='Y' and pic_private='N'") or die(mysql_error()); 
}
$pics_count = mysql_num_rows($pic_query);
$aPicture = mysql_fetch_object($pic_query);
if ($pics_count > 0) {
	$medium = $aPicture->pic_picture."_ps.".$aPicture->ext;
	$male1_picture1 = "$SITE_MAIN_WWW_ROOT/members/$sql->mem_username/picture/$medium";
             }else{
$male1_picture1=$CONST_LINK_ROOT."/".$picture->GetProfilePicture($sql->mem_userid);
}
if ($sql->mem_profileid != null) { $male1_name1= $sql->mem_profileid; }
else { $male1_name1= $sql->mem_username; }
						?>
	<div class="content4 border-1px-light<?php if(!empty($sql->status) || !empty($sql->expired)) echo " redlight_row_back";?>" id="<?=$i?>_post<?=$sql->postID?>">
<div class="delete"><a href="javascript:;" onclick="javascript:hidePost('<?=$i?>_post<?=$sql->postID?>');">x</a></div>
<div class="share"><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($sql->price)) echo " for ".strtoupper($sql->price);?>' }); return false;">Email</a></div>
		<div class="content5">
		<div class="image_w100h1003"><a href="<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>" onclick="javascript: jQuery.facebox({ajax:'<?=$CONST_LINK_ROOT?>/mshowlistPop.php?tab=categories&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>'}, '<?=$sql->forTitle?>', 'hotpost'); return false;"><img src="<?=$url?>" width="170" height="170" border="0" /></a></div>
		<span class="rightContent5"><strong>
		<?=$sql->forTitle?>
		:</strong> <a href="<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>" onclick="javascript: jQuery.facebox({ajax:'<?=$CONST_LINK_ROOT?>/mshowlistPop.php?tab=categories&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>'}, '<?=$sql->forTitle?>', 'hotpost'); return false;" class="blue_b"> <?php echo ucwords($sql->title); if(!empty($sql->price)) echo " for ".strtoupper($sql->price);?></a> <br />
		<span class="rightContent6">
		<?php /*if(!empty($sql->why)) { echo ucwords($sql->why); } else*/ echo ucfirst($sql->description);?>
		</span> </span>
		<span class="image_w50h50"><a href="<?=$CONST_LINK_ROOT?>/<?=$male1_name1?>"><img src="<?=$male1_picture1?>" title="Name:&nbsp;<?=ucwords($sql->mem_username)?>"/></a></span><span class="rightContent3 lightgrey_10">
		<span class='grey_10'><?=$sql->Category?></span><br />
		<?=ucwords($sql->Location)?><div class="clear"><img src="images/spacer.gif" height="5" /></div><span class="lightgrey_10">
		<a href="<?=$CONST_LINK_ROOT?>/<?=$male1_name1?>"><span class="lightgrey_10"><?=ucwords($sql->mem_username)?></span></a>
		-
		<?=ago($sql->postDate)?>
		</span>
		</span>
		
		<div class="clear"><img src="images/spacer.gif" height="3" /></div>
		<span class="grey_10"> <span class="orangeBackp3">Clicks: <strong>
		<?=$sql->clickTotal2?>
		</strong></span> <span class="orangeBackp3">Impressions: <strong>
		<?=$sql->ImpTotal2?>
		</strong></span> <span class="orangeBackp3">Comments: <strong>
		<?=$comment->CommentTotal?>
		</strong></span> <span class="orangeBackp3">Expiration: <strong>
		<?=$sql->expDate?>
		</strong></span> </span> 
		</div>
		</div>
	<?php 
	} ?>
<div class="clear"><img src="images/spacer.gif" /></div>
<?php if ($active_total==10){?>
<div id="loadMore"><a href="javascript: void(null)" onclick="javascript: last_msg_funtion(); return false;" ><div class="paging" align="center">NEXT<div id="paginate_loading"><img src="images/spacer.gif"></div></div></a></div>
<div id="noMore" align="center"><img src="images/spacer.gif" /></div>
<?php } else {?>
<div id="noMore" align="center">There are no more items to show at the moment</div>
<?php } ?>
</div>
<?php
						} else {
						 print(NO_RECORDS_SECTION_NAME."!"); 
						 }?>
</div></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>
