//Debut code pour Maat (auteurs divers) ---- nécessite les-libs.js -----------------------

var baseIcon = new GIcon();
baseIcon.iconAnchor       = new GPoint(4, 14);
baseIcon.infoWindowAnchor = new GPoint(9, 12);

function switchIcon(disponible) {
    var icon = new GIcon(baseIcon);
    switch (disponible) {
        case "1":
            var iconImg = "http://www.paris-parking.com/geolocalisation/images/P-vert";
        	break;
        default:
            var iconImg = "http://www.paris-parking.com/geolocalisation/images/P-rouge";
    }
    iconImg = iconImg + ".png";
    icon.image = iconImg;
    icon.iconSize   = new GSize(14, 14);
    return icon;
}


function createMarker(point, nom, disponible, description) {
    //alert(description);
    var icon = switchIcon(disponible);
    var marker = new GMarker(point,{icon:icon, title:nom});
    GEvent.addListener(marker, "click", function() {
          		  marker.openInfoWindowHtml(description);
          		});
    return marker;
}

function addSquareOverlay ( Lat, Lng, map) {

deltaLng=0.004106691; deltaLat=0.002700084; //pour 300m de demi-côté
var polyline = new GPolyline([
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
	], "#FF8800", 1, 0.9);
map.addOverlay(polyline);
deltaLng=0.004106691/3; deltaLat=0.002700084/3; //pour 100m
var polyline1 = new GPolyline([
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
	], "#FFFF00", 1, 1.0);
map.addOverlay(polyline1);
deltaLng=0.004106691*5.0/3.0; deltaLat=0.002700084*5.0/3.0; //pour 500m
var polyline2 = new GPolyline([
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng + deltaLng),
    new GLatLng(Lat + deltaLat, Lng - deltaLng),
    new GLatLng(Lat - deltaLat, Lng - deltaLng),
	], "#FF4400", 1, 1.0);
map.addOverlay(polyline2);

};


function displayListings(map) {

	GDownloadUrl("/geolocalisation/data/geo-maat.xml", function(data) {
		var xml = GXml.parse(data);
//if ( window.ActiveXObject ) {WriteToFile('avant parse markers');};
		var markers = xml.documentElement.getElementsByTagName("point");
//if ( window.ActiveXObject ) { var chaine = 'Nb total trouvé : ' + markers.length;WriteToFile(chaine);} ;
        var names = xml.getElementsByTagName("name");
        var descriptions = xml.documentElement.getElementsByTagName("description");
		for (var i = 0; i < markers.length; i++) {

// if ( window.ActiveXObject ) {
//var chaine= 'dans boucle' + i; WriteToFile(chaine); 
//var chaine = names[i].getAttribute("Parking");WriteToFile(chaine);
//var chaine = names[i].getAttribute("Disponible");WriteToFile(chaine);
// } ;
			var lenom = names[i].getAttribute("Parking") + ' - Tel: ' + names[i].getAttribute("Telephone") + '\nCliquer pour plus de détails';
 			var ladescription = '';
	for ( var j=0; j < descriptions[i].childNodes.length; j++) {
              ladescription += descriptions[i].childNodes[j].data;
	};
//			var ladescription = 'Descr. ' + descriptions[i].textcontent.data;
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
									parseFloat(markers[i].getAttribute("lng")));
			var marker = createMarker(point, lenom,
                                      names[i].getAttribute("Disponible"),
                                      ladescription);
                       				//descriptions[i].childNodes[0].data);
       		marker.nom = names[i].getAttribute("Parking");
			map.addOverlay(marker);
			}
		});
	}

	


// === Create the tilelayer ===
var tilelayer = new GTileLayer(new GCopyrightCollection(), 0, 17);
      
// === Set the getTileUrl to use the Google KML tile processor with our KML file ===
tilelayer.getTileUrl = function(a,b) {
    b=this.maxResolution()-b;
    return "http://maps.google.com/mapsdt?id=http://www.paris-parking.com/geolocalisation/images/Arrondissements_Paris.kmz&x="+a.x+"&y="+a.y+"&zoom="+b;
    };
tilelayer.isPng = function() {return true;} ;


