var fadeTimeout = null;
var fadeInterval = null;
var rewindInterval = null;
var rewindFlag = false;
var mOver = false;
var curTop = 0;
var lastTop = 0;

var map;
var infoWindow = null;
var overlay;
var svDefault;
var xMarker = null;
var nearbyMarkers = [];
var nearbyType = "";

var xIcon = new google.maps.MarkerImage ('http://bizzorg.com/img/cross.png',
	new google.maps.Size(24, 24),
	new google.maps.Point(0, 0),
	new google.maps.Point(12, 12)
);

var xMarker = new google.maps.Marker ({
	icon: xIcon,
	zIndex: 10
});

function load() {
	
	var latlng = new google.maps.LatLng (markerLat, markerLng);
	var mapOptions = {
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("moreinfomap"), mapOptions);
	overlay = new google.maps.OverlayView();
	overlay.draw = function() {};
	overlay.setMap(map);
	xMarker.setMap(map);

	var adUnitDiv = document.createElement('div');
	var adUnitOptions = {
		format: google.maps.adsense.AdFormat.BUTTON,
		position: google.maps.ControlPosition.RIGHT_BOTTOM,
		map: map,
		visible: true,
		publisherId: 'ca-pub-4002245024903759',
		channelNumber: '5626973176'
	};
	adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);
	adUnit.getContainer().style.opacity = "0.85";
	adUnit.getContainer().style.paddingRight = "10px";

	var alttext = "Blue Flag";
	var icon = "http://bizzorg.com/img/blueflag.png";

	var marker = new createMarker(latlng, "<div class='info_name'>" + markerName + "</div><br/>", icon, alttext);  
	marker.setMap(map);

	//if (markerType == 12) {
	//	var bdata = markerBounds.split(' ');
	//	var vspoly = new GPolygon.fromEncoded({
	//		polylines:[ 
	//			{points: bdata[1],
	//			color: "#FF9900",
	//			levels: bdata[0],
	//			opacity: 0.5,
	//			weight: 3,
	//			numLevels: 18,
	//			zoomFactor: 2}],
	//		fill: true,
	//		color: "#FFFF99",
	//		opacity: 0.4,
	//		outline: true
	//	});
	//	map.addOverlay(vspoly);
	//}
}

function plak_sv_close() {
	document.getElementById("plak_sv_container").style.display = "none";
	svDefault.setVisible(false);
	map.setStreetView(svDefault);
}

function plak_sv_show() {
	svDefault = map.getStreetView();
	var sv = new google.maps.LatLng(markerLat, markerLng);
	var panoramaOptions = {
		position: sv,
		pov: {
			heading: 0,
			pitch: 0,
			zoom: 1
		}
	};
	var panorama = new  google.maps.StreetViewPanorama(document.getElementById("sv_image"), panoramaOptions);
	map.setStreetView(panorama);
	document.getElementById("plak_sv_container").style.display = "block";
}

function createMarker(point, text, ico, alttext) {

	var markerIcon = new google.maps.MarkerImage (ico,
		new google.maps.Size(32, 32),
		new google.maps.Point(0, 0),
		new google.maps.Point(4, 31)
	);

	var marker = new google.maps.Marker ({
		position: point,
		zIndex: 5,
		icon: markerIcon
	});

	google.maps.event.addListener(marker, "click", function(event) {
		if (infoWindow != null) {
			infoWindow.close();
		}
		infoWindow = new google.maps.InfoWindow();
		infoWindow.setContent("<div class='info_div'><img src='" + ico + "' class='info_icon' style='width: 32px; height: 32px;' alt='" + alttext + "'/><br/>" + text + "<div style='text-align: center;'><input class='plak_button' type='button' value='View in Context' onclick='goHome(" + markerLat + ", " + markerLng + ")' /><br/><br/></div></div>");
		infoWindow.open(map, marker);
	});
	return marker;
}

function getPinColor (value) {
	var text;
	var type = parseInt(value);
	switch(type) {
		case 1:
			text = "Gray";
			break;
		case 2:
			text = "Blue";
			break;
		case 3:
			text = "Red";
			break;
		case 4:
			text = "Pink";
			break;
		case 5:
			text = "Purple";
			break;
		case 6:
			text = "Green";
			break;
		case 7:
			text = "Yellow";
			break;
		case 8:
			text = "saps";
			break;
		case 9:
			text = "school";
			break;
		case 10:
			text = "hospital";
			break;
		case 11:
			text = "other";
			break;
		case 12:
			text = "voting station";
			break;
	}
	return text;
}

