// (c) 2001 - 2010 Netsilik
// Internet : http://www.netsilik.nl
// E-mail   : info (at) netsilik x nl

Math.PI_2 = 1.57079632679;
var waypointInfo = [];

function globeInit() {
	attachEventHandler('globeImg', 'contextmenu', mouse.clickRight, true);
	attachEventHandler('globeImg', 'mousemove', mouse.track, true);
	attachEventHandler('globeImg', 'mousedown', mouse.dragStart, true);
	attachEventHandler('globeImg', 'click', mouse.dragStop, true);
	attachEventHandler('globeImg', 'mouseup', mouse.dragStop, true);
	attachEventHandler('globeImg', 'mouseout', mouse.dragCancel);
	attachEventHandler('globeImg', 'mousescroll', mouse.scroll);
}
var Waypoint = function (id, x, y, num, name) {
	this.id = id;
	this.x = x;
	this.y = y;
	this.num = num;
	this.name = name;
	this.album = []; 
	this.travelLog = [];
}
Waypoint.prototype.addEntry = function(type, label, uri) {
	if (type == 'album') {
		this.album.push([label, uri]);
	} else {
		this.travelLog.push([label, uri]);
	}
};

var map = {
	waypoints: [],
	waypointRadius: 4,
	
	addWaypoint: function (waypointId, x, y, num, name) {
		map.waypoints[waypointId] = new Waypoint(waypointId, x, y, num, name);
	},
	addWaypointEntry: function (waypointId, type, label, uri) {
		map.waypoints[waypointId].addEntry(type, label, uri);
	},
	isWaypoint: function (x, y) {
		var waypointCount = map.waypoints.length
		for (var waypointId in map.waypoints) {
			if (((map.waypoints[waypointId].y - y) * (map.waypoints[waypointId].y - y)) + ((map.waypoints[waypointId].x - x) * (map.waypoints[waypointId].x - x)) <= map.waypointRadius * map.waypointRadius) {
				return map.waypoints[waypointId];
			}
		}
		return null;
	}
};



var mouse = {
	dragging: 0,
	dragOrigin: [0, 0],
	scrolled: false,

	track: function (event) {
		var mousePos, point, latLong;
		
		mousePos = mouse.getPos(event);
		if (mousePos == false) {
			window.status = window.defaultStatus;	
			return false;
		}
		
		point = projection.inverse(mousePos[0], mousePos[1]);
		if (point == false) {
			window.status = window.defaultStatus;
			return false;
		}
		
		if (mouse.dragging == 0) {
			mouse.showCoords(point);
			waypoint = map.isWaypoint(mousePos[0], mousePos[1]);
			if (waypoint === null) {
				tooltip.hide();
			} else {
				tooltip.showWaypointInfo(waypoint);
			}
		} else if (mouse.dragging == 1) {
			mouse.showCoords(point);
			mouse.dragging = true;
			mouse.dragOrigin = mousePos;
			mouse.dragging = 2;
		}
		return true;
	},
	dragStart: function (event) {
		mouse.dragging = 1;
		return stopEvent(event);
	},
	dragStop: function (event) {
		var mousePos;
		if ( mouse.dragging < 2) {
			return true;
		}
		mousePos = mouse.getPos(event);
		if (mousePos == false || (mouse.dragOrigin[0] - mousePos[0] == 0 && mouse.dragOrigin[1] - mousePos[1] == 0)) {
			mouse.dragging = 0;
			return true;
		}
		nextClick = '';
		for (n = 0; n < getElemnt('globeForm').nextClick.length; n++) {
			if (getElemnt('globeForm').nextClick[n].checked && getElemnt('globeForm').nextClick[n].value == 'relocateWaypoint') {
				nextClick += '&nextClick=relocateWaypoint';
				break;
			}
		}
		var nextUri = getBaseUri();
			nextUri += '?ph=' + getElemnt('globeForm').ph.value;
			nextUri += '&lm=' + getElemnt('globeForm').lm.value;
			nextUri += '&zl=' + getElemnt('globeForm').zl.value;
			nextUri += '&ox=' + mouse.dragOrigin[0];
			nextUri += '&oy=' + mouse.dragOrigin[1];
			nextUri += '&dx=' + mousePos[0];
			nextUri += '&dy=' + mousePos[1];
			nextUri += nextClick;
			nextUri += getAlbumNameValue();
			nextUri += getSessionIdValue();
		document.location.href = nextUri;
		return stopEvent(event);
	},
	dragCancel: function () {
		window.status = window.defaultStatus;
		mouse.dragOrigin = [0, 0];
		mouse.dragging = 0;
		return true;
	},
	clickRight: function (event) {
		var mousePos;
		if (getElemnt('globeForm').zl.value > 1) {
			mousePos = mouse.getPos(event);
			tooltip.showCoordInfo(mousePos[0], mousePos[1]);
		}
		return stopEvent(event);
	},
	getPos: function (event, elmnt) {
		var mouseX, mouseY;
		var elmnt = getElemnt('globeImg');
		
		if (typeof(event.offsetX) != 'undefined') {
			mouseX = event.offsetX + 1;
			mouseY = event.offsetY + 1;
			
			return [mouseX, mouseY];
		} else if(typeof(event.clientX) != 'undefined' && typeof(elmnt.offsetParent) != 'undefined' && typeof(window.scrollX) != 'undefined') {
			// The mozilla way
			mouseX = event.clientX + window.scrollX + 1;;
			mouseY = event.clientY + window.scrollY + 1;;
			
			while (elmnt.offsetParent != null) {
				elmnt = elmnt.offsetParent;
				mouseX -= elmnt.offsetLeft;
				mouseY -= elmnt.offsetTop;
			}
			
			return [mouseX, mouseY];
		}
		return false;	
	},
	scroll: function (event) {
		var scroll = event.detail ? event.detail : event.wheelDelta / -40; 
		var mousePos = mouse.getPos(event);
		var zl;
		if (mouse.scrolled) {
			return true;
		}
		mouse.scrolled = true;
		if (mousePos == false || scroll == 0) {
			return true;
		}
		zl = getElemnt('globeForm').zl.value;
		if ((zl == 1 && scroll > 0) || (zl == 7 && scroll < 0)){
			return true;
		}
		var nextUri = getBaseUri();
			nextUri += '?ph=' + getElemnt('globeForm').ph.value;
			nextUri += '&lm=' + getElemnt('globeForm').lm.value;
			nextUri += '&zl=' + zl;
			nextUri += '&x=' + mousePos[0];
			nextUri += '&y=' + mousePos[1];
			nextUri += '&nextClick=' + ((scroll > 0) ? 'zoomOut' : 'zoomIn');
			nextUri += getAlbumNameValue();
			nextUri += getSessionIdValue();
		document.location.href = nextUri;
		return stopEvent(event);
	},
	showCoords: function (point) {
		if (getElemnt('globeForm').zl.value == 1) {
			return false;
		}
		latLong = projection.formatGeodetic(point);
		window.status = 'Latitude: ' + latLong[0] + ', Longitude: ' + latLong[1] + '.';
	}
};

