var myIconItem = new google.maps.Icon();
myIconItem.image = "/static/icons/casa.png";
myIconItem.iconSize = new google.maps.Size(32, 32);
myIconItem.iconAnchor = new google.maps.Point(14, 31);
myIconItem.infoWindowAnchor = new google.maps.Point(5, 1);
myIconItem.dragCrossImage = "";
myIconItem.maxHeight = 0.1; 

var myIconItemPhoto = new google.maps.Icon();
myIconItemPhoto.image = "/static/icons/casa_foto.png";
myIconItemPhoto.iconSize = new google.maps.Size(32, 32);
myIconItemPhoto.iconAnchor = new google.maps.Point(14, 31);
myIconItemPhoto.infoWindowAnchor = new google.maps.Point(5, 1);
myIconItemPhoto.dragCrossImage = "";
myIconItemPhoto.maxHeight = 0.1; 

var myIconPOI = new google.maps.Icon();
myIconPOI.iconSize = new google.maps.Size(32, 32);
myIconPOI.iconAnchor = new google.maps.Point(14, 31);
myIconPOI.infoWindowAnchor = new google.maps.Point(15, 0);
myIconPOI.dragCrossImage = "";
myIconPOI.maxHeight = 0.1;

var ZANGOA_STATUS_DEFAULT = 1; // El mapa esta en estado normal
var ZANGOA_STATUS_INFOPOINT_EDITOR = 2; // El mapa esta en modo editor de infpoint
var ZANGOA_HOME_ADS_DISTANCE = 30000; // in meters, distància per calcular quan s'han de recarregar els anuncis de la home

var zangoa_status = ZANGOA_STATUS_DEFAULT; //estado de la aplicacion

var zoom_no_filter = 8;
var zoom_no_pois = 11;
    
var pe = {}; //POIEditor
var map = {};   // Map() object
var geo;        //GClientGeocoder() object
var currentZoom = 10;
var tooltip;
var map_global = false;
var map_detail = false;
var map_stage = false;
var show_all_pois = false;
var mm = {}; // mapmanager
var poly = {};
var stage_id = 0;

