/*
 * EstateVue House Directory
 * JavaScript Property Search Library version 2.0
 * This version uses GMap API V3
 * Author: Sigit Noviandi <sigit@dedicated-it.com>
 * August 2010
 * Copyright 2010 EstateVue
 *  
 */


var Avi = {};

//------- Custom Label -------------
var Ev_Label = function(map,point,div,offset){
	// Now initialize all properties.
	this.point_ = point;
	this.div_ = div;
	this.map_ = map;
	this.offset_ = offset;
	// Explicitly call setMap() on this overlay
	this.setMap(this.map_);
};
Ev_Label.prototype = new google.maps.OverlayView();
Ev_Label.prototype.onAdd = function() {
	var panes = this.getPanes();
	panes.floatShadow.appendChild(this.div_);
};
Ev_Label.prototype.draw = function() {
	var overlayProjection = this.getProjection();
	var p = overlayProjection.fromLatLngToDivPixel(this.point_);

	// Resize the image's DIV to fit the indicated dimensions.
	var div = this.div_;
	div.style.left = (p.x - this.offset_.w) + 'px';
	div.style.top = (p.y - this.offset_.h) + 'px';
};
Ev_Label.prototype.remove = function(){
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;
};


//------- Custom label -------------
var Avi_Marker_Label = new Class({
	Implements: google.maps.OverlayView,
	label: new Hash(),
	mirror_link: null,
	initialize: function(map, options) {
		this.map_ = map;
		this.options = {
			offset: options.offset || new Size(0,0),
			zIndex: options.zIndex || 1000,
			onHover: options.onHover || {display:'block'},
			onLeave: options.onLeave || {display:'none'}
		};
	    this.div_ = new Element('div', {
			style: 'position: absolute;display:none;z-index:' + this.options.zIndex
		});
		if(options.classname) {
			this.options.classname = options.classname;
			this.div_.addClass(options.classname);
		}
	},
	//--------------------------------------------------
	create: function(id, marker, html) {
		var e = this.div_.clone();
		e.set('html', html);

		var wrapper = new Element('div',{})
		var points = marker.getPosition();
		
		var w = this.options.offset.width;		
		var h = this.options.offset.height;
		h += 48;
		var overlay = new Ev_Label(this.map_, points, e,{'w':w,'h':h});
		overlay.el = e;
		this.label.set(id, overlay);
		google.maps.event.addListener(marker, 'mouseover', function(){
			this.hover(id);
	    }.bind(this));
		google.maps.event.addListener(marker, 'mouseout', function() {
        	this.leave(id);
        }.bind(this));
	},
	
	//--------------------------------------------------
	hover: function(id) {
		if(this.current == id) return false;
		
		var label = this.label.get(id);
		label.el.setStyles(this.options.onHover);
	},
	
	//--------------------------------------------------
	leave: function(id) {
		var label = this.label.get(id);
		label.el.setStyles(this.options.onLeave);
	},
	
	clear: function(){
		this.label.each(function(e,k){
			this.leave(k);
		},this);
	}
});

//------- Custom Info Window -------------
var Ev_InfoWin = function(map,point,div,div2,offset){
	// Now initialize all properties.
	this.point_ = point;
	this.div_ = div;
	this.div2_ = div2;
	this.map_ = map;
	this.offset_ = offset;
	// Explicitly call setMap() on this overlay
	this.setMap(this.map_);
};
Ev_InfoWin.prototype = new google.maps.OverlayView();
Ev_InfoWin.prototype.onAdd = function() {
	var panes = this.getPanes();
	panes.floatPane.appendChild(this.div_);
	panes.floatPane.appendChild(this.div2_);
};
Ev_InfoWin.prototype.draw = function() {
	var overlayProjection = this.getProjection();
	var p = overlayProjection.fromLatLngToDivPixel(this.point_);
	
	// Resize the image's DIV to fit the indicated dimensions.
	var div = this.div_;
	var div2 = this.div2_;
	div.style.left = (p.x - this.offset_.w - 20) + 'px';
	div.style.top = (p.y - this.offset_.h - div.offsetHeight + 1) + 'px';
	
	div2.style.left = (p.x - this.offset_.w) + 'px';
	div2.style.top = (p.y - this.offset_.h) + 'px';
};
Ev_InfoWin.prototype.remove = function(){
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;
	this.div2_.parentNode.removeChild(this.div2_);
	this.div2_ = null;
};
Ev_InfoWin.prototype.repos = function(){
	var div = this.div_;
	var overlayProjection = this.getProjection();
	var p = overlayProjection.fromLatLngToDivPixel(this.point_);
	div.style.top = (p.y - this.offset_.h - div.offsetHeight + 1) + 'px';
};

//------- Custom Info Window -------------
var Avi_Marker_InfoWin = new Class({
	Implements: google.maps.OverlayView,
	info_win: new Hash(),
	mirror_link: null,
	current_content: new Hash(),
	_show_current: null,
	initialize: function(map, options) {
		this.map_ = map;
		this.options = {
				offset: options.offset || new Size(0,0),
				zIndex: options.zIndex || 1000,
				onHover: options.onHover || {display:'block'},
				onLeave: options.onLeave || {display:'none'}
		};
		this.div_ = new Element('div', {
			style: 'position: absolute;display:none;z-index:' + this.options.zIndex
		});
		this.div2_ = new Element('div',{
			style: 'background:url(http://econym.org.uk/gmap/stem7.png) no-repeat top left;width:24px;height:24px;position: absolute;display:none;z-index:' + this.options.zIndex+1
		});
		if(options.classname) {
			this.options.classname = options.classname;
			this.div_.addClass(options.classname);
		}
	},
	//--------------------------------------------------
	create: function(latlngid, id, marker, html) {
		var paging = this._create_paging(latlngid,id);
		this.current_content.include(latlngid,1);
		var e = this.div_.clone();
		e.set('html', html);
		paging.inject(e);
		
		var e2 = this.div2_.clone();
		var points = marker.getPosition();
		
		var w = this.options.offset.width;		
		var h = this.options.offset.height;
		var overlay = new Ev_InfoWin(this.map_, points, e,e2,{'w':w,'h':h});
		overlay.el = e;
		overlay.el2 = e2;
		this.info_win.include(latlngid, overlay);
	},
	
	//--------------------------------------------------
	show: function(id) {
		if(this.current == id) return false;
		
		var info_win = this.info_win.get(id);
		info_win.el.setStyles(this.options.onHover);
		info_win.el2.setStyles(this.options.onHover);
	},
	
	//--------------------------------------------------
	hide: function(id) {
		var info_win = this.info_win.get(id);
		info_win.el.setStyles(this.options.onLeave);
		info_win.el2.setStyles(this.options.onLeave);
	},
	
	clear: function(){
		this.info_win.each(function(e,k){
			if(this._show_current != null && k == this._show_current){
				this._show_current = null;
			} else {
				this.hide(k);
			}
		},this);
	},
	
	switch_content: function(latlngid,action){
		if(action == 'next'){
			var index = this.current_content.get(latlngid);
			index++;
			this.current_content.set(latlngid,index);
		} else {
			var index = this.current_content.get(latlngid);
			index--;
			this.current_content.set(latlngid,index);
		}
		this._change_content(latlngid);
	},
	
	_change_content: function(latlngid){
		var info_win = this.info_win.get(latlngid);
		var contents = Avi.Search.markers_lat_lng.get(latlngid).marker_data;
		var content = '';
		var i=1;
		contents.each(function(c){
			if(i==this.current_content.get(latlngid)) content = c.content;
			i++;
		},this);
		info_win.el.getElement('div[id=content-paging]').dispose();
		var paging = this._create_paging(latlngid);
		paging.inject(info_win.el);
		
		info_win.el.getElement('div[id=info-window-content]').set('html',content);
		info_win.repos();
		this._show_current = latlngid;
	},
	
	_create_paging: function(latlngid){
		var marker_data = Avi.Search.markers_lat_lng.get(latlngid).marker_data;
		var length = marker_data.getLength();
		var act = new Element('div',{
			id: 'content-paging',
			style: 'text-align:right;margin:10px;'
		});
		var str = '';
		var index = this.current_content.get(latlngid);
		
		if(length > 1){
			if(index < length){
				if(index > 1){
					str += '<a onclick="Avi.InfoWin.switch_content(\''+latlngid+'\',\'prev\');">prev</a>&nbsp;&nbsp;';
				}
				str += '<a onclick="Avi.InfoWin.switch_content(\''+latlngid+'\',\'next\');">next</a>';
			} else if(index == length) {
				str += '<a onclick="Avi.InfoWin.switch_content(\''+latlngid+'\',\'prev\');">prev</a>'
			}
		}
		act.set('html',str);
		return act;
	}
});

