
//---------------------------------------------
//	BlueDasherViewer main object
//---------------------------------------------
//  version 1.8.22
// 

function BlueDasherViewer(divname, apikey, width, height, parameters)
{
	this.serviceurl="http://nav.bluedashertech.com/service.aspx";
	this.photosfolder="http://live.bluedashertech.com/Pano_Photos/";
	this.mainfolder="http://nav.bluedashertech.com/";	//root folder of "images/"
	
	if(document.getElementById("BDTapicss")==null)
	{
		var head = document.getElementsByTagName("head")[0];
		var css=document.createElement('link');
		if(css && head)
		{
			css.id="BDTapicss";
			css.type="text/css"; 
			css.rel="stylesheet";
			css.href=this.mainfolder+"BDTapi.css";
			head.appendChild(css);
		}
	}
	
	//----------- Internal vars
	this.isOP=(navigator.userAgent.indexOf('Opera')!=-1);
	this.isIE=(navigator.platform.indexOf('Win')!=-1 && navigator.appVersion.indexOf("MSIE")!=-1 && !this.isOP);
	this.isMac=(navigator.platform.indexOf('Mac')!=-1 || navigator.platform.indexOf('PowerPC')!=-1);
	this.apikey=apikey;
	this.minDevalVRVersion = "0,8,2,0";
	this.addedVBcode=0;
	this.objectname="BlueDasherViewer_"+divname;
	this.pluginname="BlueDasherPlugin_"+divname;
	eval(this.objectname+"=this");	//autoreferer variable
	this.divname=divname;
	this.debugapi=null;
	this.debugwindow=null;
	this.debugnextvector=null;
	this.EnableDebug(0);
	this.http_requestini=new BlueDasherAjax(this.objectname+".http_requestini");
	this.http_request=new BlueDasherAjax(this.objectname+".http_request");
	this.http_requestgeo=new BlueDasherAjax(this.objectname+".http_requestgeo");
	this.http_requestlog=new BlueDasherAjax(this.objectname+".http_requestlog");
	this.http_requestcov=new BlueDasherAjax(this.objectname+".http_requestcov");
	this.http_requestrooftop=new BlueDasherAjax(this.objectname+".http_requestrooftop");
	this.http_requestsigns=new BlueDasherAjax(this.objectname+".http_requestsigns");
	this.http_requestads=new BlueDasherAjax(this.objectname+".http_requestads");
	this.http_requestroute=new BlueDasherAjax(this.objectname+".http_requestroute");
	this.http_requestpoi=Array();
	this.http_requestpoi0=new BlueDasherAjax(this.objectname+".http_requestpoi0");
	this.http_requestpoi1=new BlueDasherAjax(this.objectname+".http_requestpoi1");
	this.http_requestpoi2=new BlueDasherAjax(this.objectname+".http_requestpoi2");
	this.http_requestpoi3=new BlueDasherAjax(this.objectname+".http_requestpoi3");
	this.http_requestpoi4=new BlueDasherAjax(this.objectname+".http_requestpoi4");
	this.carimage=this.mainfolder+'images/car.swf';
	this.carsize=70;
	this.pluginused=1;		//0=Java  1=BlueDasherPlugin
	if(this.isMac) this.pluginused=0;
	this.pluginstate=0;
	this.pluginobj=null;
	this.pluginwindowless=0;
	this.plugincache=0;
	this.photosfolder_array=Array();
	this.photosfolder_attemps=0;
	this.photosfolder_attemphigh=0;
	this.photosfolder_searchhigh=0;
	this.photosfolder_use=0;
	this.loadingframe=0;
	this.wasmapdragged=0;
	this.autopanstate=0;
	this.distancemeasurestate=0;
	this.distancelat=null;
	this.distancelon=null;
	this.distanceindex=0;
	this.dashboardstate=0;
	this.dashboardsetdef=null;
	this.accesslog="";
	this.accesslognum=0;
	this.accesslogenabled=1;
	this.extmap=null;
	this.attachedmap=0;
	this.maploading=0;
	this.currentlatinfo=Array(-1,-1,-1,-1,-1,-1,-1,-1,-1);
	this.currentloninfo=Array(-1,-1,-1,-1,-1,-1,-1,-1,-1);
	this.currentlatmap=-1;
	this.currentlonmap=0;
	this.setzoompoints=0;
	this.visibleads=0;
	this.visiblemarkers=Array(0,0);
	this.visiblestreetarrows=0;
	this.visiblesplash=1;
	this.visiblesplashweb=0;
	this.visibleinternalmap=0;
	this.visibleroute=0;
	this.enableaddanchors=0;
	this.enablepointdircalc=0;
	this.latestfile="";
	this.latestframename="";
	this.latestpicture="";
	this.picturetimeout=null;
	this.topleftbannerurl="";
	this.toprightbannerurl="";
	this.bottomleftbannerurl="";
	this.bottomrightbannerurl="http://www.bluedashertech.com";
	this.boxw=0;
	this.boxh=0;
	this.moveboxenable=1;
	this.boxmap=null;
	if(width!=undefined) this.CreateBox(divname,width,height);
	else this.box=null;
	this.buttonstates=Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);
	this.buttonaction=Array("","","","");
	this.snapshotnumber=0;
	this.nkeycommands=Array(0,0,0,0,0);
	this.bdtmessages="";
	this.googlekey="ABQIAAAAF63xr4thrNNiTzN5baK4zxToFzGl9nWA1i0c_KyRU-OLB1FJshSenSU6sLBELYH9raqD2K5MJgKB9g";
	this.carcameraheight=2.0; //meters
	
	//------------ Events ----------------------------
	this.OnPictureLoaded=null;
	this.OnClickEvent=null;
	this.OnDoubleClickEvent=null;
	this.OnViewerClickEvent=null;
	this.OnMarkerEvent=null;
	
	//------------ Viewer attributes -----------------
	this.lightlevel=0;			//Current light level
	this.waitseconds=3;			//Time to load the High quality picture
	this.interfacefile=this.mainfolder+"images/skindefault.txt";		//Default interface file
	this.zoomdefault=0.62;

	//------------ Movement attributes ---------------
	this.navmode=0;				//0=vectors  1=stops
	this.ismoving=0;			//(movement state, 0=stopped  1=moving)
	this.facingdirection=0;		//(direction viewer should be looking at (relative to front of car), in degrees)
	this.nextmovingdirection=0;
	this.nextfacingdirection=0;
	this.turndirectionmode=1;	//0: No turn   1:Turn several images before intersection	2: Turn in the intersection
	this.searchingnextvector=0;
	this.lockdirection=0;		//(current lock direction)
	this.movingdirection=0;		//(direction of movement, in degrees)
	this.nextdirection=0;		//(Next direction angle, change with Turn(); 0 for forward; 90, right; -90, left)
	this.nextvectorlevel=0;
	this.isrouting=0;
	this.numgear=1;
	this.numimagesnavleft=0;	//Counting images for navigation limits
	this.numimagesnavmax=300;	//Maximum number of images for navigation limits
	this.messagenavmax="To continue navigating click on DRIVE again";
	this.messageenabled=0;
	
	this.currentvector=null;	//Current Vector object
	this.foundpoint=null;		//Latest Point returned by FindAddress function
	this.numcurrentpoint=-1;	//Index of current Point of Pictures list into currect Vector
	this.numcachepoint=-1;
	this.preloadingcacheenabled=0;
	this.preloadingcachestate=0;
	this.preloadingcachemax=10;
	this.preloadingcachenum=-1;
	this.preloadingcacheshowbar=0;
	
	//------------ Ads -------------------------------
	this.ads=new Array();
	this.numads=0;
	this.sceneobj=new Array();
	this.numsceneobj=0;
	this.adsimages=[];
	this.adsframes=[];
	this.adsicons=[];
	for(var n=0;n<10;n++)
	{
		this.adsimages[n]="";
		this.adsframes[n]="";
		this.adsicons[n]="";
	}
	
	//------------ Map Buttons --------------------------
	this.mapbuttondivs=[];
	this.nummapbuttons=0;
	this.maptooltipdiv=null;
	this.mapbuttonsleft=0;
	this.mapbuttonstop=0;
	this.maprightmargin=0;
	this.mapmenudiv=null;
	this.mapshapeover=null;
	this.mapshapeovermenu=null;

	this.mapdialogdiv=Array(null,null,null,null);
	this.mapdialogtab=Array(null,null,null,null);
	this.mapdialogvisible=Array(0,0,0,0);
	
	//------------ Routes -------------------------------
	this.routevectors=[];
	this.routepoints=[];
	this.routenumpoints=0;
	this.shaperoute=null;
	this.routedistancetoend=0;
	this.routefacingtoend=0;
	this.routetopoint=new BlueDasherCoords(0,0);
	this.routewindow=null;
	this.latestroutefrom="";
	this.latestrouteto="";
	this.latestroute=null;

	//------------ Rest Stops navigation ----------------
	this.allstops=null;
	this.boundlines=null;
	this.numcurrentstop=0;
	this.currentbound="";
	this.currentstoppoints=null;
	
	//------------ Parse parameters ---------------------
	if(parameters!=undefined)
	{
		try{
			eval(parameters);
		}catch(e){}
	}
	
	//------------ Create viewer ------------------------
	this.CreatePlugin();

	//--------------- Events ----------------------------
	if(this.isIE) document.attachEvent("onkeydown", keydown);
	else document.addEventListener("keydown", keydown, true);
	var pthis=this;

	function keydown(event)
	{
		pthis.OnKeyDown(event);
	}
	
	function Point()
	{
		this.ID=0;				//ID number of this point
		this.X=0.0;				//Longitude
		this.Y=0.0;				//Latitude
		this.Z=0.0;				//Altitude
		this.FacingX=0;			//FacingX
		this.FacingY=0;			//FacingY
		this.FacingDirection=0;	//Facing direction
		this.Roll=0.0;			//(Z axis correction)
		this.Pitch=0.0;			//(ramps correction)
		this.Yaw=0.0;			//(heading)
		this.Map="";			//Image
		this.File="";			//Image
		this.Vector=0;			//The vector this point belongs to
	};
	
	function Vector()
	{
		this.Direction=0;		//(angle from "From" to "To" in degrees)
		this.ID=0;				//ID number of this vector
		this.FromX=0;
		this.FromY=0;
		this.ToX=0;
		this.ToY=0;
		this.Pictures=null;		//(list of Point objects in the vector ordered from From to To)
		this.FromVectors=null;	//(list of Vector intersecting the current vector in From)
		this.ToVectors=null;	//(list of Vector intersecting the current vector in To)
	};	
}

function BlueDasherCoords(lat,lon,lat2,lon2)
{
	this.lat=lat;
	this.lon=lon;
	this.lat2=lat2;
	this.lon2=lon2;
}

BlueDasherViewer.prototype.GetValue= function(name)
{
	var value=0;
	if(this.navmode==0)	//Vectors
	{
		if(this.currentvector)
		{
			if(name=="numpictures") value=this.currentvector.Pictures.length;
			else 
			{
				if(this.enablepointdircalc && name=="Direction")
					value=this.GetAnglePoints(this.currentvector.FromY,this.currentvector.FromX,this.currentvector.ToY,this.currentvector.ToX);
				else value=this.currentvector[name];
			}
			
			if(name=="pointid" || value==undefined)
			{
				if(name=="pointid") name="ID";

				if(this.numcurrentpoint>=0 && this.numcurrentpoint<this.currentvector.Pictures.length)
				{
					if(this.enablepointdircalc && name=="Yaw" && this.currentvector.Pictures.length>1)
					{
						value=this.GetDirectionFromPoints(this.currentvector.Pictures,this.numcurrentpoint,0);
					}
					else value=this.currentvector.Pictures[this.numcurrentpoint][name];
				}
				else if(this.foundpoint) value=this.foundpoint[name];

				if(name=="Yaw")	//Adjust Yaw to vector direction
				{
					var vectordir=this.GetValue("Direction");
					var dif=this.DifAngle(vectordir,value);
					if(dif<10) value=vectordir;
					else if(dif>170) value=this.NegPosAngle(vectordir+180);
				}
			}
		}
		else if(this.foundpoint)
		{
			if(name=="Direction") name="Yaw";
			value=this.foundpoint[name];
		}
	}
	else if(this.navmode==1)	//Rest Stops
	{
		if(this.currentstoppoints)
		{
			if(name=="numpictures") value=this.currentstoppoints.length;
			else 
			{
				if(name=="pointid") name="ID";

				if(this.numcurrentpoint>=0 && this.numcurrentpoint<this.currentstoppoints.length)
				{
					if(name=="Direction" && this.currentstoppoints.length>1){
						value=GetDirectionFromPoints(this.currentstoppoints,this.numcurrentpoint,1);
					}
					else value=this.currentstoppoints[this.numcurrentpoint][name];
				}
				
			}
		}
	}
	if(value==undefined) value=0;
	else if(name=="Pitch") value=-value;
	return value;
}

BlueDasherViewer.prototype.GetDirectionFromPoints= function(points, numcurrentpoint, calculateYaw)
{
	var p0,p1,n0=numcurrentpoint,n1;
	var value=0;
	if(numcurrentpoint==points.length-1) n0--;
	n1=n0+1;
	p0=points[n0];
	p1=points[n1];
	value=this.GetAnglePoints(p0.Y,p0.X,p1.Y,p1.X);
	if(calculateYaw){
		var yaw=points[numcurrentpoint].Yaw;
		if(this.DifAngle(value,yaw)<90) value=yaw;
		else value=this.NegPosAngle(yaw+180);
	}
	
	return value;
}

BlueDasherViewer.prototype.GetVectorValue= function(vector,name, index, field, setvalue)
{
	var value=0;
	if(name=="ToVectors" || name=="FromVectors") 
	{
		if(index>=0 && index<vector[name].length)
		{
			if(field=="setNextSide") vector[name][index].NextSide=setvalue;
			else if(field=="setNextDirection") vector[name][index].NextDirection=setvalue;
			else if(field=="setNumBrothers") vector[name][index].NumBrothers=setvalue;
			else value=vector[name][index][field];
		}
	}
	else if(name=="numFrom")
	{
		if(vector.FromVectors)
			value=vector.FromVectors.length;
	}
	else if(name=="numTo")
	{
		if(vector.ToVectors)
			value=vector.ToVectors.length;
	}
	return value;
}

//---------------------------------------------
//	DevalVR plugin initialization
//---------------------------------------------

BlueDasherViewer.prototype.IsPluginInstalled = function()
{
	var installed=0;
	
	if(this.isIE)
	{
		if(this.addedVBcode==0)
		{
			str='Function detectActiveXControl(activeXControlName) \n';
			str+='  on error resume next \n';
			str+='  detectActiveXControl = False \n';
			str+='	set pControl = CreateObject(activeXControlName) \n';
			str+='	If (IsObject(pControl)) then \n';
			str+='		detectActiveXControl = True \n';
			str+='	End If \n';
			str+='End Function \n';

			var head = document.getElementsByTagName("head")[0];
			var script=document.createElement('script');
			if(script && head)
			{
				script.language ='VBscript';
				script.type = 'text/vbscript';
				script.defer=true;
				script.text = str;
				head.appendChild(script);
			}

			var scriptvb=document.createElement('script');
   			var strvb='Sub '+this.pluginname+'_DVLCommands(ByVal command, ByVal args) \n';
			strvb+='call '+this.pluginname+'_DoDVLCommands(command, args) \n';
			strvb+='end sub \n';
			if(scriptvb && head)
			{
				scriptvb.language ='VBscript';
				scriptvb.type = 'text/vbscript';
				scriptvb.defer=true;
				scriptvb.text = strvb;
				head.appendChild(scriptvb);
			}
			
			this.addedVBcode=1;
		}
		if(this.addedVBcode)
		{
			if(this.pluginused==1) installed=detectActiveXControl('DevalVRXCtrl.DevalVRXCtrl.1');
			else installed=detectActiveXControl('JavaPlugin') && navigator.javaEnabled();
		}
	}
	else
	{
		if(this.pluginused==1)
		{
			if(navigator.mimeTypes && navigator.mimeTypes["application/x-devalvrx"] && navigator.mimeTypes["application/x-devalvrx"].enabledPlugin)
			{
				var words = navigator.plugins["DevalVR 3D Plugin"].description.split(" ");
				var version = words[3].split(",");
				var min = this.minDevalVRVersion.split(",");
				installed=this.CheckMinVersion(version,min,4);
			}	
		}
		else
		{
			if (this.isOp || (navigator.mimeTypes && navigator.mimeTypes['application/x-java-applet'] && navigator.mimeTypes["application/x-java-applet"].enabledPlugin))
			{
				installed=navigator.javaEnabled();
			}
		}
	}
	return installed;
}

BlueDasherViewer.prototype.CheckMinVersion = function(version,min,num)
{
	var installed=0;
	for (var i = 0; i < num; i++)
	{
		if(parseInt(version[i])>parseInt(min[i])) 
		{
			installed=1;
			break;
		}
		else if(parseInt(version[i])<parseInt(min[i])) break;
		else if(parseInt(version[i])==parseInt(min[i]) && i==num-1) installed=1;
	}
	return installed;
}

BlueDasherViewer.prototype.SetPluginObject = function()
{
	ref=document.getElementById(this.pluginname);

	if(ref) 
	{
		str="this.pluginobj_=document."+this.pluginname;
		try{
			eval(str);
		}catch(e){}
		if(this.pluginobj_)
		{
			if(this.pluginused==1 && typeof(this.pluginobj_.pluginversion)!="undefined")
			{
				var minversion=this.minDevalVRVersion.split(",");
				var nminversion=0,n;
				for(n=0;n<4;n++) nminversion=(nminversion<<8)+parseInt(minversion[n]);
				if(this.pluginobj_.pluginversion<nminversion)
				{
					//Message to install a new version???
				}
				this.pluginobj=this.pluginobj_;
				if(this.plugincache==0)
					setTimeout(this.objectname+".EnablePluginCache(0)",5000);
				this.pluginstate=2;		//started
			}
			else if(this.pluginused==0 && typeof(this.pluginobj_.newPano)!="undefined")
			{
				this.pluginobj=this.pluginobj_;
				this.pluginstate=2;		//started
			}
		}
	}
	if(this.pluginstate<2)
	{
		setTimeout(this.objectname+".SetPluginObject()",500);
	}
}

BlueDasherViewer.prototype.CreatePlugin=function()
{
	var refdiv=document.getElementById(this.divname);
	if(refdiv)
	{
		if(this.IsPluginInstalled())
		{
			var str='';
			var srcfile=this.mainfolder+"images/startphoto.txt";
			
			if(this.pluginused==1)
			{
				str+='<div align=center style="width: 100%; height: 100%"><object id="'+this.pluginname+'" classid="clsid:5D2CF9D0-113A-476B-986F-288B54571614"';
				str+='  codebase="http://www.devalvr.com/instalacion/plugin/devalocx.cab';
				str+='#version='+this.minDevalVRVersion+'"';
				str+='  style="width: 100%; height: 100%" width="100%" height="100%" >';

				str+='  <param name="src" value="'+srcfile+'" />';
				str+='  <param name="projection" value="3" />';
				str+='  <param name="minrotationx" value="-15" />';
				str+='  <param name="zoom" value="'+this.zoomdefault+'" />';
				str+='  <param name="filter" value="1" />';
				str+='  <param name="minzoom" value="0.45" />';
				str+='  <param name="maxzoom" value="1.5" />';
				str+='  <param name="autoplayspeed" value="12" />';
				str+='  <param name="stamp" value="saveview,update,deletecache" />';
				str+='  <param name="progressbar" value="0" />';
				str+='  <param name="resize" value="0" />';
				str+='  <param name="toolsbar" value="0" />';
				str+='  <param name="activebuttons" value="#FF7" />';
				if(this.pluginwindowless)
					str+='  <param name="windowless" value="1" />';
			
				str+='<embed id='+this.pluginname+' name='+this.pluginname+' style="width: 100%; height: 100%" width="100%" height="100%"';
				str+=' pluginspage="http://www.devalvr.com/instalacion/plugin/install.html"';
				str+=' type="application/x-devalvrx"';

				str+=' src="'+srcfile+'"';
				str+=' projection="3"';
				str+=' minrotationx="-15"';
				str+=' zoom="'+this.zoomdefault+'"';
				str+=' filter="1"';
				str+=' minzoom="0.45"';
				str+=' maxzoom="1.5"';
				str+=' autoplayspeed="12"';
				str+=' stamp="saveview,update,deletecache"';
				str+=' progressbar="0"';
				str+=' resize="0"';
				str+=' toolsbar="0"';
				str+=' activebuttons="#FF7"';
				if(this.pluginwindowless)
					str+=' windowless="1"';
			
				str+=' />';
				str+='</object></div>';

				var head = document.getElementsByTagName("head")[0];
				var scriptcall=document.createElement('script');
				var strcall='function '+this.pluginname+'_DoDVLCommands(command, args)';
				strcall+='{ '+this.objectname+'.DoDVLCommands(command, args); }';
				if(scriptcall && head)
				{
					scriptcall.language ='Javascript';
					scriptcall.type = 'text/javascript';
					scriptcall.defer=true;
					scriptcall.text = strcall;
					head.appendChild(scriptcall);
				}
			}
			else
			{
				str+='<div align=center style="width: 100%; height: 100%"><applet id="'+this.pluginname+'" name="'+this.pluginname+'" code="ptviewer.class" archive="ptviewer.jar" width=100% height=100%>';
				str+='<param name=file value="'+srcfile+'">';
				str+='<param name=fov value="'+(45.0/this.zoomdefault)+'">';
				str+='<param name=cursor value="MOVE">';
				str+='<param name=showToolbar value="false">';
				str+='<param name=imgLoadFeedback value="false">';
				str+='</applet></div>';
			}
			refdiv.innerHTML=str;
			this.pluginstate=1;		//created
			this.autopanstate=0;

			setTimeout(this.objectname+".SetPluginObject()",1000);
			if(this.interfacefile!="")
				this.dashboartsetdef=setTimeout(this.objectname+".LoadInterface('"+this.interfacefile+"')",2500);
		}
		else
		{
			str='<div align=center><table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%" width=100%  height=100%><tr><td align="center" valign="middle">';
			str+='<div style="FONT-WEIGHT: 500; BACKGROUND-IMAGE: url('+this.mainfolder+'images/plugincheck.jpg); width: 491px; FONT-FAMILY: Arial, Helvetica, sans-serif; height: 316px; background-color: #ffffff">';
			str+='<br><br><br><div style="FONT-SIZE: x-small; width: 420px; height: 199px; TEXT-ALIGN: center">';
			str+='<p style="MARGIN-left: 120px"><FONT color=#FFFFFF size=2><b>In order to fully experience our virtual drive<br>you need to install the BlueDasher 360 Viewer.<br>';
			str+='<br>Quickly downloads in about 15 seconds over DSL connections.<br><br><br></FONT>';
			str+='</p><input type="submit" onclick="javascript:'+this.objectname+'.RunInstallation()" style="width: 140; MARGIN-left: 120px; cursor:pointer; border:outset 1px #ccc; background:#999; color:#666; font-weight:bold; padding: 1px 2px; background:url('+this.mainfolder+'images/formbg.gif) repeat-x left top;" value="    Install Plugin    ">';
			str+='</div></div>';
			str+='</td></tr></table></div>';
		
			refdiv.innerHTML=str;

			setTimeout(this.objectname+".CheckInstallation()",5000);
		}
	}
}

BlueDasherViewer.prototype.RunInstallation = function()
{
	var installer='';
	var userAgent=navigator.userAgent.toLowerCase();
	if(userAgent.indexOf('windows 95')!=-1 || userAgent.indexOf('win95')!=-1 || userAgent.indexOf('windows 98')!=-1 || userAgent.indexOf('win98')!=-1 || userAgent.indexOf('winnt4.0')!=-1 || userAgent.indexOf('windows nt 4')!=-1)
	{
		if(this.isIE) installer="BlueDasher_installer_ie_w98.exe";
		else installer="BlueDasher_installer_w98.exe";
	}
	else
	{
		if(this.isIE) installer="BlueDasher_installer_ie.exe";
		else installer="BlueDasher_installer.exe";
	}
//	window.location.replace('http://nav.bluedashertech.com/plugin/'+installer);
	window.location.replace('http://www.devalvr.com/install/'+installer);
}

BlueDasherViewer.prototype.CheckInstallation = function()
{
	if(!this.isIE) 
		navigator.plugins.refresh(0);

	if(this.IsPluginInstalled()) window.location.reload();
	else setTimeout(this.objectname+".CheckInstallation()",2000);
}

//-------------------------------------------------------
//	AJAX functions
//-------------------------------------------------------

function BlueDasherAjax(objectname)
{
	this.objectname=objectname;
    this.readyState = 0;
	this.status=0;
	this.isrequesting=0;
	this.timeout=0;
	this.node=null;
	this.nexturl="";
	this.nextfunc=null;
	this.type=0;
}

BlueDasherAjax.prototype.open = function(method, url, asynchronous) 
{
    if (method == 'GET')
	{
		this.RequestData=null;
		this.dataobject=null;
	    this.readyState = 1;
		this.status=0;
		this.respondToReadyState(1);
		if(this.onreadystatechange) this.onreadystatechange();
	    this.url = url;
	}
}

BlueDasherAjax.prototype.send = function(body) 
{
    this.readyState = 2;
	if(this.onreadystatechange) this.onreadystatechange();

	// remove previous <script> node
	if(this.node)
	{
		try{
			var head = document.getElementsByTagName('HEAD')[0];
			if(head) head.removeChild(this.node);
		}catch(e){}
	}
    // generate <script> node
	this.node = document.createElement('SCRIPT');
    this.node.type = 'text/javascript';
	this.node.defer=true;
    this.node.src = this.url+"&callback="+this.objectname+".Callback";
 	var pthis=this;
	
     /* inject <script> node into <head> of document */
    this.readyState = 3;
	if(this.onreadystatechange) this.onreadystatechange();
    var head = document.getElementsByTagName('HEAD')[0];
    if(head) head.appendChild(this.node);
	
	this.timeout=setTimeout(this.objectname+".Timeout()",20000);
	this.status=500;
}

BlueDasherAjax.prototype.setRequestHeader = function(){
}
BlueDasherAjax.prototype.onreadystatechange = function(){
}
BlueDasherAjax.prototype.respondToReadyState = function(){
}

BlueDasherAjax.prototype.Timeout = function()
{
	if(this.status==500)
	{
		if(this.onreadystatechange) this.onreadystatechange();
		this.isrequesting=0;
	}
}

BlueDasherAjax.prototype.Callback = function(object)
{
	if(this.timeout) clearTimeout(this.timeout);
	this.readyState = 4;
	this.status=200;
	if(object=="0") object=arguments[1];
	if(object)
	{
		this.dataobject=object;
		if(this.onreadystatechange) this.onreadystatechange();
	}
	this.isrequesting=0;
}

