<?php
//$langA checked

//	development keys:: 
//	http://wikyblog/include :: ABQIAAAAv_Vq5WwUX1FrEVLMAACe1BSrm2N4mj0PRi9DvgbSCJw3lokWwBTYlLssTPGnpiW2m_r7I627CoTJkQ

defined('WikyBlog') or die("Not an entry point...");



//	A: Normal Page
class CLASSmap extends dbPage{
	// database values
	var $objectType = 'map';
	var $json;
	var $json_abbr;
	var $center_lat;
	var $center_lng;
	
	var $dbValues = array('owner'=>1,'title'=>1,'content'=>1,'json'=>1,'json_abbr'=>1,'center_lat'=>1,'center_lng'=>1);
	var $userValues = array('content'=>1,'keywords'=>1);
	
	function CLASSmap(){
		$this->setDbInfo();
	}
	function newPage(){
		parent::newPage();
		$this->randomMap();
	}
	
	function randomMap(){
		global $langA;
		if( $this->editable ){
			$message = $langA['MAP_DEFAULT_CONTENT'];
		}else{
			$message = $langA['MAP_DEFAULT_CONTENT_PROTECTED'];
		}
		$randLat = mt_rand(34,48).'.'.mt_rand(0,1000000);
		$randLng = '-'.mt_rand(78,119).'.'.mt_rand(0,1000000);
		$this->content = '<map><center lat="'.$randLat.'" lng="'.$randLng.'" level="12" /><marker lat="'.$randLat.'" lng="'.$randLng.'" index="0"><![CDATA['.wbHtmlspecialchars($message).']]></marker></map>';
	}
	

	function setLinks(){
		global $page,$pageOwner;

		parent::setLinks('javascript:wbMaps.load()');
		//$page->regLink($this->editLabel,'javascript:wbMaps.load()');
		$page->regLink('?','Maps?en=Maps');
		$page->displayTitle = toDisplay($this->title);
	}	

	
	
	function outputObj($field=true){
		global $page,$pageOwner,$jsNum,$googleMapKeys;
		global $wbLinkPrefixStor,$userLanguage,$langA,$wbDirPrefix;
		
		
		
		//not the $langA['save'] value!
		if($page->userCmd=='save'){
			return false;
		}
		
		//
		//new
		//
		if( $field === true ){
			$field = $this->uniqLink;
		}
		$linkId = $field;

				
		//
		//old
		//
		// $field = $this->getOutputField($field);
		// $linkId = $page->findLink($field);
		// if( !$linkId ){
		// 	trigger_error('have to have a field');
		// }
		// message('old: '.$linkId);
		
		$linkId = str_replace('&','&amp;',$linkId);
		$linkId = $wbLinkPrefixStor.toStorageUrl($linkId);
		
		
		////////	Script
			$page->css2 = true;
			$page->styles[] = '/include/js/mapsParent.css?'.$jsNum;
			$page->scripts[] = '/include/js/mapsParent.js?'.$jsNum;
			$page->scripts[] = '/include/lang/'.$userLanguage.'/lang.mapsParent.js?'.$jsNum;
			$page->autoForm = true;


		////////	NavBar
			$page->navbar = '<div id="WBnavbar'.$linkId.'" >';
				$page->navbar .= '<h4 class="heading">'.$langA['map'].'</h4>';
				$page->navbar .= '<span style="font-size:83%">';
					$page->navbar .= '<a href="javascript:void(0)" onclick="wbMaps.prev();return false;">'.$langA['previous'].'</a>';
					//$page->navbar .= ' - <a href="javascript:void(0)"  onclick="mf.chText(event,\'takeTour()\',\''.$langA['play'].'\',\''.$langA['stop'].'\');return false;">'.$langA['play'].'</a>';
					$page->navbar .= ' - <a href="javascript:void(0)" onclick="wbMaps.next();return false;">'.$langA['next'].'</a>';
					$page->navbar .= '</span>';
				$page->navbar .= '<div id="WBmarkers'.$linkId.'" class="mapActions"></div><br />';
			$page->navbar .= '</div>';
		
		////////	iFrame
			//needs to be different for sending the toolbar with xmlHttp
			$page->contentB[$field] = '<div><div id="WBmapEdit'.$linkId.'"></div></div>';
			
			
			$key = CLASSmap::getMapKey($server);
			if( $key === false ){
				$page->contentB[$field] .= '<div style="border:1px solid #cccccc;width:100%;margin:0px;padding:3em;" height="500">';
				$page->contentB[$field] .= 'The Google Maps API Key not set for this server: <tt>';
				if( isAdmin(false) ){
					$page->contentB[$field] .= wbLinks::admin('EnableMaps?cmd=new&url='.urlencode($server),$server);
				}else{
					$page->contentB[$field] .= $server;
				}
				
				$page->contentB[$field] .= '</tt></div>';
				
			}else{
				
				$iframeSrc = $server.'/WBmap.php?v='.$jsNum;
				$iframeSrc .= '&amp;key='.$key;
				$iframeSrc .= '&amp;l='.$userLanguage;
				$page->contentB[$field] .= '<iframe id="WBmapFrame'.$linkId.'" name="WBmapFrame'.toStorageUrl($this->uniqLink).'" src="'.$iframeSrc.'" style="border:1px solid #cccccc;width:100%;margin:0px;padding:0px;" frameBorder="0" scrolling="no" height="500"></iframe>';
			}
			

		
		////////	MAP Data
			if( empty($this->json) ){
				if( empty($this->content) ){
					$this->randomMap();
				}
				$page->contentXml[$linkId] = $this->content;
			}else{
				$page->contentB[$field] .= '<input type="hidden" name="json" value="'.htmlspecialchars($this->json).'" />';
				//$page->contentB[$field] .= '<textarea style="display:none" name="json" >'.htmlspecialchars($this->json).'</textarea>';
			}
			
		return $field;
	}
	