var Avi_Search = new Class({
	init:{},
	search_history: [],
	markers: new Hash(),
	markers_data: new Hash(),
	icons: new Hash(),
	color_hex: new Hash(),
	listings_data: new Hash(),
	markers_lat_lng: new Hash(), // untuk mendeteksi latlong yang sama, agar tidak numpuk
	markers_plus: {},
	win_info:{},
	widget: false,
	number_marker:0,
	counters: {},
	default_listing: null,
	sliders: new Hash(),
	legend_y: 62,
	options: {
		max_number_marker: 500, 
		st_price_val:[0,'100K','200K','400K','700K','1M','2M','3M','4M','5M',0],
		st_br_val:[0,1,2,3,4,5,6,7,8,9,10,0],
		st_size_val:[0,250,500,1000,1250,1500,1750,2000,2250,2500,2750,3000,3500,4000,5000,0],
		marker_color:['green','purple','yellow','blue','white','red','black','orange','gray','brown'],
		marker_color_hex:['#65e265','#e54fe5','#fcfc64','#5858ff','#ffffff','#ff3f4f','#000000','#f2c30c','#c1c1c1','#cca065'],
		icon: {
		    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() {
		this.default_listing = default_listing;
		
		this.url = site_url + 'search/';
		this.elements = {};
		this.elements.show_all_toggler = $('search-show-all-toggler');
		this.elements.form = $('search-form');
		this.elements.si = this.elements.form.getElements('.closable');
		this.elements.location = $('at');
		this.elements.use_map = $('use-map');
		this.elements.total_records = $('search-total-record');
		this.elements.result_summary = $('search-result-summary');
		if($type($('save-profile-btn'))=='element'){
			$('save-profile-btn').addEvent('click',function(){this.changeProfile();}.bind(this));
		}
		
		//show_all checkboxes
		this.elements.show_featured_listing = $('show-featured-listing');
		this.elements.show_new = $('show-new');
		if(!window.location.hash){
			if(this.default_listing == 'new_listing'){
				this.elements.show_new.setProperty('checked','checked');
				var search_terms = this._build_search_term();
				window.location.hash = '#' + encodeURIComponent(search_terms.str);
			} else if(this.default_listing == 'feature_listing'){
				this.elements.show_featured_listing.setProperty('checked','checked');
				var search_terms = this._build_search_term();
				window.location.hash = '#' + encodeURIComponent(search_terms.str);
			}
		} 
		
		// tab view switcher 
		this.elements.tab_map = $('tab_map');
		this.elements.tab_list = $('tab_list');
		this.elements.map_wrapper = $('search-result-map');
		this.elements.list_wrapper = $('search-result-list');
		
		this.elements.tab_map.addEvent('click', function(e){
			e.stop();
			if(this.elements.tab_map.hasClass('selected')) return;
			
			this.elements.tab_list.removeClass('selected');
			this.elements.tab_map.addClass('selected');
			
			this.elements.list_wrapper.addClass('hidden');
			this.elements.map_wrapper.removeClass('hidden');
			if(!Avi.Map){
				init_map();
			}
		}.bind(this));
		
		this.elements.tab_list.addEvent('click', function(e){
			e.stop();
			if(this.elements.tab_list.hasClass('selected')) return;
			
			this.elements.tab_map.removeClass('selected');
			this.elements.tab_list.addClass('selected');
			
			this.elements.map_wrapper.addClass('hidden');
			this.elements.list_wrapper.removeClass('hidden');
		}.bind(this));
		
		// initialize marker
		/*this.baseIcon = new google.maps.Icon();
	    this.baseIcon.iconSize = new GSize(12, 20);
	    this.baseIcon.shadowSize = new GSize(22, 20);
	    this.baseIcon.iconAnchor = new GPoint(6, 20);
	    this.baseIcon.infoWindowAnchor = new GPoint(5, 5); */
		
		if(this.elements.location.value=='') {
//			this.elements.location.value = geoip_city() +', '+ geoip_region_name();
			this.elements.location.value = default_location;
		}
		this.elements.location.value = this.elements.location.value.replace(',','');
		this.elements.location.addEvent('keypress',function(evt){
			if(evt.key==',') {
				return false;
			}
		});
		if(this.elements.use_map.checked == true) {
			this.elements.location.disabled = true;
			this.elements.location.addClass('disabled');			
		}
		this.elements.use_map.addEvent('click', function(){
			this.elements.location.disabled = this.elements.use_map.checked;
			if(this.elements.use_map.checked == true) {
				this.elements.location.addClass('disabled');	
			} else {
				this.elements.location.removeClass('disabled');	
			}
		}.bind(this));
		
		this.options.st_ba_val = this.options.st_br_val; // copy value
		var d = new Date(), last_10years = d.getFullYear() - 10;
		this.options.st_yb_val = [0, last_10years - 10, last_10years - 5, last_10years, last_10years + 1, last_10years + 2, last_10years + 3, last_10years + 4, last_10years + 5, last_10years + 6, last_10years + 7, last_10years + 8, last_10years + 9, d.getFullYear(), 0];
		
		this.elements.form = $('search-form');
		this.elements.form.addEvents({
			submit: function(e){
				e.stop();
				this.search();
				return false;
			}.bind(this)
		});
		$('do-search').addEvent('click', function(e){
			e.stop();
			this.search();
		}.bind(this));
		/*$('search-tool').addEvent('click', this.search_tool.bind(this));*/
		/*$('mail-alert').addEvent('click', this.mail_alert.bind(this));
		$('rss-search').addEvent('click', function(e){
			e.stop();
			var last_search = this.search_history.getLast();
			var hash = last_search.get('str'); 
			document.location = site_url + 'search/rss/' + encodeURIComponent(hash);
		}.bind(this));*/
		
		var hash = window.location.hash;
//		alert(window.location.href);
		if(hash) {
			hash = hash.substring(1);
			hash = this._parse_hash(hash,true);
			this.search();
		}
		
		$$('at', 'keyword', 'mls').addEvent('keydown', function(evt){
			if (evt.key == 'enter') {
				evt.stop();
				this.search();
			}
		}.bind(this));
		this.hidden_checkboxes = new Hash();
		this.si_clossed = 0;
		var _slider_id;
		$each(this.elements.si, function(el){
			if(el.hasClass('clossed')) this.si_clossed++;
			var legend = el.getElement('.legend');
			var slider = el.getLast();
			
			if(slider.hasClass('slider-container')) {
				_slider_id = slider.get('id');
			} else {
				_slider_id = false;
			}
			
			legend.addEvent('click', function(slider_id){
				if (el.hasClass('clossed')) {
					this.si_clossed--;
					el.removeClass('clossed');
					
					if(slider_id) {
						this._slider_init(slider_id);
					}
				}
				else {
					this.si_clossed++;
					el.addClass('clossed');
				}
				
				if(this.si_clossed == 0) {
					this.elements.show_all_toggler.set('html','hide all').removeClass('clossed');
				} else {
					this.elements.show_all_toggler.set('html','show all').addClass('clossed');
				}
			}.bind(this, _slider_id));
		}, this);
				
		this.elements.order_by = $('search-order');
		
		this.elements.show_all_toggler.addEvent('click', function(e){
			e.stop();
			if(this.elements.show_all_toggler.hasClass('clossed')) {
				this.si_clossed = 0;
				this.elements.show_all_toggler.removeClass('clossed').set('html','hide all');
				$each(this.elements.si, function(el){
					if (el.hasClass('clossed')) {
						el.removeClass('clossed');
					}
				}, this);
				
				// activate slider
				//this._slider_init('st_br');
				//this._slider_init('st_ba');
				//this._slider_init('st_size');
				//this._slider_init('st_yb');
				
			} else {
				this.si_clossed = this.elements.si.length;
				this.elements.show_all_toggler.addClass('clossed').set('html','show all');
				$each(this.elements.si, function(el){
					if (!el.hasClass('clossed')) {
						el.addClass('clossed');
					}
				}, this);
			}
		}.bind(this));
		
		//this._slider_init('st_price');
		
		//this.sliders.get('st_price').setMin(700).setMax(1);
		//alert(this.sliders.get('st_price'));
		
		/*// choose at least 1 checkbox
		var cb_group = $$('#listing-type-resale', '#listing-type-new', '#listing-type-foreclosure');
		for(var i=0,j=cb_group.length;i<j;i++) {
			cb_group[i].addEvent('click', this._checkbox_init.bind(this,[cb_group[i],cb_group]));
		}*/
		//this._search_by_bound();
		if(widget==true) this.widget = true;
	},
	
	_init_filter: function(parent,el){
		var parent_id = parent.get('id');
		var cb = new Array();
		var letter = new Array();
		letter.include('All');
		$each(el,function(e){
			var l = e.getElement('label').innerHTML;
			letter.include(l.charAt(0));
			cb.include(e);
			e.dispose();			
		},this);
		var letter_wrapper = parent.getElement('span[class=heading]').getElement('span[class=letter-filter]');
		letter.each(function(l){
			new Element('a',{
				html: l,
				style: 'color:#000000;pointer:cursor;'
			}).addEvent('click',function(){
				this._show_checkboxes(parent_id, l);
			}.bind(this)).inject(letter_wrapper,'bottom');
			letter_wrapper.appendText(' ');
		},this);
		this.hidden_checkboxes.set(parent_id,cb);
		this._show_checkboxes(parent_id,'A');
	},
	
	_show_checkboxes: function(wrapper_id,letter){
		var i = 1;
		$(wrapper_id).getElements('span[class=modal-item-left]').dispose();
		$(wrapper_id).getElements('span[class=modal-item-left-large]').dispose();
		$(wrapper_id).getElements('br').dispose();
		this.hidden_checkboxes.get(wrapper_id).each(function(e){
			if(letter != 'All'){
				if(e.getElement('label').innerHTML.charAt(0)==letter){
					e.inject($(wrapper_id),'bottom');
					if(e.hasClass('modal-item-left') == true){
						if((i%4)==0){
							new Element('br',{style:'clear:both;'}).inject($(wrapper_id));
						}
					} else {
						if((i%3)==0){
							new Element('br',{style:'clear:both;'}).inject($(wrapper_id));
						}
					}
					i++;
				}
			} else {
				e.inject($(wrapper_id),'bottom');
				if(e.hasClass('modal-item-left') == true){
					if((i%4)==0){
						new Element('br',{style:'clear:both;'}).inject($(wrapper_id));
					}
				} else {
					if((i%3)==0){
						new Element('br',{style:'clear:both;'}).inject($(wrapper_id));
					}
				}
				i++;
			}
		});
	},
	
	apply_checkbox: function(e){
		var p1 = e.getParent().getParent();
		var p2 = p1.getParent();
		//p1.fade('out');
		this.si_clossed++;
		p2.addClass('clossed');
	},
	
	//------------------------------------------------------
	_parse_hash: function(hash,direct) {
		var terms = {keyword:''}, temp,
			field = ['at', 'subarea', 'price', 'bathroom', 'bedroom', 'builton', 'size', 'type', 'listing-type', 'mls', 'show', 'type', 'page', 'sort-by'];
		if(!direct){
			hash = hash.replace(/\+/g,' ');
		}
		hash = decodeURIComponent(hash);
		var m1 = hash.match(/([a-z\-]*):"([^"]*)"/gi); // cari dulu yang ada kutipnya
		if(m1!=null) {
			m1.each(function(m){
				if(m.test(/"$/)) {
					temp = m.split(':');
					if(field.indexOf(temp[0]) > -1) {
						temp[1] = temp[1].replace(/"/g,'').clean();
						terms[temp[0]] = temp[1];
					}
					hash = hash.replace(m, '');
				}
			});
		}
		var m2 = hash.match(/([a-z\-]*):([^\s]*)/gi); // cari yang tidak ada kutip
		if(m2!=null) {
			m2.each(function(m){
				temp = m.split(':');
				if(field.indexOf(temp[0]) > -1) {
					terms[temp[0]] = temp[1].clean();
				}
				hash = hash.replace(m, '');
			});
		}
		terms.keyword = hash.toString().clean();		
		
		// fill to form
		$each(terms, function(val, key){
			var el = $(key);
			if (!el) {
				if (key == 'size' || key == 'price') {
					$('st_' + key + '_input').set('value', val);
					if(key == 'price'){
						if(val.clean() != '') {
							if(val.contains('+')) {
								val = val.replace('+', '');
								if(!isNaN(val)) val *= 1; // convert into numeric
								min = val;
								max = 'Any';
							} else if(val.contains('-')) {
								val = val.split('-');
								if(!isNaN(val[0])) val[0] *= 1; // convert into numeric
								if(!isNaN(val[1])) val[1] *= 1; // convert into numeric
								
								if(val[1] == '') {
									min = 'Any';
									max = val;
								} else {
									// min
									min = val[0];
									// max
									max = val[1];
								}
							}
							$('price_min').set('value',min);
							$('price_max').set('value',max);
						}
						
					}
				} else if (key == 'bathroom') {
					$('st_ba_input').set('value', val);
				} else if (key == 'bedroom') {
					$('st_br_input').set('value', val);
				} else if (key == 'builton') {
					$('st_yb_input').set('value', val);
				} else if(key=='listing-type' || key=='show') {
					var cb = this.elements.form.getElements('input[name^='+ key +']'); // get checkbox
					val = val.split('|');
					cb.each(function(c){
						c.checked = val.indexOf(c.value) > -1;
					});
				} else if(key == 'subarea'){
					var cb = this.elements.form.getElements('input[name^='+ key +']'); // get checkbox
					if(val.contains('|')==true){
						val = val.split('|');
						cb.each(function(c){
							if(c.value == val){
								c.checked = true;
							} else {
								c.checked = false;
							}
						});
					} else {
						cb.each(function(c){
							
							if(c.value == val){
								c.checked = true;
							} else {
								c.checked = false;
							}
						});
					}
				} else if(key == 'type'){
					var cb = this.elements.form.getElements('input[name^='+ key +']'); // get checkbox
					if(val.contains('|')==true){
						val = val.split('|');
						cb.each(function(c){
							if(c.value == val){
								c.checked = true;
							} else {
								c.checked = false;
							}
						});
					} else {
						cb.each(function(c){
							if(c.value == val){
								c.checked = true;
							} else {
								c.checked = false;
							}
						});
					}
				}
			} else if(key=='type') {
				var options = el.getChildren();
				for(var i=0, j=options.length; i<j; i++) {
					if (options[i].value == val) {
						options[i].selected = true;
						break;
					}
				}
			} else {
				el.set('value', val);
			}
		}, this);
		
		return terms;
	},
	
	
	//------------------------------------------------------
	set_busy: function(is_busy) {
		var img_width = 130, img_height = 60;
		if(!this.busy_el) {
			this.busy_el = new Element('img', {
				src:'http://v3.estatevue.com/public/admin/images/loading.gif',
				width:img_width,
				height:img_height,
				styles: {
					position:'absolute',
					display:'none',
					zIndex:1000000
				}
			}).inject(document.body);
		}
		if(is_busy==true) {
			var pos, l, t;
			if(this.elements.tab_map.hasClass('selected')) {
				pos = $('search-result-map').getCoordinates();
				l = pos.left + ((pos.width - img_width)/2).toInt();
				t = pos.top + ((pos.height - img_height)/2).toInt();
			} else {
				pos = $('search-result-list').getCoordinates();
				l = pos.left + ((pos.width - img_width)/2).toInt();
				t = pos.top + 100;
			}
			this.busy_el.setStyles({
				top: t,
				left: l,
				display:''
			});
		
			$(document.body).setStyle('cursor','progress');
		}
		else {
			this.busy_el.setStyle('display','none');
			$(document.body).setStyle('cursor','default');
		}
	},
	
	_get_province : function(idx_feed){
		if(idx_feed == 'Tarasoft' || idx_feed == 'Tarasoft Realty Executive' || idx_feed == 'Tarasoft Realty Executive' || 
			 idx_feed == 'Soreb' || idx_feed == 'Kamloops'){
			return 'BC';
		} else if(idx_feed == 'Calgary Real Estate Board'){
			return 'Alberta';
		}
	},
	
	//------------------------------------------------------
	search: function(sort_by) {
		//if(this.elements.location.value.clean()=='' || $('st_price_input').value.clean()=='') {
		if(this.elements.location.value.clean()=='') {
			alert('You must enter a location');
			this.elements.location.focus();
			return false;
		}
		
		var search_terms = this._build_search_term();
		var url = window.location.href.split('/');
		url = url[url.length-1];
		if(sort_by){
			search_terms.json.set('sort-by',sort_by);
			window.location.hash += ' sort-by:'+sort_by;
			document.title += ' sort-by:'+sort_by;
		}
		window.location = search_url+search_terms.str+'/'+url;

	},
	
	/*//------------------------------------------------------
	_move_bounds: function () {
		if(this.number_marker > this.options.max_number_marker && Avi.Map.getZoom() < 13) {
			return false;
		}
		
		if(this.bound_status != 'delay') {
			this.bound_status = 'delay';
			this._search_by_bound.delay(2500, this); // in milisec
		}
	},
	
	//------------------------------------------------------
	_search_by_bound: function() {
		this.set_busy(true); // show loading
		this.bound_status = 'loading';
		
		var search_terms = this.search_history.getLast().get('json'), 
			bounds = Avi.Map.getBounds(),
			southWest = bounds.getSouthWest(),
			northEast = bounds.getNorthEast();
		search_terms = search_terms.getClean();
		search_terms.map_mode = true;
		
		search_terms.sw = southWest.lat() + ',' + southWest.lng();
		search_terms.ne = northEast.lat() + ',' + northEast.lng();
		
		var search_on_server = new Request.JSON({
			url: this.url + 'ajax_search', 
			onComplete: function(respons) {
				if (this.bound_status == 'loading') {
					this.bound_status = 'idle';
				}
				this._search_callback(respons, true);
				this.set_busy(false); // show loading
			}.bind(this)
		}).post(search_terms);
	},*/
	//------------------------------------------------------
	_build_search_term: function() {
		var form_el = this.elements.form.getElements('input, select, textarea', true), form_data = new Hash();
		form_el.each(function(el){
			if (!el.name || el.disabled || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return;
			var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
			$splat(value).each(function(val){
				if (typeof val != 'undefined' && val != '') {
					if(el.type == 'checkbox' && el.name.contains('[]')) {
						el.name = el.name.replace('[]','');
						var arr = form_data.get(el.name);
						if(arr) {
							arr.push(val);
							val = arr;
						} else {
							val = [val];
						}
					}
					/*if(el.name == 'at'){				
						var province = this._get_province(idx_feed);				
						if(!val.contains(province))
							val += ' '+province+' Canada';
					}*/
					form_data.set(el.name, val);
				}
			}.bind(this));
		}.bind(this));
		
		str = '';
		if(form_data.get('keyword')) {
			str = form_data.get('keyword') + ' ';
		}
		
		//handle price
		if(form_data.has('price_min') == true)
			var minprice = form_data.get('price_min').replace(/^\s*|\s*$/g,'');
		if(form_data.has('price_max') == true)
			var maxprice = form_data.get('price_max').replace(/^\s*|\s*$/g,'');
		
		if(/Any/.test(minprice) == false && /Any/.test(maxprice) == false){
			form_data.set('price',minprice+'-'+maxprice);
		} else if(/Any/.test(minprice) == false && /Any/.test(maxprice) == true){
			form_data.set('price', minprice+'+');
		} else if(/Any/.test(minprice) == true && /Any/.test(maxprice) == false){
			form_data.set('price',maxprice+'-');
		}
		form_data.erase('price_min');
		form_data.erase('price_max');
		
		form_data.each(function(val, key){
			//if(key == 'keyword') return; // skip keyword karena sudah ditambahkan diatas
			
			if ($type(val) == 'array') {
				val = val.join('|');
			} else {
				val = val.replace(':','%3A');
			}
			
			if (val.contains(' ')) { // tambahkan kutip jika term mengandung spasi
				val = '"' + val + '"';
			}
			str += key +':'+ val +' ';
		}, this);
		return {'str': str, json: form_data};
	},
	
	//------------------------------------------------------
	_checkbox_init: function(clicked, group) {
		if(clicked.checked == true) return true;
		for (var i=0, j=group.length; i<j; i++) {
			if(group[i].checked) {
				return true;
			}
		}
		clicked.checked = true;
		return true;
	},
	
	//------------------------------------------------------
	_open_tab: function(marker, tab_number, marker_name) {
		Avi.Label.current = marker_name;
		Avi.Label.leave(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>';
		}
		html = '<div class="info-window-wrapper">'+html+'</div>';
		this.ew.openOnMarker(marker,html);
	},
	
	//------------------------------------------------------
	_slider_init: function(slider_id) {
		if(this.init[slider_id] == true) return false;
		
		var label_value = this.options[slider_id +'_val'];
		var slider_el = $(slider_id), el = slider_el.getChildren(), label_el = $(slider_id +'_label'), input_el = $(slider_id +'_input');
		
		// parse slider value
		var val = input_el.get('value'), min = 0, max = label_value.length - 1, x;
		if(val.clean() != '') {
			if(val.contains('+')) {
				val = val.replace('+', '');
				if(!isNaN(val)) val *= 1; // convert into numeric
				x = label_value.indexOf(val);
				if(x != -1) min = x;
			} else if(val.contains('-')) {
				val = val.split('-');
				if(!isNaN(val[0])) val[0] *= 1; // convert into numeric
				if(!isNaN(val[1])) val[1] *= 1; // convert into numeric
				
				if(val[1] == '') {
					x = label_value.indexOf(val[0]);
					if(x != -1) max = x;
				} else {
					// min
					x = label_value.indexOf(val[0]);
					if(x != -1) min = x;
					// max
					x = label_value.indexOf(val[1]);
					if(x != -1) max = x;
				}
			}
		}
		
		var slider_instance = new Slider(slider_el, el[1], el[0], {
			start: 0,
			end: label_value.length - 1,
			offset:0,
			knobheight: 21,
			knobwidth: 15,
			onChange: function(pos){
				var _min='', _max='', label='';
				if($type(pos)=='object'){
					_min = label_value[pos.minpos];
					_max = label_value[pos.maxpos];
					if(_min == _max && _min == 0) {
						html = 'any';
						input_el.set('value', '');
					} else {
						if(pos.minpos == 0) {
							html = 'max ' + _max;
							input_el.set('value', _max + '-');
						} else if(pos.maxpos == label_value.length-1) {
							html = 'min ' + _min;
							input_el.set('value', _min + '+');
						} else {
							html = _min + ' to ' + _max;
							input_el.set('value', _min + '-' + _max);
						}
					}
				} else {
					if(html == 0) {
						html = 'any';
						input_el.set('value', '');
					} else {
						html = label_value[pos];
						input_el.set('value', label_value[pos]);
					}
				}
				label_el.set('html', html);
			}.bind(this)
		}, el[2]).setMin(min).setMax(max);
		this.sliders.set(slider_id,slider_instance);
		
		this.init[slider_id] = true;
	},
	
	
	//------------------------------------------------------
	captcha_refresh: function() {
		var img = $('captcha-img');
		if(!img) return;
		var rand = Math.round(Math.random() * 100000);
		img.src = this.url + 'captcha/rand-' + rand + '.jpg';
		$('s-captcha').value = '';
	},
	
	//------------------------------------------------------
	search_tool: function(evt) {
		evt.stop();
		if (!this.Modal) {
			this.Modal = new Avi_Modal();
		}
		if (!this.modal_search_tool) {
			var html = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus est. Phasellus sed purus. Sed gravida, odio nec congue tempus, nulla odio iaculis velit, vitae porta sapien nisl eget nunc.</p>';
			html += '<p align="center"><img usemap="#img-map1" src="http://v3.estatevue.com/public/images/search-tools.jpg" width="300" height="69" alt="search on browser and windows7" />';
			html += '<p>need more information? click <a href="http://www.estatevue.com/real-estate-websites/" title="open Estate Vue blog in new window" target="_blank">here</a>.</p>';
			html += '<map name="img-map1" id="img-map1"><area shape="rect" coords="1,0,162,74" href="#" title="add EstateVue search to your favorite browser" onclick="window.external.AddSearchProvider(\''+this.url+'provider/get_search.xml\')" /><area shape="rect" coords="185,0,299,69" title="download Estatevue search for Windows Explorer" href="'+this.url+'provider/windows.osdx" /></map>';
			
			this.modal_search_tool = this.Modal.build({
				title: 'EstateVue Search Tool',
				html: html,
				width: 320,
				height: 300,
				ok_label: false,
				cancel_label:false
			});
		}
		this.modal_search_tool.show();
	},
	_parse_query: function(query){
		var terms = {}, temp,
		field = ['at', 'price', 'bathroom', 'bedroom', 'builton', 'size', 'type', 'listing-type', 'mls', 'show', 'type', 'page', 'sort-by'];
		query = query.replace(/\+/g,' ');
		query = decodeURIComponent(query);
		var m1 = query.match(/([a-z\-]*):"([^"]*)"/gi); // cari dulu yang ada kutipnya
		if(m1!=null) {
			m1.each(function(m){
				if(m.test(/"$/)) {
					temp = m.split(':');
					if(field.indexOf(temp[0]) > -1) {
						temp[1] = temp[1].replace(/"/g,'').clean();
						terms[temp[0]] = temp[1];
					}
					query = query.replace(m, '');
				}
			});
		}
		var m2 = query.match(/([a-z\-]*):([^\s]*)/gi); // cari yang tidak ada kutip
		if(m2!=null) {
			m2.each(function(m){
				temp = m.split(':');
				if(field.indexOf(temp[0]) > -1) {
					terms[temp[0]] = temp[1].clean();
				}
				query = query.replace(m, '');
			});
		}
		return terms;
	},
	_parse_param: function(param){
		var terms = {}, temp,
		field = ['limit', 'page', 'sort', 'method'];
		param = param.replace(/\+/g,' ');
		param = decodeURIComponent(param);
		var m1 = param.match(/([a-z\-]*):"([^"]*)"/gi); // cari dulu yang ada kutipnya
		if(m1!=null) {
			m1.each(function(m){
				if(m.test(/"$/)) {
					temp = m.split(':');
					if(field.indexOf(temp[0]) > -1) {
						temp[1] = temp[1].replace(/"/g,'').clean();
						terms[temp[0]] = temp[1];
					}
					param = param.replace(m, '');
				}
			});
		}
		var m2 = param.match(/([a-z\-]*):([^\s]*)/gi); // cari yang tidak ada kutip
		if(m2!=null) {
			m2.each(function(m){
				temp = m.split(':');
				if(field.indexOf(temp[0]) > -1) {
					terms[temp[0]] = temp[1].clean();
				}
				param = param.replace(m, '');
			});
		}
		return terms;
	},
	_prepare_hash: function(){
		var hash = window.location.href.split('search.html/');
		hash = hash[1];
		var filter = hash.split('/');
		var parsed_query = this._parse_query(filter[0]);
		//var parsed_param = this._parse_param(filter[1]);
		var terms = {'query':parsed_query/*,'param':parsed_param*/};
		return terms;
	},
	search_for_map: function(){
		var search_terms = this._prepare_hash();
		var bounds = Avi.Map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		search_terms.map_mode = true;
		
		search_terms.sw = southWest.lat() + ',' + southWest.lng();
		search_terms.ne = northEast.lat() + ',' + northEast.lng();
		
		var search_on_server = new Request.JSON({
			url: this.url + 'ajax_search', 
			onComplete: function(respons) {
				this.search_callback(respons);
			}.bind(this)
		}).post(search_terms);
	},
	search_callback : function(data){
		$each(data,function(e){
			this.listings_data.set(e.id,e);
			this._create_marker(e);
		},this);
	},
	_marker_info_window: function(latlngid,marker_name) {
		Avi.Label.current = latlngid;
		Avi.Label.leave(latlngid);
		var marker_lat_lng = this.markers_lat_lng.get(latlngid);
		var marker_data = marker_lat_lng.marker_data;
		var title = marker_lat_lng.title;
		marker_data = marker_data.get(marker_name);
		var marker = marker_lat_lng.marker;
		
		//clear displayed info win
		Avi.InfoWin.clear();
		
		//no info window for this marker, create one
		if(Avi.InfoWin.info_win.has(latlngid) == false){
			var content = marker_data.content;
			var html = '<div class="title"><span id="info-window-title">'+title+'</span></div><div class="content" id="info-window-content">'+content+'</div>';
			html = '<div class="info-window-wrapper">'+html+'</div>';
			Avi.InfoWin.create(latlngid, marker_name,marker, html);
			Avi.InfoWin.show(latlngid);
		} else {
		//info window for this marker exists, show
			Avi.InfoWin.show(latlngid);
		}
		
	},
	_marker_label: function(data,marker){
		var id_ = data.lat+','+data.lng;
		//create label
		Avi.Label.create(id_, marker, '<strong>MLS&reg; #: '+data.mls+'</strong>$'+data.price+' | ba: '+data.ba +' | br: '+data.br);

		//----- Build window info ----------------------
		var title = '', content = '';
    	title = data.address;
    	if(data.status=='Sold')
    		title += ' (Sold)';
    	content = '<table border="0" width="100%"><tr>';
    	
    	var link = site_url + 'for-sale/property-detail/'+ data.eID + '/' + data.alias +'.html';
    	
    	content += '<td width="90"><a href="'+ link +'"><img src="' + data.img + '" width="75" height="75"/></a><br/>&raquo; <a href="'+ link +'">more info</a></td>';
    	content += '<td><p>MLS&reg; #: <strong>'+data.mls+'</strong></p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'</p><p>Realtor: '+data.realtor+'</p><p>Brokerage: '+data.brokerage+'</p><p>'+data.type+'</p><p class="price">Price: <span>'+data.price+'</span></p></td>';
    	content += '</tr></table>';

		var marker_info = new Hash();
    	marker_info.set(data.id,{'content':content});
		this.markers_lat_lng.set(id_,{'marker':marker,'marker_data':marker_info,'title':title});
		
	    google.maps.event.addListener(marker, 'click', function(){
			this._marker_info_window(id_,data.id);
	    }.bind(this));
		
		return marker;
	},
	_append_data : function(data,latlngid){
		var marker_lat_lng = this.markers_lat_lng.get(latlngid);
		var marker_data = marker_lat_lng.marker_data;
		var marker = marker_lat_lng.marker;
		var marker_title = marker_lat_lng.title;
		// if only one data found, change the content
		if(marker_data.getLength() == 1){
			//retrieve old data
			var old_id = null;
			marker_data.each(function(d,k){
				old_id = k;
			},this);
			var data_old = this.listings_data.get(old_id);
			//begin changing old data			
			var address = '<strong>'+data_old.address;
	    	if(data_old.unit)
	    		address += ' #' + data_old.unit;
	    	if(data_old.status == 'Sold')
    			address += ' (Sold)';
	    	address += '</strong><br/>';
			content = address+'<table border="0" width="100%"><tr>';
	    	
	    	var link = site_url + 'for-sale/property-detail/'+ data_old.eID + '/' + data_old.alias +'.html';
	    	
	    	content += '<td width="90"><a href="'+ link +'"><img src="' + data_old.img + '" width="75" height="75"/></a><br/>&raquo; <a href="'+ link +'">more info</a></td>';
	    	content += '<td><p>MLS&reg; #: <strong>'+data_old.mls+'</strong></p><p>'+data.br+' br  /  '+data_old.ba+' ba  /  '+data_old.lot+'</p><p>Realtor: '+data_old.realtor+'</p><p>Brokerage: '+data_old.brokerage+'</p><p>'+data_old.type+'</p><p class="price">Price: <span>'+data_old.price+'</span></p></td>';
	    	content += '</tr></table>';
	    	
	    	marker_data.set(old_id,{'content':content});
	    	//set new marker image
			var hexcol = this.icons.get(data_old.type).hex;
			var image = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=home|'+hexcol,
				new google.maps.Size(15, 24),
				new google.maps.Point(0,0),
				new google.maps.Point(6, 20),
				new google.maps.Size(15,24)
			);
			marker.setIcon(image);
		}
		// build new info window
		var content = '';
    	var address = '<strong>'+data.address;
    	if(data.unit)
    		address += ' #' + data.unit;
    	if(data.status == 'Sold')
			address += ' (Sold)';
    	address += '</strong><br/>';
		content = address+'<table border="0" width="100%"><tr>';
    	
    	var link = site_url + 'for-sale/property-detail/'+ data.eID + '/' + data.alias +'.html';
    	
    	content += '<td width="90"><a href="'+ link +'"><img src="' + data.img + '" width="75" height="75"/></a><br/>&raquo; <a href="'+ link +'">more info</a></td>';
    	content += '<td><p>MLS&reg; #: <strong>'+data.mls+'</strong></p><p>'+data.br+' br  /  '+data.ba+' ba  /  '+data.lot+'</p><p>Realtor: '+data.realtor+'</p><p>Brokerage: '+data.brokerage+'</p><p>'+data.type+'</p><p class="price">Price: <span>'+data.price+'</span></p></td>';
    	content += '</tr></table>';
    	
    	marker_data.set(data.id,{'content':content});
    	this.markers_lat_lng.set(latlngid,{'marker':marker,'marker_data':marker_data,'title':marker_title});
		
    	// set new label
		var label = Avi.Label.label.get(latlngid);
		var newlabel = '<strong>'+data.address+'</strong>('+marker_data.getLength()+' listings)';
		label.el.set('html',newlabel);
		
	},
	_create_marker : function(data){
		var id_ = data.lat+','+data.lng;
		
		//no marker in this lat lng point, create one
		if(this.markers_lat_lng.has(id_) == false){
			//if icon set does not exist yet, create a new one
			if(this.icons.has(data.type) == false){
				var i = this.icons.getLength() % this.options.marker_color.length; // kenapa di MOD? 
				//alert(i);
				var image = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_'+this.options.marker_color[i]+'.png',
					new google.maps.Size(15, 24),
					new google.maps.Point(0,0),
					new google.maps.Point(6, 20));
				var shadow = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
					new google.maps.Size(22, 20),
					new google.maps.Point(0,0),
					new google.maps.Point(6, 20));
				var hex = this.options.marker_color_hex[i];
				hex = hex.replace('#', '');
				this.icons.include(data.type,{'image':image,'shadow':shadow,'hex':hex});
				this.update_legend(i,data.type);
				
			} else {
				var image = this.icons.get(data.type).image;
				var shadow = this.icons.get(data.type).shadow;
			}
			var myLatLng = new google.maps.LatLng(data.lat,data.lng);
			var marker = new google.maps.Marker({
				position: myLatLng,
			    map: Avi.Map,
			    shadow: shadow,
			    icon: image,
			    title: data.title
			});
			this._marker_label(data, marker);
		} else {
		//marker in this point exists, try to append data
			var marker_data = this.markers_lat_lng.get(id_).marker_data;
			//this listing is not in the storage, append to the marker
			if(marker_data.has(data.id) == false){
				this._append_data(data,id_);
			}
			//the listing is in the storage, do nothing
		}
	},
	update_legend: function(i,type){
		var legend_wrapper = $('avi-map-legend');
		var legend_target = legend_wrapper;
		var old_h = this.legend_y;
		if(this.icons.getLength()==3) {
			new Element('a',{
				html:'----- more legend -----',
				events: {
					mouseenter: function(){
						legend_wrapper.addClass('avi-map-legend-hover');
						var h1 = this.legend_y;
						var h2 = legend_wrapper.offsetHeight;
						this.repos_legend(h1,h2);
					}.bind(this)
				}
			}).inject($('avi-map-legend'));
			
			legend_target = new Element('div',{
				id:'avi-map-legend-more',
				style:'display:none'
			}).inject(legend_wrapper);	
			
			legend_wrapper.addEvent('mouseleave',function(){
				var h1 = this.legend_y;
				var h2 = legend_wrapper.offsetHeight;		
				this.repos_legend(h1,h2);
			}.bind(this));
		}
		

		if(this.icons.getLength()>2) {
			legend_target = $('avi-map-legend-more');
		} 
		
		
		var bg_icon = 'http://labs.google.com/ridefinder/images/mm_20_'+ this.options.marker_color[i] +'.png';
		new Element('span',{
			html:type,
			style:'background-image:url('+ bg_icon +')'
		}).inject(legend_target);
		
		var new_h = legend_wrapper.offsetHeight;
		this.repos_legend(old_h,new_h);
	},
	
	repos_legend: function(old_h,new_h){
		this.legend_y = new_h;
		var legend_wrapper = $('avi-map-legend');
		var top = legend_wrapper.getStyle('margin-top');
		top = top.replace('px','');
		top = parseInt(top);
		if(old_h > new_h){
			var h = old_h - new_h;
			h = top + h;
		} else {
			var h = new_h - old_h;
			h = top - h;
		}
		legend_wrapper.setStyle('margin-top',h+'px');
	}
	
});

var init_map;
window.addEvents({
	domready: function() {
		$('si_last').setStyle('height','24px');
		
		Avi.Search = new Avi_Search();
		
		var MAX_ZOOM_LEVEL = 19;
		var MIN_ZOOM_LEVEL = 11;
		
		
		/*if (!google.maps.BrowserIsCompatible()) {
			alert('Your browser is NOT compatible to view our map, please use other web browser.');
			return false;
		}*/
		init_map = function(){
		Avi.Map = new google.maps.Map(Avi.Search.elements.map_wrapper, {
		      zoom: 15,
		      mapTypeId: google.maps.MapTypeId.ROADMAP,
		      disableDoubleClickZoom:true,
		      scaleControl: false,
		      mapTypeControl: false,
		      navigationControl: false,
		      scrollwheel: false,
		      streetViewControl: false
		});
		if($('at').value == '')
			$('at').value = 'Kelowna BC';
		
		var geocoder = new google.maps.Geocoder();
		var address = $('at').value;
		var pos;
	    geocoder.geocode( { 'address': address}, function(results, status) {
	      if (status == google.maps.GeocoderStatus.OK) {
	    	  pos = results[0].geometry.location;
	    	  Avi.Map.setCenter(pos);
			  Avi.Map.fitBounds(results[0].geometry.viewport);
	      } else {
	    	  pos = new google.maps.LatLng(-119.4496250, 49.8799130);
	    	  Avi.Map.setCenter(pos);
	      }
	    });		
			
	    Avi.Label = new Avi_Marker_Label(Avi.Map, {classname:'avi-label',offset: {width:59,height:18}});
	    Avi.InfoWin = new Avi_Marker_InfoWin(Avi.Map, {classname:'ev-listing-baloon',offset: {width:0,height:40}});
	    
		//-------- custom zoom level -----------------
		Avi_Map_Zoom_Control = function(map){return this.initialize(map);};
		Avi_Map_Zoom_Control.prototype.initialize = function(map) {
			//alert(map);
			this.map = map;
			var container = new Element('div',{
				'class': 'avi-zoom',
				'style': 'margin:7px;'
			});
			var zoom_in = new Element('img', {
				src: 'http://v2.estatevue.com/public/images/blank.gif',
				'class': 'avi-zoom-in',
				title:'zoom in',
				events: {
					click: function() {
						var z = MAX_ZOOM_LEVEL - this.map.getZoom() - 1;
						if(z < 0) return;
						this.slider.setMin(z);
					}.bind(this)
				}
			}).inject(container);
			
			var knob_area = new Element('div', {
				'class': 'avi-zoom-knob-area'
			}).inject(container);
			
			var gutter= new Element('img', {
				src: 'http://v2.estatevue.com/public/images/blank.gif',
				'class': 'avi-zoom-gutter'
			}).inject(knob_area);
			this.knob = new Element('img', {
				src: 'http://v2.estatevue.com/public/images/blank.gif',
				'class': 'avi-zoom-knob',
				title:'drag to zoom map'
			}).inject(knob_area);
			var zoom_out = new Element('img', {
				src: 'http://v2.estatevue.com/public/images/blank.gif',
				'class': 'avi-zoom-out',
				title:'zoom out',
				events: {
					click: function() {
						var z = MAX_ZOOM_LEVEL - this.map.getZoom() + 1;
						if(z > MAX_ZOOM_LEVEL) return;
						this.slider.setMin(z);
					}.bind(this)
				}
			}).inject(container);
			Avi.Map.controls[google.maps.ControlPosition.TOP_LEFT].push(container);
			container.inject(Avi.Search.elements.map_wrapper);
			this.slider = new Slider(knob_area, this.knob, gutter, {
				snap:true,
				start:0,
				end:MAX_ZOOM_LEVEL - MIN_ZOOM_LEVEL,
				mode:'vertical',
				knobheight:8,
				knobwidth:17,
				clip_w:0, 
				clip_l:0,
				onChange: function(pos){
					var z = MAX_ZOOM_LEVEL - pos;
					this.map.setZoom(z);
				}.bind(this)
			}).setMin(19 - this.map.getZoom());
			
			// Listen for other things changing the zoom level and move the slider
        	google.maps.event.addListener(map, 'zoomend', function(a,zoom) {this.slider.setMin(MAX_ZOOM_LEVEL - zoom);}.bind(this));
			
			//return container;
		};
		Avi_Map_Zoom_Control.prototype.getDefaultPosition = function() {
			return google.maps.ControlPosition.TOP_LEFT;
		};
		
		//-------- custom map type -----------------
		Avi_Map_Type_Control = function(map){return this.initialize(map);};
		Avi_Map_Type_Control.prototype.initialize = function(map){
			this.map = map;
			var container = new Element('div', {
				'class':'avi-map-type',
				'style':'margin:7px;'
			});
			var ul = new Element('ul').inject(container);
			var t_map = new Element('li', {
				'id':'map',
				'class':'selected',
				events: {
					click: function(){
						if (t_map.hasClass('selected')) 
							return true;
						t_map.addClass('selected');
						selected.removeClass('selected');
						selected = t_map;
						
						map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
						
						return true;
					}
				}
			}).inject(ul);
			var t_satellite = new Element('li', {
				id:'satellite',
				events: {
					click: function(){
						if (t_satellite.hasClass('selected')) 
							return true;
						t_satellite.addClass('selected');
						selected.removeClass('selected');
						selected = t_satellite;
						
						map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
						
						return true;
					}
				}
			}).inject(ul);
			var t_hybrid = new Element('li', {
				id:'hybrid',
				events: {
					click: function(){
						if (t_hybrid.hasClass('selected')) 
							return true;
						t_hybrid.addClass('selected');
						selected.removeClass('selected');
						selected = t_hybrid;
						
						map.setMapTypeId(google.maps.MapTypeId.HYBRID);
						
						return true;
					}
				}
			}).inject(ul);
			var selected = t_map;
			Avi.Map.controls[google.maps.ControlPosition.TOP_RIGHT].push(container);
			
			return container;
		};
		Avi_Map_Type_Control.prototype.getDefaultPosition = function() {
			return google.maps.ControlPosition.TOP_RIGHT;
		};
		
		//---- custom map legend ----------
		Avi_Map_Legend_Control = function(map){return this.initialize(map);};
		Avi_Map_Legend_Control.prototype.getDefaultPosition = function() {
			return google.maps.ControlPosition.BOTTOM_RIGHT;
		};
		Avi_Map_Legend_Control.prototype.initialize = function(map){
			this.map = map;	
			
			var container = new Element('div', {
				'class':'avi-map-legend',
				'id':'avi-map-legend',
				html:'<h4>Map Legend</h4>',
				style:'opacity:.6;margin-right:7px;margin-top:400px;'
			});
			container.addEvents({
				'mouseenter':function(){
					this.setStyle('opacity',1);
				},
				'mouseleave':function(){
					this.setStyle('opacity',.8).removeClass('avi-map-legend-hover');
				}
			});
			Avi.Map.controls[google.maps.ControlPosition.RIGHT].push(container);
			new Element('span',{
				html:'My Listing',
				style:'background-image:url('+public_url+'images/my_listing.png)'
			}).inject(container);
			new Element('span',{
				html:'Multiple Listings',
				style:'background-image:url('+public_url+'images/multiple_listing.png)'
			}).inject(container);
			return container;
		};
		var mapzoomcontrol = new Avi_Map_Zoom_Control(Avi.Map);
		var maptypecontrol = new Avi_Map_Type_Control(Avi.Map);
		var maplegendcontrol = new Avi_Map_Legend_Control(Avi.Map);
		
		google.maps.event.addListener(Avi.Map, 'tilesloaded', function () {			
			Avi.Search.search_for_map();			
		});
		
		google.maps.event.addListener(Avi.Map, 'click', function(){
			Avi.Label.clear();
			Avi.InfoWin.clear();
			Avi.Label.current = '';
		});
		}
		$('search-result-list').removeClass('hidden');
		$('search-result-map').addClass('hidden');
		//window.addEvent('unload', function(){GUnload();});
		$('tab_map').removeClass('selected');
		$('tab_list').addClass('selected');
		
	}
});


var Avi_Modal = new Class({
	modals:[],
	elements: {},
	options: {
		title:null,
		html:'',
		width:300,
		height:300,
		ok_fn: null,
		cancel_fn: null,
		ok_label: 'OK',
		cancel_label:'Cancel'
	},
	
	initialize: function(opts) {
		this.options = $merge(this.options, opts);
		this.elements.modal = new Element('div', {
			'class': 'avi-modal',
			styles:{
				position:'fixed',
				display:'none'
			}
		}).inject(document.body);
	},
	
	//----------------------------
	build: function(options) {
		options = $merge(this.options, options);
		var wrapper = new Element('form',{
			'class':'avi-modal-wrapper',
			styles: {
				width: options.width
			}
		});
		
		if(options.title) {
			new Element('h3',{'class':'avi-modal-title',html:options.title}).inject(wrapper);
		}
		new Element('div',{
			'class':'avi-modal-content',
			html:options.html,
			styles:{
				height:options.height - 70
			}
		}).inject(wrapper);
		var footer = new Element('div',{'class':'avi-modal-footer'}).inject(wrapper);
		if(!this.ok_label && !options.cancel_label) {
			new Element('button',{
				text:'close',
				events:{
					click:this.hide.bind(this)
				}
			}).inject(footer);
		} else {
			if (options.ok_label) {
				new Element('button', {
					text: options.ok_label,
					events: {
						click: function(){
							var close = true;
							if ($type(options.ok_fn)=='function') 
								close = options.ok_fn.run();
							if(close !== false)
								this.hide();
							return false;
						}.bind(this)
					}
				}).inject(footer);
			}
			if (options.cancel_label) {
				new Element('button', {
					text: options.cancel_label,
					events: {
						click: function(){
							if ($type(options.cancel_fn)=='function') {
								options.cancel_fn.run();
							}
							this.hide();
						}.bind(this)
					}
				}).inject(footer);
			}
		}
			
		var i = this.modals.length;
		var modal = {
			el: wrapper,
			options: options,
			show: function(num) {
				this.show(num);
			}.bind(this, i),
			hide: function() {
				this.hide();
			}.bind(this)
		};
		this.modals.push(modal);
		
		return modal;
	},
	
	//----------------------------
	show: function(num) {
		var m = this.modals[num];
		if(!m) return false;
		this.elements.modal.set('html','');
		m.el.inject(this.elements.modal);		
		this.elements.modal.setStyles({
			display:'',
			top: ((window.getHeight() - m.options.height)/2).toInt(),
			left: ((window.getWidth() - m.options.width)/2).toInt()
		});
		return true;
	},
	//----------------------------
	hide: function() {
		this.elements.modal.setStyle('display','none');
		return false;
	},
	//----------------------------
	fade: function(num) {
	},
	//----------------------------
	unfade: function(num) {
	}
	
});

/**
 * Check all checkbox 
 * 
 * @param STRING theform FORM element id
 * @param STRING cb_name checkbox element name
 * @return void
 **/
function checkAll(wrapper, cb_name, check) {
	var wrapper = $type(wrapper)=='element' ? wrapper : $(wrapper);
	if (!wrapper) return false;
	var cb = wrapper.getElements('input[name^='+cb_name+']');
	if (!cb) return false;
	var val = [];
	cb.each(function(el){
		el.checked = check;
	});
	return true;
}
