var Listing, Avi_Listing = new Class({
	is_map_open:false,
	map_data:{},
	marker:{},
//	idx_markers:[],
//	total_idx_loaded:0,
	limit_markers:25,
	loaded_markers:0,
	mode:'swf',
	icons:{},
	win_info:{},
	default_lat_long:{
		lat:49.892201,
		long:-119.449024
	},
	default_zoom_level:14,
	options:{
		icon: {
		    forsale: ['House / Landed building', 'http://maps.google.com/mapfiles/kml/pal5/icon10.png', 'http://maps.google.com/mapfiles/kml/pal5/icon10s.png'],
		    house: ['House / Landed building', 'http://maps.google.com/mapfiles/kml/pal3/icon56.png', 'http://maps.google.com/mapfiles/kml/pal3/icon56s.png'],
		    airport: ['Airport', 'http://maps.google.com/mapfiles/kml/pal2/icon56.png', 'http://maps.google.com/mapfiles/kml/pal2/icon56s.png'],
		    bank: ['Bank', 'http://maps.google.com/mapfiles/kml/pal2/icon58.png', 'http://maps.google.com/mapfiles/kml/pal2/icon58s.png'],
		    church: ['Church / Mosque', 'http://maps.google.com/mapfiles/kml/pal2/icon11.png', 'http://maps.google.com/mapfiles/kml/pal2/icon11s.png'],
		    gas_station: ['Gas Station', 'http://maps.google.com/mapfiles/kml/pal2/icon29.png', 'http://maps.google.com/mapfiles/kml/pal2/icon29s.png'],
		    golf_cource: ['Golf Course', 'http://maps.google.com/mapfiles/kml/pal2/icon13.png', 'http://maps.google.com/mapfiles/kml/pal2/icon13s.png'],
		    hospital: ['Hospital', 'http://maps.google.com/mapfiles/kml/pal3/icon46.png', 'http://maps.google.com/mapfiles/kml/pal3/icon46s.png'],
		    market: ['Market', 'http://maps.google.com/mapfiles/kml/pal3/icon26.png', 'http://maps.google.com/mapfiles/kml/pal3/icon26s.png'],
		    hotel: ['Hotel / Apartment', 'http://maps.google.com/mapfiles/kml/pal3/icon21.png', 'http://maps.google.com/mapfiles/kml/pal3/icon21s.png'],
		    recreation: ['Recreation Facilities', 'http://maps.google.com/mapfiles/kml/pal2/icon12.png', 'http://maps.google.com/mapfiles/kml/pal2/icon12s.png'],
		    sport: ['Sport Center', 'http://maps.google.com/mapfiles/kml/pal2/icon57.png', 'http://maps.google.com/mapfiles/kml/pal2/icon57s.png'],
		    school: ['School / University', 'http://maps.google.com/mapfiles/kml/pal2/icon10.png', 'http://maps.google.com/mapfiles/kml/pal2/icon10s.png'],
		    transportation: ['Public Transportation', 'http://maps.google.com/mapfiles/kml/pal4/icon15.png', 'http://maps.google.com/mapfiles/kml/pal4/icon15s.png'],
		    pushpin: ['Site Influence', 'http://maps.google.com/mapfiles/kml/pal5/icon14.png', 'http://maps.google.com/mapfiles/kml/pal5/icon14s.png']
		}
	},
	
	/*initialize:function(listing_id) {
		this.listing_id = listing_id;
		this.is_map_open = true;
		showLoading('loading map data');
		new Request.JSON({
			url: site_url + 'rets/map', 			
			onComplete: function(r){
				hideLoading();
				this.map_data = r.map;
				this.modalObj = new Facebox( {
					title : null,
					message : '<div style="" id="map-modal"><ul class="tab-menu"><li class="tab-selected">'+r.map.config.title+'</li><li id="map-tips">asdsa</li></ul><div id="map-container" style="height:'+(window.getHeight()-150)+'px"></div></div>',
					width : window.getWidth() - 60,
					submitValue : null,
					cancelValue : 'Close',
					cancelFunction: function() {
						this.map_hide();
					}.bind(this)
				});
				this.modalObj.show();
				
				this.modal_el = $(document.body).getElement('.facebox');
				
				new avi_news_flash($('map-tips'), {
					news: ['Use arrow button on your keyboard to pan map, use <b>+</b> or <b>&ndash;</b> to zoom in/out', 'You can click on <b>Satellite</b> or <b>Hybrid</b> to view satellite photos instead of graphics']
				});
				
				this.map_init.delay(500, this);
	        }.bind(this)
		}).get();
		
		
		if (navigator.appName.indexOf("Microsoft") != -1) {
            this.swf = window['ev_platform'];
        } else {
        	this.swf = document['ev_platform'];
        }
	},*/
	
	initialize:function(listing_id,index,is_widget,is_feat_widget) {
		if(is_widget){ 
			this.mode = 'widget';
			var is_idx_widget = "true";
		} else
			var is_idx_widget = "false";
		
		if(is_feat_widget) this.mode = 'feat_widget';
		
		this.listing_id = listing_id;
		this.is_map_open = true;
		if(index==0){
			if(this.mode != 'widget')
				showLoading('loading featured listings data: 0%');
			else 
				showLoading('loading...');
		}
		new Request.JSON({
			url: site_url + 'rets/map', 
			onComplete: function(r){
				if(index==0){
					this.map_data = r.map;
					this.loaded_markers += r.map.counted;					
				} else {
					$each(r.map.markers,function(marker_data,id){
						this.map_data.markers[id] = marker_data;						
					}.bind(this));	
					this.loaded_markers += r.map.counted;
				}
				
				updateProgress('loading featured listings data',this.loaded_markers,r.map.total_markers);
				//keep retrieving data	
				if(this.loaded_markers < r.map.total_markers){	
					this.initialize(this.listing_id,index+this.limit_markers);
				} else {
					hideLoading();
					if(this.map_data.config.show_idx && !is_feat_widget){
						this.loaded_markers = 0;
						this.init_map_container();
						(function(){this.get_idx(0);}).delay(3000,this);
					}
					else{
						this.init_map_container();
						(function(){
							this.map.enableScrollWheelZoom();
							new GKeyboardHandler(this.map); // keyboard handler
							this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(80, 7)));
							this.map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7)));
						}).delay(3000,this);
					}
				}				
	        }.bind(this)
		}).post({"offset":index,"limit":this.limit_markers,"is_widget":is_idx_widget});		
	},
	
	init_map_container: function(){
		showLoading('drawing map');
		statement = '<br/><div style="margin-left:5px;">'+this.map_data.config.disclaimer+' '+this.map_data.config.copyright+'</div>';
		this.modalObj = new Facebox( {
			title : null,
			message : '<div style="" id="map-modal"><ul class="tab-menu"><li class="tab-selected">'+this.map_data.config.title+'</li><li id="map-tips">asdsa</li></ul><div id="map-container" style="height:'+(window.getHeight()-150)+'px"></div></div>'+statement,
			width : window.getWidth() - 60,
			submitValue : null,
			cancelValue : 'Close',
			cancelFunction: function() {
				this.map_hide();
			}.bind(this)
		});
		this.modalObj.show();
		
		this.modal_el = $(document.body).getElement('.facebox');
		
		new avi_news_flash($('map-tips'), {
			news: ['Use arrow button on your keyboard to pan map, use <b>+</b> or <b>&ndash;</b> to zoom in/out', 'You can click on <b>Satellite</b> or <b>Hybrid</b> to view satellite photos instead of graphics']
		});
		
		this.map_init.delay(500, this);
		
		if (navigator.appName.indexOf("Microsoft") != -1) {
            this.swf = window['ev_platform'];
        } else {
        	this.swf = document['ev_platform'];
        }
		hideLoading();
	},
	
	get_idx: function(index){		
		/*this.modalObj.fade();
		markers = [];
		if(this.idx_markers.length>0){
			$each(this.idx_markers,function(item,index){
				markers[index] = item;
			}.bind(this));
		}*/
		
//		var post_data = {"markers":markers,"sw_lat":sw.lat(),"sw_long":sw.lng(),"ne_lat":ne.lat(),"ne_long":ne.lng()};
		
		if(index==0)
			showLoading('loading all listings data: 0%');
		new Request.JSON({
			url: site_url + 'rets/idx_map/json', 
			onComplete: function(r){
				//store the loaded marker
				if(r.markers!=''){		
//					i=0;
					$each(r.markers,function(marker_data,id){
						this.map_data.markers[id] = marker_data;
						this.loaded_markers++;
						
						//create marker
						var m = this.createMarker(id, new GLatLng(marker_data.lat, marker_data.lang), marker_data);			
						if (marker_data.status != 'Sold') {	
					    	this.MarkerManager.addMarker(m,11,17);
					    } else {
					    	this.MarkerManager.addMarker(m,0,17);
					    }
						/*if(i==0 && index==0)
							this.map.setCenter(new GLatLng(marker_data.lat, marker_data.lang), 11);
						i++;*/
						/*if (marker_data.photo) {
					    	if (marker_data.status != 'Sold') {					    			
					    		this.mm['Available'].push(m);
					    	} else {
					    		this.mm['Sold'].push(m);
					    	}
					    } else {
					        this.mm['amenities'].push(m);
					    }					        					        
							
					    if(id == this.listing_id) {
					    	this.map.setCenter(new GLatLng(marker_data.lat, marker_data.lang), 16);
					    	GEvent.trigger(this.marker[id],'ClickTab',0);
					    }*/
					},this);
					
					/*if(ceil((this.loaded_markers/r.total_markers)*100)>30)
					this.MarkerManager.addMarkers(this.mm['Available'],0,17);
					this.MarkerManager.addMarkers(this.mm['Sold'],11,17);
					this.MarkerManager.addMarkers(this.mm['amenities'],14,17);
					this.MarkerManager.refresh();
*/				}
					
				updateProgress('loading all listings data',this.loaded_markers,r.total_markers);
				//keep retrieving data		
				if(this.loaded_markers < r.total_markers){				
					this.get_idx(index+this.limit_markers);
				} else {
					/*$each(this.map_data.markers,function(marker_data,id){
						if (marker_data.photo) {
					    	if (marker_data.status != 'Sold') {					    			
					    		this.mm['Available'].push(m);
					    	} else {
					    		this.mm['Sold'].push(m);
					    	}
					    } else {
					        this.mm['amenities'].push(m);
					    }					        					        
							
					    if(id == this.listing_id) {
					    	this.map.setCenter(new GLatLng(marker_data.lat, marker_data.lang), 16);
					    	GEvent.trigger(this.marker[id],'ClickTab',0);
					    }				        
					    this.MarkerManager.addMarkers(this.mm['Available'],0,17);
						this.MarkerManager.addMarkers(this.mm['Sold'],11,17);
						this.MarkerManager.addMarkers(this.mm['amenities'],14,17);
					});*/
					this.map.enableScrollWheelZoom();
					new GKeyboardHandler(this.map); // keyboard handler
					this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(80, 7)));
					this.map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7)));
					hideLoading();						
	//				this.init_map_container();
				}		
		    }.bind(this)
		}).post({"offset":index,"limit":this.limit_markers});
	},
	
	map_init: function() {
		this.map = new GMap2($('map-container'));
//		if(this.map_data.config.total_idx_listings>0){
//			GEvent.addListener(this.map, 'moveend', function() {
//				if(this.total_idx_loaded < this.map_data.config.total_idx_listings){
//			    	var bounds = this.map.getBounds();
//			    	var southWest = bounds.getSouthWest();
//			    	var northEast = bounds.getNorthEast();
//			    	this.get_idx(southWest,northEast);
//				}
//		    }.bind(this));
//		}
		
//	    this.map.enableScrollWheelZoom();
//		new GKeyboardHandler(this.map); // keyboard handler
		this.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5)));
