//KangCache
/* Global Namespace*/
var ELNK = window.ELNK || {};

ELNK.Cache = Class.create();

ELNK.Cache.DEFAULT_SIZE = 50;
ELNK.Cache.DEFAULT_TTL = 5 * 1000;

ELNK.Cache.prototype = {
	initialize: function(size, ttl) {
		this.size = size > 0 ? size : ELNK.Cache.DEFAULT_SIZE;
		this.ttl = ttl > 0 ? ttl : ELNK.Cache.DEFAULT_TTL;
		thiss = {};
		this.length = 0;
	},
	
	_insert: function(key, value) {
		thiss[key] = {
			element: value,
			timestamp: new Date().getTime()
		};
		this.length++;
	},
	
	remove: function(key) {
		if(thiss[key]) {
			delete thiss[key];
			this.length--;
		}
	},
	
	get: function(key) {
		if(!key || !key.length) return null;
		if(thiss[key]) {
			if((new Date().getTime() - thiss[key].timestamp) > this.ttl) {
				this.remove(key);
				return null;
			}
			return thiss[key];
		}
		return null;
	},
	
	put: function(key, value) {
		if(!key || !key.length) return null;
		this._insert(key, value);
		// leave out the upper bound limit check for now, put in later
		/* if(this.length > this.size) {
			this.findLRU();
		} */
	},
	
	findLRU: function() {
		var lookupKey;
		var timestamp = new Date().getTime();
		$H(thiss).each(function(element) {
			if(element.value.timestamp < timestamp) {
				lookupKey = element.key;
				timestamp = element.value.timestamp;
			}
		});
		this.remove(lookupKey);
	},
	
	values: function() {
		return $H(thiss).values();
	},

	keys: function() {
		return $H(thiss).keys();
	}

}

//Vars
var sprint_num = '5';
var msMap = null
var LoadErr = 0;
var cache = new ELNK.Cache(10, 5 * 60 * 1000);
var bMap = new Object;
var mbsDropDown;
var d=document;
var isFF = false;
var isIE = false;
var isIE6 = false;
var classRef = "class";
var isSafari = false;
var isCamino = false;

bMap.user = new Object;
bMap.mapinfo = new Object;
bMap.results = new Object;
bMap.request = new Object;
bMap.pins = new Object;
bMap.dList = new Object;

if(navigator.userAgent.indexOf("Firefox") != -1) { isFF = true; }
if(navigator.userAgent.indexOf("MSIE") != -1) { isIE = true; }
if(navigator.userAgent.indexOf("MSIE 6.0") != -1) { isIE6 = true; }
if(isIE) { classRef = "className"; }  // IE expects 'className' for the attribute param in setAttribute.
if(navigator.userAgent.indexOf("AppleWebKit") > -1) { isSafari = true; }
if(navigator.userAgent.indexOf("Camino") > -1) { isCamino = true; }

//Redirect Users if not supported
if(!isFF && !isIE){
	lowFiMap();
}
function lowFiMap(){//Sends user to low fi EarthLink Local Search Product
	if(window.location.search){
		window.location='http://search.feather.com/search/local'+window.location.search;
	}else{
		window.location='http://search.feather.com/';
	}
}

//Debug tools
function sprintBlock(cond){
	if(window.location.port != 8080 && cond){
		alert('This feature is disabled for ' + navigator.appName + ' users in sprint #' + sprint_num);
		return false;
	}else{
		return true;
	}
}
function getProps(obj) {
	if(obj == null) {
		return "null";
	}
	var props = "";
	for(p in obj) {
		props += p + " | ";
	}
	return props;
}

//Utilities
function makeRand() {
	var newRand = new Date().getTime().toString().substring(8,12) + Math.random().toString().substring(2,6);
	return newRand;
}
function mergeObjects(original,newo){
	if(newo && original){
		var m = $H(original).merge($H(newo));
		m.each(function(e){
			original[e[0]] = e[1];
		});
		return true;
	}else{
		return false;
	}
}
function dropDownTimer(div){
	if(!div.id){
		div.id='mbsDropDown'+makeRand();
	}
	clearTimeout(mbsDropDown);
	mbsDropDown = setTimeout("$('"+div.id+"').hide();",1000);
}

