﻿// JScript File

 var map = null;
 var latLong = null;
 var zoomLevel = 3;
 var increment = 3;
 var KEY_ENTER = 13;
 var initView = new VEMapViewSpecification(new VELatLong(38.62504326121764, -90.18497586250308), 16, 1000, -90, 0);

 var zoomMin = 3;
 var zoomMax = 17;        
 var lastMapZoom = -1;
 //var mapStyle = 'h';
 var layer;
 var _fromLatitude;
 var _fromLongitude;
 var _toLatitude;
 var _toLongitude;
 var _init = "false";
    
function GetMap()
{
    map = new VEMap('div_MyMap');
    map.LoadMap();

    //map.AttachEvent('onclick', UpdateLabel);
    map.AttachEvent('onmousewheel', MouseWheelGo);
    map.SetMapStyle(hd_MapStyle.value);
    map.HideDashboard();
    map.HideFindControl();
    // zoom to cursor and center
    map.SetMouseWheelZoomToCenter(false);

    //generate relative buttons
    var tagDef ;
    var height = getObj('div_MapSliders').clientHeight;
    var n = zoomMax-zoomMin+1;
    var tagRowInterval = (height-n*11)/(n+1);
    
    for (var i=zoomMin;i<=zoomMax;i++)
    {
       n = i - zoomMin + 1;
       tagDef = "<img onclick=\"javascript:Zoom(" + String(zoomMax+zoomMin-i) +")\" id=\"Zoom" + i +"\" state=\"0\" src=\"images/mapbar.png\" onmouseover=\"javascript:this.src='images/mapbar_sel.png';\" onmouseout=\"javascript:if (this.state=='0' || this.state==null){this.src='images/mapbar.png'}\" style=\"cursor:pointer;margin-bottom:" + tagRowInterval + "px;\" /><br />";
       document.getElementById('div_MapSliders').innerHTML +=tagDef;
    }
    var labelDef = "<a id=\"mapstyle_h\" href=\"javascript:setMapStyle('h');\" style=\"font-size:11px;text-decoration: none;cursor:pointer;color:gray\" onmouseover=\"this.style.color='red'\" onmouseout=\"if(hd_MapStyle.value=='h') {this.style.color='#000'}else{this.style.color='gray'} ;\" Font-Underline=\"False\">Hybrid</a><br />";
    labelDef += "<a  id=\"mapstyle_r\" href=\"javascript:setMapStyle('r');\" style=\"font-size:11px;text-decoration: none; cursor:pointer;color:gray\" onmouseover=\"this.style.color='red'\" onmouseout=\"if(hd_MapStyle.value=='r') {this.style.color='#000'}else{this.style.color='gray'};\" Font-Underline=\"False\">Road</a><br />";
    labelDef += "<a  id=\"mapstyle_a\" href=\"javascript:setMapStyle('a');\" style=\"font-size:11px;text-decoration: none; cursor:pointer;color:gray\" onmouseover=\"this.style.color='red'\" onmouseout=\"if(hd_MapStyle.value=='a') {this.style.color='#000'}else{this.style.color='gray'};\" Font-Underline=\"False\">Aerial</a>";
    
    getObj('div_ViewDiv').innerHTML = labelDef;
    setMapLinkColor(hd_MapStyle.value);
    
    //map.SetZoomLevel(zoomLevel);
    map.AttachEvent("onendzoom", OnEndZoom);
   
    //initialize
    Locate();
    
    if (_fromLatitude != null)
        drawRoute(_fromLatitude, _fromLongitude, _toLatitude, _toLongitude);
        
    if (_init == "true")
        InitMap();
 }
 
 function setMapStyle(style)
 {
    hd_MapStyle.value=style;
    map.SetMapStyle(style);
    setMapLinkColor(style);
    
 }
 
 function setMapLinkColor(style)
 {
    if (style == 'h')
    {
        getObj('mapstyle_r').style.color= "gray";
        getObj('mapstyle_a').style.color= "gray";
        getObj('mapstyle_h').style.color= "#000";
    }
    
    if (style == 'r')
    {
        getObj('mapstyle_h').style.color= "gray";
        getObj('mapstyle_a').style.color= "gray";
        getObj('mapstyle_r').style.color= "#000";
    }
    
    if (style == 'a')
    {
        getObj('mapstyle_r').style.color= "gray";
        getObj('mapstyle_h').style.color= "gray";
        getObj('mapstyle_a').style.color= "#000";
    }
 }
 
 function drawRoute(fromLatitude, fromLongitude,toLatitude, toLongitude)
 {
    //map.GetRoute(new VELatLong(fromLatitude,fromLongitude),new VELatLong(toLatitude,toLongitude), VEDistanceUnit.Kilometers, VERouteType.Quickest);
    
    var SeattleStart = new VELatLong(fromLatitude, fromLongitude, 0, VEAltitudeMode.Default);
    var SeattleEnd = new VELatLong(toLatitude, toLongitude, 0, VEAltitudeMode.Default);

    var locations = new Array(SeattleStart, SeattleEnd);
    var options = new VERouteOptions;
    options.DrawRoute      = true;
    options.SetBestMapView = true;
    options.DistanceUnit   = VERouteDistanceUnit.Mile;
    options.ShowDisambiguation = true;
    options.RouteWeight = 3;
    options.RouteCallback = removePushpin;
    map.GetDirections(locations, options);
 }
 
 function removePushpin(route)
 {
     // Unroll route
     var legs = route.RouteLegs;
     var numTurns = 0;

     // Leg is a VERouteLeg object
     var leg = null;
     var shape = null;

     // Get intermediate legs
     for(var i = 0; i < legs.length; i++)
     {
         // Get this leg so we don't have to derefernce multiple times
         leg = legs[i];

         for(var j = 0; j < leg.Itinerary.Items.length; j ++)
         {
             //Remove original route pushpins
             if (j!=0 && j!= leg.Itinerary.Items.length-1)
             {
                map.DeleteShape(leg.Itinerary.Items[j].Shape);
             }
         }
     }
 }
 
 function RouteComplete()
 {
    //alert();
 }

 function AddPins(locInfo,locdes)
 {
        
    var pos = 0,desPos = 0,desIndex;
    var latitude,longitude;
    var index;
    var labels = "abcdefghijklmnopqrstuvwxyz";
    var i = 0;
    var points = new Array();
    while (pos<locInfo.length)
    {
       index = locInfo.indexOf(',',pos);
       latitude = parseFloat( locInfo.substr(pos,index-pos) );
       pos = index + 1;
       index = locInfo.indexOf('\t',pos);
       longitude = parseFloat( locInfo.substr(pos,index-pos) );
       pos = index + 1;
       
       desIndex = locdes.indexOf('\t',desPos);
       var description = locdes.substr(desPos , desIndex-desPos);
       desPos = desIndex + 1;
       
       var pushpin =new VEPushpin(i+1000,new VELatLong(latitude,longitude),"pageElems/"+labels.substr(i,1)+"_c.bmp",null,description,'iconStyle','titleSytle','detailsStyle');
       points.push(new VELatLong(latitude,longitude));
       map.AddPushpin(pushpin);
       i = i + 1;
    }
    return points;            
 }
 
