﻿//script file om in VE een map te tonen met een aantal parkings

/*global variables*/
var map = null;
var geocoder = new GClientGeocoder();
var extrainfo;

//hoogte & breedte vd kaart, hiermee wordt de table om een adres te zoeken dynamisch geplaatst
var m_mapHeight = null;
var m_mapWidth = null;
/*end global variables*/


/* class definitions */

//class om de zoek ve kaart te initialiseren
function ITO_VE_Initializer(cityToAppend, countryToAppend, street, city, country, info, searchIconURL, pushphinIconURL, msg_AddressNotFound)
{
    this.cityToAppend = cityToAppend;
    this.countryToAppend = countryToAppend;
    this.Street = street;
    this.City = city;
    this.Country = country;
    this.Info = info;
    this.searchIconURL = searchIconURL;
    this.pushphinIconURL = pushphinIconURL;
    this.msg_AddressNotFound = msg_AddressNotFound;
    
}
/* end class definitions */




//functie om een kaar te initialseren
//param: id --> id of div
//param:points --> array of VELatLong objects
//param:showKM (optional) --> KM or Mile Selection
//param:info  (optional) --> ITO_VE_Initializer object. als dit null is, wordt er geen zoekbox getoond, zie class definitions voor meer info 

function initListMap(id,points, showKM, detailzoomlevel, info)
{
    map = new GMap2(document.getElementById(id));
    extrainfo=info;
    var bounds = new GLatLngBounds();
    if (points != null)  
    {

        var j;
        
        j = points.length;
        
         for (var i = 0; i < j; i++)
         {
             //map.addOverlay(new GMarker(points[i],markerOptions));  
             bounds.extend(points[i]);
         }
    }
   
   /* TODO
    if (showKM == null)
        showKM = true;  
    else
    {
        if (showKM)        
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        else
            map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    }*/
    if (points != null)  
    {
         map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds))
    }
    
    map.setUIToDefault();
    map.addControl(new RefineSearchControl());
    map.addControl(new RefineSearchInput());
   
    //hoogte en breedte opslaan van div die de map bevat, adhv kan de custom zoekbox geplaatst worden
    var mapDiv = document.getElementById(id);
    m_mapHeight = parseInt(mapDiv.style.height);
    m_mapWidth = parseInt(mapDiv.style.width);
    
    if (info != null)
    {                        
        //default stad en land toekennen
        
        if (info.cityToAppend != null)
            document.getElementById('txtCity').value = info.cityToAppend;
            
        if (info.countryToAppend != null)
            	document.getElementById('txtCountry').value = info.countryToAppend;           	
      
        if (info.City != null)
        {
        		if (document.all)   //IE
            	document.getElementById('lblCity').innerHTML = info.City;
            else
            		document.getElementById("lblCity").firstChild.nodeValue = info.City;
        }
        if (info.Country != null)
        {
       			if (document.all)   //IE
            	document.getElementById('lblCountry').innerHTML = info.Country;
            else
            	document.getElementById("lblCountry").firstChild.nodeValue = info.Country;
        }   
        if (info.Info != null)
       	{
        		if (document.all)   //IE
        			document.getElementById('lblInfo').innerHTML = info.Info;
        		else
            	document.getElementById("lblInfo").firstChild.nodeValue = info.Info;
        }  
          if (info.Street != null)
        {
        		if (document.all)   //IE
            	document.getElementById('lblstreet').innerHTML = info.Street;
            else
            	document.getElementById("lblstreet").firstChild.nodeValue = info.Street;
        }   
       
    }
}

function search(addr)
{

     //geocoder.setBaseCountryCode('<%= GetCountry() %>');
           
      if (geocoder) {
        geocoder.getLatLng(
          addr,
          function(point) {
            if (!point) {
                alert(extrainfo.msg_AddressNotFound);
            } else {
              map.setCenter(point, 14);
            
              showPusphin(point);
              
              toggleSearch(); //Hide search
            }
          }
        );
      }
}

function showPusphin(point)
        {
            var marker = new GMarker(point, {draggable: false});

            //map.clearOverlays() 
            map.addOverlay(marker);
            //marker.draggable = true;

        }


