
// Set Google maps API key
var arVersion = navigator.appVersion.split("MSIE"); 
var version = parseFloat(arVersion[1]); 

var baseIcon              = new GIcon();

baseIcon.iconSize         = new GSize(20, 34);
baseIcon.iconAnchor       = new GPoint(10,34);

baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(19, 29);

var masterIcon 			  = new GIcon();
masterIcon.iconSize 	  = new GSize(32, 32);
masterIcon.iconAnchor 	  = new GPoint(16, 16);
masterIcon.infoWindowAnchor = new GPoint(16, 0);

var polylines = [];
var markers   = [];

var i=0;

var map;
if(vCenterLat){ 
	var mapCenter = new GLatLng(vCenterLat, vCenterLng);
}
var mapcheck = false;
var arrDates = [];

var MarkersLoaded = false;

var tooltip = document.createElement('div');
tooltip.style.visibility = 'hidden'; 

var polyline;
var encPoly;
var encZoom;
var overlayColor;

function e(id) {return document.getElementById(id)}

function init(){
  if(!vYoutube&&vCenterLat){
    initMap();
  }
  loadPrevNext(vStartSchedID);
  labelLoad();
}

function loadtab(tab){
  if(tab=='map'){
	  setTimeout('initMap();', 1);  
  }else if(tab=='itin'){	  
  }else if(tab=='ship'){	  
  }else if(tab=='rooms'){	  
  }else if(tab=='inclusions'){	  
  }else if(tab=='webcam'){
	  loadWebcam();	  
  }
}

function loadWebcam(){
  var webcam = document.getElementById('webcam');
  webcam.src = vWebCam;
  setTimeout('loadWebcam();', 60000);
}

function visibleZoom(bounds) {
   var mapSize = map.getSize(); 
   if((mapSize.height > 230) && (mapSize.width > 260)) {
      mapSize = new GSize(mapSize.width - 30, mapSize.height - 30);
   }    
   return map.getCurrentMapType().getSpanZoomLevel(mapCenter, bounds.toSpan(), mapSize);
}

function schCompare(schedId, action){
	if((action=='add')&&(arrSess.length>=4)){//4 cruise limit
		yuiLimit.show();
	}else{
		var url = '/saveCruise.asp?sch='+schedId+'&action='+action;
		var request = YAHOO.util.Connect.asyncRequest('GET', url, { success:CompareCatcher, failure:CompareCatcher});
		var compareLink = e(schedId+'_compare');
		
		if(action=='add'){
			if(schedId !=''){
				arrSess[arrSess.length] = schedId;
			}
			compareLink.innerHTML = '<div id="'+schedId+'_compare"> <b>Added to Comparison</b> - <a href="#" title="Remove from cruise comparison" onclick="schCompare(\''+ schedId+'\', \'remove\'); return false;">Remove</a> - <a title="View cruise comparison" href="/cruise_compare.asp">View</a></div>';
		}else if(action=='remove'){
			compareLink.innerHTML = '<div id="'+schedId+'_compare"> <a href="#" title="Add to cruise comparison" onclick="schCompare(\''+ schedId+'\', \'add\'); return false;">Add to Comparison</a></div>';
			for(var j=0; j<arrSess.length;j++)if(arrSess[j].indexOf(schedId)!=-1){				
				arrSess.splice(j,1);
			}
		}		
	}
	function CompareCatcher(o){}
}

function labelLoad(){
	yuiLimit = new YAHOO.widget.Panel("yuilimit", { width:"320px", draggable:false, fixedcenter:true, visible:false, close:true, underlay:"matte", modal:false, effect:
{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.1}} );
	yuiLimit.setHeader("Too many cruises");	
	yuiLimit.setBody('You have already selected the maximum of 4 cruises to compare at the same time. Visit <a href="/cruise_compare.asp">Cruise Comparison</a> to review and remove an existing cruise before adding another one.');
	yuiLimit.render("container");	
}

function itin_select(portnum){
  var tabset = document.getElementById("menu");
  var links = tabset.getElementsByTagName("a");
  resetTabs();
  links[1].parentNode.className = "";
  links[0].parentNode.className = "active";	
  
  map.setMapType(G_SATELLITE_MAP);
  map.setCenter(markers[portnum].point, 13);
  markers[portnum].marker.openInfoWindowTabsHtml(markers[portnum].infoTabs);
}

function zoomin(num){
  if (map.getInfoWindow()){
	map.closeInfoWindow();
  }
  map.setMapType(G_SATELLITE_MAP);
  map.setCenter(markers[num].point, 13);
}

