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

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

$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'];

if (!empty($_REQUEST["catID"]) && $_REQUEST["catID"]!=0) {
$catID = $_REQUEST["catID"];
} else {
$catID = 0;
}

if (!empty($_REQUEST["dataID"]) && $_REQUEST["dataID"]!=0) {
$parent = $_REQUEST["dataID"];
} else {
$parent = 0;
}

if (!empty($_REQUEST["SubdataID"]) && $_REQUEST["SubdataID"]!=0) {
$Subparent = $_REQUEST["SubdataID"];
} else {
$Subparent = 0;
}

function getPath ($firstID,$secID,$thirdID){
	$catpath="";
	if ($thirdID >0 && $secID > 0) {
	$catName=mysql_query("select dataName as MainCat from market_category_data where dataID=$secID limit 1");
	$catNameTotal = mysql_num_rows($catName);
	if ($catNameTotal > 0) {
		$row=mysql_fetch_object($catName);
		$catpath="<a href=\"#mlistings?tab=categories&catID=$firstID&dataID=$secID\" class=\"blue_b\" onclick=\"javascript: callpage(this.href);\">".$row->MainCat."</a> > ";

		if ($firstID >1) {
		$catName2=mysql_query("select catName as MainCat from market_category where catID=$firstID limit 1");
		$catNameTotal2 = mysql_num_rows($catName2);
		if ($catNameTotal2 > 0) {
			$row2=mysql_fetch_object($catName2);
			$catpath="<a href=\"#mlistings?tab=categories&catID=$firstID\" class=\"blue_b\" onclick=\"javascript: callpage(this.href);\">".$row2->MainCat."</a> > ".$catpath;
		}
		}
	}
	}
	
	if ($thirdID==0 && $secID > 0) {
		if ($firstID >1) {
		$catName2=mysql_query("select catName as MainCat from market_category where catID=$firstID limit 1");
		$catNameTotal2 = mysql_num_rows($catName2);
		if ($catNameTotal2 > 0) {
			$row2=mysql_fetch_object($catName2);
			$catpath="<a href=\"#mlistings?tab=categories&catID=$firstID\" class=\"blue_b\" onclick=\"javascript: callpage(this.href);\">".$row2->MainCat."</a> > ".$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;
	}


$redirect = 0;
if ($catID==1) {
	if ($Subparent>0) {
	$catName=mysql_query("select dataName as MainCat from market_category_data where catID=$catID and dataID=$Subparent limit 1");
	$catNameTotal = mysql_num_rows($catName);
	} else {
	$catName=mysql_query("select dataName as MainCat from market_category_data where catID=$catID and dataID=$parent limit 1");
	$catNameTotal = mysql_num_rows($catName);
	} 
	$redirect = $catNameTotal;
} elseif ($catID>1) {
	if ($Subparent>0) {
	$catName=mysql_query("select dataName as MainCat from market_category_data where catID=$catID and dataID=$Subparent limit 1");
	$catNameTotal = mysql_num_rows($catName);
	} elseif ($parent>0) {
	$catName=mysql_query("select dataName as MainCat from market_category_data where catID=$catID and dataID=$parent limit 1");
	$catNameTotal = mysql_num_rows($catName);
	} else {
	$catName=mysql_query("select catName as MainCat from market_category where catID=$catID limit 1");
	$catNameTotal = mysql_num_rows($catName);
	}
	$redirect = $catNameTotal;
} elseif ($catID==0) {
	$redirect = 1;
} else {
echo "<script>location.href='" . $CONST_LINK_ROOT . "/home.php#mcategories'</script>"; 
die;
}

if ($redirect==0) {
echo "<script>location.href='" . $CONST_LINK_ROOT . "/home.php#mcategories'</script>"; 
die;
}

if ($catID==0) {
$sql=mysql_query("select dataID, dataName from market_category_data where catID=1 and parent=0 order by dataName asc");
$sqlTotal = mysql_num_rows($sql);
} else if ($Subparent>0) {
$sql=mysql_query("select dataID, dataName from market_category_data where catID=$catID and parent=$Subparent order by dataName asc");
$sqlTotal = mysql_num_rows($sql);
} else if ($parent>=0) {
$sql=mysql_query("select dataID, dataName from market_category_data where catID=$catID and parent=$parent order by dataName asc");
$sqlTotal = mysql_num_rows($sql);
} 

$query="SELECT postID, case when char_length(A.title) > 100 then concat(LEFT(A.title,100), '...') else A.title end as title, forTitle, price, postDate, repostDate, location as Location, why, description, mem_userid, mem_username, mem_profileid, DATE_FORMAT(expDate, '%M %d, %Y') as expDateShow, IFNULL(clickTotal,'0') as clickTotal2, IFNULL(ImpTotal,'0') as ImpTotal2, price2, commision 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 approve=1 and expDate > now()";

if ($catID==0) {
$query.=" and mainCat=1";
//echo "1";
} elseif ($Subparent==0 && $parent==0) {
$query.=" and mainCat=$catID";
//echo "2";
} elseif ($Subparent==0) {
$query.=" and mainCat=$catID and subCat=$parent";
//echo "3";
} else {
$query.=" and mainCat=$catID and subCat=$parent and subCatsub=$Subparent";
//echo "4";
}
$query.=" order by expDate desc";
$active_query=mysql_query($query,$link) or die(mysql_error());
$activeTotal = mysql_num_rows($active_query);

?>

<div id="top_panel" class="submenu2">
	<?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(){
    jQuery("#search_post").submit(function(){
	 	jQuery('#loading').show();
//	 	jQuery('#right_loading_m').show();
		
		var q = jQuery("#q").val();
		
		q=jQuery.trim(q);
		
		jQuery("#q").val(q);

		var str = jQuery(this).serialize();
	
		window.location.href = "<?=$CONST_LINK_ROOT?>/home.php#msearch?tab=search&" + str;
		return false;
    });
});

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>
							Search</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><form name="search_post" id="search_post" style="padding:0; margin:0; border:0;">
							<table width="100%" border="0" cellspacing="0" cellpadding="5">
								<tr>
									<td align="center"><input type="text" size="40" name="q" id="q" class="grey_12_xb"/>
										<input name="type" type="hidden" id="type" value="all" />
										<input name="init" type="submit" class="button" id="init" value="Search"/></td>
								</tr>
							</table>
						</form></td>
				</tr>
				<tr>
					<td><table width="100%" border="0" cellspacing="0" cellpadding="0">
							<tr>
								<?php if($sqlTotal>0) {?>
								<td valign="top"><div class="mainCatLeft">
										<div class="grey_style_back2 margin_b_5">Sub Categories</div>
										<?php
					while($row=mysql_fetch_array($sql))
					{
					$id=$row['dataID'];
					$data=$row['dataName'];
					if ($catID==0) {
					$countQuery=mysql_query("select mainCat from market_Post where approve=1 and expDate > now() and subCat=$id");
					$countTotal = mysql_num_rows($countQuery);
					echo "<span class=\"main\">&diams; <a href=\"#mlistings?tab=categories&catID=1&dataID=$id\" onclick=\"javascript: callpage(this.href);\">".$data."&nbsp;<span class=\"orange_12\">($countTotal)</span></a></span>";
					} elseif ($parent > 0) {
					$countQuery=mysql_query("select mainCat from market_Post where approve=1 and expDate > now() and subCatsub=$id");
					$countTotal = mysql_num_rows($countQuery);
					echo "<span class=\"main\">&diams; <a href=\"#mlistings?tab=categories&catID=$catID&dataID=$parent&SubdataID=$id\" onclick=\"javascript: callpage(this.href);\">".$data."&nbsp;<span class=\"orange_12\">($countTotal)</span></a></span>";
					} else {
					$countQuery=mysql_query("select mainCat from market_Post where approve=1 and expDate > now() and subCat=$id");
					$countTotal = mysql_num_rows($countQuery);
					echo "<span class=\"main\">&diams; <a href=\"#mlistings?tab=categories&catID=$catID&dataID=$id\" onclick=\"javascript: callpage(this.href);\">".$data."&nbsp;<span class=\"orange_12\">($countTotal)</span></a></span>";
					}
					}
					?>
									</div></td>
								<?php } ?>
								<td width="100%" valign="top"><div class="padding_lr_5 style_left">
										<div class="light_orang_h">
											<div style="background-color:#FF00FF; width:10px; height:10px; float:left; margin-top:3px; margin-right:5px;"><img src="images/spacer.gif" width="10" height="10" /></div>
											<?php echo getPath($catID,$parent,$Subparent); if ($catNameTotal > 0) {$row=mysql_fetch_object($catName); echo $row->MainCat; } else echo "Stuff"; ?></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>
									</div>
									<div class="clear"><img src="images/spacer.gif" />
										<?php if($activeTotal>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 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") 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; }

$price = number_format(ceil($sql->price/$currencypoint),0);
$price2 = number_format(ceil($sql->price2/$currencypoint),0);
					?>
											<div class="content2" id="item<?=$sql->postID?>"><div class="delete"><a href="javascript:;" onclick="javascript:hidePost('item<?=$sql->postID?>');" title="Hide the item">x</a></div>
												<span 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></span>
												<?php if ($photoTotal>0) { ?>
												<span class="right ">
												<div class="image_w100h100"><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="100" height="100" border="0" /></a></div>
												
												</span>
												<?php } ?>
												<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;"><strong>
												<?=$sql->forTitle?>
												: </strong><?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="image_w50h50"><a href="<?=$CONST_LINK_ROOT?>/<?=$male1_name1?>" <?php /*?>onclick="javascript: callprofileInfo(<?=$sql->mem_userid?>);"<?php */?>><img src="<?=$male1_picture1?>" title="Name:&nbsp;<?=ucwords($sql->mem_username)?>"/></a></span> <span class="rightContent3"> <span class="lightgrey_10">
												<?=ucwords($sql->Location)?>
												</span> <br />
												<?php echo ucfirst($desc);?>
												</span> <span class="lightgrey_10">
												<?php if (!empty($sql->repostDate)) echo "Reposted by"; else echo "Posted by";?>
												<a href="<?=$CONST_LINK_ROOT?>/<?=$male1_name1?>" <?php /*?>onclick="javascript: callprofileInfo(<?=$sql->mem_userid?>);"<?php */?>><span class="lightgrey_10"><?=ucwords($sql->mem_username)?></span></a>
												-
												<?php if (!empty($sql->repostDate)) echo ago($sql->repostDate); else echo ago($sql->postDate);?>
												</span><br /><br />
												<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->expDateShow?>
												</strong></span> <span class="orangeBackp3 clear">Promo Link: <strong><?=$CONST_LINK_ROOT."/MKT".$sql->postID?>
		</strong></span> </span>
												<div class="clear"><img src="images/spacer.gif" /></div>
											</div>
											<?php } ?>
										</div>
										<?php } else {?>
										<?php  print(NO_RECORDS_SECTION_NAME); ?>
										!
										<?php } ?>
									</div></td>
							</tr>
						</table></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
				</tr>
			</table></td>
	</tr>
</table>
<div id="fb-root-showall"></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-showall').appendChild(e);
		  
      }());
</script>
