
var map;
var gdir;
var svp;
var svOverlay;
var panoClient;
var arrowmarker;
var spiraltimer;
var panoavailable;
var sfpanodata;

var cyosf_active = false;

var lastPoint;
var clickloc = false;
var trafficInfo;
var geocoder;
var reasons=[];
var globalproxdistance=5;
var defaultzoom = 13;
var destinationzoom = 16;
var mapclickactive = false;
var tbmapclickactive = false;
var currentYaw = 180;
var currentPitch = 0;
var spiralon = 1;
var currentZoom = 0;
var zoomingIn = true;
var langlocale='en';
var mapcenter_lat = 51.890053935216926;
var mapcenter_lng = -97.470703125;
var initzoom = 4;
var initmaptype;
var dynamicmarker;
var markericon = "cplanet_stand.png";
var markerpath  = "/globalgraphics/markers/";
var markerstandard = markerpath+markericon;
var markerimage = markerpath+markericon;
var markerimagesave = markericon;
var location_marker;
var linecolor = '#990000';

var locmarker;
var currentresponse;
var currentlocation=[];
var currenttourlocation = [];
var savedestination=[];
var savedestinationname;
var savedestinationid;
var action;
var geopurpose = '';
var savestring;
var createmarker;
var mastercreatetype;
var locsearchtype;
var mod_searchstring='';
var api_inputstring='';
var search_locstring='';
var non_usaloc = false;
var mashup_searchstring='';
var mediamarker;
var globaldirectionpoint;

var activemarker;
var activedescription;
var activeevent=[];
var editdest;
var formtype;
var contextmenu;
var savecount=1;
var destinationloc;

var showsearchrad = false;
var CircleOverlay;
var circle = null;
var circleRadius = 50; // Miles
var tooltip;

var destbubbleform_t1
var destbubbleform_t2


// HIGHSLIDE FUNCTIONS USED
// highslidecontrol('agr') - args used: dynhtml, dynhtmloff, explore, pano, panooff, directions, 
function sendresponse(responsehtml, responseheader){
	//document.getElementById("dynhtmlcontent").innerHTML = responsehtml;
	//document.getElementById('dynheader').innerHTML = responseheader;
	//highslidecontrol('dynhtml');
	displayMessage(responsehtml, responseheader)
}



//**************************************************MAP FUNCTIONS*************************************************
// CREATE THE GOOGLE MAP
function loadmap(){
	
	if (GBrowserIsCompatible()) {
		
		panoClient = new GStreetviewClient();
		trafficInfo = new GTrafficOverlay();
		geocoder = new GClientGeocoder();
		
		map = new GMap2(mapdiv);
		map.enableScrollWheelZoom();
		map.enableDoubleClickZoom();
		//map.addControl(new GLargeMapControl());
	  	//map.addControl(new GMapTypeControl());
		
		configmap(new GLatLng(mapcenter_lat,  mapcenter_lng), initzoom, initmaptype);
		initcircle();
		
		var mapsetup = 'success';
		
		return mapsetup;
		
	}else{
		alert('Your Browser is not configured to use the Google Map API.');
		var mapsetup = 'failed';
		return mapsetup;
	}
	
}

function resetmap(){
	configmap(new GLatLng(mapcenter_lat,  mapcenter_lng), initzoom, initmaptype);
}

function addcustommarkers(){
	// Create our "standard" marker icon
		var DynamicIcon = new GIcon();
		DynamicIcon.image = "/globalgraphics/markers/cplanet_stand.png";
		DynamicIcon.shadow = "/globalgraphics/markers/standard_shadow.png";
		DynamicIcon.iconSize = new GSize(34, 45);
		DynamicIcon.shadowSize = new GSize(45, 45);
		DynamicIcon.iconAnchor = new GPoint(7, 45);
		DynamicIcon.infoWindowAnchor = new GPoint(12, 5);
	
	
// Create our "location" marker icon
		var LocationIcon = new GIcon();
		LocationIcon.image = "/globalgraphics/markers/location_marker.png";
		LocationIcon.shadow = "/globalgraphics/markers/location_shadow.png";
		LocationIcon.iconSize = new GSize(36, 45);
		LocationIcon.shadowSize = new GSize(60, 45);
		LocationIcon.iconAnchor = new GPoint(7, 45);
		LocationIcon.infoWindowAnchor = new GPoint(12, 5);
		
		
		location_marker = LocationIcon;
		dynamicmarker = DynamicIcon;
		
}


function setup_mapcontrols(){
//ADDS AND POSITIONS A DIV FOR EXTRA MAP CONTROLS
		var pos_mapcontrols = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(3,60));
		pos_mapcontrols.apply(mapcontrolsdiv);
		map.getContainer().appendChild(mapcontrolsdiv);
		
}

function setup_createcontrols(){
	//ADDS AND POSITIONS A DIV FOR CREATE CONTROLS
		var pos_create = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(3,3));
		pos_create.apply(mapcreatetoolsdiv);
		map.getContainer().appendChild(mapcreatetoolsdiv);
	
	
//RIGHT CLICK MENU FUNCTIONALITY
	// === create the context menu div ===
	  contextmenu = document.createElement("div");
	  contextmenu.style.visibility="hidden";
	  contextmenu.style.background="#ffffff";
	  contextmenu.style.border="1px solid #8888FF";

	  contextmenu.innerHTML = '<div>'
	  						  +'<img id="mapclickbut_cur" src="globalgraphics/dmo_menu/dmo_mapclick.jpg" border="0" onclick="markthemap(\'click\')" onmouseover="this.style.cursor=\'pointer\'" />'
							  +'<img id="mapclickexact" src="globalgraphics/dmo_menu/dmo_mapclick_exact.jpg" border="0" onclick="markthemap(\'clickfortour\')" onmouseover="this.style.cursor=\'pointer\'" />'
							  +'<img id="maplatlng" src="globalgraphics/dmo_menu/dmo_mapclick_exact.jpg" border="0" onclick="markthemap(\'latlng\')" onmouseover="this.style.cursor=\'pointer\'" />'
							  +'</div>';
							

	  map.getContainer().appendChild(contextmenu);
	  
	  
	  
	  radinfobox = document.createElement("div");
	  radinfobox.style.visibility="hidden";
	  radinfobox.style.background="#ffffff";
	  radinfobox.style.border="1px solid #8888FF";

	  radinfobox.innerHTML = '<div></div>';
	  map.getContainer().appendChild(radinfobox);

	  // === listen for singlerightclick ===
	  GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
		// store the "pixel" info in case we need it later
		// adjust the context menu location if near an egde
		// create a GControlPosition
		// apply it to the context menu, and make the context menu visible
		clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
		if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
		if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
		var pos_rightclick = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
		pos_rightclick.apply(contextmenu);
		contextmenu.style.visibility = "visible";
	  });
	  
	  GEvent.addListener(map, "click", function() {
		contextmenu.style.visibility="hidden";
		radinfobox.style.visibility="hidden";
	  });
	  
	  // ====== set up marker mouseover tooltip div ======
      tooltip = document.createElement("div");
      document.getElementById("map").appendChild(tooltip);
      tooltip.style.visibility="hidden";
}

function setup_intdirections(){
	
	//INTERNAL DIRECTIONS FUNCTIONS
		// === create a GDirections Object ===
		  gdir=new GDirections(map, mapdirectionsdiv);
	
		  // === Array for decoding the failure codes ===
		  
		  reasons[G_GEO_SUCCESS]            = "Success";
		  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
		  reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		  reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
		  reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
	
		  // === catch Directions errors ===
		  GEvent.addListener(gdir, "error", function() {
			var code = gdir.getStatus().code;
			var reason="Code "+code;
			if (reasons[code]) {
			  reason = reasons[code]
			} 
	
			alert("Failed to obtain directions, "+reason);
		  });
	  
}

function createstreetview(){
	svp = new GStreetviewPanorama(mappanodiv);	
}

function init_streetview(){
		
		if(!svp){
			createstreetview();
		}
			
      	GEvent.addListener(svp, "error", handleNoFlash);
		svOverlay = new GStreetviewOverlay();

//STREETVIEW LOCATOR
		var guyIcon = new GIcon(G_DEFAULT_ICON);
		  guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
		  guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
		  guyIcon.imageMap = [
				26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
				16,20, 16,14, 19,13, 22,8
			 ];
		  guyIcon.iconSize = new GSize(49, 52);
		  guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
		  guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head

		arrowmarker = new GMarker(new GLatLng(90,0),{icon:guyIcon});
      	map.addOverlay(arrowmarker) ;	
	  
	  	map.addOverlay(svOverlay);
		
		GEvent.addListener(map,"click",function(overlay,point) {
			if (!overlay) {
			  svp.remove();
			  svp.setLocationAndPOV(point);
			  arrowmarker.setLatLng(point);
			  lastPoint = point;
			}
			if(overlay==null){
				panoClient.getNearestPanorama(point, handlepanoreponse);
			}
		  });
	
		  GEvent.addListener(svp,"yawchanged",function(yaw) {
 			  var GUY_NUM_ICONS = 16;
			  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
			  if (yaw < 0) {
				yaw += 360;
			  }
			  guyImageNum = Math.round(yaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  			  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  			  arrowmarker.setImage(guyImageUrl);
			//var dir = Math.round(yaw/3) * 3;
			//while (dir >= 120) {dir -= 120;}
			//arrowmarker.setImage("http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-"+dir+".png");
		  });
	
		  GEvent.addListener(svp,"initialized",function(a) {
			arrowmarker.setLatLng(a.latlng);
			map.addOverlay(new GPolyline([lastPoint,a.latlng], '#990000', 8));
			map.setCenter(a.latlng, 17);
			lastPoint = a.latlng;
		  });
		  
		  panotoggleState = 1;
}

function handleNoFlash(errorCode) {
	if (errorCode == 603) {    
		alert("Error: Flash doesn't appear to be supported by your browser");
		toggletraffic();
		return;  
	}
} 


function clearmap(){
	try{
		tooltip.style.visibility="hidden";
		circle.remove();
	}catch(err){
	}
	
	map.clearOverlays();
	if(traffictoggleState==1){
		map.addOverlay(trafficInfo);
	}
	
	if(panotoggleState==1){
		map.addOverlay(svOverlay);
		map.addOverlay(arrowmarker);
	}
	
	//alert('clearing overlays');
}

function createmenu(){
	var offset=map.getSize().width - 225
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50,70));  
    pos.apply(contextmenu);
	contextmenu.style.visibility = "visible";
}

function toggletraffic() {
      if (traffictoggleState == 1) {
        map.removeOverlay(trafficInfo);
        traffictoggleState = 0;
      }else{
        map.addOverlay(trafficInfo);
        traffictoggleState = 1;
      }
}

function togglepano() {
	if(includepano == 1){
	  if (panotoggleState == 1) {
		map.removeOverlay(svOverlay);
		arrowmarker.hide();
		highslidecontrol('panooff');
		panotoggleState = 0;
	  } else {
		  if(!svp){
			 alert('initalizing streetview');
			init_streetview();
		  }else{
			map.addOverlay(svOverlay);
			arrowmarker.show();
			panotoggleState = 1;
		  }
	  }
	}
}

function handlepanoreponse(panoData){
	if (panoData.code != 200) {
		showPanoData('off');
	}else{
		showPanoData('show', panoData);
	}
}

