var mapshown = new Array();
var gmap_options = new Array();
var deathList = new Array();
var module;
var currentMarker;

function mapView() {
	// Show large map and small list. Hide small map and large list.
	if (document.getElementById('map_view_div')) {
		document.getElementById('map_view_div').style.display = 'block'
	}
	if (document.getElementById('list_view_div')) {
		document.getElementById('list_view_div').style.display = 'none'
	}
	if (document.getElementById('googlemap_block')) {
		document.getElementById('googlemap_block').style.display = 'none'
	}
	if (document.getElementById('listings_block')) {
		document.getElementById('listings_block').style.display = 'block'
	}
	kjax('setSession',{viewMode: 'map'},'fail','fail');
}

function listView() {
	// Show small map and large list. Hide large map and small list.
	gmap_zoom = undefined;
	gmap_options['minLat'] = 0;
	gmap_options['minLong'] = 0;
	gmap_options['maxLat'] = 0;	
	gmap_options['maxLong'] = 0;
	gmap_options['centerLat'] = 0;
	gmap_options['centerLong'] = 0;

	if (document.getElementById('map_view_div')) {
		document.getElementById('map_view_div').style.display = 'none'
	}
	if (document.getElementById('list_view_div')) {
		document.getElementById('list_view_div').style.display = 'block'
	}
	if (document.getElementById('googlemap_block')) {
		document.getElementById('googlemap_block').style.display = 'block'
	}
	if (document.getElementById('listings_block')) {
		document.getElementById('listings_block').style.display = 'none'
	}
	kjax('setSession',{viewMode: 'list'},'fail','fail');
}

function toggleDisplay() {
	var id;
	var display;
	for (var i = 0; i < arguments.length; i++) {
		id = arguments[i];
		display = document.getElementById(id).style.display;
		if (display == 'none') {
			document.getElementById(id).style.display = '';
		} else {
			document.getElementById(id).style.display = 'none';
		}
	}
}

function populateMap(array,map_details) {
	// Not strictly populating the map, but first let's clear out the explanatory list.
	var ul = document.getElementById('smallList');
	if (ul) {
		clearList(ul);
	}
	if (GBrowserIsCompatible() && document.getElementById(map_details['canvas'])) {
		var point;
		var marker;
		var id;
		var map = new GMap2(document.getElementById(map_details['canvas']));
		map.setCenter(new GLatLng(array['center']['latitude'],array['center']['longitude']), 13);
		var bounds = map.getBounds();
		var greenIcon = new GIcon(G_DEFAULT_ICON);
		greenIcon.image = '_images/maps-pin-off.png';
		greenIcon.shadow = '';
		greenIcon.shadowSize = new GSize(0,0);
		greenIcon.iconSize = new GSize(23,23);
		greenIcon.iconAnchor = new GPoint(10,18);

		var markers = [];
		var clusterStyles = [];
		var clusterOptions = {gridSize:20, styles:[{height:23, width:17,opt_anchor:[5,],url:'_images/'+module+'-icon-off.png'}]};
		for (var ele in array['points']) {
			if (ul) {
				var li = document.createElement('li');
				li.innerHTML = "<div class='listing_without_pic_div'>"
					+ "<span class='feed_title'>"
					+ "<a href='"+array['details'][ele]['href']+"'>"+array['details'][ele]['name']+"</a>"
					+ "</span><br />\n</div>"
					+ "<div class='li_separator'></div>";
				ul.appendChild(li);
			}
			if (array['points'][ele]['latitude'] != 0 || array['points'][ele]['longitude'] != 0) {
				point = new GLatLng(array['points'][ele]['latitude'], array['points'][ele]['longitude']);
				marker = new GMarker(point, { icon:greenIcon, draggable: array['points'][ele]['draggable'] });
				markers.push([marker,array['details'][ele]]);
			}
		}

		if (array['bounds'] == undefined || array['bounds'].length == 0) {
			array['bounds'] = array['points'];
		}

		for (var ele in array['bounds']) {
			point = new GLatLng(array['bounds'][ele]['latitude'], array['bounds'][ele]['longitude']);
			bounds.extend(point);
		}
		if (array['details']['zoom']) {
			map.setZoom(array['details']['zoom'] * 1);
		} else {
			var zoom = map.getBoundsZoomLevel(bounds);
			map.setZoom(zoom);
			gmap_options['zoom'] = zoom;
		}
		var markerCluster = new MarkerClusterer(map, markers, clusterOptions);	
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		GEvent.addListener(map,'moveend',function() {mapMoved(map,map_details); });
//		Zooming appears to trigger moveend anyway.
//		GEvent.addListener(map,'zoomend',function() {mapMoved(map,map_details); });
		bounds = String(bounds).replace(/[()\s]/g,'').split(',');
		var center = String(map.getCenter()).replace(/[()\s]/g,'').split(',');
		gmap_options['minLat'] = bounds[0];
		gmap_options['minLong'] = bounds[1];
		gmap_options['maxLat'] = bounds[2];	
		gmap_options['maxLong'] = bounds[3];
		gmap_options['centerLat'] = center[0];
		gmap_options['centerLong'] = center[1];
		if (map_details['canvas'] == 'large_canvas') {
			document.getElementById('resultMatches').innerHTML = array['extra']['matches'];
			document.getElementById('resultTotMatches').innerHTML = array['extra']['totMatches'];
			document.getElementById('resultNumbers').style.display = 'inline';
			setTimeout("document.getElementById('mapOverlay_" + map_details['canvas']+"').style.display = 'none'",500);
		}
	}
}