var Map = window.Map = function(){
    return{
    		initStage: function (stg_id, stage_poly) {
    			poly = stage_poly;
    			stage_id = stg_id;
    			Map.initialize(2, poly.getBounds().getCenter().lat(), poly.getBounds().getCenter().lng());
    		},
    
        initialize: function(type, lat, lon, zoom) {
        	
            if (type == 0) {
            	map_global = true;
            } else if (type == 1) {
            	map_detail = true;
            } else if (type == 2) {
            	map_stage = true;
            } else if (type == 3) {
            	map_detail = true;
            	show_all_pois = true;
            }
            
            Map.loadStatus();
            if (map_global) {  // Load status only if map is global
            	if (zangoa.settings.lat) {
            		lat = zangoa.settings.lat;
            	}
            	if (zangoa.settings.lon) {
            		lon = zangoa.settings.lon;
            	}
            	if (zangoa.settings.zoom) {
            		zoom = zangoa.settings.zoom;
            	}
            }

            Map.resize();
            Map.initMap(lat, lon, zoom);
            Map.bindWindowEvents();
						
						mm = new MapManager(map);
						mm.refresh();
						mm.getData();
            
            pe = new POIEditor(map); 
            geo = new google.maps.ClientGeocoder();

			  if (map_global) {
				  
	            GEvent.addListener(map, "moveend", function() {
	            	
	            	if (zangoa_status == ZANGOA_STATUS_INFOPOINT_EDITOR) return;
		         		//mm.closeInfoWindow();
		         	      if (map.getZoom() >= zoom_no_filter) {
		          			$("#sidebar").hide();
		          			if($("#filter2").is(":hidden") && $("#filter1").is(":hidden")) {
			          			$("#filter2").hide();
			          			$("#filter1").show();		          				
		          			}
		          		} else {
		          			$("#filter1").hide();
		          			$("#filter2").hide();
		          			$("#sidebar").show();
		          		}      
	
							 
	             	mm.getData();
	            });
	            
	            GEvent.addListener(map, "dragend", function() {
		         		//mm.closeInfoWindow();
	            });
	            
	            GEvent.addListener(map, "zoomend", function() {
	            	mm.closeInfoWindow();
	            });
	            
	          } else if (map_detail) {
         	     //init wiki layer
		            if (mm.getWikipedia() == 1) {
		            	mm.addWikiLayer();
		            	$("#check_wiki").attr('checked', true);
		            } else {
		            	$("#check_wiki").attr('checked', false);
		            }
		           Map.setWikiEvents();
	          } else if (map_stage) {
	          	//init wiki layer
		            if (mm.getWikipedia() == 1) {
		            	mm.addWikiLayer();
		            	$("#check_wiki").attr('checked', true);
		            } else {
		            	$("#check_wiki").attr('checked', false);
		            }
		           Map.setWikiEvents();
	          
	          }
	          
	          
	            Map.refreshCheckTypes();
	            
	            // draw pois in edit poi map
	            if (show_all_pois) {
	          	  for (key in mm.pois) {
	          		   	mm.pois[key].show();
	          	  }
	            }
	            
	        }, // end initialize
        
        initMap: function(lat, lon, zoom){
            var settings = zangoa.settings;
            map = new google.maps.Map2(document.getElementById("map"));
            map.addMapType(G_PHYSICAL_MAP);

            map.setMapType(map.getMapTypes()[settings.mapType]);
            
            map.addControl(new google.maps.MapTypeControl());
            map.setUIToDefault();

			  tooltip = document.createElement("div");
	          map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
	          tooltip.style.visibility="hidden";

            if (map_global) {
            	map.addControl(new GOverviewMapControl(new GSize(150,150)));
	            map.enableScrollWheelZoom();
	            map.enableContinuousZoom();
	            
	            zoom = parseInt(zoom);
	           	if (map.getCurrentMapType().getMaximumResolution()<zoom) {
	 							zoom=map.getCurrentMapType().getMaximumResolution();
							}
	            	            
	            map.setCenter(new google.maps.LatLng(lat, lon), zoom);
	          
		          // ====== Restricting the range of Zoom Levels =====
	            // Get the list of map types      
	            var mt = map.getMapTypes();
	            // Overwrite the getMinimumResolution() and getMaximumResolution() methods
	            for (var i=0; i<mt.length; i++) {
	                mt[i].getMinimumResolution = function() {return 2;}
	            }
	            
	          }

	          if (map_detail) {
              map.setCenter(new GLatLng(lat, lon), 13);
              var item = new GMarker(new GLatLng(lat, lon), {icon: myIconItem, zIndexProcess: function(){ return 1000000}});
	      			map.addOverlay(item);
	            
	            // ====== Restricting the range of Zoom Levels =====
	            // Get the list of map types      
	            var mt = map.getMapTypes();
	            // Overwrite the getMinimumResolution() and getMaximumResolution() methods
	            for (var i=0; i<mt.length; i++) {
	                mt[i].getMinimumResolution = function() {return 9;}
	                //mt[i].getMaximumResolution = function() {return 18;}
	          	}
	          

	           	map.disableScrollWheelZoom();
		        }  
		        
		        if (map_stage) {
		         	map.addOverlay(poly);
		         	map.setCenter(poly.getBounds().getCenter(), map.getBoundsZoomLevel(poly.getBounds())-1);
	            	            
	            // ====== Restricting the range of Zoom Levels =====
	            // Get the list of map types      
	            var mt = map.getMapTypes();
	            // Overwrite the getMinimumResolution() and getMaximumResolution() methods
	            for (var i=0; i<mt.length; i++) {
	                mt[i].getMinimumResolution = function() {return 9;}
	                //mt[i].getMaximumResolution = function() {return 18;}
	          	}
	          		          
	           	map.disableScrollWheelZoom();
		        }
                
	      }, //end initMap
        
        draw: function() {
            MapManager.showItems();
        }, //end Draw
        
        bindWindowEvents : function(){
            $(window).bind('resize', function(){ Map.resize() });
        },
        resize : function() {
            if ($("#homepage #map-wrapper").css("display") === "none"){
                return;
            }
            var height =  Map.getWindowHeight() - ( $('#header').get(0).offsetHeight + $('#footer').get(0).offsetHeight );
            var width  = Map.getWindowWidth() - ($('#filter').get(0).offsetWidth + 20);
            //var width  = Map.getWindowWidth() - 20;

            $('#homepage #map-wrapper').css('width', width + 'px');
            $('#homepage #map-wrapper').css('height', height + 'px');
            $('#homepage #filter').css('height', (height-11) + 'px');
            $('#homepage #map_item_list').css('height', (height-330) + 'px');
            
            $('#hhh').val(height);
            $('#www').val(width);
            
        }, //end resize

        getWindowHeight : function() {
            var windowHeight=0;
            if (typeof(window.innerHeight) === 'number') {
                windowHeight=window.innerHeight;
            } 
            else if (document.documentElement&&document.documentElement.clientHeight) {
                windowHeight=document.documentElement.clientHeight;
            } 
            else if (document.body&&document.body.clientHeight) {
                windowHeight=document.body.clientHeight;
            }
            return windowHeight;
        }, //end getWindowHeight

        getWindowWidth : function() {
            var windowWidth=0;
                if (typeof(window.innerWidth) === 'number') {
            windowWidth=window.innerWidth;
            } 
            else if (document.documentElement&&document.documentElement.clientWidth) {
                windowWidth=document.documentElement.clientWidth;
            } 
            else if (document.body&&document.body.clientWidth) {
                windowWidth=document.body.clientWidth;
            }
            return windowWidth;
        }, //end getWindowWidth
        
        updatePOIsbyType: function(checkbox){
          var type = $(checkbox).attr('name');
          var checked = $(checkbox).attr('checked')
          
          if(checked) {
              mm.showType(type);
          }
          else {
              mm.hideType(type);
          }
        },
        
	      refreshCheckTypes: function(){
	          var me= this;
	          $('#poi_filter').find("input").each(function(){
	             var type = $(this).attr("name");
	             var visibility = mm.getVisibility();
	
	    		if (jQuery.inArray(parseInt(type), visibility) > -1) {
	                 $(this).attr("checked",true);
	             }
	             else {
	                 $(this).attr("checked",false);                
	             }  
	             $(this).click(function(){
	             	 if (map.getZoom() >= 10) {              
	               	 Map.updatePOIsbyType(this)}
	               }
	             );  
          });
        },   
        
        setWikiEvents: function() {
          //set wiki click
          $("#check_wiki").click(function(){
		     	if ($(this).attr('checked')) {
		     		mm.addWikiLayer();
		     		mm.setWikipedia(1);
		   		} else {
		   			mm.removeWikiLayer();
		   			mm.setWikipedia(0);
		   		}
		     });
        }, // end wikievents
        
        loadStatus: function(){
            loadStatus();    
        }, //end loadStatus

        saveStatus: function(){
        		if (map_detail) {
        			loadStatus();
        			var settings = zangoa.settings;
			        settings.wikipedia = mm.getWikipedia();
        		} else {
	            var settings = zangoa.settings;
	            var center = map.getCenter();
	            var zoom = map.getZoom();
	            var mapType = 0;
	            for (var i=0;i<map.getMapTypes().length;i++) {
	                if (map.getCurrentMapType() == map.getMapTypes()[i]) {
	                    mapType = i;
	                }
	            }
	            settings.lat = center.lat();
	            settings.lon = center.lng();
	            settings.zoom = zoom;
	            settings.mapType = mapType;
						}
            var string = settings.lat + "|" + settings.lon + "|" + settings.zoom + "|" + settings.mapType + "|" + mm.getVisibility().join("-") + "|" + settings.wikipedia;

            $.cookies.set('zangoamap',string);
        } //end saveStatus
    }//end return
}(); //end Map