function panocheck(){
	panoClient.getNearestPanorama(currentlocation[0].point, ispanoavailable);	
}

function ispanoavailable(panoData){
	//alert('inside pano');
	if (panoData.code != 200) {
		 panoavailable = false;
	}else{
		 panoavailable = true;
		 sfpanodata = panoData;
		 
		 try{
			 //alert('pano is available');
		 	document.getElementById("panobutton").innerHTML = '<img src="globalgraphics/general/streetview_on.jpg" border="0" onclick="showsfpano()" onmouseover="this.style.cursor=\'pointer\'" />';			
		 }catch(err){
			//Handle errors here
		}
		 
			 
		if(!svp){
			createstreetview();
		}
		
	}
	
}

function showsfpano(){
	
	highslidecontrol('pano');
	poppano();

}

function poppano(){
	
	svp.setLocationAndPOV(sfpanodata.location.latlng);	
	
	mappanodetailsdiv.innerHTML = sfpanodata.location.description;
	
	spiraltimer = window.setInterval(spiral, 200);

}

function showlocpano(){
	showPanoData(state, panoData)	
}


function showPanoData(state, panoData) {
	if (state=='off') {
		try{
			highslidecontrol('panooff');
			arrowmarker.hide();
			//alert('showPanoData: Server rejected with code: ' + panoData.code);    
			return;  
		}catch(err){
			highslidecontrol('panooff');
			return;  
		}
		
	}else{  
		//alert('showPanoData: Server rejected with code: ' + panoData.code);   
		arrowmarker.show();
		highslidecontrol('pano');		
		
//		var displayString = '<div id="streetinfo" style="width:250px;">'
//							+'Panorama ID: ' + panoData.location.panoId    
//							+'<br>LatLng: ' + panoData.location.latlng    
//							+'<br>Copyright: ' + panoData.copyright    
//							+'<br>Description: ' + panoData.location.description; 
//							+'</div>';
		
		mappanodetailsdiv.innerHTML = panoData.location.description;
		setTimeout("resizepano()", 600);
		//map.openInfoWindowHtml(panoData.location.latlng, displayString);      
		//GLog.write('Viewer moved to' + panoData.location.latlng); 
		svp.setLocationAndPOV(panoData.location.latlng);
		svp.show();
		spiraltimer = window.setInterval(spiral, 200);
		
		setTimeout("sendpanoagain("+panoData.location.latlng+")", 1000);
	}
}

function sendpanoagain(panopoint){
	svp.setLocationAndPOV(panopoint);
}

function resizepano(){
	
	var panowidth=highslidepanodiv.offsetWidth;
	var panoheight=highslidepanodiv.offsetHeight;
	//mappanodetailsdiv.innerHTML = panowidth+'  ,  '+panoheight;
	mappanodiv.style.width=(panowidth-35)+'px';
	mappanodiv.style.height=(panoheight-70)+'px';
	
	svp.checkResize();
	svp.show();
}


function spiral() {
	if(spiralon==1){
		currentYaw += 2;
  		svp.panTo({yaw:currentYaw, pitch:currentPitch});
	}
}

function restartspiral(){
	spiralon=1;
	spiraltimer = window.setInterval(spiral, 400);
}


function stopspiral(){
	window.clearInterval(spiraltimer);
	spiraltimer=null;
	spiralon=0;
}


function zoom() {
	
	  if (zoomingIn) {
		currentZoom++;
	  } else {
		currentZoom--;
	  }
	
	  svp.panTo({yaw:currentYaw, pitch:currentPitch, zoom:currentZoom});
	  if (currentZoom == 2) {
		zoomingIn = false;
	  }
	  if (currentZoom == 0) {
		clearInterval(timer);
		timer = window.setInterval(spiral, 200);
	  }
	  
}


//CONFIGURES THE MAP TYPE THEN CENTERS AND ZOOMS THE MAP.
function configmap(point, zoom, type){
	
	if (type){
		
		switch (type){
			case 'Map':
				map.setMapType(G_NORMAL_MAP);
			break;
		
			case 'Hybrid':
				//alert('setting map type');
				map.setMapType(G_HYBRID_MAP);
			break;
		
			case 'Satellite':
				map.setMapType(G_SATELLITE_MAP);
			break;
		}		
	}
	
	if(zoom){
		map.setCenter(point, zoom);
	}else{
		map.setCenter(point, destinationzoom);
	}
	
}


//MAP LOCATION SEARCH FUNCTION 1 - CALLED FROM SEARCHBOXES - SORTS AND SUBMITS
function callgeocode(loc){
	//alert(loc);
	geocoder.getLocations(loc, processgeoresponse);
	
}

function setmarkeratlocation(address){
	locsearchtype='location';
	geocoder.getLocations(address, addAddressToMap);	
}

function setsearchcenter(address){
	if(dmoflag == true){
		geopurpose = 'locsearch';
	}else{
		geopurpose = 'comguide';
	}
	callgeocode(address);	
}

function setsearchcenterpoint(lat, lng){
	var point = new GLatLng(lat,lng);
	//alert(point);
	if(dmoflag == true){
		geopurpose = 'locsearch';
	}else{
		geopurpose = 'comguide';
	}
	
	clickloc = true;
	geocoder.getLocations(point, processgeoresponse);	
}

function cleansearchstring(searchstring){
	var newstring=searchstring.replace(/,/g, '');
	newstring=newstring.replace(/'/g, '\'');
	
	//alert(newstring);
	return newstring;
}

function cleanstring(searchstring){
	var newstring=searchstring.replace(/'/g, "\\'");
	newstring=newstring.replace(/|/g, '');
	
	//alert(newstring);
	return newstring;
}

//MAP LOCATION SEARCH FUNCTION - CALLED FROM SEARCHBOXES
function processgeoresponse(response) {
		var responsehtml;
      	currentresponse = response;
		if (response.Status.code == G_GEO_SUCCESS) {
			if ((response.Placemark.length > 1) && (clickloc == false)) { 
				//alert(response.Placemark.length);
				responsehtml = "<b>Did you mean:</b>";
				for (var i=0; i<response.Placemark.length; i++) {
					
				  var accuracy = response.Placemark[i].AddressDetails.Accuracy;
				  //alert(accuracy);
				  var lng = response.Placemark[i].Point.coordinates[0];
				  var lat = response.Placemark[i].Point.coordinates[1];
					
				  responsehtml += "<hr />"+(i+1)+": <a href='javascript:resultfromlist(" +accuracy+", "+lat+", "+lng+", \""+response.Placemark[i].address+ "\")'>"+ response.Placemark[i].address+"</a>";
				  
				}
				
				sendresponse(responsehtml);
				
			}else {
				var i=0;
				var accuracy = response.Placemark[i].AddressDetails.Accuracy;
				var lng = response.Placemark[i].Point.coordinates[0];
				var lat = response.Placemark[i].Point.coordinates[1];
				
				if (accuracy==3){
					//alert(response.Placemark[i].address);
					var county = response.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
					parselocation(accuracy, lat, lng, response.Placemark[i].address, county);
				}else{
					parselocation(accuracy, lat, lng, response.Placemark[i].address);
				}
				
				clickloc = false;
			}
		}
		// ====== Decode the error status ======
		else {
		  var reason="Code "+response.Status.code;
		  if (reasons[response.Status.code]) {
			reason = reasons[response.Status.code]
		  } 
		  mod_searchstring='';
		  alert('Could not find the location you entered \n' + reason);
		}
			
}

function resultfromlist(accuracy, lat, lng, address, county){
	highslidecontrol('dynhtmloff');
	parselocation(accuracy, lat, lng, address, county)	
}

function parselocation(accuracy, lat, lng, address, county){
	//alert(accuracy+' ---- '+address);
	var blank='';
	var currentlocation_country =  blank;
	var currentlocation_state =  blank;
	var currentlocation_county =  blank;
	var currentlocation_city =  blank;
	var currentlocation_zip =  blank;
	var currentlocation_address =  blank;
	var currentlocation_point =  blank;
	
	var temp_mod_searchstring;
	var temp_search_locstring;
	
	switch (accuracy){
		case 0:
			//alert('Search not found\nPlease refine your search and try again');
		break;
		
		case 1:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==2){
				currentlocation_country=locstring[1];
				currentlocation_state=locstring[0];
			}
			mod_searchstring=currentlocation_state;
			
			currentlocation_country = address;
			temp_mod_searchstring=currentlocation_country;
			temp_search_locstring=temp_mod_searchstring;
			//alert('Country: '+address);
		break;
		
		case 2:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==2){
				currentlocation_country=locstring[1];
				currentlocation_state=locstring[0];
			}
			temp_mod_searchstring=currentlocation_state;
			temp_search_locstring=temp_mod_searchstring;
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]);
		break;
		
		case 3:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==2){
				currentlocation_country=locstring[1];
				currentlocation_state=locstring[0];
				temp_mod_searchstring=currentlocation_county+' '+currentlocation_state;
				temp_search_locstring=temp_mod_searchstring;
			}
			if(locstring.length==3){
				currentlocation_country=locstring[2];
				currentlocation_state=locstring[1];
				currentlocation_city=locstring[0];
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=temp_mod_searchstring;
			}
			
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]+'\n County:'+county);
		break;
		
		case 4:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==2){
				currentlocation_country=locstring[1];
				currentlocation_city=locstring[0];
				temp_mod_searchstring=currentlocation_city;
				temp_search_locstring=temp_mod_searchstring;
			}
			if(locstring.length==3){
				currentlocation_country=locstring[2];
				currentlocation_state=locstring[1];
				currentlocation_city=locstring[0];
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=temp_mod_searchstring;
			}
			if(locstring.length==4){
				currentlocation_country=locstring[3];
				currentlocation_state=locstring[2];
				currentlocation_city=locstring[0];
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=temp_mod_searchstring;
			}
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]);
		break;
		
		case 5:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==3){
				currentlocation_country=locstring[2];
				var splitzip=locstring[1].split(' ');
				currentlocation_state=splitzip[0];
				currentlocation_zip=splitzip[1];
				currentlocation_city=locstring[0];
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=temp_mod_searchstring;
			}else{
				
				currentlocation_address = getgeoaddress();
				currentlocation_city = getgeocity();
				currentlocation_state = getgeostate();
				currentlocation_zip = getgeozip();
				currentlocation_country = getgeocountry();
				
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
				
			}
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]);
		break;
		
		case 6:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==4){
				currentlocation_country=locstring[3];
				ziptest=locstring[2].search(' ');
				if (ziptest!= -1){
					var splitzip=locstring[2].split(' ');
					currentlocation_state=splitzip[0];
					currentlocation_zip=splitzip[1];
				}else{
					currentlocation_state=locstring[2];
				}	
				currentlocation_city=locstring[1];
				currentlocation_address=locstring[0];
			}
			
			temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
			temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]+'\n County:'+county);
		break;
		
		case 7:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==4){
				currentlocation_country=locstring[3];
				ziptest=locstring[2].search(' ');
				if (ziptest!= -1){
					var splitzip=locstring[2].split(' ');
					currentlocation_state=splitzip[0];
					currentlocation_zip=splitzip[1];
				}else{
					currentlocation_state=locstring[2];
				}	
				currentlocation_city=locstring[1];
				currentlocation_address=locstring[0];
				
				
			}
			
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]+'\n County:'+county);
		break;
		
		case 8:
			var locstring = address.split(', ');
			//alert(locstring.length);
			if(locstring.length==4){
				currentlocation_country=locstring[3];
				ziptest=locstring[2].search(' ');
				if (ziptest!= -1){
					var splitzip=locstring[2].split(' ');
					currentlocation_state=splitzip[0];
					currentlocation_zip=splitzip[1];
				}else{
					currentlocation_state=locstring[2];
				}	
				currentlocation_city=locstring[1];
				currentlocation_address=locstring[0];
				
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
			
			}else{
				
				currentlocation_address = getgeoaddress();
				currentlocation_city = getgeocity();
				currentlocation_state = getgeostate();
				currentlocation_zip = getgeozip();
				currentlocation_country = getgeocountry();
				
				temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
				temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
				
			}
			
			
		default:
			var locstring = address.split(', ');
			//alert(locstring.length);
			switch(locstring.length){
				
				case 3:
					currentlocation_country=locstring[2];
					ziptest=locstring[1].search(' ');
					if (ziptest!= -1){
						var splitzip=locstring[1].split(' ');
						currentlocation_state=splitzip[0];
						currentlocation_zip=splitzip[1];
					}else{
						currentlocation_state=locstring[1];
					}
				break;
				
				case 4:
					currentlocation_country=locstring[3];
					ziptest=locstring[2].search(' ');
					if (ziptest!= -1){
						var splitzip=locstring[2].split(' ');
						currentlocation_state=splitzip[0];
						currentlocation_zip=splitzip[1];
					}else{
						currentlocation_state=locstring[2];
					}
				break;
				
				default:
					currentlocation_address = getgeoaddress();
					currentlocation_city = getgeocity();
					currentlocation_state = getgeostate();
					currentlocation_zip = getgeozip();
					currentlocation_country = getgeocountry();
				break;
				
			}
			
			temp_mod_searchstring=currentlocation_city+' '+currentlocation_state;
			temp_search_locstring=currentlocation_address+' '+temp_mod_searchstring;
			
			//alert('Accuracy:'+accuracy+'\n 1:'+locstring[0]+'\n 2:'+locstring[1]+'\n 3:'+locstring[2]+'\n 4:'+locstring[3]+'\n 5:'+locstring[4]+'\n County:'+county);
		break;
	}
	
	
	var currentlocation_fulladdress = address.replace(/\./g,"");
	var currentlocation_lat = lat;
	var currentlocation_lng = lng;
	var currentlocation_point = new GLatLng(lat, lng);
	
	if((currentlocation_country != 'USA') && (currentlocation_country != 'US')){
		temp_mod_searchstring = currentlocation_city+' '+currentlocation_country;
		non_usaloc = true;
	}else{
		non_usaloc = false;
	}
	
	temp_mod_searchstring=temp_mod_searchstring.replace(/\./g,"");
	temp_search_locstring=temp_search_locstring.replace(/\./g,"");
	
	
	currentlocation[0] = new popcurrentlocation(accuracy, currentlocation_fulladdress, currentlocation_lat, currentlocation_lng,  currentlocation_point, currentlocation_country, currentlocation_state, county, currentlocation_city, currentlocation_zip, currentlocation_address);
	
	mod_searchstring = temp_mod_searchstring;
	search_locstring = temp_search_locstring;
	api_inputstring = mod_searchstring;
		
	//alert(accuracy+'  ,  '+mod_searchstring+'  ,  '+search_locstring);

	
	handleresult();
	
}