BlueDasherAjax.prototype.SendAjaxRequest= function(type, url, func)
{
	var ret=0;
	if(this.isrequesting==0 && (this.readyState==0 || this.readyState==4))
	{
		if(url=='') url=this.nexturl;
		if(func==null) func=this.nextfunc;
		this.nexturl="";
		if(url!='')
		{
			this.type=type;
			this.isrequesting=1;
			this.open("GET", url, true);
			this.setRequestHeader("accept","application/json");
			if(func) this.onreadystatechange = func;
			this.send(null);
		}
		ret=1;
	}
	else 
	{
		if(this.nexturl=="" || url=="")
			setTimeout(this.objectname+".SendAjaxRequest("+type+",'',null)",500);
		if(url!='') this.nexturl=url;
		if(func!=null) this.nextfunc=func;
		ret=1;
	}
	return ret;
}

//---------------------------------------------------
//	Server communication functions
//---------------------------------------------------

BlueDasherViewer.prototype.FindAddressTextBox = function(idtext)
{
	ref=document.getElementById(idtext);
	if(ref)
	{
		this.FindAddress(ref.value);
	}
}

BlueDasherViewer.prototype.FindAddressGeo = function(address, lat, lon, senddata)
{
	var pthis=this;
	var url="http://maps.google.com/maps/geo?output=json&oe=utf-8&key="+this.googlekey+"&mapclient=jsapi&hl=en";

	if(address!="") url+="&q="+encodeURI(address);
	else url+="&ll="+lat+"%2C"+lon;

	this.http_requestgeo.SendAjaxRequest(senddata,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			obj=this.dataobject;
			
			if(obj && obj.Status && obj.Status.code==200 && obj.Placemark)
			{
				if(this.type=="FindPosition"){
					var lat=obj.Placemark[0].Point.coordinates[1];
					var lon=obj.Placemark[0].Point.coordinates[0];
					var address=obj.Placemark[0].address.split(",");;
					setTimeout(pthis.objectname+".FindPosition('"+address[0]+"',"+lat+","+lon+",0)",200);
				}
				else if(this.type=="FromRoute"){
					pthis.Route("from",obj.Placemark[0].address);
				}
				else if(this.type=="ToRoute"){
					pthis.Route("to",obj.Placemark[0].address);
				}
				else if(this.type=="searchAddress"){
					pthis.SetSearchText(obj.Placemark[0].address);
				}
			}
			else
			{
				alert("Address not found. Please verify your address and try again");
			}
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
}

BlueDasherViewer.prototype.FindAddress = function(address)
{
	if(this.IsInterfaceLoaded("FindAddress('"+address+"')",1000))
	{
		this.Dbg("find1",address);
		this.FindPosition(address,0,0,0);
	}
}

BlueDasherViewer.prototype.FindPoint = function(lat, lon, facingdirection, tilt, zoom)
{
	if(this.IsInterfaceLoaded("FindPoint("+lat+","+lon+","+facingdirection+","+tilt+","+zoom+")",1000))
	{
		this.Dbg("find2",lat,lon);
		this.FindPosition("",lat,lon,0,facingdirection,tilt,zoom);
	}
}

BlueDasherViewer.prototype.FindImage = function(pointid, facingdirection, tilt, zoom)
{
	if(this.IsInterfaceLoaded("FindImage("+pointid+","+facingdirection+","+tilt+","+zoom+")",1000))
	{
		this.Dbg("find3",pointid);
		this.FindPosition("",0,0,pointid, facingdirection, tilt, zoom);
	}
}

BlueDasherViewer.prototype.FormatAddress = function(address, deletenum)
{
	if(address!="")
	{
		if(deletenum==0) address=address.replace(/#/,"UNIT ");
		var pdo1=address.indexOf("#"),pdo2;
		if(pdo1!=-1)
		{
			pdo2=address.indexOf(",");
			if(pdo2!=-1) address=address.substr(0,pdo1)+address.substr(pdo2,address.length-pdo2);
		}
		address=decodeURI(address);
	}
	return address;
}

BlueDasherViewer.prototype.FindPosition = function(address, lat, lon, pointid, facingdirection, tilt, zoom) 
{
	var url=this.serviceurl;
	var pthis=this;
	var type;

	if(lat==0 && lon==0 && pointid==0) {type=0; url+="?service=FindAddress&address="; }
	else if(address!="") {type=1; url+="?service=FindAddressGeo&lat=" + lat + "&lon=" + lon + "&streetaddress="; }
	else if(pointid!=0) {type=2; url+="?service=FindImage&Pointid="+ pointid; }
	else {type=3; url+="?service=FindPoint&latitude=" + lat + "&longitude=" + lon + "&address="; }
	address=this.FormatAddress(address,0);
	url+=encodeURI(address);
	if(this.navmode==1) url+="&bound="+this.currentbound;
	url+="&customer="+this.apikey;

	this.UpdateInterface("hideclickdrag");
	this.UpdateMessages("showwaiting,hidemessage");
	this.http_request.SendAjaxRequest(type,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			var obj=this.dataobject;
			if(obj && obj.d)
			{
				pthis.foundpoint=obj.d;
				pthis.Dbg("findr",obj.d,this);
			
				pthis.foundpoint.address=address;

				pthis.photosfolder_attemps=0;
				pthis.photosfolder_attemphigh=0;

				if (pthis.foundpoint.BdtAccuracy != undefined) 
				{
					if (pthis.foundpoint.BdtAccuracy == 2) {		//Neighborhood Found
						pthis.ShowMessage("This image may be displaying an approximate location. [br]If you see the correct address on the satellite map and a blue line on the correct street, double click on the address number to display image. [br]If you are still not able to find the correct image, contact customer service at contact@bluedashertech.com");
						pthis.messageenabled=0;
						pthis.ShowRoofTopNumbers();
						pthis.ShowCoverage();
					}
					else if (pthis.foundpoint.BdtAccuracy == 1) {	//Not covered coming soon
						pthis.ShowMessage("We do not have coverage in this address. [br]It may be a private road, unpaved road or gated community. [br]Double click on the blue line on the satellite map to display the closest image. [br]To submit this address for coverage, contact customer service at contact@bluedashertech.com");
						pthis.messageenabled=0;
						pthis.ShowRoofTopNumbers();
						pthis.ShowCoverage();
					}
					else if (pthis.foundpoint.BdtAccuracy == 0) {	//Not found, check address
						pthis.ShowMessage("We were unable to find the address used. [br]If you know correct address, contact customer service at contact@bluedashertech.com");
						pthis.messageenabled=0;
					}
				}
				else pthis.foundpoint.BdtAccuracy=3;
				
				if((pthis.foundpoint.BdtAccuracy==3 || pthis.foundpoint.BdtAccuracy==2) && pthis.foundpoint.Vector!=undefined && pthis.foundpoint.Vector!=0 && pthis.foundpoint.Y!=0 && pthis.foundpoint.X!=0) 
				{	// Address found correctly
					if(pthis.box)
					{
						pthis.ShowBox(1);
						if(address!="") pthis.SetBoxInfo(address);
					}
					if(facingdirection!=undefined)
					{
						pthis.foundpoint.FacingDirection=facingdirection;
						if(tilt==undefined) tilt=0.0;
						if(zoom==undefined) zoom=pthis.zoomdefault;
						pthis.foundpoint.Tilt=tilt;
						pthis.foundpoint.Zoom=zoom;
					}
					if(this.type==0) pthis.SetSearchText(pthis.foundpoint.address);
					else pthis.FindAddressGeo("",pthis.foundpoint.Y,pthis.foundpoint.X,"searchAddress");
					setTimeout(pthis.objectname+".LoadVector('"+pthis.foundpoint.Vector+"','"+pthis.foundpoint.Map+"')",300);
				}
				else if(pthis.foundpoint.BdtAccuracy==3 && pthis.foundpoint.NextStop!=undefined && pthis.foundpoint.NextStop!=0) 
				{
					pthis.numcurrentstop=pthis.GetStopIndex(pthis.foundpoint.Bound,pthis.foundpoint.NextStop);
					setTimeout(pthis.objectname+".LoadStop("+(pthis.numcurrentstop)+")",300);
				}
				else 
				{
					if(pthis.foundpoint)
					{
						pthis.currentvector=null;
						pthis.numcurrentpoint=-1;
						pthis.numcachepoint=-1;
					}
					if(pthis.foundpoint.BdtAccuracy!=3) 
					{
						pthis.foundpoint.File="";
						if(pthis.foundpoint.Y!=0 && pthis.foundpoint.X!=0 && pthis.foundpoint.BdtAccuracy!=0)
						{
							if(pthis.foundpoint.FacingY==0 && pthis.foundpoint.FacingX==0)
							{
								pthis.foundpoint.FacingY=pthis.foundpoint.Y;
								pthis.foundpoint.FacingX=pthis.foundpoint.X;
							}
							pthis.movingdirection=pthis.foundpoint.Yaw;
							pthis.facingdirection=pthis.GetAnglePoints(pthis.foundpoint.Y,pthis.foundpoint.X, pthis.foundpoint.FacingY, pthis.foundpoint.FacingX);
							pthis.UpdateFacingDirection(0);

							pthis.MoveFlag(pthis.foundpoint.FacingY,pthis.foundpoint.FacingX,pthis.foundpoint.address);
							pthis.MoveMap(pthis.foundpoint.FacingY,pthis.foundpoint.FacingX,1);
							pthis.MoveCar(pthis.foundpoint.Y,pthis.foundpoint.X);
							if(pthis.extmap && pthis.extmap.zoomlevel<18) pthis.ZoomMap(18,1);
							pthis.ZoomMapPoints(pthis.foundpoint.FacingY,pthis.foundpoint.FacingX,pthis.foundpoint.Y,pthis.foundpoint.X);

							if(this.type==0) pthis.SetSearchText(pthis.foundpoint.address);
							else pthis.FindAddressGeo("",pthis.foundpoint.Y,pthis.foundpoint.X,"searchAddress");
						}
						else 
						{	//Reset to initial position (USA view)
							pthis.MoveMap(39.774769,-99.492187,1);
							pthis.ZoomMap(3,1);
							pthis.ShowCar(false);
							pthis.ShowFlag(false);
						}
						pthis.LoadPicture("nophoto");
						pthis.UpdateMessages("hidewaiting,showsplash");
					}
					else if(lat==0 && pthis.foundpoint.Y==0 && pthis.foundpoint.X==0)
					{
						if(pthis.foundpoint.File=="serviceerror") alert("Service error in FindAddress function");
						else alert("Address not found: "+address+"\nPlease verify your address and try again");
						pthis.UpdateMessages("hidewaiting");
					}
				}
			}
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
}

BlueDasherViewer.prototype.LoadVector = function(id, map) {
    var pthis = this;
    var url = this.serviceurl + "?service=LoadVector&id=" + id + "&map=" + map;
    url += "&customer=" + this.apikey;

	pthis.Dbg("loadvec",id);
    this.http_request.SendAjaxRequest(0,url, function() {
        if (this.readyState == 4 && this.status == 200) {
            var obj = this.dataobject;
			pthis.Dbg("loadvecr",obj.d);
			if (obj && obj.d && (obj.d.File == undefined || obj.d.File != "serviceerror")) {
                if (pthis.foundpoint && pthis.foundpoint.Vector == obj.d.ID && pthis.foundpoint.ID != 0) {
					pthis.Dbg("loadvecfound",obj.d);
                    var isrouting = pthis.isrouting;
                    pthis.ResetViewer();

                    pthis.currentvector= obj.d;
                    num = pthis.GetValue("numpictures");
                    for (n = 0; n < num; n++) {
                        if (pthis.foundpoint.ID == pthis.currentvector.Pictures[n].ID) {
                            pthis.numcurrentpoint = n;
                            pthis.numcachepoint = n;
                            break;
                        }
                    }
                    pthis.foundpoint.ID = 0; //To do it only first time, when Point is found after a FindPoint call

                    var x = pthis.GetValue("X");
                    var y = pthis.GetValue("Y");
                    pthis.movingdirection= pthis.GetValue("Direction");
                    if (pthis.foundpoint.Tilt != undefined)
                        pthis.facingdirection = pthis.foundpoint.FacingDirection;
                    else if (pthis.foundpoint.FacingY != 0 && pthis.foundpoint.FacingX != 0)
                        pthis.facingdirection = pthis.GetAnglePoints(y, x, pthis.foundpoint.FacingY, pthis.foundpoint.FacingX);
                    else pthis.facingdirection = pthis.movingdirection;

                    pthis.currentlatmap=-1;
                    pthis.LoadPicture("foundpoint");

                    if (isrouting == 2) {
                        pthis.isrouting = 1;
                        pthis.GoForward();
                    }
                }
                else if (pthis.currentvector) {
                    if(pthis.StoreVector(pthis.currentvector, obj.d)==0)
						pthis.Dbg("loadvecnot",obj.d);
                }
            }
            else 
			{
				pthis.UpdateMessages("hidewaiting");
				alert("Service error in LoadVector function");
			}
        }
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
    });
}

BlueDasherViewer.prototype.StoreVector = function(vector, vectordata) 
{
	var fromto="From";
	var saved=0;
	var n,ft,num,paso;
	var vec=null;
	
	for(paso=0;paso<2;paso++)
	{
		fromto="From";
		for(ft=0;ft<2 && saved==0;ft++)
		{
			vec=vector[fromto+"Vectors"];
			if(vec)
			{
				num=vec.length;
				for(n=0;n<num && saved==0;n++)
				{
					if(paso==0)
					{
						if(vec[n] && vec[n].ID==vectordata.ID)
						{
							this.Dbg("loadvecsaved",vectordata,fromto,n,vector);
							vec[n]=vectordata;
							saved=1;
						}
					}
					else
					{
						if(vec[n] && (vec[n].FromVectors!=null || vec[n].ToVectors!=null))
						{
							saved=this.StoreVector(vec[n],vectordata);
						}
					}
				}
			}	
			fromto="To";
		}
	}
	return saved;
}

BlueDasherViewer.prototype.FindRoute = function(addressFrom, addressTo)
{
	if(this.IsMapLoaded("FindRoute('"+addressFrom+"','"+addressTo+"')",2000))
	{
		var url="http://maps.google.com/maps/nav?output=js&key="+this.googlekey+"&q=";
		var pthis=this;

		addressFrom=this.FormatAddress(addressFrom,1);
		addressTo=this.FormatAddress(addressTo,1);
		url+="from: "
		url+=encodeURI(addressFrom);
		url+=" to: "
		url+=encodeURI(addressTo);

		this.Dbg("findroute",addressFrom,addressTo);
		this.http_requestroute.SendAjaxRequest(0,url,function()
		{
			if (this.readyState==4 && this.status==200)
			{
				obj=this.dataobject;
				
				if(obj && obj.Status && obj.Status.code==200 && obj.Directions)
				{
					if(pthis.extmap)
					{
						if(pthis.extmap.layerroute) pthis.extmap.EmptyLayer(pthis.extmap.layerroute);
						else pthis.extmap.layerroute=pthis.extmap.CreateLayer();
						pthis.extmap.ShowLayer(pthis.extmap.layerroute);

						pthis.Dbg("findrouter",obj);

						var n,lat,lon,lat0,lon0,facing;
						var route=new Array();
						var nump=obj.Directions.Routes[0].Steps.length;

						if(pthis.extmap.zoomlevel<16) pthis.ZoomMap(16,1);

						latend=obj.Directions.Routes[0].End.coordinates[1];
						lonend=obj.Directions.Routes[0].End.coordinates[0];
						for(n=0;n<=nump;n++)
						{
							if(n<nump)
							{
								lat=obj.Directions.Routes[0].Steps[n].Point.coordinates[1];
								lon=obj.Directions.Routes[0].Steps[n].Point.coordinates[0];
							}
							else
							{
								lat=latend;
								lon=lonend;
							}
							route[n*2]=lat;
							route[n*2+1]=lon;
							latpoint=lat;
							lonpoint=lon;
							if(n==0)
							{
								if(nump>1)
								{
									lat0=obj.Directions.Routes[0].Steps[1].Point.coordinates[1];
									lon0=obj.Directions.Routes[0].Steps[1].Point.coordinates[0];
								}
								else
								{
									lat0=latend;
									lon0=lonend;
								}
								facing=pthis.GetAnglePoints(lat,lon,lat0,lon0);
							}
							else if (n<nump)
							{
								lat0=route[(n-1)*2];
								lon0=route[(n-1)*2+1];
								facing=pthis.GetAnglePoints(lat0,lon0,lat,lon);
								angle=90-facing;
								latpoint=lat-Math.sin((angle*Math.PI)/180.0)*0.0003;
								lonpoint=lon-Math.cos((angle*Math.PI)/180.0)*0.0003;
							}
							else
							{
								lat0=obj.Placemark[1].Point.coordinates[1];
								lon0=obj.Placemark[1].Point.coordinates[0];
								pthis.routetopoint.lat=lat0;
								pthis.routetopoint.lon=lon0;
								facing=pthis.GetAnglePoints(lat,lon,lat0,lon0);

								var shape=pthis.extmap.CreateShape(lat0,lon0,8,-10,17,21,'<div style="background: url('+pthis.mainfolder+'images/imgapi.gif) 0px -68px; background-repeat:no-repeat; width: 100%; height: 100%" ></div>');
								if(shape) pthis.extmap.layerroute.AddShape(shape);
							}
							
							var mark='<div zindex=2000 style="background: url('+pthis.mainfolder+'images/imgapi.gif) 0px -36px; background-repeat:no-repeat; width: 100%; height: 100%" onmouseover="this.style.cursor=\'pointer\'" onmousedown="'+pthis.objectname+'.FindPoint('+latpoint+','+lonpoint+','+facing+')" ';
							mark+='><font class="textmap"><b>'+n+'<b></font></div>';
							var shape = pthis.extmap.CreateShape(lat,lon,0,-14,23,30, mark);
							if(shape) pthis.extmap.layerroute.AddShape(shape);
							
							if(n==0) pthis.MoveMap(lat,lon);
	//						else pthis.extmap.IncludePointInView(lat,lon);
						}

						route=pthis.DecodePolyline(obj.Directions.Polyline.points);
						pthis.shaperoute = pthis.extmap.CreateLine(route, 0,255,0, 0.7, 5);
						if(pthis.shaperoute) pthis.extmap.layerroute.AddShape(pthis.shaperoute);

						this.isrequesting=0;
						pthis.LoadRouteVectors(route);
						
						pthis.latestroutefrom=addressFrom;
						pthis.latestrouteto=addressTo;
						pthis.latestroute=obj;
					}
				}
				else
				{
					alert("Address not found. Please verify your address and try again");
				}
			}
			else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
		});
	}
}

BlueDasherViewer.prototype.LogAccess = function(id) 
{
	var url=this.serviceurl+"?service=LogAccess&customer="+this.apikey;
	var pthis=this;

	if(id!="")
	{
		if(this.accesslog!="") this.accesslog+=",";
		this.accesslog+=id;
		this.accesslognum++;
	}
	url+="&images="+this.accesslog;

	if(this.accesslognum>=10 && this.http_requestlog.isrequesting==0)
	{
		this.http_requestlog.SendAjaxRequest(0,url,null);
		this.accesslog="";
		this.accesslognum=0;
	}
}

BlueDasherViewer.prototype.EnableLogAccess = function(enable) 
{
	this.accesslogenabled=enable;
}

BlueDasherViewer.prototype.FindMapinfo = function(info,lat1,lon1,lat2,lon2) 
{
	var url="";
	var pthis=this;
	var http_request=null;
	var layer=null;
	var layerant=null;

	if(this.extmap==null) return;
	
	if(info<=3) url+=this.serviceurl+"?customer="+this.apikey+"&map="+this.GetValue("Map")+"&lat1="+lat1+"&lon1="+lon1+"&lat2="+lat2+"&lon2="+lon2;
	else if(info<=8) url+='http://www.google.com/uds/GlocalSearch?context=0&lstkp=0&rsz=large&hl=en&gss=.com&sig=457a1b12dfe20ca00fd65f9ad5d52ccd&llsep=500,500&key=notsupplied&v=1.0';
	if(info==0)
	{
		url+="&service=GetVectors";
		http_request=this.http_requestcov;
	}
	else if(info==1) 
	{
		url+="&service=GetRoofTops";
		http_request=this.http_requestrooftop;
	}
	else if(info==2) 
	{
		if(this.navmode==0) url+="&service=GetPropertySigns";
		else
		{
			url+="&service=GetSigns";
			url+="&bound="+this.currentbound;
		}
		http_request=this.http_requestsigns;
	}
	else if(info==3) 
	{
		if(this.navmode==0) url+="&service=GetPropertyAds";
		else
		{
			url+="&service=GetAds";
			url+="&bound="+this.currentbound;
		}
		http_request=this.http_requestads;
	}
	else if(info<=8)
	{
		var type="";
		if(info==4){
			type="pharmacy";
			http_request=this.http_requestpoi0;
		}
		else if(info==5){
			type="market";
			http_request=this.http_requestpoi1;
		}
		else if(info==6){
			type="church";
			http_request=this.http_requestpoi2;
		}
		else if(info==7){
			type="school";
			http_request=this.http_requestpoi3;
		}
		else if(info==8){
			type="hospital";
			http_request=this.http_requestpoi4;
		}
		url+='&q='+type;
		url+='&sll='+(lat1+(lat2-lat1)/2)+','+(lon1+(lon2-lon1)/2)+'&sspn=0.023188,0.042915&gll='+parseInt(lat2*100000)+','+parseInt(lon1*100000)+','+parseInt(lat1*100000)+','+parseInt(lon2*100000);
	}
	if(info!=3)
	{
		layer=this.extmap.layermapinfo[info*2+1-this.extmap.ilayermapinfo[info]];
		layerant=this.extmap.layermapinfo[info*2+this.extmap.ilayermapinfo[info]];
		if(layer==null || layerant==null) return;
	}	
	this.Dbg("mapinfo",info,lat1,lon1,lat2,lon2);
	
	http_request.SendAjaxRequest(info,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			var obj=null;
			if(this.dataobject.results) obj=this.dataobject.results;
			else if(this.dataobject.d) obj=this.dataobject.d;
			if(obj && (obj.File==undefined || obj.File!="serviceerror"))
			{
				var info=this.type;
				pthis.Dbg("mapinfor",info,obj);
				num=obj.length;

				if(pthis.extmap.enabledmapinfo[info] && pthis.extmap.zoomlevel>=pthis.extmap.mininfozoom[info])
				{
					if(info==0)	//Coverage
					{
						for(n=0;n<num;n++) 
						{
							v = obj[n];
							if (v && v.FromY) 
							{
								var shape = pthis.extmap.CreateLine([v.FromX,v.FromY, v.ToX,v.ToY], 0,20,255, 0.5, 2);
								layer.AddShape(shape);
							}
							else if (v && v.Y1) 
							{
								var shape = pthis.extmap.CreateLine([v.Y1,v.X1, v.Y2,v.X2], 0,20,255, 0.5, 2);
								layer.AddShape(shape);
							}
						}
					}
					else if(info==1)	//Rooftop numbers
					{
						for(n=0;n<num;n++) 
						{
							r = obj[n];
							if (r && r.Lat && r.Number) 
							{
								var sizex=r.Number.length*8+2;
								var shape = pthis.extmap.CreateShape(r.Lat,r.Lon,0,0,sizex+6,13, "<img src='"+pthis.mainfolder+"images/rooftop1.gif' /><FONT style='position:relative; top:-2px; height:13px; width:"+sizex+"px; TEXT-ALIGN: center; FONT: bold 11px Arial; color:#202020; background-color:#FFEEDD'>" + r.Number + "</FONT><img src='"+pthis.mainfolder+"images/rooftop2.gif' />");
								if(shape.SetTitle!=undefined) shape.SetTitle(r.Address);
								layer.AddShape(shape);
							}
						}
					}
					else if(info==2)	//Property signs
					{
						for(n=0;n<num;n++) 
						{
							r = obj[n];
							if (r && r.Lat && r.Lon && (r.Bound==undefined || r.Bound==pthis.currentbound)) 
							{
								var htmlcode="";
								if(r.HTML!=undefined) 
								{
									if(r.SignContentUrl!=undefined) htmlcode+="<a href='"+r.SignContentUrl+"' target='_blank'>";
									htmlcode+="<img border='0' src='"+r.HTML+"' />";
									if(r.SignContentUrl!=undefined) htmlcode+="</a>";
								}
								else
								{
									var typesale="sale";
									if(r.Type=="R") typesale="rent";
									htmlcode="<img src='"+pthis.mainfolder+"images/for"+typesale+"icon.gif' />";
								}
								var shape = pthis.extmap.CreateShape(r.Lat,r.Lon,0,0,20,20, htmlcode);
								if(r.HTML==undefined) 
								{
									shape.BDTTitle="- Property -";
									shape.BDTTooltip="";
									shape.BDTAddress="_latlon_"
								}
								layer.AddShape(shape);
							}
						}
					}
					else if(info==3)	//Property ads
					{
						pthis.RemoveAds();
						for(n=0;n<num;n++) 
						{
							r = obj[n];
							if (r && r.Lat && r.Lon && (r.Bound==undefined || r.Bound==pthis.currentbound)) 
							{
								pthis.InsertPropertyAd(r.Lat,r.Lon,r.HTML,r.AdFrameUrl,r.AdIconUrl);
							}
						}
					}
					else if(info<=8)
					{
						for(n=0;n<num;n++) 
						{
							r = obj[n];
							if (r && r.lat && r.lng) 
							{
								var htmlcode="",type="";
								if(info==4) type="pharmacy";
								else if(info==5) type="market";
								else if(info==6) type="church";
								else if(info==7) type="school";
								else if(info==8) type="hospital";
								htmlcode='<img src="'+pthis.mainfolder+'images/'+type+'_ico.gif" />';

								var shape = pthis.extmap.CreateShape(r.lat,r.lng,0,0,20,20, htmlcode);
								shape.BDTTitle=r.titleNoFormatting;
								shape.BDTTooltip="<b>"+r.titleNoFormatting+"</b><br>";
								if(r.streetAddress!="") shape.BDTTooltip+=r.streetAddress+"<br>";
								shape.BDTTooltip+=r.city+", "+r.region;
								shape.BDTAddress=r.addressLines[0]+", "+r.addressLines[1];

								layer.AddShape(shape);
							}
						}
					}
					
					if(info==3){
						if(pthis.ismoving==0 && pthis.pluginobj){
							pthis.CreateSceneObjects(pthis.latestframename,pthis.GetValue("Y"),pthis.GetValue("X"),pthis.GetValue("Yaw"),1);
						}
					}
					else{
						pthis.extmap.ilayermapinfo[info]=1-pthis.extmap.ilayermapinfo[info];
						pthis.extmap.ShowLayer(layer);
						pthis.extmap.HideLayer(layerant);
						pthis.extmap.EmptyLayer(layerant);
					}

				}
				pthis.extmap.busymapinfo[info]=0;
			}
			else alert("Service error in FindMapinfo function");
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
}

BlueDasherViewer.prototype.LoadAllStops = function() 
{
	var url=this.serviceurl+"?service=GetStops&customer="+this.apikey;
	var pthis=this;

	this.http_requestini.SendAjaxRequest(0,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			obj=this.dataobject;
			if(obj && obj.d && (obj.d.File==undefined || obj.d.File!="serviceerror"))
			{
				pthis.allstops=obj.d;
				pthis.numcurrentstop=pthis.allstops.length-1;
				pthis.LoadAllLines();
			}
			else alert("Service error in GetStops function");
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
}

BlueDasherViewer.prototype.LoadAllLines = function() 
{
	var url=this.serviceurl+"?service=GetLines&customer="+this.apikey;
	var pthis=this;

	if(this.IsMapLoaded("LoadAllLines()",1000))
	{
		this.http_requestroute.SendAjaxRequest(0,url,function()
		{
			if (this.readyState==4 && this.status==200)
			{
				obj=this.dataobject;
				if(obj && obj.d && (obj.d.File==undefined || obj.d.File!="serviceerror"))
				{
					pthis.boundlines=obj.d;

					var n,num,bound;
					var shapeline;
					num=pthis.allstops.length;
					for(n=0;n<num;n++)
					{
						bound=pthis.allstops[n].Bound;
						if(pthis.extmap.layerbound[bound]==undefined) 
							pthis.extmap.layerbound[bound]=pthis.extmap.CreateLayer();

						shapeline=pthis.extmap.CreateLine(pthis.boundlines.Points[n], 0,255,0, 0.5, 5);
						if(shapeline) pthis.extmap.layerbound[bound].AddShape(shapeline);
					}
					pthis.SetBound(pthis.allstops[0].Bound);
				}
				else alert("Service error in GetLines function");
			}
			else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
		});
	}
}

BlueDasherViewer.prototype.LoadStop = function(numindex)
{
	var url=this.serviceurl+"?service=GetAllImagesForStop&customer="+this.apikey;
	var pthis=this;
	var n,num,numstop,bound;
	
	url+="&bound="+this.allstops[numindex].Bound;
	url+="&stop="+this.allstops[numindex].NextStop;

	function SetParameters()
	{
		if(pthis.foundpoint && pthis.foundpoint.ID!=0)
		{
			pthis.ResetViewer();

			num=pthis.GetValue("numpictures");
			for(n=0;n<num;n++)
			{
				if(pthis.foundpoint.ID==pthis.currentstoppoints[n].ID)
				{
					pthis.numcurrentpoint=n;
					pthis.numcachepoint=n;
					break;
				}
			}
			pthis.foundpoint.ID=0; //To do it only first time, when Point is found after a FindPoint call

			pthis.movingdirection=pthis.GetValue("Direction");
			if(pthis.foundpoint.Tilt!=undefined)
				pthis.facingdirection=pthis.foundpoint.FacingDirection;
			else if(pthis.foundpoint.FacingY!=0 && pthis.foundpoint.FacingX!=0)
				pthis.facingdirection=pthis.GetAnglePoints(pthis.foundpoint.Y,pthis.foundpoint.X,pthis.foundpoint.FacingY,pthis.foundpoint.FacingX);
			else 
				pthis.facingdirection=pthis.movingdirection;

			pthis.currentlatmap=-1;
			pthis.LoadPicture("foundpoint");
		}
		else
		{
			pthis.movingdirection=pthis.GetValue("Direction");
			pthis.facingdirection=0;
			pthis.LoadPicture();
		}
		bound=pthis.currentstoppoints[0].Bound;
		if(pthis.extmap && pthis.currentbound!=bound)
		{
			if(pthis.currentbound!="" && pthis.extmap.layerbound[pthis.currentbound]!=undefined)
				pthis.extmap.HideLayer(pthis.extmap.layerbound[pthis.currentbound]);

			pthis.extmap.ShowLayer(pthis.extmap.layerbound[bound]);
		}
		pthis.currentbound=bound;
	}

	if(this.allstops[numindex].Points!=undefined)
	{
		if(this.numcurrentstop==numindex)
		{
			this.currentstoppoints=this.allstops[numindex].Points;
			SetParameters();
		}
	}
	else
	{
		this.http_request.SendAjaxRequest(0,url,function()
		{
			if (this.readyState==4 && this.status==200)
			{
				var numloadingstop;
				var n,num;
				
				obj=this.dataobject;
				if(obj && obj.d && (obj.d.File==undefined || obj.d.File!="serviceerror"))
				{
					numloadingstop=pthis.GetStopIndex(obj.d[0].Bound,obj.d[0].NextStop);
					if(pthis.numcurrentstop==numloadingstop)
					{
						pthis.currentstoppoints=obj.d;
						SetParameters();
					}
					pthis.allstops[numloadingstop].Points=obj.d;
				}
				else alert("Service error in GetAllImagesForStop function");
			}
			else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
		});
	}
}

BlueDasherViewer.prototype.SaveListing = function(association, ml)
{
	var url=this.serviceurl+"?service=SaveListing&customer="+this.apikey;
	var pthis=this;
	
	url+="&association="+association;
	url+="&ml="+ml;
	url+="&lat="+this.GetValue("Y");
	url+="&lon="+this.GetValue("X");
	url+="&tilt="+this.GetTiltCamera();
	url+="&facingdirection="+this.GetFacingDirection();
	url+="&zoom="+this.GetZoomCamera();
	url+="&brightness="+this.GetBrightness();

	this.http_request.SendAjaxRequest(0,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			obj=this.dataobject;
			if(obj && obj.d && (obj.d.File==undefined || obj.d.File!="serviceerror"))
			{
			}
			else alert("Service error in SaveListing function");
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
}

BlueDasherViewer.prototype.SetPhotosFolder= function(numfolder, url)
{
	this.photosfolder_array[this.photosfolder_array.length]=url;
}

BlueDasherViewer.prototype.GetFilename= function(file, quality)
{
	var img=file.split(",");
	var filename="";
	if(this.photosfolder_array.length==0) filename=this.photosfolder;
	else filename=this.photosfolder_array[this.photosfolder_use];
	if(filename.charAt(filename.length-1)!='/') filename+='/';
	filename+="Photos_"+img[0]+"_"+img[1]+"/Photo/";
	filename+=quality+"/IMAGE_"+img[2]+".JPG";
	
	return filename;
}


//-------------------------------------------------------
//	Navigation
//-------------------------------------------------------

//	Notes:
//	They exist 3 types of degree values: DevalVR, API, Facing
//	DevalVR: 0 in the 75% width of the panorama( this is 270 degrees of the image), +90 to the left, -90 to the right
//	API: 0 in the North, -90 to West, +90 to East
//	Facing: Relative to the car, 0 in the moving direction, -90 to look to the left, +90 to look to the right

BlueDasherViewer.prototype.NegPosAngle = function(angle)
{
	angle=angle%360;
	if(angle>180) angle-=360;
	if(angle<-180) angle+=360;
	return angle;
}

BlueDasherViewer.prototype.DifAngle = function(angle1, angle2)
{
	return(Math.abs(this.NegPosAngle(angle1-angle2)));
}

BlueDasherViewer.prototype.DifDirection = function(angle1, angle2)
{
	dif=this.DifAngle(angle1,angle2);
	if(dif>90) dif=180-dif;
	return dif;
}

BlueDasherViewer.prototype.GetAnglePoints = function(centerlat, centerlon, lat, lon)
{
	var angle=0;
	x=lon-centerlon;
	y=lat-centerlat;
	if(x!=0)
	{
		angle=(Math.atan(y/x)*180)/Math.PI;
		if(x<0) angle-=180;
		angle=this.NegPosAngle(90-angle);
	}
	else if(y<0) angle=180;
	return angle;
}

//Get the distance in meters between two lat/long coordinates
BlueDasherViewer.prototype.GetDistancePoints = function(centerlat, centerlon, lat, lon)
{ 
	var radians= Math.PI / 180.0;
	var l=((centerlat+lat)/2)* radians;	//latitude for calculations (approximation to simplify)
	var a=6378.137;		//equatorial radius of Earth in Km
	var b=6356.7523;	//polar radius of Earth in Km
	var n1=a*a*Math.cos(l);
	var n2=b*b*Math.sin(l);
	var d1=a*Math.cos(l);
	var d2=b*Math.sin(l);
	var R = Math.sqrt((n1*n1+n2*n2)/(d1*d1+d2*d2))*1000; // Earth radius
	var dLat = (lat-centerlat)* radians;
	var dLon = (lon-centerlon)* radians; 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(centerlat*radians) * Math.cos(lat*radians) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var distance = R * c;
	
	return distance;
}

BlueDasherViewer.prototype.Rotate = function(direction, nochangefacing)
{
	this.lockdirection=direction;
	this.UpdateInterface("lockview");
	if(nochangefacing==undefined)
	{
		this.facingdirection=direction;
		this.UpdateFacingDirection(1);
	}
}

BlueDasherViewer.prototype.Turn = function(nextdirection)
{
	if(nextdirection!=180)
	{
		this.nextdirection=nextdirection;
		this.UpdateInterface("turn");
		this.UpdateExternalMap("turn");
	}
	else
	{
		this.Stop();
		this.Turn(0);
		this.CalculateMovingDirection(1);
		this.movingdirection=(this.movingdirection+180)%360;
		this.facingdirection=this.lockdirection;
		this.UpdateFacingDirection(1);
		this.UpdateInitialFacingDirection(1);
	}
}

//Converts API angle value to viewer value or viceversa
BlueDasherViewer.prototype.ConvertRotation= function(angle)
{
	angle=90-angle+this.GetValue("Yaw");
	while(angle>180) angle-=360;
	while(angle<-180) angle+=360;
	return angle;
}

//Get where the plugin must look in current point (API degrees)
BlueDasherViewer.prototype.GetNextFacingDirection= function(ismoving)
{
	var facing=0;
	if(this.isrouting && this.routefacingtoend)
	{
		facing=this.GetAnglePoints(this.GetValue("Y"),this.GetValue("X"),this.routetopoint.lat,this.routetopoint.lon);
	}
	else facing=this.facingdirection;
	if(ismoving && this.routefacingtoend==0) 
		facing+=this.movingdirection+this.nextfacingdirection;
	return facing;
}

//Get where the viewer is looking now (API degrees)
BlueDasherViewer.prototype.GetFacingDirection= function()
{
	var direction=0;
	if(this.pluginused==1 && this.pluginobj)
		direction=this.ConvertRotation(this.pluginobj.rotationy);

	return direction;
}

//Calculate current moving direction closer to where the viewer is looking (API degrees)
BlueDasherViewer.prototype.CalculateMovingDirection= function(ismoving)
{
	if(ismoving) lockdirection=this.lockdirection;
	else lockdirection=0;
	
	if(this.navmode==0)
	{
		if(this.DifAngle(this.GetFacingDirection(),this.movingdirection+lockdirection)>90)
			this.movingdirection=(this.movingdirection+180)%360;
	}
	else if(this.navmode==1)
	{
		this.movingdirection=this.GetValue("Direction");
	}
}

//Calculates current facing direction to prepare the camera for the next point (Facing degrees)
BlueDasherViewer.prototype.CalculateFacingDirection= function(ismoving)
{
	if(ismoving) this.facingdirection=this.lockdirection;
	else this.facingdirection=this.NegPosAngle(this.GetFacingDirection()-this.movingdirection);
}

//Update the current facing direction in the plugin
BlueDasherViewer.prototype.UpdateFacingDirection= function(ismoving)
{
	if(this.IsPluginLoaded("UpdateFacingDirection("+ismoving+")",1000))
	{
		if(this.ismoving) 
		{
			this.UpdateInitialFacingDirection(ismoving);
		}
		else 
		{
			if(this.pluginused==1)
			{
				var focusangle=this.GetNextFacingDirection(ismoving);
				var direction=this.ConvertRotation(focusangle);
				var pitch=this.GetValue("Pitch");
				this.pluginobj.Command("rotcamera",0,direction,pitch);
			}
		}
	}
}

//Update the facing direction in the panorama loaded in the plugin
BlueDasherViewer.prototype.UpdateInitialFacingDirection= function(ismoving)
{
	if(this.IsPluginLoaded("UpdateInitialFacingDirection("+ismoving+")",1000))
	{
		if(this.pluginused==1)
		{
			var direction=this.ConvertRotation(this.GetNextFacingDirection(ismoving));
			var pitch=this.GetValue("Pitch");
			var code='InitialCameraRotation("'+this.latestfile+'",0,'+direction+','+this.zoomdefault+','+pitch+');';
			this.pluginobj.Commands('runcode',code);
		}
	}
}

//Returns the next vector to load in the next intersection
BlueDasherViewer.prototype.GetNextVector= function(vector, movingdirection, nextdirection)
{
	var dif=360;
	var nextvector=null;
	var nextvector2=null;
	var nextdir=0;
	var fromto="From";
	var index=-1;
	var numbrothers=0;
	var num=0,x,y,distance,vectordir;
	this.nextvectorlevel++;
	
	this.searchingnextvector=0;
	this.routefacingtoend=0;
	if(this.isrouting==1)
	{
		for(n=0;n<this.routevectors.length;n++)
		{
			if(this.currentvector.ID==this.routevectors[n].ID)
			{
				if(n<this.routevectors.length-1)
				{
					do{
						n++;
					}while(n<this.routevectors.length-1 && this.routevectors[n].Pictures.length<2);
					return this.routevectors[n];
				}
				else
				{
					this.routefacingtoend=1;
					return null;
				}
			}
		}
	}

	if(vector==null) return null;

	if(this.enablepointdircalc==0) vectordir=vector.Direction;
	else vectordir=this.GetAnglePoints(vector.FromY,vector.FromX,vector.ToY,vector.ToX);
	if(this.DifAngle(movingdirection,vectordir)<90) fromto="To";	//ToVectors

	num=this.GetVectorValue(vector,"num"+fromto);
	numbrothers=num;
	extremelon=vector[fromto+"X"];
	extremelat=vector[fromto+"Y"];
	for(n=0;n<num;n++)
	{
		if(vector[fromto+"Vectors"][n])
		{
			this.GetVectorValue(vector,fromto+"Vectors",n,"setNumBrothers",numbrothers);
			nextdir=this.CalculateNextDirection(vector,fromto,n,extremelon,extremelat);
			angle=this.DifAngle(nextdir,nextdirection);
			if(angle<dif)
			{
				dif=angle;
				index=n;
				nextvector=vector[fromto+"Vectors"][n];
			}
		}
	}
	if(nextvector && this.debugnextvector!=nextvector.ID)
	{
		this.Dbg("next",nextvector);
		this.debugnextvector=nextvector.ID;
	}

	if(nextvector && (nextvector.ToVectors!=null || nextvector.FromVectors!=null) && nextvector.Pictures.length<=1)
	{
		if(this.nextvectorlevel<4) 
		{
			this.Dbg("next0",nextvector,this.nextvectorlevel);
			nextvector2=this.GetNextVector(nextvector,nextvector.NextDirection,nextdirection);
		}
		else 
		{
			this.Dbg("nextend",nextvector,this.nextvectorlevel);
			nextvector2=null;
		}
		
		if(nextvector2) this.searchingnextvector=1;
		if(this.nextvectorlevel==1 && nextvector2==null) 
			vector[fromto+"Vectors"][index]=null;
		nextvector=nextvector2;
	}
	this.nextvectorlevel--;
	return nextvector;
}

BlueDasherViewer.prototype.CalculateNextDirection= function(vector,fromto,n,extremelon,extremelat)
{
	var x,y,lon,lat,lon2,lat2,distFrom,distTo;
	var nextdir;

	if(this.GetVectorValue(vector,fromto+"Vectors",n,"NextSide")==undefined)
	{
		lon=this.GetVectorValue(vector,fromto+"Vectors",n,"FromX");
		lat=this.GetVectorValue(vector,fromto+"Vectors",n,"FromY");
		lon2=this.GetVectorValue(vector,fromto+"Vectors",n,"ToX");
		lat2=this.GetVectorValue(vector,fromto+"Vectors",n,"ToY");
		x=lon-extremelon;
		y=lat-extremelat;
		distFrom=x*x+y*y;
		x=lon2-extremelon;
		y=lat2-extremelat;
		distTo=x*x+y*y;
		if(distFrom<distTo)
		{
			lon=lon2;
			lat=lat2;
			this.GetVectorValue(vector,fromto+"Vectors",n,"setNextSide",1);
		}
		else this.GetVectorValue(vector,fromto+"Vectors",n,"setNextSide",2);
		
		nextdir=this.GetAnglePoints(extremelat,extremelon,lat,lon);
		this.GetVectorValue(vector,fromto+"Vectors",n,"setNextDirection",nextdir);
	}
	else nextdir=this.GetVectorValue(vector,fromto+"Vectors",n,"NextDirection");
	
	return nextdir;
}

BlueDasherViewer.prototype.SetTurnMode= function(mode)
{
	this.turndirectionmode=mode;
}

BlueDasherViewer.prototype.SetNextVector= function(nextvector,direction)
{
	var olddirection=0;
	
	if(nextvector)
	{
		olddirection=this.GetValue("Direction")+direction;

		delete this.currentvector;
		this.currentvector=nextvector;
		this.Dbg("setvec",nextvector);
		
		this.movingdirection=this.GetValue("Direction")+direction;
		if(this.currentvector.NextSide==1) this.numcurrentpoint=0;
		else 
		{
			this.numcurrentpoint=this.GetValue("numpictures")-1;
			this.movingdirection=(this.movingdirection+180)%360;
		}
		this.numcachepoint=this.numcurrentpoint;
		if(this.currentvector.NumBrothers>1 && this.DifDirection(this.movingdirection,olddirection)>20)	//A turn was made
		{
			this.Turn(0);
		}
	}
}

BlueDasherViewer.prototype.StepForward= function()
{
	this.Stop();
	this.CalculateMovingDirection(0);
	this.CalculateFacingDirection(0);
	this.Step(0);
}

BlueDasherViewer.prototype.StepBackward= function()
{
	this.Stop();
	this.CalculateMovingDirection(0);
	this.CalculateFacingDirection(0);
	this.Step(180);
}

BlueDasherViewer.prototype.Step= function(direction)
{
	var numpictures=this.GetValue("numpictures");
	var vectordir=this.GetValue("Direction");
	var turnsteps=6;
	var nextvector=null;
	var vectorcargando=0;
	var setvector=0,vectordir;
	var addcache=0,increm=1,tonumpoint=numpictures-1;
	var numgear=1,file,prevfile;
	
	if(this.ismoving) numgear=this.numgear;
	this.loadingframe=0;
	this.nextfacingdirection=0;
	this.nextmovingdirection=0;

	if(this.navmode==0)
	{
		if(this.currentvector==null)
		{
			this.Stop();
			return;
		}
		nextvector=this.GetNextVector(this.currentvector,this.movingdirection+direction,this.movingdirection+direction+this.nextdirection);
		if(nextvector)
		{
			if(this.enablepointdircalc==0) vectordir=nextvector.Direction;
			else vectordir=this.GetAnglePoints(nextvector.FromY,nextvector.FromX,nextvector.ToY,nextvector.ToX);
			this.nextmovingdirection=vectordir;
			if(nextvector.NextSide==2) this.nextmovingdirection+=180;
			if(nextvector.FromVectors==null && nextvector.ToVectors==null)
			{
				if(this.http_request.isrequesting==0)
					this.LoadVector(nextvector.ID,this.GetValue("Map"));
				nextvector=null;
				vectorcargando=1;
			}
		}
		if(this.DifAngle(this.movingdirection+direction,vectordir)>90)
		{
			increm=-1;
			tonumpoint=0;
		}
	}
	else if(this.navmode==1)
	{
		if(direction==180)
		{
			increm=-1;
			tonumpoint=0;
		}
	}

	prevfile=this.GetValue("File");
	do{
		if(this.numcurrentpoint!=tonumpoint)
		{
			if((this.numcachepoint-this.numcurrentpoint)*increm<0) this.numcachepoint=this.numcurrentpoint;
			var antnumcachepoint=this.numcachepoint;
			
			while(Math.abs(this.numcachepoint-this.numcurrentpoint)<=this.preloadingcachemax*numgear && addcache<2)
			{
				if((this.numcachepoint+increm)%numgear==0)
				{
					this.PreloadPicture(nextvector,increm);
					addcache++;
				}
				else this.numcachepoint+=increm;
			}
	
			if(this.preloadingcacheenabled)
			{
				this.preloadingcachenum=this.GetPreloadedFrames();
				if(this.preloadingcachenum!=-1)
				{
					var preloadingcache=this.preloadingcachestate;
					if(this.preloadingcachestate)
					{
						if(this.preloadingcachenum==-1 || this.preloadingcachenum>=this.preloadingcachemax || antnumcachepoint==this.numcachepoint) this.preloadingcachestate=0; 
					}
					else
					{
						if(this.preloadingcachenum<=1) this.preloadingcachestate=1;
					}
					if(preloadingcache!=this.preloadingcachestate || this.preloadingcacheshowbar)
						this.ShowPluginCache(1,this.preloadingcachestate,this.preloadingcachenum/this.preloadingcachemax);
				}
				else this.preloadingcacheenabled=0;
			}
			if(this.preloadingcachestate==0 || this.preloadingcacheenabled==0)
			{
				this.numcurrentpoint+=increm;
				if(this.CheckEndRouting())
				{
					this.numcurrentpoint-=increm;
					return;
				}
				file=this.GetValue("File");
				if((this.numcurrentpoint%numgear)==0 && file!=prevfile)
				{
					if(this.ismoving && this.routefacingtoend==0)
					{
						if(this.navmode==0 && nextvector)
						{
							if(this.turndirectionmode==1)
							{
								var numstep=Math.abs(tonumpoint-this.numcurrentpoint);
								if(numstep<turnsteps)
								{
									dir=this.NegPosAngle(this.nextmovingdirection-this.movingdirection)/turnsteps;
									this.nextfacingdirection=dir*(turnsteps-numstep);
								}
							}
						}
						else if(this.navmode==1)
						{
							this.CalculateMovingDirection(1);
						}
					}
					this.LoadPicture();
				}
			}
		}
		else setvector=1;
	}while(setvector==0 && this.loadingframe==0 && this.preloadingcacheenabled==0)
				
	if(setvector)
	{	
		if(this.navmode==0)
		{
			if(nextvector)
			{			
				if(this.turndirectionmode==2 && this.pluginobj)
				{
					var tilt=this.pluginobj.rotationx;
					var pitch=this.GetValue("Pitch");
					this.pluginobj.Command("rotcamera",tilt,this.ConvertRotation(this.nextmovingdirection),pitch);
				}
				this.SetNextVector(nextvector,direction);
				if((this.numcurrentpoint%numgear)==0) this.LoadPicture();
			}
			else if(vectorcargando==0 && this.searchingnextvector==0)
			{
				setTimeout(this.objectname+".Stop()",500);
				this.ShowMessage("No more photos ahead");
				return;
			}
		}
		else if(this.navmode==1 && this.numcurrentpoint>0 && this.numcurrentstop<this.allstops.length-1)
		{
			this.numcurrentstop++;
			this.numcurrentpoint=0;
			this.numcachepoint=0;
			this.LoadStop(this.numcurrentstop);
		}
	}
	if(this.loadingframe)
	{
		if(this.ismoving)
		{
			this.numimagesnavleft--;
			if(this.numimagesnavleft<=0) 
			{
				this.Stop();
				this.ShowMessage(this.messagenavmax);
			}
		}
	}
	else
	{
		setTimeout(this.objectname+".Step("+direction+")",500);
	}
}

BlueDasherViewer.prototype.SetGear= function(numgear)
{
	this.numgear=numgear;
	this.UpdateInterface("gear");
}

BlueDasherViewer.prototype.SetNavigationMode= function(mode)
{
	if(mode=="vectors")
	{
		this.navmode=0;
	}
	else if(mode=="stops")
	{
		this.navmode=1;
		this.LoadAllStops();
	}
}

BlueDasherViewer.prototype.CheckEndRouting= function()
{
	var ret=0;
	if(this.isrouting && this.routefacingtoend)
	{
		var x=this.routetopoint.lon-this.GetValue("X");
		var y=this.routetopoint.lat-this.GetValue("Y");
		var distance=x*x+y*y;
		if(distance>this.routedistancetoend)
		{
			this.Stop();
			ret=1;
		}
		else this.routedistancetoend=distance;
	}
	return ret;
}

BlueDasherViewer.prototype.PreloadPicture= function(nextvector,increm)
{
	var numpicturesnext,numpointnext,numpoint,numpictures=this.GetValue("numpictures");
	var point=null;
	var file="",prevfile="";
	
	numpoint=this.numcachepoint;
	do{
		point=null;
		if(numpoint>=0 && numpoint<numpictures)
		{
			if(this.navmode==0) point=this.currentvector.Pictures[numpoint];
			else if(this.navmode==1) point=this.currentstoppoints[numpoint];
		}
		else if(nextvector)
		{
			if(numpoint<0) numpointnext=-(numpoint+1);
			else numpointnext-=numpictures;
			numpicturesnext=nextvector.Pictures.length;
			if(nextvector.NextSide==2)
				numpointnext=numpicturesnext-1-numpointnext;
			if(numpointnext>=0 && numpointnext<numpicturesnext)
			{
				point=nextvector.Pictures[numpointnext];
			}	
		}
		if(point){
			if(prevfile=="") prevfile=file=point.File;
			else file=point.File;
			if(file==prevfile) numpoint+=increm;
		}
	}while(point!=null && file==prevfile);

	if(point)
	{
		var yaw;
		if(this.enablepointdircalc) yaw=this.GetValue("Yaw");
		else yaw=point.Yaw;
		this.LoadPicture(point.File,1,point.Y,point.X,yaw);
		this.numcachepoint=numpoint;
	}
}

BlueDasherViewer.prototype.GoForward= function()
{
	var n,routing=0;
	if(this.isrouting==0 && this.extmap && this.routevectors.length>0 && this.currentvector)
	{
		var refcheck=document.getElementById(this.extmap.divname+"_routeShowRoute");
		if(refcheck && refcheck.checked)
		{
			for(n=0;n<this.routevectors.length;n++){
				if(this.currentvector.ID==this.routevectors[n].ID){
					routing=1;
					break;
				}
			}
		}
	}
	if(routing) this.DriveRoute();
	else{
		this.CalculateMovingDirection(1);
		this.CalculateFacingDirection(1);
		this.UpdateFacingDirection(1);
		this.ismoving=1;
		this.numimagesnavleft=this.numimagesnavmax;
		this.UpdateInterface("updatego,hideclickdrag");
		this.UpdateMessages("hidemessage");
		this.Step(0);
	}
}

BlueDasherViewer.prototype.Stop= function()
{
	if(this.isrouting && this.extmap)
	{
		var ref=document.getElementById(this.extmap.divname+"_routeDrive");
		if(ref) ref.value="Drive Route";
	}
	this.numcachepoint=this.numcurrentpoint;
	this.ismoving=0;
	this.isrouting=0;
	this.UpdateInterface("updatego,showclickdrag");
}

BlueDasherViewer.prototype.SetNavigationLimit= function(numimages, message)
{
	this.numimagesnavmax=numimages;
	if(message!=undefined && message!="")
		this.messagenavmax=message;
}

//-------------------------------------------------------
//	Viewer functions
//-------------------------------------------------------

BlueDasherViewer.prototype.DoDVLCommands=function(command, data)		//Receive DevalVR events
{
//	alert(command+"="+data);
	if(command!="panevent" && (command!="panorama" || this.ismoving==0))
		this.Dbg("plugevent",command,data);
	if(command=="event")
	{
		if(data=="EVENT_FULLTOGGLE")
		{
			if(this.buttonstates[10]) this.FullScreen();
		}
		else if(data=="EVENT_GO") 
		{
			if(this.buttonstates[0]) this.GoForward();
		}
		else if(data=="EVENT_STOP")
		{
			if(this.buttonstates[1]) this.Stop();
		}
		else if(data=="EVENT_STEPFORWARD")
		{
			if(this.buttonstates[2]) this.StepForward();
		}
		else if(data=="EVENT_STEPBACKWARD")
		{
			if(this.buttonstates[3]) this.StepBackward();
		}
		else if(data=="BRIGHTNESS")
		{
			if(this.buttonstates[11])
			{
				var light=this.lightlevel;
				light=(light+1)%6;
				this.SetBrightness(light);
			}
		}
		else if(data=="GO_FORWARD")	this.Turn(0);
		else if(data=="GO_LEFT") 
		{
			if(this.buttonstates[4]) this.Turn(-90);
		}
		else if(data=="GO_RIGHT") 
		{
			if(this.buttonstates[5]) this.Turn(90);
		}
		else if(data=="EVENT_UTURN")
		{		
			if(this.buttonstates[6]) this.Turn(180);
		}
		else if(data=="AUTOPAN_ON")
		{		
			if(this.buttonstates[12]) this.SetAutopan(1);
		}
		else if(data=="AUTOPAN_OFF") 
		{
			if(this.buttonstates[12]) this.SetAutopan(0);
		}
		else if(data=="DISTANCE_ON")
		{		
			this.EnableDistanceMeasure(1);
		}
		else if(data=="DISTANCE_OFF") 
		{
			this.EnableDistanceMeasure(0);
		}
		else if(data=="SHOWINTERNALMAP")
		{
			if(this.buttonstates[13]) this.ShowInternalMap();
		}
		else if(data=="HIDEINTERNALMAP") 
		{
			if(this.buttonstates[13]) this.HideInternalMap();
		}
		else if(data=="MAP_ZOOMIN") this.UpdateInterface("zoominmap");
		else if(data=="MAP_ZOOMOUT") this.UpdateInterface("zoomoutmap");
		else if(data.indexOf("streetevent")!=-1)
		{
			var value= data.split(",");
			alert(value[1]);
		}
		else if(data.indexOf("markerevent")!=-1)
		{
			var value= data.split(",");
			if(this.OnMarkerEvent && typeof(this.OnMarkerEvent)=="function")
				this.OnMarkerEvent(value[1]);
		}
		else if(data.indexOf("EVENT_OPTIONBUTTON")!=-1)
		{
			var value= data.split(",");
			var numoption=parseInt(value[1]);
			
			if(numoption>=0 && numoption<4)
			{
				var action=this.buttonaction[numoption];
				if(action=="snapshot" && this.IsInterfaceLoaded())
				{
					this.ShowInterface(0);
					setTimeout(this.objectname+".SaveSnapshot(1)",500);
				}
				else if(action=="hidesigns")
				{
				}
				else if(action.indexOf("http://")!=-1 && this.IsPluginLoaded())
				{
					this.pluginobj.Commands('runcode','OpenURL("'+action+'","_blank");');
				}
			}
		}
		else if(data=="EVENT_SNAPSHOT")
		{
			setTimeout(this.objectname+".ShowInterface(1)",1000);
		}
		else if(data.indexOf("EVENT_GEAR")!=-1)
		{
			var value=data.split(",");
			this.SetGear(parseInt(value[1]));
		}
		else if(data.indexOf("EVENT_LOCKVIEW")!=-1)
		{
			if(this.buttonstates[7])
			{
				var value=data.split(",");
				this.Rotate(parseFloat(value[1]))
			}
		}
		else if(data=="EVENT_PREVREST" || data=="EVENT_NEXTREST")
		{
			if(this.navmode==1)
			{
				var incremstop=-2;
				if(data=="EVENT_PREVREST" && this.numcurrentstop==0) incremstop=0;
				else if(data=="EVENT_PREVREST" && this.numcurrentstop>0) incremstop=-1;
				else if(data=="EVENT_NEXTREST" && this.numcurrentstop<this.allstops.length-1) incremstop=1;
				else if(data=="EVENT_NEXTREST" && this.numcurrentstop==this.allstops.length-1) incremstop=2;
				if(incremstop!=-2)
				{
					this.Stop();
					if(incremstop==0) this.numcurrentpoint=0;
					else if(incremstop==2) this.numcurrentpoint=this.currentstoppoints.length-1;
					else 
					{
						this.numcurrentstop+=incremstop;
						this.numcurrentpoint=0;
					}
					this.numcachepoint=this.numcurrentpoint;
					this.UpdateInterface("hideclickdrag,numstop");
					this.UpdateMessages("showwaiting,hidemessage");
					if(incremstop==0) this.LoadPicture();
					else this.LoadStop(this.numcurrentstop);
				}
			}
		}
		else if(data=="EVENT_TOPLEFTBANNER")
		{
			if(this.topleftbannerurl!="" && this.pluginobj) 
				this.pluginobj.Commands('runcode','OpenURL("'+this.topleftbannerurl+'","_blank");');
		}
		else if(data=="EVENT_TOPRIGHTBANNER")
		{
			if(this.toprightbannerurl!="" && this.pluginobj) 
				this.pluginobj.Commands('runcode','OpenURL("'+this.toprightbannerurl+'","_blank");');
		}
		else if(data=="EVENT_BOTTOMLEFTBANNER")
		{
			if(this.bottomleftbannerurl!="" && this.pluginobj) 
				this.pluginobj.Commands('runcode','OpenURL("'+this.bottomleftbannerurl+'","_blank");');
		}
		else if(data=="EVENT_BOTTOMRIGHTBANNER")
		{
			if(this.bottomrightbannerurl!="" && this.pluginobj) 
				this.pluginobj.Commands('runcode','OpenURL("'+this.bottomrightbannerurl+'","_blank");');
		}
		else if(data=="_clickevent_")
		{
			var rotx=this.pluginobj.Commands('getvalue','mousetilt');
			if(rotx<0)
			{
				var radians= Math.PI / 180.0;
				var roty=this.ConvertRotation(this.pluginobj.Commands('getvalue','mousepan'));
				var dist=this.carcameraheight / Math.tan(-rotx*radians);
				var disty= dist * Math.sin((90+roty)*radians);
				var distx= dist * Math.cos((90+roty)*radians);
				
				var lat=this.GetValue("Y");
				var lon=this.GetValue("X");
				var l= lat* radians;	//latitude for calculations
				var a=6378.137;			//equatorial radius of Earth in Km
				var b=6356.7523;		//polar radius of Earth in Km
				var n1=a*a*Math.cos(l);
				var n2=b*b*Math.sin(l);
				var d1=a*Math.cos(l);
				var d2=b*Math.sin(l);
				var R = Math.sqrt((n1*n1+n2*n2)/(d1*d1+d2*d2))*1000; // Earth radius
				
				var dLat = Math.asin(disty/R)*180/ Math.PI;
				var dLon = Math.acos(distx/R)*180/ Math.PI; 

				var lat2=lat+dLat;
				var lon2=lon+dLon-90;
				
				if(this.OnViewerClickEvent && typeof(this.OnViewerClickEvent)=="function")
					this.OnViewerClickEvent(lat2,lon2);
					
				if(this.distancemeasurestate==1)
				{
					var distance=0;
					this.AddAnchor("distpoint"+this.distanceindex,lat2,lon2,this.mainfolder+"images/pointmarkericon.png",this.mainfolder+"images/pointmarker.png");
					if(this.distanceindex==0)
					{
						this.AddAnchor("distpoint1",lat2,lon2,this.mainfolder+"images/pointmarkericon.png",this.mainfolder+"images/pointmarker.png");
						this.pluginobj.Commands('runcode','ObjectValue("","BDT_TEXT_DISTANCEMEASURE","","description","Distance: \nClick in the image to select the second point...");');
						this.ShowAnchors(1);
					}
					this.distancelat[this.distanceindex]=lat2;
					this.distancelon[this.distanceindex]=lon2;
					this.distanceindex++;
					if(this.distanceindex==2)
					{
						distance=this.GetDistancePoints(this.distancelat[0],this.distancelon[0],this.distancelat[1],this.distancelon[1]);
						this.distanceindex=0;
						this.pluginobj.Commands('runcode','ObjectValue("","BDT_TEXT_DISTANCEMEASURE","","description","Distance: '+distance.toFixed(2)+' meters\nClick in the image to select the first point...");');
					}
				}
			}
		}
	}
	else if(command=="panorama" && data!="startphoto")
	{
		if(this.picturetimeout) clearTimeout(this.picturetimeout);
	
		var updateinterface="updateposmap,car,turn,street,numstop";
		if(this.ismoving==0 && this.latestfile!="nophoto")
		{
			if(this.extmap && this.extmap.zoomlevel<14) this.ZoomMap(17,1);
			if(this.setzoompoints && this.extmap.shapeflag)
			{
				this.ZoomMapPoints(this.extmap.shapeflag.Lat,this.extmap.shapeflag.Lon,this.GetValue("Y"),this.GetValue("X"));
				this.setzoompoints=0;
			}

			updateinterface+=",showclickdrag";
			this.CalculateMovingDirection(0);
			this.SendEvent(this.OnPictureLoaded);
		}
		if(this.latestfile!="nophoto")
			this.UpdateMessages("hidewaiting,hidesplash");
		this.UpdateInterface(updateinterface);
		this.UpdateExternalMap("updateposmap,car,turn");

		this.photosfolder_attemps=0;
		this.photosfolder_attemphigh=0;
		if(this.ismoving==1)
		{	
			this.Step(0);
		}
	}
	else if(command=="panevent")
	{
		var carangleant=this.movingdirection+this.nextfacingdirection;
		if(this.ismoving==0)
		{
			this.CalculateMovingDirection(0);
			if(this.messageenabled>0)
			{
				this.messageenabled--;
				if(this.messageenabled==0) 
				this.UpdateMessages("hidemessage");
			}
			this.UpdateInterface("car,stepcompass");
			this.UpdateExternalMap("car");
		}
		var carangle=this.movingdirection+this.nextfacingdirection;
		angle=this.GetFacingDirection()-carangle;
		if(this.extmap) this.RotateFocusMap(angle);
		if(this.wasmapdragged && this.pluginobj)
		{
			this.pluginobj.Commands("javascript:","imageMap,RotateFocus("+angle+")");
			if(carangleant!=carangle)
			{
				this.pluginobj.Commands("javascript:","imageMap,RotateCar("+carangle+")");
			}
		}
	}
	else if(command=="eventsMap")
	{
		if(this.pluginobj)
		{
			var value= data.split(",");
			if(value[0]=="drag")
			{
				if(this.wasmapdragged==0)
				{
					var carangle=this.movingdirection+this.nextfacingdirection;
					this.pluginobj.Commands('runcode','Show("","imagecarMap",0);Show("","imagefocusMap",0);Show("","leftblinkerMap",0);Show("","rightblinkerMap",0);');
					this.pluginobj.Commands("javascript:","imageMap,CreateCenteredCar("+carangle+","+(this.GetFacingDirection()-carangle)+")");
					this.wasmapdragged=1;
				}
				this.pluginobj.Commands("javascript:","imageMap,PanMap("+parseInt(value[1])+","+parseInt(value[2])+")");
			}
			else if(value[0]=="click")
			{
				lat=this.pluginobj.Commands("javascript:","imageMap,GetLatPixel("+value[1]+","+value[2]+")");
				lon=this.pluginobj.Commands("javascript:","imageMap,GetLongPixel("+value[1]+","+value[2]+")");
				this.EventMapClick(lat,lon);
			}
			else if(value[0]=="doubleclick")
			{
				lat=this.pluginobj.Commands("javascript:","imageMap,GetLatPixel("+value[1]+","+value[2]+")");
				lon=this.pluginobj.Commands("javascript:","imageMap,GetLongPixel("+value[1]+","+value[2]+")");
				this.EventMapDoubleClick(lat,lon);
			}
			else if(value[0]=="mousewheelin")
			{
				this.UpdateInterface("zoominmap");
			}
			else if(value[0]=="mousewheelout")
			{
				this.UpdateInterface("zoomoutmap");
			}
		}
	}
	else if(command=="filenotfound") //404
	{
		if(this.picturetimeout) clearTimeout(this.picturetimeout);
		
		if(this.photosfolder_searchhigh){
			if(data.indexOf("/MEDIUM/")!=-1) this.photosfolder_attemphigh=0;
			else this.photosfolder_attemphigh=1;
			if(this.photosfolder_attemphigh) this.photosfolder_attemps++;
		}
		else this.photosfolder_attemps++;
			
		if(this.photosfolder_attemps<this.photosfolder_array.length)
		{
			if(this.photosfolder_searchhigh==0 || this.photosfolder_attemphigh)
				this.photosfolder_use=(this.photosfolder_use+1)%this.photosfolder_array.length;
			if(this.photosfolder_searchhigh)
				this.photosfolder_attemphigh=1-this.photosfolder_attemphigh;
			this.LoadPicture(this.latestpicture);
		}
		else
		{
			this.photosfolder_attemps=0;
			this.photosfolder_attemphigh=0;
			if(this.ismoving==0)
			{
				var message="The image you need is not available in our system.[br]We are working to solve this issue.[br]Sorry for the inconvenience.";
				this.latestfile="nophoto";
				this.DoDVLCommands('panorama',"nophoto");
				this.ShowSplash();
				this.ShowMessage(message);
			}
			else this.DoDVLCommands('panorama',data);
		}
	}
}

BlueDasherViewer.prototype.ResetViewer= function()
{
	this.Stop();
	this.Turn(0);
	this.SetBrightness(0);
	this.Rotate(0,1);
	this.nextfacingdirection=0;
}

BlueDasherViewer.prototype.FullScreen= function()
{
	if(this.pluginused==1 && this.IsPluginLoaded("FullScreen()",1000))
	{
		this.pluginobj.Commands("runcode","ToolCommand(3);");
	}
}

BlueDasherViewer.prototype.SetAutopan= function(value)
{
	if(this.IsInterfaceLoaded("SetAutopan("+value+")",1000))
	{
		if(this.autopanstate!=value && (value==0 || this.ismoving==0))
		{	
			this.pluginobj.Commands("runcode","ToolCommand(5);");
			this.autopanstate=1-this.autopanstate;
			this.UpdateInterface("autopan");
		}
	}
}

BlueDasherViewer.prototype.EnableDistanceMeasure= function(value)
{
	if(this.IsInterfaceLoaded("EnableDistanceMeasure("+value+")",1000))
	{
		if(this.distancemeasurestate!=value && (value==0 || this.ismoving==0))
		{	
			if(value)
			{
				this.pluginobj.Commands('runcode','ObjectValue("","BDT_TEXT_DISTANCEMEASURE","","description","Distance: \nClick in the image to select the first point...");Fade("","BDT_TEXT_DISTANCEMEASURE",100,0.5);');
				this.distancelat=new Array();
				this.distancelon=new Array();
				this.distanceindex=0;
				this.pluginobj.Commands("enableclickevent","1");
			}
			else{
				this.pluginobj.Commands("enableclickevent",""+this.clickevent);
				this.ShowAnchors(0);
			}
			this.distancemeasurestate=value;
			this.UpdateInterface("distancemeasure");
		}
	}
}

BlueDasherViewer.prototype.GetBrightness= function()
{
	return(this.lightlevel);
}

BlueDasherViewer.prototype.SetBrightness= function(level)
{
	if(this.pluginused==1 && this.IsPluginLoaded("SetBrightness("+level+")",1000))
	{
		if(level<0) level=0;
		if(level>5) level=5;
		this.lightlevel=level;
		this.pluginobj.Commands("light",""+level);
		this.UpdateInterface("brightness");
	}
}

BlueDasherViewer.prototype.SetFovMode= function(mode)
{
	if(this.pluginused==1 && this.IsPluginLoaded("SetFovMode("+mode+")",1000))
	{
		this.pluginobj.Commands("fovmode",mode);
	}
}

BlueDasherViewer.prototype.SetFacingDirection= function(angle)
{
	if(this.ismoving==0)
	{
		this.facingdirection=angle;
		this.UpdateFacingDirection(0);
	}
}

BlueDasherViewer.prototype.GetZoomCamera= function()
{
	var angle=0;
	if(this.pluginobj && this.ismoving==0)
		angle=this.pluginobj.zoom;
	return angle;
}

BlueDasherViewer.prototype.GetTiltCamera= function()
{
	var angle=0;
	if(this.pluginobj && this.ismoving==0)
		angle=this.pluginobj.rotationx;
	return angle;
}

BlueDasherViewer.prototype.GetPreloadedFrames= function()
{
	var numpreloaded=-1;
	if(this.pluginobj && this.pluginobj.pluginversion>=0x07070E)
		numpreloaded=this.pluginobj.Commands("preloadedframes","");
	return numpreloaded;
}

BlueDasherViewer.prototype.SetTiltCamera= function(angle)
{
	if(this.pluginobj)// && this.ismoving==0)
	{
		var pitch=this.GetValue("Pitch");
		var direction=this.pluginobj.rotationy;
		this.pluginobj.Command("rotcamera",angle,direction,pitch);
	}
}

BlueDasherViewer.prototype.SetZoom= function(zoom)
{
	if(this.pluginobj && this.ismoving==0)
	{
		this.pluginobj.Command("zoomcamera",zoom,0,0);
	}
}

BlueDasherViewer.prototype.CallJavascript= function(code)
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("CallJavascript('"+code+"')",1000))
	{
		if(this.pluginobj.Commands("getobjectvalue2Dx","BDT_BUTTON_MAPVIEW0")!=0)
		{
			if(this.pluginobj.Commands("javascript:",code)==0)
				setTimeout(this.objectname+".CallJavascript('"+code+"')",1000);
		}
	}
}

BlueDasherViewer.prototype.UpdateInterface= function(action)
{
	var code="";
	var alpha;

	if(this.IsInterfaceLoaded("UpdateInterface('"+action+"')",1000))
	{
		if(action=="all" || action.indexOf("street")!=-1)
		{
			var name=this.GetValue("Street");
			if(name!="0")
			{
				code+='ObjectValue("","text1","","description","'+name+'");';
			}
		}
		if(action=="all" || action.indexOf("textcompass")!=-1)
		{
			var textdir=Array("N","NE","E","SE","S","SW","W","NW","N");
			var angle=this.NegPosAngle(this.movingdirection+this.nextfacingdirection);
			if(angle<0) angle+=360;
			angle=parseInt((angle+33.75)/45);
			code+='ObjectValue("","textcompass","","description","'+textdir[angle]+'");';
		}
		if(action=="all" || action.indexOf("numstop")!=-1)
		{
			if(this.navmode==1 && this.allstops)
			{
				if(this.numcurrentstop<this.allstops.length-1)
				{
					var name=this.allstops[this.numcurrentstop+1].Name;
					if(name.length>11)
					{
						name=name.substr(0,9);
						name+="...";
					}
				}
				else name="End";
				code+='ObjectValue("","textstopnum","","description","'+(this.allstops[this.numcurrentstop].NextStop)+'");';
				code+='ObjectValue("","textstopname","","description","'+(name)+'");';
				if(this.extmap)
				{
					if(this.allstops[this.numcurrentstop].Bound=="S") 
					{
						this.ChangeButtonState("day1",1);
						this.ChangeButtonState("day2",0);
					}
					else
					{
						this.ChangeButtonState("day2",1);
						this.ChangeButtonState("day1",0);
					}
				}
			}
		}
		if(action=="all" || action.indexOf("car")!=-1)
		{
			var carangle=this.movingdirection+this.nextfacingdirection;
			code+='ObjectValue("","imagecarMap","","rotation",'+carangle+');';
			code+='ObjectValue("","leftblinkerMap","","rotation",'+carangle+');';
			code+='ObjectValue("","rightblinkerMap","","rotation",'+carangle+');';
		}
		if(action=="all" || action.indexOf("turn")!=-1)
		{
			code+='Show("","",0,"timersignal");Show("","",0,"rightsignal");Show("","",0,"leftsignal");';
			code+='Show("","leftblinkerMap",0);Show("","rightblinkerMap",0);';
			code+='Fade("","BDT_BUTTON_LEFT",'+(20+this.buttonstates[4]*80)+',0.1);';
			code+='Fade("","BDT_BUTTON_RIGHT",'+(20+this.buttonstates[5]*80)+',0.1);';

			if(this.nextdirection==-90) code+='Show("","timerleft1",1);Show("","",1,"leftsignal");Show("","leftblinkerMap",1);Show("","BDT_BUTTON_LEFT",0);';
			else if(this.nextdirection==90) code+='Show("","timerright1",1);Show("","",1,"rightsignal");Show("","rightblinkerMap",1);Show("","BDT_BUTTON_RIGHT",0);';

			this.CallJavascript("imageMap,Turn("+this.nextdirection+")");
		}
		if(action=="all" || action.indexOf("gear")!=-1)
		{
			code+='Show("","",0,"gears");Show("","gearshift'+this.numgear+'",1);';
		}
		if(action=="all" || action.indexOf("updatego")!=-1)
		{
			if(this.ismoving) 
			{
				code+='Fade("","BDT_BUTTON_STOP",'+(20+this.buttonstates[1]*80)+',0.1);';
				code+='Show("","BDT_BUTTON_GO",0);';
			}
			else
			{
				code+='Fade("","BDT_BUTTON_GO",'+(20+this.buttonstates[0]*80)+',0.1);';
				code+='Show("","BDT_BUTTON_STOP",0);';
			}
		}
		if(action=="all" || action.indexOf("stepforward")!=-1)
		{
			code+='Fade("","BDT_BUTTON_STEPFORWARD",'+(20+this.buttonstates[2]*80)+',0.1);';
		}
		if(action=="all" || action.indexOf("stepbackward")!=-1)
		{
			code+='Fade("","BDT_BUTTON_STEPBACKWARD",'+(20+this.buttonstates[3]*80)+',0.1);';
		}
		if(action=="all" || action.indexOf("uturn")!=-1)
		{
			code+='Fade("","BDT_BUTTON_UTURN",'+(20+this.buttonstates[6]*80)+',0.1);';
		}
		if(action=="all" || action.indexOf("zoomin")!=-1)
		{
			code+='Show("","BDT_BUTTON_ZOOMIN",'+this.buttonstates[8]+');';
		}
		if(action=="all" || action.indexOf("zoomout")!=-1)
		{
			code+='Show("","BDT_BUTTON_ZOOMOUT",'+this.buttonstates[9]+');';
		}
		if(action=="all" || action.indexOf("fullscreen")!=-1)
		{
			code+='Fade("","BDT_BUTTON_FULLTOGGLE0",'+(20+this.buttonstates[10]*80)+',0.1);';
		}
		if(action=="all" || action.indexOf("compass")!=-1)
		{
			var northangle=90+this.GetValue("Yaw");
			code+='ObjectValue("","compass1","","rotation",'+northangle+');';
			code+='ObjectValue("","imagefocusMap","","rotation",'+northangle+');';
		}
		if(action=="all" || action.indexOf("stepcompass")!=-1)
		{
			var northangle=90+this.GetValue("Yaw")-this.movingdirection;
			code+='ObjectValue("","BDT_BUTTON_STEPFORWARD","","rotation",'+(northangle)+');';
			code+='ObjectValue("","BDT_BUTTON_STEPBACKWARD","","rotation",'+(northangle)+');';
		}
		if(action.indexOf("showclickdrag")!=-1)
		{
			if(this.visiblesplash==0)
				code+='Show("","",0,"timerclickdrag");Show("","timerclickdrag1",1);Fade("","textclickdrag",0,0.5);';
		}
		if(action=="all" || action.indexOf("hideclickdrag")!=-1)
		{
			if(this.visiblesplash==0)
				code+='Show("","",0,"timerclickdrag");Show("","textclickdrag",0);';
		}
		if(action.indexOf("showads")!=-1)
		{
			code+='Show("","",1,"adsgroup");';
		}
		if(action=="all" || action.indexOf("hideads")!=-1)
		{
			code+='Show("","",0,"adsgroup");';
		}
		if(action=="all" || action.indexOf("showanchors")!=-1)
		{
			code+='Show("","",1,"_anchorsgroup");';
		}
		if(action.indexOf("hideanchors")!=-1)
		{
			code+='Show("","",0,"_anchorsgroup");';
		}
		if(action=="all" || action.indexOf("showmarkers")!=-1)
		{
			code+='Show("","",1,"_markersgroup");';
		}
		if(action.indexOf("hidemarkers")!=-1)
		{
			code+='Show("","",0,"_markersgroup");';
		}
		if(action.indexOf("mapview")!=-1)
		{
			alpha=20+this.buttonstates[13]*80;
			if(this.visibleinternalmap) code+='Show("","BDT_BUTTON_MAPVIEW0",0);Fade("","BDT_BUTTON_MAPVIEW1",'+alpha+',0.1);';
			else code+='Show("","BDT_BUTTON_MAPVIEW1",0);Fade("","BDT_BUTTON_MAPVIEW0",'+alpha+',0.1);';
		}
		if(action=="all" || action.indexOf("brightness")!=-1)
		{
			alpha=20+this.buttonstates[11]*80;
			code+='Show("","",0,"BDT_BUTTON_BRIGHTNESS");Fade("","Brightness'+this.lightlevel+'",'+alpha+',0.1);Fade("","BDT_BUTTON_BRIGHTNESS",'+alpha+',0.1);';
		}
		if(action=="all" || action.indexOf("lockview")!=-1)
		{
			code+='Show("","",0,"BDT_BUTTON_LOCKVIEW");';
			alpha=20+this.buttonstates[7]*80;
			if(this.lockdirection==0) code+='Fade("","CarLockFront",'+alpha+',0.1);';
			else if(this.lockdirection==45) code+='Fade("","CarLockRight45",'+alpha+',0.1);';
			else if(this.lockdirection==-45) code+='Fade("","CarLockLeft45",'+alpha+',0.1);';
			else if(this.DifAngle(this.lockdirection,-90)<5) code+='Fade("","CarLockLeft",'+alpha+',0.1);';
			else if(this.DifAngle(this.lockdirection,90)<5) code+='Fade("","CarLockRight",'+alpha+',0.1);';
		}
		if(action=="all" || action.indexOf("autopan")!=-1)
		{
			alpha=20+this.buttonstates[12]*80;
			if(this.autopanstate) code+='Show("","BDT_BUTTON_AUTOPAN0",0); Fade("","BDT_BUTTON_AUTOPAN1",'+alpha+',0.1);';
			else code+='Fade("","BDT_BUTTON_AUTOPAN0",'+alpha+',0.1); Show("","BDT_BUTTON_AUTOPAN1",0);';
		}
		if(action=="all" || action.indexOf("distancemeasure")!=-1)
		{
			if(this.distancemeasurestate) code+='Show("","BDT_BUTTON_DISTANCE0",0); Show("","BDT_BUTTON_DISTANCE1",1);';
			else code+='Show("","BDT_BUTTON_DISTANCE0",1); Show("","BDT_BUTTON_DISTANCE1",0);Show("","BDT_TEXT_DISTANCEMEASURE",0);';
		}
		if(action=="all" || action.indexOf("updateposmap")!=-1)
		{
			var lat=this.GetValue("Y");
			var lon=this.GetValue("X");
			if(lat!=0)
			{
				this.CallJavascript("imageMap,MoveMap("+lat+","+lon+")");

				if(this.wasmapdragged)
				{
					code+='Show("","imagecarMap",1);Show("","imagefocusMap",1);Show("","leftblinkerMap",1);Show("","rightblinkerMap",1);';
					this.wasmapdragged=0;
				}
			}
		}
		else if(action.indexOf("zoominmap")!=-1) this.CallJavascript("imageMap,ZoominMap()");
		else if(action.indexOf("zoomoutmap")!=-1) this.CallJavascript("imageMap,ZoomoutMap()");

		if(code!="") this.pluginobj.Commands('runcode',code);
	}
}

BlueDasherViewer.prototype.UpdateMessages= function(action)
{
	var code="";
	if(this.pluginused==1 && this.IsInterfaceLoaded("UpdateMessages('"+action+"')",1000))
	{
		if(action=="all" || action.indexOf("hidewaiting")!=-1)
		{
			code+='Fade("","textWaitPos",0,0.5);';
		}
		if(action.indexOf("showwaiting")!=-1)
		{
			code+='Fade("","textWaitPos",100,0.5);EnableQualityUpdate("_this_",0);';
		}
		if(action=="all" || action.indexOf("hidesplash")!=-1)
		{
			code+='Show("","",0,"splash");';
			this.visiblesplash=0;
		}
		if(action.indexOf("showsplash")!=-1)
		{
			code+='Show("","",1,"splash")';
			if(this.visiblesplashweb==0) code+='Show("","splashfrontweb",0);';
			else code+='Show("","splashfront",0);';
			this.visiblesplash=1;
		}
		if(action=="all" || action.indexOf("hidemessage")!=-1)
		{
			code+='Fade("","BDT_TEXT_MESSAGE",0,0.5);Show("","BDT_BUTTON_TEXTMESSAGE",0);';
			this.messageenabled=0;
		}
		if(code!="") this.pluginobj.Commands('runcode',code);
	}
}

BlueDasherViewer.prototype.UpdateExternalMap= function(action)
{
	if(this.IsMapLoaded("UpdateExternalMap('"+action+"')",1000))
	{
		if(action=="all" || action.indexOf("car")!=-1)
		{
			var carangle=this.movingdirection+this.nextfacingdirection;
			this.RotateCarMap(carangle);
			this.RotateFocusMap(this.GetFacingDirection()-carangle);
		}
		if(action=="all" || action.indexOf("turn")!=-1)
		{
			this.BlinkerCarMap("carimg.left",0);
			this.BlinkerCarMap("carimg.right",0);
			if(this.nextdirection==-90) this.BlinkerCarMap("carimg.left",100);
			else if(this.nextdirection==90) this.BlinkerCarMap("carimg.right",100);
		}
		if(action=="all" || action.indexOf("updateposmap")!=-1)
		{
			var lat=this.GetValue("Y");
			var lon=this.GetValue("X");
			if(lat!=0 || lon!=0)
			{
				this.MoveCar(lat,lon);
				if(this.ismoving) this.MoveMap(lat,lon,0);
			}
		}
	}
}

BlueDasherViewer.prototype.ShowSplash= function(filename)
{
	var code='';

	if(this.IsInterfaceLoaded("ShowSplash('"+filename+"')",500))
	{
		if(filename!=undefined)
		{
			if(filename.indexOf('.jpg')!=-1 || filename.indexOf('.png')!=-1) 
			{
				code='Load("splashfrontimg","'+filename+'");';
				this.visiblesplashweb=0;
			}
			else 
			{
				code='Load("splashfrontweb","'+filename+'");';
				this.visiblesplashweb=1;
			}
			this.pluginobj.Commands('runcode',code);
		}
		this.UpdateMessages("showsplash");
	}
}

BlueDasherViewer.prototype.HideSplash= function()
{
	this.UpdateMessages("hidesplash");
}

BlueDasherViewer.prototype.ShowMessage= function(message)
{
	var code='';
	if(this.IsInterfaceLoaded("ShowMessage('"+message+"')",1000))
	{
		message=message.replace(/\[br\]/g,"\n");
		code+='ObjectValue("","BDT_TEXT_MESSAGE","","description","'+message+'");Fade("","BDT_TEXT_MESSAGE",100,0.5);Show("","BDT_BUTTON_TEXTMESSAGE",1);';
		if(code!="") this.pluginobj.Commands('runcode',code);
		this.messageenabled=3;
	}
}

BlueDasherViewer.prototype.LoadInterface= function(filename)
{
	if(this.pluginused==1)
	{
		if(this.dashboartsetdef){
			clearTimeout(this.dashboartsetdef);
			this.dashboartsetdef=null;
		}
		this.dashboardstate=1;
		if(this.IsPluginLoaded("LoadInterface('"+filename+"')",2000))
		{
			this.wasmapdragged=0;
			this.ResetViewer();
			var code='SetInterfaceFile("'+filename+'");';
			this.pluginobj.Commands('runcode',code);
			this.carimage=filename+'/../images/car.swf';
			if(this.GetValue("File")!=0)
			{
				setTimeout(this.objectname+".UpdateInterface('all')",2000);
			}
		}
	}
}

BlueDasherViewer.prototype.IsInterfaceLoaded= function(funcstring, time)
{
	var ret=0;
	if(this.dashboardstate==2) ret=1;
	else if(this.dashboardstate==1)
	{
		if(this.pluginobj && typeof(this.pluginobj.Commands)!="undefined")
		{
			if(this.pluginobj.Commands("getobjectvalue2Dx","splashfront")==0) ret=-1; //loading
			else 
			{
				this.dashboardstate=2;
				ret=1;	//loaded
			}
		}
		else if(this.pluginstate>0 && funcstring!="") ret=-1; //loading
		if(ret==-1)
		{
			setTimeout(this.objectname+"."+funcstring,time);
			ret=0;
		}
	}
	return ret;
}

BlueDasherViewer.prototype.IsPluginLoaded= function(funcstring, time)
{
	var ret=0;
	if(this.pluginobj)
	{
		if(this.pluginused==1 && typeof(this.pluginobj.Commands)!="undefined") ret=1;
		else if(this.pluginused==0) ret=1;
	}
	else if(this.pluginstate>0) setTimeout(this.objectname+"."+funcstring,time);
	return ret;
}

BlueDasherViewer.prototype.IsMapLoaded= function(funcstring, time)
{
	var ret=0;
	if(this.extmap) ret=1;
	else if(this.extmap_) setTimeout(this.objectname+"."+funcstring,time);
	return ret;
}

BlueDasherViewer.prototype.EnablePluginCache= function(enable)
{
	if(this.pluginused==1 && this.IsPluginLoaded("EnablePluginCache("+enable+")",1000))
	{
		this.plugincache=enable;
		this.pluginobj.Commands("enablecache",""+enable);
	}
}

BlueDasherViewer.prototype.EnableClickEvent= function(enable)
{
	if(this.pluginused==1 && this.IsPluginLoaded("EnableClickEvent("+enable+")",1000))
	{
		this.clickevent=enable;
		this.pluginobj.Commands("enableclickevent",""+enable);
	}
}

BlueDasherViewer.prototype.EnablePreloadingCache= function(enable, numimages)
{
	this.preloadingcacheenabled=enable;
	if(numimages!=undefined)
		this.preloadingcachemax=numimages;
}

BlueDasherViewer.prototype.SetCurrentPicture= function(file, facing, tilt, zoom)
{
	this.Stop();
	this.facingdirection=facing;
	this.foundpoint.File=file;
	this.foundpoint.Tilt=tilt;
	this.foundpoint.Zoom=zoom;
	this.LoadPicture("foundpoint");
}

BlueDasherViewer.prototype.LoadPicture= function(file, preload, centerlat, centerlon, north)
{
	var code="";
	var filemed="";
	var filehigh="";
	var ismoving=1,accuracy=3;
	var tilt=0,direction=0,pitch=undefined;
	var zoom=this.zoomdefault;
	var onlyhigh=0;
	var existframe=1;
	var framename="";
	var updateinterface="";
	var pointid=undefined;

	if(preload==undefined) preload=0;
	if(this.IsPluginLoaded("LoadPicture('"+file+"',"+preload+","+centerlat+","+centerlon+")",1000))
	{
		if(this.autopanstate==1)
			this.SetAutopan(0);
		
		if(preload==0) this.latestpicture=file;
		if(file==undefined || file=="foundpoint")
		{
			if(file=="foundpoint")
			{
				ismoving=0;
				if(this.foundpoint.BdtAccuracy==2) accuracy=2;
				
				if(this.foundpoint.Tilt!=undefined && (this.foundpoint.Tilt>2.0 || this.foundpoint.Tilt<-2.0)) 
				{
					tilt=this.foundpoint.Tilt;
					onlyhigh=1;
				}
				if(this.foundpoint.Zoom!=undefined && this.foundpoint.Zoom<0.60) 
				{
					zoom=this.foundpoint.Zoom;
					onlyhigh=1;
				}
				file=this.foundpoint.File;
				centerlat=this.foundpoint.Y;
				centerlon=this.foundpoint.X;
				north=this.foundpoint.Yaw;
				pointid=this.foundpoint.ID;
				pitch=-this.foundpoint.Pitch;
				if(preload==0 && this.extmap && typeof(this.extmap.CreateShape)!="undefined")
				{
					this.MoveFlag(this.foundpoint.FacingY,this.foundpoint.FacingX,this.foundpoint.address);
					this.MoveMap(this.foundpoint.FacingY,this.foundpoint.FacingX,1);
					this.setzoompoints=1;
				}
			}
			else
			{
				file=this.GetValue("File");
				centerlat=this.GetValue("Y");
				centerlon=this.GetValue("X");
				north=this.GetValue("Yaw");
			}
		}
		if(file!=0 && file!="" && file!="nophoto")
		{
			filemed=this.GetFilename(file,"MEDIUM");
			filehigh=this.GetFilename(file,"HIGH");
			if(onlyhigh || this.photosfolder_attemphigh)
			{
				filemed=filehigh;
				filehigh="";
			}
			if(preload==0)
			{
				if(pointid==undefined) pointid=this.GetValue("pointid");
				if(this.accesslogenabled) this.LogAccess(pointid);
			}
		}
		else
		{
			ismoving=0;
			filemed=this.mainfolder+"images/nophoto.jpg";
			filehigh="";
		}
		
		if(filemed!="")
		{
			if(this.pluginused==1)
			{
				if(file!="nophoto")
				{
					file+=","+this.photosfolder_use+","+this.photosfolder_attemphigh;
					var files=file.split(",");
					framename=files[0]+'-'+files[1]+'-'+files[2]+'-'+files[3]+'-'+files[4];
				}
				else framename=file;
				existframe=this.pluginobj.Commands('existframe',framename);
				
				if(existframe==0)
					code+='CreateFrame("'+framename+'","PANORAMIC","'+filemed+'",'+this.waitseconds+',"'+filehigh+'");';
				code+='PreloadFrame("'+framename+'",30);';

				if(preload==0)
				{
					updateinterface="compass,stepcompass";
					direction=this.ConvertRotation(this.GetNextFacingDirection(ismoving));
					if(pitch==undefined) pitch=this.GetValue("Pitch");
					if(this.latestfile!=file)
					{
						if(ismoving==0) this.Dbg("loadpic",file);
						code+='EnableQualityUpdate("_this_",0);';	
						code+='DeleteFrame("_this_");';					
						code+='Transition("_this_",2,100,0,blend);';
						code+='InitialCameraRotation("'+framename+'",'+tilt+','+direction+','+zoom+','+(pitch)+');';
						code+='Transition("'+framename+'",2,100,0,blend);';
						code+='EnableQualityUpdate("'+framename+'",1);';
						code+='GoToFrame("'+framename+'");';
						
						this.picturetimeout=setTimeout(this.objectname+".AddMessage('- Picture Timeout: "+filemed+"')",5000);
					}
					else if(file!="nophoto")
					{
						code+='EnableQualityUpdate("'+framename+'",1);';
						this.pluginobj.Command("zoomcamera",zoom,0,0);
						this.pluginobj.Command("rotcamera",tilt,direction,pitch);
						this.SendEvent(this.OnPictureLoaded);

						updateinterface+=",updateposmap";
						this.UpdateExternalMap("updateposmap");
						this.UpdateMessages("hidewaiting,hidesplash");
						if(ismoving==0 && file!="nophoto") updateinterface+=",showclickdrag";
					}
					if(file!="nophoto" && this.photosfolder_attemps==0)
					{
						if(this.extmap && this.extmap.zoomlevel<14) this.ZoomMap(17,1);
						this.UpdateInterface(updateinterface);
						if(accuracy==3) this.UpdateMessages("hidemessage");
					}
					this.UpdateMapInfo(0);
					this.loadingframe=1;
					this.latestframename=framename;
					this.latestfile=file;
				}
				this.pluginobj.Commands('runcode',code);
					
				if(existframe==0 && file!="nophoto")
				{		
					this.CreateSceneObjects(framename,centerlat,centerlon,north,0);			
				}
			}
			else
			{
				this.pluginobj.newPano('{file='+filehigh+'}');
				setTimeout(this.objectname+".DoDVLCommands('panorama')",1000);
			}
		}
		else if(preload==0) pthis.UpdateMessages("hidewaiting");
	}
}

BlueDasherViewer.prototype.EnableQualityUpdate= function(enable)
{
	if(this.pluginused==1 && this.IsPluginLoaded("EnableQualityUpdate("+enable+")",2000))
	{
		var code='EnableQualityUpdate("_this_",'+enable+');';
	    this.pluginobj.Commands('runcode',code);
	}
}

BlueDasherViewer.prototype.InsertAddressAd= function(centerlat,centerlon,lat, lon)
{
	size=1;

	distance=0.00008;
	angle=90-this.GetAnglePoints(centerlat,centerlon,lat,lon)-38;
	angle=(angle*Math.PI)/180.0;
	centerlat+=Math.sin(angle)*distance;
	centerlon+=Math.cos(angle)*distance;
	this.InsertAd(centerlat,centerlon,2,(3.00*size),(3.50*size),"#11", this.mainfolder+"imgads/250x250_frame.png",2, (2.50*size), (2.50*size), "#11", "http://dev.bluedashertech.com/agents/forsale.aspx?mls=M1246442&ext=html");
}

BlueDasherViewer.prototype.InsertPropertyAd= function(lat,lon,url,frameurl,iconurl)
{
	if(frameurl==undefined) frameurl=this.mainfolder+"imgads/for_sale_sign.png";
	if(iconurl==undefined) iconurl=this.mainfolder+"imgads/info.png";
	if(url.indexOf("?")!=-1) url+="&ext=html";
	this.InsertAd(lat,lon,-2,8.00,8.0,"#21", frameurl,-1.2, 5.0, 5.0, "#21", url, iconurl);
}

BlueDasherViewer.prototype.RemoveAds= function()
{
	this.ads=null;
	this.ads=new Array();
	this.numads=0;
}

function BDTAd(name, group,lat, lon, altframe, widthframe, heightframe, alignframe, urlframe, altimg, widthimg, heightimg, alignimg, urlimg, urlicon, fixedsize, markerevent)
{
	this.Name=name;
	this.Group=group;
	this.Latitude=lat;
	this.Longitude=lon;
	this.AltFrame=altframe;
	this.WidthFrame=widthframe;
	this.HeightFrame=heightframe;
	this.AlignFrame=alignframe;
	this.URLFrame=urlframe;
	this.AltImage=altimg;
	this.WidthImage=widthimg;
	this.HeightImage=heightimg;
	this.AlignImage=alignimg;
	this.URLImage=urlimg;
	this.URLIcon=urlicon;
	this.distance=0;
	this.skinframe=-1;
	this.skinimage=-1;
	this.skinicon=-1;
	this.FixedSize=fixedsize;
	this.markerevent=markerevent;
};

BlueDasherViewer.prototype.AddAnchor= function(name, lat, lon, icon, image, markerevent)
{
	this.AddMapObject(0, "_anchors", name, lat, lon, icon, image, 2.0, 2.0, markerevent);
}

BlueDasherViewer.prototype.AddMarker= function(name, lat, lon, icon, image, width, height, markerevent)
{
	this.AddMapObject(1, "_markers", name, lat, lon, icon, image, width, height, markerevent);
}

BlueDasherViewer.prototype.AddMapObject= function(layer, group, name, lat, lon, icon, image, width, height, markerevent)
{
	if(this.IsMapLoaded('AddMapObject('+layer+',"'+group+'","'+name+'",'+lat+','+lon+',"'+icon+'","'+image+'","'+markerevent+'")',2000))
	{
		var n,num;
		var imagename=name;
		if(name=="" || name==undefined){
			name=group+this.extmap.shapemarker.length;
			imagename=group+this.sceneobj.length;
		}
		if(icon!=""){
			num=this.extmap.shapemarker.length;
			for(n=0;n<this.extmap.shapemarker.length;n++) 
				if(this.extmap.shapemarker[n].Name==name) {num=n; break;}
			if(this.extmap.layermarkers[layer]==null ||this.extmap.layermarkers[layer]==null){
				this.extmap.layermarkers[layer]=this.extmap.CreateLayer();
				if(this.extmap.layermarkers[layer] && this.visiblemarkers[layer]) this.extmap.ShowLayer(this.extmap.layermarkers[layer]);
			}
			if(this.extmap.layermarkers)
			{
				if(num!=this.extmap.shapemarker.length)
					this.extmap.RemoveShape(this.extmap.shapemarker[num]);
				this.extmap.shapemarker[num]=this.extmap.CreateShape(lat,lon,0,-16,32,32,'<img border="0" src="'+icon+'" />',markerevent);
				this.extmap.shapemarker[num].BDTTitle="- Address -";
				this.extmap.shapemarker[num].Name=name;
				if(markerevent!=undefined && markerevent!="") this.extmap.shapemarker[num].BDTAddress=markerevent;
				else this.extmap.shapemarker[num].BDTAddress="_latlon_";
				this.extmap.layermarkers[layer].AddShape(this.extmap.shapemarker[num]);
			}
		}
		if(image!="") 
		{
			if(layer==0) this.CreateSceneObject(imagename,group,lat,lon, -this.carcameraheight, width, height, image, 0,0,0,"","",1);
			else this.CreateSceneObject(imagename,group,lat,lon, -this.carcameraheight, width, height, image, 0,0,0,"","",0,markerevent);
		}
	}
}

BlueDasherViewer.prototype.CreateSceneObject= function(name,group,lat,lon, level, width, height, image, framelevel, framewidth, frameheight, AdFrameUrl, AdIconUrl, fixedsize, markerevent)
{
	var n,num=this.sceneobj.length;
	for(n=0;n<this.sceneobj.length;n++) {
		if(this.sceneobj[n].Name==name){ num=n; break; }
	}
	this.sceneobj[num]=new BDTAd(name,group, lat, lon, framelevel, framewidth, frameheight, "#21", AdFrameUrl, level, width, height, "#21", image, AdIconUrl,fixedsize, markerevent);
	if((this.visibleads || this.visiblemarkers[0] || this.visiblemarkers[1]) && this.ismoving==0 && this.pluginobj)
	{
		if(this.pluginobj.Commands('existobject','_this_,'+this.sceneobj[num].Name)==0)
			this.CreateSceneObjects("_this_",this.GetValue("Y"),this.GetValue("X"),this.GetValue("Yaw"),1);
		else
			this.CreateSceneObjectCode("_this_",this.GetValue("Y"),this.GetValue("X"),this.GetValue("Yaw"),this.sceneobj[num]);
	}
}

BlueDasherViewer.prototype.InsertAd= function(lat, lon, altframe, widthframe, heightframe, alignframe, urlframe, altimg, widthimg, heightimg, alignimg, urlimg, urlicon)
{
	var distance=1000000;

	for(var n=0;n<this.numads;n++)
	{
		var dist=this.GetDistancePoints(lat,lon,this.ads[n].Latitude,this.ads[n].Longitude);
		if(dist<distance)
		{
			distance=dist;
		}
	}
	
	if(distance>0.00005)
	{
		this.ads[this.numads]=new BDTAd("ads"+this.numads,"ads",lat, lon, altframe, widthframe, heightframe, alignframe, urlframe, altimg, widthimg, heightimg, alignimg, urlimg, urlicon,0);
		this.numads++;
	}
}

BlueDasherViewer.prototype.CreateSceneObjects= function(framename,centerlat,centerlon,north,forcedraw)
{
	var numtotal=0,numads=0,numobjs=0;
	if(this.numads>0 && this.visibleads && (forcedraw || this.pluginobj.Commands('existobject',framename+',ads0ad')==0)) 
		numads=this.numads;
	if(this.sceneobj.length>0 && ((this.visibleads && this.sceneobj[0].Name=="adeditor") || this.visiblemarkers[0] || this.visiblemarkers[1]) && (forcedraw || this.pluginobj.Commands('existobject',framename+','+this.sceneobj[0].Name)==0)) 
		numobjs=this.sceneobj.length;
	numtotal=numads+numobjs;
	if(numtotal>0 && this.IsInterfaceLoaded("CreateSceneObjects('"+framename+"',"+centerlat+","+centerlon+","+north+","+forcedraw+")",2000))
	{
		var n,i;
		var usedframe=new Array();
		var usedimage=new Array();
		var usedicon=new Array();
		var code='';
		var ad=null;

		for(n=0;n<10;n++)
		{
			usedframe[n]=0;
			usedimage[n]=0;
			usedicon[n]=0;
		}
		for(n=0;n<numtotal;n++)
		{
			if(n<numads) ad=this.ads[n];
			else ad=this.sceneobj[n-numads];
			distance=this.GetDistancePoints(centerlat,centerlon,ad.Latitude,ad.Longitude);
			ad.distance=distance;
			
			if(distance<100.0)	//only ads in a radius of 100m
			{
				ad.skinimage=-1;
				ad.skinframe=-1;
				ad.skinicon=-1;
				for(i=0;i<10;i++)
				{
					if(ad.skinimage==-1 && ad.URLImage!="" && this.adsimages[i]==ad.URLImage) 
					{
						ad.skinimage=i;
						usedimage[i]=1;
					}
					if(ad.skinframe==-1 && ad.URLFrame!="" && this.adsframes[i]==ad.URLFrame) 
					{
						ad.skinframe=i;
						usedframe[i]=1;
					}
					if(ad.skinicon==-1 && ad.URLIcon!="" && this.adsicons[i]==ad.URLIcon)
					{
						ad.skinicon=i;
						usedicon[i]=1;
					}
				}
			}
		}
		for(n=0;n<numtotal;n++)
		{
			if(n<numads) ad=this.ads[n];
			else ad=this.sceneobj[n-numads];
			if(ad.distance<100.0)
			{
				for(i=0;n>0 && i<10;i++)
				{
					if(ad.skinimage==-1 && ad.URLImage!="" && this.adsimages[i]==ad.URLImage) 
					{
						ad.skinimage=i;
						usedimage[i]=1;
					}
					if(ad.skinframe==-1 && ad.URLFrame!="" && this.adsframes[i]==ad.URLFrame) 
					{
						ad.skinframe=i;
						usedframe[i]=1;
					}
					if(ad.skinicon==-1 && ad.URLIcon!="" && this.adsicons[i]==ad.URLIcon)
					{
						ad.skinicon=i;
						usedicon[i]=1;
					}
				}
				for(i=0;i<10;i++)
				{
					if(ad.skinimage==-1 && ad.URLImage!="" && usedimage[i]==0) 
					{
						this.adsimages[i]=ad.URLImage;
						code+='Load("imgads'+i+'","'+this.adsimages[i]+'");';
						ad.skinimage=i;
						usedimage[i]=1;
					}
					if(ad.skinframe==-1 && ad.URLFrame!="" && usedframe[i]==0) 
					{
						this.adsframes[i]=ad.URLFrame;
						code+='Load("imgadsframe'+i+'","'+this.adsframes[i]+'");';
						ad.skinframe=i;
						usedframe[i]=1;
					}
					if(ad.skinicon==-1 && ad.URLIcon!="" && usedicon[i]==0)
					{
						this.adsicons[i]=ad.URLIcon;
						code+='Load("imgadsicon'+i+'","'+this.adsicons[i]+'");';
						ad.skinicon=i;
						usedicon[i]=1;
					}
				}
				if(ad.skinimage!=-1)
				{
					this.CreateSceneObjectCode(framename,centerlat,centerlon,north,ad);
				}
			}
		}
		if(code!='') this.pluginobj.Commands('runcode',code);
	}
}

BlueDasherViewer.prototype.CreateSceneObjectCode= function(framename,centerlat,centerlon,north,ad)
{
	var code='';
	var angle=90-this.GetAnglePoints(centerlat,centerlon,ad.Latitude,ad.Longitude);
	angle=(angle*Math.PI)/180.0;
	var x=Math.cos(angle)*ad.distance;
	var z=Math.sin(angle)*ad.distance;
	var widthimg=ad.WidthImage;
	var heightimg=ad.HeightImage;
	if(ad.FixedSize){
		widthimg=widthimg*(ad.distance/100.0)*5;
		heightimg=heightimg*(ad.distance/100.0)*5;
	}
	if(this.pluginobj.pluginversion<0x080200 && x<0) {x=-x; z=-z; north+=180;}	//This fixes a bug in the plugin with Atan2
	if(ad.skinicon!=-1) code+='Create3DPlaneCamera("'+framename+'", "'+ad.Name+'icon", "'+ad.Group+'group", "imgadsicon'+ad.skinicon+'", '+north+', '+x+', '+(ad.AltFrame+ad.HeightFrame/2-2.0/2)+', '+z+', '+2.0+', '+2.0+', '+ad.AlignFrame+', "Click to show info","Show(_this_,"'+ad.Name+'frame",1);Show(_this_,"'+ad.Name+'ad",1);");';
	if(ad.skinframe!=-1 && ad.skinicon!=-1) code+='Create3DPlaneCamera("'+framename+'", "'+ad.Name+'frame", "'+ad.Group+'group", "imgadsframe'+ad.skinframe+'", '+north+', '+x+', '+ad.AltFrame+', '+z+', '+ad.WidthFrame+', '+ad.HeightFrame+', '+ad.AlignFrame+', "Click to hide info","Show(_this_,"'+ad.Name+'frame",0);Show(_this_,"'+ad.Name+'ad",0););';
	else if(ad.skinframe!=-1) code+='Create3DPlaneCamera("'+framename+'", "'+ad.Name+'frame", "'+ad.Group+'group", "imgadsframe'+ad.skinframe+'", '+north+', '+x+', '+ad.AltFrame+', '+z+', '+ad.WidthFrame+', '+ad.HeightFrame+', '+ad.AlignFrame+');';
	var eventmarker="";
	if(ad.Group=="_markers" && ad.markerevent!=undefined) eventmarker='JavascriptEvent("markerevent,'+ad.markerevent+'");';
	if(widthimg>0 && heightimg>0) code+='Create3DPlaneCamera("'+framename+'", "'+ad.Name+'ad", "'+ad.Group+'group", "imgads'+ad.skinimage+'", '+north+', '+x+', '+ad.AltImage+', '+z+', '+widthimg+', '+heightimg+', '+ad.AlignImage+',"","'+eventmarker+'");';			
	this.pluginobj.Commands('runcode',code);
}

BlueDasherViewer.prototype.CreateStreetArrows= function(framename)
{
	var fromto="From";
	var num,side;
	var nextdir,distance,angle;
	var code="";
	var numarrow=0;
	
	if(this.pluginobj)
	{
		if(this.pluginobj.Commands("getobjectvalue2Dy","arrow0")==0)
		{
			var centerlat=this.GetValue("Y");
			var centerlon=this.GetValue("X");
			var north=this.GetValue("Yaw");

			for(side=0;side<2;side++)
			{
				num=this.GetVectorValue(this.currentvector,"num"+fromto);
				extremelon=this.currentvector[fromto+"X"];
				extremelat=this.currentvector[fromto+"Y"];
		
				for(n=0;n<num;n++)
				{
					if(this.currentvector[fromto+"Vectors"][n])
					{
						distance=this.GetDistancePoints(centerlat,centerlon,extremelat,extremelon);
						if(distance<200)
						{
							angle=90-this.GetAnglePoints(centerlat,centerlon,extremelat,extremelon);
							angle=(angle*Math.PI)/180.0;
							x=Math.cos(angle)*distance;
							z=Math.sin(angle)*distance;
							nextdir=this.CalculateNextDirection(this.currentvector,fromto,n,extremelon,extremelat);
							angle=((90-nextdir)*Math.PI)/180.0;
							x+=Math.cos(angle)*5;
							z+=Math.sin(angle)*5;
		
							code+='Create3DPlane("'+framename+'", "arrow'+numarrow+'", "arrowgroup", "streetarrow", '+north+', '+x+', -2, '+z+', 2.0, 2.0, 0,'+nextdir+', "#11", "", "JavascriptEvent("streetevent,'+this.GetVectorValue(this.currentvector,fromto+"Vectors",n,"ID")+'");");';			
						}
					}
				}		
				
				fromto="To";
			}
			if(code!="") this.pluginobj.Commands('runcode',code);
		}
	}
}

BlueDasherViewer.prototype.ShowPluginCache= function(show,loading,size)
{
	var code='';
	if(this.pluginobj)
	{
		if(loading) code+='Show("","BDT_IMAGE_TEXTCACHELOAD",1);';
		else code+='Show("","BDT_IMAGE_TEXTCACHELOAD",0);';
		if(this.preloadingcacheshowbar)
		{
			if(loading) code+='Show("","BDT_IMAGE_CACHELOAD",1);Show("","BDT_IMAGE_CACHEUNLOAD",0);';
			else code+='Show("","BDT_IMAGE_CACHELOAD",0);Show("","BDT_IMAGE_CACHEUNLOAD",1);';
			code+='ObjectValue("","BDT_IMAGE_CACHELOAD","","width",'+(200.0*size)+');ObjectValue("","BDT_IMAGE_CACHEUNLOAD","","width",'+(200.0*size)+');';
		}
		this.pluginobj.Commands('runcode',code);
	}
}

BlueDasherViewer.prototype.ShowBanner= function(side, filename, url, tooltip)
{
	var code='',banner='',show=1;

	if(filename==undefined) filename="";
	if(url==undefined) url="";
	if(tooltip==undefined) tooltip="";
	if(this.IsInterfaceLoaded("ShowBanner('"+side+"','"+filename+"','"+url+"','"+tooltip+"')",1000))
	{
		if(filename=="hide") show=0;
		if(side=="left") 
		{
			banner="BDT_BUTTON_TOPLEFTBANNER";
			if(url!="") this.topleftbannerurl=url;
			if(show && filename!="")
				code+='Load("'+banner+'img","'+filename+'");';
		}
		else if(side=="right") 
		{
			banner="BDT_BUTTON_TOPRIGHTBANNER";
			if(url!="") this.toprightbannerurl=url;
			if(show && filename!="")
				code+='Load("'+banner+'img","'+filename+'");';
		}
		else if(side=="bottomleft") 
		{
			banner="BDT_BUTTON_BOTTOMLEFTBANNER";
			if(url!="") this.bottomleftbannerurl=url;
			if(show && filename!="")
				code+='ObjectValue("","BDT_TEXT_BOTTOMLEFTBANNER","","description","'+filename+'");';			
			code+='Show("","BDT_TEXT_BOTTOMLEFTBANNER",'+show+');';
		}
		else if(side=="bottomright") 
		{
			banner="BDT_BUTTON_BOTTOMRIGHTBANNER";
			if(url!="") this.bottomrightbannerurl=url;
			if(show && filename!="")
				code+='ObjectValue("","BDT_TEXT_BOTTOMRIGHTBANNER","","description","'+filename+'");';			
			code+='Show("","BDT_TEXT_BOTTOMRIGHTBANNER",'+show+');';
		}
		if(show) code+='ObjectValue("","'+banner+'","","description","'+tooltip+'");';
		code+='Show("","'+banner+'",'+show+');';
		this.pluginobj.Commands('runcode',code);

		this.visiblesplash=1;
	}
}

BlueDasherViewer.prototype.HideBanner= function(side)
{
	this.ShowBanner(side,"hide","","");
}

BlueDasherViewer.prototype.ShowButton=function(numbutton, imagefile, imagefileroll, action, tooltip, show)
{
	var code='';
	if(show==undefined) show=1;
	if(imagefile==undefined) imagefile="";
	if(imagefileroll==undefined) imagefileroll="";
	if(action==undefined) action="";
	if(tooltip==undefined) tooltip="";
	if(this.IsInterfaceLoaded("ShowButton('"+numbutton+"','"+imagefile+"','"+imagefileroll+"','"+action+"','"+tooltip+"','"+show+"')",1000))
	{
		if(numbutton>=0 && numbutton<4)
		{
			code+='Show("","BDT_BUTTON_OPTION'+numbutton+'",'+show+');';
			if(imagefile!="") code+='Load("BDT_BUTTON_OPTION'+numbutton+'img","'+imagefile+'");';
			if(imagefileroll!="") code+='Load("BDT_BUTTON_OPTION'+numbutton+'rollimg","'+imagefileroll+'");';
			if(action!="") this.buttonaction[numbutton]=action;
			if(tooltip!="") code+='ObjectValue("","BDT_BUTTON_OPTION'+numbutton+'","","description","'+tooltip+'");';

			this.pluginobj.Commands('runcode',code);
		}
	}
}

BlueDasherViewer.prototype.HideButton=function(numbutton)
{
	ShowButton(numbutton, "", "", "", "", 0);
}

BlueDasherViewer.prototype.ShowInterface=function(show)
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("ShowInterface('"+show+"')",1000))
	{
		var code='ShowGroup("","",'+show+');';
		this.pluginobj.Commands('runcode',code);
		
		if(show && this.visibleinternalmap==0)
		{
			this.HideInternalMap();
		}
	}
}

BlueDasherViewer.prototype.SaveSnapshot=function(showinterface)
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("SaveSnapshot('"+showinterface+"')",1000))
	{
		this.pluginobj.Commands("saveview","Snapshot"+this.snapshotnumber+".jpg");
		this.snapshotnumber++;
		if(showinterface)
		{
			this.pluginobj.Commands('runcode','PreloadFrame("EVENT_SNAPSHOT");JavascriptEvent("EVENT_SNAPSHOT");');
		}
	}
}

