var map;
var localSearch = new GlocalSearch();
var addM = 0;
var incidentPhotoPath;
var imgUniqueId = 0;
var tempMarker;
var markerIDs = [];
var markerPopupHTML = "<div class='map-popup'><p>Drag the pin below to the exact location. If this message disappears just click the pin to reopen it.</p><p>When you're happy with the location <a href='javascript:submitIncident();'>click here &#187;</a></div>";

var poicon = new GIcon();
    poicon.image = "images/P_and_O_Ferries.png";
    poicon.shadow = "images/shadow-P_and_O_Ferries.png";
    poicon.iconSize = new GSize(55.0, 32.0);
    poicon.shadowSize = new GSize(72.0, 32.0);
    poicon.iconAnchor = new GPoint(27.0, 32.0);
    poicon.infoWindowAnchor = new GPoint(27.0, 0.0);


/*
var poicon = new GIcon();
    poicon.image = "images/icons/other.png";
    poicon.shadow = "images/icons/shadow.png";
    poicon.iconSize = new GSize(44.0, 63.0);
    poicon.shadowSize = new GSize(76.0, 63.0);
    poicon.iconAnchor = new GPoint(22.0, 63.0);
    poicon.infoWindowAnchor = new GPoint(22.0, 63.0);
*/
function load(c_str, zoom, mypop, cid, zid) {
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("map"));
	if(zid>0){
		map.addControl(new GSmallMapControl());
	}else{
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GOverviewMapControl());
	}

	map.addControl(new GMapTypeControl());
	map.enableScrollWheelZoom();
	
	
	//var browserVer=navigator.appVersion; 
	//alert(browserVer);
	if (map) {
		//2.213749&y=46.227638
		map.setCenter(new GLatLng(46.227638, 2.213749), 5);
		
		
		
		
		if(zid == 0){
			map.setMapType(G_HYBRID_MAP);
			usePointFromPostcode(c_str, zoom, searchzoom);
		}else{
			map.setMapType(G_NORMAL_MAP);
		}
			try{
				//alert('drawing');
				setTimeout('drawMarkers(' + cid + ', 0, 0, "", ' + zid + ', 0)', 1000);
			}catch(err){
				//alert(err.description);
			}
		
		if(mypop > 0){
			//alert(mypop);
			setTimeout('popup(' + mypop + ')',3000);
			
		}
		
	}
  }
}

function getRandomPoint() {
	var lat = 48.25 + (Math.random() - 0.5)*14.5;
	var lng = 11.00 + (Math.random() - 0.5)*36.0;
	return new GLatLng(Math.round(lat*10)/10, Math.round(lng*10)/10);
}

function usePointFromPostcode(postcode, zoom, callbackFunction) {
	localSearch.setCenterPoint(map);
	//localSearch.setAddressLookupMode(ADDRESS_LOOKUP_DISABLED);
	localSearch.setSearchCompleteCallback(null,
	function() {
	  
	  if (localSearch.results[0]) {    
		var resultLat = localSearch.results[0].lat;
		var resultLng = localSearch.results[0].lng;
		var point = new GLatLng(resultLat,resultLng);
		//map.setCenter(point, 10);
		alertStr = 'title=' +localSearch.results[0].title + '\r\n address=' +localSearch.results[0].streetAddress + '\r\n city=' + localSearch.results[0].city + '\r\n region=' + localSearch.results[0].region + '\r\n country=' + localSearch.results[0].country;
		//alert(alertStr);
		
		callbackFunction(point, zoom);
	  }else{
		//alert("location not found!\r\nTry searching All regions");
	  }
	});  
	
	localSearch.execute(postcode);
}

function fn_search(){
	var strSearch = document.getElementById("strSearch").value;
	usePointFromPostcode(strSearch, searchzoom);
}

function searchzoom(point, zoom){
	//alert('zoom');
	//if(querySt('id') != null){
		map.setCenter(point, zoom);
		
	//}
}

function LocationSearch(zoom_level){
	objFrm = document.SearchForm;
	strCountry = objFrm.NewCountry.value;
	if(strCountry == 'United Kingdom'){
		strCountry = 'UK';
	}
	
	if(strCountry == 'San Marino, Europe'){
		strCountry = 'San Marino';
	}
	
	srchStr = strCountry; // + ', Europe';
	//zoom_level = 5;
	
	if(objFrm.NewRegion.value != '' && objFrm.NewRegion.value != 'Select'){
		srchStr = objFrm.NewRegion.value + ', ' + srchStr;
		zoom_level = zoom_level+5;
	}
	
	if(objFrm.NewSearch.value != '' && objFrm.NewSearch.value != 'Location'){
		srchStr = objFrm.NewSearch.value + ', ' + srchStr;
		zoom_level = 16;
	}
	
	//alert(srchStr);
	usePointFromPostcode(srchStr, zoom_level, searchzoom);
	return false;
}