function getgeoaddress(){
	try{
		var currentlocation_address = currentresponse.Placemark[i].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
	}catch(err){
		var currentlocation_address = '';
	}
	
	return currentlocation_address;
}

function getgeocountry(){
	try{
		var currentlocation_country = currentresponse.Placemark[0].AddressDetails.Country.CountryNameCode;
	}catch(err){
		var currentlocation_country = '';
	}
	
	return currentlocation_country;
}

function getgeostate(){
	try{
		var currentlocation_state = currentresponse.Placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
	}catch(err){
		var currentlocation_state = '';
	}
	
	return currentlocation_state;
}

function getgeocity(){
	try{
		var currentlocation_city = currentresponse.Placemark[i].AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
	}catch(err){
		var currentlocation_city = '';
	}
	
	return currentlocation_city;
}

function getgeozip(){
	try{
		var currentlocation_zip = currentresponse.Placemark[i].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
	}catch(err){
		var currentlocation_zip = '';
	}
	
	return currentlocation_zip
}


function handleresult(){
	
	switch (geopurpose){
		case 'create':
			markaddress();
		break;
		
		case 'createcthere':
			cthereaddress();
		break;
		
		case 'storefront':
			storefrontaddress();
		break;
		
		case 'bizsearch':
			globallocation = currentlocation[0].fulladdress;
			searchyahoo('search', 'initial', 'business');
		break;
		
		case 'centermap':
			configmap(currentlocation[0].point, defaultzoom);
		break;
		
		case 'comguide':
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, true, true);
		break;
		
		case 'locsearch':
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, true, false);
		break;
		
		case 'adddesttopp':
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, false, false);
		break;
		
		case 'tripbuilder':
			tb_active = true;
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, true, true);
			closeextajax();
		break;
		
		case 'sponsor':
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, false, false);
		break;
		
		default:
			globallocation = currentlocation[0].fulladdress;
			setcurrentlocation(true, true, true);
		break;
	}
	geopurpose = '';
	
}


function popcurrentlocation(accuracy, fulladdress, lat, lng, point, country, state, county, city, zip, address){
	
	this.accuracy=accuracy;
	this.fulladdress=fulladdress;
	this.lat = lat;
	this.lng = lng;
	this.point=point;
	this.country=country;
	this.state=state;
	this.county=county;
	this.city=city;
	this.zip=zip;
	this.address=address;
}

function popsavedestination(destinationid, name, description, desttags, public, address1, address2, city, state, zip, country, phone, fax, weblink, email, datemanual, datecreated, lat, lng, zoom, maptype, marker){
	
	this.destinationid=destinationid;
	this.name=name;
	this.description=description;
	this.desttags=desttags;
	this.public=public;
	this.address1=address1;
	this.address2=address2;
	this.city=city;
	this.state=state;
	this.zip=zip;
	this.country=country;
	this.phone=phone;
	this.fax=fax;
	this.weblink=weblink;
	this.email=email;
	this.datemanual=datemanual;
	this.datecreated=datecreated;
	this.lat = lat;
	this.lng = lng;
	this.zoom= zoom;
	this.maptype=maptype;
	this.marker=marker;
	
	savedestinationname=name;
	
}


function setcurrentlocation(plantflag, openpanel, comguidesetup){
	
	var uslocation = true;
	var extabStrip = getexploretabstrip();
	var bizvenues = extabStrip.findTabByText("Venues");
	var bizsearch = extabStrip.findTabByText("Search");
	var nobiz = extabStrip.findTabByText("Off");
	
	globallocation=currentlocation[0].fulladdress;
	settextfields();
	
	//Builds the Venue Structure if the location is inside the USA
	if(non_usaloc == false){
		var bizvenues = extabStrip.findTabByText("Venues");
		bizvenues.enable();
		bizvenues.select();
		bizsearch.enable();
		nobiz.disable();
		
		//highslidecontrol('explore');
		if((dmoflag==true)&&(locsearchtype=='location')){
			populatedmo();
		}
		
	}else{
		bizvenues.disable(); 
		bizsearch.disable();
		nobiz.enable();
		nobiz.select();
		openpanel = true;
		uslocation = false;
	}
	
	if(openpanel == true){
		mashupsprepopulate();
		expandmappane();
		highslidecontrol('explore');
		highslidecontrol('cpresultshtmloff');
	}
	
	
	if(plantflag == true){
		locationbubble();
//THE FOLLOWING FUNCTION MAKES THE CALL TO THE CPLANET DATABASE TO FIND ANY CPLANET DESTINATIONS WITHIN THE GLOBALPROXDISTANCE
		//getdestinations('', '', 'prox_storefronts');
	}
	
	//SETS THE COMMUNITY GUIDE FOR THE DESTINATION ENTERED UNLESS DMO FUNCTIONS ARE ACTIVATED
	if(comguidesetup == true){
		setcommunityguide(globallocation, uslocation);
	}
	
	
}

//BUILDS THE LAYOUT OF THE LOCATION BUBBLE BASED ON CURRENTLOCATION
function locationbubble(restore){
	
	var label1 = 'Info';
	var label2 = 'Directions';
	
	var directiontitle = cleanstring(currentlocation[0].fulladdress);
	
	if(dmoflag == true){
		locbubble = dmolocationbubble(directiontitle);
	}else{
		locbubble = buildlocbubble(directiontitle);
	}
	
//	locbubble = buildlocbubble(directiontitle);
	
	
	var directionstab ='<div class="bubble" ><span class="titlefont">DIRECTIONS:<br><br><a href="javascript:setdirectionbubble(\'to\', \''+directiontitle+'\' )">To Here  </a>   OR   <a href="javascript:setdirectionbubble(\'from\', \''+directiontitle+'\')">  From Here</a></span></div>';	
	
	if(restore!=true){
		//map.clearOverlays();
		clearmap();
		map.setCenter(currentlocation[0].point, defaultzoom);
	}
	
	locmarker = new GMarker(currentlocation[0].point, location_marker);
	locmarker.tooltip;
	map.addOverlay(locmarker);
	activemarker=locmarker;
	
	GEvent.addListener(locmarker, "click", function() {
		activemarker=locmarker;
		createtype='location';
		setmastercreatetype(createtype);
		locmarker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,locbubble), new GInfoWindowTab(label2,directionstab)]);
    });
	
	if(restore!=true){
		locmarker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,locbubble), new GInfoWindowTab(label2,directionstab)]);
	}
	
	panoClient.getNearestPanorama(currentlocation[0].point, ispanoavailable);
	
}

