<?php
/**
 * YellowBook Feed Parser 
 * Yannick 3/31/10
 * Version 2.1
 *
 * @Array   All parameter should be passed in an array
 * Array[KEY]=>[VALUE]
 */
ini_set("display_errors",0);
//require_once ("lib/php/feed/yelp.class.php");

require_once ("lib/php/feed/yelp.class.php");
require_once ("lib/php/feed/local.php");
require_once ("lib/php/feed/localBizDB.php");

class lib_YBMemcache extends Memcache {
	static private $instance = null;
	static private $port = 11211;
	static function mYBGet($ServerArray = array("192.168.30.32")) {
		if (self::$instance == null) {
			self::$instance = new Memcache;
			foreach  ($ServerArray as $Server)
				self::$instance->addServer($Server, self::$port);
		}
		return self::$instance;
	}
}
	
function YB_ConnectToMasterLP()
{
	$mysql_host = "192.168.30.115";
	$mysql_user = "c3slave";
	$mysql_password = "RstG496u*#rky2";
	$mysql_db = "local_pages";
	$dbd = mysql_connect ($mysql_host, $mysql_user, $mysql_password );
	@mysql_select_db ($mysql_db, $dbd);
	return $dbd; 
}

function YB_ConnectToSlaveLP()
{	return false;
	if(stristr($_SERVER['SERVER_ADDR'], '192.168.50.')) {
		$mysql_host = "64.74.172.199";
	} else {
		$mysql_host = "64.74.172.199"; 
	}
	$mysql_user = "c3slave";
	$mysql_password = "RstG496urky2";
	$mysql_db = "local_pages";
	$dbd = mysql_connect ($mysql_host, $mysql_user, $mysql_password );
	@mysql_select_db ($mysql_db, $dbd);
	return $dbd; 
}
		
/**
 * With timeout 10 milli sec
 * @param array $CurlData
 */
function async_curl_get_contents($CurlData)
{ 
	##### FETCH INPUT #####
	if (is_array($CurlData))
		$URL = $CurlData['url'];
	else
		$URL = $CurlData;	
			
	###### INIT ############ 
	$ch = curl_init($URL);
	###### CURL & OPTION #####
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 5);	//5 milliseconds to just make the req and return
	curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5); //5 milliseconds to just make the req and return
	curl_setopt($ch, CURLOPT_USERPWD, $CurlData['login']);
	curl_setopt($ch, CURLOPT_USERAGENT, $CurlData['ua']);
	if($CurlData['Authorization'])
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CurlData['Authorization'])); 
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

/***** USAGE ****** 
$data = array(	"what" => urlencode($search),
				"where" => urlencode($place),				  					
				"clientIp" => $ipaddress,				
				"browserAgent" => $ua,				  					
				"pageNumber" => $Page,	
				"visitorId" => session_id(),	
				"sessionId" => session_id(),	
				"sort"		=> $sort,
			  );
*/

function YB_place2latlon_new($place,$dbd){

	if (   strlen($place) == 5 && is_number($place)){
			
		 	return (zip2latlon($place, $dbd));
	
	} elseif ((strlen($place)==3) && is_number($place)){
	
			return(area2latlon($place, $dbd));
	}

	$locationarray = array();
	$locationarray = explode(",",$place);
	$count = count($locationarray);
	
	if ($count >= 2){
		$city = trim($locationarray[$count-2]);
		$state = trim($locationarray[$count-1]);
	} else {
		$city = trim($locationarray[$count-1]);
	}

	if ($state){
		 $query = "select zipcode, lat,lon,state_abbr,city_name from zip_codes where city_name like '$city' and (state_abbr like '$state' or state_name like '$state') limit 1";
	} else {
		 $query = "select zipcode, lat,lon,state_abbr,city_name from zip_codes where city_name like '$city' limit 1";		
	}
	
	$result = mysql_query($query,$dbd);
	$row=mysql_fetch_assoc($result);

	return $row;
}

/**********************************
///////latitude to distance ///////
**********************************/
function YB_latmin($latitude,$distance = 10){

	$latmin = ($latitude - $distance/69.1);
	return $latmin;
}
/**********************************
///////latitude to distance ///////
**********************************/
function YB_latmax($latitude,$distance = 10){

	$latmax = ($latitude + $distance/69.1);
	return $latmax;
}
/***********************************
///////longitude to distance ///////
**********************************/
function YB_lonmin($longitude,$distance = 10){
	
	$lonmin = ($longitude - $distance/53.0 );
	return $lonmin;
}
/***********************************
///////longitude to distance ///////
**********************************/
function YB_lonmax($longitude,$distance = 10){
	
	$lonmax = ($longitude + $distance/53.0);
	return $lonmax;
}


/************************************
////modified search businesses using lat long//
************************************/
function YB_search_keyword_new($search,$dbd,$latmin,$latmax,$lonmin,$lonmax,$resultcount = 20){

	$searchresult = array();
	$query_start = microtime(true);

	//$query = "select * from local_pages_lat_lon_updated where bname like '%$search%' and lat between $latmin and $latmax and lon between $lonmin and $lonmax and duplicate=0 limit 0,$resultcount";
	$query = "select * from local_pages_lat_lon_updated where match(bname) against('$search' in boolean mode) and lat between $latmin and $latmax and lon between $lonmin and $lonmax and duplicate=0 limit 0,$resultcount";
	$result = @mysql_query($query,$dbd);
	$query_time = microtime(true) - $query_start;
	while ($row = @mysql_fetch_assoc($result))
	{
		//$searchresult[] = $row;
		$duplicate = false;
		for($i=0; $i<count($searchresult); $i++){
			if($searchresult[$i]['biz_id'] == $row['biz_id']){
				$duplicate = true;
				break;
			}
		}
		if(!$duplicate)
			$searchresult[] = $row;
	}	
	
	$query_start = microtime(true);
	//$query = "select * from local_pages_lat_lon_updated where keywords like '%$search%' and lat between $latmin and $latmax and lon between $lonmin and $lonmax and duplicate=0 limit 0,$resultcount";
	$query = "select * from local_pages_lat_lon_updated where match(keywords) against('$search' in boolean mode) and lat between $latmin and $latmax and lon between $lonmin and $lonmax and duplicate=0 limit 0,$resultcount";
	$result = @mysql_query($query,$dbd);
	$query_time = microtime(true) - $query_start;
	while ($row = @mysql_fetch_assoc($result)) {
		//$searchresult[] = $row;
		$duplicate = false;
		for($i=0; $i<count($searchresult); $i++){
			if($searchresult[$i]['biz_id'] == $row['biz_id']){
				$duplicate = true;
				break;
			}
		}
		if(!$duplicate)
			$searchresult[] = $row;
	}
	
#	$splitkeyword = array();
#	$splitkeyword = explode(" ", $search);
#
#	if (count($searchresult) > $resultcount){
#		return $searchresult;
#	} else {
#			$query_start = microtime(true);
#			$query1 = "select * from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and duplicate=0 ";
#			for ($j=0; $j < count($splitkeyword);$j++){
#				$query1 .= " and keywords like '%";
#				$query1 .= $splitkeyword[$j];
#				$query1 .=	"%'";
#			}
#			$query1 .= " limit 0,$resultcount";
#			$result = @mysql_query($query1);
#			$query_time = microtime(true) - $query_start;
#			while ($row = @mysql_fetch_assoc($result)) {
#				//$searchresult[] = $row;
#				$duplicate = false;
#				for($i=0; $i<count($searchresult); $i++){
#					if($searchresult[$i]['biz_id'] == $row['biz_id']){
#						$duplicate = true;
#						break;
#					}
#				}
#				if(!$duplicate)
#				$searchresult[] = $row;
#			}
#
#	}
#	if (count($searchresult) > $resultcount){
#		return $searchresult;
#	} else {
#			$query_start = microtime(true);
#			$query2 = "select * from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and keywords like '%$splitkeyword[0]%' and duplicate=0 ";
#			$query2 .= " limit 0,$resultcount";
#			$result = @mysql_query($query2,$dbd);
#			$query_time = microtime(true) - $query_start;
#			while ($row = @mysql_fetch_assoc($result)) {
#				//$searchresult[] = $row;
#				$duplicate = false;
#				for($i=0; $i<count($searchresult); $i++){
#					if($searchresult[$i]['biz_id'] == $row['biz_id']){
#						$duplicate = true;
#						break;
#					}
#				}
#				if(!$duplicate)
#				$searchresult[] = $row;
#			}
#
#	}
#	if (count($searchresult) > $resultcount){
#		return $searchresult;
#	} elseif ($splitkeyword[1]){
#			$query_start = microtime(true);
#			$query3 = "select * from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and keywords like '%$splitkeyword[1]%' and duplicate=0 ";
#			$query3 .= " limit 0,$resultcount";
#			$result = @mysql_query($query3,$dbd);
#			$query_time = microtime(true) - $query_start;
#			while ($row = @mysql_fetch_assoc($result)) {
#				//$searchresult[] = $row;
#				$duplicate = false;
#				for($i=0; $i<count($searchresult); $i++){
#					if($searchresult[$i]['biz_id'] == $row['biz_id']){
#						$duplicate = true;
#						break;
#					}
#				}
#				if(!$duplicate)
#				$searchresult[] = $row;
#			}
#

	if ($searchresult)
		return $searchresult;
}