BlueDasherViewer.prototype.ShowInternalMap= function()
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("ShowInternalMap()",1000))
	{
		this.pluginobj.Commands('runcode','ShowGroup("","",1,"mapwindow");ResetDrag("","","mapwindow");');
		this.visibleinternalmap=1;
		this.UpdateInterface("mapview");
	}
}

BlueDasherViewer.prototype.HideInternalMap= function()
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("HideInternalMap()",1000))
	{
		this.pluginobj.Commands('runcode','ShowGroup("","",0,"mapwindow");');
		this.visibleinternalmap=0;
		this.UpdateInterface("mapview");
	}
}

BlueDasherViewer.prototype.SetInterfaceImage= function(imagename,url)
{
	if(this.pluginused==1 && this.IsInterfaceLoaded("SetInterfaceImage('"+imagename+"','"+url+"')",1000))
	{
		this.pluginobj.Commands('runcode','Load("'+imagename+'","'+url+'");');
	}
}

BlueDasherViewer.prototype.EnableButton= function(buttonname, enable)
{
	var buttons=Array("go","stop","stepforward","stepbackward","leftturn","rightturn","uturn","lockview","zoomin","zoomout"
					,"fullscreen","brightness","autopan","mapview");
	var name="",state,n,num=-1;
	var code="";
	
	name=buttonname.toLowerCase();
	for(n=0;n<buttons.length;n++)
	{
		if(name==buttons[n])
		{
			num=n;
			break;
		}
	}
	if(num>=0)
	{
		if(enable) state=1;
		else state=0;
		this.buttonstates[num]=state;
		
		if(num==4 || num==5) name="turn";	
		this.UpdateInterface(name);
	}		
}