	//return the appropriatte key
	function getMapKey(&$server){
		global $googleMapKeys;
		$key = false;
		if( isset($_SERVER['HTTP_HOST']) ){
			$server = 'http://'.$_SERVER['HTTP_HOST'];
		}else{
			$server = 'http://'.$_SERVER['SERVER_NAME'];
		}
		
		//new keys (for the whole domain)
		if( isset($googleMapKeys[$server]) ){
			$key = $googleMapKeys[$server];
		}
		
		//finish setting $server variable
		if( !empty($wbDirPrefix) ){
			$server .= $wbDirPrefix;
		}
		$server = $server.'/include';
		if( $key ){
			return $key;
		}
		
		//old keys (for directory only)
		if( isset($googleMapKeys[$server]) ){
			return $googleMapKeys[$server];
		}
		return false;
	}
	
	function doActions(){
		global $page,$langA;
		
		switch( $page->userCmd ){
			case 'customedit':
				$this->editMapValues();
			return;
			
			case 'save':
			case wbStrtolower($langA['save']):
				$this->saveChanges();
			return;
			
			
			//!!hack ... but it works!!
			case 'show':
			case 'revision':
				$page->userCmd = 'stop';
				includeFile('tool/History1.php');
				$link = '<a href="javascript:void(0)" onclick="wbMaps.load();return false;" >'.$langA['edit_revision'].'</a>';
				showRevision($link);
			return; //don't do the normal stuff
			case 'data':
				$this->GPX();
			return;
			
		}
		parent::doActions();
	}
	
	function saveChanges(){
		includeFile('tool/SavePage.php',false); 
		if( !cookies() ){
			message('COOKIES_REQUIRED');
			return;
		}
		
		//checks $This->editable and calls $this->checkData(), $this->setFromPost()
		if( !objectSave::saveControl($this) ){
			//message('OOPS');
		}else{
			message('SAVED_FILE');
		}
	}

	function GPX(){
		global $page,$langA,$jsNum;
		// Send a map page without the edit values if the map isn't already loaded
		if( !isset($_GET['wb'])){
			$link = wbLinks::local($this->uniqLink,'Not Loaded');
			$page->contentB[$this->uniqLink] = '<p>'.wbLang::text('MAP_MUST_BE_LOADED').$link.'</p>';
			return;
		}
		
		// send Map GPX script
		$page->scripts[] = '/include/js/maps_gpx.js?'.$jsNum;
	}
	