function YB_select_biz_new2($results,$dbd){
	global $searchresult;

	$count = 0;

	$bizresult = array();
	for ($i=0;$i< count($results);$i++){
		//echo $results[$i]['biz_id']." - ";
		 $query = "select LAT,LON, id, record_id, business_name,FULL_ADDRESS,city,STATE,zip,PHONE,PHONE_CODE,web_address,description,specialOffer, specialOffer_url  from local_pages_biz_updated where id = ". $results[$i]['biz_id']." AND (BUSINESS_FLAG IS NULL OR BUSINESS_FLAG != 'S') and duplicate=0 and (CHANGE_CODE IS NULL OR CHANGE_CODE != 'C') GROUP BY business_name limit 1";
		$result = mysql_query($query,$dbd);
		if ($row = mysql_fetch_assoc($result)){
			if($row['business_name']){
				$count++;
				$searchresult[$count]['business_name'] = $row['business_name'];
				$searchresult[$count]['address1'] = $row['FULL_ADDRESS'];
				$searchresult[$count]['biz_id'] = $row['id'];
				$searchresult[$count]['city'] = $row['city'];
				$searchresult[$count]['state'] = $row['STATE'];
				$searchresult[$count]['zip'] = $row['zip'];
				$searchresult[$count]['area_code'] = $row['PHONE_CODE'];
				$searchresult[$count]['phone_number'] = $row['PHONE'];
				$searchresult[$count]['record_id'] = $row['record_id'];
				$searchresult[$count]['specialOffer'] = $row['specialOffer'];
				$searchresult[$count]['specialOffer_url'] = $row['specialOffer_url'];
				$searchresult[$count]['lat'] = $row['LAT'];
				$searchresult[$count]['lon'] = $row['LON'];
				if ($row['PHONE']){
					$searchresult[$count]['PHONE'] = "(".substr($row['PHONE'],0,3).") ".substr($row['PHONE'],3,3).'-'.substr($row['PHONE'],6,4);
				}
				$searchresult[$count]['web_url_address'] = $row['web_address'];
				$QueryPremium = "select id from premium where id = ". $searchresult[$i]['biz_id']." limit 1";
				$ResultPremium = @mysql_query($QueryPremium,$dbd);
				if(@mysql_num_rows($ResultPremium))
					$searchresult[$count]['premium'] = 1;
				else
					$searchresult[$count]['premium'] = 0;
			}
		}
	}
//	print_r($searchresult);
	if ($searchresult)
		return $searchresult;
}