function flash(marker) {
    var azx = 10;
    var markerDefImg = marker.getIcon().image;
    var flashHandle;
    function flasher() {
        if (azx % 2 == 0) {marker.setImage("http://www.paris-parking.com/geolocalisation/images/P-gris.png");}
        else {marker.setImage(markerDefImg);};
        if (azx-- == 0) {
            marker.setImage(markerDefImg);
            window.clearInterval(flashHandle);};
    }
    flashHandle = window.setInterval(flasher,1000);
}
function log(message,opt_color){}
function logHtml(html){}
function logUrl(url){}
function createElement(tagName,opt_parent,opt_position,opt_size){
    var element=document.createElement(tagName);
    if (opt_position) {moveTo(element,opt_position);}
    else {element.style.position="relative";}
    if(opt_size) setSize(element,opt_size);
    if(opt_parent) opt_parent.appendChild(element);
    return element;
    }
function setSize(element,size) {
    element.style.width = Math.round(size.width)+"px";
    element.style.height = Math.round(size.height)+"px";
    }
function moveTo(element,position) {
    element.style.position = "absolute";
    element.style.left = Math.round(position.x)+"px";
    element.style.top = Math.round(position.y)+"px";
    }
function disableSelection(element) {
    element.onselectstart = returnFalse;
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
    }
function setOpacity(element,opacity) {
    if (navigator.userAgent.indexOf("MSIE") >= 0){element.style.filter = "alpha(opacity="+Math.round(opacity*100)+")";}
    else {element.style.opacity = opacity;}
    }
function stopEvent(e) {
    if(e.stopPropagation){e.stopPropagation();}
    else {e.cancelBubble = true;}
    }
function createPngImage(src,opt_parent,opt_position,opt_size) {
    if(navigator.userAgent.indexOf("MSIE") >= 0) {
        var element = createElement("div",opt_parent,opt_position,opt_size);
        element.style.filter = "progid:DXImageTransform.Microsoft."+"AlphaImageLoader(src='"+src+"')";
        return element;
    }
    else {var image = createElement("img",opt_parent,opt_position,opt_size);
        image.src=src;
        return image;
        }
    }
function Transition(milliseconds,opt_curve) {
    this.milliseconds_ = milliseconds;
    this.curve_ = opt_curve||SineCurve;
    this.start_ = new Date().getTime();
    }
Transition.prototype.run = function(stepTime,stepFn) {
    if(!this.hasNext())return;
    stepFn.call(null,this.next());
    window.setTimeout(GEvent.callbackArgs(this,this.run,stepTime,stepFn),stepTime);
    }
Transition.prototype.hasNext = function() {
    if(this.done_) return this.oneLeft_;
    var now=new Date().getTime();
    if((now-this.start_)>this.milliseconds_){this.done_=true;this.oneLeft_=true;}
    return true;
    }
Transition.prototype.next = function() {
    this.oneLeft_ = false;
    var now = new Date().getTime();
    var percentage = Math.min(1,(now-this.start_)/this.milliseconds_);
    return this.curve_(percentage);
    }

function LinearCurve(percentage){
    return percentage;
    }
function SineCurve(percentage) {
    return(1-Math.cos(percentage*Math.PI))/2;
    }

function SearchControl(opt_initialSearch) {
    this.initialSearch_ = opt_initialSearch;
    this.geocoder_ = new GClientGeocoder();
    }
SearchControl.prototype = new GControl();
SearchControl.prototype.initialize = function(map) {
    var container = createElement("div",map.getContainer());
    var icon = createPngImage("images/spotlight.png",container,new GPoint(0,0),new GSize(25,25));
    icon.style.zIndex = 2;
    var contentContainer = createElement("div",container);
    contentContainer.style.zIndex = 1;
    contentContainer.style.marginLeft = "12px";
    contentContainer.style.height = "25px";
    var searchContainer = createElement("div",contentContainer);
    var form = createElement("form",contentContainer);
    form.action = location.pathname;
    form.method = "get";
    form.onsubmit = GEvent.callback(this,this.doSearch_);
    var input = createElement("input",form);
    input.type = "text";
    input.name = "q";
    input.style.width = "300px";
    input.style.fontFace = "Arial, sans-serif";
    input.style.fontSize = "13px";
    input.style.padding = "1px";
    input.style.paddingLeft = "15px";
    input.style.marginTop = "2px";
    input.style.border = "1px solid #979797";
    if(this.initialSearch_) {input.value = this.initialSearch_;}
    this.input_ = input;
    this.map_ = map;
    return container;
    }
SearchControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,5));
    }
SearchControl.prototype.selectable = function() {
    return true;
    }
SearchControl.prototype.focus = function() {
    this.input_.focus();
    }
SearchControl.prototype.doSearch_ = function() {
    address = this.input_.value;
    leMap = this.map_;
    if(!address) {return false;};
    var overlays = leMap.getOverlays();
    for(var i = 0; i < overlays.length; i++) {
        if((new String(overlays[i].nom)).toLowerCase() == address.toLowerCase()) {
            point = overlays[i].getPoint();
            if(leMap.getZoom()==15){leMap.panTo(point);}
            else{leMap.setCenter(point,15, G_NORMAL_MAP);};
                        //alert('found it: ' + overlays[i].nom); 
           // flash(overlays[i]);
            GEvent.trigger(overlays[i],"click");
            return false;
    }}; 
    this.geocoder_.getLocations(address,GEvent.callback(this,function(res){
            if(res.Status.code!=200) {
                this.showError_("\""+address+"\" est introuvable");return;
                }
            this.showPlacemark_(res.Placemark[0]);}));
    return false;
    }
    
SearchControl.prototype.findThoroughfare_ = function(object) {
    if(!object)return null;
    if(typeof object!='object')return null;
    for(key in object) {
        if(key=="Thoroughfare")return object[key];
        var thoroughfare=this.findThoroughfare_(object[key]);
        if(thoroughfare)return thoroughfare;
        }
    return null;
    }
    
SearchControl.prototype.showPlacemark_ = function(place) {
    var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    var map = this.map_;
   // this.map_.clearOverlays();
    if (this.findThoroughfare_(place)) {
        if(Math.abs(map.getZoom()-16)>3||!map.getBounds().contains(point)){map.setCenter(point,16, G_NORMAL_MAP);}
        this.createMarker_(point,place);}
    else {
        if(map.getZoom()==13){map.panTo(point);}
        else{map.setCenter(point,13, G_NORMAL_MAP);}
        }
    }
SearchControl.prototype.createMarker_ = function(point,place) {
    var marker=new GMarker(point,G_DEFAULT_ICON);
    this.map_.addOverlay(marker);
    var parts=place.address.split(', ');
    var lines=[];lines.push(parts.shift());
    var country=parts.pop();
    lines.push(parts.join(', '));
    lines.push(country);
    var html='<div>'+lines.join('</div><div>')+'</div>';
    GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml(html);});
    marker.openInfoWindowHtml(html);
    }
SearchControl.prototype.showError_ = function(message) {
    var div=createElement("div",this.map_.getContainer());
    div.style.border="1px solid #979797";
    div.style.backgroundColor="white";
    div.style.padding="1em";
    div.style.fontSize="medium";
    div.style.position="absolute";
    div.style.top="50%";
    div.style.left="50%";
    div.style.width="24em";
    div.style.marginTop="-1em";
    div.style.marginLeft="-13em";
    div.style.textAlign="center";
    div.style.zIndex=100000;
    div.appendChild(document.createTextNode(message));
    window.setTimeout(function() {
        var transition = new Transition(500);
        transition.run(25,function(percentage){if(percentage == 1){div.parentNode.removeChild(div);}else{setOpacity(div,1-percentage);}});
        },1000);
    }
function SelfContainedMap(container) {
    this.container_ = container;
    }

SelfContainedMap.prototype.run = function(Lat, Long, Zoom, Carre) {
	var Zoom1 = 12;
	if ( undefined != Zoom ) Zoom1 = Zoom;
	var map = new GMap2(this.container_);
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,35)));
    map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,5)));
    //var searchControl = new SearchControl();
    //map.addControl(searchControl,new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(100,5)));
    map.setCenter(new GLatLng(Lat,Long),Zoom1, G_NORMAL_MAP);
    map.addOverlay( new GTileLayerOverlay(tilelayer) );
	if ( Carre) addSquareOverlay(Lat,Long,map);
    displayListings(map);
    //searchControl.focus();
    }