function addListPushPin(name, description, x, y, imgUrl, infoUrl)
{

    var markerIcon = new GIcon();
    if(imgUrl != '')
    {
        markerIcon.image = imgUrl; 
        markerIcon.iconAnchor = new GPoint(0, 0);  
        markerIcon.infoWindowAnchor = new GPoint(2, 2);
     } 
     else
        markerIcon = new GIcon(G_DEFAULT_ICON);
        
     var html;
     if (infoUrl == null)
        html = '<div class="QPARK_ParkingLocator_InfoBox"><span class="name">' + name + '</span><br><span class="descr">' + description + '</span></div>';
     else
        html = '<div class="QPARK_ParkingLocator_InfoBox><a href="' + infoUrl + '"><span class="name">' + name + '</span></a><br><span class="descr">' + description + '</span></div>';
     
     // Set up our GMarkerOptions object  
     markerOptions = { icon:markerIcon };  
     var marker = new GMarker(new GLatLng(y, x) ,markerOptions);
     GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
     map.addOverlay(marker);  
}

function ShapeHandler(e)
{
    if (e.elementID != null)
    {
         shape = map.GetShapeByID(e.elementID);
//        var url = shape.GetMoreInfoURL();
//        shape.SetDescription(description);
        if (shape.infoUrl != null)
            document.location.href = shape.infoUrl;
    }
}

//voor adres te zoeken in een lijst van parkings
function AddRefineSearchPushpin(name, description, x, y, imgUrl, clearshapes)
{  
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(x, y));
    
    if (imgUrl != null && imgUrl != '')
    {
        var icon = '<div><img src=' + imgUrl + ' /></div>';
        shape.SetCustomIcon(icon);
    }
    
    if (clearshapes != null && clearshapes == true)
        map.Clear();
        
    map.AddShape(shape);
    shape.SetDescription(description);
}



////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////// Alles wat te maken heeft met custom control(s) //////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

var m_shapePushpin;

//functie om events aan een control toe te voegen die in alle browsers zou moeten werken (zie: http://javascript.about.com/library/bldom21.htm)
function addEvent(el, eType, fn, uC) {
    if (el.addEventListener) {
        el.addEventListener(eType, fn, uC);
        return true;
    } 
    else if (el.attachEvent) {
        return el.attachEvent('on' + eType, fn);
    } 
    else {
        el['on' + eType] = fn;
    }
}

function toggleSearch()
{
    var divSearchBox = document.getElementById('divSearchGoogle');
    
    if (divSearchBox.style.display == 'none')
    {
        divSearchBox.style.display = '';
    }
    else
    {
        divSearchBox.style.display = 'none';
    }
    
    return false;
}

function searchPopup(e)
{
  
    if (e == null)
        e = window.event;
        
    var key = (e.keyCode) ? e.keyCode : e.which;
    
    if (key == 13)
    {
         searchPopupclick();
    }
}

function searchPopupclick()
{
    var el = document.getElementById('txtSearch');
    var addr = el.value
    
    
    
    var elcity = document.getElementById('txtCity');
    var elcountry = document.getElementById('txtCountry');
    
    if (elcity.value != '' && elcountry.value != '')
        addr = addr + ', ' + elcity.value + ', ' + elcountry.value;
    else if (elcity.value != '')
        addr = addr + ',' + elcity.value;
    else if (elcountry.value != '')
        addr = addr + ', ' + elcountry.value;    
    search(addr) //TODO , searchHandlerPopup);
}

function searchHandlerPopup(layer, resultsArray, places, hasMore, veErrorMessage)
{
    //goed mogelijk dat places meerdere hits heeft, het eerste nemen in dit geval
    if (places != null && places.length != null && places.length > 0)
    {
        var place = places[0];
        var LL = place.LatLong;
        
        //indien nog niet bestaat -> toevoegen, anders enkel de coordinaten veranderen
        if (m_shapePushpin == null)
        {
            m_shapePushpin = new VEShape(VEShapeType.Pushpin, LL);
            map.AddShape(m_shapePushpin);
            m_shapePushpin.SetDescription('');
       }
        else
        {
            m_shapePushpin.SetPoints([LL]); 
        }
    }
}



// A RefineSearchControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).
// We define the function first

function RefineSearchControl() {}
function RefineSearchInput() {}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object

RefineSearchControl.prototype = new GControl();
RefineSearchInput.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.