function createNBMarker(point, text, ico, alttext, type, id) {
	var markerIcon;
	if (type > 7) {
		markerIcon = new google.maps.MarkerImage (ico,
			new google.maps.Size(16, 16),
			new google.maps.Point(0, 0),
			new google.maps.Point(14, 16)
		);
	} else {
		markerIcon = new google.maps.MarkerImage (ico,
			new google.maps.Size(14, 30),
			new google.maps.Point(0, 0),
			new google.maps.Point(0, 30)
		);
	}

	var marker = new google.maps.Marker ({
		position: point,
		zIndex: 5,
		icon: markerIcon
	});

	if (type > 7) {
		google.maps.event.addListener(marker, "click", function(event) {
			if (infoWindow != null) {
				infoWindow.close();
			}
			infoWindow = new google.maps.InfoWindow();
			infoWindow.setContent("<div class='info_div'><img src='" + ico + "' class='info_icon' style='width: 16px; height: 16px;' alt='" + alttext + "'/><br/><div class='info_name'> " + text + "</div><br/><div style='text-align: center;'><input class='plak_button' type='button' value='More info...' onclick=\"document.location.href='/moreinfo.php?id=" + id + "'\"/><br/><br/><input class='plak_button' type='button' value='View in Context' onclick='goHome(" + point.lat() + ", " + point.lng() + ")' /><br/><br/></div></div>");
			infoWindow.open(map, marker);
		});
	} else {
		google.maps.event.addListener(marker, "click", function(event) {
			if (infoWindow != null) {
				infoWindow.close();
			}
			infoWindow = new google.maps.InfoWindow();
			infoWindow.setContent("<div class='info_div'><img src='" + ico + "' class='info_icon' style='width: 14px; height: 30px;' alt='" + alttext + "'/><br/><div class='info_name'> " + text + "</div><br/><div style='text-align: center;'><input class='plak_button' type='button' value='More info...' onclick=\"document.location.href='/moreinfo.php?id=" + id + "'\"/><br/><br/><input class='plak_button' type='button' value='View in Context' onclick='goHome(" + point.lat() + ", " + point.lng() + ")' /><br/><br/></div></div>");
			infoWindow.open(map, marker);
		});
	}

	google.maps.event.addListener(marker, "mouseover", function(event) {
		showName(text, event.latLng, type);
	});

	google.maps.event.addListener(marker, "mouseout", function(event) {
		hideName();
	});

	return marker;
}

function getNearby(type) {
	if (type == 1) {
		nearbyType = "place";
	} else {
		nearbyType = "service";
	}
	document.getElementById("nearby_button").disabled = true;
	document.getElementById("nearby_button1").disabled = true;
	if (nearbyMarkers.length > 0) {
		for (var n = 0; n < nearbyMarkers.length; n++) {
			nearbyMarkers[n].setMap(null);
		}
		nearbyMarkers = [];
	}
	AJAXCall("getNearby", encodeURI("lat=" + markerLat + "&lng=" + markerLng + "&id=" + markerID + "&type=" + type), "gotNearby(rep)");
}

function gotNearby(obj) {
	if (obj[0][0] == "none") {
		alert("Sorry. No "+ nearbyType + "s were found in the vicinity of this Plak.");
	} else {
		var marker;
		for (var n = 0; n < obj.length; n++) {
			var LatLng = new google.maps.LatLng(obj[n][0], obj[n][1]);
			var pin = getPinColor(obj[n][4]);
			var icon;
			if (obj[n][4] > 7) {
				icon = "http://bizzorg.com/img/" + obj[n][4] + ".png";
			} else {
				icon = "http://bizzorg.com/img/" + pin + "Pin.png";
			}
			marker = new createNBMarker(LatLng, obj[n][2], icon, obj[n][2], obj[n][4], obj[n][3]);
			marker.setMap(map);
			nearbyMarkers.push(marker);
		}
		if (obj.length == 1) {
			alert(obj.length + " " + nearbyType + " was found in the vicinity of this Plak. You might need to zoom out to it.");
		} else {
			alert(obj.length + " " + nearbyType + "s were found in the vicinity of this Plak. You might need to zoom out to see all of them.");
		}
	}
	document.getElementById("nearby_button").disabled = false;
	document.getElementById("nearby_button1").disabled = false;
}