function addIncident()  {
	
   if (!map) {
		window.location = "/index.php";
		return;
  }
	//map.clearOverlays();
	
	if (tempMarker!=undefined){
		  map.removeOverlay(tempMarker);
	}
	
	
	var tmpicon = new GIcon();
    tmpicon.image = "images/P_and_O_Ferries_flag_place.png";
    tmpicon.shadow = "images/P_and_O_Ferries_flag_place_shadow.png";
    tmpicon.iconSize = new GSize(57.0, 48.0);
    tmpicon.shadowSize = new GSize(57.0, 48.0);
    tmpicon.iconAnchor = new GPoint(22.0, 48.0);
    tmpicon.infoWindowAnchor = new GPoint(22.0, 10.0);

  tempMarker = new GMarker(map.getCenter(), {draggable:true, icon:tmpicon});
  
  GEvent.addListener(tempMarker, 'click', function() {
    tempMarker.openInfoWindowHtml(markerPopupHTML);
  });
  GEvent.addListener(tempMarker, 'drag', function() {
    tempMarker.openInfoWindowHtml(markerPopupHTML);
  });

  //map.addOverlay(tempMarker);
  //tempMarker.openInfoWindowHtml(markerPopupHTML);
  setTimeout('map.addOverlay(tempMarker)', 100);
  setTimeout('tempMarker.openInfoWindowHtml(markerPopupHTML)', 100);

}

function submitIncident(){
	var coordY = tempMarker.getPoint().lat();
    var coordX = tempMarker.getPoint().lng();
	cid = document.getElementById('NewCountry').value;
	rid = document.getElementById('NewRegion').options[document.getElementById('NewRegion').selectedIndex].value;
	title = document.getElementById('NewSearch').value;
	if(title == 'Location'){
		title = '';
	}
	//alert('x=' + coordX);
	//alert('y=' + coordY);
	window.location = 'post_form.php?x=' + coordX + '&y=' + coordY + '&c=' + cid + '&r=' + rid + '&title=' + title;
	return;
}

function popup(mypop){
	//alert(mypop);
	if(mypop == 1){
  		map.openInfoWindowHtml(map.getCenter(),"<div class='search-popup'><p><img src='images/logo_post_search.gif' /></p><p class='bold'>Search a post</p><ul><li>Use the search on the right to filter the posts by category, area and location or under the search options you will see the last 5 posts for the country you have selected. Simply click on a post to read a summary. Alternatively, you can click on a marker to view the summary.</li><li>Each summary will have a &lsquo;read more&rsquo; link where you can see extended information about the post and view a larger photo (if available)</li></ul><a href='javascript:map.closeInfoWindow();'>close</a></div>");
	}else{
		map.openInfoWindowHtml(map.getCenter(),"<div class='search-popup'><p><img src='images/logo_post_add.gif' /></p><p class='bold'>How to post a new entry</p><ul><li>Close this bubble and click &lsquo;Place marker&rsquo;. Alternatively if you would like to find an exact location, select a region from the drop down on right</li><li>Enter a location in the free text field below and click search</li><li>The map will refresh to the location you have searched for</li><li>You can move the map around and zoom in using your mouse and out to find the exact location of the road, building, park etc.</li><li>When you are happy click &lsquo;Place marker&rsquo;</li><li>Follow the instructions in the bubble that appears</li></ul><a href='javascript:map.closeInfoWindow();'>close</a></div>");
	}
}