function YellowBookBusinessSearch($data, $cache=0){


	if (stristr($_SERVER['HTTP_HOST'],"localpages.com")) {
//		return array();
	}

	$search = urldecode($data['what']);
	$place = urldecode($data['where']);
	$place = str_replace(", "," ",$place);
	$place = str_replace(","," ",$place);

	$mkey = "YB_LZE_SEARCH_".md5($search.$place);
	$expire = 3600 * 24 * 30;
	$cache = 1;
	if($_SERVER['HTTP_X_FORWARDED_FOR']=="199.27.174.35" || stristr($_SERVER['HTTP_HOST'], '192.168.')) {
//		echo '<!-- search: ';print_r($search);echo ' -->'."\n";
//		echo '<!-- place: ';print_r($place);echo ' -->'."\n";
//		echo '<!-- mkey: ';print_r($mkey);echo ' -->'."\n";
	}
	if(stristr($_SERVER['HTTP_HOST'], 'localpages')) {
		if ($BizResult = lib_YBMemcache::mYBGet()->get($mkey)) {

			if (is_array($BizResult) && count($BizResult) > 0){
				return $BizResult;
			} else {
				store_yb_search_cache($BizResult++,$mkey,$expire);
			}
		}
	} else {
		return array();
	}

//	$Yelp = new Yelp();
//  	$res = $Yelp->businessSearch(array('term'=>urlencode($search), 'location'=>urlencode($place), 'output'=>'php'));
//	$total = count($res['businesses']);
//	for($i=0; $i<$total; $i++){
//		$BizResult['InArea'][$i]['business_id'] = $res['businesses'][$i]['id'];
//		$BizResult['InArea'][$i]['business_name'] = $res['businesses'][$i]['name'];
//		$BizResult['InArea'][$i]['description'] = $res['businesses'][$i]['snippet_text'];
//		$BizResult['InArea'][$i]['AverageReviewScore'] = $res['businesses'][$i]['rating'];
//		$BizResult['InArea'][$i]['TotalNumberOfReviews'] = $res['businesses'][$i]['review_count'];
//		$BizResult['InArea'][$i]['phone'] = $res['businesses'][$i]['phone'];
//		$BizResult['InArea'][$i]['url'] = $res['businesses'][$i]['url'];
//		$BizResult['InArea'][$i]['img'] = $res['businesses'][$i]['image_url'];
//		$BizResult['InArea'][$i]['rating_img_url_large'] = $res['businesses'][$i]['rating_img_url_large'];
//		$BizResult['InArea'][$i]['address1'] = $res['businesses'][$i]['location']['display_address'][0];
//		$BizResult['InArea'][$i]['city'] = $res['businesses'][$i]['location']['display_address'][1];
//		$BizResult['InArea'][$i]['state'] = $res['businesses'][$i]['location']['state_code'];
//		$BizResult['InArea'][$i]['zip'] = $res['businesses'][$i]['location']['postal_code'];		
//		$BizResult['InArea'][$i]['lat'] = $res['businesses'][$i]['location']['coordinate']['latitude'];
//		$BizResult['InArea'][$i]['lon'] = $res['businesses'][$i]['location']['coordinate']['longitude'];
//	}

	//$BizResult = LocalSearch($search, $place, $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_USER_AGENT']);
	//if($data['inc_db'] && $data['inc_db'] == true)

 	if(!stristr($_SERVER['HTTP_HOST'], '192.168.')){   //0 for DEV server
		if(!stristr($_SERVER['HTTP_HOST'], 'localpages')) {
			$dbd = YB_ConnectToSlaveLP();
			$latlon = localBizDB_place2latlon_new(trim(urldecode($data['where'])),$dbd);

			$longitude = $latlon['lon'];
			$latitude = $latlon['lat'];

			//$latmin = latmin($latitude,$distance = 10);
			//$latmax = latmax($latitude,$distance = 10);
			//$lonmin = lonmin($longitude,$distance = 10);
			//$lonmax = lonmax($longitude,$distance = 10);
			$latmin = $latitude + 10 / 69;
			$latmax = $latitude - 10 / 69;
			$lonmin = $longitude + 10 / (69 / cos(deg2rad($latitude)));
			$lonmax = $longitude - 10 / (69 / cos(deg2rad($latitude)));
			$resultcount = 10;
			$resultstart = $resultcount*($data['pageNumber']-1);
			$localBizDB = localBizDB_search_keyword_new($search,$dbd,$latmin,$latmax,$lonmin,$lonmax,$resultstart,$resultcount);
			$biz_results = localBizDB_select_biz_new2($localBizDB,$dbd);
			
			//$BizResults = array('InArea' => array());
			//$BizResults['InArea'] = array_values(array_filter(array_merge($BizResult['InArea'], $biz_results['InArea'])));
			$BizResults = $biz_results;
			$count = count($BizResults['InArea']);
			if($count > 0)
				$BizResults['InArea']['TotalListings'] = $count;
		}
	}

	if ($cache){
		if (is_array($BizResults) && $count > 0){
			store_yb_search_cache($BizResults,$mkey,$expire);
		} else if(is_int($BizResult)) {
			store_yb_search_cache($BizResult++,$mkey,$expire);
		} else {
			store_yb_search_cache(1,$mkey,$expire);
		}
	}

	return $BizResults;
}

//function YellowBookBusinessSearch($data, $cache=0){
//
//	if (stristr($_SERVER['HTTP_HOST'],"localpages.com")) {
//		return array();
//	}
//	$db = YB_ConnectToSlaveLP();
//	$search = urldecode($data['what']);
//	$place = urldecode($data['where']);
//	$latlon = YB_place2latlon_new(trim($place),$db);
//	$longitude  = $latlon['lon'];
//	$latitude = $latlon['lat'];
//
//	$latmin = YB_latmin($latitude,$distance = 10);
//	$latmax = YB_latmax($latitude,$distance = 10);
//	$lonmin = YB_lonmin($longitude,$distance = 10);
//	$lonmax = YB_lonmax($longitude,$distance = 10);
//	$results =  YB_search_keyword_new($search,$db,$latmin,$latmax,$lonmin,$lonmax,$resultcount = 10);
//
//	$biz_results = YB_select_biz_new2($results,$db);
//	for($i = 1;$i <= count($biz_results); $i++){ 
//		$BizResult['InArea'][$i]['business_id'] = $biz_results[$i]['biz_id'];
//		$BizResult['InArea'][$i]['business_name'] = $biz_results[$i]['business_name'];
//		$BizResult['InArea'][$i]['ListingType'] = $biz_results[$i]['InArea'];
//		$BizResult['InArea'][$i]['address1'] = $biz_results[$i]['address1'];
//		$BizResult['InArea'][$i]['city'] = $biz_results[$i]['city'];
//		$BizResult['InArea'][$i]['state'] = $biz_results[$i]['state'];
//		$BizResult['InArea'][$i]['zip'] = $biz_results[$i]['zip'];
//		$BizResult['InArea'][$i]['phone'] = $biz_results[$i]['phone_number'];
//		$BizResult['InArea'][$i]['lat'] = $biz_results[$i]['lat'];
//		$BizResult['InArea'][$i]['lon'] = $biz_results[$i]['lon'];
//	}
//
//	return $BizResult;
//}