	//	Edit Values
	//
	//
	function editValues(){
		$this->outputObj();
	}
	function editMapValues(){
		global $page,$pageOwner,$jsNum,$langA;
		
		includeFile('tool/EditPage.php');
		initEdit::init();
		
		// send Map Editing HTML
		//
		$page->scripts[] = '/include/js/editingAll.js?'.$jsNum;
		$page->scripts[] = '/include/js/mapsParentEdit.js?'.$jsNum;
		
		$tabUrl = $_GET['wb']['u']; //url of the shown page

		//loads the table that has New Marker, New Route, GPX Data...
		

		$toolbar = '<div id="WBmapEdit'.$tabUrl.'">';
		
		$toolbar .= '<div id="WBmapEdit1'.$tabUrl.'">';
			$toolbar .= '<table border="0" style="margin:0;padding:0;" class="WBtoolbar">';
			$toolbar .= '<tr>';
				$toolbar .= '<td class="mapEditing" style="vertical-align:top;">';
					$toolbar .= ' <a href="javascript:void(0)" onclick="olE.find();return false;">'.$langA['search'].'</a>';
					$toolbar .= ' <a href="javascript:void(0)" onclick="olE.m_New();return false;">'.$langA['new_marker'].'</a>';
					$toolbar .= ' <a href="javascript:void(0)" onclick="olE.p_New();return false;">'.$langA['new_route'].'</a>';
					$toolbar .= ' <a href="javascript:void(0)" onclick="olE.gpx();return false;">'.$langA['gpx_data'].'...</a>';
					$toolbar .= ' <a href="javascript:void(0)" onclick="olE.showBoxes(\''.addcslashes($tabUrl,'"\'').'\',2);return false;">'.$langA['save'].'...</a>';
				$toolbar .= '</td>';
				$toolbar .= '<td style="overflow:hidden;text-align:right;">';
					$toolbar .= '<div id="WBmapInfo'.$tabUrl.'" class="sm" style="overflow:hidden">';
					$toolbar .= '</div>';
				$toolbar .= '</td>';
				$toolbar .= '<td class="sm" style="text-align:center !important;width:15ex;">';
					$toolbar .= '<a href="javascript:void(0)" id="WBunits'.$tabUrl.'" onclick="olE.cUnits();return false;">'.$langA['miles/km'].'</a>';
	 			$toolbar .= '</td>';
	 		$toolbar .= '</tr>';
	 		$toolbar .= '<tr>';
		 		$toolbar .= '<td colspan="3" id="WBmapEditOpt'.$tabUrl.'">';
		 		$toolbar .= '</td>';
	 		$toolbar .= '</tr>';
			$toolbar .= '</table>';
		$toolbar .= '</div>';
		
		
		$toolbar .= '<div id="WBmapEdit2'.$tabUrl.'" style="display:none">';
		//$toolbar .= '<h3 class="heading" id="WBmapSave'.$tabUrl.'">'.$langA['SAVE_HEADER'].'</h3>';
		$toolbar .= '<table class="WBtoolbar"><tr>';
		$toolbar .= '<td><a href="javascript:void(0)" onclick="olE.save(\''.$tabUrl.'\');return false;" class="WBbutton">'.$langA['save_map'].'</a></td>';
		$toolbar .= '<td><a href="javascript:void(0)" onclick="olE.showBoxes(\''.addcslashes($tabUrl,'"\'').'\',1);return false;" class="WBbutton">'.$langA['continue_editing'].'</a></td>';
		$toolbar .= '<td style="text-align:right">';
		
		$toolbar .= '<input type="hidden" name="cmd" value="save" />';
		$toolbar .= '<div id="WBinputs'.$tabUrl.'" style="display:none"></div>';
		
		//	auto complete keywords:
		//		similar to toolEditPage.php
		//
		$keyArray = array();
		if(empty( $this->keywords ) ){
			$temp = '('.wbHtmlspecialchars($langA['DEFAULT_KEYWORD_FIELD']).')';
		}else{
			$temp = wbStr_replace(',',', ',$this->keywords).',';
			foreach($pageOwner['keywords'] as $key => $num){
				$keyArray[] = $key;
			}
		}		

		$toolbar .= '<input type="hidden" name="keyList" value="'.wbHtmlspecialchars(implode(',',$keyArray)).'" />';
		$toolbar .= $langA['tags'].': <input onfocus="WBe.create(this,\''.wbHtmlspecialchars($pageOwner['username']).'\')" onkeyup="WBe.show()" onblur="WBe.blur()" type="text" size="60" title="('.wbHtmlspecialchars($langA['DEFAULT_KEYWORD_FIELD']).')" class="WBinputText" maxlength="200" name="keywords" value="'.$temp.'" />';
		
		$toolbar .= '<br/>';
		$toolbar .= $langA['summary'].' <input type="text" size="60" class="WBinputText" maxlength="200" name="summary" value="" />';
		$toolbar .= '</td></tr></table>';
		$toolbar .= '</div>'; //end save box
		
		
		//space for GPX
		$toolbar .= '<div id="WBmapEdit3'.$tabUrl.'" style="display:none">';
			$toolbar .= '<table class="WBtoolbar"><tr>';
			$toolbar .= '<td class="mapEditing" style="width:11em" id="gpxControls">';
				$toolbar .= '<b>'.$langA['gpx_data'].'</b> &nbsp; ';
				$toolbar .= ' <a href="javascript:void(0)" onclick="export_gpx();return false;">'.$langA['export'].'</a>';
				$toolbar .= ' <a href="javascript:void(0)" onclick="import_gpx();return false;">'.$langA['import'].'</a>';
				$toolbar .= ' <a href="javascript:void(0)" onclick="clear_data();return false;">'.$langA['reset'].'</a>';
				$toolbar .= ' <a href="javascript:void(0)" onclick="olE.showBoxes(\''.addcslashes($tabUrl,'"\'').'\',1)">'.$langA['continue_editing'].'</a>';
				$toolbar .= '</td>';
				$toolbar .= '<td style="text-align:right" class="mapEditing">';
				$toolbar .= '<a href="http://www.topografix.com/gpx.asp">'.$langA['gpx_exchange_format'].'</a>';
				$toolbar .= '</td>';
			$toolbar .= '</tr>';
				
			$toolbar .= '<tr>';
			$toolbar .= '<td colspan="2">';
				$toolbar .= '<div class="WBeditArea2">';
				$toolbar .= '<table class="WBwrapTextarea" width="100%"><tr><td>'; //used because of explorer, otherwise textareas change size when editing
				$toolbar .= '<textarea id="mapData" style="width:100%" rows="8" class="WBtextarea"></textarea>';
				$toolbar .= '</td></tr></table>';
				$toolbar .= '</div>';
				$toolbar .= '</td></tr></table>';		
		$toolbar .= '</div>';
		$toolbar .= '</div>';
		

		$addContent = new content();
		$addContent->aa = 'addcontent';
		$addContent->bb = 'WBmapEdit';
		$addContent->cc = $tabUrl;
		$addContent->dd = $toolbar;
		$page->contentClasses[] = $addContent;
	}
	