//-------------------------------------------------------
//	External map functions
//-------------------------------------------------------

// BlueDasherMap constructor
function BlueDasherMap(divname,parent)
{
	this.divname=divname;
	this.map = null;
	this.shapecar=null;
	this.shapeflag=null;
	this.shapemarker=new Array();
	this.layerroute=null;
	this.layermarkers=Array(null,null);
	this.layerbound=Array();
	this.layermapinfo=new Array();
	this.ilayermapinfo=new Array();
	this.mininfozoom=new Array();
	this.enabledmapinfo=new Array();
	this.busymapinfo=new Array();
	this.objectname="BlueDasherMap_"+divname;
	this.moviename="BlueDasherMap_car_"+divname;
	this.movieref=null;
	this.carangle=0;
	this.iscarvisible=1;
	this.isflagvisible=1;
	this.focusangle=0;
	this.parent=parent;
	this.loading=1;
	this.offsetxshape=0;
	this.offsetyshape=0;
	eval(this.objectname+"=this");	//autoreferer variable
	this.nummaxmapinfo=9;
	for(n=0;n<this.nummaxmapinfo;n++)
	{
		this.layermapinfo[n*2]=null;
		this.layermapinfo[n*2+1]=null;
		this.ilayermapinfo[n]=0;
		this.enabledmapinfo[n]=0;
		this.busymapinfo[n]=0;
		this.mininfozoom[n]=10;
	}
	this.mininfozoom[0]=16;	//Coverage zoom
	this.mininfozoom[1]=17;	//Rooftop zoom
	this.mininfozoom[2]=10;	//Signs zoom
	this.mininfozoom[3]=0;	//Ads zoom
	
	this.zoomlevel=3;
	this.currentlat=39.774769;		//USA view
	this.currentlon=-99.492187;
	this.nochangecenter=0;
	this.blockmousebutton=0;
}

