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

$option_manager = new OptionManager();
$currencysym = $option_manager->GetValue('currency_symbol');
$currency = $option_manager->GetValue('currency');
$currencypoint = $option_manager->GetValue('currency_point');

$type = $_REQUEST["type"];

	switch ($type) {
	case "all"; 
		Search_all($type);
		break;
/*	case "page"; 
		Search_page($type);
		break;
*/	default; 
		SearchDefault();
		break;
	}

function Search_all ($type) {
include_once __INCLUDE_CLASS_PATH."/class.Picture.php";
$picture = new Picture();
global $SITE_MAIN_WWW_ROOT, $CONST_LINK_ROOT, $SITE_WWW_ROOT, $ConfirmSign, $currencypoint;

if(!empty($_REQUEST['q']) || ($_REQUEST['q']!= ' ')){
$q = $_REQUEST['q'];
}  else {
$q = '';
}
		$i = 2;
		$j = 0;

	if(isset($_REQUEST['start'])) {
		$start=($_REQUEST['start']-1)*10; 
		$i = $_REQUEST['start']+1;
		$j = $_REQUEST['start']-1;
	} else {	
		$start=0;
	}
?>

<div id="top_panel" class="submenu2">
	<?php include ("panel_top_main.php"); ?>
</div>
<script type="text/javascript">
jQuery.noConflict();


jQuery(document).ready(function(){
    jQuery("#search_media").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 = "<?=$CONST_LINK_ROOT?>/home.php#msearch?tab=search&" + str;
		return false;
    });
});

	 function paginate(type,id,value) {
	 	jQuery('#paginate_loading').show();
//	 	jQuery('#right_loading_m').show();

//	var str = "type=page&start=" + id + "&q=" + value;
	var str = "type=" + type + "&start=" + id + "&q=" + value;
		window.location = "<?=$CONST_LINK_ROOT?>/home.php#msearch?tab=search&" + str;
		return false;

/*   		jQuery.ajax({
   		type: "POST",
   		url: "search.php",
   		data: str,
   		success: function(result){
//			alert(result);
		jQuery('#paginate_loading').hide();	
//	 	jQuery('#right_loading_m').hide();
 		jQuery("#search_result").fadeIn('slow');
 		jQuery('#search_result').html(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">
				<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_media" id="search_media" style="padding:0; margin:0; border:0;">
							<table width="100%" border="0" cellspacing="0" cellpadding="5">
								<tr>
									<td align="center"><input name="q" type="text" class="grey_12_xb" id="q" value="<?=$q?>" size="40"/>
										<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><div id="search_result" class="result_box solid_line">
							<?php 
  if(!empty($q)){
  $all_post_query=mysql_query("SELECT postID FROM market_Post A LEFT JOIN market_category_for on (optionFor=forID) LEFT JOIN members USING (mem_userid) where (A.title like '%$q%' or why like '%$q%' or description like '%$q%') and approve=1 and expDate > now()") or die(mysql_error());
$all_post_TOTAL = mysql_num_rows($all_post_query);
$page = ceil($all_post_TOTAL/10);

$post_query=mysql_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, location as Location, why, description, mem_userid, mem_username, mem_profileid, 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) where (A.title like '%$q%' or why like '%$q%' or description like '%$q%') and approve=1 and expDate > now() limit $start, 10") or die(mysql_error());
$post_TOTAL = mysql_num_rows($post_query);

if ($post_TOTAL >0) {

  if ($j>0) {
  	if (($page >= $i) && ($i!=2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$j.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">PREVIOUS<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	if ($page < $i) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$j.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">PREVIOUS<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	}

	while ($sql = mysql_fetch_object($post_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") 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";

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">
												<?php if ($photoTotal>0) { ?>
												<span class="right ">
												<div class="image_w100h100"><a href="<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>"><img src="<?=$url?>" width="100" height="100" border="0" /></a></div>
												</span>
												<?php } ?>
												<a href="<?=$CONST_LINK_ROOT."/MKT".$sql->postID?>"><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 /*if(!empty($sql->why)) { echo ucwords($sql->why); } else*/ echo ucfirst($desc);?>
												</span>
												<span class="lightgrey_10"> 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>
												-
												<?=ago($sql->postDate)?>
												</span>
								<div class="clear"><img src="images/spacer.gif" /></div>
							</div>
							<?php
	}
	if (($page >= $i) && ($i!=2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$i.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">NEXT<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	if (($page >= $i) && ($i==2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$i.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">NEXT<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
} else {
die ("<strong>No results found for your query!</strong><br>Check your spelling or try another term.");
}
	} else {
	die ("<strong>Please enter a query!</strong>");
	}
	?>
						</div></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
				</tr>
			</table></td>
	</tr>