#########################################
#		YELLOWBOOK LISTING SEARCH		#
#########################################
//function YellowBookBusinessSearch($data, $cache=0)
//{
//	global $msacommon_check;
//	$msacommon_check = "From msacommon lib";
//	##### FETCH INPUT
//	if (!$data['serving'])
//		$data['serving'] = 'all';
//	$data['version'] = '3.1';
//	$data['geoExpand'] = 'yes';
//	if(empty($data['pageSize']))
//		$data['pageSize'] = '10';
//		
//	$Param = '';
//	foreach ($data as $key => $value)
//		$Param .= $key.'='.$value.'&'; 
//	
//	if (stristr($_SERVER['HTTP_HOST'],"pointcom") 
//	|| stristr($_SERVER['HTTP_HOST'],"192.168.30.184") 
//	|| stristr($_SERVER['HTTP_HOST'],"localpages")
//	|| stristr($_SERVER['HTTP_HOST'],"leisure.com")
//	|| stristr($_SERVER['HTTP_HOST'],"counselingeducation.com")
//	|| stristr($_SERVER['HTTP_HOST'],"yield.com")
//	|| stristr($_SERVER['HTTP_HOST'],"1stcreditrepairs.com")
//	|| stristr($_SERVER['HTTP_HOST'],"http://1800coupon.com")
//	|| stristr($_SERVER['HTTP_HOST'],"rateit.com")){
//		$cache = 1;
//	}
//
//	
//	######## LOGS THE REQUEST ########
//	//YellowBookLogs($data);
//
//	###### INIT DOM XML #####
//	$YellowBookFeed = new DomDocument();
//	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/GetListings.ashx?".$Param;
//	if($_GET['debug'] == 'msa123')
//		echo '<hr>'.$YellowBookFeedUrl;
//
//	if ($cache){
//		$mkey = "_msa_ybbizsearch_";
//		if ($data['what']){
//			$mkey .= "_".md5($data['what']);
//		}
//		if ($data['where']){
//			$mkey .= "_".md5($data['where']);
//		}
//		if ($data['pageNumber']){
//			$mkey .= "_".$data['pageNumber'];
//		}
//		if ($data['pageSize']){
//			$mkey .= "_".$data['pageSize'];
//		}
//		$expire = 3600 * 24 * 3;
//		if ($BizResult = lib_YBMemcache::mYBGet()->get($mkey)) {
//			if (is_array($BizResult) && count($BizResult) > 0){
//				//Make a async call even when in cache
//				###### CURL & PARSE XML #####
//				$CurlData = array(	"url" => $YellowBookFeedUrl,
//						"timeout" => '10',
//						"login" => 'apirlclp01:zx31kw+23@VkNsa');
//				$curl_data = async_curl_get_contents($CurlData);
//				return $BizResult;
//			}
//		}
//	}
//	###### CURL & PARSE XML #####
//	$CurlData = array(	"url" => $YellowBookFeedUrl,
//						"timeout" => '20',
//						"login" => 'apirlclp01:zx31kw+23@VkNsa');
//	
//	$curl_data = curl_get_contents($CurlData);
//	if($curl_data == ""){
//		return;
//	}
//	//var_dump($data, $YellowBookFeedUrl, $curl_data);
//	$YellowBookFeed->loadXML($curl_data);
//
//	########### PARSING REFINEMENT LISTING #######
//	if ($YellowBookFeed->getElementsByTagName("Refinements")->item(0))
//	{
//		$Refinements = $YellowBookFeed->getElementsByTagName("Refinements")->item(0); 
//		if($Refinements->getElementsByTagName("PopularTerms")->item(0))
//			foreach($Refinements->getElementsByTagName("PopularTerms")->item(0)->getElementsByTagName("Term") as $PopularTerms)
//				$BizResult['Refinements'][]['PopularTerms'] = $PopularTerms->nodeValue;
//				
//		if($Refinements->getElementsByTagName("ExpandLocations")->item(0)) 
//			foreach($Refinements->getElementsByTagName("ExpandLocations")->item(0)->getElementsByTagName("Where") as $Location) 
//				$BizResult['ExpandLocations'][]['Where'] = $Location->nodeValue;
//		
//		if($Refinements->getElementsByTagName("NarrowLocations")->item(0)) 
//			foreach($Refinements->getElementsByTagName("NarrowLocations")->item(0)->getElementsByTagName("Where") as $Location) 
//				$BizResult['NarrowLocations'][]['Where'] = $Location->nodeValue;
//	}
//
//	$rand = rand(0,100);;
//	if($rand%50 == 0){
//		$store_yb_cat = true;
//	}
//	else{
//		$store_yb_cat = false;
//	}
//	########### PARSING CATEGORY LISTING #######
//	if ($YellowBookFeed->getElementsByTagName("SearchInfo")->item(0))
//	{
//		$SearchInfo = $YellowBookFeed->getElementsByTagName("SearchInfo")->item(0); 
//		if($SearchInfo->getElementsByTagName("Categories")->item(0)){
//			if($store_yb_cat)
//				$db = YB_ConnectToMasterLP();
//			for($i = 0; $SearchInfo->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category")->item($i) && $i < 20 ; $i++ ) {
//				$yb_cat_id = $SearchInfo->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category")->item($i)->getAttribute('Id');
//				$yb_cat = $SearchInfo->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category")->item($i)->getAttribute('Name');
//				$BizResult['Category'][] = $yb_cat;
//				$BizResult['CategoryWithID'][intval($yb_cat_id,10)] = $yb_cat;
//				if($store_yb_cat){
//					$yb_cat_key = md5("YB_CAT_".$yb_cat_id);
//					if (!$yb_cat_stored = lib_YBMemcache::mYBGet()->get($yb_cat_key)) {
//						$yb_cat = mysql_real_escape_string($yb_cat);
//						$sql = "INSERT IGNORE INTO `yellowbook_categories`(`id`, `category`) VALUES ($yb_cat_id,'$yb_cat')";
//						mysql_query($sql, $db);
//						$yb_cat_expire = 24*60*60*5;
//						store_yb_search_cache("1",$yb_cat_key,$yb_cat_expire);
//					}
//				}
//			}
//			if($store_yb_cat)
//				mysql_close($db);
//		}			
//	}
//
//	########### PARSING BANNER #######
//	if ($YellowBookFeed->getElementsByTagName("Banner")->item(0))
//	{
//		$BizResult['Banner']['img'] = $YellowBookFeed->getElementsByTagName("Banner")->item(0)->getAttribute('MediaUrl');
//		$BizResult['Banner']['url'] = $YellowBookFeed->getElementsByTagName("Banner")->item(0)->getAttribute('DestinationUrl');
//		$BizResult['Banner']['type'] = $YellowBookFeed->getElementsByTagName("Banner")->item(0)->getAttribute('MediaType');
//	}
//
//	########### PARSING INAREA LISTING #######
//	if ($YellowBookFeed->getElementsByTagName("InAreaListings")->item(0) && $YellowBookFeed->getElementsByTagName("InAreaListings")->item(0)->getElementsByTagName("Listing")->item(0))
//	{
//		$BizResult['InArea']['TotalListings'] = $YellowBookFeed->getElementsByTagName("InAreaListings")->item(0)->getAttribute("TotalListings");
//		$Listing = $YellowBookFeed->getElementsByTagName("InAreaListings")->item(0)->getElementsByTagName("Listing"); 
//		for($i = 0;$i < 10; $i++) 
//		{ 
//			if($Listing->item($i))
//			{
//				$BizResult['InArea'][$i]['business_id'] = $Listing->item($i)->getAttribute('ListingId');
//				$BizResult['InArea'][$i]['business_name'] = $Listing->item($i)->getAttribute("Name");
//				$BizResult['InArea'][$i]['description'] = $Listing->item($i)->getAttribute("TagLine");
//				$BizResult['InArea'][$i]['ListingType'] = $Listing->item($i)->getAttribute("ListingType");
//				
//				$Location = $Listing->item($i)->getElementsByTagName("Location")->item(0);
//				$BizResult['InArea'][$i]['address1'] = $Location->getAttribute("Address1");
//				$BizResult['InArea'][$i]['city'] = $Location->getAttribute("City");
//				$BizResult['InArea'][$i]['state'] = $Location->getAttribute("State");
//				$BizResult['InArea'][$i]['zip'] = $Location->getAttribute("Zip");
//				$BizResult['InArea'][$i]['phone'] = $Location->getAttribute("Phone");
//				$BizResult['InArea'][$i]['lat'] = $Location->getAttribute("Latitude");
//				$BizResult['InArea'][$i]['long'] = $Location->getAttribute("Longitude");
//				
//				$listingCatId = explode(',',$Listing->item($i)->getAttribute("Categories"));
//				$BizResult['InArea'][$i]['category_id'] = $listingCatId[0];
//				
//				if($Listing->item($i)->getElementsByTagName("ContactInfo")->item(0))
//				{
//					$BizResult['InArea'][$i]['email'] = $Listing->item($i)->getElementsByTagName("ContactInfo")->item(0)->getAttribute("EmailAddress");
//					$BizResult['InArea'][$i]['tollfree'] = $Listing->item($i)->getElementsByTagName("ContactInfo")->item(0)->getAttribute("TollFreeNumber");
//				}
//				// Url
//				if($Listing->item($i)->getElementsByTagName("Website")->item(0))
//					$BizResult['InArea'][$i]['url'] = $Listing->item($i)->getElementsByTagName("Website")->item(0)->getAttribute("Url");
//				// Logo
//				if($Listing->item($i)->getElementsByTagName("Media")->item(0))
//					$BizResult['InArea'][$i]['logo'] = $Listing->item($i)->getElementsByTagName("Media")->item(0)->getAttribute("LogoUrl");
//				//Video
//				if($Listing->item($i)->getElementsByTagName("VideoAd")->item(0))
//					$BizResult['InArea'][$i]['video'] = $Listing->item($i)->getElementsByTagName("VideoAd")->item(0)->getAttribute("SwfUrl");
//				// Reviews
//				if($Listing->item($i)->getElementsByTagName("Reviews")->item(0))
//				{
//					$BizResult['InArea'][$i]['AverageReviewScore'] = $Listing->item($i)->getElementsByTagName("Reviews")->item(0)->getAttribute("AverageReviewScore");
//					$BizResult['InArea'][$i]['TotalNumberOfRatings'] = $Listing->item($i)->getElementsByTagName("Reviews")->item(0)->getAttribute("TotalNumberOfRatings");
//					$BizResult['InArea'][$i]['TotalNumberOfReviews'] = $Listing->item($i)->getElementsByTagName("Reviews")->item(0)->getAttribute("TotalNumberOfReviews");
//				}
//			}
//		}
//	}
//
//	########### PARSING ALSO SERVING LISTING #######
//	if ($YellowBookFeed->getElementsByTagName("AlsoServingListings")->item(0))
//	{
//		$Listing = $YellowBookFeed->getElementsByTagName("AlsoServingListings")->item(0)->getElementsByTagName("Listing"); 
//		for($i = 0;$i < 10; $i++) 
//		{ 
//			if($Listing->item($i))
//			{
//				$BizResult['AlsoServing'][$i]['business_id'] = $Listing->item($i)->getAttribute('ListingId');
//				$BizResult['AlsoServing'][$i]['business_name'] = $Listing->item($i)->getAttribute("Name");
//				$BizResult['AlsoServing'][$i]['description'] = $Listing->item($i)->getAttribute("TagLine");
//				
//				$Location = $Listing->item($i)->getElementsByTagName("Location")->item(0);
//				$BizResult['AlsoServing'][$i]['address1'] = $Location->getAttribute("Address1");
//				$BizResult['AlsoServing'][$i]['city'] = $Location->getAttribute("City");
//				$BizResult['AlsoServing'][$i]['state'] = $Location->getAttribute("State");
//				$BizResult['AlsoServing'][$i]['zip'] = $Location->getAttribute("Zip");
//				$BizResult['AlsoServing'][$i]['phone'] = $Location->getAttribute("Phone");
//				$BizResult['AlsoServing'][$i]['lat'] = $Location->getAttribute("Latitude");
//				$BizResult['AlsoServing'][$i]['long'] = $Location->getAttribute("Longitude");
//
//				$listingCatId = explode(',',$Listing->item($i)->getAttribute("Categories"));
//				$BizResult['AlsoServing'][$i]['category_id'] = $listingCatId[0];
//				
//				if($Listing->item($i)->getElementsByTagName("ContactInfo")->item(0))
//				{
//					$BizResult['AlsoServing'][$i]['email'] = $Listing->item($i)->getElementsByTagName("ContactInfo")->item(0)->getAttribute("EmailAddress");
//					$BizResult['AlsoServing'][$i]['tollfree'] = $Listing->item($i)->getElementsByTagName("ContactInfo")->item(0)->getAttribute("TollFreeNumber");
//				}
//				// Url
//				if($Listing->item($i)->getElementsByTagName("Website")->item(0))
//					$BizResult['AlsoServing'][$i]['url'] = $Listing->item($i)->getElementsByTagName("Website")->item(0)->getAttribute("Url");
//				// Logo
//				if($Listing->item($i)->getElementsByTagName("Media")->item(0))
//					$BizResult['AlsoServing'][$i]['logo'] = $Listing->item($i)->getElementsByTagName("Media")->item(0)->getAttribute("LogoUrl");
//				//Video
//				if($Listing->item($i)->getElementsByTagName("VideoAd")->item(0))
//					$BizResult['AlsoServing'][$i]['video'] = $Listing->item($i)->getElementsByTagName("VideoAd")->item(0)->getAttribute("SwfUrl");
//			}
//		}
//	}
//	if ($cache){
//		if (is_array($BizResult) && count($BizResult) > 0){
//			store_yb_search_cache($BizResult,$mkey,$expire);
//		}
//	}
//	return $BizResult;
//}