BlueDasherViewer.prototype.LoadMap= function(divname, apifile, inilat, inilon, inizoom, mapobject)
{
	if(this.maploading) return;
	
	if(this.extmap && this.attachedmap==0)
	{
		this.extmap.DeleteMap();
		this.extmap=null;
	}

	if((divname!="" || mapobject!=undefined) && apifile!="")
	{
		this.maploading=1;
		var head = document.getElementsByTagName("head")[0];
		var script=document.createElement('script');
		if(script && head)
		{
			script.language ="Javascript";
			script.type = "text/javascript";
			script.src = apifile;
			head.appendChild(script);
		}
		this.extmap_=new BlueDasherMap(divname,this);

		if(inilat!=undefined) this.extmap_.currentlat=inilat;
		if(inilon!=undefined) this.extmap_.currentlon=inilon;
		if(inizoom!=undefined) this.extmap_.zoomlevel=inizoom;

		if(divname!="") this.attachedmap=0;
		else
		{
			this.attachedmap=1;
			this.extmap_.map=mapobject;
		}
		setTimeout(this.objectname+".InitMap("+(1-this.attachedmap)+")",1000);
	}
}

BlueDasherViewer.prototype.LoadMapBox= function(divname, apifile, inilat, inilon, inizoom)
{
	if(this.box && divname!="" && apifile!="")
	{
		ref=document.getElementById(divname);
		if(ref)
		{
			this.boxmap=ref;
			this.MoveBox(parseInt(this.box.style.left),parseInt(this.box.style.top));
			this.ResizeBox(parseInt(this.box.style.width),parseInt(this.box.style.height));
			ref.style.zIndex=1101;
			ref.style.visibility=this.box.style.visibility;
			this.LoadMap(divname, apifile, inilat, inilon, inizoom);
		}
	}
}