function buildlocbubble(directiontitle){
	
	locbubble = '<div style="width:365px; min-height:230px;">';
	locbubble += '<div align="left" class="cpfont"><span class="cpfontheading18" style="font-style:italic;">';
	if (currentlocation[0].address!=""){
		locbubble += currentlocation[0].address+'<br>';
	}
	if (currentlocation[0].city!=""){
		locbubble += currentlocation[0].city;
	}
	if (currentlocation[0].state!=""){
		locbubble += ', '+currentlocation[0].state;
	}
	if (currentlocation[0].zip!=""){
		locbubble += ', '+currentlocation[0].zip;
	}
	if (currentlocation[0].country!=""){
		locbubble += '<br>'+currentlocation[0].country;
	}
	locbubble += '</span></div>';
	
	locbubble += '<div align="center" id="panobutton"><img src="globalgraphics/general/streetview_off.jpg" border="0" /><script type=""text/javascript"">panocheck()</script></div>';
	
	if(non_usaloc == false){
		
		locbubble += '<hr><div class="cpfont"><table width="100%" border="0" cellpadding="0" class="minifont">';
		
		locbubble += '<tr><td valign="middle"><img src="globalgraphics/general/lodging_icon.jpg" border="0" onclick="cgsearch(\'Lodging\')" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:cgsearch(\'Lodging\')">Where to Stay</a></td>';
		locbubble += '<td valign="middle" style="padding-left:5px;"><img src="globalgraphics/general/restaurant_icon.jpg" border="0" onclick="cgsearch(\'Restaurants\')" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:cgsearch(\'Restaurants\')">Where to Eat</a></td>';
		
		if(sponsoractive == true){
			locbubble += '<td align="right" rowspan="3"><img src="globalgraphics/general/sponsor_mcds.jpg" border="0" onclick="sponsorareasearch(\'mcdonalds\')" onmouseover="this.style.cursor=\'pointer\'" /></td></tr>';
		}else{
			locbubble += '</tr>';	
		}
		
		locbubble += '<tr><td valign="middle"><img src="globalgraphics/general/events_icon.jpg" border="0" onclick="callgetevents()" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:callgetevents()">Events</a></td>';
		locbubble += '<td valign="middle" style="padding-left:5px;"><img src="globalgraphics/general/shopping_icon.jpg" border="0" onclick="cgsearch(\'Shopping\')" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:cgsearch(\'Shopping\')">Where to Shop</a></td></tr>';
		
		locbubble += '<tr><td valign="middle"><img src="globalgraphics/general/entertainment_icon.jpg" border="0" onclick="cgsearch(\'Entertainment and Arts\')" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:cgsearch(\'Entertainment and Arts\')">Entertainment</a></td>';
		locbubble += '<td valign="middle" style="padding-left:5px;"><img src="globalgraphics/general/taxi_icon.jpg" border="0" onclick="cgsearch(\'Taxi Services\')" onmouseover="this.style.cursor=\'pointer\'" /></td>';
		locbubble += '<td valign="middle"><a href="javascript:cgsearch(\'Taxi Services\')">Getting Around</a></td></tr>';
		
		locbubble += '</table></div>';
		
	}
	
	
	
	if(tb_active == false){
		if(geopurpose == 'adddesttopp'){
			locbubble += '<hr><div class="cpfont" align="center"><div style="width:125px; padding:2px; background-color:#103194; border:solid 1px #666666;">';
			locbubble += '<table border="0" width="100%" cellpadding="2" class="cpfontreg" bgcolor="#FFFFFF">';
			locbubble += '<tr><td align="center" valign="middle"><img src="globalgraphics/general/passport_icon.jpg" /></td>';
			locbubble += '<td align="left" valign="middle"><a href="javascript:verifiedaddpassport(\'location\')">Add to Passport</a></td>';
			locbubble += '</tr></table></div></div>';
			locbubble += '</div>';
		
		}else{
			locbubble += '<hr><div class="cpfont"><table border="0" width="100%" cellpadding="5" class="cpfontreg">';
			locbubble += '<tr><td align="left" valign="middle"><img src="globalgraphics/general/passport_icon.jpg" /></td>'
			locbubble += '<td align="left" valign="middle"><a href="javascript:verifiedaddpassport(\'location\')">Add to my Passport</a></td>';
			locbubble += '<td align="left" valign="middle"><img src="globalgraphics/general/tripbuilder_icon.jpg" /></td>'
			locbubble += '<td align="left" valign="middle"><a href="javascript:tripbuilder(false);">Build a Trip Here!</a></td>';
			locbubble += '</tr></table></div>';
			locbubble += '</div>';
		}
	}else{
		locbubble += '<hr><div class="cpfont" align="center"><div style="width:125px; padding:2px; background-color:#F9AF6C; border:solid 1px #666666;">';
		locbubble += '<table border="0" width="100%" cellpadding="2" class="cpfontreg" bgcolor="#FFFFFF">';
		locbubble += '<tr><td align="center" valign="middle"><img src="globalgraphics/general/tripbuilder_icon.jpg" /></td>';
		locbubble += '<td align="left" valign="middle"><a href="javascript:verifiedaddpassport(\'location\')">Add to Trip</a></td>';
		locbubble += '</tr></table></div></div>';
		locbubble += '</div>';	
	}
	
	return locbubble;
	
}


//BUILDS THE LAYOUT OF THE DESTINATION SEARCH BUBBLE BASED ON CURRENTLOCATION
function buildlocationseach(address){
	var locsearchlayout='<div id="business_search" style="padding-left:5px; padding-top:1px" runat="server">'
		+'<span style="font-weight:bold;">Destination Search</span><br />'
		+'<span class="minifont">Business Name or Business Catagory</span><br />'
		+'<input type="text" id="txtBusinessSearchBubble" name="textfield" size="25" onfocus="setthefocus(this.id)" /><br />'
		+'<span class="minifont">City, State, Zip</span><br />'
		+'<input type="text" id="txtBusinessSearchLocationBubble" name="textfield" size="25" value="'+address+'"/><br />'
		+'<input id="btnBusinessSearchBubble" type="button" value="Search" onclick="processinput(\'txtBusinessSearchBubble\')" />'
		+'<span style="padding-right:10px;"></span><a href="javascript:processinput(\'bubbleeverything\')">Search All</a>'
		+'</div>';	
	
	activemarker.openInfoWindowHtml(locsearchlayout);
	
}

//BUILDS THE TO AND FROM DIRECTIONS BUBBLE
function setdirectionbubble(whichway, directionpoint, name){
	
	//alert(name);
	
	globaldirectionpoint=directionpoint;
	
	if(!name){
		//alert('No Name');
		name=directionpoint;
	}

	// The info window version with the "to here" form open
	if(whichway=='to'){
		var tohtml = '<div class="bubble"><form action="javascript:processinput(\'saddr\')"><table width="100%" border="0" cellspacing="1" cellpadding="0">'
		+'<tr><td><b>Directions:</b></td></tr>'
		+'<tr><td> <b>To:'+name+'</b><br> OR <a href="javascript:setdirectionbubble(\'from\', \''+directionpoint+'\')">From here</a><br><br></td></tr>'
		+'<tr><td>Start address:</td></tr>'
		+'<tr><td><input type="text" SIZE=28 MAXLENGTH=40 name="topointtext" id="saddr" value="" onfocus="setthefocus(this.id)" /><br></td></tr>'
		+'<tr><td valign="middle">Select a language:<select id="langlocale" name="langlocale" onchange="setlocale()"><option value="en" selected>English</option><option value="fr">French</option>'
		+'<option value="de">German</option><option value="ja">Japanese</option><option value="es">Spanish</option></select></td></tr>'
		+'<tr><td><div align="center"><INPUT value="Get Directions" TYPE="SUBMIT"> or <a href="javascript:clickdirections(\'to\', \''+directionpoint+'\', \'true\')">Click a marker</a></div></td></tr></table></form></div>';
		   
		activemarker.openInfoWindowHtml(tohtml);   
	}
	
	if(whichway=='from'){
        // The info window version with the "to here" form open
        var fromhtml = '<div class="bubble"><form action="javascript:processinput(\'daddr\')"><table width="100%" border="0" cellspacing="1" cellpadding="0">'
		+'<tr><td><b>Directions:</b></td></tr>'
		+'<tr><td> <b>From:'+name+'</b><br> OR <a href="javascript:setdirectionbubble(\'to\', \''+directionpoint+'\')">To here</a><br><br></td></tr>'
		+'<tr><td>End Address:</td></tr>'
		+'<tr><td><input type="text" SIZE=28 MAXLENGTH=40 name="frompointtext" id="daddr" value="" onfocus="setthefocus(this.id)" /><br></td></tr>'
		+'<tr><td valign="middle">Select a language:<select id="langlocale" name="langlocale" onchange="setlocale()"><option value="en" selected>English</option><option value="fr">French</option>'
		+'<option value="de">German</option><option value="ja">Japanese</option><option value="es">Spanish</option></select></td></tr>'
		+'<tr><td><div align="center"><INPUT value="Get Directions" TYPE="SUBMIT"> or <a href="javascript:clickdirections(\'from\', \''+directionpoint+'\', \'true\')">Click a marker</a></div></td></tr></table></form></div>';
		   
		activemarker.openInfoWindowHtml(fromhtml);
	}
	
}


function setlocale(){
	langlocale=document.getElementById('langlocale').value;
	//alert(langlocale);
}

//SUBMITS THE TO AND FROM POINTS TO THE GDIR GOOGLE GEOCODING FUNCTIONS
function getdirections(whichway, directionpoint) {
	
	document.getElementById('directionscontent').InnerHtml = '';
	
	if (whichway == 'to'){
		var frompoint = document.getElementById("saddr").value;
		gdir.load("from: "+frompoint+" to: "+directionpoint, { "locale": langlocale });
	}
	
	if (whichway == 'from'){
		var topoint = document.getElementById("daddr").value;
		gdir.load("from: "+directionpoint+" to: "+topoint, { "locale": langlocale });	
	}
	
	map.closeInfoWindow();
	//expandmappane();
	highslidecontrol('directions');
}


function clickdirections(whichway, directionpoint, clickevent){
	
	if(whichway=='to'){
		var clickdirhtml='Click another marker or a point on the map<br>to get the directions to this destination.<br><br>Please click now...'
	}else{
		var clickdirhtml='Click another marker or a point on the map<br>to get the directions from this destination.<br><br>Please click now...'	
	}
	
	activemarker.openInfoWindowHtml(clickdirhtml);
	
	GEvent.addListener(map, "click", function(marker, point) {
		if(clickevent=='true'){
			if(marker){
				var clickdirpoint=marker.getPoint().y+','+marker.getPoint().x;
				//alert(directionpoint+', '+clickdirpoint);
				if(whichway=='to'){
					gdir.load("from: "+clickdirpoint+" to: "+directionpoint, { "locale": langlocale });
				}else{
					gdir.load("from: "+directionpoint+" to: "+clickdirpoint, { "locale": langlocale });	
				}
				
				map.closeInfoWindow();
				expandmappane();
				highslidecontrol('directions');
			}
			
			if(point){
				if(whichway=='to'){
					gdir.load("from: "+point+" to: "+directionpoint, { "locale": langlocale });
				}else{
					gdir.load("from: "+directionpoint+" to: "+point, { "locale": langlocale });	
				}
				map.closeInfoWindow();
				expandmappane();
				highslidecontrol('directions');
			}
			
			clickevent=false;
		}
	});
		
}

function testconnections(){
	var waypoint1=currentdestinations[2].lat+','+currentdestinations[2].lng;
	var waypoint2=currentdestinations[0].lat+','+currentdestinations[0].lng;
	var waypoint3=currentdestinations[3].lat+','+currentdestinations[3].lng;
	
	var waypoints = new Array (waypoint1, waypoint2, waypoint3);
	
	gdir.loadFromWaypoints(waypoints);
	
	//setlayout('standard');
	expandmappane();
	
	swapcontent('content');
	
}