//Ms Map Specific
function mapZoom(lat,lon,zoom){
	msMap.SetCenterAndZoom(new VELatLong(lat,lon),zoom);
	
}
function initMap(div){
	//Set Default Location
	msMapCenter=new Object();
	msMapCenter['location']=new Object();
	msMapCenter['location'].near = 'United States';
	msMapCenter['location'].lat = 38.4897347278551;
	msMapCenter['location'].lon = -96.7082113261037;
	msMapCenter.zoom = 4;
	msMapCenter.mode = 'r';
	msMapCenter.resultSet = 'local';
	msMapCenter.resultNum = 10;
	bMap.mapinfo=msMapCenter;
	
	//Create Map Object
	try{
		msMap = new VEMap('bigmap');
		msMap.SetDashboardSize(VEDashboardSize.Small);
		drawMap();
		
	}catch(err){
		if (LoadErr < 5){
			LoadErr++;
			setTimeout("initMap()",1000);
		}else{//If error was raised by Virtual Earth, redirect user to Low Fi
			lowFiMap();
		}
	}
	
	// run functions in index.html
	runTodo();
}

function runTodo(){
	runAfterMapLoadEvent();
}

function drawMap(){
	try{
		msMap.LoadMap(new VELatLong(bMap.mapinfo['location'].lat,bMap.mapinfo['location'].lon), bMap.mapinfo.zoom ,bMap.mapinfo.mode ,false);
	}catch(err){//If error was raised by Virtual Earth, redirect user to Low Fi
		lowFiMap();
	}
	//
}
function addPins(resSet){
	msMap.HideAllShapeLayers();
	if(bMap.mapinfo.resultSet=='local') {
		if($(resSet+'_list') && bMap.results[resSet]){
			if(!bMap.pins[resSet]){
				bMap.pins[resSet] = new VEShapeLayer();
				bMap.pins[resSet].SetTitle(resSet);
				msMap.AddShapeLayer(bMap.pins[resSet]);
			}else{
				bMap.pins[resSet].DeleteAllShapes();
			}
			var tshape;
			var tlist = $A($(resSet+'_list').childNodes)
			for(i = 0;tlist.length > i;i++){
				bMap.pins[resSet].AddShape(new VEShape(VEShapeType.Pushpin, new VELatLong(bMap.results[resSet][i]['lat'],bMap.results[resSet][i]['lon'])));
				bMap.pins[resSet].GetShapeByIndex(i).SetCustomIcon('<div class="pushpin">'+tlist[i].getElementsByClassName('pushpin')[0].innerHTML+'</div>');
				bMap.pins[resSet].GetShapeByIndex(i).SetTitle(bMap.results[resSet][i]['name']);
				bMap.pins[resSet].GetShapeByIndex(i).SetDescription(tlist[i].innerHTML);
			}
		}
	}
}
function panMap(lat,lon){
	//Set Location
	msMap.PanToLatLong(new VELatLong(lat,lon));
}
function openPin(id){
	msMap.ShowInfoBox(bMap.pins[bMap.mapinfo.resultSet].GetShapeByIndex(id));
}
function closePins(){
	bMap.results[bMap.mapinfo.resultSet].each(function(i){
		msMap.HideInfoBox(i);
	})
}