	function JSON_ENCODE($array){
		$result_array = array();
		foreach($array as $key => $value){
			if( is_array($value) ){
				$result_array[] = $this->JSON_ESCAPE($key).':'.$this->JSON_ENCODE($value);
			}elseif( is_int($value) || is_float($value) ){
				$result_array[] = $this->JSON_ESCAPE($key).':'.$value;
			}else{
				$result_array[] = $this->JSON_ESCAPE($key).':'.$this->JSON_ESCAPE($value);
			}
		}
		$result = '{';
		$result .= implode(',',$result_array);
		$result .= '}';
		return $result;
	}
	
	
	function JSON_ESCAPE(&$txt){
		$txt = '"'.addcslashes($txt,'"\\').'"';
		return str_replace(array("\r\n","\r","\n"),array('\n','\r','\n'),$txt);
	}
	
	function setFromPost(){
		global $wbParser;
		initiateParser();

		
		//Try JSON
		$JSON = array();
		
		//ex 
		// 	(-119.32989120483398, 36.320381127477916)
		// (-119.36731338500977, 36.326743155386225),(-119.36731338500977, 36.29824829011859),(-119.31375503540039, 36.29880168761798)
		
		////////	Map Type
			$type = 0;
			if( is_numeric($_POST['mapType']) ){
				$type = $_POST['mapType'];
			}
		


		////////	ZOOM
			if( !isset($_POST['zoom']) ){
				trigger_error('Invalid Map Data: No Zoom Level.');
				$this->validData = false;
			}else{
				if( !is_numeric($_POST['zoom']) ){
					trigger_error('Invalid Map Data: Invalid Zoom Value');
					$zoom = '4';
				}else{
					$zoom = $_POST['zoom'];
				}
			}		
			
			$center = false;
			$JSON['mtype'] = $type;
			$JSON['level'] = $zoom;
			$JSON_ABBR = $JSON;
			
			
		
		////////	POINTS
			if( isset($_POST['npts']) && is_array($_POST['npts']) ){
				$index = 0;
				
				foreach($_POST['npts'] as $key => $pt){
					
					$description = $this->getDescription($key);
						
					if( is_array($pt[0]) ){
						////////////	PLines
						
						
						$JSON_TMP = array();
						$JSON_TMP['pts'] = array();
						$JSON_TMP['desc'] = $description;
						$JSON_TMP['ol'] = 'poly';
			 			foreach($pt as $linePt){
				 			if( !$center ){
					 			$center = array($linePt[0],$linePt[1]);
				 			}
							$JSON_TMP['pts'][] = array($linePt[0],$linePt[1]);
						}
						
						$JSON_TMP_ABBR = array();
						$JSON_TMP_ABBR['desc'] = $description;
						$JSON_TMP_ABBR['ol'] = 'poly';
						
						
					}else{
						////////////	Markers
						
							if( !$center ){
					 			$center = array($pt[0],$pt[1]);
					 			
				 			}

						
						$JSON_TMP = array();
						$JSON_TMP['pt'] = array($pt[0],$pt[1]);
						$JSON_TMP['desc'] = $description;
						$JSON_TMP['ol'] = 'mark';
						
						
						$JSON_TMP_ABBR = array();
						$JSON_TMP_ABBR['pt'] = array($pt[0],$pt[1]);
						$JSON_TMP_ABBR['desc'] = $description;
						$JSON_TMP_ABBR['ol'] = 'mark';
						
					}
					$JSON['olay'][] = $JSON_TMP;
					
					if( $index < 5 ){
						$JSON_ABBR['pts'][] = $JSON_TMP_ABBR;
					}
					$index++;
				}
			}
			
			
		////////	CENTER
			if( !$center ){
				if( isset($_POST['c2'])){
					$JSON['center_lat'] = $_POST['c2'][0];
					$JSON['center_lng'] = $_POST['c2'][1];
				}else{
					trigger_error('Invalid Map Data: No Center');
					$this->validData = false;
					$JSON['center_lat'] = "37.441944";
					$JSON['center_lng'] = "-122.141944";
				}
				
			}else{
				$JSON['center_lat'] = $center[0];
				$JSON['center_lng'] = $center[1];
			}
			$this->center_lat = $JSON['center_lat'];
			$this->center_lng = $JSON['center_lng'];
			
		ob_start();
		var_export($JSON);
		$this->content = wb::get_clean();
		
		$this->json = $this->JSON_ENCODE($JSON);
		$this->json_abbr = serialize($JSON_ABBR);
		
		parent::setFromPost(); //after, otherwise the pts array will be turned into a comma list
		
	}//end function
	
