
function MapControl(div_id,content_base_url,base_url){
	this.setBaseContentUrl(content_base_url);
	this.setBaseUrl(base_url);
	this.map=new GMap2(document.getElementById(div_id));
	this.map.addControl(new GLargeMapControl());
	this.map.addControl(new GMapTypeControl());
	this.map.addControl(new GScaleControl());
	this.map.enableScrollWheelZoom();
}

MapControl.prototype.setDefaultShadow=function(shadow){
	 this.default_shadow=shadow;
}

MapControl.slideshow;

MapControl.right_info_id;
MapControl.right_info_loading_id;
MapControl.right_no_property_in_view_id;

MapControl.prototype.setRightInfoId=function(string){
	this.right_info_id=string;
	$('#'+this.right_info_id).hide();
}
MapControl.prototype.setRightInfoLoadingId=function(string){
	this.right_info_loading_id=string;
}

MapControl.prototype.setRightNoPropertyInViewId=function(string){
	this.right_no_property_in_view_id=string;
}


MapControl.prototype.setSlideShow=function(slideshow){
	this.slideshow=slideshow;	
}

MapControl.prototype.activateChooseRandomRightSide=function(){
	this.choose_random_right_side=true;
}

MapControl.prototype.setCenter=function(latitude,longitude,zoom){
	if(zoom==null)
	this.map.setCenter(new GLatLng(latitude,longitude));
	else
	this.map.setCenter(new GLatLng(latitude,longitude),zoom);
}

MapControl.prototype.setZoom=function(zoom){
	this.map.setZoom(zoom);
}

MapControl.prototype.getMap=function(){
	return this.map;
}

MapControl.choose_random_right_side=false;
MapControl.map=null;
MapControl.mm=null; //GMarkerManager
MapControl.link_properties;
MapControl.link_update_position;
MapControl.link_right_info;
MapControl.listener_moveend;
MapControl.listener_mm_changed;
MapControl.default_shadow;
MapControl.base_content_url;
MapControl.base_url;

MapControl.prototype.init=function(){
	this.mm=new GMarkerManager(this.map);
	this.default_shadow=this.getBaseContentUrl()+'img/mm_20_shadow.png';
	this.cache_mapparts=true;
	this.choose_random_right_side=false;	
	this.initial_load=true;
	this.loadIcons();
	//after zoom change or position change.
	this.listener_moveend=GEvent.bind(this.map,'moveend',this,this.mapEventMove);
	//After a Marker was removed or added in Marker-Manager
	this.listener_mm_changed=GEvent.bind(this.mm,'changed',this,this.mmEventChanged);
	
}

MapControl.prototype.setBaseContentUrl=function(value){
	this.base_content_url=value;
}
MapControl.prototype.getBaseContentUrl=function(){
	return this.base_content_url;
}

MapControl.prototype.setBaseUrl=function(value){
	this.base_url=value;
}
MapControl.prototype.getBaseUrl=function(){
	return this.base_url;
}

MapControl.prototype.setUpdatePositionUrl=function(value){
    this.link_update_position=value;
}
MapControl.prototype.getUpdatePositionUrl=function(){
    return this.link_update_position;
}


MapControl.prototype.setLinkProperties=function(value){
	this.link_properties=value;
}

MapControl.prototype.setLinkRightInfo=function(value){
	this.link_right_info=value;
}

/**
 * Is called if new markers are added or removed
 */
MapControl.prototype.mmEventChanged=function(borders,num_of_markers){
	if(this.choose_random_right_side){
		this.chooseRandomRightSide();
	}
}

//Caches the Parts of a Map First-In-First-Out
MapControl.store_card_parts=null;
MapControl.store_card_index=0;
MapControl.store_card_max=20;
MapControl.initial_load=false;
MapControl.cache_mapparts;