//Display
function clientResize(){
	if(isIE){
		var mheight=$('map_container').getHeight()-parseFloat($('bigmap').offsetTop-$('map_container').offsetTop)+40
	}else{
		var mheight=$('map_container').getHeight()-parseFloat($('bigmap').offsetTop-$('map_container').offsetTop)
	}
	if(!isIE6){
		$('doc3').style.height=parseFloat(document.documentElement.offsetHeight)+'px'
		$('doc3').style.width=parseFloat(document.documentElement.offsetWidth-20)+'px'
		msMap.Resize($('map_container').offsetWidth,mheight);
	}
}
function updateDisplay(){
	if(bMap.results[bMap.mapinfo.resultSet]){
		//Clear Display
		if($(bMap.mapinfo.resultSet+'_results')){
			$(bMap.mapinfo.resultSet+'_results').remove();
		}
		if(bMap.pins[bMap.mapinfo.resultSet]){
			msMap.DeleteShapeLayer(bMap.pins[bMap.mapinfo.resultSet]);
			bMap.pins[bMap.mapinfo.resultSet]='';
		}
		
		//Write results
		displayContent($('content'),bMap.results[bMap.mapinfo.resultSet],bMap.mapinfo.resultSet);
		
		//Show Side Bar
		showSideBar();
		
		//Display map only if the map type is controlled by client and not MSVE
		if(bMap.mapinfo.resultSet=='local'){
			//drawMap();
		}
		clientResize();
		
		//Add pin Layer
		addPins(bMap.mapinfo.resultSet);
		
		//Set Best Map View
		if(bMap.pins[bMap.mapinfo.resultSet]) {//is there a pin layer to zoom too
			msMap.Clear();
			//Set map to best view for current result set page
			msMap.SetMapView(bMap.pins[bMap.mapinfo.resultSet].GetBoundingRectangle());
			msMap.SetMapStyle(bMap.mapinfo.mode);
			
			//Capture new zoom level and style in bMap object
			bMap.mapinfo.zoom = msMap.GetZoomLevel();
			bMap.mapinfo.mode = msMap.GetMapStyle();
		}else{//zoom to default level in bMap object
			msMap.Clear();
			msMap.SetCenterAndZoom(new VELatLong(bMap.mapinfo.location.lat, bMap.mapinfo.location.lon), bMap.mapinfo.zoom);
			msMap.SetMapStyle(bMap.mapinfo.mode);
		}
		
		//remove loading
		$('loading').hide()
	}else{
		if(bMap.pins[bMap.mapinfo.resultSet] && bMap.pins[bMap.mapinfo.resultSet].GetShapeCount() > 0){//if pin layer remove it
			bMap.pins[bMap.mapinfo.resultSet].DeleteAllShapes();
		}
		//remove loading
		$('loading').hide()
		
		msMap.Clear();
		msMap.SetCenterAndZoom(new VELatLong(bMap.mapinfo.location.lat, bMap.mapinfo.location.lon), bMap.mapinfo.zoom);
		msMap.SetMapStyle(bMap.mapinfo.mode);
		
		//Remove the side bar if no results
		hideSideBar();
		clientResize();
	}
}
function displayContent(div,array,contentId){

	if(div && array){
		if(bMap.mapinfo.resultSet=='local'){
			div.innerHTML='';
			//Create a container for results
			var resContainer = div.appendChild(Builder.node('div', {id: contentId+'_results'}));
			resContainer.className='result_div';
			//Create Sponsored Results
			if(bMap.results.sponsoredResults && bMap.results.sponsoredResults.length > 0){
				var sponsTitle = resContainer.appendChild(Builder.node('h4'));
				sponsTitle.innerHTML='Sponsored Results';
				var sponsGroup = resContainer.appendChild(Builder.node('ol', {id: 'sponsored_list'}));
				sponsGroup.className='sponsored_group';
				$(bMap.results.sponsoredResults).each(function(s){
					var sponsGroupli = sponsGroup.appendChild(Builder.node('li'));
					var sponsItem = sponsGroupli.appendChild(Builder.node('ul', {id: contentId + '_' + i['id']}));
						sponsItem.className='sponsored_item';
					var sponsItem1 = sponsItem.appendChild(Builder.node('li'));
						sponsItem1.className='result_item_name';
						sponsItem1.innerHTML='<a target="_new" href="'+s['url']+'">'+s['name']+'</a>';
					var sponsItem2 = sponsItem.appendChild(Builder.node('li'));
						sponsItem2.className='result_item_text';
						sponsItem2.innerHTML=s['text'];
					var sponsItem3 = sponsItem.appendChild(Builder.node('li'));
						sponsItem3.innerHTML='<a target="_new" href="'+s['url']+'">'+s['url_friendly']+'</a>';
						sponsItem3.className='result_item_url';
				});
			}
			
			//Create Local Results
			var resTitle = resContainer.appendChild(Builder.node('h3'));
			resTitle.innerHTML='Local Results';
			var resGroup = resContainer.appendChild(Builder.node('ol', {id: contentId+'_list'}));
			resGroup.className='result_group';
			array.each(function(i){
				if(i['id'] < parseFloat(bMap.mapinfo.resultNum)){
					var resGroupli = resGroup.appendChild(Builder.node('li'));
					Event.observe(resGroupli,'click',function(){
						closePins();
						openPin(i['id']);
						});
					var resItem = resGroupli.appendChild(Builder.node('ul', {id: contentId + '_' + i['id']}));
					resItem.className='result_item';
					var respushpin = resItem.appendChild(Builder.node('div'));
						respushpin.className='pushpin';
						respushpin.innerHTML=parseFloat(document.forms[bMap.mapinfo.resultSet+'_search'].elements['start'].value)+parseFloat(i['id'])+1;
					var resItem1 = resItem.appendChild(Builder.node('li'));
						resItem1.className='result_item_name link';
						resItem1.innerHTML=i['name'];
					var resItem2 = resItem.appendChild(Builder.node('li'));
						resItem2.innerHTML=i['near'];
						resItem2.className='result_item_near';
					var resItem3 = resItem.appendChild(Builder.node('li'));
						resItem3.innerHTML=i['phone'];
						resItem3.className='result_item_phone';
					var resItem4 = resItem.appendChild(Builder.node('li'));
						resItem4.innerHTML='Web Search: <a href="http://search.feather.com/search?q='+escape(i['name'])+'" target="googleSearchFromMBS">'+i['name']+'</a>';
						resItem4.className='result_item_webSearch';
					var resItemNav = resGroupli.appendChild(Builder.node('div'));
						resItemNav.className='result_item_nav';
						var resItemNav_direct = resItemNav.appendChild(Builder.node('div'));
							resItemNav_direct.innerHTML='<span class="link" onclick="document.forms[\'search_tabs\'].elements[\'tab\'][2].checked=true;toggleForm(\'search\',false);document.direction_search.near[0].value=\''+i['near']+'\'">Drive from...</span> or <span class="link" onclick="document.forms[\'search_tabs\'].elements[\'tab\'][2].checked=true;toggleForm(\'search\',false);document.direction_search.near[1].value=\''+i['near']+'\'">Drive to...</span>';
						var resItemNav_zoom = resItemNav.appendChild(Builder.node('div'));
							resItemNav_zoom.innerHTML='Zoom to: <span class="link" onclick="mapZoom(' + i['lat'] + ',' + i['lon']+',15);">street</span> or <span class="link" onclick="mapZoom(' + i['lat'] + ',' + i['lon']+',12);">city</span> or <span class="link" onclick="mapZoom(' + i['lat'] + ',' + i['lon']+',10);">region</span>';
				}
			});
			//Create Pagination
			var resPagination = resContainer.appendChild(Builder.node('div', {className: 'result_pagination'}));
			
			if(parseFloat(document.forms[bMap.mapinfo.resultSet+'_search'].elements['start'].value) > 0 || parseFloat(bMap.results[bMap.mapinfo.resultSet].length) > parseFloat(bMap.mapinfo.resultNum)){	
				var paginatTitle = resPagination.appendChild(Builder.node('span'));
				paginatTitle.className="paginateTitle"
				paginatTitle.innerHTML='Results Page';
			}
			
			if(parseFloat(document.forms[bMap.mapinfo.resultSet+'_search'].elements['start'].value) > 0){
				var resLast = resPagination.appendChild(Builder.node('a', {href: '#', onclick: 'javascript:document.'+bMap.mapinfo.resultSet+'_search.start.value=parseFloat(document.'+bMap.mapinfo.resultSet+'_search.start.value)-parseFloat(bMap.mapinfo.resultNum);document.'+bMap.mapinfo.resultSet+'_search.submit();'}));
				resLast.innerHTML='< previous';
			}
			
			if(parseFloat(bMap.results[bMap.mapinfo.resultSet].length) > parseFloat(bMap.mapinfo.resultNum)){
				var resNext = resPagination.appendChild(Builder.node('a', {href: '#', onclick: 'javascript:document.'+bMap.mapinfo.resultSet+'_search.start.value=parseFloat(document.'+bMap.mapinfo.resultSet+'_search.start.value)+parseFloat(bMap.mapinfo.resultNum);document.'+bMap.mapinfo.resultSet+'_search.submit();'}));
				resNext.innerHTML='next >';
			}
		}
		if(bMap.mapinfo.resultSet=='direction'){
			div.innerHTML='';
			//Create a container for results
			var resContainer = div.appendChild(Builder.node('div', {id: contentId+'_results'}));
			resContainer.className='result_div';
		
			//Create Direction Summary
			var sumTitle = resContainer.appendChild(Builder.node('h3'));
			sumTitle.innerHTML='Route Summary';
			
			var sumlist = resContainer.appendChild(Builder.node('ul'));
			sumTitle.id='route_summary';
			
			var sumStart = sumlist.appendChild(Builder.node('li'));
			sumStart.innerHTML='<div class="green">Start: </div>'+bMap.results.direction.Start.near;
			
			var sumEnd = sumlist.appendChild(Builder.node('li'));
			sumEnd.innerHTML='<div class="red">End: </div>'+bMap.results.direction.End.near;
			
			var sumDist = sumlist.appendChild(Builder.node('li'));
			sumDist.innerHTML='<div class="subdue">Total Distance: </div>'+bMap.results.direction.distance+' mi';
			
			var sumTime = sumlist.appendChild(Builder.node('li'));
			sumTime.innerHTML='<div class="subdue">Estimated Time: </div>'+bMap.results.direction.Time;
			
			//Create Direction Results
			var resTitle = resContainer.appendChild(Builder.node('h3'));
			resTitle.innerHTML='Driving Directions';
			
			var resGroup = resContainer.appendChild(Builder.node('ol', {id: contentId+'_list'}));
			resGroup.className='result_group';
			
			var resStyle='on';
			bMap.results.direction.Itinerary.each(function(i){
				var resitem = resGroup.appendChild(Builder.node('li'));
				resitem.innerHTML=i.Instruction;
				resitem.className='result_item '+resStyle;
				if(resStyle == 'on'){
					resStyle = 'off';
				}else{
					resStyle = 'on';
				}
			})
			 
		}
	
	}
	
}
function hideSideBar(){
	$('content_container').style.display='none';
	$('yui-main').getElementsByClassName('yui-b')[0].style.marginLeft='0';
	
	if(isIE6){//if ie6 reset size of map
		msMap.Resize(985,464);
	}
}
function showSideBar(){
	$('content_container').style.display='block';
	$('yui-main').getElementsByClassName('yui-b')[0].style.marginLeft='300px';
	
	if(isIE6){//if ie6 reset size of map
		msMap.Resize(682,464);
	}
}