var tooltip = {
	SHOW_QUICK: 10,
	SHOW_DELAY: 50,
	HIDE_DELAY: 100,
	timerId: 0,
	
	init: function() {
		var ttc = getElemnt('globeInner').insertBefore(document.createElement('DIV'), getElemnt('globeImg'));
		ttc.id = 'toolTipContainer';
		ttc.className = 'invisible';
		var ttp0 = ttc.appendChild(document.createElement('DIV'));
		ttp0.id = 'toolTipPtrDiv0';
		var ttp1 = ttc.appendChild(document.createElement('DIV'));
		ttp1.id = 'toolTipPtrDiv1';
		var ttd = ttc.appendChild(document.createElement('DIV'));
		ttd.id = 'toolTipDiv';
		
		attachEventHandler('toolTipDiv', 'mouseover', tooltip.clearTimer);
		attachEventHandler('toolTipDiv', 'mouseout', tooltip.hide);
	},
	showWaypointInfo: function (waypoint) {
		var tooltipHtml;
		var label, uri;
		tooltip.clearTimer();
		if (typeof(waypoint) == 'object') {
		
			
			tooltipHtml = '<div class="nobr">'+waypoint.num+': <strong>'+waypoint.name+'</strong>';
			if (typeof(getElemnt('globeForm').sessionId) != 'undefined' && getElemnt('globeForm').action.indexOf('/globe/') >= 0) {
				tooltipHtml += ' <a href="/globe/';
				tooltipHtml += (waypoint.name == '') ? 'nameWaypoint' : 'renameWaypoint';
				tooltipHtml += '/waypointId-' + waypoint.id + '/index.php?sessionId=' + getElemnt('globeForm').sessionId.value + '">[ ';
				tooltipHtml += (waypoint.name == '') ? 'Enter name' : 'Rename';
				tooltipHtml += ' ]</a>';
			}
			tooltipHtml += '</div>\n';
			
			if (waypoint.travelLog.length > 0) {
				
				
				tooltipHtml += '<span class="nobr">';
				tooltipHtml += (waypoint.travelLog.length == 1) ? 'Travel Journal' : 'Travel Journals';
				tooltipHtml += '</span><ul>\n';
				
				for ( var i in waypoint.travelLog ) {
					label = (i < 8) ? waypoint.travelLog[i][0] : '[ Even More ]';
					uri = (i < 8) ? waypoint.travelLog[i][1] : '/gallery/';
					if (typeof(getElemnt('globeForm').sessionId) != 'undefined') {
						uri += 'index.php?sessionId=' + getElemnt('globeForm').sessionId.value;
					}
					tooltipHtml += '\t<li class="nobr"><a href="'+uri+'">'+label+'</a></li>\n';
				}
				tooltipHtml += '</ul>\n';
			}
			if (waypoint.album.length > 0) {
				tooltipHtml += '<span class="nobr">';
				tooltipHtml += (waypoint.album.length == 1) ? 'Photo Album' : 'Photo Albums';
				tooltipHtml += '</span><ul>\n';
				for ( var i in waypoint.album ) {
					label = (i < 8) ? waypoint.album[i][0] : '[ Even More ]';
					uri = (i < 8) ? waypoint.album[i][1] : '/travelLog/';
					if (typeof(getElemnt('globeForm').sessionId) != 'undefined') {
						uri += 'index.php?sessionId=' + getElemnt('globeForm').sessionId.value;
					}
					tooltipHtml += '\t<li class="nobr"><a href="'+uri+'">'+label+'</a></li>\n';
				}
				tooltipHtml += '</ul>\n';
			}
			getElemnt('toolTipDiv').innerHTML = tooltipHtml;
			tooltip.timerId = setTimeout('tooltip.show(' + waypoint.x + ', ' + waypoint.y + ');', tooltip.SHOW_DELAY);
		}
	},
	showCoordInfo: function (x, y) {
		var point = projection.inverse(x, y);
		if (point != false) {
			tooltip.clearTimer();
	
			formattedPoint = projection.formatGeodetic(point);
			
			tooltipHtml = '<table>';
			tooltipHtml += '<tr><th>Latitude:</th><td>' + formattedPoint[0] + '</td></tr>';
			tooltipHtml += '<tr><th>Longitude:</th><td>' + formattedPoint[1] + '</td></tr>';
			tooltipHtml += '</table>';
			
			getElemnt('toolTipDiv').innerHTML = tooltipHtml;
		
			tooltip.timerId = setTimeout('tooltip.show(' + x + ', ' + y + ');', tooltip.SHOW_QUICK);
		}
	},
	hide: function () {
		tooltip.clearTimer();
		if ( ! css.hasClass('toolTipContainer', 'invisible')) {
			tooltip.timerId = setTimeout("css.replaceClass('toolTipContainer', '', 'invisible');", tooltip.HIDE_DELAY);
		}
		return true;
	},
	show: function (toolTipX, toolTipY) {
		css.replaceClass('toolTipContainer', '', 'invisible');
		getElemnt('toolTipPtrDiv0').style.left = toolTipX + 'px';
		getElemnt('toolTipPtrDiv0').style.top = toolTipY + 'px';

		getElemnt('toolTipPtrDiv1').style.left = (toolTipX + 2) + 'px';
		getElemnt('toolTipPtrDiv1').style.top = (toolTipY + 3) + 'px';
		
		getElemnt('toolTipDiv').style.left = (toolTipX + 5) + 'px';
		getElemnt('toolTipDiv').style.top = (toolTipY + 6) + 'px';
		
		css.replaceClass('toolTipContainer', 'invisible', '');
	},
	clearTimer: function () {
		if (tooltip.timerId) {
			clearTimeout(tooltip.timerId);
			tooltip.timerId = 0;
		}
	}
};