MapControl.prototype.mapEventMove=function(){
	if(this.cache_mapparts){
		if(this.store_card_parts==null){
			this.store_card_parts=Array();
			this.store_card_index=0;
		}
		if(this.isMapPartCached()){
			this.updatePosition();		
			return true;
		}
		
		
		//Store that we already loaded this Mappart!
		this.store_card_parts[this.store_card_index]=this.map.getBounds();
		this.loadProperties();
		if(this.store_card_index>=this.store_card_max){
			this.store_card_index=0;
		}else{
			this.store_card_index++;
		}
	}else{
		this.loadProperties();
	}
	
}

MapControl.prototype.isMapPartCached=function(){
	var check_bounds=this.map.getBounds();
	for(var x=0;x<this.store_card_parts.length;x++){
		var bounds=this.store_card_parts[x];
		if(bounds.containsBounds(check_bounds)){
			return true;
		}
	}
	return false;
}

MapControl.call_attributes;
MapControl.property_type=null;
MapControl.property_for=null;

MapControl.prototype.setCallAttribute=function(key,value){
	if(value.length<=0)
	return;
	if(this.call_attributes==null){
		this.call_attributes=Array();
	}
	
	this.call_attributes[key]=value;
}

MapControl.prototype.getCallAttributes=function(extra_params){
	map_bounds=this.map.getBounds();
	map_sw=map_bounds.getSouthWest();
	map_ne=map_bounds.getNorthEast();

	this.setCallAttribute('sw_lat',map_sw.lat());
	this.setCallAttribute('sw_lng',map_sw.lng());
	this.setCallAttribute('ne_lat',map_ne.lat());
	this.setCallAttribute('ne_lng',map_ne.lng());
    this.setCallAttribute('zoom',this.getMap().getZoom());

	map_center=this.map.getCenter();
	map_center_lat=map_center.lat();
	map_center_lng=map_center.lng();	
	
	this.setCallAttribute('center_lat',map_center_lat);
	this.setCallAttribute('center_lng',map_center_lng);
	
	var params='';
	init=true;
	if(this.call_attributes!=null){
		 for (var key in this.call_attributes){
		 	if(init)
		 	params+=key+'='+escape(this.call_attributes[key]);
		 	else
		 	params+='&'+key+'='+escape(this.call_attributes[key]);
		 	init=false;
		 }
	}
	if(extra_params!=null){
		 for (var key in extra_params){
		 	if(init)
		 	params+=key+'='+escape(extra_params[key]);
		 	else
		 	params+='&'+key+'='+escape(extra_params[key]);
		 	init=false;
		 }
	}
	return params; 
}


MapControl.prototype.loadProperties=function(){
	this.clearTimeoutUpdatePosition();
	GDownloadUrl(this.link_properties,GEvent.callback(this,this.resultProperties),this.getCallAttributes(),"application/x-www-form-urlencoded");
}

MapControl.timeout_posupdate=null;

MapControl.prototype.updatePosition=function(){
	if(this.timeout_posupdate==null){
		var _self = this;
		this.timeout_posupdate=setTimeout(function(ms){_self.call_updatePosition();},3000);
	}else{
        this.clearTimeoutUpdatePosition();
	}
}

MapControl.prototype.call_updatePosition=function(){
	GDownloadUrl(this.link_update_position,GEvent.callback(this,this.resultUpdatePosition),this.getCallAttributes(),"application/x-www-form-urlencoded");
	this.timeout_posupdate=null;
}

MapControl.prototype.clearTimeoutUpdatePosition=function(){
	if(this.timeout_posupdate!=null){
	   clearTimeout(this.timeout_posupdate);
	   this.timeout_posupdate=null;
	}
}

MapControl.prototype.resultUpdatePosition=function(data){
	
}