function markthemap(choice){
	
	contextmenu.style.visibility="hidden";
	
	switch (choice){
		case 'click':
			expandmappane();
			removesearchcircle();
			try{
				document.getElementById('mapsetflagicon').src = 'globalgraphics/mapcontrols/clickmap_mapicon.png';
				document.getElementById('mapclickbut').src = 'globalgraphics/dmo_menu/dmo_mapclick_waiting.jpg';
			}catch(err){
				//Error catch goes here.
			}
			//tb_active = false
			mapclickactive=true;
			clickmap();
		break;
		
		case 'clickfortour':
			expandmappane();
			removesearchcircle();
			try{
				document.getElementById('tourmapclickbut').src = 'globalgraphics/general/tour_clickmap.png';
			}catch(err){
				//Error catch goes here.
			}
			tbmapclickactive=true;
			clickmapexact();
		break;
	
		case 'latlng':
			var dialoghtml='<div align="center"><b>Decimal Values</b><br /><table border="0" cellpadding="2"><tr>'
			+'<td colspan="2" align="center">Lat:<input name="latdec" id="latdec" type="text" value="decimal" size="12" maxlength="20" /></td>'
			+'<td colspan="3" align="center">Lng:<input name="lngdec" id="lngdec" type="text" value="decimal" size="12" maxlength="20" /></td></tr>'
			+'<td colspan="5" align="center"><input id="btnBusinessSearchBubble" type="button" value="Plot Decimal" onclick="showlatlng(\'dec\')" />'
			+'</td></tr>'
			+'<tr><td colspan="5" align="center"><b>Or</b><hr /><br /><b>Degree Values</b><br /></td></tr>'
			+'<tr><td>Lat:</td><td><input name="lathour" id="lathour" type="text" value="hours" size="8" maxlength="20" /></td>'
			+'<td><input name="latmin" id="latmin" type="text" value="min" size="8" maxlength="20" /></td>'
			+'<td><input name="latsec" id="latsec" type="text" value="sec" size="12" maxlength="20" /></td>'
			+'<td><input name="latdir" id="latdir" type="text" value="n or s" size="8" maxlength="20" /></td></tr>'
			+'<tr><td>Lng:</td><td><input name="lnghour" id="lnghour" type="text" value="hours" size="8" maxlength="20" /></td>'
			+'<td><input name="lngmin" id="lngmin" type="text" value="min" size="8" maxlength="20" /></td>'
			+'<td><input name="lngsec" id="lngsec" type="text" value="sec" size="12" maxlength="20" /></td>'
			+'<td><input name="lngdir" id="lngdir" type="text" value="e or w" size="8" maxlength="20" /></td></tr>'
			+'<td colspan="5" align="center"><input id="btnBusinessSearchBubble" type="button" value="Plot Degrees" onclick="showlatlng(\'deg\')" />'
			+'</td></tr></table></div>'
			
			var dialogheader = 'Enter Latitude and Longitude';
			
			sendresponse(dialoghtml, dialogheader);
		break;
	
		case 'address':
			var dialoghtml='<div align="center">'
				+'<span class="minifont">City, State, Zip, Address</span><br />'
				+'<input type="text" id="createaddressloctext" size="35" name="textfield" onfocus="setthefocus(this.id)" /><br /><br />'
				+'<input id="btnBusinessaddresscreate" type="button" value="Search" onclick="processinput(\'createaddressloctext\')" />'
				+'<input id="btnCancelAddresscreate" type="button" value="Cancel" onclick="highslidecontrol(\'dynhtmloff\')" />'
				+'</div>';
			
			var dialogheader = 'Location or Address Search';
			sendresponse(dialoghtml, dialogheader);
		break;
		
		case 'business':
			var dialoghtml='<div align="center">'
				+'<span class="minifont">Business Name or Business Catagory (USA only)</span><br />'
				+'<input type="text" id="createbizsearchtext" size="35" name="createbizsearchtext" onfocus="setthefocus(this.id)" /><br />'
				+'<span class="minifont">City, State, Zip</span><br />'
				+'<input type="text" id="createbizsearchloctext" size="35" name="createbizsearchloctext" /><br /><br />'
				+'<input id="btnBusinessSearchcreate" type="button" value="Search" onclick="processinput(\'createbizsearchtext\')" />'
				+'<input id="btnCancelSearchcreate" type="button" value="Cancel" onclick="highslidecontrol(\'dynhtmloff\')" /><br>'
				+'</div>';
			
			var dialogheader = 'Business Search';
			sendresponse(dialoghtml, dialogheader);
		break;
	}
	
}

function removeactivemarker(){
	map.closeInfoWindow();
	activemarker.remove();
}

function whatcreatemarker(markertype, createtype){
	//alert(markertype+' - '+createtype);
	lat=activemarker.getPoint().y;
	lng=activemarker.getPoint().x;
	
	setmastercreatetype(createtype);
	
	if(markertype=='create'){
		switch (createtype){
			case 'click':
					var bubbletext='<div class="bubble"><span style="font-weight:bold;">MAP CLICK RESULT</span><br>'
						+'<span class="minifont">Latitude='+lat+'<br>Longitude='+lng
						+'<br><br>To adjust the marker\'s location, close this bubble and drag the marker.'
						+'<br>Click the marker to reopen the bubble.</span><br><br>'
						+'<table border="0" cellspacing="0" cellpadding="0"><tr>'
						+'<td ><div align="left"><a href="javascript:verifiedaddpassport(\'click\')">Add to my stuff</a></div></td>'
						+'<td width="20%"></td>'
						+'<td ><div align="right"><a href="javascript:removeactivemarker()">Remove</a></div></td></tr></table></div>';
			break;
			
			case 'latlng':
					var bubbletext='<div class="bubble"><span style="font-weight:bold;">LONGITUDE LATITUDE RESULT</span><br>'
						+'<span class="minifont">Latitude='+lat+'<br>Longitude='+lng
						+'<br><br>To adjust the marker\'s location, close this bubble and drag the marker.'
						+'<br>Click the marker to reopen the bubble.</span><br><br>'
						+'<table border="0" cellspacing="0" cellpadding="0"><tr>'
							+'<td ><div align="left"><a href="javascript:verifiedaddpassport(\'latlng\')">Add to my stuff</a></div></td>'
						+'<td width="20%"></td>'
						+'<td ><div align="right"><a href="javascript:removeactivemarker()">Remove</a></div></td></tr></table></div>';
			break;
			
			case 'location':
				var bubbletext='<div class="bubble"><span style="font-weight:bold;">LOCATION SEARCH RESULT</span><br>'
					+currentlocation[0].fulladdress+'<br><br><span class="minifont"><span style="font-weight:bold;">'
					+'Note:</span>To adjust the marker\'s location, close this bubble and drag the marker.'
					+'Click the marker to reopen the bubble.</span><br><br>'
					+'<table border="0" cellspacing="0" cellpadding="0"><tr>'
					+'<td ><div align="left"><a href="javascript:verifiedaddpassport(\'location\')">Add to my stuff</a></div></td>'
					+'<td width="20%"></td>'
					+'<td ><div align="right"><a href="javascript:removeactivemarker()">Remove</a></div></td></tr></table></div>';
			break;
			
			case 'business':
				var bubbletext='<div class="bubble"><span style="font-weight:bold;">BUSINESS SEARCH RESULT</span><br>'
				+bizbubble+'<br><br><span class="minifont"><span style="font-weight:bold;">'
				+'Note:</span>To adjust the marker\'s location, close this bubble and drag the marker.'
				+'Click the marker to reopen the bubble.</span><br><br>'
				+'<hr><div class="cpfont"><table align="center" border="0" cellpadding="5" class="cpfontreg">';
				+'<tr><td align="right" valign="middle"><img src="globalgraphics/general/passport_icon.jpg" /></td>'
				+'<td align="left" valign="middle"><a href="javascript:verifiedaddpassport(\'location\')">Add to my Passport</a></td>'
				+'</tr></table></div></div>';
			break;
		}
		
		activemarker.openInfoWindowHtml(bubbletext);
	}
	
}

function setmastercreatetype(type){
	mastercreatetype=type;	
}


// THIS FUNCTION MARKS THE MAP WITH A USER ENTERED DESTINATION FROM LATITUDE AND LONGITUDE
function showlatlng(type){
	
	if (type!='dec'){
		var lathour = parseFloat(document.getElementById("lathour").value);
		var latmin = parseFloat(document.getElementById("latmin").value);
		var latsec = parseFloat(document.getElementById("latsec").value);
		var latdir = document.getElementById("latdir").value
		
		var lnghour = parseFloat(document.getElementById("lnghour").value);
		var lngmin = parseFloat(document.getElementById("lngmin").value);
		var lngsec = parseFloat(document.getElementById("lngsec").value);
		var lngdir = document.getElementById("lngdir").value
		
		//alert(lnghour+' , '+lngmin+' , '+lngsec+' , '+lngdir)
		
		var decmlat = lathour+((latmin/60)+(latsec/3600));
		var decmlng = lnghour+((lngmin/60)+(lngsec/3600));
		
		if(latdir=='s'){
			decmlat = decmlat*-1;
		}
		
		if(lngdir=='w'){
			decmlng = decmlng*-1;
		}
		
		//alert('Lat: '+decmlat+', Lng: '+decmlng);
		
		var point = new GLatLng(decmlat,decmlng);
	}else{
		var formlat = document.getElementById("latdec").value;
		var formlng = document.getElementById("lngdec").value;
		
		var lat = parseFloat(formlat);
		var lng = parseFloat(formlng);
		var point = new GLatLng(lat,lng);
		
	}
	
	
	map.setCenter(point, defaultzoom);
	var newmarker = new GMarker(point, {icon:dynamicmarker, draggable: true});
	map.addOverlay(newmarker);
	newmarker.enableDragging();

	var latlngtext='<div class="bubble" ><span style="font-weight:bold;">LONGITUDE LATITUDE RESULT</span><br>'
				+'<span class="minifont">Latitude='+lat+'<br>Longitude='+lng
				+'<br><br>To adjust the marker\'s location, close this bubble and drag the marker.'
				+'<br>Click the marker to reopen the bubble.</span><br><br>'
				+'<table width="240" border="0" cellspacing="0" cellpadding="0"><tr>'
				+'<td ><div align="left"><a href="javascript:verifiedaddpassport(\'latlng\')">Add to my stuff</a></div></td>'
				+'<td width="20%"></td>'
				+'<td ><div align="right"><a href="javascript:removeactivemarker()">Remove</a></div></td></tr></table></div>';
				
	GEvent.addListener(newmarker, "drag", function(){
		map.closeInfoWindow();
	});
				
	GEvent.addListener(newmarker, "click", function(marker, point) {
		//alert('create by latlng');
		markertype='create';
		createtype='latlng';
		activemarker = newmarker;
		whatcreatemarker(markertype, createtype);
	});
	
	activemarker = newmarker;
	newmarker.openInfoWindowHtml(latlngtext);
	
	highslidecontrol('dynhtmloff');
		
}

function showAddress(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
        place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
    marker.openInfoWindowHtml(
        '<b>orig latlng:</b>' + response.name + '<br/>' +
        '<b>latlng:</b>' + place.Point.coordinates[0] + "," + place.Point.coordinates[1] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
  }
}

function clickmap(){
	
	GEvent.addListener(map, "click", function(overlay, latlng) {
			if(mapclickactive==true){
				if (latlng != null) {
					geopurpose = 'comguide';
					clickloc = true;
					//alert(latlng);
					
					try{
						document.getElementById('mapsetflagicon').src = 'globalgraphics/mapcontrols/setflag_mapicon.png';
						document.getElementById('mapclickbut').src = 'globalgraphics/dmo_menu/dmo_mapclick.jpg';
					}catch(err){
						//Error catch goes here.
					}
					geocoder.getLocations(latlng, processgeoresponse);
					mapclickactive = false;
				}
			}
		});
	
}
		
