<?php

/**
 * 
 *
 * @version $Id$
 * @copyright 2003 
 **/

class rhc_gmap_venue_fields {
	function __construct(){
		add_filter('rhc_venue_meta',array(&$this,'rhc_venue_meta'),10,1);
		add_filter('rhc_event_term_meta',array(&$this,'rhc_event_term_meta'),10,3);
		
		add_action('add_tag_form_pre', array(&$this,'add_tag_form_pre'), 10, 1);
		add_action(RHC_VENUE . '_pre_edit_form', array(&$this,'pre_edit_form'), 10, 2);		
		
		add_filter('rhc_gmap_marker_sources', array(&$this,'marker_sources'), 10, 1 );
	}
	
	function marker_sources($sources){
		$plugin_root = RHCGMAP_PATH.'css/markers/';
		$plugins_dir = @ opendir( $plugin_root);
		if ( $plugins_dir ) {
			while (($file = readdir( $plugins_dir ) ) !== false ) {
				if ( substr($file, 0, 1) == '.' )
					continue;
				if ( is_dir( $plugin_root.'/'.$file ) ) {
					continue;
				} else {
					if( false!==strpos($file,'@2x'))continue;//ignore retina version files
					if ( substr($file, -4) == '.png' )
						$sources[] = RHCGMAP_URL.'css/markers/'.$file;
				}
			}
			closedir( $plugins_dir );
		}
		
		sort($sources,SORT_STRING);

		return $sources;
	}
	
	function use_ssl(){
		//bug fix, some sites with mixed https, the is_ssl function is not returning correctly.
		global $rhc_plugin;
		if( '1' == $rhc_plugin->get_option( 'force_addon_https', '0', true ) ){
			return true;
		}		
		//--end bug fix.
		return is_ssl() ? true : false;
	}
	
	function rhc_event_term_meta($new, $term_id, $taxonomy){
		if($taxonomy==RHC_VENUE){
			$new = is_object($new) ? $new : (object)array() ;
			$green = get_term_meta($term_id,'marker_inactive',true);
			$green = $this->use_ssl() ? str_replace('http:','https:',$green) : $green;
			if($green!=''){
				$new->marker_inactive = $green;
			}
			$red = get_term_meta($term_id,'marker_active',true);
			$red = $this->use_ssl() ? str_replace('http:','https:',$red) : $red;
			if($red!=''){
				$new->marker_active = $red;
			}		
			$val = get_term_meta($term_id,'marker_size',true);
			if($val!=''){
				$new->marker_size = $val;
			}				
		}
		
		return $new;
	}
	
	function rhc_venue_meta($fields){
		global $rhc_plugin;
		$markers = apply_filters('rhc_gmap_marker_sources',array());
		$encoded_markers = htmlspecialchars(json_encode($markers));
		
		$fields = is_array($fields)?$fields:array();
		$fields[]=	(object)array(
				'label'			=> __('Google Map view','rhcgmap'),
				'type'			=> 'subtitle'
		);		
		$fields[]=(object)array(
				'id'	=> 'marker_inactive',
				'label'	=> __('Inactive Map Marker','rhctc'),
				'el_properties' => array('class'=>'rhc_marker_picker','data-markers'=>$encoded_markers)
		);
		$fields[]=(object)array(
				'id'	=> 'marker_active',
				'label'	=> __('Active Map Marker','rhctc'),
				'el_properties' => array('class'=>'rhc_marker_picker','data-markers'=>$encoded_markers)
		);
		$fields[]=(object)array(
				'id'	=> 'marker_size',
				'label'	=> __('Marker size','rhctc'),
				'el_properties' => array('class'=>'rhc_marker_size'),
				'description' => __('Comma separated dimension for the icon.  Example: 36,48','rhctc')
		);
		
		$venue_taxonomies = $rhc_plugin->get_option( 'venue_directory', array(), true );
		if(is_array($venue_taxonomies) && count($venue_taxonomies)>0){
			$fields[]=	(object)array(
					'label'			=> __('Business directory filters','rhcgmap'),
					'type'			=> 'subtitle'
			);	

			foreach( $venue_taxonomies as $name){
				if( $t = get_taxonomy($name) ){			
					$fields[]=(object)array(
							'id'		=> 'custom_filter',
							'label'		=> $t->label,
							'taxonomy'	=> $name,
							'el_properties' => array('data-taxonomy'=>$t->name),
							'type'	=> 'callback',
							'callback' => array(&$this,'cb_taxonomy_terms')
					);				
				}		
			}
		}
		
		return $fields;
	}