function MapManager(map, opt_opts){
    this.options = opt_opts || {};
    
    this.map_ = map;
		this.mapZoom_ = map.getZoom();
    
    this.clusters = []; // se guardan los clusters de items
    this.items = []; //guarda los items por id
    
    this.pois = []; // guarda los puntos de inter�s
    this.pois_by_type = []; //guarda los infopoints por categoria
    this.pois_visibility = zangoa.settings.categories;  // guarda la visibiliad por categoria   
    this.wikipedia = zangoa.settings.wikipedia;
    this.wiki_layer = new GLayer("org.wikipedia.es");
    
    this.home_ads_latlng = new GLatLng(0,0);
}  

MapManager.prototype.refresh = function(force) {
    if (map.getZoom() != currentZoom || force) {
    	this.hideItems();
    	this.hidePOIs();
    	this.hideClusters();
    }
}


MapManager.prototype.hideClusters = function() {
		zoom = this.map_.getZoom()
    for (key in this.clusters[zoom]) {
        this.map_.removeOverlay(this.clusters[zoom][key]);
        //this.items[key].hide();
    }    
}


MapManager.prototype.hideItems = function() {
    for (key in this.items) {
        this.map_.removeOverlay(this.items[key]);
        //this.items[key].hide();
    }    
}

MapManager.prototype.showItems = function() {
    for (key in this.items) {
        this.items[key].show();
    }    
}

MapManager.prototype.getData = function(foreceLoadAds) {
	
	if (map_global) {
		this.getDataGeneral();
	}
	
	if (map_detail) {
		this.getDataDetail();
	}

	if (map_stage) {
		this.getStageDetail();
	}

	return;
}

MapManager.prototype.closeInfoWindow = function() {
  this.map_.closeExtInfoWindow();
}


MapManager.prototype.getDataGeneral = function(force) {
    var me = this;
    var bounds = me.map_.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var zoom = me.map_.getZoom();

    if (typeof me.clusters[zoom] == 'undefined') me.clusters[zoom] = new Array();	

		if (zoom != me.mapZoom_ || force) {
		    for (i in me.clusters) {
		    	for(j in me.clusters[i]) {
		    	    map.removeOverlay(me.clusters[i][j]);
		    	}	
		    }
		    me.clusters = [];
		} 

		me.mapZoom_ = zoom;


    var params = {
        "minx": southWest.lng(),
        "miny": southWest.lat(),
        "maxx": northEast.lng(),
        "maxy": northEast.lat(),
        "z"   : zoom
    };
    
  	params = getFilterParams(params);

		// refresh map before ajax call, if not the items are displayed during the call
		me.refresh(true);

    $.ajax({
        url: buildAjaxUrl("/ajax/items/"),
        data: params,
        dataType: 'json',
        async: false,
        cache: false,

        error: function(){},

        success: function(rs,textstatus){
             var curZoom = me.map_.getZoom();
             //if currend zoom of map different of input data, do nothing
             if (rs.zoom != curZoom)  return;

             $('#bar-items-num').html(rs.count);
             me.refresh(true); 
	           //me.map_.clearOverlays();
						 me.items = [];
						 me.pois = [];
						 
	           me.processJSON(rs.items);
	           if (rs.items.length == 0 && rs.clusters.length==0) {
	        	   $('#alert').html(translate('no_home_results')).show();
	           } else{
	        	   $('#alert').html('').hide();
	           }
	           if (rs.zoom>zoom_no_pois) {
	           		me.processPOIS(rs.pois);
	           		$("#message_list_many_pois").hide();
	           } else {
	           		$("#message_list_many_pois").show();
	           }
	           me.createItemList(rs);
	           me.createRegionList(rs);
	           me.createCountryList(rs);
	           //me.createItemTypeList(rs);

             $.each(rs.clusters, function(i, json) {
               if (typeof me.clusters[json.zoom] == 'undefined') me.clusters[json.zoom] = [];
               if (me.clusters[json.zoom][json.id] instanceof Cluster){
                   me.map_.removeOverlay(me.clusters[json.zoom][json.id]);
                   //var cluster = create_cluster(json.minx, json.miny, json.maxx, json.maxy, json.items, {id: json.id});
                   
                   var cluster = create_cluster(json.minx, json.miny, json.maxx, json.maxy, json.avgx, json.avgy, json.items, {id: json.id, name: json.name});
                   me.clusters[json.zoom][cluster.id] = cluster;
               } else {
                   //var cluster = create_cluster(json.minx, json.miny, json.maxx, json.maxy, json.items, {id: json.id});
            	   
              	 var cluster = create_cluster(json.minx, json.miny, json.maxx, json.maxy, json.avgx, json.avgy, json.items, {id: json.id, name: json.name});
                   me.clusters[json.zoom][cluster.id] = cluster;
               }
           	   if(json.zoom == curZoom){
	        	 	 	map.addOverlay(cluster);
  	      	   }  
             });

        }
    });
}