function mapMoved(map,map_details) {
	var bounds = map.getBounds();
	bounds = String(bounds).replace(/[()\s]/g,'').split(',');
	var center = String(map.getCenter()).replace(/[()\s]/g,'').split(',');
	gmap_options['zoom'] = map.getZoom();
	gmap_options['minLat'] = bounds[0];
	gmap_options['minLong'] = bounds[1];
	gmap_options['maxLat'] = bounds[2];	
	gmap_options['maxLong'] = bounds[3];
	gmap_options['centerLat'] = center[0];
	gmap_options['centerLong'] = center[1];
	getListings(map_details['canvas']);
}

function makeInfoBoxContainer(id) {
	var element = document.getElementById(id)
	if (element) {
		element.parentNode.removeChild(element);
	}

	if (document.getElementById(id) == null) {
		var containerdiv = document.createElement('div');
		containerdiv.setAttribute('id',id);
		containerdiv.setAttribute('class','block_' + module + ' var_thin infoBoxContainer');
		containerdiv.setAttribute('className','block_' + module + ' var_thin infoBoxContainer');
		containerdiv.style.borderBottom = '1px gray solid';
		containerdiv.onmouseover = function() { stopDeathCount(id); };
		containerdiv.onmouseout = function() { startDeathCount(id); };
		document.body.appendChild(containerdiv);
	}
}

