<?php
$wb_friendly_url = $_GET['shortName'];

// keep the map coordinates
$json_locations = array();

// Get Advert Categories array
$wb_fm_categs = array();
$q = "select * from wb_filters_mains where wb_uid='$wb_uid' and active='1'";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) > 0) {
	while ($row = mysql_fetch_assoc($r)) {
		$wb_fm_categs[$row['fm_uid']] = stripslashes($row['title']);
	}
}

$range = ( isset($wb_srch_rpp) && $wb_srch_rpp > 0 ) ? $wb_srch_rpp : 10;

if($range > 0) {
	$rel_page = 1;
	if(isset($_REQUEST['rel_page'])) {
		$rel_page = intval($_REQUEST['rel_page']);
	}
	
	$start = ($rel_page - 1) * $range;
}

$r = mysql_query($q_wb) or die("<strong>$q</strong>".mysql_error());
if($r && mysql_num_rows($r) > 0) {
    $count = 0;
    while ($line = mysql_fetch_assoc($r)) {
        $results[$count] = array();
        $results[$count]["order"] = 0;
        $results[$count]["categ_order"] = 0;
        $results[$count]["short_title_en"] = stripslashes($line["short_title_en"]);
        $results[$count]["advertisment_id"] = $line["advertisment_id"];
        $results[$count]["use_town_dir"] = false;
        $results[$count]["town_locations"] = array();

        $wb_search_params['wb_adverts'][] = $line['adv_code'];

        $max_order = 0;

        // Featured
        $query_categtop = "SELECT * FROM domain_advertisment WHERE category_top='yes' AND advertisment_id='{$line['advertisment_id']}' and catdom_id in (" . (implode(",", $catdoms)) . ")";
        $result_categtop = mysql_query($query_categtop) or die("<strong>$query_categtop</strong>" . mysql_error());
        if ($result_categtop && mysql_num_rows($result_categtop) > 0) {
            $max = 0;
            while ($row_categtop = mysql_fetch_assoc($result_categtop)) {
                if ($row_categtop['catdom_id'] == $domain_id) $max = 10;
                elseif ($max == 0) {
                    $max = 6;
                }

                $params = $row_categtop['params'];
                if ($params != "") {
                    $params = unserialize(base64_decode($params));
                    if (is_array($params) && count($params) > 0) {
                        $results[$count]["town_locations"] = $params;
                    }
                }

            }

            $max_order = ($max_order < $max) ? $max : $max_order;
        }

        // Non featured
        $query_categtop = "SELECT * FROM domain_advertisment WHERE active='yes' AND advertisment_id='{$line['advertisment_id']}' and catdom_id in (" . (implode(",", $catdoms)) . ")";

        $result_categtop = mysql_query($query_categtop) or die("<strong>$query_categtop</strong>" . mysql_error());
        if ($result_categtop && mysql_num_rows($result_categtop) > 0) {
            $max = 0;

            while ($row_categtop = mysql_fetch_assoc($result_categtop)) {
                if ($row_categtop['catdom_id'] == $domain_id) $max = 8;
                elseif ($max == 0) {
                    $max = 6;
                }

                $params = $row_categtop['params'];
                if ($params != "") {
                    $params = unserialize(base64_decode($params));
                    if (is_array($params) && count($params) > 0) {
                        $results[$count]["town_locations"] = $params;
                    }
                }

            }

            $max_order = ($max_order < $max) ? $max : $max_order;
        }

        // Get the main location

        $ql = "select l.adv_code, l.lat, l.lng, w.fm_uid from advertisment_locations l, wb_filters_adverts_categs w where l.adv_code='{$line['adv_code']}' and l.adv_code=w.adv_code and w.wb_uid='$wb_uid' and l.main_location='1';";
        $rl = @mysql_query($ql);
        if ($rl && mysql_num_rows($rl) > 0) {
            $rowl = mysql_fetch_assoc($rl);

            if (abs($rowl['lat']) - 0 > 0) {

                $json_locations [] = array(
                    "lat" => $rowl['lat'],
                    "lng" => $rowl['lng'],
                    "adv_code" => $rowl['adv_code'],
                    "title" => htmlentities(stripslashes($line['short_title_en'])),
                    "fm_uid" => $row['fm_uid'],
                    "fm_name" => isset($wb_fm_categs[$row['fm_uid']]) ? htmlentities($wb_fm_categs[$row['fm_uid']]) : ''
                );
            }


        }


        $results[$count]["order"] = $max_order;
        $results[$count]["categ_order"] = $max_order;

        $count++;
    }

    $num_results = $count;
    $order = array();
    $categ_order = array();
    $title_en = array();
    $advertisment_id = array();
    $town_locations = array();
    foreach ($results as $key => $row) {
        $order [$key] = $row['order'];
        $categ_order [$key] = intval($row['categ_order']);
        $title_en [$key] = $row['short_title_en'];
        $advertisment_id [$key] = $row['advertisment_id'];
    }

    array_multisort($categ_order, SORT_NUMERIC, SORT_DESC, $title_en, SORT_ASC, SORT_STRING, $results);


    $i = 0;
    foreach ($results as $key => $row) {
        $order[$i] = $row['order'];
        $categ_order[$i] = $row['categ_order'];
        $title_en[$i] = $row['short_title_en'];
        $advertisment_id[$i] = $row['advertisment_id'];
        $town_locations[$i] = $row['town_locations'];
        $i++;
    }


    // Show the MAP
    if (isset($module_map_search) && $module_map_search == 1) {
        require_once(dirname(__FILE__) . "/../wb_search_map/wb_search_map_default.php");
    }

    //echo '<pre>$categ_order  = ', var_export($categ_order, true), '</pre>';

    //echo "<hr>";
    if ($num_results > $start + $range) {
        $end = $start + $range;
    } else {
        $end = $num_results;
    }

    $click_count_paths = array();

    if ($range == 0) {
        $start = 0;
        $end = count($results);
    }

    $have_template = false;
    $template_file = dirname(__FILE__) . "/templates/witmpl_$wb_uid.tmpl.php";
    if (file_exists($template_file)) {
        $have_template = true;
    } else {
        $q = "select * from wb_categories_details where categ_uid='$wb_uid' and lang='en';";
        $r = @mysql_query($q);
        if ($r && mysql_num_rows($r) == 1) {
            $row = mysql_fetch_assoc($r);
            $wb_uid_title = stripslashes($row['title']);
            $tmpl_data = "<?php \r\n/********" . "\r\n" . $wb_uid_title . " | " . $wb_uid . "\r\n" . "*******/" . "\r\n" . "?>";
            $tmpl_data .= file_get_contents(dirname(__FILE__) . "/templates/witmpl_default.tmpl.php");

            $ftmpl = fopen($template_file, "w");
            fwrite($ftmpl, $tmpl_data);
            fclose($ftmpl);

            $have_template = true;
        }
        //copy(dirname(__FILE__). "/templates/witmpl_default.tmpl.php", dirname(__FILE__) . "/templates/witmpl_$wb_uid.tmpl.php");

    }

    $template_file_css = dirname(__FILE__) . "/templates_css/wb_search_results_" . $wb_uid . ".css";
    if (!file_exists($template_file_css)) {

        $q = "select * from wb_categories_details where categ_uid='$wb_uid' and lang='en';";
        $r = @mysql_query($q);
        if ($r && mysql_num_rows($r) == 1) {
            $row = mysql_fetch_assoc($r);
            $wb_uid_title = stripslashes($row['title']);
            $tmpl_data = "/********" . "\r\n" . $wb_uid_title . " | " . $wb_uid . "\r\n" . "*******/" . "\r\n";
            $tmpl_data .= file_get_contents(dirname(__FILE__) . "/templates_css/default.css");

            $ftmpl = fopen($template_file_css, "w");
            fwrite($ftmpl, $tmpl_data);
            fclose($ftmpl);
        }
        //copy(dirname(__FILE__). "/templates/witmpl_default.tmpl.php", dirname(__FILE__) . "/templates/witmpl_$wb_uid.tmpl.php");

    }


    if ($have_template) {
        if (file_exists(dirname(__FILE__) . "/templates_css/wb_search_results_$wb_uid.css")) {
            $optres['css'][] = $path . "amodules/wb_search_results/templates_css/wb_search_results_$wb_uid.css";
            //echo "<br>" . dirname(__FILE__) . "/templates_css/$wb_uid.css";
        } else {
            //echo "<br>" . dirname(__FILE__) . "/templates_css/wb_search_results_".$wb_uid . ".css not exist";
        }
    }


    //echo '<pre>', var_export($optres['css'], true), '</pre>';

    /*
    for($i=$start; $i<$end; $i++){
        $paying_advert = false;
        $query = "SELECT * FROM advertisment WHERE advertisment_id='{$advertisment_id[$i]}'";



        if(isset($_REQUEST['debug1'])) {
            echo "<br/>$i ) <strong>$query</strong>";
        }
        $result = mysql_query($query);
        if(mysql_num_rows($result)>0){
            if($have_template) {
                include($template_file);
            }

        }
    }
    */

    /*itemscope itemtype="http://schema.org/ItemList"*/
    ?>
    <div>
        <?php
        /*echo '<meta itemprop="numberOfItems" content="'.count($advertisment_id).'">';*/
        for ($advert_num = 0; $advert_num < count($advertisment_id); $advert_num++) {
            $paying_advert = false;

            $query = "SELECT * FROM advertisment WHERE advertisment_id='{$advertisment_id[$advert_num]}'";

            if (isset($_REQUEST['debug1'])) {
                echo "<br/>$advert_num ) <strong>$query</strong>";
            }
            $result = mysql_query($query);
            if ($result && mysql_num_rows($result) > 0) {
                if ($have_template) {
                    include($template_file);
                }

            }
        }
        ?>
    </div>
    <?php
	
	
	/*
	?>
	<table width="100%" border="0" cellpadding="0" cellspacing="0">
		<tr>
			<td><img src="<?php echo $path;?>images/navigation/spacer.gif" width="1" height="3"></td>
		</tr>
		<tr>
			<td align="center" class="small10">Results
				<?php
				
				
				if($num_results > $start + $range){
					$end = $start + $range;
				}
				else{
					$end = $num_results;
				}
				echo ($start+1), ' - ', $end, ' out of ', $num_results, '<br/>';
				
				$pagesrange=2;					  
				$pages = (($num_results/$range) - intval($num_results/$range) == 0) ? intval($num_results/$range) : (intval($num_results/$range) + 1);
				
				
				//echo '<pre>$pages = ' . $pages . '</pre>';
				//echo '<pre>$rel_page = ' . $rel_page . '</pre>';
				
				if($pages > 1) {
					if($rel_page == 1) {
						$rel_next_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-2.html';
					}
					
					if($rel_page == 2) {
						$rel_prev_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.html';
						
						if($pages > 2) {
							$rel_next_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-2.html';
						}
					}
					
					if($rel_page > 2) {
						$prv_rel = $rel_page - 1;
						if($pages > $rel_page) {
							$nxt_rel = $rel_page + 1;
							$rel_prev_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-' . $prv_rel .'.html';
							$rel_next_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-' . $nxt_rel .'.html';
						}
						elseif($pages == $rel_page) {
							$rel_prev_page = 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-' . $prv_rel .'.html';
						}
					}
					
				}
				
				$startmsg = '';
				$endmsg = '';
				
				if(($start/$range)<=$pagesrange){
						$startrange=0;
				}
				else{
					$startrange = $start/$range-$pagesrange;
					$prev = $rel_page - 1;
					if($prev == 1) {
						$startmsg = '<a href="http://'.$microdata_host.'/'.$wb_friendly_url.'.html" class="wb_page small10" rel="1">Previous</a>';
					}
					else {
						$startmsg = '<a href="http://'.$microdata_host.'/'.$wb_friendly_url.'.page-'.$prev.'.html" class="wb_page small10" rel="'.$prev.'">Previous</a>';
					}
					$startmsg .= ' <a href="http://'.$microdata_host.'/'.$wb_friendly_url.'.html" class="wb_page small10" rel="1">1</a> . . .  ';
				}
		
				if(($startrange+(2*$pagesrange)+1)>=$pages){
					$endrange = $pages;
				}
				else{
					$endrange=$startrange+(2*$pagesrange)+1;
					//$nex=$start+$range;
					$nex = $rel_page + 1;
					$endpage=ceil($pages);
					$end=floor($pages)*$range;
					$endmsg='  . . .  <a href="http://'.$microdata_host.'/'.$wb_friendly_url.'.page-'.($endpage).'.html" class="wb_page small10" rel="'.$endpage.'">'.$endpage.'</a>';
					$endmsg .= ' <a href="http://'.$microdata_host.'/'.$wb_friendly_url.'.page-'.($nex).'.html" class="wb_page small10" rel="'.$nex.'">Next</a>';
				}
		
				echo "<span class=\"small10\">$startmsg</span>";
				
				for ($noofpage = $startrange; $noofpage < $endrange; $noofpage++) {
					if ($start != $noofpage * $range){
						if($noofpage > 0) {
							?>
							<a href="<?php echo 'http://'.$microdata_host.'/'.$wb_friendly_url.'.page-'.($noofpage+1).'.html'; ?>" class="wb_page small10" rel="<?php echo ($noofpage+1); ?>">
							<?php
						}
						else {
							?>
							<a href="<?php echo 'http://'.$microdata_host.'/'.$wb_friendly_url.'.html'; ?>" class="wb_page small10" rel="1">
							<?php
						}
						echo ($noofpage+1), '</a>&nbsp;';
					}
					else {
						echo '&nbsp;<span class="current_page">' . ($noofpage+1), '</span>&nbsp;';
					}
				} 
				echo "<span class=\"small10\">$endmsg</span>";
				?>
			</td>
		</tr>
	</table>
	<?php
	*/
}