window.addEvent('domready', function() {
	prepareSearchBox();
	init();
	load();
});
window.addEvent('resize', function() {
	prepareFrame();
	if (typeof(map)==='object' && typeof(map.checkResize)==='function') { map.checkResize(); }
});

function init() {
	prepareFrame();
	prepareCatSelect();
}

function prepareFrame() {
	window_height = getWindowHeight().toInt(); 
	header_height = $('header').getStyle('height').toInt(); 
	shadow_height = $('mainnav_shadow').getStyle('height').toInt() + 2; 
	mapinfo_height = $('map_info').getStyle('height').toInt() + 20; 
	$('categories').style.height = (window_height - header_height - shadow_height - 10) + 'px';
	$('listings').style.height = (window_height - header_height - shadow_height - 37) + 'px';
	$('mapzone').style.height = (window_height - header_height - shadow_height - mapinfo_height) + 'px';
}

function prepareCatSelect() {
	var headings = $$('#category_results ul li a.toggle');
	var list = $$('#category_results ul li ul');
	headings.each( function(heading, i) {
		var slidey = new Fx.Slide(list[i]);	
		slidey.hide();
		heading.addEvent('click', function(e){
			if (heading.hasClass('expand')) {
				heading.className = 'toggle collapse';
			} else {
				heading.className = 'toggle expand';
			}
			e.stop();
			slidey.toggle();
		});
	});
}