MapManager.prototype.getDataDetail = function() {
    var me = this;
    centerx = me.map_.getCenter().lng();
    centery = me.map_.getCenter().lat();
    distance = 0.4 //50km aprox
    
    var zoom = me.map_.getZoom();

    if (typeof me.clusters[zoom] == 'undefined') me.clusters[zoom] = new Array();	

    me.mapZoom_ = zoom;

    var params = {
        "minx": centerx-distance,
        "miny": centery-distance,
        "maxx": centerx+distance,
        "maxy": centery+distance,
        "z"   : zoom
    };
  
    $.ajax({
        url: buildAjaxUrl("/poi/ajax/pois/"),
        data: params,
        dataType: 'json',
        async: false,
        cache: false,

        error: function(){},

        success: function(rs,textstatus){
           var curZoom = me.map_.getZoom();
           //if currend zoom of map different of input data, do nothing
           if (rs.zoom != curZoom)  return;             
           //me.refresh(); 
           me.processPOIS(rs.pois);
        }
    });
}

MapManager.prototype.getStageDetail = function() {
    var me = this;
    
    //var zoom = me.map_.getZoom();

    //if (typeof me.clusters[zoom] == 'undefined') me.clusters[zoom] = new Array();	

    //me.mapZoom_ = zoom;

    var params = {
        "stage_id": stage_id
    };
  
    $.ajax({
        url: buildAjaxUrl("/trail/ajax_stage/"),
        data: params,
        dataType: 'json',
        async: false,
        cache: false,

        error: function(){},

        success: function(rs,textstatus){
           //var curZoom = me.map_.getZoom();
           //if currend zoom of map different of input data, do nothing
           //if (rs.zoom != curZoom)  return;             
           //me.refresh(); 
           me.processPOIS(rs.pois);
           me.processJSON(rs.items);
        }
    });
}   


MapManager.prototype.createItemTypeList = function(rs) {
    var me = this;
    var content = [];
    var selected = $('#type').val();
    
    $('#type').empty();

    content.push('<option value="">Tipo de alquiler</option>');
 
	$.each(rs.types, function(i, json) {
		if (json.id == selected) {
			content.push('<option value="'+json.id+'" selected>'+json.desc+'</option>');
		} else {
			content.push('<option value="'+json.id+'">'+json.desc+'</option>');
		}
	});
	
	$('#type').html(content.join('\n'));
	
}

MapManager.prototype.createRegionList = function(rs) {
	var me = this;
    var region = ''
    var k = 0;
    var content = [];
    $('#region_list').empty();
    content.push('<ul>');
	$.each(rs.regions, function(i, json) {
		if (region != json.country_id) {
			if (k>=4) {
				content.push('<li><h2><a href="#" id="more_region_'+ region +'">más..</a></li>');
			}
			
			content.push('</ul>');
			content.push('<ul id="region_country_'+ json.country_id +'">');
			content.push('<li class="region_country"><h2>'+json.country+'</li>');
			region = json.country_id;
			k=0;
		} else {
			k = k+1;
		}

		if (k<4) {
			content.push('<li><h2><a href="#" id="region_'+ json.id +'" title="'+ json.name +'">'+ json.name +'</a></h2></li>');
		} else {
			content.push('<li style="display:none"><h2><a href="#" id="region_'+ json.id +'" title="'+ json.name +'">'+ json.name +'</a></h2></li>');
			//ids_hidden.push(json.id)
		}

		if (i==rs.regions.length-1) {
			if (k>=4) {
				content.push('<li id="li_more_region"><h2><a href="#" id="more_region_'+ region +'">más..</a></li>');
				content.push('<li id="li_close_more_region" style="display:none"><h2><a href="#" id="close_more_region_'+ region +'">cerrar</a></li>');
			}
		}
		
	});
	
	content.push('</ul>');
	
	$('#region_list').html(content.join('\n'));

	$.each(rs.regions, function(i, json) {
		$('#region_' + json.id).click(function(){
			  setCenterMap(json.ne_lat, json.ne_lon, json.sw_lat, json.sw_lon);
			  return false;
		});
		$('#more_region_' + json.country_id).click(function(){
			$('#region_country_'+json.country_id+ ' li').show();
			$('#li_more_region').hide();
		});
		
		$('#close_more_region_' + json.country_id).click(function(){
			$('#region_country_'+json.country_id+ ' li:gt(4)').hide();
			$('#li_more_region').show();
			$('#li_close_more_region').hide();
		});
	});
	
}

MapManager.prototype.createCountryList = function(rs) {
	var me = this;
    if (rs.countries) {
        var region = ''
        var k = 0;
        var content = [];
        $('#region_list').empty();
        content.push('<ul>');
    	
		$.each(rs.countries, function(i, json) {
			content.push('<li><h2><a href="#" id="region_'+ json.id +'" title="'+ json.name +'">'+ json.name +'</a></h2></li>');
		});
		
		content.push('</ul>');
		
		$('#region_list').html(content.join('\n'));
	
		$.each(rs.countries, function(i, json) {
			$('#region_' + json.id).click(function(){
				  setCenterMap(json.ne_lat, json.ne_lon, json.sw_lat, json.sw_lon);
				  return false;
			});
		});
    }
}



MapManager.prototype.createItemList = function(rs) {
    var me = this;
    $('#map_item_list_ajax').empty();
    $('#map_item_list').empty();
    $('#PaginationMap').empty();
    
    if(rs.item_ad) {
     	 $('#no_ads').hide();
     	 $('.ad_medium').show();
 
     	 for (i=0; i<2; i++) {
          $('#ad_small_'+i+' p.name a').text(rs.item_ad.title);
          $('#ad_small_'+i+' p.city').text(rs.item_ad.city);
          $('#ad_small_'+i+' img').attr('src', rs.item_ad.thumbnail);
          $('#ad_small_'+i+' a').attr('href', url_show_item.replace('item_slug/item_slug/item_slug', rs.item_ad.slug));
         }
    } else {
    	$('.ad_medium').hide();
    }
    
    if (rs.clusters.length>0) {
    	//show message
    	$("#message_list_many_items").show();
    } else {
    	$("#message_list_many_items").hide();
    }
    
    showItemList(rs, true); 
    
}