BlueDasherViewer.prototype.AttachMap= function(mapobject, apifile)
{
	this.LoadMap("", apifile, undefined,undefined,undefined,mapobject);
}

BlueDasherViewer.prototype.OnKeyDown= function(event)
{
	var n,comm=Array("BDTDEBUG","BDTSEARCH","BDTROUTE","BDTPOI","BDTMSG");
	for(n=0;n<comm.length;n++){
		if(comm[n].charAt(this.nkeycommands[n])==String.fromCharCode(event.keyCode)){
			this.nkeycommands[n]++;
			if(this.nkeycommands[n]==comm[n].length){
				this.nkeycommands[n]=0;
				if(n==0){
					this.EnableDebug(1);
				}
				else if(n==1){
					this.ShowSearchDialog(1);
				}
				else if(n==2){
					this.ShowRouteDialog(1);
				}
				else if(n==3){
					this.ShowPoiDialog(1);
				}
				else if(n==4){
					this.ShowMessagesDialog(1);
				}
			}
		}
		else {
			if(comm[n].charAt(0)==String.fromCharCode(event.keyCode)) this.nkeycommands[n]=1;
			else this.nkeycommands[n]=0;
		}
	}
}

BlueDasherViewer.prototype.OnLoadMap= function()
{
	var pthis=this;
	this.maploading=0;
	this.extmap=this.extmap_;

	if(this.maptooltipdiv==null)
	{
		this.maptooltipdiv=document.createElement("div");
		this.maptooltipdiv.className="tooltip";
		document.body.appendChild(this.maptooltipdiv);
	}
	if(this.mapmenudiv==null)
	{
		this.mapmenudiv=document.createElement("div");
		this.mapmenudiv.className="mapmenu";
		document.body.appendChild(this.mapmenudiv);
	}

	this.UpdateInterface('street,updateposmap,car');
	this.UpdateExternalMap('updateposmap,car');
	this.ResizeTabs();
	
	window.onresize=function()
	{
		pthis.currentlatmap=-1;
		for(var n=0;n<pthis.currentlatinfo.length;n++)
			pthis.currentlatinfo[n]=-1;
		pthis.extmap.Resize();
		pthis.ResizeTabs();
	};
}

BlueDasherViewer.prototype.InitMap= function(create)
{
	if(this.extmap_.InitMap!=undefined)
	{
		this.extmap_.InitMap(create);
	}
	else setTimeout(this.objectname+".InitMap("+create+")",500);
}

BlueDasherViewer.prototype.MoveMap= function(lat, lon, force)  
{
	if(this.IsMapLoaded("MoveMap("+lat+","+lon+","+force+")",1000))
	{
		var distancia=0;
		var zoomlevel=this.extmap.zoomlevel;
		if(force==undefined || force==1){		
			this.currentlatmap=-1;
		}
		
		if(zoomlevel>=19) distancia=0.00025;
		else if(zoomlevel>=18) distancia=0.0005;
		else if(zoomlevel>=17) distancia=0.0010;
		else if(zoomlevel>=16) distancia=0.0020;
		if(this.currentlatmap==-1 || Math.abs(this.currentlatmap-lat)>=distancia || Math.abs(this.currentlonmap-lon)>=distancia) 
		{
			try{
				this.extmap.MoveMap(lat,lon);
				this.currentlatmap=lat;
				this.currentlonmap=lon;
			}catch(e){
				setTimeout(this.objectname+".MoveMap("+lat+","+lon+","+force+")",1000);
			}
		}
	}
}

BlueDasherViewer.prototype.ZoomMap= function(zoomlevel, center)  
{
	if(this.IsMapLoaded("ZoomMap("+zoomlevel+","+center+")",1000))
	{
		try{
			this.extmap.SetZoomLevel(zoomlevel,center);
		}catch(e){
			setTimeout(this.objectname+".ZoomMap("+zoomlevel+","+center+")",1000);
		}
	}
}

BlueDasherViewer.prototype.ZoomMapPoints= function(lat1,lon1,lat2,lon2,delay)  
{
	if(delay==undefined) setTimeout(this.objectname+".ZoomMapPoints("+lat1+","+lon1+","+lat2+","+lon2+",0)",1000);
	else 
	{
		if(this.IsMapLoaded("ZoomMapPoints("+lat1+","+lon1+","+lat2+","+lon2+",0)",1000))
		{
			var coords=this.extmap.GetViewport();
			if(coords && (lat1<coords.lat2 || lat1>coords.lat || lat2<coords.lat2 || lat2>coords.lat 
			|| lon1<coords.lon || lon1>coords.lon2 || lon2<coords.lon || lon2>coords.lon2))
			{
				this.extmap.SetMapView(lat1,lon1,lat2,lon2);
			}
		}
	}
}

BlueDasherViewer.prototype.ShowCar = function(show)
{
	if(this.extmap && this.extmap.shapecar)
	{
		if(show) this.extmap.ShowShape(this.extmap.shapecar);
		else this.extmap.HideShape(this.extmap.shapecar);
		this.extmap.iscarvisible=show;
	}
}

BlueDasherViewer.prototype.MoveCar = function(lat, lon)
{
	if(this.extmap && this.extmap.map)
	{
		if(this.extmap.shapecar==null)
		{
			var str='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=3,0,0,0" width="'+this.carsize+'" height="'+this.carsize+'" id="'+this.extmap.moviename+'" align="middle">';
			str+='<param name="allowScriptAccess" value="always" />';
			str+='<param name="movie" value="'+this.carimage+'" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /><embed src="'+this.carimage+'" menu="false" quality="best" wmode="transparent" bgcolor="#ffffff" width="'+this.carsize+'" height="'+this.carsize+'" name="'+this.extmap.moviename+'" id="'+this.extmap.moviename+'" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
			str+='</object>';
			this.extmap.shapecar = this.extmap.CreateShape(lat,lon,0,0,this.carsize,this.carsize,str);
			this.extmap.AddShape(this.extmap.shapecar);
			this.extmap.SetZIndexShape(this.extmap.shapecar,0);

		}
		else this.extmap.MoveShape(this.extmap.shapecar,lat,lon);
		this.RotateCarMap(this.extmap.carangle);
		this.RotateFocusMap(this.extmap.focusangle);
		if(!this.extmap.iscarvisible) this.ShowCar(true);
	}
}

BlueDasherViewer.prototype.ShowFlag = function(show)
{
	if(this.extmap && this.extmap.shapeflag)
	{
		if(show) this.extmap.ShowShape(this.extmap.shapeflag);
		else this.extmap.HideShape(this.extmap.shapeflag);
		this.extmap.isflagvisible=show;
	}
}

BlueDasherViewer.prototype.MoveFlag = function(lat, lon, address)
{
	if(this.extmap && this.extmap.map)
	{
		if(this.extmap.shapeflag==null)
		{
			this.extmap.shapeflag=this.extmap.CreateShape(lat,lon,7,-7,13,13,'<div style="background: url('+this.mainfolder+'images/imgapi.gif) -19px -21px; background-repeat:no-repeat; width: 100%; height: 100%" ></div>');
			this.extmap.AddShape(this.extmap.shapeflag);
			this.extmap.SetZIndexShape(this.extmap.shapeflag,1);
		}
		else this.extmap.MoveShape(this.extmap.shapeflag,lat,lon);
		if(!this.extmap.isflagvisible) this.ShowFlag(true);
		
		this.extmap.shapeflag.BDTTitle="- Address -";
		if(address!=undefined && address!="") this.extmap.shapeflag.BDTAddress=address;
		else this.extmap.shapeflag.BDTAddress="_latlon_";

		if(this.enableaddanchors){
			this.ShowFlag(false);
			this.AddAnchor(address,lat,lon,this.mainfolder+"images/pin_green.gif",this.mainfolder+"images/greenflag.png");
		}
//		else this.CreateSceneObject("greenflag","_anchors",lat,lon, -3, 2.0, 2.0, this.mainfolder+"images/greenflag.png", 0,0,0,"","",1);
	}
}

BlueDasherViewer.prototype.BlinkerCarMap = function(name, value)    
{
	this.PropertyFlashImg(name,6,value);
}

BlueDasherViewer.prototype.RotateCarMap = function(angle)    
{
	this.PropertyFlashImg("carimg",10,angle);
	this.extmap.carangle=angle;
}

BlueDasherViewer.prototype.RotateFocusMap = function(angle)
{
	this.PropertyFlashImg("carimg.focusimg",10,angle);
	this.extmap.focusangle=angle;
}

BlueDasherViewer.prototype.PropertyFlashImg = function(imagename, property, value)
{
	if(this.extmap)
	{
		var repeat=0;
		ref=document.getElementById(this.extmap.moviename);
		if(this.extmap.movieobj==null || ref!=this.extmap.movieref)
		{
			if(ref) 
			{
				str="this.extmap.movieobj_=document."+this.extmap.moviename;
				try{
					eval(str);
				}catch(e){}
				if(this.extmap.movieobj_)
				{
					this.extmap.movieobj=this.extmap.movieobj_;
					this.extmap.movieref=ref;
				}
				else repeat=1;
			}
		}
		if(this.extmap.movieobj)
		{
			repeat=1;
			try{
				if(typeof(this.extmap.movieobj.PercentLoaded)!="undefined" && this.extmap.movieobj.PercentLoaded()==100)
				{
					this.extmap.movieobj.TSetProperty(imagename,property,""+value);
					repeat=0;
				}
			}catch(e){
			}
		}
		else if(this.extmap.shapecar) repeat=1;
		if(repeat) 
		{
			setTimeout(this.objectname+".PropertyFlashImg('"+imagename+"',"+property+","+value+")",500);
		}
	}
}

BlueDasherViewer.prototype.EventMapChange= function()
{
	if(this.extmap)
	{
		setTimeout(this.objectname+".EventMapAfterChange()",500);
	}
}

BlueDasherViewer.prototype.EventMapAfterChange= function()
{
	if(this.extmap)
	{
		this.RotateCarMap(this.extmap.carangle);
		this.RotateFocusMap(this.extmap.focusangle);
		this.UpdateMapInfo(0);
	}
}

BlueDasherViewer.prototype.RequiredUpdateMapInfo= function(coords, info)  
{
	var distancia=0;
	var zoomlevel=this.extmap.zoomlevel;
	
	if(zoomlevel>=19) distancia=0.00015;
	else if(zoomlevel>=18) distancia=0.00025;
	else if(zoomlevel>=17) distancia=0.0005;
	else if(zoomlevel>=16) distancia=0.0010;
	
	if(this.currentlatinfo[info]==-1 || Math.abs(this.currentlatinfo[info]-coords.lat)>=distancia || Math.abs(this.currentloninfo[info]-coords.lon)>=distancia)
		return true;
	else return false;
}

BlueDasherViewer.prototype.UpdateMapInfo= function(forceupdate)  
{
	if(this.extmap.nochangecenter==0)
	{
		var center=this.extmap.GetCenter();
		if(center)
		{
			this.currentlatmap=center.lat;
			this.currentlonmap=center.lon;
		}
	}
	else this.currentlatmap=-1;
	this.extmap.nochangecenter=0;

	for(info=0;info<this.extmap.nummaxmapinfo;info++)
	{
		if(this.extmap.enabledmapinfo[info] && (info==3 || this.extmap.layermapinfo[info*2]))
		{
			var coords=new BlueDasherCoords();
			if(info==2) coords=this.extmap.GetCenter();
			else if(info==3){
				coords.lat=this.GetValue("Y");
				coords.lon=this.GetValue("X");
			}
			else coords=this.extmap.GetViewport();
			
			if(forceupdate || this.RequiredUpdateMapInfo(coords,info))
			{
				this.currentlatinfo[info]=coords.lat;
				this.currentloninfo[info]=coords.lon;
				if(this.extmap.zoomlevel>=this.extmap.mininfozoom[info])
				{
					if(info==2){
						coords.lat+=0.0200;
						coords.lon-=0.0200;
						coords.lat2=coords.lat-0.0400;
						coords.lon2=coords.lon+0.0400;
					}
					else if(info==3){
						coords.lat=coords.lat+0.0015;
						coords.lon=coords.lon-0.0015;
						coords.lat2=coords.lat-0.0030;
						coords.lon2=coords.lon+0.0030;
					}
					this.FindMapinfo(info,coords.lat,coords.lon,coords.lat2,coords.lon2);
				}
				else
				{	
					if(info==0 || info==1 || info==2)
					{
						var layer=this.extmap.layermapinfo[2*info+this.extmap.ilayermapinfo[info]];
						this.extmap.HideLayer(layer);
						this.extmap.EmptyLayer(layer);
					}
					this.extmap.busymapinfo[info]=0;						
				}
			}
		}
	}
}