function getWindowHeight() {
	myHeight = 0;
	if( typeof( window.innerHeight ) == 'number' ) {
		myHeight = window.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight ) {
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function showLoadingMessage(elem_id) {
	var elem = $(elem_id);
	if (elem) {
		elem.set('html','<div class="boxpadding"><div class="icon-loading">Loading... Please Wait...</div></div>');
		prepareFrame();
	}
}

function showSelectListingMessage() {
	var elem = $('map_info');
	if (elem) {
		var or_markers = ''; var i = 0;
		for (i in listing_markers) i++;
		if (i>0) or_markers = ' or a marker';
		elem.set('html','<div class="boxpadding"><div class="tobegin">Please select a listing'+or_markers+'.</div></div>');
		prepareFrame();
	}
}

function getCategories() {
	showLoadingMessage('categories');
	var req = new Request({
		url: 'api.php?a=getcat&d=' + $('dir_select').value,
		link: 'cancel',
		onSuccess: function(txt){ 
			$('categories').innerHTML = txt; prepareFrame(); prepareCatSelect(); },
		onFailure: function(){ $('categories').innerHTML = 'The request failed.'; }
	});
	req.send();
}

function getListings(dir,cat,subcat) {
	expandResultsPane();
	showLoadingMessage('listings');
	showLoadingMessage('map_info');
	var req = new Request({
		url: 'api.php?a=getlistings&d=' + dir + '&c=' + cat + '&s=' + subcat,
		link: 'cancel',
		onSuccess: function(txt){ 
			//txt = txt.replace(/^\s+|\s+$/g,"");
			$('listings').innerHTML = txt;
			showSelectListingMessage();
			prepareFrame();
		}, onFailure: function(){ $('listings').innerHTML = 'The request failed.'; }
	});
	req.send();
}

function expandResultsPane() {
	if ($('listing_pane').getStyle('display') == 'none') {
		$('listing_pane').style.display = 'block';
		$('map_pane').style.marginLeft = '444px';
		map.checkResize();
		map.panTo(new GLatLng(-36.427895, 145.415235));
	}
	prepareFrame(); 
}

function clearMarker(listing_id) {
	map.removeOverlay(listing_markers[listing_id].marker_ref);
	clearListingHighlights();
	delete listing_markers[listing_id];
	showSelectListingMessage();
	prepareFrame();
}

function clearAllMarkers() {
	for (listing_id in listing_markers) {
		map.removeOverlay(listing_markers[listing_id].marker_ref);
	}
	delete listing_markers;
	clearListingHighlights();
	window.listing_markers = new Object();
	showSelectListingMessage();
	prepareFrame();
}

function clearListingHighlights() {
	$$('#listings .active').removeClass('active');
}

function highlightListing(id_to_highlight) {
	clearListingHighlights();
	if ($('listing'+id_to_highlight)) $('listing'+id_to_highlight).addClass('active');
}

function showListing(listing_id) {
	
	if (typeof listing_markers[listing_id] === 'undefined') {
		
		showLoadingMessage('map_info');
		
		var req = new Request({
			url: 'api.php?a=getlisting&l=' + listing_id,
			link: 'cancel',
			onSuccess: function(response){ 
				response = response.split('[[[[[SEPARATOR]]]]]');
				//.replace(/^\s+|\s+$/g,"") not sure what this was for, doesn't seem to be doing anything
				
				var listinginfo = new Element('div',{
												id: 'listinginfo'+listing_id,
												'class': 'listinginfo'
											  });
				
				var listingname = new Element('div',{ 'class': 'name', html: response[0] });
				var listingaddr = new Element('div',{ 'class': 'address', html: response[1] });
				var removemarker = new Element('a',{
									   href:'#',
									   'class':'removemarker',
									   html:'Remove marker',
									   events: {
										   'click': function(event) {
												event.preventDefault();
												clearMarker(listing_id);
										   }
									   }
									});
				var removeallmarkers = new Element('a',{
									   href:'#',
									   'class':'removeallmarkers',
									   html:'Remove all markers',
									   events: {
										   'click': function(event) {
												event.preventDefault();
												clearAllMarkers();
										   }
									   }
									});
				listinginfo.adopt(listingname,listingaddr,removemarker,removeallmarkers);
				
				listing_markers[listing_id] = {org:response[0], addr:response[1], coords:response[2], full:response[3], info_window:listinginfo};
				
				highlightListingMarker(listing_id);
				
			}, onFailure: function(){ $('map_info').innerHTML = 'The request failed.'; prepareFrame(); }
		});
		req.send();
	} else {
		highlightListingMarker(listing_id);
	}
}

function highlightListingMarker(listing_id) {
	
	$('map_info').set('html',listing_markers[listing_id].full);
	prepareFrame();
	
	if (listing_markers[listing_id].coords && listing_markers[listing_id].coords!=='NA') {
		
		// Set marker location as map centre and pan map to the marker position
		var coords = listing_markers[listing_id].coords.split(',');		
		var listingpoint = new GLatLng(coords[0], coords[1]);
		map.setCenter(listingpoint, 16);
		map.panTo(listingpoint);
		
		// If marker reference has not been created yet, create it
		if (typeof(listing_markers[listing_id].marker_ref)!=='object') {
			
			// Define custom icon
			var gs_marker_icon = new GIcon(G_DEFAULT_ICON);
			gs_marker_icon.image = 'images/marker.png';
			
			// Set marker reference for this listing as a new GMarker using our custom icon
			listing_markers[listing_id].marker_ref = new GMarker(listingpoint,{icon:gs_marker_icon});
		
			// Add marker to map
			map.addOverlay(listing_markers[listing_id].marker_ref);
		
			// Add click event to marker to open info window and highlight listing in results list
			GEvent.addListener(listing_markers[listing_id].marker_ref,'click',function() {
				showListingDetails(listing_id);
			});
			
		}
		
		// Open info window and highlight listing in results list
		showListingDetails(listing_id);
		
		// Remove listing highlight in results list when the marker loses focus (i.e. when the infowindow is closed)
		GEvent.addListener(map,'infowindowclose',function() {
			clearListingHighlights();
		});
		
	} else {
		
		map.closeInfoWindow();
		highlightListing(listing_id);
		
	}
	
}

function showListingDetails(listing_id) {
	
	// Open infowindow with marker details inside
	listing_markers[listing_id].marker_ref.openInfoWindowHtml(listing_markers[listing_id].info_window);
	
	// Show full listing details in the map_info div
	var mapinfo = $('map_info');
	mapinfo.set('html',listing_markers[listing_id].full);
	
	// Do effect on map info div to draw attention to the new details
	var effect = new Fx.Tween(mapinfo,{duration:200,link:'chain'});
	effect.start('background-color',mapinfo.getStyle('background-color'),'#ffffff');
	effect.start('background-color','#ffffff',mapinfo.getStyle('background-color'));
	
	// Highlight listing in results list
	highlightListing(listing_id);
}

function prepareSearchBox() {
	
	var searchform = $('searchform');
	var searchinput = $('keywordsinput');
	
	if (searchinput) {
		
		var initialvalue = searchinput.get('value');
		
		if (searchinput.get('value')===initialvalue) searchinput.className = 'hint';
		
		searchinput.addEvent('focus',function() {
			if (this.get('value')===initialvalue) this.set('value','');
			this.removeClass('hint');
		});
		
		searchinput.addEvent('blur',function() {
			if (this.get('value')==='') {
				this.set('value',initialvalue);
				this.addClass('hint');
			}
		});
		
	}
	
	searchform.addEvent('submit',function(event) {
		
		event.preventDefault();
		
		keywords = searchinput.get('value');
		
		if (keywords!=='') {
			
			expandResultsPane();
			showLoadingMessage('listings');
			showLoadingMessage('map_info');
			
			var req = new Request({
				url: 'api.php?a=searchlistings&k=' + keywords,
				link: 'cancel',
				onSuccess: function(txt){ 
					txt = txt.replace(/^\s+|\s+$/g,"");
					$('listings').innerHTML = txt;
					showSelectListingMessage();
					prepareFrame();
				}, onFailure: function(){ $('listings').innerHTML = 'The request failed.'; }
			});
			req.send();
			
		}
		
	});
	
}

// GOOGLE MAPS CODE

var map;
var marker;
var listing_markers = new Object();
var overlayInstance = null;
var client = new GStreetviewClient();
var lastMarkerLocation;
var streetViewObject;
var normalStreetViewDiv;
var mapT;
var streetViewToggle;
var currentPOV = null;
var geocoder = null;

function load() {
	if (GBrowserIsCompatible()) {
		
		
		map = new GMap2($('mapzone'));
		var sw = new GLatLng(-36.70054, 145.03197);
		var ne = new GLatLng(-36.15525, 145.79850);
		var bounds = new GLatLngBounds(sw, ne);
		var mapZoomLevel = map.getBoundsZoomLevel(bounds);
		var mapCenter = new GLatLng(-36.427895, 145.415235);
		map.setCenter(mapCenter, mapZoomLevel);
		
	    map.addControl(new GLargeMapControl());
		var mapControl = new GMenuMapTypeControl();
		
		//map.removeMapType(G_SATELLITE_MAP);
		//map.removeMapType(G_HYBRID_MAP);
		map.addMapType(G_PHYSICAL_MAP);
        map.addControl(mapControl);
		
		streetViewToggle = new StreetViewButton()
		map.addControl(streetViewToggle);
		
		map.enableScrollWheelZoom();
		geocoder = new GClientGeocoder();
		
		var boundary = new GPolyline.fromEncoded({
			color: "#0000cc",
			weight: 3,
			opacity: 0.4,
			points: "lxm|Ekt|tZxmJL@paVjm]PBo~U|nDgJ|Sce@tm@~TlfC}CfBv]phD@FjpBbePFDceFvzAUQcx@vl@jb@fSsg@}Ty_@ua@xMe_@eYtAueFor@`Map@aKqHhj@ac@zQcGfn@_HrBoA}n@_LjIgRn^mi@qh@nA_c@iKqLFwv@w\\EIklMkS|HeExTqXwH{Skq@__@mOs_@|PkV}CaL|KuGeU{@k|@{~IywEi@yxk@jg@cv@zDc@@gwFqpK^A{qRq_JjB_r@fk@s|@e@nHcbAz^wZzQlIVybAbLylAUaQp`@oKrKcy@s`UcoCseEFGtr_@eoRK^n`gA}PhUyG|JgO{BtF~QoLvQeGuIkNfHoMoWgHpMhThVkM`Gaa@pAgF`N_Pv@lHrMvNgF_E~V}h@K_B`Kd_@rQyf@hBcDlMkNg@qD_]wJnCfA|UWrU`f@ne@{a@C{P~K{Hsu@}JxFnAlb@`d@`_@eVha@wK{K}CzOxe@t`@oWj^mWtMd^tg@nGgZ|OJ_Ftm@p~@zHwDso@l]fOyDnkAxLjP{Op^ww@eK{ThVdH`b@wc@D_Px`AfOhj@i`@z\\t@vm@pH`Wvh@vLzIeo@nq@hJyR|\\rWiFrGpYra@cWbbS[h@iqB",
			levels: "PKKLLGHGIGIIKIHHHNGGIJFHFGEIHEHJEFGGJFHFFHFEIEHLHDHLKKGGJGFGEDGGKNJKKJAFGFGFFHFHEEFHFGHFGHEFGFICGIFHFLFHFFGHEIHFHHGHIFJGGGGIGGGELHHGGGHGIP",
			zoomFactor: 2, 
			numLevels: 18
		});
		map.addOverlay(boundary);
			
		guyIcon = new GIcon(G_DEFAULT_ICON);
		guyIcon.shadow = "";
		guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
		guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
		guyIcon.imageMap = [
			26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
			16,20, 16,14, 19,13, 22,8
		];
		guyIcon.iconSize = new GSize(49, 52);
		guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
		guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head
		
}
}

function toggleStreetViewOverlay() {
  if (typeof(overlayInstance)==='undefined' || overlayInstance===null) {
	  
	streetViewToggle.toggleOnOff($('streetviewtogglebutton'));
	
	marker = new GMarker(map.getCenter(), {icon: guyIcon, draggable: true});
	map.addOverlay(marker);
	
	marker.openInfoWindow("Drag me onto a blue-outlined street!");
	onDragEnd();

	overlayInstance = new GStreetviewOverlay();
    map.addOverlay(overlayInstance);
	
	lastMarkerLocation = map.getCenter();
	GEvent.addListener(marker,"dragstart", onDragStart);
	GEvent.addListener(marker, "dragend", onDragEnd);
	GEvent.addListener(marker, "click", openPanoramaBubble);
	/*GEvent.addListener(map, "click", function(overlay,latlng) {
		marker.setLatLng(latlng);
		onDragEnd();
		openPanoramaBubble();
	});*/
	
	currentPOV = null;
	if (streetViewObject) { streetViewObject.setPOV({yaw:0}); }
	
  } else {
	streetViewToggle.toggleOnOff($('streetviewtogglebutton'));
	map.removeOverlay(marker);
    map.removeOverlay(overlayInstance);
    overlayInstance = null;
  }
}

function openPanoramaBubble() {
	
	normalStreetViewDiv = new Element('div',{
		'id': 'streetviewcontainer',
		'styles': {
			'width': '460px',
			'height': '275px'
		}
	})
	
	normalStreetViewDiv.adopt(
		new Element('div',{'id': 'streetviewaddress'}),
		new Element('div',{
			'id': 'streetview',
			'styles': {
				'width': '460px',
				'height': '250px'
			}
		})
	);
	
	streetViewObject = new GStreetviewPanorama(normalStreetViewDiv.childNodes[1]);
	streetViewObject.setLocationAndPOV(marker.getLatLng(), currentPOV);
	
	marker.openInfoWindow(normalStreetViewDiv);
	
	GEvent.addListener(streetViewObject, "initialized", onPanoLocationChange);
	GEvent.addListener(streetViewObject, "yawchanged", onYawChange);

	onPanoLocationChange({latlng: marker.getLatLng()});
	
}

function onYawChange(newYaw) {
	var GUY_NUM_ICONS = 16;
	var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
	if (newYaw < 0) {
		newYaw += 360;
	}
	guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
	guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
	marker.setImage(guyImageUrl);
	currentPOV = streetViewObject.getPOV();
}

function onPanoLocationChange(loc) {
	
	marker.setLatLng(loc.latlng);
	
	/*
	var iw = map.getInfoWindow();
	
	if (iw) {
		iw.reset(new GLatLng(loc.latlng.lat,loc.latlng.lng),iw.getTabs(),new GSize(460,275),iw.getPixelOffset(),null);
	}
	*/
	
	geocoder.getLocations(loc.latlng, function(addresses) {
		if (addresses) {
			if (addresses.Status.code !== 200) {
				if ($('streetviewaddress')) {
					$('streetviewaddress').set('html','');
				}
			} else {
				if (addresses && addresses.Placemark[0] && addresses.Placemark[0].AddressDetails && addresses.Placemark[0].AddressDetails.Country && addresses.Placemark[0].AddressDetails.Country.AdministrativeArea && addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality && addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare && addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName) {
					var streetviewaddress = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
					if ($('streetviewaddress')) {
						$('streetviewaddress').set('html',streetviewaddress+'<span class="approx">(approx.)</span>');
					}
				}
			}
		}
	});

}

function onDragStart() {
	map.closeInfoWindow();
}

function onDragEnd() {
  if (typeof marker !== 'undefined' && marker !== null) {
	  var latlng = marker.getLatLng();
  }
  client.getNearestPanorama(latlng, onResponse);
  if (streetViewObject) {
  	currentPOV = streetViewObject.getPOV();
  }
}

function onResponse(response) {
	if (response.code !== 200) {
		marker.setLatLng(lastMarkerLocation);
	} else {
		var latlng = new GLatLng(parseFloat(response.Location.lat), parseFloat(response.Location.lng));
		marker.setLatLng(latlng);
		lastMarkerLocation = latlng;
		openPanoramaBubble();
	}
}

// SET UP THE "STREET VIEW" BUTTON
function StreetViewButton() {}
StreetViewButton.prototype = new GControl();

StreetViewButton.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var ButtonOutter = document.createElement("div");
  this.setButtonStyleOutter_(ButtonOutter);
  
  container.appendChild(ButtonOutter);
  
  var ButtonInner = document.createElement("div");
  ButtonInner.setAttribute('id','streetviewtogglebutton');
  this.setButtonStyleInner_(ButtonInner);
  
  ButtonOutter.appendChild(ButtonInner);
  
  ButtonInner.appendChild(document.createTextNode("Street View"));

  GEvent.addDomListener(ButtonInner, "click", function() {
    toggleStreetViewOverlay();
  });

  map.getContainer().appendChild(container);
  return container;
}

StreetViewButton.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(100, 7));
}

StreetViewButton.prototype.setButtonStyleOutter_ = function(button) {
  button.style.border = "1px solid black";
  button.style.textAlign = "center";
  button.style.width = "6em";
}

StreetViewButton.prototype.setButtonStyleInner_ = function(button) {
  button.style.backgroundColor = "white";
  button.style.font = "12px/1.5em Arial";
  button.style.border = "1px solid";
  button.style.borderColor = "white rgb(176,176,176) rgb(176,176,176) white";
  button.style.padding = "2px";
  button.style.textAlign = "center";
  button.style.cursor = "pointer";
}

StreetViewButton.prototype.toggleOnOff = function(button) {
	
	if (button.style.fontWeight!=='bold') {
		button.style.fontWeight='bold';
		button.style.borderColor = "rgb(52,86,132) rgb(108,157,223) rgb(108,157,223) rgb(52,86,132)";
	} else {
		button.style.fontWeight='';
		button.style.borderColor = "white rgb(176,176,176) rgb(176,176,176) white";
	}
	
}
