/**
 * SearchMapRender
 **/

var searchMapRender = null;

function SearchMapRender(renderMenu,renderZoom) {
    this.gmap = null;
    this.geocode = null;
    this.bounds = null;
	
	this.renderMenu = renderMenu;
	this.renderZoom = renderZoom;
	
	this.pins = new HashMap();
	this.markerRedrawCounter = -1;
    this.mapAdjustedToBounds=false;
    
    searchMapRender = this;
};

SearchMapRender.prototype.render = function render(object,htmlElementId){
	
	if(!this.gmap){  
    	
		var div = $(htmlElementId);
    	div.style.display="block";
    	div.style.backgroundColor="white";
	   	div.innerHTML="maps.google.com Kartan kan inte laddas.";
	      
        if (GBrowserIsCompatible()) {
  
      	   this.gmap = new GMap2($("gmap"));
           this.gmap.setCenter(new GLatLng(59.332788, 18.064488), 5);
        
           if(this.renderMenu && this.renderMenu) this.gmap.addControl(new GLargeMapControl());
           if(this.renderZoom && this.renderZoom) this.gmap.addControl(new GMapTypeControl());
 
           this.geocode = new GClientGeocoder();
           this.geocode.setBaseCountryCode("se");
           this.bounds = new GLatLngBounds();

       }else{ 
    	   div.innerHTML = "Kartfunktionen inte kompatibel med webblasaren.";
	   }
	}
	
	if(object==null) {

		//log("SearchMapRender.render object=null?");

		// NOTE THAT IT IS WRONG TO USE THIS METHOD THIS WAY! NOPE ,  
		// log("SearchMapRender.render object=null?");

		return;
	}
	
	var elementList = object.getElementsByTagName("firm");
	
	if (elementList != null && elementList.length > 0) {	

		this.clearMap();
		
		this.markerRedrawCounter = elementList.length;
		// log("searchMapRender.render:"+elementList.length);
		
		for(var i = 0 ; i < elementList.length ; i++){
		
		    var isLast = (i == elementList.length - 1);
		
			var id = elementList[i].getAttribute("id");
			var firmName = elementList[i].getAttribute("name")+" ";
			var hash = elementList[i].getAttribute("hash");
			
			var addresses = elementList[i].getElementsByTagName("address");
			var firmTown = "";
			var street = "";
			var streetnr = "";
			var zip = "";
			
		  	if(addresses != null && addresses != undefined && addresses.length > 0){
		  		var addressNode = addresses[0];
		  		firmAddressId = addressNode.getAttribute("id");
		  		geo = addressNode.getAttribute("geo");
		  		firmTown = addressNode.getAttribute("city");
		  		street = addressNode.getAttribute("street");
		  		zip = addressNode.getAttribute("zip");
		  		streetnr = addressNode.getAttribute("streetnr");
		  		if (streetnr == "-1") streetnr = "";
		  	}
		
			this.addAddress(id, firmAddressId, firmName, street+" "+streetnr+", "+firmTown, geo, isLast,hash); 				
		}

	}	
};

SearchMapRender.prototype.addAddressToProject = function addAddressToProject(innerHtml,address,zoomIn) {

	var t = this;
	if (address.length <= 2) return;
	if (address.toLowerCase().indexOf("box") > 0) return;

	var f = function(point){
		if(point!=null){
			t.bounds.extend(point);
			var markerOptions = null;
			var icon1 = new GIcon(G_DEFAULT_ICON, SearchMapRender.getImageUrl("red"));
			icon1.iconSize = new GSize(32,32);
			markerOptions = {icon:icon1};	
			var marker = new GMarker(point,markerOptions);
			marker.onClick = function () {t.gmap.openInfoWindowHtml(this.getLatLng(),innerHtml);};	
	 		GEvent.bind(marker, "click", marker, marker.onClick);
	 		t.gmap.addOverlay(marker);	
 		}else{
 				//alert(address+" sweden");
 		}
	};
	t.geocode.getLatLng(address+" sweden", f);
};