//Pan the map 
function Pan(x, y)
{
    if (map)
    {
        map.Pan(-x, -y);
    }
}

function OnEndZoom(e)
{
    //alert("OnEndZoom:"+map.GetZoomLevel());
    var corespondZoom = zoomMax + zoomMin - lastMapZoom;
    if (map != null)
    {
        if ( lastMapZoom != -1)
        {
           getObj('Zoom'+corespondZoom).src = 'images/mapbar.png';
           getObj('Zoom'+corespondZoom).state = '0';
        }
        var zoom = map.GetZoomLevel();
        if (zoom < zoomMin)
        {
            map.SetZoomLevel(zoomMin);
        }
        
        if(zoom > zoomMax)
        {
            map.SetZoomLevel(zoomMax);
        }
        lastMapZoom = map.GetZoomLevel();
        corespondZoom = zoomMax + zoomMin - lastMapZoom;
        //alert("index= "+corespondZoom);
        getObj('Zoom'+corespondZoom).src = 'images/mapbar_sel.png';
        getObj('Zoom'+corespondZoom).state = '1';
    }
    

}

function GetInfo()
{  
    // VEMap.GetTop returns the position of the top edge of the map control, in pixels.
    // VEMap.GetLeft returns the position of the left edge of the map control, in pixels.
    // These units are defined using standard DHTML markup.
    // See the style attribute for the <div> element 'myMap'.
    var info = 'The top edge of the map on the Web page is at pixel: '+ map.GetTop() + "\n";
    info += 'The left edge of the map on the Web page is at pixel: '+ map.GetLeft() + "\n";
    info += 'The latitude,longitude at the center of the map is: '+ map.GetCenter() + "\n";
    info += 'The current zoom level of the map is: '+ map.GetZoomLevel() + "\n";
    info += 'The map control version is: '+ VEMap.GetVersion() + "\n";            
    alert(info);
 }
 
