var theSearchForm;
var maps;

window.addEvent('domready',function(){
	theSearchForm = new SearchForm('searchForm');
	maps = new Maps('map_canvas', 153.1076779, -27.6393129, 12);
	 	
})

var SearchForm = new Class({

    
    initialize: function(e){
		this.databaseType = $('databaseType').get('value');
        this.el = $(e);
        this.captureCategoryChange();
        this.captureFormSubmit();
    },
    
    captureCategoryChange: function(){
		$('categorySelector').addEvent('change', function(event){
			this.fillSubcategoryOptions($('categorySelector').get('value'));
		}.bind(this))
    },
    
    captureFormSubmit: function(){
		$('searchForm').addEvent('submit', function(event){
			this.submitSearchForm();
		}.bind(this))
    },
    
    
    fillSubcategoryOptions: function(categoryID){
    	var req = new Request({	
		url:'/requestCodeMarkup.php',
		async:'false', 
		onSuccess:  function(responseOptions){ 
						$('subcategorySelector').set('html', responseOptions)
					} 
		}).send("content=directorySearch&action=get_subcategory_options&"+this.getQueryString());
    },
    
    
    submitSearchForm: function(){
    	var organisation_name;
    	var address1;
    	var address2;
    	var suburb;
    	var state;
    	var postcode;
    	
		$('searchResults').removeClass('hidden');
		
    	$('searchResults').set('html', 'Searching, please wait.');
    	
    	var myFx = new Fx.Scroll(document).toElement($('searchResults'));
    	
    	var req = new Request({	
		url:'/requestCodeMarkup.php',
		async:'false', 
		onSuccess:  function(response){ 
						maps.clearMarkers();
						var results = JSON.decode(response);
						var length = 0
						
						$('searchResults').empty();
						$('searchResults').setStyle('display','block');
						
						if($('resultContainer')){
							$('resultContainer').setStyle('display','none');
							$('resultContainer').empty();							
						}
						

						results.each(function(organisation, i){
							
							length++;
							//clean results
							
							if(organisation['address1'] == ''){
								address1 = '';
							}else{
								address1 = organisation['address1']+", ";
							}
							
							if(organisation['address2'] == ''){
								address2 = '';
							}else{
								address2 = organisation['address2']+", ";
							}
							
							if(organisation['suburb'] == ''){
								suburb = '';
							}else{
								suburb = organisation['suburb']+", ";
							}
							
							if(organisation['state'] == ''){
								state = '';
							}else{
								state = organisation['state']+", ";
							}
							
							if(organisation['postcode'] == ''){
								postcode = '';
							}else{
								postcode = organisation['postcode'];
							}
							
							// Render Search Result.
							var organisationName = new Element('h3', {'text': organisation['organisation_name']});
							var address = new Element('p', {'html': '<strong>Address: </strong> '+address1+address2+suburb+state+postcode});
						
							//plot marker
							if(organisation['gmap_longitude'] != "" && organisation['gmap_latitude'] != "" && maps.compatible){
								var hasMap = true;
								maps.plotMarker(organisation['organisation_id'], organisation['gmap_latitude'], organisation['gmap_longitude'], '<h2>'+organisation['organisation_name']+'</h2> <p><br />'+organisation['gmap_full_address']+'</p></div>')
							
								var showInMap = new Element('a',{
									'text':'Show in Map',
									'class':'showInMap',
									'events': {
										'click': function(event){
											event.preventDefault();
											maps.showInfo(organisation['organisation_id']);
											var myFx = new Fx.Scroll(document).toElement($('searchResults'));
										}.bind(this)
									}
								});
							
							}else{
								var showOnMap = new Element('span');
								var hasMap = false;
							}
							
							
							var moreInfoLink = new Element('a',{
								'text':'More Information',
								'events': {
									'click': function(event){
										event.preventDefault();
										if(hasMap){
											maps.highlightMarker(organisation['organisation_id']);
											maps.showInfo(organisation['organisation_id']);
										}
										this.showInfo(organisation['organisation_id'], hasMap);
									}.bind(this)
								}
							});	
	
											
							new Element('div', {'class':'a-result'}).adopt([organisationName,address,moreInfoLink,showInMap]).inject($('searchResults'));	
							
						}.bind(this))
						
						if(length == 0){
							$('searchResults').set('html', 'Sorry, no results found.');
						}
						
					}.bind(this)
		}).send("content=directorySearch&action=get_results&"+this.getQueryString());
    },
    
    getQueryString: function(){
    	var queryString = "category_id="+$('categorySelector').get('value');
    	queryString += "&subcategory_id="+$('subcategorySelector').get('value');
    	queryString += "&postcode="+$('postcode').get('value');
    	queryString += "&keyword="+$('keyword').get('value'); 
    	queryString += "&database_type="+this.databaseType;
    	return queryString;
    },
    
    
    showInfo: function(id, hasMap){
		var req = new Request({	
		url:'/requestCodeMarkup.php',
		async:'false', 
		onSuccess:  function(response){ 
						var organisation = JSON.decode(response);
						$('searchResults').toggle(); 
						
						// If there is no result container, make one to drop the result in. 
						if(!$defined(this.resultContainer)){
							this.resultContainer = new Element('div',{
								'id':'resultContainer'
							}).inject($('searchResults'),'after');
						} else {
							this.resultContainer.setStyle('display','block');
						}
						
						// pointing to this.resultContainer to save changing all those ones down there.
						var results = this.resultContainer;
									
						new Element('h1',{'text': organisation['organisation_name']}).inject(results);  
								
						new Element('input', {'type':'button', 'value':'Print', 'class': 'print' }).inject(results).addEvent('click', function(ev){
							window.print();    						
						}.bind(this)) 
						
						new Element('a', {'text':"Back to results", 'class': 'button'}).inject(results).addEvent('click', function(ev){
							results.empty();
							$('searchResults').toggle();
							maps.showAllMarkers()							
						}.bind(this))
						
						new Element('p', {'class': 'clearleft'}).inject(results);
						
						if(organisation['focus_area'] != ''){
							new Element('p',{'html': '<strong>Focus Area:</strong> '+organisation['focus_area']}).inject(results);
						}
						
						if(organisation['phone'] != ''){
							new Element('p',{'html': '<strong>Phone Number:</strong> '+organisation['phone']}).inject(results);
						}
						
						if(organisation['fax'] != ''){
							new Element('p',{'html': '<strong>Fax Number:</strong> '+organisation['fax']}).inject(results);
						}
						
						if(organisation['email'] != ''){
							new Element('p',{'html': '<strong>Email:</strong> <a href="mailto:'+organisation['email']+'">'+organisation['email']}).inject(results);
						}
						
						
						if(organisation['website'] != ''){
							var prefix = "";
							if(organisation['website'].substring(0,7) != 'http://'){
								prefix = "http://"
							}
							new Element('p',{'html': '<strong>Website: </strong><a href="'+prefix+organisation['website']+'" target="_blank">'+organisation['website']+'</a>'}).inject(results);
						}
						
						
						if(organisation['address1'] != '' || organisation['suburb'] != '' || organisation['state'] != ''){
							var address = "";
							
							if(organisation['address1'] != ''){
								address += organisation['address1']+"<br />";
							}
							if(organisation['address2'] != ''){
								address += organisation['address2']+"<br />";
							}
							if(organisation['suburb'] != ''){
								address += organisation['suburb']+"<br />";
							}
							if(organisation['state'] != ''){
								address += organisation['state']+" ";
							}
							if(organisation['postcode'] != ''){
								address += organisation['postcode']
							}
							
							new Element('p',{'html': '<strong>Physical Address:</strong><br />'+address}).inject(results);
						}
						
						
						if(organisation['abn'] != ''){
							new Element('p',{'html': '<strong>ABN:</strong> '+organisation['abn']}).inject(results);
						}
						
						if(organisation['age_group'] != ''){
							new Element('p',{'html': '<strong>Audience Catered For:</strong> '+organisation['age_group']}).inject(results);
						}
						
						if(organisation['service_hours'] != ''){
							new Element('p',{'html': '<strong>Service Hours:</strong> '+organisation['service_hours']}).inject(results);
						}
						
						if(organisation['fees'] != ''){
							new Element('p',{'html': '<strong>Fees:</strong> '+organisation['fees']}).inject(results);
						}
						
						if(organisation['languages'] != ''){
							new Element('p',{'html': '<strong>Languages:</strong> '+organisation['languages']}).inject(results);
						}
						
						if(organisation['specialty_area'] != ''){
							new Element('p',{'html': '<strong>Area of Speciality:</strong> '+organisation['specialty_area']}).inject(results);
						}
						
						if(organisation['additional_information'] != ''){
							new Element('p',{'html': '<strong>Additional Information:</strong> '+organisation['additional_information']}).inject(results);
						}
						
						if(organisation['referral_process'] != ''){
							new Element('p',{'html': '<strong>Referral Process:</strong> '+organisation['referral_process']}).inject(results);
						}
						
						
						
						
						var childrenContainer = new Element('div', {'class':'childrenContainer'}).inject(results);
						
						var i = 0;
						if(organisation['database'] == 'community'){
							var theEvent = organisation['event_results'];
							
							new Element('h3', {'text':'Community Events'}).inject(childrenContainer);
							
							organisation['event_results'].each(function(theEvent){
								i++;
								var date = new Date();
																
								date.set('year', theEvent['year']);
								date.set('mo', 	 theEvent['month']);
								date.set('date', theEvent['date']);

								new Element('div', {'class':'event'}).adopt(
									new Element('p', {'html':'<strong>Event Name: </strong>'+theEvent['event_name']}),
									new Element('p', {'html':'<strong>Date: </strong>'+date.format('%A, %d %B %Y')}),
									new Element('p', {'html':'<strong>Time: </strong>'+theEvent['event_time']}),
									new Element('p').adopt(
										new Element('a', {'text':'more information', 'href':'/events-calendar/'+theEvent['month']+'/#'+theEvent['event_id']})
									)
								).inject(childrenContainer);
							});
							if(i==0){
								new Element('div', {'html':'<p><em>No events available.</em></p>'}).inject(childrenContainer);
							}
							
						}else{
							var theContact = organisation['contact_results'];
							
							new Element('h3', {'text':'Contacts'}).inject(childrenContainer);
							
							organisation['contact_results'].each(function(theContact){
								i++;
								var eventEl = new Element('div', {'class':'contact'}).inject(childrenContainer);
								
								if(theContact['last_name'] != ''){
									new Element('p', {'html':'<strong>Name: </strong>'+theContact['title']+' '+theContact['first_name']+' '+theContact['last_name']}).inject(eventEl);
								}
								
								if(theContact['phone'] != ''){
									new Element('p', {'html':'<strong>Phone: </strong>'+theContact['phone']}).inject(eventEl);
								}
								
								if(theContact['email'] != ''){
									new Element('p', {'html':'<strong>Email: </strong><a href="mailto:'+theContact['email']+'">'+theContact['email']+'</a>'}).inject(eventEl);
								}
								
								if(theContact['category'] != ''){
									new Element('p', {'html':'<strong>Focus Area: </strong>'+theContact['category']}).inject(eventEl);
								}
								
								
								if(theContact['subcategory'] != ''){
									new Element('p', {'html':'<strong>Profession: </strong>'+theContact['subcategory']}).inject(eventEl);
								}							
							})
							if(i==0){
								new Element('div', {'html':'<p><em>No contacts available.</em></p>'}).inject(childrenContainer);
							}
						}
						
						/*
						@todo: get contacts/events also
						*/
						//new Element('p').inject(results);          
				        new Element('a', {'text':"Back to results", 'class': 'button'}).inject(results).addEvent('click', function(ev){
							results.empty();
							$('searchResults').toggle();
							maps.showAllMarkers()							
						}.bind(this))
					
						
						if(hasMap){
							var myFx = new Fx.Scroll(document).toElement($('searchResults'));
						}else{
							var myFx = new Fx.Scroll(document).toElement(results);
						}
						
					}.bind(this)
		}).send("content=directorySearch&action=get_details&organisation_id="+id);	
    }
})

