//console.log( "OMNIBOX MAPBOX", "omnibox-search-7342212083199630821-p" );

;(function( webletId ) {

	var jQuery = window.jQuery || window.$;
	
	if( window._gmrp && window._gmrp.$ ) {
		jQuery = window._gmrp.$;
	}
	
	var $beds = jQuery( "#" + webletId + " [name=unibox-bedrooms]" );
	var $baths = jQuery( "#" + webletId + " [name=unibox-bathrooms]" );
	var $propTypes = jQuery( "#" + webletId + " [name=unibox-prop-types]" );
	var $transTypes = jQuery( "#" + webletId + " [name=unibox-trans-types]" );
	var $priceMin = jQuery( "#" + webletId + " [name=unibox-price-min]" );
	var $priceMax = jQuery( "#" + webletId + " [name=unibox-price-max]" );
	var $submit = jQuery( "#" + webletId + " [name=unibox-run]" );
	
	var $ctx = jQuery( "#" + webletId + " [name=unibox-search-context]" );
	var $acct = jQuery( "#" + webletId + " [name=unibox-search-account]" );
	var $listingType = jQuery( "#" + webletId + " [name=unibox-search-listing-type]" );
	var $mapName = jQuery( "#" + webletId + " [name=unibox-search-map]" );
	var $region = jQuery( "#" + webletId + " [name=unibox-search-region]" );
	
	var country = "CA" || "CA";
	var region = "CALGARY" || "GV";
	var initLat = 51.048 || 49.25;
	var initLng = -114.064 || -123.088;
	
	$priceMin.on( "keydown", function(e) {
		if( e.keyCode == 13 ) {
			setTimeout( function() {
				runUnibox();
			}, 100 );
		}
	});
	$priceMax.on( "keydown", function(e) {
		if( e.keyCode == 13 ) {
			setTimeout( function() {
				runUnibox();
			}, 100 );
		}
	});
	
	
	function runUnibox() {
	
		
		var location = jQuery( "#" + webletId + " [name=unibox-field]" ).data();
		var locationValue = jQuery( "#" + webletId + " [name=unibox-field]" ).val();
		
		var beds = $beds.val() || "";
		var baths = $baths.val() || "";
		var propType = $propTypes.val() || "";
		var transType = $transTypes.val() || "";
		var priceMin = $priceMin.val() || "";
		var priceMax = $priceMax.val() || "";
		var ctx = $ctx.val() || "recip";
		var acct = $acct.val() || "-";
		var listingType = $listingType.val() || "AUTO";
		var region = $region.val() || "";
		
		var page = "recip.html";
		if( ctx == "vow" ) {
			page = "vow.html";
		}
		
		var qs = "";
		
		if( ( "GV" == region || "ALBERTA" == region ) && findUniboxDropdownLabel( $submit, "unibox-prop-types" ).indexOf( " (Commercial)" ) != -1 ) {
			qs += "listingType=AUTO_COMM&";
		}
		else if( listingType && listingType != "AUTO" ) {
			qs += "listingType=" + listingType + "&";
		}
		
		if( location && location.properties && location.properties['mls'] ) {
			qs += "i_mlsnum=" + escape(location.properties['mls']) + "&";
		}
		else if( locationValue && isMLSNumber( locationValue ) ) {
			qs += "i_mlsnum=" + escape(locationValue) + "&";
		}
		else {
		
			if( beds ) {
				qs += "i_beds=" + escape(beds) + "-" + "&";
			}
			if( baths ) {
				qs += "i_baths=" + escape(baths) + "-" + "&";
			}
			
			if( priceMin ) {
				priceMin = priceMin.replace(/[^0-9\.]+/g, '' );
				if( !isNaN( parseFloat(priceMin) ) ) {
					qs += "i_price_from=" + escape( priceMin ) + "&";
				}
			}
			if( priceMax ) {
				priceMax = priceMax.replace(/[^0-9\.]+/g, '' );
				if( !isNaN( parseFloat(priceMax) ) ) {
					qs += "i_price_to=" + escape( priceMax ) + "&";
				}
			}
			
			if( propType ) {
				if( ( "GV" == region || "ALBERTA" == region ) && findUniboxDropdownLabel( $submit, "unibox-prop-types" ).indexOf( " (Commercial)" ) != -1 ) {
					qs += "i_prop_type_com=" + escape( propType ) + "&";
				}
				else {
					qs += "i_prop_type=" + escape( propType ) + "&";
				}
			}
			
			if( transType ) {
				qs += "i_trans_type=" + escape( transType ) + "&";
			}
			
			if( location ) {
				if( location.place_name ) {
					qs += "i_location=" + escape( location.place_name ) + "&";
				}
				if( location.bbox ) {
					// we are doing lat,lng,lat,lng for backward compat
					qs += "i_bounds=" + location.bbox[1] + "," + location.bbox[0] + "," + location.bbox[3] + "," + location.bbox[2] + "&";
				}
				else if( location.center ) {
					qs += "i_place=" + location.center[1] + "," + location.center[0] + "&";
				}
			}
		}
		
		console.log( location, beds, baths, propType, priceMin, priceMax, ctx, acct, listingType, region );
		
		//var url = "/wps/-/noframe~true/" + ctx + "/" + acct + "/idx.search?";
		//url += qs;
	
		console.log( page + "?autosearch&" + qs );
		window.location = page + "?autosearch&" + qs;
	}
	
	function findUniboxDropdownLabel( from, selector ) {
		
		return jQuery( from ).closest( ".unibox-search" ).find( "[name=" + selector + "] option:selected" ).text() || "";
	}
		
		
	function isMLSNumber( val ) {
		// mls numbers can be a123456 ab123456 123456 123455a 123456ab ... we allow up to 6 letters and no less 
		// than 6 digits
		var out = /^\s*[A-Za-z]{0,6}\d{6,}[A-Za-z]{0,6}\s*$/.test(val);
		
		if( "DDF" == region ) {
			out = /^\s*[A-Za-z]{0,6}\d{3,}[A-Za-z]{0,6}\s*$/.test(val);
		}
		
		return out;
	}
	
	function mlsNumberGeocoder( query ) {
			
		if( query.indexOf( 'Find MLS\xAE # ' ) == 0 ) {
			query = query.replace( 'Find MLS\xAE # ', '' ).trim();
		}
					
		if( isMLSNumber( query ) ) {
			return [{
	            center: [0, 0],
	            geometry: {
	                type: "Point",
	                coordinates: [0, 0]
	            },
	            place_name: 'Find MLS\xAE # ' + query, 
	            place_type: ['coordinate'], 
	            properties: {
	            	mls : query
	            },
	            type: 'Feature'
	        }];
		}
		else {
			return null;
		}
	}	
	
	function CustomGeocoder(options) {
		MapboxGeocoder.call(this, options );
	};
	CustomGeocoder.prototype = Object.create( MapboxGeocoder.prototype, {	
		// custom class code here
		onAdd : {
			value : function( $el ) {
			
				var out = MapboxGeocoder.prototype.onAdd.apply( this, null );
				
				var _this = this;
				
				this._inputEl.setAttribute('name','unibox-field');
				this._inputEl.classList.add('unibox-field');
				this._inputEl.setAttribute('autocomplete', 'off' );		
				this._inputEl.setAttribute('autocorrect', 'off' );		
				this._inputEl.setAttribute('autocapitalize', 'off' );		
				this._inputEl.setAttribute('spellcheck','false');
				
				this._inputEl.addEventListener('keydown', function(e) {
				
					if( e.keyCode == 13 ) {
						setTimeout( function() {
							runUnibox();
						}, 100 );
					}
					setTimeout( function() {
						if( e.metaKey && _this._inputEl.value ) {
							// force for copy and pasted MLS&reg; numbers
							if (_this._inputEl.value.length >= _this.options.minLength) {
								_this._geocode(_this._inputEl.value);
							}
						}
					},10);
				});
				
				
				this.on( 'result', function( e ) {
			
					var result = e.result || e;
					
					//console.log( result );
					
					if( result.properties && result.properties['mls'] ) {
						//page( "/wps/-/tmpl~v2,noframe~true/" + _gmrp.settings["CONTEXT"] + "/" +
						//		_gmrp.settings["ACCOUNT_ID"] + "/mls-" + result.properties['mls'] + "?offmarket=true");
						console.log( "mls", result.properties['mls'] );
						jQuery( _this._inputEl ).data( result );
					}
					else if( result.bbox ) {
						//_this.map.fitBounds( result.bbox );
						console.log( "bbox", result.bbox );
						jQuery( _this._inputEl ).data( result );
					}
					else if( result.center ) {
						console.log( "center", result.center );
						jQuery( _this._inputEl ).data( result );
					}					
				});
				
				return out;
			}
		}
	});
	CustomGeocoder.prototype.constructor = CustomGeocoder;
	
	var $locField = jQuery( "#" + webletId + " input[name=unibox-field]" );
	
window._gmrp_geoFilter = function(item,index,items) {

	var overrides = {
		"Greenwood, Nova Scotia, Canada" : { // Greenwood, Nova Scotia
			center: [-64.934722, 44.971944],
			// sw, ne trigge 'mrp.debug.map.bounds' on document to dump
			bbox : [-64.98192887852869,44.95217585223236,-64.87687211583203,44.990491318266294]
		},
		"neighborhood.7899298212961420" : {
			// replacing "Scarborough City Centre, M1P 4P5, Etobicoke, Ontario, Canada"
			// with more appropriate "Scarborough, Toronto"
			text: "Scarborough, Toronto",
			place_name: "Scarborough, Toronto",
			center: [-79.3128433, 43.7589442 ],
			bbox: [ -79.36823308452246, 43.707401993492596, -79.09305989726784, 43.81241425080441 ]
		}
	};


	if( item.place_name ) {
		var override = overrides[item.place_name];
		if( override ) {
			item.center = override.center;
			item.bbox = override.bbox;
		}
		override = overrides[item.id];
		if( override ) {
			item.place_name = override.place_name;
			item.text = override.text || item.text;
			item.center = override.center;
			item.bbox = override.bbox;
		}
	}
	return true;
}
	
	var geocoder = new CustomGeocoder({
	    accessToken: "pk.eyJ1IjoibXlyZWFscGFnZSIsImEiOiJjamd3dTBvd24wMDV3MnFuOXg2NTB6eDFrIn0.sKvYZK1dR9Jz7VUfTebaAA",
	    country : country,
	    trackProximity : false, // no map, no proximity
	    flyTo: false,
	    proximity : { longitude : initLng, latitude : initLat },
	    placeholder : $locField.attr( "placeholder" ) || "",
		filter: window._gmrp_geoFilter || null,
	    //types : 'postcode,district,neighborhood,locality,address',
	    localGeocoder : mlsNumberGeocoder
	});
	
	var wrapper = geocoder.onAdd( null ); //  no map
	
	//$locField.parent().addClass( wrapper.className );
		
	$locField.parent().html("").append( jQuery(wrapper).children() );	
	
	$submit.on( "click", function() {
		runUnibox();
	});
	
	
	
})( "omnibox-search-7342212083199630821-p" );