	function checkData($warn=true){
		//hmm..
		$this->getParserInfo();
	}
	
	function getDistance($Alat,$Alng,$Blat,$Blng){
		$radius = 6371; // earth's mean radius in km
		$dist = acos(
					sin( deg2rad($Alat) )
					*
					sin( deg2rad($Blat) )
					+
					cos( deg2rad($Alat) )
					*
					cos( deg2rad($Blat))
					*
					cos( deg2rad($Alng-$Blng) )
					) * $radius;
		return $dist;
	}
	
	function getDescription($key){
		global $wbParser;
		//initiateParser(); done by CLASSmap::setFromPost();
		
		
		if( empty($_POST['desc'][$key]) ){
			return '';
		}
		if( wbStrlen($_POST['desc'][$key]) > 1000){
			message('MAP_LONG_DESCRIPTION');
			$_POST['desc'][$key] = wbSubstr($_POST['desc'][$key],0,1000);
		}
		
		$stripped = $wbParser->parseXML($_POST['desc'][$key],false,$this,true);
		
		if( $wbParser->errors ){
			$this->validData = false;
		}
		return $stripped;
	}
	
	/*
	http://maps.google.com/staticmap?&center=38.459712,-102.178961&zoom=13&size=300x250&markers=38.459712,-102.178961,reda&key=ABQIAAAAv_Vq5WwUX1FrEVLMAACe1BTo1E6uurzpZZHahHuqLyE6TJQq5BRjQpqiiPWxXsraCEaC_-oRx_57PQ
	*/
	