function makeInfoBox(array,marker,container,display) {
	// Take the information in array to build an info box, return the new div's id.
	// firstly check thast the box doesn't already exist!
	if(!array) {return;}
	var id = 'infobox_' + array['id'];
	var element = document.getElementById(id)
	if (element) {
		element.parentNode.removeChild(element);
	}
	var active = (document.getElementById(container).childNodes.length == 0?'active':'inactive');

	if (document.getElementById(id) == null) {
		var containerdiv = document.createElement('div');
		containerdiv.setAttribute('id',id);
		containerdiv.setAttribute('class','block_' + module);// + ' var_thin');
		containerdiv.setAttribute('className','block_' + module);// + ' var_thin');
		containerdiv.style.border = '1px gray solid';
		containerdiv.style.borderBottom = 'none';
		containerdiv.style.marginTop = '0';

		var headerdiv = document.createElement('div');
		headerdiv.setAttribute('class','block_top ' + active);
		headerdiv.setAttribute('className','block_top ' + active);
		headerdiv.onclick = function() { slidedown(id + '_contents',container); };

		var plusLink = document.createElement('span');
		plusLink.setAttribute('class','plusLink');
		plusLink.setAttribute('className','plusLink');
		plusLink.innerHTML='+';
		headerdiv.appendChild(plusLink);

		var headertitle = document.createElement('h2');
		headertitle.innerHTML = array['name'];
		headerdiv.appendChild(headertitle);
		containerdiv.appendChild(headerdiv);

		var infodiv = document.createElement('div');

		infodiv.setAttribute('id',id + '_contents');
		if (display) {
			infodiv.style.display = 'block';
			downs[container] = id + '_contents';
		} else {
			infodiv.style.display = 'none';
		}
		infodiv.style.oferflow = 'hidden';
		infodiv.style.height = '80px';
		infodiv.style.backgroundColor = '#FFFFFF';
		infodiv.style.margin = 0;
		infodiv.style.padding = '7px 0 0 0';

		var imagediv = document.createElement('div');
		imagediv.setAttribute('class','feed_image_div');
		imagediv.setAttribute('className','feed_image_div');
		imagediv.style.marginLeft = '8px';

		var pic = document.createElement('img');
		pic.setAttribute('src',array['img']);
		pic.setAttribute('alt',array['name']);
		pic.setAttribute('title',array['name']);
		pic.setAttribute('class','feed_image');
		pic.setAttribute('className','feed_image');
//		pic.style.height = '84px'; // Messes up ie.
		imagediv.appendChild(pic);
		infodiv.appendChild(imagediv);

		var infospan = document.createElement('span');
		var html = '';
//		if (array['name']) {
//			html += array['name'] + "<br />\n";
//		}
		if (array['address']) {
			html += array['address'] + "<br />\n";
		}
		if (array['postcode']) {
			html += array['postcode'] + "<br />\n";
		}
		infospan.innerHTML = html;
		if (array['href']) {
			var moreLink = document.createElement('a');
			moreLink.setAttribute("href", array['href']);

			var linkImg = document.createElement('img');
			linkImg.setAttribute('src','_images/view-full-listing-off.gif');
			linkImg.setAttribute('alt','Full Listing');
			linkImg.setAttribute('title','Full Listing');
			linkImg.style.paddingTop = '5px';
			linkImg.onmouseover = function() {this.setAttribute('src','_images/view-full-listing-on.gif'); };
			linkImg.onmouseout = function() {this.setAttribute('src','_images/view-full-listing-off.gif'); };

			moreLink.appendChild(linkImg);
			infospan.appendChild(moreLink);
		}

		infodiv.appendChild(infospan);


		var reviewdiv = document.createElement('div');
		reviewdiv.style.clear = 'left';

		if (array['class']) {
			var starpic =  document.createElement('img');
			starpic.setAttribute('src','_images/' + array['class'] + 'star.png');
		}

		if (array['numrevues']) {
			var reviewspan = document.createElement('span');
			reviewspan.innerHTML = 'Rating ' + array['score'] + ' (' + array['numrevues'] + ' reviews)';
			reviewdiv.appendChild(reviewspan);
		}
		infodiv.appendChild(reviewdiv);
		containerdiv.appendChild(infodiv);
		document.getElementById(container).appendChild(containerdiv);
	}
}

function toggleInfoBox(box_id,marker) {
	if (document.getElementById(box_id).style.display == 'none') {
		showInfoBox(box_id,marker);
	} else {
		hideInfoBox(box_id,marker);
	}
}

function showInfoBox(box_id,marker,map) {
	if (!showBusiness) {
		image_replace();
		currentMarker = marker;
		activateImage(marker);
		var box = document.getElementById(box_id);
		var offsets = getOffsetsFor(marker,box,map);
		box.style.top = offsets[1] + 'px';
		box.style.left = offsets[0] + 'px';
		box.style.visibility = 'visible';
	}
}

function hideInfoBox(box_id,marker) {
	if (deathList[box_id]) {
		deactivateImage(marker);
		document.getElementById(box_id).style.visibility = 'hidden';	
//		marker.setImage('_images/maps-pin-off.png');
	}
}

function startDeathCount(box_id,marker) {
	deathList[box_id] = 1;
	setTimeout(function() { hideInfoBox(box_id,marker); },100);
}

function stopDeathCount(box_id) {
	deathList[box_id] = 0;
}

function activateImage(marker) {
	if (!marker) {marker = currentMarker;}
	var image = marker.style.backgroundImage;
	marker.style.backgroundImage = 'url(_images/restaurants-icon-on.png)'
}