// THIS FUNCTION MARKS THE MAP WITH A USER ENTERED DESTINATION FROM A MAP CLICK
function clickmapexact(){
		
		GEvent.addListener(map, "click", function(overlay, point) {
			if(tbmapclickactive==true){
				if (point != null) {
					geopurpose = 'create';
					clickloc = true;
					//alert(latlng);
					
					try{
						//document.getElementById('mapsetflagicon').src = 'globalgraphics/general/tourmapclickbut.png';
						document.getElementById('tourmapclickbut').src = 'globalgraphics/general/tour_activatemapclick.png';
					}catch(err){
						//Error catch goes here.
					}
					
					var newmarker=new GMarker(point, {icon:dynamicmarker, draggable: true});
					lat=point.y;
					lng=point.x;
					
					map.addOverlay(newmarker);
					newmarker.enableDragging();
			
					GEvent.addListener(newmarker, "drag", function(){
						map.closeInfoWindow();										
						activemarker = newmarker;
					});
								
							
					GEvent.addListener(newmarker, "click", function(marker) {
						//alert('create by mapclick');
						markertype='create';
						createtype='click';
						activemarker=newmarker;
						verifiedaddpassport('click');
						//whatcreatemarker(markertype, createtype);
					});
				
					activemarker=newmarker;
					verifiedaddpassport('click');
					//newmarker.openInfoWindowHtml(clicktext);
					//geocoder.getLocations(latlng, processgeoresponse);
					
					tbmapclickactive = false;
				}
			}
		});
	
}

function markaddress() {
	
	tourlocbubble = '<div style="width:350px; height:auto;">';
	tourlocbubble += '<div align="left" class="cpfont"><span class="cpfontheading18" style="font-style:italic;">';
	if (currenttourlocation[0].address!=""){
		tourlocbubble += currenttourlocation[0].address+'<br>';
	}
	if (currenttourlocation[0].city!=""){
		tourlocbubble += currenttourlocation[0].city;
	}
	if (currenttourlocation[0].state!=""){
		tourlocbubble += ', '+currenttourlocation[0].state;
	}
	if (currenttourlocation[0].zip!=""){
		tourlocbubble += ', '+currenttourlocation[0].zip;
	}
	if (currenttourlocation[0].country!=""){
		tourlocbubble += '<br>'+currenttourlocation[0].country;
	}
	tourlocbubble += '</span></div>';
	
	tourlocbubble += '<hr><div class="cpfont"><table border="0" cellpadding="5" class="cpfontreg">';
	tourlocbubble += '<tr><td align="left" valign="middle" width="50%" ></td>'
	tourlocbubble += '<td style="background-color:#F9AF6C; border:solid 1px #666666; padding:4px;" align="right" width="50%" valign="middle" style="padding-left:5px;"><a href="javascript:verifiedaddpassport(\'tourlocation\')">Add to Trip</a></td>';
	tourlocbubble += '</tr></table></div>';
	tourlocbubble += '</div>';
	
	
	
	map.setCenter(currenttourlocation[0].point, defaultzoom);
	var newmarker=new GMarker(currenttourlocation[0].point, {icon:dynamicmarker, draggable: true});
	map.addOverlay(newmarker);
	
	activemarker=newmarker;
	
	GEvent.addListener(newmarker, "drag", function(){
		map.closeInfoWindow();
	});
				
	GEvent.addListener(newmarker, "click", function(marker, point) {
		//alert('create by location search');
		markertype='create';
		createtype='location';
		activemarker = newmarker;
		newmarker.openInfoWindowHtml(tourlocbubble);
	});
				
	newmarker.openInfoWindowHtml(tourlocbubble);
	
	//highslidecontrol('dynhtmloff');
	  
}

function plotevent(eventarray){
	
	var mediapoint = new GLatLng(parseFloat(eventarray[1]), parseFloat(eventarray[2]));
	
	activeevent[0] = new popactiveevent(eventarray[0], eventarray[1], eventarray[2], mediapoint, eventarray[3], eventarray[4], eventarray[5], eventarray[6], eventarray[7], eventarray[8], eventarray[9], eventarray[10], eventarray[11], eventarray[12]);
	
	//alert(eventarray[0]+' , '+eventarray[1]+' , '+eventarray[2]+' , '+eventarray[3]);
	markericon = "eventmarker.png";
	mediamarkerimage=markerpath+markericon;
	
	var eventhtml = buildeventhtml();
	
	mediamarker=new GMarker(mediapoint, {icon:dynamicmarker});
	map.setCenter(mediapoint, defaultzoom);
	map.addOverlay(mediamarker);
	GEvent.addListener(mediamarker, "click", function(marker, point) {
		mediamarker.openInfoWindowHtml(eventhtml);
	});
	mediamarker.setImage(mediamarkerimage);
	
	mediamarker.openInfoWindowHtml(eventhtml);
	activemarker = mediamarker;
	
	expandmappane();
	
}

function popactiveevent(name, lat, lng, point, startdate, starttime, enddate, endtime, address, city, state, country, zip, description){
	
	this.name=name;
	this.lat = lat;
	this.lng = lng;
	this.point=point;
	this.startdate=startdate;
	this.starttime=starttime;
	this.enddate=enddate;
	this.endtime=endtime;
	this.address=address;
	this.city=city;
	this.state=state;
	this.country=country;
	this.zip=zip;
	this.description=description;
	
}

function buildeventhtml(){
	
	var eventaddrress = activeevent[0].address+' '+activeevent[0].city+' '+activeevent[0].state+' '+activeevent[0].country+' '+activeevent[0].zip;
	
	activeevent[0].description = cleanstring(activeevent[0].description);

	var eventhtml='<div class="bubble"><span class="cpfont">';
	
	eventhtml+='<b>' + activeevent[0].name+'</b>';
	eventhtml+='<br /><b>Date: </b>' + activeevent[0].startdate + ', <b>Time: </b>'+activeevent[0].starttime;
	eventhtml+='<br />' + activeevent[0].address;
	eventhtml+='<br />' + activeevent[0].city+', '+activeevent[0].state+', '+activeevent[0].country+', '+activeevent[0].zip;
	eventhtml+='<br /><br /><table width="100%" border="0" cellpadding="3" style="font-size:11px;"><tr>'
	if(activeevent[0].description != ''){
		eventhtml+='<td colspan="2" align="center"><a href="javascript:displayMessage(\''+activeevent[0].description+'\')">Show Description</a></td></tr><tr>'
	}
	
	if(non_usaloc == false){
		eventhtml+='<td align="left"><a href="javascript:buildlocationseach(\''+eventaddrress+'\')">What\'s Close by?</a></td>';
	}else{
		eventhtml+='<td align="left"></td>';
	}
	eventhtml+='<td align="right"><a href="javascript:verifiedaddpassport(\'event\')">Add to my Passport</a></td>';
	eventhtml+='</tr></table></span></div>';
	
	return eventhtml;
}
						

function plotmedia(type, lat, lng, description){
	
	var mediamarkerimage;
	
	//description=cleanstring(description);
	
	switch (type){
			case 'photo':
					markericon = "photomarker.png";
					
			break;
			
			case 'info':
					markericon = "infomarker.png";
			break;
			
			case 'event':
					markericon = "eventmarker.png";
					cleanvenuname
					
			break;
			
			case 'video':
					markericon = "videomarker.png";
			break;
	}
	
	mediamarkerimage=markerpath+markericon;
	
	if(mediamarker){
		map.closeInfoWindow();
		mediamarker.remove();
	}
	
	var mediapoint = new GLatLng(lat, lng);
	mediamarker=new GMarker(mediapoint, {icon:dynamicmarker});
	map.setCenter(mediapoint, defaultzoom);
	map.addOverlay(mediamarker);
	GEvent.addListener(mediamarker, "click", function(marker, point) {
		mediamarker.openInfoWindowHtml(description);
	});
	mediamarker.setImage(mediamarkerimage);
	
	mediamarker.openInfoWindowHtml(description);
	
}

function markbizresult(biz){
	
	expandmappane();
	activeresult=biz;
	//changemarkerimage('/globalgraphics/markers/marker_test.png');
	
	var markonmap = false;
	var htmltab2="";
	var label1='Info';
	var label2='Directions';
	var point = new GLatLng(currentbusinesses[biz].lat,currentbusinesses[biz].lng);
    var selectedbiz = new GMarker(point, {icon:dynamicmarker, draggable: true});
	map.setCenter(point, destinationzoom);
	activemarker = selectedbiz;
	buildhtml(biz, false);	
	
	var businesstext='<div style="width:350px;" class="cpfont"><span class="cpfontbold"><u>BUSINESS SEARCH RESULT</u></span><br>'
				+bizbubble+'<br><span class="minifont"><b>'
				+'Note:</b>To adjust the marker\'s location, close this bubble and drag the marker.'
				+'Click the marker to reopen the bubble.</span>'
				+'<hr><div class="cpfont"><table align="center" border="0" cellpadding="5" class="cpfontreg">'
				+'<tr><td align="right" valign="middle"><img src="globalgraphics/general/passport_icon.jpg" /></td>'
				+'<td align="left" valign="middle"><a href="javascript:verifiedaddpassport(\'business\')">Add to my Passport</a></td>'
				+'</tr></table></div></div>';
		
		map.addOverlay(selectedbiz);
		
		selectedbiz.enableDragging();
		
		GEvent.addListener(selectedbiz, "drag", function(){
			map.closeInfoWindow();
		});
					
		GEvent.addListener(selectedbiz, "click", function(marker, point) {
			markertype='create';
			createtype='business';
			activemarker = selectedbiz;
			whatcreatemarker(markertype, createtype);
		});
					
		selectedbiz.openInfoWindowHtml(businesstext);
}

//FOLLOWING ARE  THE CREATE FUNCTIONS