MapControl.prototype.resultProperties=function(data){
	var all_obj=eval("("+data+")");
	do_run_add_markers=false;
	for(var x=0;x<all_obj.length;x++){
		var obj=all_obj[x];
		if(obj!=null){
			var gps_point = new GLatLng(parseFloat(obj.latitude),parseFloat(obj.longitude));
			data=Array();
			data['description']=obj.title;
			data['link_to_details']=obj.link_to_details;
			marker_added=this.addMarker(obj.object_id,gps_point,obj.accurancy,data,obj.provider);
			if(marker_added){
				do_run_add_markers=true;
			}
		}
	}
	
	//Was it the first time? 
	if(this.initial_load && do_run_add_markers==false){
		$('#'+this.right_info_loading_id).hide();
		$('#'+this.right_no_property_in_view_id).show();
	}
	
	this.initial_load=false;
	
	if(do_run_add_markers)
	this.runAddMarkers();
}

MapControl.marker_store;
MapControl.marker_store_ids;

MapControl.prototype.addMarker=function(id,point,gps_accurancy,data,provider) {
	if(provider==null)
	provider='unknown';
	this.initMarkerStore(provider);
		
	if(this.marker_store[provider][id]!=null){
		//console.log("Marker",provider,id,"cached",this.marker_store[provider][id]);
		return false;
	}
	
	marker=null;
	if(provider=='ebay'){
		marker=new EbayMarker(point,gps_accurancy,id,provider,data['description'],data['link_to_details'],this);
	}else{
		marker=new DefaultMarker(point,gps_accurancy,id,provider,data['description'],data['link_to_details'],this);
	}
	
	
	this.marker_store[provider][id]=marker;
	this.marker_store_ids[provider][this.marker_store_ids[provider].length]=id;
	//console.log("Add to marker store:",marker,provider,id);
	return true;
}

MapControl.prototype.sendGeocodeUpdate=function(provider,property_id){
	$.post(this.getBaseUrl()+'index.php/property/ajax_update_geocoding.html','provider='+escape(provider)+'&property_id='+property_id);
}

MapControl.prototype.getCommercial=function(){
	var screenh = screen.availHeight;
	var store_obj=this;
	//$.post(this.getBaseUrl()+'index.php/property/ajax_commercial.html','screenh='+escape(screenh),function(data){store_obj.getCommercial_Result(data)});
}

MapControl.prototype.getCommercial_Result=function(data){
	$('#commercial_right').append(data);
}

MapControl.prototype.initMarkerStore=function(provider){
	if(this.marker_store==null){
		this.marker_store=new Object();
	}

	if(this.marker_store_ids==null){
		this.marker_store_ids=new Object();
	}
	
	if(this.marker_store[provider]==null){
		this.marker_store[provider]=new Object();
	}
	
	if(this.marker_store_ids[provider]==null){
		this.marker_store_ids[provider]=Array();
	}
}

MapControl.prototype.runAddMarkers=function(){
	//console.log("Run add markers:"," Store:",this.marker_store," IDS:",this.marker_store_ids);
	providers=Array('ebay','mapoot');
	markers=Array();
	cleanup_needed=false;
	provider_id_null_count=0;
	for(var y=0;y<providers.length;y++){	
		provider=providers[y];
		if(this.marker_store_ids[provider]==null){
			continue;
		}
		for(var x=0;x<this.marker_store_ids[provider].length;x++){
			provider_id=this.marker_store_ids[provider][x];
			if(provider_id!=null){
				sel_marker=this.marker_store[provider][provider_id];
				//Delete Element?
				if(!this.map.getBounds().containsLatLng(sel_marker.getMarker().getLatLng())){
					//console.log("Marker",provider,provider_id,"is out of view!");
					this.marker_store[provider][provider_id]=null;
					this.marker_store_ids[provider][x]=null;
					cleanup_needed=true;
				}else if(this.marker_store[provider][provider_id].getMarker().isHidden()){
					//console.log("Marker",provider,provider_id,"is hidden and needed!");
					markers[markers.length]=this.marker_store[provider][provider_id].getMarker();
				}
			}else{
				provider_id_null_count++;
			}
		}
	}
	if(cleanup_needed)
	this.cleanMarkerCache();
	
	this.mm.addMarkers(markers,0);
	this.mm.refresh();
}