function deactivateImage(marker) {
	if (!marker) {marker = currentMarker;}
	var image = marker.style.backgroundImage;
	marker.style.backgroundImage = 'url(_images/restaurants-icon-off.png)'
}

function getOffsetsFor(ele,div,map) {
	var xPos;
	var yPos;
	var image;
	var leftAdjust = 2;
 	var rightAdjust = 16;
	var topAdjust = -20;
	var ele_loc = getXY(ele);
	var cont = map.getContainer();
	var cont_loc = getXY(cont);
	var div_dim = getDim(div);
	var cont_dim = getDim(cont);	// If the element would go off the right hand side place it on the left instead.
	if (ele_loc[0] + div_dim[0] + rightAdjust > cont_loc[0] + cont_dim[0]) {
		xPos = ele_loc[0] + leftAdjust - div_dim[0];
		image = '_images/maps-pin-on-left.png';
	} else {
		xPos = ele_loc[0] + rightAdjust;
		image = '_images/maps-pin-on-right.png';
	}
	// If the element would  go off the bottom of the map, move it up.
	if (ele_loc[1] + div_dim[1] + topAdjust> cont_loc[1] + cont_dim[1]) {
		yPos = cont_loc[1] + cont_dim[1] - div_dim[1]; 
	} else {
		yPos = ele_loc[1] + topAdjust;
	}
	return [xPos,yPos,image];
}

function getXY(ele) {
	var xpx = 0;
	var ypx = 0;
	while( ele != null ) {
		ypx += ele.offsetTop;
		xpx += ele.offsetLeft;
		ele = ele.offsetParent;
	}
	return [xpx,ypx];
}

function getDim(ele) {
	return [ele.offsetWidth,ele.offsetHeight];
}


function centerMapFromInput(lat_id,long_id,canvas_id) {
	// Build the array
	array = new Array();
	array['points'] = new Array();
	array['points'][0] = new Array();
	array['events'] = new Array();
	array['events'][0] = new Array();
	mapDetails = new Array();
	array['points'][0]['latitude'] = document.getElementById(lat_id).value;
	array['points'][0]['longitude'] = document.getElementById(long_id).value;
	array['points'][0]['draggable'] = true;
	array['events'][0]['dragend'] =  'var ele = this.getLatLng(); document.getElementById("' + lat_id + '").value = ele.lat(); document.getElementById("' + long_id + '").value = ele.lng();';
	mapDetails['canvas'] = canvas_id;
	populateMap(array,mapDetails);
}

function post2geo(post_id, lat_id, long_id,canvas_id) {
	var postcode = document.getElementById(post_id).value;
	id_array = new Array();
	id_array['lat'] = lat_id;
	id_array['long'] = long_id;
	id_array['canvas'] = canvas_id;
	kjax('post2geo',postcode,'updateLatLong','updateLatLong',id_array);
}

function updateLatLong(response,id_array) {
	if (response['error']) {
		alert(response['error']);
	} else {
		var latbox = document.getElementById(id_array['lat']);
		var longbox = document.getElementById(id_array['long']);
		latbox.value = response['results']['Latitude'];
		longbox.value = response['results']['Longitude'];
		if (id_array['canvas'] != null) {
			centerMapFromInput(id_array['lat'], id_array['long'], id_array['canvas']);
		}
	}
}

function getListings(mapcanvas) {
	if (document.getElementById('mapOverlay_' + mapcanvas)) {
		document.getElementById('mapOverlay_' + mapcanvas).style.display = 'block';
	}

	mapshown[mapcanvas] = true;
	args = new Array();
	args['module'] = module;
	args['map_id'] = mapcanvas;
	args['extra'] = gmap_options;
	mapDetails = new Array();
	mapDetails['canvas'] = mapcanvas;
	kjax('getListings',args,'populateMap','fail',mapDetails,mapcanvas);
}

function fail() {
}

function updateNumbers(number) {
	gmap_options['results'] = number;
	setTimeout('updateNumbersConfirm(' + number + ');',500);
}

function updateNumbersConfirm(number) {
	if (number == gmap_options['results']) {
		getListings('large_canvas');
	}
}

function clearList(list) {
	while(list.hasChildNodes()){
		list.removeChild(list.childNodes[0])
	}
}