RefineSearchControl.prototype.initialize = function(map) 
{  

/*
var container = document.createElement("div");  
var zoomInDiv = document.createElement("div");  
this.setButtonStyle_(zoomInDiv);  
container.appendChild(zoomInDiv);  
zoomInDiv.appendChild(document.createTextNode("Zoom In"));  
GEvent.addDomListener(zoomInDiv, "click", 
    function() {    map.zoomIn();  });  
var zoomOutDiv = document.createElement("div");  
this.setButtonStyle_(zoomOutDiv);  
container.appendChild(zoomOutDiv);  
zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));  
GEvent.addDomListener(zoomOutDiv, "click", 
    function() {    map.zoomOut();  });  
map.getContainer().appendChild(container);  
return container;
*/

    //eerst container creëren
    var div = document.createElement("div");  
    
    var newDiv = document.createElement("div"); 
    //zie QPARKVE.css voor opmaak van deze div        
    newDiv.id = 'searchDivGoogle';
    this.setButtonStyle_(newDiv);  

    div.appendChild(newDiv);
    
    var lnk = document.createElement('a');
    newDiv.appendChild(lnk);
    
    var img = document.createElement('img');
    
    lnk.id = 'lnkToggle';
    lnk.title = '';
    lnk.href = '#'; 

    img.id = 'imgToggle';    
    img.src = extrainfo.pushphinIconURL;
    img.alt = 'Search';
    lnk.appendChild(img);
    
    GEvent.addDomListener(lnk, "click", 
    function() {    toggleSearch();  });  
   
    map.getContainer().appendChild(div);  
    return div;

}

RefineSearchInput.prototype.initialize = function(map) 
{  
    //div waarin een zoekbox getoond zal worden
    var divInput = document.createElement('div');
    
    divInput.id = 'divSearchGoogle';
    divInput.style.display = 'none';
    	
    //divInput.style.width = '234px'; //(m_mapWidth - parseInt(divInput.style.left)) + 'px';    //volledige beschikbare breedte nemen
    divInput.style.zIndex = 1000;
       
    this.setElementStyle_(divInput);  
    
    var htmltable = '<TABLE width="100%"><tr><td colspan="3"><b><span id="lblInfo" class="refinesearchlabel title">lblInfo</span></b></td></tr><tr><td><span id="lblstreet" class="refinesearchlabel">lblStreet</span></td><td><INPUT TYPE="text" id="txtSearch" name="txtSearch"></td><td>&nbsp;</td></tr>';
    htmltable = htmltable + '<tr><td><span id="lblCity" class="refinesearchlabel">lblCity</span></td><td><INPUT TYPE="text" id="txtCity" disabled="true" name="txtCity"></td><td>&nbsp;</td></tr>';
    divInput.innerHTML = htmltable  + '<tr><td><span id="lblCountry" class="refinesearchlabel">lblCountry</span></td><td><INPUT TYPE="text" disabled="true" id="txtCountry" name="txtCountry"></td><td><a href="#" id="searchLnk"><img id="imgSearch" src="' + extrainfo.searchIconURL + '"/></a></td></tr></TABLE>';  
    map.getContainer().appendChild(divInput);  
   
       
    //enter opvangen
    addEvent(document.getElementById('searchLnk'), 'click', searchPopupclick, false); 
    addEvent(document.getElementById('txtSearch'), 'keypress', searchPopup, false);  
    /*GEvent.addDomListener(document.getElementById('searchLnk'), "click", 
    function() {    searchPopupclick();  });  
      GEvent.addDomListener(document.getElementById('txtSearch'), "keypress", 
    function() {    searchPopup();  });  
       */
       
     //teksten aanpassen
    var lblInfo = document.getElementById('lblInfo');
    lblInfo.innerHTML = 'Info....';
    var lblstreet = document.getElementById('lblstreet');
    lblstreet.innerHTML = 'Info....';
    var lblCity = document.getElementById('lblCity');
    lblCity.innerHTML = 'Info....';
    var lblCountry = document.getElementById('lblCountry');
    lblCountry.innerHTML = 'Info....';
       
    return divInput;

}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.

RefineSearchControl.prototype.getDefaultPosition = function() 
{  
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(92, 6));
    
}

RefineSearchInput.prototype.getDefaultPosition = function() 
{  
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(30, 70));
    
}

// Sets the proper CSS for the given button element.

RefineSearchControl.prototype.setButtonStyle_ = function(button) 
{  
/*
button.style.textDecoration = "underline";  
button.style.color = "#0000cc";  
button.style.backgroundColor = "white";  
button.style.font = "small Arial";  
button.style.border = "1px solid black";  
button.style.padding = "2px";  
button.style.marginBottom = "3px";  
button.style.textAlign = "center";  
button.style.width = "20px";  
button.style.cursor = "pointer";
button.style.opacity= 100;
*/
}

RefineSearchInput.prototype.setElementStyle_ = function(button) 
{  
button.style.color = "#0000cc";  
button.style.backgroundColor = "white";  
button.style.font = "small Arial";  
button.style.border = "1px solid black";  
button.style.padding = "2px";  
button.style.marginBottom = "3px";  
button.style.textAlign = "center";  
//button.style.width = "6em";  
button.style.cursor = "pointer";
}