function buildcreateform(updatedmarker){
	
	var formbuttons;
	
	if(formtype=='create'){
		action='save';
		markerimage = markerpath+markericon;
		var formmarker = markerimage;
		
		if(cyosf_active == true){
			
			var formbuttons = '<input name="canelsave1" type="button" value="Cancel"  style="font-size:11px;" onclick="map.closeInfoWindow()"/>'
								  +'<input name="saveinfodata1" type="button" value="Continue"  style="font-size:11px;" onclick="savebubble(\'storefront\')" />';
			
		}else{
			var formbuttons = '<input name="canelsave1" type="button" value="Cancel"  style="font-size:11px;" onclick="map.closeInfoWindow()"/>'
								+'<input name="saveinfodata1" type="button" value="Save"  style="font-size:11px;" onclick="savebubble(\'create\')" />';
		}
	}else{
		action='editcontent';
		if(updatedmarker){
			var formmarker = markerpath+updatedmarker;
		}else{
			markericon=currentdestinations[activeresult].marker;
			var formmarker = markerpath+currentdestinations[activeresult].marker;
		}
		var formbuttons = '<input name="saveinfodata1" style="font-size:11px;" type="button" value="Save" onclick="savebubble(\'edit\')" /><input name="canelsave1" type="button" value="Cancel" style="font-size:11px;" onclick="map.closeInfoWindow()"/><input name="deletedest" style="font-size:11px;" type="button" value="Delete" onclick="deletedestination(\''+currentdestinations[activeresult].destinationid+'\', \''+currentdestinations[activeresult].tourid+'\')"/><br /><input name="btneditdescript" type="button" value="Description" style="font-size:11px;" onclick="editdestdescription(\''+currentdestinations[activeresult].destinationid+'\')" /><input name="btneditcontent" type="button" value="Cthere" style="font-size:11px;" onclick="addeditmedia(\''+currentdestinations[activeresult].destinationid+'\')" />';
	}
	
	if(cyosf_active){
		destbubbleform_t1 = '<div class="cpfont"><span class="cpfontheading">Step 3.</span><br><span class="cpfontbold">Verify/Edit Business Information</span></div>';
	}else{
		destbubbleform_t1 = '';
	}
	
	destbubbleform_t1 += 
		'<div class="cpfont">'+
		'<span class="cpfontheading"><i>Enter Destination Details</i></span>'+
		'<form name="destinfoform" action="#" >'+
		'<div id="bubbleform1" style="width:260px; height:300px; overflow:auto;">'+
		'<table border="0" cellspacing="0" cellpadding="0">'+
		'<tr><td colspan="2"><span class="minifont">Name</span><br /><input name="destname" type="text" value="" size="30" /></td></tr>'+
		'<tr><td valign="middle"><span class="minifont"><input type="radio" name="public" value="Public" checked>Public<input type="radio" name="public" value="Private">Private</span></td>'+
		'<td align="center" valign="middle"><a href="javascript:openmarkermenu()"><img src="'+formmarker+'" border="0" width="34" height="45" alt="Select a custom marker"/></a></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Address1</span><br /><input name="address1" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Address2</span><br /><input name="address2" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">City</span><br /><input name="city" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">State</span><br /><input name="state" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Zip</span><br /><input name="zip" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Country</span><br /><input name="country" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Phone</span><br /><input name="phone" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Fax</span><br /><input name="fax" type="text" value="" size="30" /></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Weblink</span><br /><input name="weblink" type="text" value="" size="30"></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Email Address</span><br /><input name="email" type="text" value="" size="30"></td></tr>'+
		'<tr><td colspan="2"><span class="minifont">Description Tags</span><br /><input name="dtags" type="text" value="" size="30" /></td></tr>'+
		'<tr><td valign="middle"><span class="minifont">Date</span><br /><input type="text" name="date" id="f_date_c" size="20"/></td>'+
		'<td valign="bottom"><img src="/globalgraphics/general/calendar.gif" id="f_trigger_c" style="cursor: pointer;" title="Date selector" /></td></tr>'+
		'</table></div><div align="center">'+formbuttons+'</div></form></div>';
		
		
	if(cyosf_active){
		destbubbleform_t2 = '<div class="cpfont"><span class="cpfontheading">Step 3.</span><br><span class="cpfontbold">Verify/Edit Business Information</span></div>';
	}else{
		destbubbleform_t2 = '';
	}
		
	destbubbleform_t2 += 
		'<div class="bubbleformholder">'+	
		'<div id="bubbleform2"><form name="destinfoform2" action="#" >'+
		'<table border="0" cellspacing="0" cellpadding="0">'+
		
		'<tr></tr>'+
  		'<tr><td colspan="2">Description<br /><textarea name="destdescript" cols="30" rows="3"></textarea></td></tr>'+
		'<tr><td><input type="radio" name="public" value="Public" checked>Public<input type="radio" name="public" value="Private">Private</td></tr>'+
		'<tr><td>Description Tags<br /><input name="dtags" type="text" value="" size="29" /></td></tr>'+
		'<tr><td colspan="2">Date</td></tr>'+
		'<table><tr><td height="25" valign="middle" ><input type="text" name="date" id="f_date_c"/></td>'+
		'<td height="25" valign="middle"><img src="/globalgraphics/general/calendar.gif" id="f_trigger_c" style="cursor: pointer;" title="Date selector" />'+
		'</td></tr></table></tr></table></form></div>'+
		'</div><div id="bubbleform2buttons">'+formbuttons+'</div>';
		
}

function openmarkermenu(){
	
	savebubble('temp');
	
	var markermenuhtml = '<div class="cpfont"><span class="cpfontheading">Click a marker to apply it</span></div><div id="bubbleform3" style="overflow: auto;">'
						+'<iframe scrolling="no" width="200" height="500" frameborder="0" src="globalgraphics/markers/marker_list1.htm" name="markerlist">'
						+'</iframe></div>'
						+'<div ><input name="backtoinfo2" type="button" value="Cancel" onclick="returntobubbleform()"/>'
						+'</div>';
	
	activemarker.openInfoWindowHtml(markermenuhtml);
	
}

function returntobubbleform(){
	
	activemarker.openInfoWindowHtml(destbubbleform_t1);
	
	popdestbubble();
	
	manualcalsetup();
	
}

//FUNCTIONS TO CONNECT THE DESTINATIONS ON THE MAP WITH A POLYLINE
function connecttoone(i){
	var numberintour = currentdestinations.length
	var hubpoint = currentdestinations[i].point;
	
	for (var a = 0; a < numberintour; a++) {
		var polyOptions = {geodesic:true};
		var polyline = new GPolyline([  
			hubpoint,  
			currentdestinations[a].point  
		], "#ff0000", 4, 0.6, polyOptions);  
		
		map.addOverlay(polyline);
	}
}

function connecttodest(lat,lng){
	var bounds = new GLatLngBounds();
	var numberintour = currentdestinations.length
	var sfhubpoint = new GLatLng(lat,lng);
	//alert('HubPoint='+hubpoint);
	bounds.extend(sfhubpoint);
	
	for (var a = 0; a < numberintour; a++) {
		//alert('Point'+a+' = '+currentdestinations[a].point);
		var polyOptions = {geodesic:true};
		var polyline = new GPolyline([  
			sfhubpoint,  
			currentdestinations[a].point
		], linecolor, 4, 0.6, polyOptions);  
		
		map.addOverlay(polyline);
		bounds.extend(currentdestinations[a].point);
	}
	
	//var newzoom = (map.getBoundsZoomLevel(bounds)+1);
	//var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	//var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	
	//configmap(new GLatLng(clat,  clng), newzoom);
}

function connectall(){
	var numberintour = currentdestinations.length
	var hubpoint = currentdestinations[i].point;
	var polyOptions = {geodesic:true};
	var pts = [];
	for (var a = 0; a < numberintour; a++) {
		pts[a] = currentdestinations[a].point;
	}
	
	var polyline = new GPolyline(pts, "#ff0000", 4, 0.6, polyOptions);  
	
	map.addOverlay(polyline);
}