//		this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(80, 7)));
//		this.map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7)));
		
		var legend_html = '<h2>LEGEND</h2><div>';
		$each(this.map_data.config.listing_status, function(status, color){
			legend_html += '<p><img src="http://labs.google.com/ridefinder/images/mm_20_'+color+'.png"/> '+status+'</p>';
		});
		legend_html += '</div>';
		
		function map_legend(){}
	    map_legend.prototype = new GControl();
	    map_legend.prototype.initialize = function(){
	        var container = new Element('div',{
	        	'class':'map-legend',
	        	html:legend_html
	        });
	        this.map.getContainer().appendChild(container);
	        return container;
	    }.bind(this);
	    map_legend.prototype.getDefaultPosition = function(){
	        return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5, 30));
	    };
		this.map.addControl(new map_legend());
		
		//filter
		var filter_html = '<h2>SEARCH BY</h2><div>';
		filter_html += 'Price: <input type="text" style="width:60px;" id="min_price"/> - <input type="text" style="width:60px;" id="max_price"/><br/>';
		filter_html += '<label>Bedrooms</label>: <select id="bedroom_select" style="height:18px;border:1px solid #CCCCCC;font-size:11px;"><option value="=">=</option><option value="<">\<</option><option value=">">\></option></select> <input type="text" style="width:40px;" id="bedrooms"/><br/>';
		filter_html += '<label>Bathrooms</label>: <select id="bathroom_select" style="height:18px;border:1px solid #CCCCCC;font-size:11px;"><option value="=">=</option><option value="<">\<</option><option value=">">\></option></select> <input type="text" style="width:40px;" id="bathrooms"/><br/>';
		filter_html += '<br/><input type="submit" onclick="Listing.map_resetFilter();" value="Reset" style="display:block;float:right;width:50px;font-size:14px;height:22px;background-color:#666666;">';
		filter_html += '<input type="submit" onclick="Listing.map_filter();" value="Go" style="display:block;float:right;width:50px;font-size:14px;height:22px;background-color:#666666;">';
		
		filter_html += '<br/></div>';
		
		function map_filter(){}
		map_filter.prototype = new GControl();
		map_filter.prototype.initialize = function(){
	        var container = new Element('div',{
	        	'class':'map-filter',
	        	html:filter_html
	        });
	        this.map.getContainer().appendChild(container);
	        return container;
	    }.bind(this);
	    map_filter.prototype.getDefaultPosition = function(){
	        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 30));
	    };
		this.map.addControl(new map_filter());
	    //end of filter
		
	    this.ew = new EWindow(this.map, E_STYLE_7);      
	    this.map.addOverlay(this.ew);
	    
	    GEvent.addListener(this.map, 'click', function(overlay,point) {
	    	if (!overlay) {
	    		this.ew.hide();
	    	}
	    }.bind(this));
		
	    // BUILD CUSTOM ICON
	    var amenitiesIcon = new GIcon();
	    amenitiesIcon.iconSize = new GSize(32, 32);
	    amenitiesIcon.shadowSize = new GSize(56, 32);
	    amenitiesIcon.iconAnchor = new GPoint(16, 32);
	    amenitiesIcon.infoWindowAnchor = new GPoint(16, 16);
	    $each(this.options.icon, function(icon, name){
	    	this.icons[name] = new GIcon(amenitiesIcon, icon[1], null, icon[2]);
	    }.bind(this));

	    var baseIcon = new GIcon();
	    baseIcon.iconSize = new GSize(12, 20);
	    baseIcon.shadowSize = new GSize(22, 20);
	    baseIcon.iconAnchor = new GPoint(6, 20);
	    baseIcon.infoWindowAnchor = new GPoint(5, 5); 
	    $each(this.map_data.config.listing_status, function(s, color){
	        this.icons[s] = new GIcon(baseIcon, 'http://labs.google.com/ridefinder/images/mm_20_'+color+'.png', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
	    }.bind(this));

	    this.mm = { // marker manager
	    	Available:[],
	    	Sold:[],
	    	amenities:[]
	    };
	    
	    $each(this.map_data.markers, function(marker_data, id) {
	        var m = this.createMarker(id, new GLatLng(marker_data.lat, marker_data.lang), marker_data);
	        if (marker_data.photo) {
	    		if (marker_data.status != 'Sold') {
	    			this.mm['Available'].push(m);
	    		} else {
	    			this.mm['Sold'].push(m);
	    		}
	        } else {
	        	this.mm['amenities'].push(m);
	        }
	        
	        if(id == this.listing_id) {
	    	    this.map.setCenter(new GLatLng(marker_data.lat, marker_data.lang), 16);
		    	GEvent.trigger(this.marker[id],'ClickTab',0);
	        }
	    }, this);
	    
	    if(this.map_data.config.lat) this.default_lat_long.lat = this.map_data.config.lat;
	    if(this.map_data.config.lang) this.default_lat_long.long = this.map_data.config.lang;
	    if(this.map_data.config.zoom) this.default_zoom_level = this.map_data.config.zoom;
	    
	    if(!this.marker[this.listing_id]){ // set default position if current listing haven't lat long
			this.map.setCenter(new GLatLng(this.default_lat_long.lat, this.default_lat_long.long), this.default_zoom_level);
		}
	    
		this.MarkerManager = new MarkerManager(this.map, {borderPadding:1});
		this.MarkerManager.addMarkers(this.mm['Available'],0,17);
		this.MarkerManager.addMarkers(this.mm['Sold'],11,17);
		this.MarkerManager.addMarkers(this.mm['amenities'],14,17);
		this.MarkerManager.refresh();
		
		
	},
	

	createMarker: function(name, latlng, data){
		var titles = [];
		var contents = [];
		if(data.photo) {
			if (!this.icons[data.icon]) { // fix updated listing status
				data.icon = 'Available';
			}
			
	    	titles[0] = 'Listing';
	    	contents[0] = '<table border="0" width="100%"><tr>';
	    	
	    	if(this.mode=='swf'){
		    	if(!data.idx_link){
		    		contents[0] += '<td colspan="2"><h3><a onclick="Listing.map_goto(\''+name+'\')" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a onclick="Listing.map_goto(\''+name+'\')"><img src="'+data.photo+'" width="100" height="75"/></a><br/><span style="font-size:10px;">Brokerage: '+data.broker_name+'</span></td>';
		    		contents[0] += '<td width="51%"><p class="price">MLS&reg; #: <span>'+data.mls+'</span></p><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a onclick="Listing.map_goto(\''+name+'\')">view house</a></td>';
		    	}
		    	else{
		    		contents[0] += '<td colspan="2"><h3><a onclick="Listing.map_goto(\''+name+'\',\''+data.idx_link+'\')" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a onclick="Listing.map_goto(\''+name+'\',\''+data.idx_link+'\')"><img src="'+data.photo+'" width="100" height="75"/></a><br/><span style="font-size:10px;">Brokerage: '+data.broker_name+'</span></td>';
		    		contents[0] += '<td width="51%"><p class="price">MLS&reg; #: <span>'+data.mls+'</span></p><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a onclick="Listing.map_goto(\''+name+'\',\''+data.idx_link+'\')">view house</a></td>';
		    	}
	    	} else {
	    		/*if(!data.idx_link){
	    			contents[0] += '<td colspan="2"><h3><a onclick="Listing.widget_goto(\''+name+'\')" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a onclick="Listing.widget_goto(\''+name+'\')"><img src="'+data.photo+'" width="100" height="75"/></a></td>';
		    		contents[0] += '<td width="51%"><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a onclick="Listing.widget_goto(\''+name+'\')">view house</a></td>';
	    		} else {
	    			contents[0] += '<td colspan="2"><h3><a onclick="Listing.widget_goto(\''+name+'\',true)" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a onclick="Listing.widget_goto(\''+name+'\',true)"><img src="'+data.photo+'" width="100" height="75"/></a></td>';
		    		contents[0] += '<td width="51%"><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a onclick="Listing.widget_goto(\''+name+'\',true)">view house</a></td>';
	    		}*/
				if(!data.idx_link){
	    			contents[0] += '<td colspan="2"><h3><a target="parent._blank" href="'+site_url+'listings/goto_widget/feat/'+name+'" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a target="parent._blank" href="'+site_url+'listings/goto_widget/feat/'+name+'" ><img src="'+data.photo+'" width="100" height="75"/></a><br/><span style="font-size:10px;">Brokerage: '+data.broker_name+'</span></td>';
		    		contents[0] += '<td width="51%"><p class="price">MLS&reg; #: <span>'+data.mls+'</span></p><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a target="parent._blank" href="'+site_url+'listings/goto_widget/feat/'+name+'" >view house</a></td>';
	    		} else {
	    			contents[0] += '<td colspan="2"><h3><a target="parent._blank" href="'+site_url+'listings/goto_widget/idx/'+name+'" title="view listing photos">'+data.address+'</a></h3></td></tr><tr>';
			    	contents[0] += '<td width="49%"><a target="parent._blank" href="'+site_url+'listings/goto_widget/idx/'+name+'"><img src="'+data.photo+'" width="100" height="75"/></a><br/><span style="font-size:10px;">Brokerage: '+data.broker_name+'</span></td>';
		    		contents[0] += '<td width="51%"><p class="price">MLS&reg; #: <span>'+data.mls+'</span></p><p class="price">price: <span>'+data.price+'</span></p><p>'+data.type+'</p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'<br/>'+data.ownership+'</p>&raquo; <a target="parent._blank" href="'+site_url+'listings/goto_widget/idx/'+name+'">view house</a></td>';
	    		}
	    	}
	    		
	    	contents[0] += '</tr></table>';
	    	
	    	if(data.realtor_name){
	    		titles[1] = 'Agent Info';
	    		agentinfo = '<table border="0" width="100%">';
	    		agentinfo += '	<tr><td>Agent</td><td>: '+data.realtor_name+'</td></tr>';
	    		agentinfo += '	<tr><td>Brokerage</td><td>: '+data.broker_name+'</td></tr>';
	    		/*agentinfo += '	<tr><td>Email</td><td>: '+data.realtor_email+'</td></tr>';
	    		agentinfo += '	<tr><td>Phone</td><td>: '+data.realtor_phone+'</td></tr>';	*/    		
	    		agentinfo += '</table>';
	    		contents[1] = agentinfo;
	    	}
	    	if(data.remarks) {
	    		var i = titles.length;
		    	titles[i] = 'Remarks';
		    	contents[i] = data.remarks;
	    	}
	    	/*if(data.amenities) {
	    		var i = titles.length;
		    	titles[i] = 'Amenities';
		    	contents[i] = data.amenities;
	    	}*/
    	} else {
    		if (!this.icons[data.icon]) {
				data.icon = 'pushpin';
			}
	    	titles = [this.options.icon[data.icon][0] + ':'];
	    	contents = ['<h3>'+data.title+'</h3>'+data.address];
    	}
		this.win_info[name] = {
			titles: titles,
			contents: contents
		};

	    var marker = new GMarker(latlng, {
	        'icon': this.icons[data.icon]
	    });
		this.marker[name] = marker;
		
	    GEvent.addListener(marker, 'mouseover', function(){
	    	this.open_tab(marker, 0, name);
	    }.bind(this));
	    
	    GEvent.addListener(marker, 'ClickTab', function(tab) {
        	this.open_tab(marker, tab, name);
        }.bind(this));
	    
	    return marker;
	},
	
	open_tab: function(marker,tab_number,marker_name) {
		var contents=this.win_info[marker_name].contents,titles=this.win_info[marker_name].titles;
		if (titles.length > 1) {
			var html= '<div class="title"><ul>';
			for (var i=0; i<titles.length; i++) {
				if (i==tab_number) {
					html+='<li class="active" onclick="GEvent.trigger(Listing.marker[\''+marker_name+'\'],\'ClickTab\','+i+')">' + titles[i] + '</li>';
				} else {
					html+='<li onclick="GEvent.trigger(Listing.marker[\''+marker_name+'\'],\'ClickTab\','+i+')">' + titles[i] + '</li>';
				}
			}
			html += '</ul></div><div class="content">' + contents[tab_number] + '</div>';
		} else {
			html = '<div class="title"><span>'+titles[0]+'</span></div><div class="content">'+contents[0]+'</div>';
		}
		this.ew.openOnMarker(marker,html);
	},
	
	map_lunch: function(listing_id) {
		if (this.is_map_open == true) return false;
		this.listing_id = listing_id;
		if(this.map_data.markers[listing_id]) {
	    	this.map.setCenter(new GLatLng(this.map_data.markers[listing_id].lat, this.map_data.markers[listing_id].lang), 16);
	    	GEvent.trigger(this.marker[listing_id],'ClickTab',0);
		}
		this.modal_el.setStyle('display','');
	},
	
	map_goto: function(listing_id,idx_link) {
		this.map_hide();
		this.swf.SetVariable('property_id', listing_id);
		if(idx_link){
			this.swf.SetVariable('idx_link',idx_link);
		}
		this.swf.goto_listing();
	},
	
	widget_goto: function(listing_id,is_idx){
		if(is_idx){
			parent.window.open(site_url+'listings/goto_widget/idx/'+listing_id);
//			parent.window.location = site_url+'listings/goto_widget/idx/'+listing_id;
		} else {
			parent.window.open(site_url+'listings/goto_widget/feat/'+listing_id);
//			parent.window.location = site_url+'listings/goto_widget/feat/'+listing_id;
		}
	},
	
	map_hide: function() {
		this.is_map_open = false;
		this.modal_el.setStyle('display','none');
	},
	
	map_filter: function() {
		showLoading('Searching...');
		bedroom = $('bedrooms').value;
		bedroom_select_val = $('bedroom_select').get('value');
		bathroom = $('bathrooms').value;
		bathroom_select_val = $('bathroom_select').get('value');
		min_price_val = $('min_price').value;
		max_price_val = $('max_price').value;
		if(min_price_val=='')min_price_val = 0;
		if(max_price_val=='')max_price_val = 999999999999;
		
		this.MarkerManager.clearMarkers();
		
		this.mm = { // marker manager
			Available:[],
			Sold:[],
			amenities:[]
		};
		
		$each(this.map_data.markers,function(marker_data,id){
			//price = marker_data.price.toInt();
			price = marker_data.price.replace(/,/gi,'');
			price = parseInt(price);
			/*price = price.trim();
			price = price.replace(',','');*/
			included_price = included_bedroom = included_bathroom = true;
			if(price >= min_price_val && price <= max_price_val) included_price = true;
			else included_price = false; //exclude if price doesn't match filter
			
			if(bedroom!=''){
				if(bedroom_select_val=='='){
					if(marker_data.br==bedroom) included_bedroom = true;
					else included_bedroom = false;
				} else if(bedroom_select_val=='>'){
					if(marker_data.br >= bedroom) included_bedroom = true;
					else included_bedroom = false;
				} else if(bedroom_select_val=='<'){
					if(marker_data.br <= bedroom) included_bedroom = true;
					else included_bedroom = false;
				}				
			}
			
			if(bathroom!=''){
				if(bathroom_select_val=='='){
					if(marker_data.ba==bathroom) included_bathroom = true;
					else included_bathroom = false;
				} else if(bathroom_select_val=='>'){
					if(marker_data.ba >= bathroom) included_bathroom = true;
					else included_bathroom = false;
				} else if(bathroom_select_val=='<'){
					if(marker_data.ba <= bathroom) included_bathroom = true;
					else included_bathroom = false;
				}				
			}
			
			
			if(included_price == true && included_bedroom == true && included_bathroom == true){
				var m = this.createMarker(id, new GLatLng(marker_data.lat, marker_data.lang), marker_data);
				if (marker_data.photo) {
		    		if (marker_data.status != 'Sold') {
		    			this.mm['Available'].push(m);
		    		} else {
		    			this.mm['Sold'].push(m);
		    		}
		        } else {
		        	this.mm['amenities'].push(m);
		        }
				
			}
		}, this);
		
//		this.MarkerManager = new MarkerManager(this.map, {borderPadding:1});
		this.MarkerManager.addMarkers(this.mm['Available'],0,17);
		this.MarkerManager.addMarkers(this.mm['Sold'],11,17);
		this.MarkerManager.addMarkers(this.mm['amenities'],14,17);
		
		this.MarkerManager.refresh();
		hideLoading();
	},
	
	map_resetFilter: function(){	
		showLoading('Resetting filter...');
		this.MarkerManager.clearMarkers();
		
		this.mm = { // marker manager
			Available:[],
			Sold:[],
			amenities:[]
		};
		
		$each(this.map_data.markers,function(marker_data,id){
			var m = this.createMarker(id, new GLatLng(marker_data.lat, marker_data.lang), marker_data);
			if (marker_data.photo) {
		    	if (marker_data.status != 'Sold') {
		    		this.mm['Available'].push(m);
		    	} else {
		    		this.mm['Sold'].push(m);
		    	}
		    } else {
		        this.mm['amenities'].push(m);
		    }
			
		}, this);
		
		this.MarkerManager.addMarkers(this.mm['Available'],0,17);
		this.MarkerManager.addMarkers(this.mm['Sold'],11,17);
		this.MarkerManager.addMarkers(this.mm['amenities'],14,17);
		this.MarkerManager.refresh();
		
		$('bedrooms').set('value','');
		$('bathrooms').set('value','');
		$('min_price').set('value','');
		$('max_price').set('value','');
		hideLoading();
	}
});