SearchMapRender.prototype.addAddress =  function addAddress(firmid,firmaddressid,name,address,geo,islast,hash) {

 	// if (B.isIE) log("IE**:ask for addr:"+address+"/"+name);
    // log("map-addr:"+address);

	if(geo!=null && geo!="" && geo != " " && geo != undefined){

		var lat = geo.substring(0,geo.indexOf(";"));
		var lng = geo.substring(geo.indexOf(";")+1);
		
		var point = new GLatLng(parseFloat(lat), parseFloat(lng), true);
		var markerOptions = null;
		
		if(window["ProspectListRender"] && !ProspectListRender.markedfirms.containsKey(firmid)){
			var blueIcon = new GIcon(G_DEFAULT_ICON, this.getImageUrl("blue"));
			blueIcon.iconSize = new GSize(32,32);
			markerOptions = {icon:blueIcon};
		}else{
			var greenIcon = new GIcon(G_DEFAULT_ICON, this.getImageUrl("green"));
			greenIcon.iconSize = new GSize(32,32);
		 	markerOptions = {icon:greenIcon};
		}
		
		var marker = this.createMarker(point,firmid,firmaddressid,address,name,markerOptions,hash);
		this.gmap.addOverlay(marker);
	
		if (markerOptions) marker.orgImgSrc = markerOptions.icon.image;
		this.pins.put(firmid,marker);
	
		this.bounds.extend(point);
		
		this.markerRedrawCounter--;		
       	if(islast || this.markerRedrawCounter < 1){
       		this.setCenter();
       	}
	
	//find point then add to map. 	
	} else if(address.length > 3 && address.toLowerCase().indexOf("box") == -1){
       // if (B.isIE) log("IE:ask google for it...");
       // log("asking google for: '"+address+"'");
       var t = this;

	   t.geocode.getLatLng(address+" sweden", 
       	function(point) {
			if (point != null) {
      			t = searchMapRender;
      			t.bounds.extend(point);
      			// if (B.isIE) log("IE:got coordinate from google:"+point);
      			
      			var markerOptions = null;
      			
				if (window["ProspectListRender"] && !ProspectListRender.markedfirms.containsKey(firmid)){
					icon1 = new GIcon(G_DEFAULT_ICON, SearchMapRender.getImageUrl("blue"));
					icon1.iconSize = new GSize(32,32);
					markerOptions = {icon:icon1};
		
				} else {
					icon1 = new GIcon(G_DEFAULT_ICON, SearchMapRender.getImageUrl("green"));
					icon1.iconSize = new GSize(32,32);
		 			markerOptions = {icon:icon1};
		 			
				}
      		
        		var marker = t.createMarker(point,firmid,firmaddressid,address,name,markerOptions,hash);
          		t.gmap.addOverlay(marker);
          		
          		if (markerOptions) marker.orgImgSrc = markerOptions.icon.image;
          		
				t.pins.put(firmid,marker);
          		
          		//save the geo location in DB.
				if(window.firmHandler)
					firmHandler.saveGeoLocation(firmid,firmaddressid,point.lat(),point.lng());
       			
       		} else {
       		    // TODO: missing place should be visible in the result. 
       		    if (window["debug"]) log("google-map could not find: '"+address+"'");
       		    
       		    var rpin = $("maptag-"+firmid);
       		 
       		    if(rpin && rpin.parentNode)
       		    	rpin.parentNode.removeChild(rpin);  	
       		}
			t.markerRedrawCounter--;
			if(islast || t.markerRedrawCounter < 1 || t.markerRedrawCounter == 4){
   				t.setCenter();
   				// console exists in IE7, but without log
   				// if (window["console"]) window["console"].log("map.setCenter()");
   			}
     	});
	} else { 
		this.markerRedrawCounter--;
		if(islast || this.markerRedrawCounter == 0) this.setCenter();
	}
};

/*
*
*/
SearchMapRender.prototype.setOrgImg = function setOrgImg(marker,color){
	if(marker){
		if(color==null){
			marker.orgImgSrc = this.getImageUrl("blue");
		}else{
			marker.orgImgSrc = this.getImageUrl(color);	
		}
	}
	return marker;	
};

/*
*
*/
SearchMapRender.prototype.changePinColor = function changePinColor(marker,color){
	if(marker){
		if(color==null){
			marker.setImage(marker.orgImgSrc);	
		}else{
			marker.setImage(this.getImageUrl(color));	
		}
	}
	return marker;	
};

/*
*
*/
SearchMapRender.prototype.getImageUrl = function getImageUrl(color){
	if(color == "yellow" || color == "red" || color == "pink" || color == "blue" || color == "green" || color == "purple"){
	    if (window.location.href.indexOf("firstrater1/") > 0)
	       return "/firstrater1/images/"+color+"-dot.png"; 
		return "/images/"+color+"-dot.png"; 
	}		
	return null;
};

SearchMapRender.getImageUrl = SearchMapRender.prototype.getImageUrl;
 
SearchMapRender.prototype.setCenter = function setCenter(){
	this.gmap.setCenter(this.bounds.getCenter(), this.gmap.getBoundsZoomLevel(this.bounds));
	this.mapAdjustedToBounds=true;
};

SearchMapRender.prototype.setZoom = function setZoom(level){
	this.gmap.setZoom(level);
};
   
SearchMapRender.prototype.createMarker = function createMarker(point,firmid,firmaddressid,address,name,markerOptions,hash){
 		
	var marker = new GMarker(point,markerOptions);
	var t = this;
	
	marker.onClick = function () {
		var str = (ProspectListRender.markedfirms.containsKey(firmid))? "avmarkera denna firma" : "v\u00e4lj denna firma"
    	t.gmap.openInfoWindowHtml(this.getLatLng(),"<b><a href='"+window["contextPath"]+"/firm/?id="+firmid+"."+hash+"'>"+name+"</b></a><br/>"+address + "<br /><br /> <a href='#' onClick='javascript:SearchListRender.toggleCheckedFirm({id:"+firmid+",status:\"NEW\"},"+firmaddressid+");searchMapRender.changePinColor((searchMapRender.pins.get("+firmid+")),null);searchMapRender.gmap.closeInfoWindow();return false;'>"+str+"</a>")
	};
	
	GEvent.bind(marker, "click", marker, marker.onClick);
	
	marker.onmouseover = function(){
		var r = $(firmid); 
		if (r) r.className = "listrowon";
		t.changePinColor(marker,"yellow");			
	};
	GEvent.bind(marker, "mouseover", marker, marker.onmouseover);
	
	marker.onmouseout = function(){
		var r = $(firmid); 
		if (r) r.className = "listrowoff";
		t.changePinColor(marker,null);
	};
	GEvent.bind(marker, "mouseout", marker, marker.onmouseout);
	
	return marker;
};

SearchMapRender.prototype.clearMap = function clearMap() {
	if (this.gmap == null) return
    this.gmap.clearOverlays();
    this.bounds = new GLatLngBounds();
    this.pins = new HashMap();    
};
 	