function saveactivemarker(type){
	
	var tempholder;
	var blank='';
	var lat = activemarker.getPoint().y;
	var lng = activemarker.getPoint().x;
	var zoom = map.getZoom();
	var maptype = map.getCurrentMapType().getName();
	var destmarker = markericon;
	
	if(type!='edit'){
		formtype='create';
		activedescription = '';
	}else{
		formtype='edit';	
	}
	
	buildcreateform();
	
	switch (type){
			case 'click':
				var destname = 'Enter Destination Name Here';
				savedestination[0] = new popsavedestination(blank, destname, blank, blank, 1, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'latlng':
				var destname='Destination #'+savecount+' from Lat/Lng';	
				savedestination[0] = new popsavedestination(blank, destname, blank, blank, 1, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'tourlocation':
				//var destname = currentlocation[0].fulladdress;
				var destname = currenttourlocation[0].fulladdress;
				savedestination[0] = new popsavedestination(blank, destname, blank, blank, 1, currenttourlocation[0].address, blank, currenttourlocation[0].city, currenttourlocation[0].state, currenttourlocation[0].zip, currenttourlocation[0].country, blank, blank, blank, blank, blank, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'location':
				//var destname = currentlocation[0].fulladdress;
				var destname = 'Enter Destination Name Here';
				savedestination[0] = new popsavedestination(blank, destname, blank, blank, 1, currentlocation[0].address, blank, currentlocation[0].city, currentlocation[0].state, currentlocation[0].zip, currentlocation[0].country, blank, blank, blank, blank, blank, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'event':
				//var destname = currentlocation[0].fulladdress;
				var destname = activeevent[0].name;
				savedestination[0] = new popsavedestination(blank, destname, activeevent[0].description, blank, 1, activeevent[0].address, blank, activeevent[0].city, activeevent[0].state, activeevent[0].zip, activeevent[0].country, blank, blank, blank, blank, activeevent[0].startdate, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'business':
				var destname = currentbusinesses[activeresult].name;
					
				savedestination[0]= new popsavedestination(blank, destname, blank, blank, 1, currentbusinesses[activeresult].address1, currentbusinesses[activeresult].address2, currentbusinesses[activeresult].city, currentbusinesses[activeresult].state, currentbusinesses[activeresult].zip, currentbusinesses[activeresult].country, currentbusinesses[activeresult].phone, blank, currentbusinesses[activeresult].weblink, blank, blank, blank, lat, lng, zoom, maptype, destmarker);
				savecount=savecount+1;
			break;
			
			case 'edit':
				var destname = currentdestinations[activeresult].name;
				
				document.getElementById("HiddenDestinationID").value = currentdestinations[activeresult].destinationid;
				activedescription = currentdestinations[activeresult].description;
				
				savedestination[0]= new popsavedestination(currentdestinations[activeresult].destinationid, destname, currentdestinations[activeresult].description, currentdestinations[activeresult].desttags, currentdestinations[activeresult].public, currentdestinations[activeresult].address1, currentdestinations[activeresult].address2, currentdestinations[activeresult].city, currentdestinations[activeresult].state, currentdestinations[activeresult].zip, currentdestinations[activeresult].country, currentdestinations[activeresult].phone, currentdestinations[activeresult].fax, currentdestinations[activeresult].weblink, currentdestinations[activeresult].email, currentdestinations[activeresult].datemanual, currentdestinations[activeresult].datecreated, currentdestinations[activeresult].lat, currentdestinations[activeresult].lng, currentdestinations[activeresult].zoom, currentdestinations[activeresult].maptype, currentdestinations[activeresult].marker);
				
			break;
			
	}
	
	//alert(savedestination[0].name);
	GEvent.addListener(activemarker, "click", function(marker, point) {
		activemarker.openInfoWindowHtml(destbubbleform_t1);
		popdestbubble();
	});
	
	activemarker.openInfoWindowHtml(destbubbleform_t1);
	popdestbubble();
//	if(!cyosf_active){
		manualcalsetup();
//	}
	
}


function savecplanetdestination(){
	associatedestination(currentdestinations[activeresult].destinationid);
}

function unassociatecpdestination(){
	//alert(currentdestinations[activeresult].associatedid);
	unassociatedestination(currentdestinations[activeresult].associatedid, currentdestinations[activeresult].tourid);
}

//called for association
function associatedestination(destid){
	var oktoassociate = verifythenopen();
	
	if(oktoassociate == true){
		activedest[0] = currentdestinations[activeresult];
		savedestinationid = destid;
		opencontrol('savedest');
	}
	
}



function popdestbubble(){
	
	//THE FOLLOWING VARIABLES ARE SENT TO THEIR CORRESPONDING FORM FIELDS IN THE BUBBLE
	if(savedestination[0].name!=''){
		document.destinfoform.destname.value = savedestination[0].name;
	}else{
		document.destinfoform.destname.value = '';
	}
	
//	if(savedestination[0].description!=''){
//		document.destinfoform2.destdescript.value = savedestination[0].description;
//	}else{
//		document.destinfoform2.destdescript.value = '';
//	}
//	if(!cyosf_active){
		if(savedestination[0].desttags!=''){
			document.destinfoform.dtags.value = savedestination[0].desttags;
		}else{
			document.destinfoform.dtags.value = '';
		}
		
		if(savedestination[0].public==0){
			//alert('Marking Private');
			document.destinfoform.public[1].checked=true;
		}else{
			document.destinfoform.public[0].checked=true;
		}
		
		if(savedestination[0].datemanual!=''){
			document.destinfoform.date.value = savedestination[0].datemanual;
		}else{
			document.destinfoform.date.value = '';
		}
//	}
	
	if(savedestination[0].address1!=''){
		document.destinfoform.address1.value = savedestination[0].address1;
	}else{
		document.destinfoform.address1.value = '';
	}
	
	if(savedestination[0].address2!=''){
		document.destinfoform.address2.value = savedestination[0].address2;
	}else{
		document.destinfoform.address2.value = '';
	}
	
	if(savedestination[0].city!=''){
		document.destinfoform.city.value = savedestination[0].city;
	}else{
		document.destinfoform.city.value = '';
	}
	
	if(savedestination[0].state!=''){
		document.destinfoform.state.value = savedestination[0].state;
	}else{
		document.destinfoform.state.value = '';
	}
	
	if(savedestination[0].zip!=''){
		document.destinfoform.zip.value = savedestination[0].zip;
	}else{
		document.destinfoform.zip.value = '';
	}
	
	if(savedestination[0].country!=''){
		document.destinfoform.country.value = savedestination[0].country;
	}else{
		document.destinfoform.country.value = '';
	}
	
	if(savedestination[0].phone!=''){
		document.destinfoform.phone.value = savedestination[0].phone;
	}else{
		document.destinfoform.phone.value = '';
	}
	
	if(savedestination[0].weblink!=''){
		document.destinfoform.weblink.value = savedestination[0].weblink;
	}else{
		document.destinfoform.weblink.value = '';
	}
	
	if(savedestination[0].email!=''){
		document.destinfoform.email.value = savedestination[0].email;
	}else{
		document.destinfoform.email.value = '';
	}
	
//	if(!cyosf_active){
		manualcalsetup();
//	}
	
}


function verifiedaddpassport(type){
	
	var isuserok = verifythenopen();
	
	if(isuserok){
		saveactivemarker(type);
	}
}



function savebubble(type){
	
	var d = new Date();
 	var datecreated = d.getTime();
	savestring='';
	
	savedestination[0].name=document.destinfoform.destname.value;
	savedestination[0].description=activedescription;
	
//	if(!cyosf_active){
		if(document.destinfoform.public[0].checked==true){
			savedestination[0].public=1;
		}else{
			savedestination[0].public=0;
		}
		savedestination[0].desttags=document.destinfoform.dtags.value;
		savedestination[0].datemanual=document.destinfoform.date.value;
//	}
	
	savedestination[0].address1=document.destinfoform.address1.value;
	savedestination[0].address2=document.destinfoform.address2.value;
	savedestination[0].city=document.destinfoform.city.value;
	savedestination[0].state=document.destinfoform.state.value;
	savedestination[0].zip=document.destinfoform.zip.value;
	savedestination[0].country=document.destinfoform.country.value;
	savedestination[0].phone=document.destinfoform.phone.value;
	savedestination[0].fax=document.destinfoform.fax.value;
	savedestination[0].weblink=document.destinfoform.weblink.value;
	savedestination[0].email=document.destinfoform.email.value;
	savedestination[0].datecreated=datecreated;
	savedestination[0].lat = activemarker.getPoint().y;
	savedestination[0].lng = activemarker.getPoint().x;
	savedestination[0].zoom = map.getZoom();
	savedestination[0].maptype = map.getCurrentMapType().getName();
	savedestination[0].marker = markericon;
	
	if(type=='create'){
		
		savestring = savedestination[0].name+'|'+savedestination[0].description+'|'+savedestination[0].desttags+'|'+savedestination[0].public+'|'+savedestination[0].address1+'|'+savedestination[0].address2+'|'+savedestination[0].city+'|'+savedestination[0].state+'|'+savedestination[0].zip+'|'+savedestination[0].country+'|'+savedestination[0].phone+'|'+savedestination[0].fax+'|'+savedestination[0].weblink+'|'+savedestination[0].email+'|'+savedestination[0].datemanual+'|'+savedestination[0].datecreated+'|'+savedestination[0].lat+'|'+savedestination[0].lng+'|'+savedestination[0].zoom+'|'+savedestination[0].maptype+'|'+savedestination[0].marker;
		
		//OpenWindow();
		if(tb_active == false){
			//opencontrol('savedest');
			WebService.createdest(savestring, '', adddesttopassportmenu);
			
			//verifythenopen('savedest');
			map.closeInfoWindow();
		}else{
			addtbdestination(savestring);
			map.closeInfoWindow();
		}
	}
	
	if(type=='edit'){
		savestring = savedestination[0].name+'|'+savedestination[0].description+'|'+savedestination[0].desttags+'|'+savedestination[0].public+'|'+savedestination[0].address1+'|'+savedestination[0].address2+'|'+savedestination[0].city+'|'+savedestination[0].state+'|'+savedestination[0].zip+'|'+savedestination[0].country+'|'+savedestination[0].phone+'|'+savedestination[0].fax+'|'+savedestination[0].weblink+'|'+savedestination[0].email+'|'+savedestination[0].datemanual+'|'+savedestination[0].datecreated+'|'+savedestination[0].lat+'|'+savedestination[0].lng+'|'+savedestination[0].zoom+'|'+savedestination[0].maptype+'|'+savedestination[0].marker+'|'+currentdestinations[activeresult].destinationid+'|'+currentdestinations[activeresult].tourid+'|'+currentuser;
		
		//alert(savestring);
		
		editdestination(currentdestinations[activeresult].tourid);
		map.closeInfoWindow();
	}
	
	if(type=='storefront'){
		
		savestring = savedestination[0].name+'|'+savedestination[0].description+'|'+savedestination[0].desttags+'|'+savedestination[0].public+'|'+savedestination[0].address1+'|'+savedestination[0].address2+'|'+savedestination[0].city+'|'+savedestination[0].state+'|'+savedestination[0].zip+'|'+savedestination[0].country+'|'+savedestination[0].phone+'|'+savedestination[0].fax+'|'+savedestination[0].weblink+'|'+savedestination[0].email+'|'+savedestination[0].datemanual+'|'+savedestination[0].datecreated+'|'+savedestination[0].lat+'|'+savedestination[0].lng+'|'+savedestination[0].zoom+'|'+savedestination[0].maptype+'|'+savedestination[0].marker;
		
		//OpenWindow();
		//alert(savestring);
		prepforsave(savestring);
	}
	
}

function editdestdescription(destid){
	//alert(destid);
	savedestinationid = destid;
	opencontrol('describedest')	;
}




function assignmarker(image){
	
	var destinfo;
	markericon=image;
	markerimage = markerpath+markericon;
	
	buildcreateform(image);
	map.closeInfoWindow();
	//alert('about to set marker')
	activemarker.openInfoWindowHtml(destbubbleform_t1);
	//activemarker.openInfoWindowHtml(destinfo);
	activemarker.setImage(markerimage);
	popdestbubble();
}


function setvizsearchrad(outerpoint){
	
	var circleRadius_mtr = currentlocation[0].point.distanceFrom(outerpoint);
	var circleRadius_miles = circleRadius_mtr*0.0006213711922373339;
	
	//alert(circleRadius_miles);
	
	removesearchcircle();
	
	if(showsearchrad == true){
		circle = new CircleOverlay(currentlocation[0].point, circleRadius_miles, "#336699", 1, 1, '#336699', 0.25);
		map.addOverlay(circle);
		showseachrad(circleRadius_mtr);
	}
	
}


function showseachrad(circleRadius_mtr) {
	var circleRadius_miles = circleRadius_mtr*0.0006213711922373339;
	circleRadius_mtr = circleRadius_mtr*0.001;
	var shortradmiles = circleRadius_miles.toFixed(3);
	var shortrad_mtr = circleRadius_mtr.toFixed(3);
	
    var radinfo = '<div align="center"><div align="left" class="tooltip">Search Radius:<br>Miles: '+shortradmiles+'<br>KM: '+shortrad_mtr+'<br><a href="javascript:removesearchcircle()">Remove</a></div></div>';
	
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(locmarker.getPoint(),map.getZoom());
	var anchor=locmarker.getIcon().iconAnchor;
	var width=locmarker.getIcon().iconSize.width;
	var height=locmarker.getIcon().iconSize.height;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y - 2.5*height)); 
	
	pos.apply(radinfobox);
	radinfobox.innerHTML = radinfo;
	radinfobox.style.visibility = "visible";
	
	//
//	var x=locmarker.lat;
//	var y=locmarker.lng;
//	if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
//	if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
//	var pos_rightclick = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
	
}


function removesearchcircle(){
	try{
		map.removeOverlay(circle);
		radinfobox.style.visibility = "hidden";
	}catch(err){
		
	}
}


function initcircle(){

	// This file adds a new circle overlay to GMaps2
	// it is really a many-pointed polygon, but look smooth enough to be a circle.
	CircleOverlay = function(latLng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
		this.latLng = latLng;
		this.radius = radius;
		this.strokeColor = strokeColor;
		this.strokeWidth = strokeWidth;
		this.strokeOpacity = strokeOpacity;
		this.fillColor = fillColor;
		this.fillOpacity = fillOpacity;
	}
	
	// Implements GOverlay interface
	CircleOverlay.prototype = GOverlay;
	
	CircleOverlay.prototype.initialize = function(map) {
		this.map = map;
	}
	
	CircleOverlay.prototype.clear = function() {
		if(this.polygon != null && this.map != null) {
			this.map.removeOverlay(this.polygon);
		}
	}
	
	// Calculate all the points and draw them
	CircleOverlay.prototype.redraw = function(force) {
		var d2r = Math.PI / 180;
		circleLatLngs = new Array();
		var circleLat = this.radius * 0.014483;  // Convert statute miles into degrees latitude
		var circleLng = circleLat / Math.cos(this.latLng.lat() * d2r);
		var numPoints = 40;
		
		// 2PI = 360 degrees, +1 so that the end points meet
		for (var i = 0; i < numPoints + 1; i++) { 
			var theta = Math.PI * (i / (numPoints / 2)); 
			var vertexLat = this.latLng.lat() + (circleLat * Math.sin(theta)); 
			var vertexLng = this.latLng.lng() + (circleLng * Math.cos(theta));
			var vertextLatLng = new GLatLng(vertexLat, vertexLng);
			circleLatLngs.push(vertextLatLng); 
		}
		
		this.clear();
		this.polygon = new GPolygon(circleLatLngs, this.strokeColor, this.strokeWidth, this.strokeOpacity, this.fillColor, this.fillOpacity);
		this.map.addOverlay(this.polygon);
	}
	
	CircleOverlay.prototype.remove = function() {
		this.clear();
	}
	
	CircleOverlay.prototype.containsLatLng = function(latLng) {
		// Polygon Point in poly 
		if(this.polygon.containsLatLng) {
			return this.polygon.containsLatLng(latLng);
		}
	}
	
	CircleOverlay.prototype.setRadius = function(radius) {
		this.radius = radius;
	}
	
	CircleOverlay.prototype.setLatLng = function(latLng) {
		this.latLng = latLng;
	}
}