function showItemList(rs, all) {
	k=0;
	$.each(rs.items, function(i, json) {
			premium_class = ' class="premium"';
       if (json.credential==1) {
       	premium_class = '';
       } 
       //no pagination
       if (all || json.credential == 3) {
       	if((rs.items.length>10 && all) || rs.count_premim > 10 ) {
       		k=k+1;
       		//$('#map_item_list_ajax').append('<div class="result"><li'+premium_class+'><a href="'+url_show_item.replace('item_slug', json.slug)+'">'+json.title+'</a><br /><img src="/static/assets/box-beds.png" style="height:15px;"/>'+json.pax+' <i>'+json.city+'</i></li></div>');
       		$('#map_item_list_ajax').append('<div class="result"><li'+premium_class+'><a href="'+url_show_item.replace('item_slug/item_slug/item_slug', json.slug)+'">'+json.title+'</a><br /><i>'+json.city+'</i></li></div>');
       	} else {
       		k=k+1;
       		//$('#map_item_list').append('<div class="result"><li'+premium_class+'><a href="'+url_show_item.replace('item_slug', json.slug)+'">'+json.title+'</a><br /><img src="/static/assets/box-beds.png" style="height:15px;"/>'+json.pax+' <i>'+json.city+'</i></li></div>');
       		$('#map_item_list').append('<div class="result"><li'+premium_class+'><a href="'+url_show_item.replace('item_slug/item_slug/item_slug', json.slug)+'">'+json.title+'</a><br /><i>'+json.city+'</i></li></div>');
       	}
       }
    });
    
    if (k>10){
		  initPaginationMap();
	  } else {
			$('#map_item_list_ajax').empty();
			$("#PaginationMap").empty();
	  }

}


MapManager.prototype.processJSON = function(rs) {
    var me = this;

    $.each(rs, function(i, json) {
        if (typeof(me.items[json.id]) == 'undefined') {
            me.add(me.createItemFromJson(json));
        }
    });
}
MapManager.prototype.add = function(item) {
    var me = this;
    me.items[item.id] = item;
    me.map_.addOverlay(item);
}

MapManager.prototype.createItemFromJson = function(json) {
	//$('#list-results').append('<li><a href="'+url_show_item.replace('item_slug', json.slug)+'">'+json.title+'</a></li>');
	if (json.credential==1){ //Basic
		return this.createItem(new google.maps.LatLng(json.lat,json.lon), {id: json.id, title: json.title, credential: json.credential, draggable: false, icon:myIconItem });
	} else { //Premium
		return this.createItem(new google.maps.LatLng(json.lat,json.lon), {id: json.id, title: json.title, credential: json.credential, draggable: false, icon:myIconItemPhoto });
	}
}

MapManager.prototype.refreshItems = function(){
    for (key in this.items) {
        this.items[key].refresh();
    }   
}

MapManager.prototype.createItem = function(point, opt_opts) {
    var me = this;
    opt_opts['zIndexProcess'] = function(){ return 1000000;}
    var item = new Item(point, opt_opts);
    item.disableDragging();   
    item.selectInfoWindow();
    item.updateEvents();
    
    return item;
}

MapManager.prototype.addWikiLayer = function(){
	this.map_.addOverlay(this.wiki_layer);
}

MapManager.prototype.removeWikiLayer = function(){
	this.map_.removeOverlay(this.wiki_layer);
}

MapManager.prototype.getWikipedia  = function(){
	return this.wikipedia;    
} 

MapManager.prototype.setWikipedia = function(value){
	this.wikipedia = value;
}

MapManager.prototype.hidePOIs = function() {
    for (key in this.pois) {
        this.pois[key].hide();
    }    
}       

MapManager.prototype.getVisibility  = function(){
	/*console.log (this.pois_visibility);
	console.log ('categories' + zangoa.settings.categories);
	console.log ('cat2' + categories_array);
	*/
	return this.pois_visibility;    
}  

MapManager.prototype.isTypeVisible  = function(type){
	return jQuery.inArray(parseInt(type), this.pois_visibility);    
}  

MapManager.prototype.showPOIs = function() {
    for (key in this.pois) {
    	if (jQuery.inArray(this.pois[key].type, this.pois_visibility) > -1) {
        	this.pois[key].show();
        }
    }    
}

MapManager.prototype.showType = function(type) {
    for (key in this.pois_by_type[type]) {
	   	this.pois[key].show();
    }
    if (this.isTypeVisible(type) == -1) {
    	this.pois_visibility.push(parseInt(type));
    }
    
    $('#id_poi_type_'+type).attr("checked",true);
}

MapManager.prototype.hideType = function(type) {
    for (key in this.pois_by_type[type]) {
	   	this.pois[key].hide();
    }
    index = this.isTypeVisible(parseInt(type));
    if (index > -1) {
    	this.pois_visibility.splice(index, 1);
    }
}  

MapManager.prototype.processPOIS = function(rs) {
   var me = this;

    $.each(rs, function(i, json) {
        if (typeof(me.pois[json.id]) == 'undefined') {
           // creem l'array per categoria si encara no hiha cap punt d'questa categoria
           if(typeof(me.pois_by_type[json.type]) == 'undefined'){
							me.pois_by_type[json.type] = new Array();
							//   infopoints_visibility[json.category] = false;
						}                      
						
            me.addPoi(me.createPOIFromJson(json));
        } else {
        	if (me.isTypeVisible(me.pois[json.id].type) > -1) {
        		me.pois[json.id].show();
        	}
        }
    });
}   