var Maps = new Class({

    initialize: function(map_el, default_latitude, default_longitude, default_zoom){
		
		//setup our local vars
		this.default_longitude = default_longitude;
		this.default_latitude = default_latitude; 
		this.default_zoom = default_zoom;
		this.markers = new Hash();
		this.timerRunning = false;
		
		if (GBrowserIsCompatible()) {
	    	this.compatible = true;

	        //create bounds object 
	        this.bounds = new GLatLngBounds();
	        
	        //create new map object 
	        this.map = new GMap2($(map_el));
	        this.map.setCenter(new GLatLng(this.default_longitude, this.default_latitude), this.default_zoom);

	        //set maps UI (zoom level/buttons/etc)
	        this.map.setUIToDefault();
	               
    	}else{
    		this.compatible = false;
    	}		
    },
    
    plotMarker: function(id, latitude, longitude, info){
    	//check if the browser is compatible
    	if(this.compatible){
	    	    	
	    	//add marker to map
	    	var point = new GLatLng(longitude, latitude);
	    	var overlay_marker = new GMarker(point);
			this.map.addOverlay(overlay_marker);
			
			//stretch bounds of the map to fit the new marker
			this.bounds.extend(overlay_marker.getPoint());
			
			//delay centering the map so that every marker can be plotted before the center is calculated
			this.resetCenterDelay()
				    
			//add a click event to the marker that shows an info window
	    	GEvent.addListener(overlay_marker, "click", function(){
	    		this.showInfo(id);
	    	}.bind(this));
	    	
	    	//add marker variables to the markers hash for later use
	    	this.markers.set(id, {'longitude':longitude, 'latitude':latitude, 'info':info, 'overlay':overlay_marker, 'point':point});
	    	
    	}
    },
    
    resetCenterDelay: function(){
    	if(this.timerRunning){
    		//if timer is already running, clear the timer
        	$clear(this.timer);
        }
        
        //start the timer to center the map in 50ms
    	this.timer = this.centerMap.delay(50, this);
    	this.timerRunning = true;
	},
   
    centerMap: function(){
    	//set zoom and centre of the map to include the newly calculated bounds
	    this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
		this.map.setCenter(this.bounds.getCenter());
    },
    
    
    showInfo: function(id){
    	//check if the browser is compatible
    	if(this.compatible){
	    	
	    	//get marker data from 
	    	var marker = this.markers.get(id);
	    	
	    	//create info marker
    		this.map.openInfoWindowHtml(marker['point'], marker['info']);
    	}
    },
    
    clearMarkers: function(){
    	//check if the browser is compatible
    	if(this.compatible){
	    	
	    	//clear all markers from the map
	    	this.map.clearOverlays();
	    	
	    	//set map center and zoom to the default values
	    	this.map.setCenter(new GLatLng(this.default_longitude, this.default_latitude), this.default_zoom);

	    	//empty markers hash
	    	this.markers.empty();
    	}
    },
    
    highlightMarker: function(id){
    	//get marker data from 
	    var marker = this.markers.get(id);
    	
    	//set map center and zoom to the default values
	    this.map.setCenter(new GLatLng(marker['longitude'], marker['latitude']), 15);
    },
    
    showAllMarkers: function(id){
    	//set zoom and centre of the map to include the newly calculated bounds
	    this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
		this.map.setCenter(this.bounds.getCenter());
    }
});