function callback(a,b,c,d,e)     
{

    if (c != null && c.length >= 1)
    {
        var pin = new VEPushpin(
                       1, 
                       c[0].LatLong, 
                       null, 
                       c[0].Name, 
                       null,
                       'iconStyle',
                       'titleSytle',
                       'detailsStyle'
                    );
         map.AddPushpin(pin);
        //show the yellow page result
        var relaLocInfo = document.getElementById( yellowPageResultId ).value;
        var relaLocDes = document.getElementById( YellowPageResultDescId ).value;
        if (relaLocInfo!='')
        {
            var points = AddPins(relaLocInfo,relaLocDes);
            points.push(c[0].LatLong);
            map.SetMapView(points);
        }
        else
        {
            map.SetZoomLevel(document.getElementById(mapSizeId).value);
        }
    } 
    
}


//set the map view as the point indicted by hiddent field "QueryPlace"
function Locate()
{  
    var center;
    var locStr = getObj(locStrId).value;
    var locDes = getObj(locDesId).value;
    map.SetZoomLevel(getObj(mapSizeId).value); 
    
    if (locDes!='')
    {
        var pos = locStr.indexOf(',',pos);
        var latitude = parseFloat( locStr.substr(0,pos) );
        var longitude = parseFloat( locStr.substr(pos+1) );
        center = new VELatLong(latitude,longitude);
        map.SetCenter(center);
        var pin = new VEPushpin(1,center,null,locDes,null,'iconStyle','titleSytle','detailsStyle');
        map.AddPushpin(pin);
    }else
    {
        map.Clear();
    }
}

function InitMap()
{
    var latitude = '38.62504326121764';
    var longitude = '-90.18497586250308';
    center = new VELatLong(latitude,longitude);
    map.SetCenter(center);
    map.SetZoomLevel(1);
}


function FindLoc()
{
   try
   {
      map.Find(null,
               document.getElementById(locStrId).value,
               null,
               layer,
               0,
               1,
               true,
               true,
                false,
               null,
               callback);
   }
   catch(e)
   {
      alert(e.message);
   }
}

function ZoomIn()
{
    if (map != null)
    {
        Zoom(map.GetZoomLevel() + 1);            
    }
}
function ZoomOut()
{         
    if (map != null)
    {
        Zoom(map.GetZoomLevel() - 1);            
    }
}

function Zoom(zoom)
{
    //alert("Zoom("+zoom+")");
    if (zoom < zoomMin)
    {
        zoom = zoomMin;
    }
    
    if (zoom > zoomMax)
    {
        zoom = zoomMax;
    }
    
    if (map != null)
    {
        map.SetZoomLevel(zoom);
    }
}


function keydown( event )
{
    if (navigator.product != "Gecko")
    {
        //for ie
        if (window.event.keyCode == 13)
        {
	        submitQuery();
        }
    }
    else
    {
        //for firfox
        if (event.keyCode == 13)
        {
	        submitQuery();
        }
    }
}