function myMouseOver(id) {
   if(tooltip.style.visibility == 'visible')
      return false; 
  
  var marker = markers[id].marker; 
  tooltip.innerHTML = markers[id].tooltipHTML;
    
   var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GLatLng(0, 0), true), map.getZoom()); 
   var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), map.getZoom()); 
   var anchor = marker.getIcon().iconAnchor; 
   var width = marker.getIcon().iconSize.width; 
   var height = tooltip.clientHeight; 
   var origin = new GSize(offset.x - point.x - anchor.x + width + 5, offset.y - point.y - anchor.y); 
   
   var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, origin);
   pos.apply(tooltip); 
   tooltip.style.visibility = 'visible'; 
   
   return true;
}

function myMouseOut(id) {
   tooltip.style.visibility = 'hidden';    
}

function myClick(id){
	/*if (map.getInfoWindow()){
	  map.closeInfoWindow();
	}*/
	
	var tempTab2 = '<tr>';
    tempTab2 += '<td style="text-align:justify"><img src="/images/ports/'+markers[id].port_id+'.jpg" height="240" width="320" border="0" style="padding-left:15px; padding-top:10px; padding-bottom:10px;"></td>';
    tempTab2 += '</tr>';
    tempTab2 += '</table></div>';
	
	markers[id].tab2 = markers[id].tabtop + tempTab2;
	
	/*var infoTabs = [
				  new GInfoWindowTab('Image', markers[id].tab2)
				  
				  ];*/
	var infoTabs = [
				  new GInfoWindowTab('Image', markers[id].tab2),
				  new GInfoWindowTab('Port Details', markers[id].tab1)
				  ];
	
	if (map.getInfoWindow()){
		map.closeInfoWindow();
	}
	markers[id].infoTabs = infoTabs;
	markers[id].marker.openInfoWindowTabsHtml(markers[id].infoTabs);
}

function createMarker(xml) {
   this.id = markers.length; 
   markers.push(this);
   this.latitude = parseFloat(xml.getAttribute("latitude")); 
   this.longitude = parseFloat(xml.getAttribute("longitude")); 
   this.day_of_cruise = parseInt(xml.getAttribute("day_of_cruise"));   
   this.port_id = xml.getAttribute("port_id"); 
   this.port_name = xml.getAttribute("port_name"); 
   this.country = xml.getAttribute("country"); 
   this.description = xml.getAttribute("description");
   
   this.tooltipHTML = '<div class="tooltip">Day '+ this.day_of_cruise +' - '+ this.port_name +', '+ this.country +'<Br>Click for details</div>';
   
   var html = '<tr>';
    html += '<td style="text-align:justify"><br>' + this.description + '</td>';
    html += '</tr>';
    html += '</table></div>';
   
   var tablinks = '<br><a href="http://www.panoramio.com/map/#lt='+this.latitude+'&ln='+this.longitude+'&z=4&k=2&a=1" target="_blank">View nearby photos at Panoramio</a>';
  tablinks += '<br><a href="http://www.youtube.com/results?search_type=search_videos&search_query='+this.port_name+'&search_sort=relevance&search_category=19" target="_blank">View traveller videos at YouTube</a>';	
	
  var tabtop = '<div><table border="0" cellspacing="0" cellpadding="0" width="350">';
    tabtop += '<tr>';
    tabtop += '<td><strong>Day '+ this.day_of_cruise +' - '+ this.port_name +', '+ this.country +'</strong><span style="font-size:80%;text-align:right;"><a href="#" onclick="zoomin(\''+this.id+'\')"> zoom in</a>&nbsp;<a href="#" onclick="map.returnToSavedPosition();map.setMapType(G_PHYSICAL_MAP);map.closeInfoWindow();"> full map</a></span></td>';
    tabtop += '</tr>';
  		
	var tab2;

   var tab1 = tabtop + html + tablinks;
  tab2 = tabtop + tab2;   
  this.tabtop = tabtop;  
  this.tab1 = tab1;
  this.tab2 = tab2; 
  
  var point = new GLatLng(this.latitude, this.longitude);
  var icon = new GIcon(baseIcon);
  icon.image    = '/images/icons/iconx'+this.day_of_cruise+'.png';
  this.point = point;
  this.marker = new GMarker(point, icon);
  
  /*var infoTabs = [
				  new GInfoWindowTab('Image', this.tab2),
				  new GInfoWindowTab('Port Details', this.tab1)
				  ];
	  
  this.infoTabs = infoTabs;*/
  
  /*this.marker.bindInfoWindowTabsHtml(this.infoTabs);*/
  
  GEvent.addListener(this.marker, 'mouseover', new Function('myMouseOver(' + this.id + ')'));
  GEvent.addListener(this.marker, 'mouseout', new Function('myMouseOut(' + this.id + ')'));
  GEvent.addListener(this.marker, "click", new Function('myClick('+this.id+')'));
}

