﻿var map;
var geocoder;
var baseIcon;
var ImageArray;
var ImageArrayIndex; 
var mapZoom;
var LatStartValue;
var LongStartValue; 
var LatEndValue;
var LongEndValue; 
var point;
var StartPoint;
var EndPoint;
var EndAddress;
var totalCount=0;
var hours=0;//Digital.getHours()
var minutes=0;//Digital.getMinutes()
var seconds=0;//Digital.getSeconds()
var minuteStr;
var CurrentCity;
var FullStateName;
var pauseOnce = 0;

    function initializeAjaxGMap(zoom) { 
       zoom = 4;        
       Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
       
        map = new google.maps.Map2(document.getElementById("map_canvas"));
        //   alert(zoom);         
        map.setCenter(new google.maps.LatLng(43, -95), zoom);
       
        var mapTypeControl = new GMapTypeControl();
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
        var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
        map.addControl(mapTypeControl, topRight);
        GEvent.addListener(map, "dblclick", function() {
          map.removeControl(mapTypeControl);
          map.addControl(new GMapTypeControl(), bottomRight);
        });
        map.addControl(new GSmallMapControl());

        GEvent.addListener(this.map, "moveend", function() { //for Lat49 Ads
            Lat49eventFired();
        });
                 
		GEvent.addDomListener(map.getContainer(), "mouseup", ResumeGame) ;

        geocoder = new GClientGeocoder();
        baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "Images/shadow50.png"; //"http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
      
      //  CenterMapbyLatLong('LatLong',8);
    }
    
//    function CenterMapbyLatLong(zoom) {   
//    var latLongCookie =  document.getElementById('TextBoxEndLatLong').value;//readCookie(latlongCookie); 
//    //alert(latLongCookie);
//    if (latLongCookie != null)
//         {
//             var latLong = latLongCookie.split(",");  
//             if (map != null && latLong.length > 0) {               
//                 var lat = latLong[0];
//                //alert(lat + " " + latLong[1]);                  
//                 var longg = latLong[1];                  
//                 map.setCenter(new google.maps.LatLng(lat, longg), zoom);//8
//        
//              }
//        } 
//   }
  
    function EndRequestHandler(sender, args) {
        // alert('endreq');
        DisableControls(false,'','');
        var cmbstate = document.getElementById('cmbStates').value;
     
        var list = document.getElementById("cmbStates"); 
        FullStateName = list.options[list.selectedIndex].text; 
       
        if(cmbstate == "Select a State")
        {
           alert('Please select a state');
           return;
        }
        
        var errorMessage = document.getElementById('TextBoxMessage').value;
        if(errorMessage.length > 0)
           {
              alert('Your Starting letter of the city should be "' + errorMessage + '"');
              return;
           }
       
    //  var city = document.getElementById('TextBoxCity').value;    //  var state = document.getElementById('cmbStates').value;
       //showLocation('AUSTIN TX','9');  //     showLocation(city + ' ' + state,'9'); 
      GetGeoCordinates(document.getElementById('TextBoxStartLatLong').value);//'AUSTIN TX','Dallas TX'); 

    }
    
    function DisableControls(enable,city,state)
    {    
       if(!enable)
        {  
            CurrentCity = document.getElementById('TextBoxCity').value;
            document.getElementById('TextBoxCity').value = '';            
            document.getElementById("ButtonStart").style.display = "none"; //  document.getElementById("ButtonStart").disabled = true; 
         }
         else
         {
             document.getElementById('TextBoxCity').value =city;             
             SetCmbStateValue(state); 
             document.getElementById("ButtonMap").disabled = true;           
         }
          document.form1.cmbStates.disabled = document.form1.TextBoxCity.disabled=enable;     
     
    }
      function SetCmbStateValue(val) {
           var ddl = document.getElementById("cmbStates");
           for (var count = 0; count < ddl.options.length; count++) {
               if (ddl.options[count].text == val) {
                   ddl.options[count].selected = true;
                   break;
               }
           }
       }
function GetGeoCordinates(addressStart) {
    //map.setCenter(new google.maps.LatLng(34, 0), zoom); //map.setCenter(new GLatLng(34, 0), zoom);    
    geocoder.getLocations(addressStart, StartAddressToPoint);        
    //CenterMapbyLatLong(zoom);
}

function ReStart(address)
{
     if(totalCount == 0)
           window.location.assign('./MapExplorerGame.aspx');//replay again if the random city is wrong.
         else
           alert("Sorry, we were unable to geocode the address '" + address.toUpperCase() + "' in US."); 
}
function StartAddressToPoint(response) {
    //   map.clearOverlays();
    if (!response || (response.Status.code != 200) ) {
     ReStart(response.name);
    } else {
        place = response.Placemark[0];
        StartPoint = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
       
       geocoder.getLocations(document.getElementById('TextBoxEndLatLong').value, EndAddressToPoint);
     }
}