function filterKeyword(keyword)
{
    var filterKey = "";

    for (var i = 0; i < keyword.length; i++)
    {
	    var ch = keyword.substring(i, i + 1);
    	
	    if (ch != " ")
	    {
	        filterKey += ch;
        }
    }
    
    return filterKey;	
}

function GetVELatLongFromEvent(e)
{
    return map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
}

function UpdateLabel(e)
{
    getObj(locDesId).value = '';
    var ll = GetVELatLongFromEvent(e);
    divVisible('div_ip', 'none');
    divVisible('div_Query', 'block');
    
    callback_ConvertToLocation(ll.Latitude,ll.Longitude );
    //document.getElementById('TxtGps').value = 'beijing';
}

function displayLearnMore()
{
    var a = getObj("div_Decription");
	var isShow = a.style.display;
	if (isShow == "none")
	{
		getObj("div_LearnMore").style.display = "none";
		getObj("div_Hide").style.display = "";
		a.style.display = "";
	}else
	{
		getObj("div_LearnMore").style.display = "";
		getObj("div_Hide").style.display = "none";
		a.style.display = "none";
	}
}


function checkEmpty(sender, args)
{
    var strIp = ipTxt.value.replace(/\s+/,'');
    var strQdl = qdlTxt.value.replace(/\s+/,'');
    //var strGps = gpsTxt.value.replace(/\s+/,'');
    
    if (strIp=="" && strQdl =="")
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
    
    if (ipTxt.value=="" && qdlTxt.value =="")
    {
        args.IsValid = false;
    }else
    {
        args.IsValid = true;
    }
}

function ResetInput()
{
    qdlTxt.value = "";
    
    //if (alertLbl != null)
    //    alertLbl.style.display = "none";
    divResult.style.display = "none";
    
}

function OnKeyPress(evt)
{
    var e =(evt)?evt:window.event; 
    if(e.keyCode==KEY_ENTER || e.charCode == KEY_ENTER)
    {
        if (!checkQuery())
        {
            if (e.charCode == null) { 
                window.event.returnValue=false;
                window.event.cancelBubble=true; 
            }else{ 
                e.preventDefault()
                e.stopPropagation(); 
            } 
            return false;
        }

        if (e.charCode == null) { 
            window.event.returnValue=false;
            window.event.cancelBubble=true; 
        }else{ 
            e.preventDefault();
            e.stopPropagation(); 
        } 
        
        doQuerySTS();
    }
}

function checkQuery()
{
    var express= /^[a-zA-Z]([\s]|[\']|[\s]|[\d]|[a-zA-Z])+$/;
    var query = trim(qdlTxt.value);
    if(trim(query) == "" || (!express.exec(query)))
    {
        alert("Your should input a valid query.");
        qdlTxt.focus();
        return false;
    }else
    {
        return true;
    }
}

function trim(str) 
{
	str = str.toString();
	
	while (1) {
		if (str.substring(0, 1) != " ")	{
			break;
		}
		str = str.substring(1, str.length);
	}
	
	while (1) {
		if (str.substring(str.length - 1,str.length) != " ") {
			break;
		}
	
		str = str.substring(0, str.length - 1);
	}
	
	return str;
}

function doQuerySTS()
{
    ib_Submit.click();
}

var isAllowWheel = false;
function MouseWheelGo(e)
{
    return !isAllowWheel;
}

function ChangeWheel(e)
{
    var ck = getObj("cb_EnableWheel");
    if (ck.checked)
        isAllowWheel = true;
    else
        isAllowWheel = false;
}

function SetJudgeType(type)
{
    getObj("hidJudgeType").value = type;
}

function SetJudgeContent(str)
{
    getObj("hidJudgeContent").value = str;
}


function  ShowResult()
{
    divVisible('div_Result','');

    if (!isChrome)
    {
        divVisible('div_FillSpace','none');
    }else
    {
        getObj('div_FillSpace').style.height = "30px";
    }
}



window.onload = function()
{
    IEHoverPseudo();
    GetMap();oload();
}