function loadMarkers() {
  var url = '/itinerary_xml.asp?cruise_id=' + vCruise;
   
  var request = GXmlHttp.create(); 
  request.open("GET", url, true); 
  request.onreadystatechange = function() {
	  if(request.readyState == 4) {
         var thisPort; 
         var bounds = new GLatLngBounds(); 
         var xmlDoc = request.responseXML; 
         var markerNodes = xmlDoc.documentElement.getElementsByTagName("marker"); 
         if(!markerNodes.length) {            
            return;
		 }        
         for(var n = 0; n < markerNodes.length; n++) {
            thisPort = new createMarker(markerNodes[n]); 
            bounds.extend(new GLatLng(thisPort.latitude, thisPort.longitude));
         }
         
		 var zoom = visibleZoom(bounds);
		 //if((zoom >= 10) && (zoom <= 17)) {
			 mapCenter = bounds.getCenter();
			 map.setCenter(mapCenter, zoom);              
		 //}
		 showMarkers();
	  }	  
	}; 
  request.send(null);  
}

function drawPoly(){
  var url = '/cruise_xml.asp?cruise_id=' + vCruise; 
  var request = GXmlHttp.create(); 
  request.open("GET", url, true); 
  request.onreadystatechange = function() {
	  if(request.readyState == 4) {
         var xmlDoc = request.responseXML; 
         var markerNodes = xmlDoc.documentElement.getElementsByTagName("marker"); 
         encPoly = markerNodes[0].getAttribute("polyline");
		 encZoom = markerNodes[0].getAttribute("zoom");
		 crunchPoly(encPoly, encZoom);		 
	  }	  
	}; 
  request.send(null);
}

var polyline = new GPolyline();

function crunchPoly(){
  //if(map.getPane(polyline)){
	//  map.removeOverlay(polyline);  
	  map.clearOverlays();
  //}
  var overlayColor;
  var overlayThickness;
  if(map.getCurrentMapType()==G_SATELLITE_MAP){
    overlayColor = '#07B3C1';
	overlayThickness = 2;
  }else if(map.getCurrentMapType()==G_SATELLITE_3D_MAP){
	overlayColor = 'ffc1b307';
	overlayThickness = 2;	  
  }else{
    overlayColor = '#000000';
	overlayThickness = 4;
  }
  
  if(map.getCurrentMapType()==G_SATELLITE_3D_MAP){	  
	  var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
	  var lat = lookAt.getLatitude();
	  var lng = lookAt.getLongitude();
	  
	  var lineStringPlacemark = ge.createPlacemark('');
	  var lineString = ge.createLineString('');
	  lineStringPlacemark.setGeometry(lineString);
	  lineString.setTessellate(true);
	  
	  for(var i=0; i<polyline.d.length; i++){
		  lineString.getCoordinates().pushLatLngAlt(polyline.d[i].y, polyline.d[i].x, 0);
	  }	  
	  
	  if (!lineStringPlacemark.getStyleSelector()) {
		  lineStringPlacemark.setStyleSelector(ge.createStyle(''));
	  }
	 
	  var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
	  lineStyle.setWidth(overlayThickness);
	  lineStyle.getColor().set(overlayColor);
	  
	  ge.getFeatures().appendChild(lineStringPlacemark);	  
  }else{
	  polyline = GPolyline.fromEncoded({
									   color: overlayColor,
									   weight: 2,
									   opacity: 0.99,
									   points: encPoly,
									   levels: encZoom,
									   zoomFactor: 2,	
									   numLevels: 18
									   });
	  map.addOverlay(polyline);	  
  }
  showMarkers();
}

function showMarkers(){
  for(var i=markers.length-1; i>-1; i--){
	  //if(markers[i].showOnMap == 'True'){
	    map.addOverlay(markers[i].marker);
	  //}
  }	
  map.savePosition();
}

function initMap() {
  var mapdiv = e("map"); 
  map = new GMap2(mapdiv); 
  var mt = map.getMapTypes();   
      
  map.setCenter(mapCenter, 4);
  map.removeMapType(G_HYBRID_MAP);
  map.addMapType(G_PHYSICAL_MAP);
  //map.addMapType(G_SATELLITE_3D_MAP);
  map.setMapType(G_PHYSICAL_MAP);  
  
  map.addControl(new GScaleControl()); 
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  //map.addControl(new GHierarchicalMapTypeControl());
  //map.getEarthInstance(getEarthInstanceCB);
  
  drawPoly();
    
  map.enableDoubleClickZoom(); 
  map.enableContinuousZoom();  
  
  GEvent.addListener(map, "maptypechanged", new Function('crunchPoly();')); 
  
  mapcheck = true;
  
  var mapSize = map.getSize(); 
 
  map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
  
  if(markers.length==0){
	  loadMarkers();
  }    
}

var ge;
function getEarthInstanceCB(object) {
  ge = object;
}

function finalize() {
 GUnload();
}