function open_map(listing_id) {
	if(Listing==null) {
		Listing = new Avi_Listing(listing_id,0);
	} else {
		Listing.map_lunch(listing_id);
	}
}

function open_map_widget(listing_id) {
	Listing = new Avi_Listing(listing_id,0,true);
}

function open_feat_listing_map(listing_id) {
	Listing = new Avi_Listing(listing_id,0,false,true);
}

function updateProgress(msg,loaded,total){	
	percent = (loaded/total)*100;
	percent = Math.ceil(percent)
	$("loading_indicator").set('text', msg+': '+percent+'%');
}

/**
 * Show loadin indicator
 */
function showLoading(msg) {
	var loading_el = $('loading_indicator');
	if (!loading_el) {
		loading_el = new Element('div', {
			id:'loading_indicator',
			styles: {
				background:'#76B41C url('+public_url+'images/loading.gif) 7px center no-repeat',
				color:'#AFD37A',
				display:'none',
				minWidth:'200px',
				padding:'13px 20px 5px 30px',
				minHeight:'25px',
				position:'fixed',
				fontSize:'14px',
				fontFamily:'Arial',
				borderBottom:'2px solid #AFD37A',
				borderLeft:'2px solid #AFD37A',
//				border:'2px solid #AFD37A',
				right:0,
				top:0,
				whiteSpace:'nowrap',
				zIndex:1000
			}
		});
		loading_el.inject(document.body);
	}
	loading_el.set('text', msg ? msg :'Loading...');
	loading_el.setStyle('display', 'block');
	
	avi_now_loading = true; // set busy
}