MapManager.prototype.addPoi = function(poi) {

    var me = this;
    me.pois[poi.id] = poi;
    if(typeof(me.pois_by_type[poi.type]) == 'undefined'){
			me.pois_by_type[poi.type] = new Array();
		}
    me.pois_by_type[poi.type][poi.id] = poi;
}

MapManager.prototype.createPOIFromJson = function(json) {

		myIconPOI.image = "/static/icons/poi"+ json.type +".png";
		poi=  this.createPOI(new google.maps.LatLng(json.lat,json.lon), {id: json.id, title: json.title, text:"Arrastra el icono a la situación correcta", type: json.type, draggable: true, icon: myIconPOI, zIndexProcess: this.setZindex_ });
		
		if (this.isTypeVisible(poi.type) > -1) {
			this.map_.addOverlay(poi);
		} else {
			this.map_.addOverlay(poi);
			poi.hide();
		}
		return poi;
}

MapManager.prototype.refreshPOIs = function(){
    for (key in this.pois) {
        this.pois[key].refresh();
    }   
}

MapManager.prototype.createPOI = function(point, opt_opts) {
    var me = this;
    var poi = new POI(point, opt_opts);
    poi.disableDragging();   
    return poi;
}    

function Item(latlng, opt_opts) {
    this.opt_opts = opt_opts || {};
    this.id = this.opt_opts.id || 0;
    this.title_ = this.opt_opts.title || '';
    this.credential_ = this.opt_opts.credential || 1;
    if (this.title) this.title = 'undefined';
    google.maps.Marker.apply(this, arguments);
    this.tooltip = '<div class="tooltip">' + this.title_ +'</div>';
    GEvent.addListener(this,"mouseover", function() {
        showTooltip(this);
    });
    GEvent.addListener(this,"mouseout", function() {
        tooltip.style.visibility="hidden";
    });    
}

Item.prototype = new google.maps.Marker( new google.maps.LatLng(0, 0));

Item.prototype.initialize = function (map) {
  this.map_ = map;
  google.maps.Marker.prototype.initialize.apply(this, arguments);
}

Item.prototype.updateEvents = function (){
	var me = this;
}

Item.prototype.selectInfoWindow = function(){
    var me = this;
    
    
    GEvent.clearListeners(me,'click');
    GEvent.addListener(me,'click', function(){
    	var css_id = 'map-dialog-box';
    	
        html_loading = '<div class="map-dialog-box" ><div class="content"><center><img src="/static/css/loader.gif" alt="loading..." /></center></div></div>';
        tooltip.style.visibility="hidden";
        
        if (me.credential_==1){
        	css_id = 'map-dialog-box-basic';
        }
        me.openExtInfoWindow(
            me.map_, 
            css_id, 
            html_loading, 
            { 
                ajaxUrl: buildAjaxUrl('/ajax/infowindow/' + me.id + '/'),
                beakOffset: 2
            }
        );
        
    });
}

Item.prototype.refresh = function(){
	this.updateEvents();
	this.selectInfoWindow();
}

function create_cluster(minx, miny, maxx, maxy, avgx, avgy, items, opt_opts) {
    return new Cluster(
    		new google.maps.LatLngBounds(new google.maps.LatLng(miny,minx), new google.maps.LatLng(maxy,maxx)),
    		new google.maps.LatLng(avgy,avgx),
    		1, 
    		"#6666ff", 
    		items, 
    		opt_opts);
}

function Cluster(bounds, center, opt_weight, opt_color, items, opt_opts) {
    this.bounds_ = bounds;
    this.center_ = center;
    this.weight_ = opt_weight || 1;
    this.color_ = opt_color || "#888888";
    this.items_ = items || 0;
    this.opt_opts_ = opt_opts || {};
    this.id = this.opt_opts_.id || 0;
    this.name = this.opt_opts_.name || '';
}

Cluster.prototype = new google.maps.Overlay();

Cluster.prototype.initialize = function(map) {
	// Crea el objeto DIV que representa nuestro rect√°ngulo.
    var div = document.createElement("div");
    var img = document.createElement("img");
    var span = document.createElement("span")
    var bgimage, items;

    items = this.items_;

    //div.style.border = this.weight_ + "px solid " + this.color_;
    div.style.position = "absolute";
    div.className = "cluster"; 
 
    var base = 25;
    var inc = 10;
    
    if (this.items_ < 25) {
    	this.size_ = base;
        div.className = "cluster cluster-xxs"; 
    }
    else if (this.items_ < 50) {
    	this.size_ = base+inc;
        div.className = "cluster cluster-xs"; 	
    }
    else if (this.items_ < 100) {
    	this.size_ = base+2*inc;
        div.className = "cluster cluster-s"; 	
    }
    else if (this.items_ < 250) {
    	this.size_ = base+3*inc;
        div.className = "cluster cluster-l"; 	
    }
    else if (this.items_ < 500) {
    	this.size_ = base+4*inc;
        div.className = "cluster cluster-xl"; 	
    }
    else {
    	this.size_ = base+5*inc;
        div.className = "cluster cluster-xxl"; 	
        items = "1000+";
    }
    
    if (this.name) {
    	items = this.name;
    }
    
    //incluimos la cantidad de items
    span.innerHTML = items;

    div.appendChild(span);
    map.getPane(G_MAP_MAP_PANE).appendChild(div);

    this.map_ = map;
    this.div_ = div;
    this.img_ = img;
    this.span = span;

    GEvent.bindDom(this.div_, 'mousedown', this,this.onClick_);
    GEvent.bindDom(this.div_, 'mouseover', this,this.onMouseOver_);
    GEvent.bindDom(this.div_, 'mouseout', this,this.onMouseOut_);
}