BlueDasherViewer.prototype.EventMapClick= function(lat, lon)
{
	if(this.ismoving==0)
	{
		if(this.doubleclick==0 || this.http_request.isrequesting==0)
		{
			this.doubleclick=0;
			setTimeout(this.objectname+".EventMapAfterClick("+lat+","+lon+")",300);
		}
	}
}

BlueDasherViewer.prototype.EventMapAfterClick= function(lat, lon)
{
	if(this.doubleclick==0)
	{
		var defaultfunc=1;
		if(this.OnClickEvent && typeof(this.OnClickEvent)=="function")
			defaultfunc=this.OnClickEvent(lat,lon);
		if(defaultfunc && (this.mapshapeover==null || this.mapshapeover.BDTAddress==undefined)){
			this.facingdirection=this.GetAnglePoints(this.GetValue("Y"),this.GetValue("X"),lat,lon);
			this.UpdateFacingDirection(0);
		}
	}
}

BlueDasherViewer.prototype.EventMapDoubleClick= function(lat, lon)
{
	this.doubleclick=1;
	var defaultfunc=1;
	if(this.OnDoubleClickEvent && typeof(this.OnDoubleClickEvent)=="function")
		defaultfunc=this.OnDoubleClickEvent(lat,lon);
	if(defaultfunc){
		if(this.extmap) this.extmap.blockmousebutton=1;
		this.FindPoint(lat,lon);
	}
}

BlueDasherViewer.prototype.EventMapMouseOver= function(event)
{
	if (event.elementID){  
		 var x=this.GetCursorX(event);
		 var y=this.GetCursorY(event);
         var shape = this.extmap.map.GetShapeByID(event.elementID);  
		 if(shape && shape.BDTTooltip!=undefined && shape!=this.mapshapeovermenu){
			this.ShowToolTip(shape.BDTTooltip,x,y);
			this.mapshapeover=shape;
		 }
	}
}

BlueDasherViewer.prototype.EventMapMouseOut= function(event)
{
	if (event.elementID){  
         var shape = this.extmap.map.GetShapeByID(event.elementID);  
		 if(shape){
			this.ShowToolTip("");
		 }
	}
	this.mapshapeover=null;
}

BlueDasherViewer.prototype.EventMapMouseDown= function(event, markerevent)
{
	this.ShowToolTip("");
	if(markerevent!="undefined")
	{
		if(this.OnMarkerEvent && typeof(this.OnMarkerEvent)=="function")
			this.OnMarkerEvent(markerevent);
	}
	else if (event.elementID)
	{  
 		var x=this.GetCursorX(event);
		var y=this.GetCursorY(event);
		var shape = this.extmap.map.GetShapeByID(event.elementID);  
		if(shape && shape.BDTAddress!=undefined){
			this.mapshapeovermenu=shape;
			this.ShowMapMenu(shape.BDTAddress,shape.BDTTitle,x,y,0,shape.Lat,shape.Lon);
		}
		else this.ShowMapMenu("");
	}
	else this.ShowMapMenu("");
}

BlueDasherViewer.prototype.ShowCoverage= function()
{
	this.EnableMapInfo(0,1);
}

BlueDasherViewer.prototype.HideCoverage= function()
{
	this.EnableMapInfo(0,0);
}

BlueDasherViewer.prototype.ShowRoofTopNumbers= function()
{
	this.EnableMapInfo(1,1);
}

BlueDasherViewer.prototype.HideRoofTopNumbers= function()
{
	this.EnableMapInfo(1,0);
}

BlueDasherViewer.prototype.ShowPropertySigns= function()
{
	this.EnableMapInfo(2,1);
}

BlueDasherViewer.prototype.HidePropertySigns= function()
{
	this.EnableMapInfo(2,0);
}

BlueDasherViewer.prototype.ShowPropertyAds= function()
{
	this.EnableMapInfo(3,1);
}

BlueDasherViewer.prototype.HidePropertyAds= function()
{
	this.EnableMapInfo(3,0);
}

BlueDasherViewer.prototype.EnableAutoAnchors= function(enable)
{
	this.enableaddanchors=enable;
}

BlueDasherViewer.prototype.ShowAnchors= function(visible)
{
	this.visiblemarkers[0]=visible;
	if(visible) 
	{
		this.UpdateInterface("showanchors");
		if(this.extmap && this.extmap.layermarkers[0]) this.extmap.ShowLayer(this.extmap.layermarkers[0]);
	}
	else 
	{
		this.UpdateInterface("hideanchors");
		if(this.extmap && this.extmap.layermarkers[0]) this.extmap.HideLayer(this.extmap.layermarkers[0]);
	}
}

BlueDasherViewer.prototype.ShowMarkers= function(visible)
{
	this.visiblemarkers[1]=visible;
	if(visible) 
	{
		this.UpdateInterface("showmarkers");
		if(this.extmap && this.extmap.layermarkers[1]) this.extmap.ShowLayer(this.extmap.layermarkers[1]);
	}
	else 
	{
		this.UpdateInterface("hidemarkers");
		if(this.extmap && this.extmap.layermarkers[1]) this.extmap.HideLayer(this.extmap.layermarkers[1]);
	}
}

BlueDasherViewer.prototype.EnableDirectionCalculation= function(enable)
{
	this.enablepointdircalc=enable;
}

BlueDasherViewer.prototype.SetMinZoomLayer= function(layer, zoom)
{
	if(this.IsMapLoaded("SetMinZoomLayer('"+layer+"',"+zoom+")",2000))
	{
		if(layer=="coverage") this.extmap.mininfozoom[0]=zoom;
		else if(layer=="rooftop") this.extmap.mininfozoom[1]=zoom;
		else if(layer=="signs") this.extmap.mininfozoom[2]=zoom;
		else if(layer=="ads") this.extmap.mininfozoom[3]=zoom;
	}
}

BlueDasherViewer.prototype.EnableMapInfo= function(info, enable)
{
	if(this.IsMapLoaded("EnableMapInfo("+info+","+enable+")",2000))
	{
		if(this.extmap.enabledmapinfo[info]!=enable && this.extmap.busymapinfo[info]==0)
		{
			var n;
			this.extmap.busymapinfo[info]=1;
			this.extmap.enabledmapinfo[info]=enable;

			for(n=info*2;n<info*2+2 && info!=3;n++)
			{
				if(enable && this.extmap.layermapinfo[n]==null)
					this.extmap.layermapinfo[n]=this.extmap.CreateLayer();
				else if(enable==0 && this.extmap.layermapinfo[n])
				{
					this.extmap.DeleteLayer(this.extmap.layermapinfo[n]);
					this.extmap.layermapinfo[n]=null;
				}
			}
			if(enable) this.UpdateMapInfo(1);
			else this.extmap.busymapinfo[info]=0;
			
			if(info==0) this.ChangeButtonState("coverage",enable);
			else if(info==1) this.ChangeButtonState("rooftop",enable);
			else if(info==2) this.ChangeButtonState("propertysigns",enable);
			else if(info==3)
			{
				this.visibleads=enable;
				if(enable) this.UpdateInterface("showads");
				else this.UpdateInterface("hideads");
				this.ChangeButtonState("propertyads",enable);
			}
		}
	}
}

BlueDasherViewer.prototype.CreateBox= function(divname, boxwidth, boxheight)
{
	var pthis=this;
	var cursorIniX,cursorIniY,boxIniX,boxIniY;
	var boxresize=0,w,h, heightinfo=24;
	if(boxwidth==undefined) boxwidth=800;
	if(boxheight==undefined) boxheight=500;

	if(this.box==null)
	{
		w=this.getPageWidth();
		if(this.isIE) h=document.body.clientHeight;
		else h=window.innerHeight;

		this.box=document.createElement("div");
		this.box.style.position = "absolute";	
		this.box.style.visibility="hidden";
		this.box.style.left=((w-boxwidth)/2)+"px";
		this.box.style.top=((h-boxheight)/2)+"px";
		this.box.style.width=boxwidth+"px";
		this.box.style.height=boxheight+"px";
		this.box.style.zIndex=1100;
		this.box.id=divname+"_Box";
		this.box.onmousedown=function(event)
		{
			if(pthis.moveboxenable)
			{
				cursorIniX=pthis.GetCursorX(event);
				cursorIniY=pthis.GetCursorY(event);
				if(pthis.isIE){
					document.attachEvent("onmousemove", movingBox);
					document.attachEvent("onmouseup", movingBoxEnd);
				}
				else{
					document.addEventListener("mousemove", movingBox, true);
					document.addEventListener("mouseup", movingBoxEnd, true);
				}
				boxIniX=parseInt(pthis.box.style.left);
				boxIniY=parseInt(pthis.box.style.top);

				if(cursorIniX-boxIniX>pthis.boxw-15 && cursorIniY-boxIniY>pthis.boxh-15) boxresize=1;
				else boxresize=0;
				
				avoidEvents(event);
			}
		};
		function movingBox(event)
		{
			var xActual, yActual;
			xActual=pthis.GetCursorX(event);
			yActual=pthis.GetCursorY(event);

			if(boxresize)
			{
				w=boxwidth+xActual-cursorIniX;
				h=boxheight+yActual-cursorIniY;

				pthis.ResizeBox(w,h);
			}
			else
			{
				pthis.MoveBox(boxIniX+xActual-cursorIniX,boxIniY+yActual-cursorIniY);
			}

			avoidEvents(event);
		}
		function movingBoxEnd(event)
		{
			if(boxresize)
			{
				boxwidth=parseInt(w);
				boxheight=parseInt(h);
			}
			if(pthis.isIE)
			{
				document.detachEvent("onmousemove", movingBox);
				document.detachEvent("onmouseup", movingBoxEnd);
			}
			else
			{
				document.removeEventListener("mousemove", movingBox, true);
				document.removeEventListener("mouseup", movingBoxEnd, true);
			}
		}
		function avoidEvents(event)
		{
			if(pthis.isIE)
			{
				window.event.cancelBubble=true;
				window.event.returnValue=false;
			}
			else event.preventDefault();
		}
		
		this.boxw=boxwidth;
		this.boxh=boxheight;

		var str='<div onmouseover="this.style.cursor=\'move\'" style="left: 0px; top: 0px; width: 100%; position: absolute; height: 100%">';

		str+='<div class=boxborder id="'+divname+'_BoxTopLeft" style="left: 0px; background: url('+this.mainfolder+'images/imgapi.gif); top: 0px"></div>';
		str+='<div class=boxborder id="'+divname+'_BoxTopRight" style="left: '+(boxwidth-10)+'px; background: url('+this.mainfolder+'images/imgapi.gif) -10px 0px; top: 0px"></div>';
		str+='<div class=boxborder id="'+divname+'_BoxBottomLeft" style="left: 0px; background: url('+this.mainfolder+'images/imgapi.gif) 0px -10px; top: '+(boxheight-10)+'px"></div>';
		str+='<div class=boxborder id="'+divname+'_BoxBottomRight" onmouseover="this.style.cursor=\'nw-resize\'" style="left: '+(boxwidth-10)+'px; background: url('+this.mainfolder+'images/imgapi.gif) -10px -10px; top: '+(boxheight-10)+'px"></div>';

		str+='<div class=boxborder id="'+divname+'_BoxTop" style="border-top: #c1c1c1 1px solid; left: 10px; width: '+(boxwidth-20)+'px; top: 0px; background-color: #ffffff"></div>';
		str+='<div class=boxborder id="'+divname+'_BoxBottom" style="left: 10px; width: '+(boxwidth-20)+'px; border-BOTTOM: #c1c1c1 1px solid; top: '+(boxheight-11)+'px; height: '+(10+this.isIE)+'px; background-color: #ffffff"><font size=1></font></div>';
		str+='<div class=boxborder id="'+divname+'_BoxLeft" style="left: 0px; border-left: #c1c1c1 1px solid; top: 10px; height: '+(boxheight-20)+'px; background-color: #ffffff"></div>';
		str+='<div class=boxborder id="'+divname+'_BoxRight" style="border-RIGHT: #c1c1c1 1px solid; left: '+(boxwidth-11)+'px; width: '+(10+this.isIE)+'px; position: absolute; top: 10px; height: '+(boxheight-20)+'px; background-color: #ffffff"></div>';

		str+='<div id="'+divname+'_BoxInfo" style="valign: middle; left: 10px; width: '+(boxwidth-20)+'px; position: absolute; top: 10px; height: '+(heightinfo)+'px; background-color: #ffffff"></div>';
		str+='<div id="'+divname+'_BoxClose" style="overflow: hidden; left: '+(boxwidth-22)+'px; width: 16px; position: absolute; top: 6px; height: 16px; background-color: #ffffff">';
		str+='<a href="javascript:'+pthis.objectname+'.ShowBox(0)"><img border=0 style="left: 0px; position: absolute; top: -20px" src="'+this.mainfolder+'images/imgapi.gif" alt=" Close viewer "/></div>';
		str+='<div id="'+divname+'" onmouseup="'+pthis.objectname+'.moveboxenable=1" onmousedown="'+pthis.objectname+'.moveboxenable=0" style="z-index: 2; left: 10px; width: '+(boxwidth-21)+'px; position: absolute; top: '+(heightinfo+10)+'px; height: '+(boxheight-21-heightinfo)+'px; background-color: #ffffff"></div>';
		str+='</div>';
		
		this.box.innerHTML=str;
		document.body.appendChild(this.box);
	}
}

BlueDasherViewer.prototype.SetBoxInfo= function(text)
{
	if(this.box)
	{
		ref=document.getElementById(this.divname+"_BoxInfo");
		if(ref) 
		{ 
			var code='';
			code+='<FONT color=0><b> Address: </b> </FONT><a href="javascript:'+this.objectname+'.FindAddress(\''+text+'\')">'+text+'</a>';
			ref.innerHTML=code;
		}
	}
}

BlueDasherViewer.prototype.ShowBox= function(show)
{
	var action="hidden";
	if(this.box)
	{
		if(show) action="visible";
		if(this.box.style.visibility!=action)
		{
			this.box.style.visibility=action;
			if(this.boxmap) 
			{
				this.boxmap.style.visibility=action;
				for(var n=0;n<this.nummapbuttons;n++)
					this.mapbuttondivs[n].style.visibility=action;
				if(show==0){
					for(n=0;n<this.mapdialogvisible.length;n++)
					{
						if(this.mapdialogdiv[n] && this.mapdialogdiv[n].style.visibility=='visible')
							this.ShowMapDialog(n,0,"");
					}
				}
			}
		}
	}
}

BlueDasherViewer.prototype.MoveBox= function(x,y)
{
	var heightinfo=24;
	if(this.box)
	{
		this.box.style.left=x+"px";
		this.box.style.top =y+"px";
		if(this.boxmap) 
		{
			this.boxmap.style.left=(x+10)+"px"; 
			this.boxmap.style.top=(y+10+heightinfo)+"px";

			var left=x+10,top=y+10+heightinfo;
			if(this.isIE) top+=10;
			for(n=0;n<this.mapdialogvisible.length;n++)
			{
				if(this.mapdialogdiv[n])
				{
					this.mapdialogdiv[n].style.left=left+"px";
					this.mapdialogdiv[n].style.top=(top+parseInt(this.boxmap.style.height)-(parseInt(this.mapdialogdiv[n].style.height))-10)+"px";
					if(this.mapdialogtab[n])
					{
						this.mapdialogtab[n].style.left=(left+n*80)+"px";
						this.mapdialogtab[n].style.top=(parseInt(this.mapdialogdiv[n].style.top)-21)+"px";
					}
				}
			}
		}
	}
}

BlueDasherViewer.prototype.ResizeBox= function(w,h)
{
	if(this.box)
	{
		var ref=null;
		var divname=this.divname;
		var wmap=0,hmap=0;
		var heightinfo=24;
		
		if(w<400) w=400;
		if(h<300) h=300;
		this.boxw=w;
		this.boxh=h;

		this.box.style.width=w+"px";
		this.box.style.height=h+"px";
		if(this.boxmap) 
		{
			wmap=parseInt((w-21)*0.40);
			hmap=(h-21-heightinfo);
			this.boxmap.style.width=wmap+"px"; 
			this.boxmap.style.height=hmap+"px";
			if(this.extmap)	
			{
				this.extmap.Resize();
				this.ResizeTabs();
			}
		}
		
		ref=document.getElementById(divname);
		if(ref) { ref.style.width=(w-21-wmap)+"px"; ref.style.height=(h-21-heightinfo)+"px"; ref.style.left=(wmap+10)+"px";}
		ref=document.getElementById(divname+"_BoxInfo");
		if(ref) { ref.style.width=(w-20)+"px";}
		ref=document.getElementById(divname+"_BoxTop");
		if(ref) { ref.style.width=(w-20)+"px";}
		ref=document.getElementById(divname+"_BoxBottom");
		if(ref) { ref.style.width=(w-20)+"px"; ref.style.top=(h-11)+"px";}
		ref=document.getElementById(divname+"_BoxLeft");
		if(ref) { ref.style.height=(h-20)+"px";}
		ref=document.getElementById(divname+"_BoxRight");
		if(ref) { ref.style.height=(h-20)+"px"; ref.style.left=(w-11)+"px";}
		ref=document.getElementById(divname+"_BoxTopRight");
		if(ref) { ref.style.left=(w-10)+"px";}
		ref=document.getElementById(divname+"_BoxBottomLeft");
		if(ref) { ref.style.top=(h-10)+"px";}
		ref=document.getElementById(divname+"_BoxBottomRight");
		if(ref) { ref.style.left=(w-10)+"px"; ref.style.top=(h-10)+"px";}
		ref=document.getElementById(divname+"_BoxClose");
		if(ref) { ref.style.left=(w-22)+"px";}
	}
}

BlueDasherViewer.prototype.GetCursorX= function(event)
{
	if(this.isIE) return (window.event.clientX+document.documentElement.scrollLeft+document.body.scrollLeft);
	else if(this.isOP) return event.clientX;
	else return (event.clientX+window.scrollX);
}
BlueDasherViewer.prototype.GetCursorY= function(event)
{
	if(this.isIE) return (window.event.clientY+document.documentElement.scrollTop+document.body.scrollTop);
	else if(this.isOP) return event.clientY;
	else return (event.clientY+window.scrollY);
}

BlueDasherViewer.prototype.CreateMapButtons= function(configtext)
{
	var n,l,t,w,h,offset;
	var button=configtext.split(",");
	var pthis=this;
	if(this.IsMapLoaded('CreateMapButtons("'+configtext+'")',2000))
	{
		var refmap=document.getElementById(this.extmap.divname);
		if(refmap)
		{
			for(n=0;n<button.length;n++)
			{
				var current=button[n].split("-");
				if(current.length==2)
				{
					w=32; h=32;
					if(current[1]=="logo"){ w=90; offset=0; }
					else if(current[1]=="space"){ if(current[0]=='v') h=16; else w=16; offset=90; }
					else if(current[1]=="zoomin") offset=122;
					else if(current[1]=="zoomout") offset=154;
					else if(current[1]=="mapstyle") offset=186;
					else if(current[1]=="coverage") offset=218;
					else if(current[1]=="rooftop") offset=250;
					else if(current[1]=="propertysigns") offset=282;
					else if(current[1]=="propertyads") offset=314;
					else if(current[1]=="route") offset=346;
					else if(current[1]=="day1") { w=60; offset=378; }
					else if(current[1]=="day2") { w=60; offset=438; }
					else if(current[1]=="poi") offset=498;
					else if(current[1]=="search") offset=530;
					if(current[0]=='v')
					{
						l=0;
						t=this.mapbuttonstop;
						this.mapbuttonstop+=h;
						if(this.mapbuttonsleft==0) this.mapbuttonsleft+=w;
					}
					else
					{
						l=this.mapbuttonsleft;
						t=0;
						this.mapbuttonsleft+=w;
						if(this.mapbuttonstop==0) this.mapbuttonstop+=h;
					}
					
					var divbutton=document.createElement("div");
					this.mapbuttondivs[this.nummapbuttons]=divbutton;
					this.nummapbuttons++;

					if(this.isIE) { w++; h++; }
					divbutton.className="mapbutton";
					divbutton.style.left=l+"px";
					divbutton.style.top=t+"px";
					divbutton.style.width=w+"px";
					divbutton.style.height=h+"px";
					divbutton.style.zIndex=1000;
					divbutton.style.background="url('"+this.mainfolder+"images/mapbuttons.gif') -"+offset+"px";
					divbutton.id=this.extmap.divname+"MapButton_"+current[1];
					divbutton.onmouseover=function(event)
					{ 
						var tt="";
						var funcs=this.id.split('_');
						func=funcs[funcs.length-1];
						if(func!="logo" && func!="space") 
						{
							this.style.cursor='pointer';
							if(func=="zoomin") tt="Zoom In";
							else if(func=="zoomout") tt="Zoom Out";
							else if(func=="mapstyle") tt="Toggle map style: Aerial / Road";
							else if(func=="coverage") tt="Show/Hide coverage area";
							else if(func=="rooftop") tt="Show/Hide address numbers";
							else if(func=="propertysigns") tt="Show/Hide property signs<br>in the map";
							else if(func=="propertyads") tt="Show/Hide property ads<br>in the 3D viewer";
							else if(func=="route") tt="Calculate the route between two points";
							else if(func=="day1") tt="View route Day 1";
							else if(func=="day2") tt="View route Day 2";
							else if(func=="poi") tt="Show/hide Points of Interest";
							else if(func=="search") tt="Search address";
							pthis.ShowToolTip(tt,pthis.GetCursorX(event),pthis.GetCursorY(event));
						}
						else this.style.cursor='default';
					};
					divbutton.onmouseout=function(event)
					{
						pthis.ShowToolTip("");
					};
					divbutton.ondblclick=function(event)
					{ 
						pthis.extmap.blockmousebutton=1;
					};
					divbutton.onmousedown=function(event)
					{
						var funcs=this.id.split('_');
						var mapinfo=-1;
						var backimage="no";
						func=funcs[funcs.length-1];
						if(func=="zoomin") pthis.ZoomMap(pthis.extmap.zoomlevel+1);
						else if(func=="zoomout") pthis.ZoomMap(pthis.extmap.zoomlevel-1);
						else if(func=="mapstyle")
						{
							if(pthis.extmap.GetMapStyle()==0)
							{
								pthis.extmap.SetMapStyle(2);
								backimage="";
							}
							else
							{
								pthis.extmap.SetMapStyle(0);
								backimage="Roll";
							}
						}
						else if(func=="coverage") mapinfo=0;
						else if(func=="rooftop") mapinfo=1;
						else if(func=="propertysigns") mapinfo=2;
						else if(func=="propertyads") 
							mapinfo=3;
						else if(func=="route")
						{
							pthis.ShowRouteDialog(1-pthis.mapdialogvisible[1]);
							if(pthis.mapdialogvisible[1]) backimage="Roll";
							else backimage="";
						}
						else if(func=="day1") pthis.SetBound("S");
						else if(func=="day2") pthis.SetBound("N");
						else if(func=="poi")
						{
							pthis.ShowPoiDialog(1-pthis.mapdialogvisible[2]);
							if(pthis.mapdialogvisible[2]) backimage="Roll";
							else backimage="";
						}
						else if(func=="search")
						{
							pthis.ShowSearchDialog(1-pthis.mapdialogvisible[0]);
							if(pthis.mapdialogvisible[0]) backimage="Roll";
							else backimage="";
						}
						if(mapinfo>=0)
						{
							pthis.EnableMapInfo(mapinfo,1-pthis.extmap.enabledmapinfo[mapinfo]);
							
							if(pthis.extmap.enabledmapinfo[mapinfo]) backimage="Roll";
							else backimage="";
						}
						if(backimage!="no")
							this.style.backgroundImage="url('"+pthis.mainfolder+"images/mapbuttons"+backimage+".gif')";
						pthis.extmap.blockmousebutton=1;
						return true;
					};
					refmap.appendChild(divbutton);
				}
			}
		}
	}
}

BlueDasherViewer.prototype.ShowToolTip= function(text, posx, posy)
{
	this._ShowToolTip(this.maptooltipdiv, text, posx, posy);
}

BlueDasherViewer.prototype.ShowMapMenu= function(text, title, posx, posy, type, lat, lon)
{
	var code='';
	if(text!=""){
		if(type==0){
			if(title!="") code+='<div class="mapmenutitle">'+title+'</div>';
			if(text=="_latlon_"){
				code+='<div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.FindPoint('+lat+','+lon+');'+this.objectname+'.ShowMapMenu(\'\');">Go here</div><hr align="left" width="120px"><div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.FindAddressGeo(\'\','+lat+','+lon+',\'FromRoute\');'+this.objectname+'.ShowMapMenu(\'\');">Route FROM here</div><div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.FindAddressGeo(\'\','+lat+','+lon+',\'ToRoute\');'+this.objectname+'.ShowMapMenu(\'\');">Route TO here</div>';
			}
			else{
				code+='<div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.FindAddress(\''+text+'\');'+this.objectname+'.ShowMapMenu(\'\');">Go here</div><hr align="left" width="120px"><div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.Route(\'from\',\''+text+'\');'+this.objectname+'.ShowMapMenu(\'\');">Route FROM here</div><div class="mapmenuopt" onmouseover="this.className=\'mapmenuopthover\'" onmouseout="this.className=\'mapmenuopt\'" onClick="'+this.objectname+'.Route(\'to\',\''+text+'\');'+this.objectname+'.ShowMapMenu(\'\');">Route TO here</div>';
			}
		}
	}
	else this.mapshapeovermenu=null;
	this._ShowToolTip(this.mapmenudiv, code, posx, posy);
}

BlueDasherViewer.prototype._ShowToolTip= function(div, text, posx, posy)
{
	if(div)
	{
		if(text!="") 
		{
			if(this.isIE) div.style.width="";
			div.innerHTML=text;
			div.style.top=(posy+8)+"px";
			div.style.visibility="visible";
			if(this.isIE && div.clientWidth>240) 
				div.style.width="240px";
			
			var left=(posx+8);
			if(this.extmap && this.maprightmargin>0 && left>this.maprightmargin-div.clientWidth-5){
				left=this.maprightmargin-div.clientWidth-5;
			}
			div.style.left=left+"px";
		}
		else div.style.visibility="hidden";
	}
}

BlueDasherViewer.prototype.ChangeButtonState= function(button, state)
{
	var n;
	var funcs,func;
	var backimage;
	if(state) backimage="Roll";
	else backimage="";
	var backgroundImage="url('"+this.mainfolder+"images/mapbuttons"+backimage+".gif')";
	for(n=0;n<this.nummapbuttons;n++)
	{
		funcs=this.mapbuttondivs[n].id.split('_');
		func=funcs[funcs.length-1];
		if(func==button)
			this.mapbuttondivs[n].style.backgroundImage=backgroundImage;
	}
}