	function cb_taxonomy_terms($tab,$i,$o,$r){
		$value = $r->get_value($tab,$i,$o);
		$options = get_terms( array($o->taxonomy), array('hide_empty'=>false) );
		$name = sprintf('%s[%s][]', 
			$r->get_name($tab,$i,$o),
			$o->taxonomy
		);
		$out = sprintf("<select multiple=\"multiple\" name=\"%s\">\n",
			$name
		);
		
		$configured_taxonomies = is_array($value) && isset($value[$o->taxonomy]) && is_array($value[$o->taxonomy]) ? $value[$o->taxonomy] : array();
		
		foreach($options as $opt){	
			$selected = in_array( $opt->slug, $configured_taxonomies ) ? 'selected="selected"' : '';
			$out.= sprintf("<option %s value=\"%s\">%s</option>\n",
				$selected,
				$opt->slug,
				$opt->name
			);
		}
		$out.= "</select>\n";
	
	
	//echo "value: ".print_r($value,true)."<br>";
	/*
	echo $name	;
	echo "<pre>";
	print_r($o);
	print_r($options);
	echo "</pre>";	
	*/
		return $out;
	}
	
	
	function add_tag_form_pre(){
		$this->head();
	}
	
	function pre_edit_form(){
		$this->head();
	}
	