/*window.addEvent('domready',function(){
	var minimap;
	open_mini_map();
});*/

function open_mini_map(){
	lat = 49.892201;
	long = -119.449024;
	icon = 'available';
	minimap = new mini_map(lat,long,icon);
}

var mini_map = new Class({
	default_point:{
		lat:49.892201,
		long:-119.449024
	},
	listing_status:{
		green: 'Available',
		red: 'Sold'
	},
	hide_map: function(){	
		this.slideFx.toggle().chain();

		$('mini-map-toggler').set('html','Show Panel');
		$('mini-map-toggler').setAttribute('onclick','minimap.show_map()');
	},
	show_map: function(){		
		this.slideFx.toggle().chain();

		$('mini-map-toggler').set('html','Hide Panel');
		$('mini-map-toggler').setAttribute('onclick','minimap.hide_map()');
	},
	initialize: function(lat,long,icon){
		//showLoading('drawing map');
		this.marker_lat = lat;
		this.marker_long = long;
		this.marker_icon = icon;
		/*this.modalObj = new Facebox( {
			title : null,
			message : '<div style="" id="map-modal"><ul class="tab-menu"><li class="tab-selected">test</li></ul><div id="map-container" style="height:'+(window.getHeight()-150)+'px"></div></div>',
			width : window.getWidth() - 60,
			submitValue : null,
			cancelValue : 'Close',
			cancelFunction: function() {
				this.map_hide();
			}.bind(this)
		});
		this.modalObj.show();*/
		var map_wrapper = new Element('div',{
			id: 'mini_map_wrapper',
			styles: {
				display:'block',
				width:'266px',
				height:'200px',
				position:'fixed',
				left:10,
				top:160,
				whiteSpace:'nowrap',
				zIndex:2
			}
		});
		
		map_wrapper.inject(document.body);
		
		var map_div = new Element('div',{
			id: 'mini_map_container',
			styles: {
				color:'#000000',
				width:'266px',
				height:'26px'
			}
		});
		header = ' <div id="mini-map-header" style="background:url(\''+public_url+'images/title-bg.png\') top left;width=266px;height:26px;font-size:10px;font-weight:bold;font-family:Arial;color:#ffffff;">';
		header += '  <div style="width:150px;padding:5px 0px 0px 7px;float:left;">Current Location</div>';
		header += '  <div style="width:68px;padding:5px 0px 0px 15px;float:right;"><a id="mini-map-toggler" style="cursor:pointer;">Show Panel</a></div>';
		header += '</div>';
		
		content = '<div id="mini-map-content" style="display:block;width:265px;height:190px;font-size:10px;font-weight:bold;font-family:Arial;color:#ffffff;background-color:#ffffff;">';
		content += '  <div style="width:227px;height:180px;float:left;border:2px solid #000000;margin:3px 0px 3px 3px;"></div>';
		content += '  <div style="width:27px;height:184px;float:left;background-color:#525252;margin:3px 3px 3px 0px;">';
		content += '    <div><img src="'+public_url+'images/plus_btn.png" style="cursor:pointer;margin-left:1px;margin-top:2px;" id="plus_btn"/></div>';
		content += '    <div><em id="zoom-knob-area" class="knob-area"><em id="zoom-knob" class="knob"></em></em></div>';
		content += '    <div><img src="'+public_url+'images/min_btn.png" style="cursor:pointer;margin-left:1px;" id="min_btn"/></div>';		
		content += '  </div>';
		content += '</div>';
		
		map_div.set('html',header+content);
		map_div.inject('mini_map_wrapper');	
		
		this.slideFx = new Fx.Slide('mini-map-content', {
		    duration: 500,
		    transition: Fx.Transitions.Sine.easeOut
		});
		
		this.slideFx.hide();
		$('mini-map-toggler').addEvent('click',function(){
			this.show_map();
		}.bind(this));		
		
		var mySlider = new Slider('zoom-knob-area', 'zoom-knob', {
		    range: [100,2000],
		    steps: 20,
		    wheel: true,
		    snap: true,
		    mode: 'vertical',
		    onStart: function(){
		        
		    },
		    onTick: function(pos){
		    },
		    onChange: function(val){
		    },
		    onComplete: function(){
		       
		    }
		});
		
		$('plus_btn').addEvent('click',function(){
			alert(mySlider.step++);
			mySlider.set(mySlider.step++);
		}.bind(this));
		
		$('min_btn').addEvent('click',function(){
			newval = this.zoom_lv-1;
			mySlider.set(newval);
			this.zoom_lv = newval;
		}.bind(this));
		//this.map_init.delay(500, this);
		
//		hideLoading();
	},
	
	map_init: function() {
		this.map = new GMap2($('mini-map-container'));
		

//	    this.map.enableScrollWheelZoom();
//		new GKeyboardHandler(this.map); // keyboard handler
//		this.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5)));
//		this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(80, 7)));
//		this.map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7)));
		
	    this.ew = new EWindow(this.map, E_STYLE_7);      
	    this.map.addOverlay(this.ew);
	    
	    GEvent.addListener(this.map, 'click', function(overlay,point) {
	    	if (!overlay) {
	    		this.ew.hide();
	    	}
	    }.bind(this));
		
	    // BUILD CUSTOM ICON
	    $each(this.listing_status, function(s, color){
	        this.icons[s] = new GIcon(baseIcon, 'http://labs.google.com/ridefinder/images/mm_20_'+color+'.png', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
	    }.bind(this));
	    
	    var m = this.createMarker('mini_marker_'+Math.random(), new GLatLng(this.marker_lat, this.marker_long), this.marker_icon);
	   
	    this.map.setCenter(new GLatLng(this.marker_lat, this.marker_long), 19);
	    this.MarkerManager = new MarkerManager(this.map, {borderPadding:1});
	    this.MarkerManager.addMarker(m,0,20);	
		
	},
	
	createMarker: function(name, latlng, icon){

	    var marker = new GMarker(latlng, {
	        'icon': this.icons[icon]
	    });
		this.marker[name] = marker;
		
	    /*GEvent.addListener(marker, 'mouseover', function(){
	    	this.open_tab(marker, 0, name);
	    }.bind(this));*/
	    
	    return marker;
	}
	
});
/**
 * Hide loading indicator
 */
function hideLoading() {
	avi_now_loading = false; // loading inactive / not busy
	
	var loading_el = $('loading_indicator');
	loading_el.setStyle('display', 'none');
}


var avi_news_flash = new Class({
	options: {
		news: [],
		delay: 8000 // milisecond
	},
	Implements:Options,
    initialize: function(news_el, option){
        this.news_el = $(news_el);
        if (this.news_el) {
        	this.news_el.set('html','');
            this.setOptions(option);
            this.start = 0;
            this.news_length = this.options.news.length;
            this.el = new Element('span').inject(this.news_el).set('html', this.options.news[this.start]);
            
            var fx = new Fx.Morph(this.el, {duration: 500});
			(function(){
				fx.start({
					opacity: [1,0]
				}).chain(function() {
					this.el.set('html', this.options.news[(++this.start % this.options.news.length)]);
					fx.start({opacity:[0,1]});
				}.bind(this));
			}).periodical(3000,this);
        }
    }
});



function EStyle(stemImage, stemSize, boxClass, boxOffset) {
    this.stemImage = stemImage;
    this.stemSize = stemSize;
    this.boxClass = boxClass;
    this.boxOffset = boxOffset;
    // this.border = border;
    
    // Known fudge factors are:
    // Firefox 1.0, 1.5, 2.0 5, -1
    // Firefox 3.0 4, -1
    // IE 6.0 0, -1
    // Opera 8.54 3, -1
    // Opera 9 4, -1
    // Netscape (7.2, 8.0) 5, -1
    // Safari 5, -1
    // Chrome 5, -1
    
    var agent = navigator.userAgent.toLowerCase();
    
    var fudge = 5;  // assume Netscape if no match found
   
    if (agent.indexOf('opera/9') > -1) {
      fudge = 4;
    }   
    else if (agent.indexOf('opera') > -1) {
      fudge = 3;
    }   
    else if (agent.indexOf('firefox/3') > -1) {
      fudge = 4;
    }   
    else if (agent.indexOf('firefox') > -1) {
      fudge = 5;
    }   
    else if (agent.indexOf('chrome') > -1) {
      fudge = 4;
    }   
    else if (agent.indexOf('safari') > -1) {
      fudge = 4;
    }   
    else if (agent.indexOf('msie') > -1) {
      fudge = 2;
    }
    this.fudge = fudge;
  }
  
  var E_STYLE_7 = new EStyle('http://econym.org.uk/gmap/stem7.png', new GSize(24,24),  'ev-listing-baloon', new GPoint(-10,21));


  function EWindow(map,estyle) {
    // parameters
    this.map=map;
    this.estyle=estyle;
    // internal variables
    this.visible = false;
    // browser - specific variables
    this.ie = false;
    var agent = navigator.userAgent.toLowerCase();
    if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true;} else {this.ie = false;}
  } 
  
  EWindow.prototype = new GOverlay();

  EWindow.prototype.initialize = function(map) {
    var div1 = document.createElement("div");
    div1.style.position = "absolute";
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div1);
    var div2 = document.createElement("div");
    div2.style.position = "absolute";
    div2.style.width = this.estyle.stemSize.width+"px";
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div2);
    this.div1 = div1;
    this.div2 = div2;
  };

  EWindow.prototype.openOnMap = function(point, html, offset) {
    this.offset = offset||new GPoint(0,0);
    this.point = point;
    this.div1.innerHTML = '<div class="' + this.estyle.boxClass + '">' + html + '</div>';
    if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
      var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
      this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
    } else {
      this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
    }
    var z = GOverlay.getZIndex(this.point.lat());
    this.div1.style.zIndex = z;
    this.div2.style.zIndex = z+1;
    this.visible = true;
    this.show();
    this.redraw(true);
  };
  
  EWindow.prototype.openOnMarker = function(marker,html) {
    var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
    var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
    this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
  };
  

  EWindow.prototype.redraw = function(force) {
    if (!this.visible) {return;}
    var p = this.map.fromLatLngToDivPixel(this.point);
    this.div2.style.left   = (p.x + this.offset.x) + "px";
    this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
    this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
    this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
  };

  EWindow.prototype.remove = function() {
    this.div1.parentNode.removeChild(this.div1);
    this.div2.parentNode.removeChild(this.div2);
    this.visible = false;
  };

  EWindow.prototype.copy = function() {
    return new EWindow(this.map, this.estyle);
  };

  EWindow.prototype.show = function() {
    this.div1.style.display="";
    this.div2.style.display="";
    this.visible = true;
  };
  
  EWindow.prototype.hide = function() {
    this.div1.style.display="none";
    this.div2.style.display="none";
    this.visible = false;
  };
  
  EWindow.prototype.isHidden = function() {
    return !this.visible;
  };
  
  EWindow.prototype.supportsHide = function() {
    return true;
  };

  EWindow.prototype.zindex = function(zin) {
    var z = GOverlay.getZIndex(this.point.lat());
    this.div1.style.zIndex = z+zin;
    this.div2.style.zIndex = z+1+zin;
  };