var projection = { // Orthographic Projection
	zf: '',
	r: '',
	xCentr: '',
	yCentr: '',	

	inverse: function (x, y) {
		var ph1, lm0;
		var ph, lm;
		var rho, tmp, c;
		
		if (getElemnt('globeForm').zl.value == 1) {
			return false;	
		}
		
		x = x - projection.xCentr;
		y = projection.yCentr - y;
		ph1 =  getElemnt('globeForm').ph.value * Math.PI / 180;
		lm0 =  getElemnt('globeForm').lm.value * Math.PI / 180;
		
		rho = Math.sqrt( x * x + y * y);
		tmp = rho / projection.r / projection.zf;
		
		if (Math.abs(tmp) > 1) {
			return false;
		}
		
		c = Math.asin(tmp);	
		ph = (rho > 0) ? ph = Math.asin( Math.cos(c) * Math.sin(ph1) + (y * Math.sin(c) * Math.cos(ph1) / rho)) : ph1;
		if (ph1 == 90) {
			lm = lm0 + Math.atan(x / - y);
		} else if (ph1 == - 90) {
			lm =  lm0 + Math.atan(x / y);
		} else {
			lm = lm0 + Math.atan2(x * Math.sin(c) , (rho * Math.cos(ph1) * Math.cos(c) - y * Math.sin(ph1) * Math.sin(c)));
		}
		
		if (ph > Math.PI_2) {
			ph -= Math.PI;
		} else if (ph < - Math.PI_2) {
			ph += Math.PI;
		}
		if (lm > Math.PI) {
			lm -= Math.PI * 2;
		} else if (lm < - Math.PI) {
			lm += Math.PI * 2;
		}
		
		ph = ph * 180 / Math.PI;
		lm = lm * 180 / Math.PI;
		
		return [ph, lm];
	},
	formatGeodetic: function (point) {
		var phDegrees = Math.abs(point[0]);
		var phMinutes = (phDegrees - Math.floor(phDegrees)) * 60;
		var phSeconds = (phMinutes - Math.floor(phMinutes)) * 60;
		phDegrees = Math.floor(phDegrees) + String.fromCharCode(176) + ' ' + Math.floor(phMinutes) + "'' " + Math.round(phSeconds) + "' ";
		phDegrees += (point[0] < 0) ? 'S' : 'N';
		
		var lmDegrees = Math.abs(point[1]);
		var lmMinutes = (lmDegrees - Math.floor(lmDegrees)) * 60;
		var lmSeconds = (lmMinutes - Math.floor(lmMinutes)) * 60;
		lmDegrees = Math.floor(lmDegrees) + String.fromCharCode(176) + ' ' + Math.floor(lmMinutes) + "'' " + Math.round(lmSeconds) + "' ";
		lmDegrees += (point[1] < 0) ? 'W' : 'E';
		
		return [phDegrees, lmDegrees];
	}
};