	function head(){
?>
<script type='text/javascript'>
jQuery(document).ready(function($){
    $('.rhc_marker_picker').each(function(i,el){
		var markers = $(el).data('markers');
		if( markers.length>0 ){
			$('<div class="rhc_marker_helper"></div>').insertBefore(el);
			var holder = $(el).parent().find('.rhc_marker_helper');
			$.each(markers,function(i,m){
				_class='helper-marker';
				if(m==$(el).val()){
					_class+=' chosen-one';
				}
				$('<a href="javascript:void(0);"></a>')
					.append( $('<img>').attr('src',m) )
					.addClass(_class)
					.appendTo(holder)
					.click(function(e){
						$(el).val( $(this).find('img').attr('src') );
						holder.find('.chosen-one').removeClass('chosen-one');
						$(this).addClass('chosen-one');
						
						if( $('.rhc_marker_size').val()=='' ){
							$('.rhc_marker_size').val( $(this).find('img').width() + ',' + $(this).find('img').height() );
						}
						//
					})
				;
			});
			holder
				.click(function(e){
					$(this).toggleClass('helper-open');
				})
			;
			
			if( holder.find('.chosen-one').length==0 ){
				holder.find('.helper-marker').first().find('img').addClass('chosen-one');
			}
		}
	});
	
	//-----
	$('#gaddress').before('<div id="gmap-helper-holder" class="gmap-helper-holder"></div>')
	;
	
	$('#gaddress')
		.wrap('<div class="gmap-helper-tools">')
		.before('<div class="gmap-tool-btn"><input type="button" class="btn-agmap-search button button-secondary" value="Open map" /></div>')
		.wrap('<div class="gmap-tool-address" />')
	;
	
	$('#gmap-helper-holder')
		.append('<div id="gmap-helper" class="gmap-helper-holder"></div>')
		.append('<div class="gmap-helper-clear"></div>')
		.append('<div id="gmap-helper-msg">')
		.append('<div id="gmap-helper-tools" class="gmap-helper-tools">' +
		'<div class="gmap-tool-btn"><input id="search_btn" type="button" class="button button-secondary"  value="search" /></div>' +
		'<div class="gmap-tool-address"><input id="search_gaddress" type="text" name="search_gaddress" value="" /></div>' +
		'</div>')
		
	;
	
	$('.btn-agmap-search').click(function(e){
		$('#gmap-helper-holder').toggleClass('gmap-helper-open');
		if( $('#gmap-helper-holder').hasClass('gmap-helper-open') ){
			$('#gmap-helper-holder').addClass('gmap-started');
			var map_options = {
			    zoom: 1
			  };			
	        $('#gmap-helper').gmap3({
				map:{
	    			options: map_options
				}
			});
			
			var map = $('#gmap-helper').gmap3("get");
			google.maps.event.addListener(map, 'click', function(event) {
				//----------
			  	$('#gmap-helper').gmap3({clear: 'custom_marker'});
				//----------
	
				var marker;
				marker = {
					id: 'custom_marker',
					latLng: event.latLng,
					draggable: true,
					animation: google.maps.Animation.DROP,
					data: {
						label: 'Click to select',
						latLng: event.latLng
					}
				}
								
				$( '#gmap-helper' ).gmap3({		
					marker : {
						values:[marker],		
						events : {
							/*mouseover*/
							click: function(marker, event, context){ 											

								$('#gaddress').val( '' );
								$('#glat').val( context.data.latLng.lat() );
								$('#glon').val( context.data.latLng.lng() );
								
								$('#gmap-helper-holder').removeClass('gmap-helper-open');
							},
							mouseover: function(marker, event, context){
								var map = $(this).gmap3("get"),
									infowindow = $(this).gmap3({get:{name:"infowindow"}});
								if (infowindow){
								  infowindow.open(map, marker);
								  infowindow.setContent(context.data.label);
								} else {
								  $(this).gmap3({
								    infowindow:{
								      anchor:marker, 
								      options:{
									  	content: context.data.label,
									  	disableAutoPan:true
										}
								    }
								  });
								}	
							},
							mouseout: function(marker, event, context){
								var infowindow = $(this).gmap3({get:{name:"infowindow"}});
								if (infowindow){
									infowindow.close();
								}
							}		
						}
					}			
				});	
				//----------
			});			
		}
	});
	
	$('#search_btn').click(function(){
		var address = $('#search_gaddress').val();
		//---- search
		var geo = new google.maps.Geocoder;
		geo.geocode({'address':address},function(results, status){
			if (status == google.maps.GeocoderStatus.OK) {
				var markers = [];
				$.each(results,function(i,r){
					
					var coords = new google.maps.LatLng(
						r['geometry']['location'].lat(),
						r['geometry']['location'].lng()
					);
				
					var marker;
					marker = {
						latLng: coords,
						data: {
							label: r.formatted_address,
							latLng: coords
						}
					}
					markers.push(marker);
				});
				

				
				$( '#gmap-helper' ).gmap3({		
					marker : {
						values:markers,		
						events : {
							/*mouseover*/
							click: function(marker, event, context){ 											
								
								$('#gaddress').val( context.data.label );
								$('#glat').val( context.data.latLng.lat() );
								$('#glon').val( context.data.latLng.lng() );
								
								$('#gmap-helper-holder').removeClass('gmap-helper-open');
							},
							mouseover: function(marker, event, context){
								var map = $(this).gmap3("get"),
									infowindow = $(this).gmap3({get:{name:"infowindow"}});
								if (infowindow){
								  infowindow.open(map, marker);
								  infowindow.setContent(context.data.label);
								} else {
								  $(this).gmap3({
								    infowindow:{
								      anchor:marker, 
								      options:{
									  	content: context.data.label,
									  	disableAutoPan:true
									  }
								    }
								  });
								}	
							},
							mouseout: function(marker, event, context){
								var infowindow = $(this).gmap3({get:{name:"infowindow"}});
								if (infowindow){
									infowindow.close();
								}
							}		
						}
					}			
				});	

				if(markers[0]){
					$( '#gmap-helper' ).gmap3("get").panTo( markers[0].latLng );
					$( '#gmap-helper' ).gmap3("get").setZoom(12);
				}
			} else {
				var _msg = "Geocode was not successful for the following reason: " + status;
				$('#gmap-helper-msg').empty().html(_msg).addClass('error').show();
			}
		});
		//-------
	});
	

});

function getLatLong(address){

}
</script>
<?php
	}
}
?>