	function abbrevOutput(&$row){
		global $langA,$page;
		
		parent::abbrevOutputHeader($row);
		
		// $thumb = '/imgs/maps/map.png';
		// $img = '<img width="300" src="'.wbLinks::getDir($thumb).'"  align="left"  class="wikiImg wikiImgLeft" alt="Map" />';
		// echo wbLinks::local($row->uniqLink,$img);

		
		//get the data
		$marks = array('A','B','C','D','E','F');
		if( !empty($row->json_abbr) ){
			$data = unserialize($row->json_abbr);
			
			$abbrevMaxDist = pow(2,(24-$data['level']))/1000; //approximation
			
			
			$textA = array();
			$markers = array();
			foreach($data['pts'] as $olay){
				
				if( $olay['ol'] == 'poly' ){
					$img = '/imgs/maps/line.png';
				}else{
					$letter = array_shift($marks);
					$img = '/imgs/maps/marker' . $letter . '.png';
					
		 			//show which markers
		 			$dist = CLASSmap::getDistance($row->center_lat,$row->center_lng,$olay['pt'][0],$olay['pt'][1]);
		 			//$dist = CLASSmap::getDistance($data['center_lat'],$data['center_lng'],$olay['pt'][0],$olay['pt'][1]);
		 			if( $dist < $abbrevMaxDist ){
			 			$markers[] = $olay['pt'][0].','.$olay['pt'][1].',red'.strtolower($letter);
		 			}					
				}
				
				$text = '<div>';
				$text .= '<img src="'.wbLinks::getDir($img).'" style="vertical-align:bottom;margin:1em 1em .4em .4em"  alt="marker" />';
				$text .= $olay['desc'];
				$text .= '</div>';
				$textA[] = $text;
			}
			
			
			//Start The Static Map
			//	REQUIRED: size, center, zoom, key
			$googleImg = '';
			if( count($markers) < 1 ){
				$googleImg .= 'center='.rawurlencode($data['center_lat'].','.$data['center_lng']);
			}else{
				$googleImg .= 'markers='.rawurlencode(implode('|',$markers));
			}
			$googleImg .= '&amp;zoom='.rawurlencode($data['level']);
			$googleImg .= '&amp;size=300x250';
			$googleImg .= '&amp;key='.rawurlencode(CLASSmap::getMapKey($server));
			
			$img = '<img width="300" height="250" src="http://maps.google.com/staticmap?'.$googleImg.'" align="left"  class="wikiImg wikiImgLeft" alt="Map" />';
	 		echo wbLinks::local($row->uniqLink,$img);
			echo implode("\n",$textA);
		}
		
		echo '... '.wbLinks::local($row->uniqLink,$langA['read_more']);
			
		echo '<div style="clear:both"></div>';
		echo '<br />';
	}	
	
	
}

			
			
			
			