#########################################
#		YELLOWBOOK LISTING SEARCH		#
#########################################

function YellowBookBusinessDetail($data, $cache=1)
{
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 
	if ($data['Id']){
		$business_id = $data['Id'];
	} elseif($data['id']){
		$business_id = $data['id'];
	}
	$mkey = "msa_localdetail_".$business_id;
	$expire = 3600 * 24 * 3;
	$cache = 1;

	if ($cache){
		class lib_YBDetailMemcache extends Memcache {
			static private $instance = null;
			static private $port = 11211;
			static function mYBDGet($ServerArray = array("192.168.30.32")) {
				if (self::$instance == null) {
					self::$instance = new Memcache;
					foreach  ($ServerArray as $Server)
						self::$instance->addServer($Server, self::$port);
				}
				return self::$instance;
			}
		}
		if ($BizResult = lib_YBDetailMemcache::mYBDGet()->get($mkey)) {
			if (is_array($BizResult) && count($BizResult) > 0){
				return $BizResult;
			}
		}
	}
	
	if(stristr($business_id, 'lze')) {
		$dbd = YB_ConnectToSlaveLP();
		$BizResult = localBizDB_biz_profile($business_id, $dbd);
	} else {
		$BizResult = LocalProfile($search, $place, $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_USER_AGENT'], $business_id);
	}
	
	if ($cache){
		if (is_array($BizResult) && count($BizResult) > 0){
			store_yb_detail_cache($BizResult,$mkey,$expire);
		}
	}

	return $BizResult;

}
function YellowBookBusinessDetail_OLD($data, $cache=0)
{
	##### FETCH INPUT
	if (!$data['getAllAds'])
		$data['getAllAds'] = 'all';
	$data['version'] = '2.5';
		
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 

	if (stristr($_SERVER['HTTP_HOST'],"rateit") || stristr($_SERVER['HTTP_HOST'],"pointcom") || stristr($_SERVER['HTTP_HOST'],"192.168.30.184") || stristr($_SERVER['HTTP_HOST'],"localpages")){
		$cache = 0;
	}
	if ($cache){
		class lib_YBDetailMemcache extends Memcache {
			static private $instance = null;
			static private $port = 11211;
			static function mYBDGet($ServerArray = array("192.168.30.32")) {
				if (self::$instance == null) {
					self::$instance = new Memcache;
					foreach  ($ServerArray as $Server)
						self::$instance->addServer($Server, self::$port);
				}
				return self::$instance;
			}
		}
		$mkey = "msa_ybbizdetail_";
		if ($data['Id']){
			$mkey .= "_".$data['Id'];
		}
		$expire = 3600 * 24 * 3;
		if ($BizResult = lib_YBDetailMemcache::mYBDGet()->get($mkey)) {
			if (is_array($BizResult) && count($BizResult) > 0){
				return $BizResult;
			}
		}
	}

	###### INIT DOM XML #####
	$YellowBookFeed = new DomDocument();
	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/GetListingDetails.ashx?".$Param;

	###### CURL & PARSE XML #####
	$CurlData = array(	"url" => $YellowBookFeedUrl,
						"timeout" => '2',
						"login" => 'apirlclp01:zx31kw+23@VkNsa');
	
	$curl_res = curl_get_contents($CurlData);
	if($curl_res == ""){
		return;
	}
	$YellowBookFeed->loadXML($curl_res);
	if($_GET['debug'] == 'msa123')
		echo '<hr>'.$YellowBookFeedUrl;

	########### PARSING DETAIL LISTING #######
	if ($YellowBookFeed->getElementsByTagName("Listing")->item(0))
	{
		$Listing = $YellowBookFeed->getElementsByTagName("Listing")->item(0);
		// Basics
		$BizResult['Listing']['business_name'] = $Listing->getAttribute("Name");
		$BizResult['Listing']['description'] = $Listing->getAttribute("TagLine");
		//AboutUs
		if($Listing->getElementsByTagName("AboutUs")->item(0))
			foreach($Listing->getElementsByTagName("AboutUs")->item(0)->getElementsByTagName("Bullet") as $Bullet)
				$BizResult['Listing']['AboutUs'][] = $Bullet->nodeValue;

		//Location		
		$Location = $Listing->getElementsByTagName("Location")->item(0);
		$BizResult['Listing']['address1'] = $Location->getAttribute("Address1");
		$BizResult['Listing']['city'] = $Location->getAttribute("City");
		$BizResult['Listing']['state'] = $Location->getAttribute("State");
		$BizResult['Listing']['zip'] = $Location->getAttribute("Zip");
		$BizResult['Listing']['phone'] = $Location->getAttribute("Phone");
		$BizResult['Listing']['lat'] = $Location->getAttribute("Latitude");
		$BizResult['Listing']['long'] = $Location->getAttribute("Longitude");

		// Contact Info
		if($Listing->getElementsByTagName("ContactInfo")->item(0))
		{
			$BizResult['Listing']['email'] = $Listing->getElementsByTagName("ContactInfo")->item(0)->getAttribute("EmailAddresses");
			$BizResult['Listing']['fax'] = $Listing->getElementsByTagName("ContactInfo")->item(0)->getAttribute("FaxNumber");
			$BizResult['Listing']['tollfree'] = $Listing->getElementsByTagName("ContactInfo")->item(0)->getAttribute("TollFreeNumber");
		}
		// CreditCards
		if($Listing->getElementsByTagName("CreditCards")->item(0))
		{
			$BizResult['Listing']['AmericanExpress'] = $Listing->getElementsByTagName("CreditCards")->item(0)->getAttribute("AmericanExpress");
			$BizResult['Listing']['CarteBlanche'] = $Listing->getElementsByTagName("CreditCards")->item(0)->getAttribute("CarteBlanche");
			$BizResult['Listing']['Discover'] = $Listing->getElementsByTagName("CreditCards")->item(0)->getAttribute("Discover");
			$BizResult['Listing']['MasterCard'] = $Listing->getElementsByTagName("CreditCards")->item(0)->getAttribute("MasterCard");
			$BizResult['Listing']['Visa'] = $Listing->getElementsByTagName("CreditCards")->item(0)->getAttribute("Visa");
		}
		// Hours
		if($Listing->getElementsByTagName("Hours")->item(0))
			$BizResult['Listing']['hours']['sunday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Sunday");
			$BizResult['Listing']['hours']['monday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Monday");
			$BizResult['Listing']['hours']['tuesday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Tuesday");
			$BizResult['Listing']['hours']['wednesday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Wednesday");
			$BizResult['Listing']['hours']['thursday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Thursday");
			$BizResult['Listing']['hours']['friday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Friday");
			$BizResult['Listing']['hours']['saturday'] = $Listing->getElementsByTagName("Hours")->item(0)->getAttribute("Saturday");
		// Url
		if($Listing->getElementsByTagName("Website")->item(0))
			$BizResult['Listing']['url'] = $Listing->getElementsByTagName("Website")->item(0)->getAttribute("Url");
		// Logo
		if($Listing->getElementsByTagName("Media")->item(0))
			$BizResult['Listing']['logo'] = $Listing->getElementsByTagName("Media")->item(0)->getAttribute("BookScanUrl");
		// Coupon
		if($Listing->getElementsByTagName("Coupon")->item(0))
		{
			$BizResult['Listing']['CouponExpiration'] = $Listing->getElementsByTagName("Coupon")->item(0)->getAttribute("Expiration");
			$BizResult['Listing']['CouponOffer'] = $Listing->getElementsByTagName("Coupon")->item(0)->getElementsByTagName("Offer")->item(0)->nodeValue;
			$BizResult['Listing']['CouponRestrictions'] = $Listing->getElementsByTagName("Coupon")->item(0)->getElementsByTagName("Restrictions")->item(0)->nodeValue;
		}
		//Video
		if($Listing->getElementsByTagName("VideoAd")->item(0))
					$BizResult['Listing']['video'] = $Listing->getElementsByTagName("VideoAd")->item(0)->getAttribute("SwfUrl");
		// Reviews
		if($Listing->getElementsByTagName("Review")->item(0))
		{
			$BizResult['Listing']['AverageReviewScore'] = $Listing->getElementsByTagName("Reviews")->item(0)->getAttribute("AverageReviewScore");
			$BizResult['Listing']['TotalNumberOfRatings'] = $Listing->getElementsByTagName("Reviews")->item(0)->getAttribute("TotalNumberOfRatings");
			$BizResult['Listing']['TotalNumberOfReviews'] = $Listing->getElementsByTagName("Reviews")->item(0)->getAttribute("TotalNumberOfReviews");
			
			$count = 0;
			foreach($YellowBookFeed->getElementsByTagName("Reviews")->item(0)->getElementsByTagName("Review") as $Review) {
				$BizResult['Listing']['Reviews'][$count]['DateCreated'] = $Review->getAttribute('DateCreated');
				$BizResult['Listing']['Reviews'][$count]['Rating'] = $Review->getAttribute('Rating');
				$BizResult['Listing']['Reviews'][$count]['Title'] = $Review->getAttribute('Title');
				$BizResult['Listing']['Reviews'][$count]['Content'] = $Review->getAttribute('Content');
				
				$UserInfo = $Review->getElementsByTagName("UserInfo")->item(0);
				$BizResult['Listing']['Reviews'][$count]['DisplayName'] = $UserInfo->getAttribute('DisplayName');
				
				$count++;
			}
		}
		}
		
		// Categories
		if ($YellowBookFeed->getElementsByTagName("Categories")->item(0)) {
			foreach($YellowBookFeed->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category") as $Category) {
				$BizResult['Listing']['Categories'][] = $Category->getAttribute('Name');
			}
		}

	if ($cache){
		if (is_array($BizResult) && count($BizResult) > 0){
			store_yb_detail_cache($BizResult,$mkey,$expire);
		}
	}

	return $BizResult;
}

/***** USAGE ****** 
$data = array(	"what" => urlencode($search),
				"where" => urlencode($place),				  					
				"serving" => "none",
			  );
*/

#########################################
#		YELLOWBOOK LISTING SEARCH		#
#########################################
function YellowBookCategorySearch($data)
{
	##### FETCH INPUT
	$data['version'] = '2.5';
		
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 
	
	###### INIT DOM XML #####
	$YellowBookFeed = new DomDocument();
	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/GetListings.ashx?".$Param;
	if($_GET['debug'] == 'msa123')
		echo '<hr>'.$YellowBookFeedUrl;

	###### CURL & PARSE XML #####
	$CurlData = array(	"url" => $YellowBookFeedUrl,
						"timeout" => '2',
						"login" => 'apirlclp01:zx31kw+23@VkNsa');
	
	$curl_res = curl_get_contents($CurlData);
	if($curl_res == ""){
		return;
	}
	$YellowBookFeed->loadXML($curl_res);
	
	########### PARSING REFINEMENT LISTING #######
	if ($YellowBookFeed->getElementsByTagName("Refinements")->item(0))
	{
		$Refinements = $YellowBookFeed->getElementsByTagName("Refinements")->item(0); 
		if($Refinements->getElementsByTagName("PopularTerms")->item(0))
			foreach($Refinements->getElementsByTagName("PopularTerms")->item(0)->getElementsByTagName("Term") as $PopularTerms)
				$BizResult['Refinements'][]['PopularTerms'] = $PopularTerms->nodeValue;
	}

	########### PARSING CATEGORY LISTING #######
	if ($YellowBookFeed->getElementsByTagName("SearchInfo")->item(0))
	{
		$SearchInfo = $YellowBookFeed->getElementsByTagName("SearchInfo")->item(0); 
		if($SearchInfo->getElementsByTagName("Categories")->item(0))
			for($i = 0; $SearchInfo->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category")->item($i) && $i < 20 ; $i++ )
				$BizResult['Category'][] = $SearchInfo->getElementsByTagName("Categories")->item(0)->getElementsByTagName("Category")->item($i)->getAttribute('Name');
	}

	return $BizResult;
}

/***** USAGE ****** 
$data = array(	"categoryStringKey" => urlencode(''),
				"categoryFilter" => urlencode(''),				  								
				"categoryId" => urlencode(''),
			  );
*/

#########################################
#		YELLOWBOOK CATEGORY BROWSE		#
#########################################
function YellowBookCategoryBrowse($data)
{	
	global $ipaddress;
	global $ua;
	
	##### FETCH INPUT
	//$data['version'] = '2.5';
	$data["clientIp"] = $ipaddress;				
	$data["browserAgent"] = $ua;
	$data['categoryDepth'] = '2';
		
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 
	
	###### INIT DOM XML #####
	$YellowBookFeed = new DomDocument();
	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/categorybrowse.ashx?".$Param . 'version=2.1';
	
	if($_GET['debug'] == 'msa123')
		echo '<hr>'.$YellowBookFeedUrl;

	###### CURL & PARSE XML #####
	$CurlData = array(	"url" => $YellowBookFeedUrl,
						"timeout" => '2',
						"login" => 'apirlclp01:zx31kw+23@VkNsa');
	
	$curl_res = curl_get_contents($CurlData);
	if($curl_res == ""){
		return;
	}
	$YellowBookFeed->loadXML($curl_res);
	
	if ($YellowBookFeed->getElementsByTagName("categories")->item(0)) {
		
		foreach($YellowBookFeed->getElementsByTagName("categories")->item(0)->childNodes as $Category) {
			$catName = $Category->getAttribute('name');
			$d2array = array();
			
			foreach($Category->childNodes as $CategoryD2) {
				$d2array[] = $CategoryD2->getAttribute('name');
			}
			
			$BizResult['Categories'][$catName] = $d2array;
		}
	}
	
	return $BizResult;
}

/***** INPUT USAGE ****** 
$data = array(	"city" => urlencode($city),
				"state" => urlencode($state),				  					
			  );
*/
#########################################
#		YELLOWBOOK LISTING SEARCH		#
#########################################
function YellowBookCoupons($data)
{
	return "";
	
	##### FETCH INPUT
	$data['version'] = '2.5';
		
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 

	###### INIT DOM XML #####
	$YellowBookFeed = new DomDocument();
	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/GetDeals.ashx?".$Param;
	
	if($_GET['debug'] == 'msa123')
		echo '<hr>'.$YellowBookFeedUrl;

	###### CURL & PARSE XML #####
	$CurlData = array(	"url" => $YellowBookFeedUrl,
						"timeout" => '2',
						"login" => 'apirlclp01:zx31kw+23@VkNsa');
	
	$curl_res = curl_get_contents($CurlData);
	if($curl_res == ""){
		return;
	}
	$YellowBookFeed->loadXML($curl_res);
	
	########### PARSING REFINEMENT LISTING #######
	if ($YellowBookFeed->getElementsByTagName("Deal")->item(0))
	{
		$i = 0;
		foreach($YellowBookFeed->getElementsByTagName("Deal") as $Deal)
		{
			$DataArray[$i]['CurrentPrice'] = $Deal->getAttribute('CurrentPrice');
			$DataArray[$i]['OriginalPrice'] = $Deal->getAttribute('OriginalPrice');
			$DataArray[$i]['DiscountPercentage'] = $Deal->getAttribute('DiscountPercentage');
			$DataArray[$i]['ImageUrl'] = $Deal->getAttribute('ImageUrl');
			$DataArray[$i]['EndTimeISO'] = $Deal->getAttribute('EndTimeISO');
			$DataArray[$i]['Title'] = $Deal->getAttribute('Title');
			$DataArray[$i]['ShortDescription'] = $Deal->getAttribute('ShortDescription');
			$DataArray[$i]['OfferUrl'] = $Deal->getAttribute('OfferUrl');
			$i++;
		}
	}

	return $DataArray;
}

#########################################
#		YELLOWBOOK COMSCRORE TAG		#
#########################################
function YellowBookComScore()
{

	if(stristr($_SERVER['HTTP_HOST'], 'pointcom.com') ||
	stristr( $_SERVER['HTTP_HOST'], 'vortal.com') ||
	stristr( $_SERVER['HTTP_HOST'], 'socialsearch.com'))
	{
		?>
		<!-- Begin comScore Tag -->
		<script>
		document.write(unescape("%3Cscript src='" + (document.location.protocol == "https:" ? "https://sb" : "http://b")
		+ ".scorecardresearch.com/beacon.js' %3E%3C/script%3E"));
		</script>
		<script>
		COMSCORE.beacon({
		c1:2,
		c2:"6036377",
		c3:"",
		c4:"",
		c5:"",
		c6:"",
		c15:""
		});
		</script>
		<noscript>
		<img src="http://b.scorecardresearch.com/p?c1=2&c2=&c3=&c4=&c5=&c6=&c15=&cj=1" />
		</noscript>
		<!-- End comScore Tag -->
        <?
	}
}

#########################################
#		YELLOWBOOK LOGS					#
#########################################
function YellowBookLogs($data)
{
	return false;
	### DB CON ####
	$mysql_host = "64.74.172.199"; 
	$mysql_user = "c3slave";
	$mysql_password = "RstG496urky2";
	$mysql_db = "YellowBook";
	$db = mysql_connect ($mysql_host, $mysql_user, $mysql_password );
	@mysql_select_db ($mysql_db, $db);
	$Location = explode(',', urldecode($data['where']));

	$sql = "INSERT INTO `xml_call_".date("m")."-".date("d")."`(date, keyword, ip, city, state, page)
			VALUES (NOW(), '".$data['what']."', '".$data['clientIp']."', '".$Location[0]."', '".$Location[1]."',  '".$_SERVER['PHP_SELF']."')";
	$res = mysql_query($sql, $db);
}


function store_yb_search_cache($data,$mkey,$expire){
	if(is_array($data) && count($data) > 0) {
		lib_YBMemcache::mYBGet()->set($mkey, $data, 0, $expire);
	} else if($data == 5) {
		lib_YBMemcache::mYBGet()->set($mkey, 6, 0, 60*60*24*5);
	} else if($data < 5) {
		lib_YBMemcache::mYBGet()->set($mkey, $data, 0, 60*60*24);
	}
}
function store_yb_detail_cache($data,$mkey,$expire){
	lib_YBDetailMemcache::mYBDGet()->set($mkey, $data, 0, $expire);
}

/*
 * $data_phone = array(

	'pN' => urlencode("212-348-5151"),

	'clientIp' => "132.168.30.184",

	'browserAgent' => 'firefox',

	'visitorId' => session_id(),

	'sessionId' => session_id(),

	'version' =>'3.0'

	);
 */
function reverse_phone_lookup($data){
	##### FETCH INPUT
	if (!$data['serving'])
		$data['serving'] = 'all';
	$data['version'] = '3.1';
	$data['geoExpand'] = 'yes';
	if(empty($data['pageSize']))
		$data['pageSize'] = '10';
		
	$Param = '';
	foreach ($data as $key => $value)
		$Param .= $key.'='.$value.'&'; 
	
	if (stristr($_SERVER['HTTP_HOST'],"pointcom") 
	|| stristr($_SERVER['HTTP_HOST'],"192.168.30.184") 
	|| stristr($_SERVER['HTTP_HOST'],"localpages")
	|| stristr($_SERVER['HTTP_HOST'],"leisure.com")
	|| stristr($_SERVER['HTTP_HOST'],"counselingeducation.com")
	|| stristr($_SERVER['HTTP_HOST'],"yield.com")
	|| stristr($_SERVER['HTTP_HOST'],"1stcreditrepairs.com")
	|| stristr($_SERVER['HTTP_HOST'],"http://1800coupon.com")
	|| stristr($_SERVER['HTTP_HOST'],"rateit.com")){
		$cache = 1;
	}

	if ($cache){
		$mkey = "_msa_ybphonesearch_";
		if ($data['what']){
			$mkey .= "_".md5($data['pN']);
		}
		
		$expire = 3600 * 24 * 3;
		if ($BizResult = lib_YBMemcache::mYBGet()->get($mkey)) {
			if (is_array($BizResult) && count($BizResult) > 0){
				return $BizResult;
			}
		}
	}


	######## LOGS THE REQUEST ########
	//YellowBookLogs($data);

	$BizResult = array();
	###### INIT DOM XML #####
	$YellowBookFeed = new DomDocument();
	$YellowBookFeedUrl = "http://api.yellowbook.com/yb_rest/ReverseLookup.ashx?".$Param;
	if($_GET['debug'] == 'msa123')
		echo '<hr>'.$YellowBookFeedUrl;

	###### CURL & PARSE XML #####
	$CurlData = array(	"url" => $YellowBookFeedUrl,
						"timeout" => '20',
						"login" => 'apirlclp01:zx31kw+23@VkNsa');
	$curl_res = curl_get_contents($CurlData);
	$YellowBookFeed->loadXML($curl_res);
	
	if ($YellowBookFeed->getElementsByTagName("listings")->item(0)){
		$total_count = $YellowBookFeed->getElementsByTagName("listings")->item(0)->getAttribute("count");
		if($total_count>0){
			$Listing = $YellowBookFeed->getElementsByTagName("preferredListing");
			for($i=0; $i<$total_count; $i++){
				$BizResult[$i]['business_id'] = $Listing->item($i)->getAttribute('listingId');
				$BizResult[$i]['business_name'] = $Listing->item($i)->getAttribute("name");
				$BizResult[$i]['ListingType'] = $Listing->item($i)->getAttribute("listingType");
				$BizResult[$i]['address1'] = $Listing->item($i)->getAttribute("address1");
				$BizResult[$i]['address2'] = $Listing->item($i)->getAttribute("address2");
				$BizResult[$i]['city'] = $Listing->item($i)->getAttribute("city");
				$BizResult[$i]['state'] = $Listing->item($i)->getAttribute("state");
				$BizResult[$i]['zip'] = $Listing->item($i)->getAttribute("zip");
				$BizResult[$i]['phone'] = $Listing->item($i)->getAttribute("phone");
		
			}
		}
	}
	return $BizResult;
}

/*
$data_url = array(
	'what' => urlencode("cars"),
	'where' => urlencode("woodland hills, CA"),
	'clientIp' => $_SERVER['HTTP_X_FORWARDED_FOR'],
	'browserAgent' => 'firefox',
	'visitorId' => session_id(),
	'sessionId' => session_id(),
	'Latitude' => "40.7482",
	'Longitude' => "-73.9864",
	'radius'=>5,
	'version' =>'3.0'
	);
	

$data_url = array(

	'what' => urlencode("cars"),

	'clientIp' => "132.168.30.184",

	'browserAgent' => 'firefox',

	'pageNumber' => "1",
	'pageSize' => 100,

	'visitorId' => session_id(),

	'sessionId' => session_id(),

	'sort'		=> $sort,
	
'Address' => urlencode('12 W 48TH ST, New York NY'),
'radius'=>5,
	'version' =>'3.0'

	);
	*/
	/*$data_url = array(
		'what' => urlencode("cars"),
		'where'=>urlencode("woodland hills, ca"),
		'clientIp' => $_SERVER['HTTP_X_FORWARDED_FOR'],
		'browserAgent' => 'firefox',
		'visitorId' => session_id(),
		'sessionId' => session_id(),
		'Latitude' => "34.178189",
		'Longitude' => "-118.623042",
		'radius'=>5,
		'version' =>'3.0'
		);
	$YellowBookBusiness = YellowBookBusinessSearch($data_url);
	var_dump($YellowBookBusiness);
	
	var_dump("----------------------------------------------------------------------------------------");
	
	$data_phone = array(

	'pN' => urlencode("212-348-5151"),

	'clientIp' => "132.168.30.184",

	'browserAgent' => 'firefox',

	'visitorId' => session_id(),

	'sessionId' => session_id(),

	'version' =>'3.0'

	);
	$res = reverse_phone_lookup($data_phone);
	var_dump($res);
	*/
?>