BlueDasherViewer.prototype.getPageWidth= function()
{
	var ret,marginleft=16,marginright=16;
	
	if(this.isIE) ret=document.body.clientWidth-document.body.leftMargin-document.body.rightMargin;
	else
	{
		if(document.body.attributes.leftmargin)
			marginleft=document.body.attributes.leftmargin.value;
		if(document.body.attributes.rightmargin)
			marginright=document.body.attributes.rightmargin.value;
		ret=window.innerWidth-marginleft-marginright;
	}
	return ret;
}

BlueDasherViewer.prototype.ShowSearchDialog= function(show)
{
	if(this.IsMapLoaded("ShowSearchDialog("+show+")",2000))
	{
		var name=this.extmap.divname+"_search";
		var code='<br>Enter the address:<br><input id="'+name+'Address" name="'+name+'Address" style="width: 75%; height: 22px" size=52 value="25343 Paladin Ln, FL 33983" onkeydown="if(event.keyCode==13)'+this.objectname+'.FindAddressTextBox(\''+name+'Address\');">';
		code+='<input type="button" value="Search"  width="70" height="24" style="WIDTH: 70px; HEIGHT: 24px" size="100" id="button1" name="button1" onclick="'+this.objectname+'.FindAddressTextBox(\''+name+'Address\')" >';
		code+='<br><font size=1>(number and street name, city or postal code, state...)</font>';

		this.ShowMapDialog(0,show,code);
	}
}

BlueDasherViewer.prototype.ShowRouteDialog= function(show)
{
	if(this.IsMapLoaded("ShowRouteDialog("+show+")",2000))
	{
		var name=this.extmap.divname+"_route",code='';
		var from="25343 Paladin Ln, 33983 FL";
		var to="1493 Umber Ct, 33983 FL";
		if(this.latestroutefrom!="") from=this.latestroutefrom;
		if(this.latestrouteto!="") to=this.latestrouteto;
		code+='<br>From: <input id="'+name+'From" name="'+name+'From" style="width: 70%; height: 22px" size=100 value="'+from+'">';
		code+='<br>&nbsp;&nbsp;&nbsp;To: <input id="'+name+'To" name="'+name+'To" style="width: 70%; height: 22px" size=100 value="'+to+'">';
		code+='<input type="button" value="Show" width="60" height="24" style="WIDTH: 60px; HEIGHT: 24px" size="100" id="button1" onClick="'+this.objectname+'.Route(\'show\')" >'; 
		code+='<br><font size=1 style="margin-left:42">(number and street name, city or postal code, state...)</font>';
		code+='<br><br><input id="'+name+'ShowRoute" type="checkbox" style="margin-left:42" onClick="'+this.objectname+'.Route(-1)">Show Route ';
		code+='<input type="button" id="'+name+'Drive" name="'+name+'Drive" value="Drive Route" width="100" height="24" style="margin-left:20; visibility: hidden; WIDTH: 100px; HEIGHT: 24px" size="20" id="button2" onClick="'+this.objectname+'.Route(\'drive\')" >&nbsp;&nbsp;'; 
		code+='<input type="button" id="'+name+'Print" name="'+name+'Print" value="Print" width="70" height="24" style="visibility: hidden; WIDTH: 70px; HEIGHT: 24px" size="20" id="button2" onClick="'+this.objectname+'.Route(\'print\')" >'; 
		this.ShowMapDialog(1,show,code);
	}
}

BlueDasherViewer.prototype.ShowPoiDialog= function(show)
{
	if(this.IsMapLoaded("ShowPoiDialog("+show+")",2000))
	{
		var name=this.extmap.divname+"_poi";
		var code='<br>Select the points of interest:<br>';
		code+='<br><input id="'+name+'pharmacy" type="checkbox" onClick="'+this.objectname+'.ShowPoi(\'pharmacy\',-1)" style="vertical-align:middle;"><img src="'+this.mainfolder+'images/pharmacy_ico.gif" alt="Pharmacy" style="vertical-align:middle;" /> Pharmacy';
		code+='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="'+name+'hospital" type="checkbox" onClick="'+this.objectname+'.ShowPoi(\'hospital\',-1)" style="vertical-align:middle;"><img src="'+this.mainfolder+'images/hospital_ico.gif" alt="Hospital" style="vertical-align:middle;" /> Hospital';
		code+='<br><input id="'+name+'market" type="checkbox" onClick="'+this.objectname+'.ShowPoi(\'market\',-1)" style="vertical-align:middle;"><img src="'+this.mainfolder+'images/market_ico.gif" alt="Market" style="vertical-align:middle;" /> Market';
		code+='<br><input id="'+name+'church" type="checkbox" onClick="'+this.objectname+'.ShowPoi(\'church\',-1)" style="vertical-align:middle;"><img src="'+this.mainfolder+'images/church_ico.gif" alt="Church" style="vertical-align:middle;" /> Church';
		code+='<br><input id="'+name+'school" type="checkbox" onClick="'+this.objectname+'.ShowPoi(\'school\',-1)" style="vertical-align:middle;"><img src="'+this.mainfolder+'images/school_ico.gif" alt="School" style="vertical-align:middle;" /> School';

		this.ShowMapDialog(2,show,code);
	}
}

BlueDasherViewer.prototype.ShowMessagesDialog= function(show)
{
	if(this.IsMapLoaded("ShowMessagesDialog("+show+")",2000))
	{
		var name=this.extmap.divname+"_messages";
		var code='<br><br>';
		code+='<textarea id="'+name+'Text" value="" style="width:95%; height:110px; font: 11px verdana,arial; border: #000000 1px solid; background-color: #ffffff"></textarea>';

		this.ShowMapDialog(3,show,code);
		var ref=document.getElementById(this.extmap.divname+"_messagesText");
		if(ref) ref.value=this.bdtmessages;
	}
}

BlueDasherViewer.prototype.SetSearchText= function(text)
{
	var ref=document.getElementById(this.extmap.divname+"_searchAddress");
	if(ref) ref.value=text;
}

BlueDasherViewer.prototype.AddMessage= function(text)
{
	if(this.extmap)
	{
		this.bdtmessages+="\n\n"+text;
		var ref=document.getElementById(this.extmap.divname+"_messagesText");
		if(ref) ref.value=this.bdtmessages;
	}
}

BlueDasherViewer.prototype.ShowPoi= function(poiname,show)
{
	if(this.IsMapLoaded("ShowPoi("+poiname+","+show+")",2000))
	{
		var info=0;
		if(poiname=="pharmacy") info=4;
		else if(poiname=="market") info=5;
		else if(poiname=="church") info=6;
		else if(poiname=="school") info=7;
		else if(poiname=="hospital") info=8;
		if(show==-1)
		{
			var refcheck=document.getElementById(this.extmap.divname+"_poi"+poiname);
			if(refcheck){
				if(refcheck.checked) show=1;
				else show=0;
			}
		}
		if(info!=0 && show!=-1) this.EnableMapInfo(info,show);
	}
}

BlueDasherViewer.prototype.ResizeTabs= function()
{
	var n,topmap=0;
	if(this.extmap)
	{
		var mapsize=this.extmap.GetViewportPixels();
		wmap=parseInt(mapsize.lon);
		hmap=parseInt(mapsize.lat);
		this.maprightmargin=wmap;

		if(!this.isIE) {wmap-=18; hmap-=12;}
		if(wmap<350) wmap=350;
		ref=document.getElementById(this.extmap.divname);
		if(ref){
			topmap=parseInt(ref.style.top)
			this.maprightmargin+=parseInt(ref.style.left);
		}
		
		for(n=0;n<this.mapdialogvisible.length;n++)
		{
			if(this.mapdialogdiv[n])
			{
				this.mapdialogdiv[n].style.width=wmap+"px";
				this.mapdialogdiv[n].style.top=(topmap+hmap-(parseInt(this.mapdialogdiv[n].style.height)))+"px";
				if(this.mapdialogtab[n])
				{
					this.mapdialogtab[n].style.top=(parseInt(this.mapdialogdiv[n].style.top)-21)+"px";
				}
			}
		}
	}
}
BlueDasherViewer.prototype.ShowMapDialog= function(numdialog, show, htmlcode)
{
	var pthis=this;

	if(this.IsMapLoaded("ShowMapDialog("+numdialog+","+show+","+htmlcode+")",2000))
	{
		this.mapdialogvisible[numdialog]=show;
		if(this.mapdialogvisible[numdialog])
		{
			var ref,refmap=document.getElementById(this.extmap.divname);
			if(refmap)
			{
				var n,h=147;
				var zindex=1050;
				if(this.boxmap) zindex+=1050;
				for(n=0;n<this.mapdialogvisible.length;n++)
				{
					if(n!=numdialog && this.mapdialogdiv[n] && this.mapdialogvisible[n] && this.mapdialogdiv[n].style.zIndex>zindex-40){
						this.mapdialogdiv[n].style.zIndex=this.mapdialogdiv[n].style.zIndex-5;
						this.mapdialogtab[n].style.zIndex=this.mapdialogtab[n].style.zIndex-5;
					}
				}
				
				if(this.isIE) h+=10;
				if(this.mapdialogdiv[numdialog]==null)
				{
					this.mapdialogdiv[numdialog]=document.createElement("div");
					this.mapdialogdiv[numdialog].className="mapdialog";	
					this.mapdialogdiv[numdialog].style.left=refmap.style.left;
					this.mapdialogdiv[numdialog].style.height=h+"px";
					this.mapdialogdiv[numdialog].innerHTML=htmlcode;
					document.body.appendChild(this.mapdialogdiv[numdialog]);
				}
				this.mapdialogdiv[numdialog].style.zIndex=zindex;
				if(this.mapdialogtab[numdialog]==null)
				{
					this.mapdialogtab[numdialog]=document.createElement("div");
					this.mapdialogtab[numdialog].style.position="absolute";	
					this.mapdialogtab[numdialog].style.left=(parseInt(refmap.style.left)+(80*numdialog))+"px";
					this.mapdialogtab[numdialog].style.height="22px";
					this.mapdialogtab[numdialog].style.width="144px";
					this.mapdialogtab[numdialog].style.cursor='pointer';
					this.mapdialogtab[numdialog].onclick=function(){pthis.ShowMapDialog(numdialog,1,'');};
					var title="Search Address";
					if(numdialog==1) title="Calculate Route";
					else if(numdialog==2) title="Points of Interest";
					else if(numdialog==3) title="Messages";
					this.mapdialogtab[numdialog].innerHTML='<table border="0" cellpadding="0" cellspacing="0"><tr><td><img src="'+this.mainfolder+'images/dialogtab1.gif" /></td><td align="center" style="WIDTH: 100px; HEIGHT:22px; font-family:Arial; background: url('+this.mainfolder+'images/dialogtab2.gif)"><font color="#FFFFFF" size=2>'+title+'</font></td><td><img src="'+this.mainfolder+'images/dialogtab3.gif" /></td></tr></table>';
					document.body.appendChild(this.mapdialogtab[numdialog]);
				}
				this.mapdialogtab[numdialog].style.zIndex=zindex+1;
				
				var mapsize=this.extmap.GetViewportPixels();
				var wi=parseInt(mapsize.lon);
				var he=parseInt(mapsize.lat);
				this.maprightmargin=parseInt(refmap.style.left)+wi;
				if(!this.isIE) {wi-=18; he-=12;}
				if(wi<350) wi=350;

				var top=parseInt(refmap.style.top)+(he-h);
				this.mapdialogdiv[numdialog].style.top=top+"px";
				this.mapdialogdiv[numdialog].style.width=wi+"px";
				this.mapdialogdiv[numdialog].style.visibility="visible";
				this.mapdialogtab[numdialog].style.top=(top-21)+"px";
				this.mapdialogtab[numdialog].style.visibility="visible";
				
				closebutton=document.createElement("div");
				closebutton.className="closedialog";
				closebutton.style.background="url('"+this.mainfolder+"images/imgapi.gif') 0px -20px";
				closebutton.onmouseup=function(){
					pthis.ShowMapDialog(numdialog,0,"");
				}
				this.mapdialogdiv[numdialog].appendChild(closebutton);

			}
		}
		else
		{
			if(this.mapdialogdiv[numdialog]){
				this.mapdialogdiv[numdialog].style.visibility="hidden";
				this.mapdialogtab[numdialog].style.visibility="hidden";
			}
		}
		var button="";
		if(numdialog==0) button="search";
		else if(numdialog==1) button="route";
		else if(numdialog==2) button="poi";
		else if(numdialog==3) button="messages";
		this.ChangeButtonState(button,show);
	}
}

BlueDasherViewer.prototype.Route= function(func, text)
{
	var from="",to="";
	if(this.IsMapLoaded("Route('"+func+"','"+text+"')",2000))
	{
		var refcheck=document.getElementById(this.extmap.divname+"_routeShowRoute");
		if(func==-1 && refcheck){
			if(refcheck.checked) func="show";
			else func="hide";
		}
		if(func=="show")
		{
			var ref=document.getElementById(this.extmap.divname+"_routeFrom");
			if(ref) from=ref.value;
			ref=document.getElementById(this.extmap.divname+"_routeTo");
			if(ref) to=ref.value;
			if(ref==null && this.extmap.layerroute){
				this.extmap.ShowLayer(this.extmap.layerroute);
			}
			else if(from!="" && to!="")
			{
				if(this.extmap.layerroute && this.latestroutefrom==from && this.latestrouteto==to)
				{
					this.extmap.ShowLayer(this.extmap.layerroute);
				}
				else 
				{
					this.Stop();
					this.FindRoute(from,to);
					ref=document.getElementById(this.extmap.divname+"_routeDrive");
					if(ref) ref.style.visibility="hidden";
				}
				if(refcheck) refcheck.checked=true;
				ref=document.getElementById(this.extmap.divname+"_routePrint");
				if(ref) ref.style.visibility="inherit";
			}
		}
		else if(func=="hide")
		{
			if(this.extmap.layerroute){
				this.extmap.HideLayer(this.extmap.layerroute);
				if(refcheck) refcheck.checked=false;
			}
		}
		else if(func=="drive")
		{
			if(this.isrouting==0) this.DriveRoute();
			else this.Stop();
		}
		else if(func=="from")
		{
			this.ShowRouteDialog(0);
			var ref=document.getElementById(this.extmap.divname+"_routeFrom");
			if(ref) ref.value=text;
		}
		else if(func=="to")
		{
			this.ShowRouteDialog(0);
			var ref=document.getElementById(this.extmap.divname+"_routeTo");
			if(ref) ref.value=text;
		}
		else if(func=="print")
		{
			try{
			if(this.routewindow){
				this.routewindow.close();
			}
			}catch(e){}
			this.routewindow=null;
			if(this.latestroute){
				if(this.routewindow==null || this.routewindow.document==null){
					this.routewindow=window.open(this.mainfolder+'printroute.html','BlueDasherAPIRoute','menubar=0,directories=0,toolbar=0,location=0,status=1,scrollbars=1,width=600,height=600,resizable');
				}
				setTimeout(this.objectname+".Route('printroute')",1000);
			}
		}
		else if(func=="printroute")
		{
			if(this.routewindow && this.routewindow.document && this.latestroute){
				var n,str;
				str='<p align="right" id="printlink"><a href="javascript:printroute()" >Print this page</a></p>';
				str+='<h3>Route description by car</h2>';
				str+='<h3>From: '+this.latestroute.Placemark[0].address+'</h3>';
				str+='<h3>To: '+this.latestroute.Placemark[1].address+'</h3>';
				str+='<p style="MARGIN-left: 20px"><b>Total distance: </b>'+this.latestroute.Directions.Distance.html+' ('+this.latestroute.Directions.Distance.meters+' meters)<br>';
				str+='<b>Total duration: </b>'+this.latestroute.Directions.Duration.html+'</p>';
				for(n=0;n<this.latestroute.Directions.Routes[0].Steps.length;n++){
					str+='<p>'+(n+1)+'.&nbsp;&nbsp;'+this.latestroute.Directions.Routes[0].Steps[n].descriptionHtml+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+this.latestroute.Directions.Routes[0].Steps[n].Distance.html+'</p>';
				}
				this.routewindow.document.body.innerHTML=str;
			}
		}
	}
}

BlueDasherViewer.prototype.DecodePolyline=function(line)
{
	var i=0,shift=0,numcoords=0,number=0;
	var coords=[];

	while(i<line.length)
	{
		c=line.charCodeAt(i++)-63;
		number|=(c&0x1F)<<shift;
		shift+=5;
		if(c<0x20)
		{
			if(number&1) number=~number;
			coords[numcoords]=(number>>1)*1e-5;
			if(numcoords>1) coords[numcoords]+=coords[numcoords-2];
			numcoords++;
			number=0;
			shift=0;
		}
	}
	return coords;
}

BlueDasherViewer.prototype.LoadRouteVectors=function(coords)
{
	var url="";
	var pthis=this;
	var numcoords=coords.length/2;
	var currentcoord=1;
	var callbackfunc=VectorCallBack;
	var latestdistance=10000;
	var Map=0;
	var endpoint=0, error=0;
	this.routevectors=[];
	this.routepoints=[];

	this.routepoints[0]=coords[0];
	this.routepoints[1]=coords[1];
	this.routenumpoints=2;
	
	url=this.serviceurl+"?service=FindPoint&latitude=" + coords[0] + "&longitude=" + coords[1];
	url+="&customer="+this.apikey;
	this.http_requestroute.SendAjaxRequest(0,url,function()
	{
		if (this.readyState==4 && this.status==200)
		{
			if(this.dataobject && this.dataobject.d) obj=this.dataobject.d;
			else obj=null;
			if(obj && obj.Vector!=0)
			{
				Map=obj.Map;
				url=pthis.serviceurl+"?service=LoadVector&id="+obj.Vector+"&map="+Map;
				url+="&customer="+pthis.apikey;
				this.isrequesting=0;
				this.SendAjaxRequest(0,url,VectorCallBack);
			}
			else
			{
				if(obj && obj.File=="serviceerror") 
					alert("Service error loading route vectors.");
			}
		}
		else if(this.status==500) pthis.AddMessage("- Call Timeout: "+this.url);
	});
	
	function VectorCallBack()
	{
		var x,y,x2,y2,pointx,pointy,n,distFrom,distTo,prevlat,prevlon,nextlat,nextlon,numvec,currentangle;
		var fromto="";
		if(this.readyState==4 && this.status==200)
		{
			if(this.dataobject && this.dataobject.d) obj=this.dataobject.d;
			else obj=null;
			if(obj && obj.ID!=0)
			{
				pthis.routevectors[pthis.routevectors.length]=obj;
				
				prevlat=nextlat=coords[currentcoord*2];
				prevlon=nextlon=coords[currentcoord*2+1];
				if(pthis.routenumpoints>2)
				{
					prevlat=pthis.routepoints[pthis.routenumpoints-2];
					prevlon=pthis.routepoints[pthis.routenumpoints-1];
				}
				x=obj.FromX-prevlon;
				y=obj.FromY-prevlat;
				distFrom=x*x+y*y;
				x=obj.ToX-prevlon;
				y=obj.ToY-prevlat;
				distTo=x*x+y*y;
				if((distFrom<distTo && pthis.routenumpoints>2) || (pthis.routenumpoints==2 && distFrom>distTo))
				{
					fromto="To";
					obj.NextSide=1;
				}
				else 
				{
					fromto="From";
					obj.NextSide=2;
				}

				lat=obj[fromto+"Y"];
				lon=obj[fromto+"X"];
				currentangle=pthis.GetAnglePoints(pthis.routepoints[pthis.routenumpoints-2],pthis.routepoints[pthis.routenumpoints-1],lat,lon);
				
				pthis.routepoints[pthis.routenumpoints]=lat;
				pthis.routepoints[pthis.routenumpoints+1]=lon;
				pthis.routenumpoints+=2;
				
				var repeat,angle,ang,dif,num,nextx,nexty,distance;
				numvec=obj[fromto+"Vectors"].length;
				do{
					angle=0;
					if(latestdistance==10000)
					{
						x=lon-nextlon;
						y=lat-nextlat;
						distance=x*x+y*y;
						if(distance<0.00000001) latestdistance=-1;
					}
					if(latestdistance>=0)
					{
						angle=360;
						repeat=0;
						num=0;
						for(n=0;n<numvec;n++)
						{
							x=obj[fromto+"Vectors"][n].FromX;
							y=obj[fromto+"Vectors"][n].FromY;
							x2=obj[fromto+"Vectors"][n].ToX;
							y2=obj[fromto+"Vectors"][n].ToY;
							distFrom=(x-lon)*(x-lon)+(y-lat)*(y-lat);
							distTo=(x2-lon)*(x2-lon)+(y2-lat)*(y2-lat);
							if(distFrom<distTo){
								x=x2;
								y=y2;
							}
							ang=pthis.GetAnglePoints(lat,lon,y,x);
							dif=pthis.DifAngle(ang,currentangle);
							if(dif<angle)
							{
								num=n;
								nextx=x;
								nexty=y;
								angle=dif;
							}
						}
						x=nextx-nextlon;
						y=nexty-nextlat;
						distance=x*x+y*y;
					}
					if(distance>latestdistance)
					{
						if(currentcoord<numcoords-1)
						{
							if(angle>45){
								repeat=0;
								error=1;
								this.routevectors=[];
								pthis.AddMessage("- Routing error: Vector not found, from '"+pthis.latestroutefrom+"' to '"+pthis.latestrouteto+"'");
							}
							else{
								currentcoord++;
								prevlat=nextlat;
								prevlon=nextlon;
								nextlat=coords[currentcoord*2];
								nextlon=coords[currentcoord*2+1];
								currentangle=pthis.GetAnglePoints(prevlat,prevlon,nextlat,nextlon);
								latestdistance=10000;
								repeat=1;
							}
						}
						else
						{
							ang=pthis.GetAnglePoints(lat,lon,nextlat,nextlon);
							dif=pthis.DifAngle(ang,currentangle);
							if(dif>90) pthis.routenumpoints-=2;
							pthis.routepoints[pthis.routenumpoints]=nextlat;
							pthis.routepoints[pthis.routenumpoints+1]=nextlon;
							pthis.routenumpoints+=2;
							endpoint=1;
						}
					}
					else latestdistance=distance;
				}while(repeat);
				
				if(error==0){
					if(endpoint==0)
					{
						url=pthis.serviceurl+"?service=LoadVector&id="+obj[fromto+"Vectors"][num].ID+"&map="+Map;
						url+="&customer="+pthis.apikey;
						this.isrequesting=0;
						this.SendAjaxRequest(0,url,callbackfunc);
					}
					else
					{
						if(pthis.shaperoute) pthis.extmap.layerroute.DeleteShape(pthis.shaperoute);
						pthis.shaperoute = pthis.extmap.CreateLine(pthis.routepoints, 0,255,0, 0.7, 5);
						if(pthis.shaperoute) pthis.extmap.layerroute.AddShape(pthis.shaperoute);
						
						ref=document.getElementById(pthis.extmap.divname+"_routeDrive");
						if(ref) ref.style.visibility="inherit";
					}
				}
			}
			else
			{
				if(obj && obj.File && obj.File=="serviceerror") 
					alert("Service error loading route vectors.");
			}
		}
	}
}

BlueDasherViewer.prototype.DriveRoute=function()
{
	var n,frombeginning=1,fromvector=0,facingdirection;

	if(this.extmap && this.routevectors.length>0)
	{
		var ref=document.getElementById(this.extmap.divname+"_routeDrive");
		if(ref) ref.value="Pause Route";

		this.routefacingtoend=0;
		if(this.currentvector)
		{
			for(n=0;n<this.routevectors.length;n++)
			{
				if(this.currentvector.ID==this.routevectors[n].ID)
				{
					fromvector=n;
					frombeginning=0;
					
					if(n==this.routevectors.length-1)
						this.routefacingtoend=1;
					break;
				}
			}
		}
		facingdirection=this.routevectors[fromvector].Direction;
		if(this.routevectors[fromvector].NextSide==2) 
			facingdirection=(facingdirection+180)%360;
		
		var x=this.routetopoint.lon-this.GetValue("X");
		var y=this.routetopoint.lat-this.GetValue("Y");
		this.routedistancetoend=x*x+y*y;
		
		if(frombeginning) 
		{
			this.isrouting=2;
			this.FindPoint(this.routepoints[0],this.routepoints[1],facingdirection);
		}
		else
		{	
			this.isrouting=1;
			this.SetFacingDirection(facingdirection);
			setTimeout(this.objectname+".GoForward()",1000);
		}
	}
}

BlueDasherViewer.prototype.SendEvent=function(eventfunc)
{
	if(eventfunc && typeof(eventfunc)=="function") eventfunc();
}

BlueDasherViewer.prototype.SetBound= function(bound)
{
	if(this.IsMapLoaded("SetBound('"+bound+"')",2000) && this.allstops)
	{
		if(this.currentbound!=bound)
		{
			var n,num=-1;
			for(n=0;n<this.allstops.length;n++)
			{
				if(this.allstops[n].Bound==bound)
				{
					num=n;
					break;
				}
			}
			if(num>=0)
			{
				this.Stop();
				this.numcurrentstop=num;
				this.numcurrentpoint=0;
				this.numcachepoint=0;
				this.UpdateMapInfo(1);
				this.UpdateInterface("hideclickdrag,numstop");
				this.UpdateMessages("showwaiting,hidemessage");
				this.LoadStop(this.numcurrentstop);
			}
		}
	}
}

BlueDasherViewer.prototype.GetStopIndex= function(bound, nextstop)
{
	var n,num,ret=0;
	num=this.allstops.length;
	for(n=0;n<num;n++)
	{
		if(this.allstops[n].NextStop==nextstop && this.allstops[n].Bound==bound)
		{
			ret=n;
			break;
		}
	}
	return ret;
}

BlueDasherViewer.prototype.EnableDebug= function(enable)
{
	if(enable)
	{
		var debugapi=document.getElementById("BDTapidebug");
		if(debugapi==null)
		{
			this.debugapi = document.createElement('script');
			this.debugapi.id="BDTapidebug";
			this.debugapi.language ="Javascript";
			this.debugapi.type = 'text/javascript';
			this.debugapi.defer=true;
			this.debugapi.src = this.mainfolder+"BDTdebug.js";
			var head = document.getElementsByTagName("head")[0];
			if(head) head.appendChild(this.debugapi);
		}
		else this.debugapi=debugapi;
		this.Dbg= function(op){if(typeof(this.DbgFunc)!='undefined') {this.Dbg=this.DbgFunc;this.DbgInit();}else setTimeout(this.objectname+".Dbg()",500);};
		this.Dbg();
	}
	else this.Dbg=function(){};
}