Cluster.prototype.onClick_ = function(e) {
    this.map_.closeExtInfoWindow();
    if (this.name) {
    	this.map_.setCenter(this.bounds_.getCenter(), this.map_.getBoundsZoomLevel(this.bounds_)+1);
    } else {
    	this.map_.setCenter(this.bounds_.getCenter(), this.map_.getBoundsZoomLevel(this.bounds_));
    }
    if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    } else {
        e.preventDefault();
        e.stopPropagation();
    }
}
Cluster.prototype.onMouseOver_ = function(e) {
	//this.div_.style.width = "70px";
}
Cluster.prototype.onMouseOut_ = function(e) {
	//this.div_.style.width = "70px";	
}

// Eliminamos el objeto DIV principal del panel del mapa.
Cluster.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
}

// Copia nuestros datos en un nuevo rect√°ngulo.
Cluster.prototype.copy = function() {
	return new Cluster(this.bounds_, this.center_, this.weight_, this.color_, this.items_,
                    this.backgroundColor_, this.opacity_);
}

// Redibuja el rect√°ngulo a partir de la proyecci√≥n y el nivel de acercamiento de cada momento.
Cluster.prototype.redraw = function(force) {
    // Solo es necesario redibujar si el sistema de coordenadas ha cambiado.
    if (!force) return;

    /* Calcula las coordenadas DIV de dos esquinas opuestas de los l√≠mites para obtener 
    el tama√±o y la posici√≥n de nuestro rect√°ngulo.*/
    var lat = this.center_.y;
    var lng = this.center_.x;
    var c = this.map_.fromLatLngToDivPixel(new google.maps.LatLng(lat,lng));

    //this.div_.style.width =  (Math.abs(128) - this.weight_ -2) + "px";
    this.div_.style.width = this.size_ + "px"; //70
    this.div_.style.height = this.size_ + "px"; //25
    this.div_.style.left = (c.x - Math.floor(this.size_/2) ) +  "px";
    this.div_.style.top = (c.y - Math.floor(this.size_/2) ) +  "px";
    this.div_.style.padding = (Math.floor(this.size_/2)-10) +"px 0 0 0";
}

/* 
clase gestiona las tareas del editor de infopoints
*/

POIEditor = function (map) {
	this.poi = {};
	this.type = 0;
	this.map_ = map
	this.initial_latlng = {};
}

POIEditor.prototype.initialize = function(type, id) {
	if (zangoa_status == ZANGOA_STATUS_INFOPOINT_EDITOR) return;
	var me = this;
	me.id = id;
	me.type = type;
	url_ajax = buildAjaxUrl('/poi/ajax/create/'+type+'/');
	if (id) {
		url_ajax = buildAjaxUrl('/poi/ajax/edit/'+type+'/'+ id);
	}
	zangoa_status= ZANGOA_STATUS_INFOPOINT_EDITOR;
	$('#filter').hide();
	$('#edit-poi-form').show();
	$('#edit-poi-form').load(url_ajax, null, function() {
		if (id) {
			me.poi = mm.pois[id];
		} else {
			me.poi = new POI(me.map_.getCenter(), {text:"Arrastra el icono a la situación correcta", type:me.type, icon:new google.maps.Icon(G_DEFAULT_ICON), draggable: true});
		  me.poi.initialize(me.map_);
		  me.map_.addOverlay(me.poi);
		}

		me.initial_latlng = me.poi.getLatLng();
	  me.poi.startEdit();
	  me.refresh();
	  GEvent.addListener(me.poi, "dragend", function(){
	    me.refresh();
	  });
	});

}


POIEditor.prototype.cancel = function() {
  zangoa_status = ZANGOA_STATUS_DEFAULT;
  //ipm.refreshInfoPoints();
	if(this.poi.id == 0){
	  this.map_.removeOverlay(this.poi);
	} else {
		this.poi.setLatLng(this.initial_latlng);
	}
	this.poi.endEdit();
	this.poi = {};
	$('#edit-poi-form').hide();
	$('#filter').show();
} 


POIEditor.prototype.refresh = function() { 
    var point_ = this.poi.getLatLng();
    var lon = point_.lng();
    var lat = point_.lat();    
    $("#id_longitude").val(lon);
    $("#id_latitude").val(lat);
    $("#id_type").val(this.type);    
}


POIEditor.prototype.save = function(params){  
   zangoa_status = ZANGOA_STATUS_DEFAULT;

	 $('#edit-poi-form').hide();
	 $('#filter').show();   
   this.poi.id=params.id;
   this.poi.title=params.title;

	 if (params.isNew) {
		 myIconPOI.image = "/static/icons/poi"+ this.poi.type +".png";
		 newpoi = new POI(this.poi.getLatLng(), {id: this.poi.id, text: "Arrastra el icono a la situación correcta", type:this.poi.type, title:this.poi.title, draggable: true, icon: myIconPOI});
		 newpoi.initialize(this.map_);
		 this.map_.removeOverlay(this.poi);
		 this.map_.addOverlay(newpoi);
		 this.poi = newpoi;
	 }
	 
	 mm.addPoi(this.poi);
   this.poi.endEdit();
   this.poi ={};
   
   mm.refreshPOIs();
}

POIEditor.prototype.delete_poi = function(id){
	if (id) {
		url_ajax = buildAjaxUrl('/poi/ajax/delete/'+ id);
		var me = this;

		if (confirm('Estás seguro que quieres eliminar este punto de interés?')) {
			 $.ajax({
			   type: "POST",
			   url: url_ajax,
			   success: function(msg){
			     poi = mm.pois[id];
			     mm.closeInfoWindow();
			     mm.pois = mm.pois.splice(id, 1);
			     me.map_.removeOverlay(poi);
			     
			     setErrorMsg( "Data deleted: " );
			   },
			   error: function(msg) {
			   	 setErrorMsg( "Data NOT deleted: " );
			   }
			 });
		}
	}
}