function setZoom(event, zl) {
	var nextUri = getBaseUri();
		nextUri += '?ph=' + getElemnt('globeForm').ph.value;
		nextUri += '&lm=' + getElemnt('globeForm').lm.value;
		nextUri += '&zl=' + zl;
		nextUri += getNextClickValue();
		nextUri += getAlbumNameValue();
		nextUri += getSessionIdValue();
	document.location.href = nextUri;
	return stopEvent(event);
}



// HELPERS
function getBaseUri() {
	var baseUri = getElemnt('globeForm').action.substr(0, getElemnt('globeForm').action.indexOf('index.php'));
	if (typeof(getElemnt('globeForm').waypointId) != 'undefined' && getElemnt('globeForm').waypointId.value > 0) {
		baseUri += 'waypointId-' + getElemnt('globeForm').waypointId.value + '/';
	}
	if (typeof(getElemnt('globeForm').countryPointId) != 'undefined' && getElemnt('globeForm').countryPointId.selectedIndex > 0) {
		baseUri += 'countryPointId-' + getElemnt('globeForm').countryPointId.options[getElemnt('globeForm').countryPointId.selectedIndex].value + '/';
	}
	if (typeof(getElemnt('globeForm').cityPointId) != 'undefined' && getElemnt('globeForm').cityPointId.selectedIndex > 0) {
		baseUri += 'cityPointId-' + getElemnt('globeForm').cityPointId.options[getElemnt('globeForm').cityPointId.selectedIndex].value + '/';
	}
	baseUri += 'index.php';
	return baseUri;
}
function getAlbumNameValue() { // for create new album only
	if ( ! getElemnt('albumNameField')) {
		return '';
	}
	return '&albumName=' + getElemnt('albumNameField').value;
}
function getNextClickValue() {
	if (typeof(getElemnt('globeForm').nextClick) == 'undefined') {
		return '';
	}
	for (n = 0; n < getElemnt('globeForm').nextClick.length; n++) {
		if (getElemnt('globeForm').nextClick[n].checked) {
			nextClick = getElemnt('globeForm').nextClick[n].value;
			break;
		}
	}
	if (nextClick == 'centerView') {
		return '';
	}
	return '&nextClick=' + nextClick;
}
function getSessionIdValue() {
	if (typeof(getElemnt('globeForm').sessionId) == 'undefined') {
		return '';
	}
	return '&sessionId=' + getElemnt('globeForm').sessionId.value;
}
preLoad.onAvailable('globeImg', globeInit, []);
preLoad.onAvailable('globeImg', tooltip.init, []);