MapControl.prototype.cleanMarkerCache=function(){
	//console.log("Cleaning up Marker Cache");
	tmp_marker_cache=new Object();
	tmp_marker_ids=new Object();
	providers=Array('ebay','mapoot');
	for(var y=0;y<providers.length;y++){	
		provider=providers[y];
		if(this.marker_store_ids[provider]==null)
		continue;
		for(var x=0;x<this.marker_store_ids[provider].length;x++){
			if(this.marker_store_ids[provider][x]!=null){
				if(tmp_marker_ids[provider]==null)
				tmp_marker_ids[provider]=Array();
				if(tmp_marker_cache[provider]==null)
				tmp_marker_cache[provider]=new Object();
				
				tmp_marker_ids[provider][tmp_marker_cache[provider].length]=this.marker_store_ids[provider][x];
				tmp_marker_cache[provider][this.marker_store_ids[provider][x]]=this.marker_store[provider][this.marker_store_ids[provider][x]];
			}
		}
	}
	this.marker_store_ids=tmp_marker_ids;
	this.marker_store=tmp_marker_cache;
}

MapControl.current_provider=null;
MapControl.current_id=null;

MapControl.prototype.getRightSideCurrentProvider=function() {
	return this.current_provider;
}

MapControl.prototype.getRightSideCurrentId=function() {
	return this.current_id;
}

MapControl.prototype.loadRightSideInfo=function(id,provider){
	$('#'+this.right_info_loading_id).show();
	//Is it already shown
	if(this.current_provider!=null && this.current_id!=null && this.current_provider==provider && this.current_id==id){
		setTimeout("$('#"+this.right_info_loading_id+"').hide('normal')",200);
		return;
	}
	
	params=Array();
	if(id!=null){
		params['property']=id;
	}
	this.current_provider=provider;
	this.current_id=id;
	params['provider']=provider;
	GDownloadUrl(this.link_right_info,GEvent.callback(this,this.resultRightSideInfo),this.getCallAttributes(params),"application/x-www-form-urlencoded");
}

MapControl.prototype.resultRightSideInfo=function(data){
	this.current_rightside=eval("("+data+")");
	//console.debug(this.current_rightside);
	var fields=['property_for','price','sq_meters','bedrooms','balcony','elevator','available_from','post_date','address'];
	var obj=this.current_rightside;
	var property_id=obj.property_id;
	this.slideshow.setImages(eval(this.current_rightside.images));
	
	for(var x=0;x<fields.length;x++){
		input=eval('obj.'+fields[x]);
		
		if(input instanceof Array){
			for(var y=0;y<input.length;y++){
				$('#'+fields[x]+'_'+(y+1)).html(input[y]);
			}						
		}else{
			if(input!=null){
				$('#'+fields[x]).show();
				$('#'+fields[x]+'_1').html(input);
			}else{
				$('#'+fields[x]).hide();
			}
		}
	}
	var obj_link_to_details=obj.link_to_details;
	$('#link_to_details').attr('href',obj_link_to_details[0]);

	//$('#link_to_save_for_later').attr('onclick',"save_for_later('"+obj.provider+"','"+property_id+"');return false;");
	//Show right side
	$('#'+this.right_info_id).show();
	$('#'+this.right_info_loading_id).hide('normal');
}