function POI(latlng, opt_opts) {
    this.opt_opts = opt_opts || {};
    this.id = this.opt_opts.id || 0;
    this.title = this.opt_opts.title || '';
    this.text = this.opt_opts.text || '';
    this.type = this.opt_opts.type || '';
    this.refresh();
    
    PopupMarker.apply(this, arguments);
}

POI.prototype = new PopupMarker(new google.maps.LatLng(0, 0));

POI.prototype.initialize = function (map) {
  var me = this;
  PopupMarker.prototype.initialize.apply(me, arguments);
  
  me.map_ = map;
  
  //if (zangoa_status == ZANGOA_STATUS_INFOPOINT_EDITOR) return;
  GEvent.clearListeners(me,'click');
  GEvent.addListener(me,'click', function(){
	    if (zangoa_status == ZANGOA_STATUS_INFOPOINT_EDITOR) return;
   	  html_loading = '<div class="map-dialog-box"><h3>LOADING....</h3></div>';
   	  
   	  me.openExtInfoWindow(
   			  me.map_, 
   			  'map-dialog-box-basic', 
   			  html_loading,
   			  { 
   				  ajaxUrl: buildAjaxUrl('/poi/ajax/info/' + me.id + '/'),
   				  beakOffset: 2
   			  }
   	  );
   	
  });
}

/**
* @desc Shows the marker.
*    Note that this method shows only the marker.
*    If you want to show marker and the popup,
*    then use the {@link showPopup}.
*/
POI.prototype.show = function () {
	PopupMarker.prototype.show.apply(this, arguments);
	if (this.editing) this.container_.style.visibility = "visible";
};

	
POI.prototype.refresh = function (force) {
	GEvent.clearListeners(this, 'mouseover');
		GEvent.clearListeners(this, 'mouseout');  
	  this.tooltip = '<div class="tooltip">' + this.title +'</div>';
	  GEvent.addListener(this,"mouseover", function() {
	      showTooltip(this);
	  });
	  GEvent.addListener(this,"mouseout", function() {
	      tooltip.style.visibility="hidden";
	  });
	};	

POI.prototype.getAjaxInfoWindowHtml = function() {
	   var me = this;
	   $.get(buildAjaxUrl('/poi/ajax/infowindow/' + me.id + '/'),{},function(data){
	   	  $('#infowindow'+me.id).html(data);
	   });
}


POI.prototype.startEdit = function(){
	 var me = this;
   me.editing = true;
   me.enableDragging();
   me.map_.closeExtInfoWindow();
   mm.showType(this.type);
   me.showPopup();
}

POI.prototype.endEdit = function(){
   this.editing = false;
   this.disableDragging();
   this.hidePopup();
}

function advancedSearch()
{
	mm.getData(true);	
}

MapManager.prototype.setZindex_ = function(marker) {
    if (zangoa_status == ZANGOA_STATUS_INFOPOINT_EDITOR) return 100000000;
	var newZindex = GOverlay.getZIndex(marker.getPoint().lat()) + ((10 - marker.type) * 100000);
	return newZindex;
}


function getFilterParams(params) {

     //var filter_by = new Array();
    if ($('#rooms_number').val()) {
    	params["rooms"] = $('#rooms_number').val();
    	//filter_by.push('rooms: ' + $('#rooms_number').val());
    }
    if ($('#type').val()) {
    	params["type"] = $('#type').val();
    	//filter_by.push('rent type: ' + $('#rent_type').val()); 
    }
    if ($('#pool').attr("checked")) {
    	params["pool"] = '1'; 
    	//filter_by.push('pool: ' + $('#pool').val());
    }
    if ($('#wheel').attr("checked")) {
    	params["wheel"] = '1';
    	//filter_by.push('wheel: ' + $('#wheel').val()); 
    }
    if ($('#internet').attr("checked")) {
    	params["internet"] = '1'; 
    	//filter_by.push('internet: ' + $('#internet').val());
    }
    if ($('#tv').attr("checked")) {
    	params["tv"] = '1'; 
    	//filter_by.push('tv: ' + $('#tv').val());
    }
    if ($('#pets').attr("checked")) {
    	params["pets"] = '1'; 
    	//filter_by.push('pets: ' + $('#pets').val());
    }
    if ($('#photos').attr("checked")) {
    	params["photos"] = '1'; 
    	//filter_by.push('photos: ' + $('#photos').val());
    }
    if ($('#chk_price').attr("checked")) {
    	params["chk_price"] = '1'; 
    }
   	if ($('#price_max').val()) {
   		params["price_max"] = $('#price_max').val();
 	  }
   	if ($('#price_min').val()) {
   		params["price_min"] = $('#price_min').val();
   	}
    if ($('#chk_pax').attr("checked")) {
    	params["chk_pax"] = '1';
    }
   	if ($('#pax').val()) {
   		params["pax"] = $('#pax').val(); 
    }
    if ($('#hhh').val()) {
   		params["hhh"] = $('#hhh').val(); 
    }
    if ($('#www').val()) {
   		params["www"] = $('#www').val(); 
    }
    
    return params

}

function setCheckAllPoisButton() {
	 $("#check_all").click(function(){
   	if ($(this).attr('checked')) {
     $('#poi_filter').find("input").each(function(){
     	if (!$(this).attr('checked') && 'check_all' != $(this).name) {
     		mm.showType($(this).attr('name'));
     	}
     });
    } else {
     $('#poi_filter').find("input").each(function(){
     	if ($(this).attr('checked') && 'check_all' != $(this).name) {
     		$(this).attr('checked', false);
     		mm.hideType($(this).attr('name'));
     	}
     });	      
    }
  });
}