</table>
<?php
}

function Search_page ($type) {
include_once __INCLUDE_CLASS_PATH."/class.Picture.php";
$picture = new Picture();
global $SITE_MAIN_WWW_ROOT, $CONST_LINK_ROOT, $SITE_WWW_ROOT, $ConfirmSign;

if(!empty($_REQUEST['q']) || ($_REQUEST['q']!= ' ')){
$q = $_REQUEST['q'];
}  else {
$q = '';
}
		$i = 2;
		$j = 0;

	if(isset($_REQUEST['start'])) {
		$start=($_REQUEST['start']-1)*10; 
		$i = $_REQUEST['start']+1;
		$j = $_REQUEST['start']-1;
	} else {	
		$start=0;
	}
  if(!empty($q)){
  $all_post_query=mysql_query("SELECT postID FROM market_Post A LEFT JOIN market_category_for on (optionFor=forID) LEFT JOIN members USING (mem_userid) where (A.title like '%$q%' or why like '%$q%' or description like '%$q%') and approve=1 and expDate > now()") or die(mysql_error());
$all_post_TOTAL = mysql_num_rows($all_post_query);
$page = ceil($all_post_TOTAL/10);

$post_query=mysql_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, location as Location, why, description, mem_userid, mem_username 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) where (A.title like '%$q%' or why like '%$q%' or description like '%$q%') and approve=1 and expDate > now() limit $start, 10") or die(mysql_error());
$post_TOTAL = mysql_num_rows($post_query);

if ($post_TOTAL >0) {

  if ($j>0) {
  	if (($page >= $i) && ($i!=2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$j.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">PREVIOUS<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	if ($page < $i) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$j.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">PREVIOUS<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	}

	while ($sql = mysql_fetch_object($post_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") 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";

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);
}
?>
							<div class="content2">
												<?php if ($photoTotal>0) { ?>
												<span class="right ">
												<div class="image_w100h100"><a href="#mshowPost?tab=search&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>" onclick="javascript: callpage(this.href);"><img src="<?=$url?>" width="100" height="100" border="0" /></a></div>
												</span>
												<?php } ?>
												<a href="#mshowPost?tab=search&postID=<?=$sql->postID?>&uID=<?=$sql->mem_userid?>" onclick="javascript: callpage(this.href);"><strong>
												<?=$sql->forTitle?>
												: </strong><?php echo ucwords($sql->title); if(!empty($sql->price)) echo " for ".strtoupper($sql->price);?></a>
												<br />
												<span class="image_w50h50"><img src="<?=$male1_picture1?>" title="Name:&nbsp;<?=ucwords($sql->mem_username)?>"/></span> <span class="rightContent3">
												<span class="lightgrey_10">
												<?=ucwords($sql->Location)?>
												</span>
												<br />
												<?php /*if(!empty($sql->why)) { echo ucwords($sql->why); } else*/ echo ucfirst($desc);?>
												</span>
												<span class="lightgrey_10"> Posted by
												<?=ucwords($sql->mem_username)?>
												-
												<?=ago($sql->postDate)?>
												</span>
								<div class="clear"><img src="images/spacer.gif" /></div>
							</div>
							<?php
	}
	if (($page >= $i) && ($i!=2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$i.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">NEXT<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
	if (($page >= $i) && ($i==2)) {
	echo "<a href=\"javascript: void(null)\" onclick=\"paginate('".$type."',".$i.", '".$q."'); return false;\" ><div class=\"paging\" align=\"center\">NEXT<div id=\"paginate_loading\"><img src=\"images/spacer.gif\"></div></div></a>";
	}
} else {
die ("<strong>No results found for your query!</strong><br>Check your spelling or try another term.");
}
	} else {
	die ("<strong>Please enter a query!</strong>");
	}
	?>
<?php
}

function SearchDefault () {
global $SITE_MAIN_WWW_ROOT, $CONST_LINK_ROOT, $SITE_WWW_ROOT, $ConfirmSign;
?>
<div id="top_panel" class="submenu2">
	<?php include ("panel_top_main.php"); ?>
</div>
<script type="text/javascript">
jQuery.noConflict();


jQuery(document).ready(function(){
    jQuery("#search_media").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 = "<?=$CONST_LINK_ROOT?>/home.php#msearch?tab=search&" + str;
		return false;
    });
});

   </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_media" id="search_media" style="padding:0; margin:0; border:0;">
							<table width="100%" border="0" cellspacing="0" cellpadding="5">
								<tr>
									<td align="center"><input name="q" type="text" class="grey_12_xb" id="q" size="40"/>
										<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>&nbsp;</td>
				</tr>
			</table></td>
	</tr>
</table>
<?php
}

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

?>