MapControl.prototype.chooseRandomRightSide=function(){
	$('#'+this.right_no_property_in_view_id).hide();
	$('#'+this.right_info_loading_id).show();
	
	var choosen_index=null;
	var choosen_type=null;
	var max_random=0.9;
	var max_tries=10;
	var do_stop=false;
	if(this.marker_store!=null){
		while(choosen_index==null && max_tries>0){
         for (var type in this.marker_store){
         	for (var key in this.marker_store[''+type+'']){
      			random=Math.random();
  	         	if(!this.marker_store[''+type+''][key].getMarker().isHidden() && random>max_random){
	         	choosen_index=key;
	         	choosen_type=''+type+'';
	         	do_stop=true;
	         	break;
	         	}
         	}
         	if(do_stop){
         		break;
         	}
         }
         max_random-=0.1;
         max_tries--;
		}
		if(choosen_index!=null && choosen_type!=null){
			$('#'+this.right_no_property_in_view_id).hide();
			this.loadRightSideInfo(choosen_index,this.marker_store[choosen_type][choosen_index].provider);
			this.choose_random_right_side=false;
		}
	}
	
	if(this.choose_random_right_side){
	$('#'+this.right_info_loading_id).hide();
	$('#'+this.right_no_property_in_view_id).show();
	}
}

MapControl.prototype.log=function(text){
	var now = new Date();
	org=document.getElementById('log').innerHTML;
	timestamp="["+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+"] ";
	document.getElementById('log').innerHTML=org+timestamp+text+"<br/>";
}


MapControl.icons;

MapControl.prototype.getIcon=function(type){
	if(this.icons==null)
	this.loadIcons();
	return this.icons[type];
}

MapControl.prototype.loadIcons=function(){
	this.icons=Array();
	this.icons['default'] = new GIcon();
	//this.icons['default'].image = this.getBaseContentUrl()+'img/mm_20_yellow.png';
	this.icons['default'].image = this.getBaseContentUrl()+'img/marker_area_yellow_small.png';
	this.icons['default'].shadow = this.getBaseContentUrl()+'img/mm_25_shadow.png';
	this.icons['default'].iconSize = new GSize(12, 20);
	this.icons['default'].shadowSize = new GSize(22, 20);
	this.icons['default'].iconAnchor = new GPoint(6, 20);
	this.icons['default'].infoWindowAnchor = new GPoint(5, 1);
	
	this.icons['default_aproximated'] = new GIcon();
	//this.icons['default_aproximated'].image = this.getBaseContentUrl()+'img/mm_20_brown.png';
	this.icons['default_aproximated'].image = this.getBaseContentUrl()+'img/marker_area_yellow_gray10_small.png';
	this.icons['default_aproximated'].shadow = this.getBaseContentUrl()+'img/mm_25_shadow.png';
	this.icons['default_aproximated'].iconSize = new GSize(12, 20);
	this.icons['default_aproximated'].shadowSize = new GSize(22, 20);
	this.icons['default_aproximated'].iconAnchor = new GPoint(6, 20);
	this.icons['default_aproximated'].infoWindowAnchor = new GPoint(5, 1);
	
	this.icons['ebay'] = new GIcon();
	this.icons['ebay'].image = this.getBaseContentUrl()+'img/marker_area_yellow_small.png';
//	this.icons['ebay'].image = this.getBaseContentUrl()+'img/mm_20_yellow.png';
	this.icons['ebay'].shadow = this.getBaseContentUrl()+'img/mm_25_shadow.png';
	this.icons['ebay'].iconSize = new GSize(12, 20);
	this.icons['ebay'].shadowSize = new GSize(22, 20);
	this.icons['ebay'].iconAnchor = new GPoint(6, 20);
	this.icons['ebay'].infoWindowAnchor = new GPoint(5, 1);
	
	this.icons['ebay_aproximated'] = new GIcon();
	this.icons['ebay_aproximated'].image = this.getBaseContentUrl()+'img/marker_area_yellow_gray10_small.png';
	this.icons['ebay_aproximated'].shadow = this.getBaseContentUrl()+'img/mm_25_shadow.png';
	this.icons['ebay_aproximated'].iconSize = new GSize(12, 20);
	this.icons['ebay_aproximated'].shadowSize = new GSize(22, 20);
	this.icons['ebay_aproximated'].iconAnchor = new GPoint(6, 20);
	this.icons['ebay_aproximated'].infoWindowAnchor = new GPoint(5, 1);
	
}