function showName(name, latlng, type) {
	var div = document.createElement("div");
	div.id = "infopop";
	div.style.position = "relative";
	div.style.whiteSpace = "nowrap";
	div.innerHTML = name;
	if (type > 7) {
		div.style.top = (overlay.getProjection().fromLatLngToDivPixel(latlng).y - 41) + 'px';
		div.style.left = (overlay.getProjection().fromLatLngToDivPixel(latlng).x - 13) + 'px';
	} else {
		div.style.top = (overlay.getProjection().fromLatLngToDivPixel(latlng).y - 54) + 'px';
		div.style.left = (overlay.getProjection().fromLatLngToDivPixel(latlng).x + 8) + 'px';
	}
	var panes = overlay.getPanes();
	panes.floatPane.appendChild(div);
}

function hideName() {
	var infopop = document.getElementById("infopop");
	if(infopop) {
		var panes = overlay.getPanes();
		panes.floatPane.removeChild(infopop);
	}
}

function showImage(e, src) {
	var posx = 0;
	var posy = 0;
	if (e.pageX || e.pageY)     {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY)     {
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	posx += 16;
	posy += 16;
	var imagediv = document.getElementById("imagediv");
	imagediv.style.left = posx + "px";
	imagediv.style.top = posy + "px";
	imagediv.innerHTML = "<img src='" + src + "' style='max-width: 300px;' alt='' />";
	imagediv.style.display = "block";
}

function hideImage() {
	document.getElementById("imagediv").style.display = "none";
}

function overResult(xLat, xLng) {
	var point = new google.maps.LatLng(xLat, xLng);
	xMarker.setPosition(point);
}

function doTranslate() {
	document.getElementById("google_translate_element").innerHTML = "<img src='http://bizzorg.com/img/throbber.gif' style='width: 16px; height: 16px;' alt='Please wait' />";
	var element = document.createElement("script");
	element.type = "text/javascript";
	element.src = "http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
	document.body.appendChild(element);
}

function googleTranslateElementInit() {
	document.getElementById("google_translate_element").innerHTML = "";
	new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}

function doShare() {
	var fburl = "http://www.facebook.com/sharer.php?u=" + escape(window.location.href) + "&t=" + escape(document.title);
	window.open(fburl, 'sharer', 'toolbar=0, status=0, width=626, height=436');
}

function showQRCode(id, type) {
	var qrurl = "http://plak.co.za/phpqrcode/qrCode.php?id=" + id + "&type=" + type;
	window.open(qrurl, 'qrcode', 'toolbar=0, status=0, width=626, height=436');
}

function startFadeTimeout() {
	if (!rewindFlag) {
		mOver = false;
		if (fadeTimeout != null) {
			clearTimeout (fadeTimeout);
		}
		if (fadeInterval != null) {
			clearInterval (fadeInterval);
		}
		fadeTimeout = setTimeout('startFade()', 6000);
	}
}

function stopFadeTimeout() {
	if (!rewindFlag) {
		mOver = true;
		clearTimeout (fadeTimeout);
		clearInterval (fadeInterval);
		curTop = lastTop;
		document.getElementById("fadeDiv").style.top = lastTop + "px";
	}
}

function startFade() {
	lastTop = curTop;
	if (curTop == -600) {
		rewindFlag = true;
		rewindInterval = setInterval ( "rewind()", 10);
	} else {
		fadeInterval = setInterval ( "fade()", 50);
	}
}

function rewind() {
	curTop++;
	document.getElementById("fadeDiv").style.top = curTop + "px";
	if (curTop >= 0) {
		curTop = 0;
		lastTop = curTop;
		clearInterval (rewindInterval);
		rewindFlag = false;
		document.getElementById("fadeDiv").style.top = curTop + "px";
		startFadeTimeout();
	}
}

function fade() {
	curTop--;
	document.getElementById("fadeDiv").style.top = curTop + "px";
	if (curTop == lastTop - 60) {
		lastTop = curTop;
		clearInterval (fadeInterval);
		startFadeTimeout();
	}
}

function submitComment() {
	if (document.getElementById("commentName").value.length == 0) {
		alert("Please supply a name.");
	} else if (document.getElementById("commentName").value.length > 40) {
		alert("Sorry, but the name can't be longer than 40 characters.");
	} else if (document.getElementById("commentEmail").value.length == 0) {
		alert("Please supply your email address.");
	} else if(!validate_email(document.getElementById('commentEmail').value)) {
		alert("The supplied email address seems to be invalid.");
	} else if (document.getElementById("commentText").value.length == 0) {
		alert("You didn't say anything in your comment.");
	} else if (document.getElementById("commentText").value.length > 1000) {
		alert("Sorry, but each comment is limited to 1000 characters.");
	} else if (checkCaps(document.getElementById("commentName").value)) {
		alert("Please DO NOT type your name using only CAPS!");
	} else if (checkCaps(document.getElementById("commentText").value)) {
		alert("Please DO NOT type your comment using only CAPS!");
	} else if (!document.getElementById("haveread").checked) {
		alert("Please read the notice in the grey block, and acknowledge that you have read and understood it.");
	} else if (document.getElementById("captchaText").value.length == 0) {
		alert("Please enter the captcha text to prove that you are not a bot.");
	} else {
		var commentText = document.getElementById("commentText").value;
		commentText = commentText.replace(/&/g, "and");
		AJAXCall("addcomment", encodeURI("id=" + markerID + "&name=" + document.getElementById("commentName").value + "&comment=" + commentText + "&email=" + document.getElementById("commentEmail").value + "&captcha=" + document.getElementById("captchaText").value), "commentAdded(rep)");
		document.getElementById("commentText").value = "";
		document.getElementById("captchaText").value = "";
		document.getElementById("submitButton").disabled = true;
	}
}

function commentAdded(object) {
	if (object[0] == "ok") {
		var currentTime = new Date();
		document.getElementById("commentList").innerHTML = "<strong>" + markerName + "</strong> has " + object[2] + " comment/s<br/>" + object[1];
		document.getElementById("captchaImage").innerHTML = "<img src='captcha.php?nc=" + currentTime.getTime() + "' style='height: 29px; width: 87px;' alt='captcha' />";
		document.getElementById("comment" + object[2]).style.backgroundColor = "#FFFFCC";
		alert("Thank you. Your comment was accepted.");
	} else {
		alert(object[1]);
	}
	document.getElementById("submitButton").disabled = false;
}

function checkCaps(text) {
	var retval = false;
	var regexp = /[A-Z]/g;
	var regexp1 = /[A-Za-z]/g;
	var textList = text.match(regexp1);
	var matchList = text.match(regexp);

	if (matchList != null) {
		if (matchList.length == textList.length) {
			retval = true;
		}
	}
	return retval;
}

function getWeather() {
	document.getElementById("weatherInfoInner").innerHTML = "Please wait. Getting weather information.";
	weatherInfo(markerLat, markerLng, "gotWeather(rep)");
}

function gotWeather(rep) {
	document.getElementById("weatherInfo").innerHTML = rep;
}

function goHome(cLat, cLng) {
	var ca = document.cookie.split(';');
	var foundFlag = false;
	var plakcookie = "";
	var value = "";
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
			if (c.indexOf("Plak") == 0) {
				foundFlag = true;
				plakcookie = c.substring(5, c.length);
				break;
			}
		}
	}
	if (foundFlag) {
		var plakarray = plakcookie.split(":");
		plakarray[0] = "15";
		plakarray[1] = cLat;
		plakarray[2] = cLng;
		for (var n = 0; n < plakarray.length; n++) {
			value += plakarray[n] + ":";
		}
	} else {
		value = "15:" + cLat + ":" + cLng + ":true:true:true:true:true:true:true:false:0:block:false:r1:false:false:false:false:false";
	}
	var date = new Date();
	date.setTime(date.getTime()+(7*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = "Plak="+value+expires+"; path=/";
	document.location.href="/";
}

function validate_email(s) {
	var regexp  = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
	return regexp.test(s);
}