//Search
function moreSearch(searchurl){
	var s_string;
	if(document.forms[bMap.mapinfo.resultSet + '_search'].elements['q'] && document.forms[bMap.mapinfo.resultSet + '_search'].elements['q'] != ''){
		s_string = document.forms[bMap.mapinfo.resultSet + '_search'].elements['q'].value;
	}else{
		s_string = 'EarthLink';	
	}
	window.location = searchurl + s_string;
}
function searchError(element,message){
	if($('search_error')){
		$('search_error').remove();
	}
	var errorBox=$('search').appendChild(Builder.node('div'));
	errorBox.id='search_error';
	if(isIE6){
		errorBox.style.top=parseInt(Position.cumulativeOffset(element)[1]-20)+'px'
	}else{
		errorBox.style.top=parseInt(Position.cumulativeOffset(element)[1]+element.getHeight())+'px'
	}
	if(isIE){
		if(isIE6){
			errorBox.style.left=parseInt(Position.cumulativeOffset(element)[0]-25)+'px'
		}else{
			errorBox.style.left=parseInt(Position.cumulativeOffset(element)[0]-14)+'px'
		}
	}else{
		errorBox.style.left=Position.cumulativeOffset(element)[0]+'px'
	}
	errorBox.innerHTML=message;
	setTimeout("$('search_error').remove();",3000);
}
function disambig(form){
	$('loading').show();
	if(form.near_disambiguated){//is disambiguation field available - if yes then disambiguate
		var nearArray=new Array();
		if(form.near_disambiguated.length > 0){//Make sure near_disambiguate field is an array
			nearArray=form.near_disambiguated;

		}else{
			nearArray[0]=form.near_disambiguated;
		}
		var increment = 0;//current loop increment
		var d_empty = 0;//Will be number of empty disambiguated fields
		$A(nearArray).each(function(e){
			if(e.value == "" && d_empty < 1){//If disambiguated field is empty, have disambig provider return list. Stop after first empty field is found.
				if(form.near[increment]){//deal with near if not an array
					var n=form.near[increment];
				}else{
					var n=form.near;
				}
				if(n.value=='' || n.value==n.alt){
					searchError(n,'Please enter a location and click the "Search" button.');
				}else{
					msMap.Find(null,n.value,null,null,null,null,false,false,false,false,msCalbackDlist);
					d_empty++
				}
			}
			increment++
		})
		if(d_empty < 1){//if no empty fields submit form
			try{
				search();
			}catch(err){
				var error=err;
			}
		}
	}
}
function search(){
	if(bMap.mapinfo.resultSet=='local'){
		localSearch();
	}
	if(bMap.mapinfo.resultSet=='direction'){
		directionSearch();
	}
}
function localSearch(){
	form = document.local_search;
	$('loading').show()
	msMap.Find(form.q.value,form.near_disambiguated.value, null, null, parseFloat(document.forms[bMap.mapinfo.resultSet+'_search'].elements['start'].value), parseFloat(bMap.mapinfo.resultNum)+1, false, false, false, false, msCallackLocal);
	form.near_disambiguated.value='';
}
function directionSearch(){
	form = document.direction_search;
	if(sprintBlock(isSafari || isCamino)){ //ToDo: Remove before Beta Launch
		msMap.GetRoute(form.near_disambiguated[0].value,form.near_disambiguated[1].value,null,null,msCalbackDirection);
		//clear disambiguated fields
		form.near_disambiguated[0].value='';
		form.near_disambiguated[1].value='';
	}
}
function toggleForm(div,noObserve){
	$('loading').show();
	div = $(div);
	var sf_forms = div.getElementsByTagName("form");
	var sf_tabs = sf_forms[0].getElementsByTagName('input');
	$A(sf_tabs).each(function(t){
		if(!noObserve){
			Event.observe(t,"click",function(){toggleForm(div,true)});
		}
		if(t.checked){
			sf_forms[t.value].style.display='block';
			t.parentNode.className='active';
			bMap.mapinfo.resultSet=t.value.split('_')[0];
			updateDisplay();
		}else{
			sf_forms[t.value].style.display='none';
			t.parentNode.className='inactive';
		}
	})
}
function neatField(field){
	if(field.value==field.alt){
		field.value='';
	}
}
function getBack(name,url,form_data){ //Gets data from backend
	if($(bMap.mapinfo.resultSet+"_results")){
		$(bMap.mapinfo.resultSet+"_results").remove();
	}
	var backData = new Ajax.Request(
		url, 
		{
			method: 'post', 
            parameters: Form.serialize(form_data),
            onComplete: function(transport){
				if(transport.status > 399){//No JSON recieved. Just update display
					updateDisplay();
				}else{
					try{
						cache.put(name,[Form.serialize(form_data),eval('(' + transport.responseText + ')')]);
						processBack(cache.get(name).element[1]);
					}catch(err){//Problom in JSON response. Just update display
						updateDisplay();
					}
				}
        	}
    	}
	);
}
function processBack(obj){
	//mergeObjects(bMap.mapinfo,obj.mapinfo); todo:remove for production
	mergeObjects(bMap.user,obj.user);
	mergeObjects(bMap.results,obj.results);
	updateDisplay();
}
function msCalbackDlist(a,b,c,d){
	if(c){//did msve return anything?
		var where = $$('#search form[name="'+bMap.mapinfo.resultSet+'_search"] div input[name="near_disambiguated"]');
		var increment = 0;//current loop increment
		var d_empty = 0;//Will be number of empty disambiguated fields
		where.each(function(field){
			if(field.value=='' && d_empty < 1){
				if(c.length > 1){//if there is a list create a DOM UI element
					var ulContainer = where[increment].parentNode.appendChild(Builder.node("ul",{ id: 'dlist'}) );
					c.each(function(item){
						if(document.forms[bMap.mapinfo.resultSet+'_search'].near_disambiguated[increment]){
							var res = ulContainer.appendChild(Builder.node("li", { onclick:'var dlistForm=document.forms[\''+bMap.mapinfo.resultSet+'_search\'];dlistForm.near_disambiguated['+increment+'].value=\''+item.Name+'\';dlistForm.near['+increment+'].value=\''+item.Name+'\';$(\'dlist\').remove();dlistForm.submit();'}));
						}else{
							var res = ulContainer.appendChild(Builder.node("li", { onclick:'var dlistForm=document.forms[\''+bMap.mapinfo.resultSet+'_search\'];dlistForm.near_disambiguated.value=\''+item.Name+'\';dlistForm.near.value=\''+item.Name+'\';$(\'dlist\').remove();dlistForm.submit();'}));
						}
						res.className='link';
						res.innerHTML = item.Name;
					});
				}else{//near value is good, populate disambig with near value - no disambig
					var dlistForm=document.forms[bMap.mapinfo.resultSet+'_search'];
					if(dlistForm.near_disambiguated[increment]){
						var nd=dlistForm.near_disambiguated[increment];
						var n=dlistForm.near[increment];
					}else{
						var nd=dlistForm.near_disambiguated;
						var n=dlistForm.near;
					}
					nd.value=n.value;
					dlistForm.submit();
				}
				d_empty++ //Already filled out the field, lets stop
			}
			increment++
		})
	}else{
		//Send error becouse no usable address
		searchError(document.local_search.near,'There were no matches found');
	}
	
}
function msCalbackDirection(route){
	if(route && bMap.results){
		//Write root level object
		bMap.results['direction'] = new Object();
		bMap.results['direction'].distance=route.Itinerary.Distance;
		bMap.results['direction'].Time=route.Itinerary.Time;
		
		//Write Start location object
		bMap.results['direction'].Start= new Object();
		bMap.results['direction'].Start.near=route.StartLocation.Address;
		bMap.results['direction'].Start.lat=route.StartLocation.LatLong.Latitude;
		bMap.results['direction'].Start.lon=route.StartLocation.LatLong.Longitude;
		
		//Write End location object
		bMap.results['direction'].End= new Object();
		bMap.results['direction'].End.near=route.EndLocation.Address;
		bMap.results['direction'].End.lat=route.EndLocation.LatLong.Latitude;
		bMap.results['direction'].End.lon=route.EndLocation.LatLong.Longitude;
		
		//Write Itinerary
		bMap.results['direction'].Itinerary= new Array();
		if(route.Itinerary.Segments && route.Itinerary.Segments.length > 0){
			for(var s=0;s<route.Itinerary.Segments.length;s++){
				bMap.results['direction'].Itinerary[s]=new Object();
				bMap.results['direction'].Itinerary[s].Distance=route.Itinerary.Segments[s].Distance;
				bMap.results['direction'].Itinerary[s].Instruction=route.Itinerary.Segments[s].Instruction;
				bMap.results['direction'].Itinerary[s].lat=route.Itinerary.Segments[s].LatLong.Latitude;
				bMap.results['direction'].Itinerary[s].lon=route.Itinerary.Segments[s].LatLong.Longitude;
			}
		}
		
		$('loading').hide();
		//Write results
		displayContent($('content'),bMap.results[bMap.mapinfo.resultSet],bMap.mapinfo.resultSet);
		showSideBar();
	}
}
function msCallackLocal(a,b,c,d,e){
	if(b){
		bMap.results.local = new Array();
		i=0;
		$A(b).each(function(r){
			if(!r.IsSponsored){
				bMap.results.local[i] = new Object();
				bMap.results.local[i]['id']=i;
				bMap.results.local[i]['name']=r.Name;
				bMap.results.local[i]['near']=r.Description;
				bMap.results.local[i]['lat']=r.LatLong['Latitude'];
				bMap.results.local[i]['lon']=r.LatLong['Longitude'];
				bMap.results.local[i]['phone']=r.Phone;
			}
			i++;
		});
	}else{//Display message if no results
		if(document.forms['local_search'].elements['q'].value != '' && document.forms['local_search'].elements['q'].value != document.forms['local_search'].elements['q'].alt){
			searchError(document.local_search.q,'Your search found 0 results');
		}else{//Remove previous result set
			if(bMap.results.local){
				bMap.results.local='';
			}
		}
	}
	if(c){
		bMap.mapinfo['location'].near = document.forms['local_search'].elements['near'].value;
		bMap.mapinfo['location'].lat = c[0].LatLong.Latitude;
		bMap.mapinfo['location'].lon = c[0].LatLong.Longitude;
		bMap.mapinfo.zoom = 12;
		bMap.mapinfo.mode = msMap.GetMapStyle();
	}
	
	if(!$('dlist')){
		getBack('backend','index.json',document.forms[bMap.mapinfo.resultSet+'_search']);
	}
}
function dList_update(val){
	$('dlist').remove();
	document.forms[bMap.mapinfo.resultSet+'_search'].near.value=val;
	document.forms[bMap.mapinfo.resultSet+'_search'].submit();
}

//Onload
Event.observe(window,'load',function(){
	initMap('bigmap');
	toggleForm('search');
	clientResize();

	Event.observe(window,'resize',function(){
		clientResize();
		if(bMap.pins[bMap.mapinfo.resultSet]){
			msMap.SetMapView(bMap.pins[bMap.mapinfo.resultSet].GetBoundingRectangle());	
		}
	})
})