function EndAddressToPoint(response) {
    //   map.clearOverlays();
    try
    {
        if (!response || response.Status.code != 200) {
            document.getElementById('TextBoxMessage').value = EndAddress;
         //   document.getElementById('TextBoxEndLatLong').value = EndAddress;   
            ReStart(response.name);//alert("Sorry, we were unable to geocode that address");
        } else {
           var gCity = "";//google CurrentCity;
           var gState = "";
           var bFound = true;
           var Ccode = "";
           var currentState = document.getElementById('cmbStates').value;
           
            if(response.Placemark[0].AddressDetails.Country != null) 
               Ccode = response.Placemark[0].AddressDetails.Country.CountryNameCode;
            else if(response.Placemark[0].address.indexOf("USA") > 0)
                Ccode = "US";
               
           if( Ccode == "US")
           {            
                var addressRes = response.Placemark[0].address.split(",");
                gState = trim(response.Placemark[0].address.split(",")[addressRes.length-2]);
                if(gState.length > 2)//if state has zipcode
                  {
                   gState = gState.split(' ')[0];
                  }
               // gState = response.Placemark[0].address;
                gCity = response.Placemark[0].address.split(",")[0];
             /*  if(response.Placemark[0].AddressDetails.AddressLine != null &&  response.Placemark[0].AddressDetails.AddressLine[0] != null)
                  gCity = response.Placemark[0].AddressDetails.AddressLine[0];
                else if(response.Placemark[0].AddressDetails.Country != null &&
                  response.Placemark[0].AddressDetails.Country.AdministrativeArea != null &&
                  response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality != null)
                  {
                   gCity = response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName; 
                   //incase city comes with county we use dependentlocality name like 	Bena , Gloucester Point, VA
                   
                    if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality != null
                    && response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName != null)
                      gCity = response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName;
                  }
                else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea != null &&
                  response.Placemark[0].AddressDetails.Country.AdministrativeArea.AddressLine != null && 
                  response.Placemark[0].AddressDetails.Country.AdministrativeArea.AddressLine[0] != null)
                   gCity = response.Placemark[0].AddressDetails.Country.AdministrativeArea.AddressLine[0];
               else if(response.Placemark[0].AddressDetails.Country != null && 
                    response.Placemark[0].AddressDetails.Country.AddressLine != null &&
                    response.Placemark[0].AddressDetails.Country.AddressLine[0] != null)
                  gCity = response.Placemark[0].AddressDetails.Country.AddressLine[0];
              else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.DependentLocalityName != null)
          {
              gCity = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.DependentLocalityName;
          }
               if(response.name != null)
                {                     
                    //gCity = trim(response.name.split(",")[0]);   //response.name contains the city name entered from user. 
                    gState = trim(response.name.split(",")[1]);                
                }*/
                
                  if(gCity.length > 0)
                  {
                       gState = gState.toLowerCase();                        
                       gState = trim(gState.replace(gCity.toLowerCase(), '').replace('usa', '').replace(/,/g, ''));
                   }    
                 if(gCity.toLowerCase() == CurrentCity.toLowerCase() && 
                 (currentState.toLowerCase() == gState.toLowerCase()
                  || gState.toLowerCase().indexOf(FullStateName.toLowerCase()) >= 0) )             //!=
                    bFound = true;//false  
                   else
                    bFound = false;                        
           }
             else
                 bFound = false;
             
              if(!bFound)
                 {  //to store the last succesful start city incase of anyerror.
                    document.getElementById('TextBoxMessage').value = EndAddress;//TextBoxMessage //TextBoxEndLatLong    
                   //  document.getElementById('TextBoxEndLatLong').value = EndAddress;         
                    ReStart(CurrentCity + ' ' + currentState);// alert("Sorry, we were unable to geocode that address in US.");
                    return;
                 }
             
            place = response.Placemark[0];
            EndPoint = new GLatLng(place.Point.coordinates[1],
                                place.Point.coordinates[0]);
                
                  var polyline = new GPolyline([
  		      new GLatLng(StartPoint.y, StartPoint.x),
  		      new GLatLng(EndPoint.y, EndPoint.x)
		    ], "#ff0000", 10);
    		 
		    EndAddress = document.getElementById('TextBoxEndLatLong').value;//stores the last successful city
		    document.getElementById('DivNextLetter').innerHTML  = "<font style='background-color: #FFFF99;font family:'Comic Sans MS','Arial';'>Your starting city letter should be '" + CurrentCity.substr(CurrentCity.length-1,1).toUpperCase() + "'</font>";
		    map.setCenter(EndPoint, 8);//8
		    map.addOverlay(polyline);		
    	          
	        var x=document.getElementById('cmbStates')
            x.remove(x.selectedIndex)
            totalCount++;
           
            marker = createMarker(EndPoint, place.address); //new GMarker(point);
            map.addOverlay(marker);        
     
           if(totalCount == 1)
             showTime();
             
            if(totalCount == 51)//51
            {
               alert('Congratulations you Won');
               var dur = (hours * 60 * 60) + (minutes * 60) + parseInt(seconds);
                window.location.assign('./GameUsersRegister.aspx?d=' + dur + '&s=' + totalCount);
            }
           var cnt = 51 - totalCount;
           document.getElementById('DivNoofStates').innerHTML = 'Remaining States: ' + cnt;
           document.getElementById('cmbStates').value ="Select a State";
         }
     }
     catch(err)
          { 
             alert("Unexcepted Error Occured.City Rover Game will Restart");
              window.location.assign('./EmailErrors.aspx?q=MapCityGame&city=' +CurrentCity +
            '&state=' + document.getElementById('cmbStates').value + '&error=' + err.description);         
             // txt+="Error description: " + err.description + "\n\n";           
          }
}
 function buttonStop()
 {  
   //document.getElementById('TextBoxCity').value = '';
    if(totalCount > 1)
    {
     var dur = (hours * 60 * 60) + (minutes * 60) + parseInt(seconds);
     window.location.assign('./GameUsersRegister.aspx?d=' + dur + '&s=' + totalCount);
     }
     else
      window.location.reload(false); 
 }
 
 function buttonStart()
 {  
//    document.getElementById("ButtonStart").disabled = true;  
    document.getElementById("ButtonMap").disabled = false;    
    document.getElementById('ButtonMap').click();
 }
 
 function buttonPause()
 {
     if(document.getElementById('ButtonPause').value == 'Pause')
     {
        if(pauseOnce == 1 )   
            {
             alert("You have already taken 1 break"); 
             return;
            }   
          pauseOnce++;
          document.form1.cmbStates.disabled= document.form1.TextBoxCity.disabled= 
          document.form1.ButtonMap.disabled = true;  
          document.getElementById('googleMap').disabled = true;  
          document.getElementById('ButtonPause').value = 'Resume';
      }
     else if(document.getElementById('ButtonPause').value == 'Resume')
     {     
          document.form1.cmbStates.disabled= document.form1.TextBoxCity.disabled= 
          document.form1.ButtonMap.disabled = false;  
          document.getElementById('ButtonPause').value = 'Pause';
          setTimeout("showTime()",1000);
     } 
 }
  function ResumeGame(e)
 { 
   if(document.getElementById('ButtonPause').value == 'Resume')
     {     
          document.form1.cmbStates.disabled= document.form1.TextBoxCity.disabled= 
          document.form1.ButtonMap.disabled = false;  
          document.getElementById('ButtonPause').value = 'Pause';
          setTimeout("showTime()",1000);
          alert("Your Game is Resumed now");
     } 
 }
// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, popuptext) {      
       
    // Create a lettered icon for this point using our icon class
  var letteredIcon = new GIcon(baseIcon);  
  letteredIcon.image = "Images/marker" + totalCount + ".png";

  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon };
  var marker = new GMarker(point, markerOptions);
  
   GEvent.addListener(marker, "click", function() {          
            marker.openInfoWindowHtml('<font style="color: black;font-weight: normal;font-size: 17px;">'+ popuptext + '</font>');
        });
        
   return marker;
}

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    
      function Lat49eventFired()     
    { 
    // alert('hi');  
      if(this.map != null)
         {
           var bnds = this.map.getBounds();
           var center = bnds.getCenter();
           var lat = center.lat();
           var lon = center.lng();
           try {
               var zoomlevel = Lat49.Tile.convertGMap2Zoom(this.map.getZoom());
               Lat49.updateAdByLatLon("adcontainer", lat, lon, zoomlevel);
           } catch (e) { }
       }
   }
   
function showTime(){
var Digital=new Date() 
seconds++;

if(seconds >59)
{
 seconds = 0;
 minutes++;
}
if(minutes > 59)
{
 minutes=0;
 hours++;
}
if(seconds < 10)
  seconds = "0" + seconds;

if(minutes < 10)
 minuteStr = "0" + minutes;
else
 minuteStr = minutes;
  
  document.getElementById('DivTextShowTime').innerHTML = hours+":"+minuteStr +":"+seconds+" ";
    if(navigator.appName != "Microsoft Internet Explorer")
    {      
      document.getElementById("DivTextShowTime").style.left ='90px';
    }
  // if(totalCount < 3)
  if(document.getElementById('ButtonPause').value == 'Pause')
   setTimeout("showTime()",1000);

}
 
 function MessageBox(msg)//GameUsersRegister
 { 
   alert(msg);
 }
 function LTrim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");	
}

// Removes ending whitespaces
function RTrim( value ) {	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

// Removes leading and ending whitespaces
function trim( value ) {	
	return LTrim(RTrim(value));	
}

   /*   function GetStartEndLatLong()
   {
   var latLongCookie = document.getElementById('TextBoxStartLatLong').value; // readCookie('CookieStartLatLong'); 
    //alert(latLongCookie);
    if (latLongCookie != null)
         {
             var latLong = latLongCookie.split(",");  
             if (map != null && latLong.length > 0) {               
                 LatStartValue = latLong[0];                                
                 LongStartValue = latLong[1];                   
              }
        } 
        
   latLongCookie = document.getElementById('TextBoxEndLatLong').value; //readCookie('CookieEndLatLong'); 
    //alert(latLongCookie);
    if (latLongCookie != null)
         {
             var latLong = latLongCookie.split(",");  
             if (map != null && latLong.length > 0) {               
                 LatEndValue = latLong[0];                                
                 LongEndValue = latLong[1];                   
              }
        } 
      
   }*/