function drawMarkers(cid, cat, rid, stext, pid, off){
	if (!map) {
		alert('Error !');
		return;
	}
	off = parseInt(off);
	//map.setMapType(G_HYBRID_MAP);
	//alert('this is where the markers would be drawn');
	obj = getHTTPObject();
	var url = 'includes/xmlhttp_new.php';
	url += '?cmd=listposts' + '&cid=' + cid + '&cat=' + cat + '&rid=' + rid + '&stext=' + stext + '&id=' + pid + '&off=' + off;
	
	if(obj){
	
	
	obj.onreadystatechange = function() {
		if (obj.readyState == 4)  {
			//stuff to make it work
			
			var xmldoc = obj.responseXML;
			var db_nodes = xmldoc.getElementsByTagName('db_record'); 
			var n_records = db_nodes.length;
			var p_x, p_y, p_html, p_marker_html;
			//var noItems = GetXMLValue(xmldoc.getElementsByTagName('all_items'));
			map.clearOverlays();
			//var mgr = new GMarkerManager(map);
			//clear div
			if(document.getElementById('recent-posts-content') != null){
				document.getElementById('recent-posts-content').innerHTML = '';
				if(n_records == 0){
					document.getElementById('recent-posts-content').innerHTML = '<p class="recent-posts-link">Sorry there were no posts found, please try again.</p>';
				}
			}
			
			var total = GetXMLValue(db_nodes[0].getElementsByTagName('total'));
			//footer
			total = parseInt(total);
			//alert('total=' + total);
			var next = 	off+50;
			var prev = off - 50;
			var strInnerHTML = '';
			
						
			if(prev >= 0){
				strInnerHTML += '<a href="#" class="previous50" onClick="drawMarkers('+cid+', '+cat+', '+rid+', \''+stext+'\', '+pid+', '+prev+');">&laquo; Previous</a>';	
			}
			
			if(next<=total){
				strInnerHTML += '<a href="#" class="next50" onClick="drawMarkers('+cid+', '+cat+', '+rid+', \''+stext+'\', '+pid+', '+next+');">Next&raquo;</a>';
			}
			
			if(document.getElementById('recent-posts-footer')){
				document.getElementById('recent-posts-footer').innerHTML = 	strInnerHTML;
			}
			
			
			//alert('record='+n_records);
			var batch = [];
			for (i=0; i < n_records; i++) {
				p_x = GetXMLValue(db_nodes[i].getElementsByTagName('p_x'));
				p_y = GetXMLValue(db_nodes[i].getElementsByTagName('p_y'));
				p_html = GetXMLValue(db_nodes[i].getElementsByTagName('p_html'));
				p_marker_html = GetXMLValue(db_nodes[i].getElementsByTagName('p_marker_html'));
				id = GetXMLValue(db_nodes[i].getElementsByTagName('p_id'));
				cat_Category = GetXMLValue(db_nodes[i].getElementsByTagName('cat_Category'));
				total = GetXMLValue(db_nodes[i].getElementsByTagName('total'));
				if(document.getElementById('recent-posts-content') != null){
					document.getElementById('recent-posts-content').innerHTML += p_html;
				}
				point = new GLatLng(p_y, p_x);
				if(pid > 0){
					//var marker = new GMarker(point, poicon);
					var marker = createMarker(point,p_marker_html, cat_Category)
				}else{
					var marker = createMarker(point,p_marker_html, cat_Category)
				}

				map.addOverlay(marker);
				markerIDs[id] = marker;
			}
			//mgr.addMarkers(batch, 4, 17);
			//mgr.refresh();
			//alert(mgr.getMarkerCount(4));
			if(pid > 0){
				//alert(p_y+'='+p_x)
				map.setCenter(new GLatLng(p_y, p_x), 15);
				//map.setMapType(G_NORMAL_MAP);
				//ViewIncident(pid, p_x, p_y);
			}
					
		}  
	 }   
	obj.open('GET', url, true);
	obj.send(null);
	
	}
}

function searchMarkers(zoom_level){
	cid = document.getElementById('SearchCountry').value;
	CountryName = document.getElementById('CountryName').value;
	rid = document.getElementById('SearchRegion').options[document.getElementById('SearchRegion').selectedIndex].value;
	cat = document.getElementById('SearchCat').options[document.getElementById('SearchCat').selectedIndex].value;
	stext = document.getElementById('searchtext').value;
	if(!IsNumeric(cid) || !IsNumeric(rid) || !IsNumeric(cat)){
		alert('Please select all options');
		return;
	}else{
		drawMarkers(cid, cat, rid, stext, 0);
	}
	usePointFromPostcode(CountryName, zoom_level, searchzoom);
	return false;
}


function createMarker(point,html, cat_Category) {
	//alert(cat_Category);
	switch(cat_Category){
		case 'Restaurants':
			var icon = createIcon('restaurant.png');
			break;
		case 'Natural beauty':
			icon = createIcon('natural_beauty.png');
			break;
		case 'Vineyards':
			icon = createIcon('vineyards.png');
			break;
		case 'Golf courses':
			icon = createIcon('golf.png');
			break;
		case 'Events':
			icon = createIcon('events.png');
			break;
		case 'General attractions':
			icon = createIcon('interest_historical.png');
			break;
		case 'Nightlife':
			icon = createIcon('nightlife.png');
			break;
		case 'Accommodation':
			icon = createIcon('accommodation.png');
			break;
		case 'Campsite / Caravan park':
			icon = createIcon('camping.png');
			break;
		case 'Shopping':
			icon = createIcon('shopping.png');
			break;
		case 'Ski and Snowboarding':
			icon = createIcon('sking.png');
			break;
		case 'Service stations':
			icon = createIcon('service_station.png');
			break;
		case 'Health & Leisure':
			icon = createIcon('health_leisure.png');
			break;
		case 'Other':
			icon = createIcon('other.png');
			break;
		default :
			//icon = poicon;
			icon = createIcon('other.png');
		
	}
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function ViewIncident(id, x, y)  {
	//map.closeInfoWindow();
	map.setCenter(new GLatLng(y,x));
	//map.setMapType(G_HYBRID_MAP);
	//force open of popup
	//alert(markerIDs[id]);
  	//settimeout('GEvent.trigger(' + markerIDs[id] + ', "click")', 500);
	
	GEvent.trigger(markerIDs[id], "click");
}

function createIcon(strFile){
	var po_icon = new GIcon();
    po_icon.image = "images/icons/" + strFile;
    po_icon.shadow = "images/icons/shadow.png";
    po_icon.iconSize = new GSize(38.0, 54.0);
    po_icon.shadowSize = new GSize(76.0, 54.0);
    po_icon.iconAnchor = new GPoint(19.0, 54.0);
    po_icon.infoWindowAnchor = new GPoint(19.0, 54.0);
	return po_icon;
}