//<![CDATA[                    

//jQuery.noConflict();

var t;
var map = null;
var geocoder = null;
var highlightIndex = 0;
var scrlPos;
var flagPushPin = null;
var orgSetCenterMsg = "";
var hShape; //Declare the Active/Hover Marker variables
var gShapes = [];	// array of the markers
var flagShapeIcon = "<div id='flagPing' style='position:absolute;top:-20px;left:10px;'><img src='http://imfimg.com/static/0/img/mapicon/icon_flag.png' /></div>";

var searchCriteria = {
	impId: "0",
	sicCode: "", 
	stype: "", 
	name: "", 
	locName: "",
	start: 0, 
	lang: "",
	eventFired:0,
	centerLat:0,
	centerLng:0
};

var iMap = {
	isDEBUG: false,
	markers: [],
	isRefreshMapOn: true,
	isZoomIgnored: false,
	isInitZoomChanged: false,
	isSetCenterClicked: false,
	
	log: function(msg) {
	},
	
	// get first marker to locate Jack as map is switched to street scene
	getInitMarkerForJack: function() {
		var ll, mk, lat, lng;
		var view = MapLIB.getMapInstance().GetMapView();

		return this.markers[0].marker;
		/*
		for(var i = 0; i < this.markers.length; i++) {
			if(this.markers[i].marker) {
				ll = this.markers[i].marker.GetPoints();
				mk = this.markers[i].marker;
				lat = ll[0].Latitude;
				lng = ll[0].Longitude;

				if(lat > view.BottomRightLatLong.Latitude && lat < view.TopLeftLatLong.Latitude &&
				   lng > view.TopLeftLatLong.Longitude || lng < view.BottomRightLatLong.Longitude) {
					break;
				}
			}
		}

		return mk;
		*/
	},

	clearMarkers: function(flagShape_) {
		var flagShape = flagShape||false;
		
		for(var i = 0; i < iMap.markers.length; i++) {
			map.DeleteShape(iMap.markers[i].marker);
		}

		iMap.markers.length = 0;
		
		if(flagShape)
			map.DeleteShape(flagPushPin);
	},

	getMarkerOf: function(idx) {
		for(var i = 0; i < iMap.markers.length; i++) {
			if(iMap.markers[i].index == idx)
				return iMap.markers[i].marker;
		}
		return null;
	},

	// it uses undcoumented API such as Decode of _xy1 object
	getBirdsEyeRect : function () {
		try {
		    var rect;
			var tl = (new _xy1).Decode(map.GetMapView().TopLeftLatLong);
			var br = (new _xy1).Decode(map.GetMapView().BottomRightLatLong);
			
		    var be = map.GetBirdseyeScene();//need to flip some lat long if the scene has been rotated
		    switch(be.GetOrientation()){
		        case VEOrientation.North:
		            rect = new VELatLongRectangle(tl,br,null,null);
		            break;
		        case VEOrientation.East:
		            //flip long
		            rect = new VELatLongRectangle(new VELatLong(tl.Latitude,br.Longitude),new VELatLong(br.Latitude,tl.Longitude),null,null);
		            break;
		        case VEOrientation.South:
		            //flip lat and long
		            rect = new VELatLongRectangle(br,tl,null,null);
		            break;
		        case VEOrientation.West:
		            //flip lat
		            rect = new VELatLongRectangle(new VELatLong(br.Latitude,tl.Longitude),new VELatLong(tl.Latitude,br.Longitude),null,null);
		            break;                                    
		    }
		    return rect;
		}
		catch (e) {
			//alert(e.message);
		};
	},	
	
	doIMapQuery: function(start) {
		var $ = jQuery;
		var view;
		
		MapLIB.blockMap();
		
		if(map.GetMapStyle() == VEMapStyle.BirdseyeHybrid || map.GetMapStyle() == VEMapStyle.Birdseye)
			view = this.getBirdsEyeRect();
		else
			view = map.GetMapView();
		
		var neLat = view.TopLeftLatLong.Latitude;
		var neLng = view.BottomRightLatLong.Longitude;
		var swLat = view.BottomRightLatLong.Latitude;
		var swLng = view.TopLeftLatLong.Longitude;

		var latDelta = (neLat - swLat) * 0.01;
		var lngDelta = (neLng - swLng) * 0.01;

		// make proper boundaries
		neLat = neLat - latDelta;
		neLng = neLng - lngDelta*0.4;
		swLat = swLat - latDelta;
		swLng = swLng - lngDelta*2;

		this.clearMarkers();
		unhighlightBox(); // for new map search

		var url;
		var urlData;
		var lang;
		var that = this;

		lang = $("#iMap_lang").html();
		
		if (searchCriteria.eventFired == 0) {  //Without any event - initial listings
			var radius = document.form2.radius.value;
			
			url = '/ms/search.jsp';
			urlData = 'radius=' + radius
				+ '&lang=' + searchCriteria.lang
				+ '&stype=' + searchCriteria.stype
				+ '&start=' + start
				+ '&lat=' + searchCriteria.centerLat
				+ '&lng=' + searchCriteria.centerLng
				+ '&sic=' + searchCriteria.sicCode 
				+ '&name=' + searchCriteria.name
				+ '&locName=' + searchCriteria.locName;
		} 
		else {
			url = '/search_area_i.jsp';
			urlData = '&imp=' + searchCriteria.impId
				+ '&lang=' + searchCriteria.lang
				+ '&nt=' + searchCriteria.stype
				+ '&str=' + start 
				+ '&ar=' + swLat + ',' + swLng + ',' + neLat + ',' + neLng 
				+ '&hid=' + searchCriteria.sicCode
				+ '&na=' + searchCriteria.name
				+ '&locName=' + searchCriteria.locName
				+ '&vm=';				
		}
		
		$.ajax({
			   type: "GET",
			   url: url,
			   data: urlData+'&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
					working = 0;
					
					var resText ;
					var navText ;
					var catText ;
					var listingInfo ;
					var stype ;
					var impId;

					$(xml).find('header').each(function() {
						resText = $(this).attr("resText");
						navText = $(this).attr("navText");
						catText = $(this).attr("catText");
						listingInfo = $(this).attr("listingInfo");
						stype = $(this).attr("stype");
						impId = $(this).attr("impId");

						/*
						if(mjStreetView.isStreetView) {
							// reset pois
							mjStreetView.pois = [];
							mjStreetView.pois = eval($(this).attr("pois"));
							//canSetPOIs();
						}
						*/
					});

					if(catText != "NO_DATA_FOUND") {
						searchCriteria.impId = impId;
						setStype(stype);							

						if (resText == "") 
							hideResult();
						else
							showResult(resText);

						if (navText == "") 
							hideNav();
						else
							showNav(navText);

						if (catText == "") 
							hideCategory();
						else
							showCategory(catText);	

						var mkCnt = 0;
						
						$(xml).find('marker').each(function() {
							// obtain the attribues of each marker
							var index = $(this).attr("index");
							var lat = parseFloat($(this).attr("lat"));
							var lng = parseFloat($(this).attr("lng"));
							var point = new VELatLong(lat,lng);
							var html = $(this).attr("html");
							var label = $(this).attr("label");
							var viewPoint = $(this).attr("viewpoint");
							
							createMarker(point,index,html,viewPoint);
							mkCnt++;
						});
	
						if (mkCnt > 0) {
							showListing(listingInfo);
						}
						else {
							hideListing();
							if (searchCriteria.eventFired==1) 
								setNoDataMsg();
							else {
								if(catText == "") 
									setNoDataMsg();  //If there are not both sub-category and data
							}
						}
						if(!mjStreetView.isStreetView) {
							Webcam.getWebcamMarkers();
						}
					}
					else
						setNoDataMsg();
					
					showResult(searchCriteria.name);
					// don't call SetMapView in the case of calling by event 
					if(searchCriteria.eventFired == 0 && mkCnt != 0) {
					  var allPins = [];
					  for(var i = 0; i < iMap.markers.length; i++)
						  allPins.push(iMap.markers[i].marker);
					  
					  iMap.isZoomIgnored = true;
					  map.SetMapView(allPins);
					}

					MapLIB.unblockMap();
			   },
			   error: function(xhr, textStatus, errorThrown) {
				  //alert("Error : " + xhr + ":" + textStatus + ":" + errorThrown);
				  MapLIB.unblockMap();
			   }
			 });
	},

	// refere to NavigationGroup.java file.
	deSelectedVM: function(vmUrl) {
		(function($){
			var vmVal = "";

			if(vmUrl.indexOf("vm=") >= 0)
				vmVal = vmUrl.substring(vmUrl.indexOf("vm=")+3);

			$("#iMap_vm").html(vmVal);
		})(jQuery);
		this.doIMapQuery(1);
	}
};

function getMap(address, country, defaultCity) {
	MapLIB.removeInfoBox();

	if(address == '') {
		findLocation(searchCriteria.lang, defaultCity);
	} 
	else {
		if (country=="CL" || country=="PR") { //Chile or Puerto Rico
			if (address.indexOf("CL")==-1 || address.indexOf("PR")==-1) {
				var temp = address.split(",");
				address = temp[0] + ", " + country;				
			}
		}			
		map.Find(null,address,null,null,0,5,false,false,false,true,
			function(layer, resultsArray, places, hasMore, veErrorMessage){
				if(places == null || places.length == 0) {
					hideSearch();
					hideResult();
					hideNav();
					hideCategory();
					hideListing();
					
					searchCriteria.sicCode = "";
					searchCriteria.name = "";					

					if(flagPushPin != null)
						map.DeleteShape(flagPushPin);

					iMap.clearMarkers();

					var msg = "<b>We were not able to find this location.<br/>Please try again.</b><br/><br/>";
					if (searchCriteria.lang=="1")
						msg = "<b>No pudimos encontrar esta localizaci�n.<br/>Por favor intente de nuevo.</b><br/><br/>";

					showMessage(msg);			
					findLocation(searchCriteria.lang, defaultCity);
					//alert('a');
				}
				else {
					// as map is loaded, the zoom level may be changed so the event should be detached and later attached
					map.DetachEvent("onendzoom", zoomEndHandler);

					showSearch();
					hideMessage();
					hideResult();
					hideNav();
					hideCategory();
					hideListing();
					searchCriteria.locName = address;
					searchCriteria.sicCode = "";
					searchCriteria.name = "";

					if(flagPushPin != null)
						map.DeleteShape(flagPushPin);

					iMap.clearMarkers();					
					
					flagPushPin = MapLIB.addPushpin({pinHTML: flagShapeIcon,
										pinIMG: "http://imfimg.com/static/0/img/mapicon/icon_flag.png",
										lat:places[0].LatLong.Latitude,
										lng:places[0].LatLong.Longitude,
										id:"FLAG"});
					
					map.SetCenterAndZoom(places[0].LatLong, 13);
					searchCriteria.centerLat = places[0].LatLong.Latitude;
					searchCriteria.centerLng = places[0].LatLong.Longitude;
					map.AttachEvent("onendzoom", zoomEndHandler);
					Webcam.get(map, searchCriteria.lang, 'F');
					//alert('b');
				}
		});		
	}	
}

function loadMap(spanishFlag, impId, impCountry, defaultCity, homePageStyle) { //frenchFlag, isReverseLookup) {	
	jQuery(document).ready(function($) {
		map = MapLIB.init({
			// loading map and set initial options
			mapId:"map", 
			centerLat:35, 	// default	
			centerLng:-95,	// default
			zoom:14,
			mapLeftOffset:320,
			lang:spanishFlag == 'T'? '1' : '0',
			resizeCallback:resizeMap,
			distanceUnit: __scaleType,
			impId:impId
		});
		
		searchCriteria.lang = spanishFlag == 'T'? '1' : '0';

		//var ext = (jQuery.browser.version=='6.0' && jQuery.browser.msie) ? ".gif" : ".png";		
		var address = "";
		if (homePageStyle=="1") address = $.trim($('#cityMS').val());
		else address = $.trim($('#city_ms').val());
		
		// get lat and long based on address and set the icon of flag to center of the map 
		getMap(address, impCountry, defaultCity);
		
		// initializing street scene object
		mjStreetView.init({
			spanishFlag:spanishFlag, 
			pageType: 'MS',
			 //serverName:__serverName,	// defined in mapListing.jsp
			 mapInstance:map});

		map.AttachEvent("onendpan", endPanHandler);
		map.AttachEvent("onclick", mouseClickHandler);
		map.AttachEvent("onmouseover", mouseOverHandler);
		map.AttachEvent("onmouseout", mouseOutHandler);
		map.AttachEvent("onmousedown", mouseDownHandler);
		map.AttachEvent("onmouseup", mouseUpHandler);
	    map.AttachEvent('onmousemove', mouseMoveHandler);

	    // IE has a bug with doubleclick which causes mousemove fired
		if($.browser.msie)
			map.AttachEvent("ondoubleclick", doubleClickHandler);

	    map.AttachEvent('oninitmode', function() {
	    	if(map.GetMapMode() == VEMapMode.Mode3D) {
	    		// In order to show custom button in 3D mode, it should be wrapped with IFRAME
	    		// It can be created in 2D mode and wrapped in 3D mode but it doesn't work.
	    		// It should be created newly in 3D mode and wrapped with IFRAME.
	    		// That is why it has different id of DIV like 'btnMoveRefresh_3D'
				$('<div id="btnMoveRefresh_3D" class="customBtn">' +
						'<div style="position:relative;top:7px;left:5px;font-weight:bold;"></div>' +
						'<img src="/images/nav_select.gif" style="position:relative;top:9px;left:40px;display:block;" /></div>')
				 .setCustomButton({
					 	containerID: "body",
				 		name: MapLIB.getMessage("moveRefresh"),
				 		style: {top: $("#"+MapLIB.defaults.mapId).offset().top+1, left:"636px", width:(spanishFlag == '1' ? "120px" : "90px")},
				 		clickFn: MapLIB.Button.moveRefresh
				 });	    		

	    		MapLIB.addShim($("#btnMoveRefresh_3D").get(0));
	    	}
	    	else if(map.GetMapMode() == VEMapMode.Mode2D) {
	    		var shim = document.getElementById("shim_btnMoveRefresh_3D");
	            if(shim != null) {
	            	$("#btnMoveRefresh_3D").remove();
	            	shim.parentNode.removeChild(shim);
	            }
	    	}
	    });
	    
		// in order to detect blue dots in the current map, bring the tiles but make the opacity 0.
		// the detection logic is defined in the function isThereBlueDots in bingmaplib.js
		//mjStreetView.showTile(0);

		var streetLeftOffset = spanishFlag == 'T' ? "5px" : "10px";
		
		$('<div id="btnMoveRefresh" class="customBtn">' +
				'<div style="position:relative;top:7px;left:5px;font-weight:bold;"></div>' +
				'<img src="/images/nav_select.gif" style="position:relative;top:9px;left:40px;display:block;" /></div>')
		 .setCustomButton({
		 		name: MapLIB.getMessage("moveRefresh"),
		 		style: {left:"260px", width:(spanishFlag == 'T' ? "120px" : "90px")},
		 		clickFn: MapLIB.Button.moveRefresh
		 });

		/*
		$('<div id="btnStreetScene" class="customBtn" style="display:none">' +
				'<div style="position:relative;top:7px;left:'+streetLeftOffset+';font-weight:bold;"></div>'+
				'<img src="/images/nav_select.gif" style="position:relative;top:9px;left:40px;display:none;" /></div>')
		 .setCustomButton({
		 		name: MapLIB.getMessage("streetScene"),
		 		style: {left:(spanishFlag == '1' ? "380px":"350px"), width:"80px"},
		 		clickFn: MapLIB.Button.streetScene
		 });
		 */

		//Webcam.get(map, spanishFlag, 'F');

		showSearch();
		hideMessage();
		hideResult();
		hideNav();
		hideCategory();
		hideListing();
		
	});
}

function findLocation(spanishFlag, address) {
	if (address=='null' || address=='' || address==null) address = 'Washington,DC';  //if publisher's default city is not defined in IMP_SETTING DB table, default city is Washington, DC.
	map.Find(null,address,null,null,0,5,false,false,false,true,
			function(layer, resultsArray, places, hasMore, veErrorMessage){
				if(places == null || places.length == 0) {
					return;	// nothing
				}
				else {
					flagPushPin = MapLIB.addPushpin({pinHTML: flagShapeIcon,
										pinIMG: "http://imfimg.com/static/0/img/mapicon/icon_flag.png",
										lat:places[0].LatLong.Latitude,
										lng:places[0].LatLong.Longitude,
										id:"FLAG"});

					map.SetCenter(places[0].LatLong);
					searchCriteria.centerLat = places[0].LatLong.Latitude;
					searchCriteria.centerLng = places[0].LatLong.Longitude;
					// it should be here not outside of Find method because Find triggers zoom end event, 
					// which calls unnecessary doIMapQuery. David Lee Feb. 24, 2010
					map.AttachEvent("onendzoom", zoomEndHandler);
					Webcam.get(map, spanishFlag, 'F');
					searchCriteria.locName = address;
				}
	});	
}

function setCenter() {
	var mapNav = document.getElementById("mapNav");
	orgSetCenterMsg = mapNav.innerHTML;
	
	var msg = "Please click on the map for a new center.";
	if (searchCriteria.lang=="1") {
		msg = "Por favor haga click en el mapa para un nuevo centro.";
	}
	mapNavMessage(msg);

	iMap.isSetCenterClicked = true;
}

function setStype(stype) {
   var radioObj = document.form2.stype;
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == stype);
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == stype) {
			radioObj[i].checked = true;
		}
	}
}

function searchMap() {
	var stype = getRadioValue(document.form2.stype);
	var name = document.form2.name.value;
	var lang = document.form2.lang.value;

	if (jQuery.trim(name) == '') 
		return;

	if (stype == 'C')
		doCategoryNameSearch(name, lang);
	else
		doNameSearch(name, lang);
} 

function showSearch() {
	var mapSearch = document.getElementById("leftSearch");
	mapSearch.style.display = 'block';
}      

function hideSearch() {
	var mapSearch = document.getElementById("leftSearch");
	mapSearch.style.display = 'none';
} 

function showMessage(text) {
	var msg = document.getElementById("leftMessage");
	var msgTxt = document.getElementById("leftMessageText");
	msgTxt.innerHTML = text;
	msg.style.display = 'block';
}

function hideMessage() {
	var msg = document.getElementById("leftMessage");
	msg.style.display = 'none';
}

function mapNavMessage(text) {
	var msg = document.getElementById("mapNav");
	msg.innerHTML = text;
}

function showResult(text) {
	var res = document.getElementById("searchResult");
	res.style.display = 'block';

	var resTxt = document.getElementById("searchResultText");
	resTxt.innerHTML = text;
}

function hideResult() {
	var res = document.getElementById("searchResult");
	res.style.display = 'none';
}

function showNav(text) {
	var res = document.getElementById("searchNav");
	res.style.display = 'block';

	var resTxt = document.getElementById("searchNavText");
	resTxt.innerHTML = text;
	resultDisplayed = 'Y';
}

function hideNav() {
	var res = document.getElementById("searchNav");
	res.style.display = 'none';
	resultDisplayed = 'N';
}

function showCategory(text) {
	var res = document.getElementById("searchCategory");
	res.style.display = 'block';
	res.innerHTML = text;
}

function hideCategory() {
	var res = document.getElementById("searchCategory");
	res.style.display = 'none';
}

function showListing(text) {
	var cont = document.getElementById("listing_container");
	cont.style.display = 'block';

	var res = document.getElementById("leftListing");
	res.innerHTML = text;

	resizeListingContainer();
}

function hideListing() {
	document.getElementById("searchNav").style.display = 'none';
	document.getElementById("listing_container").style.display = 'none';
	resultDisplayed = 'N';
}

function doCategorySearch(sicCode, lang) {
	searchCriteria.sicCode = sicCode;
	searchCriteria.stype = "C";
	searchCriteria.name = "";
	searchCriteria.start = 1;
	searchCriteria.lang = lang;	
	searchCriteria.eventFired = 0;
	iMap.doIMapQuery(1);
}

function doCategoryNameSearch(catName, lang) {
	document.form2.name.value = '';
	searchCriteria.sicCode = "";
	searchCriteria.stype = "C";
	searchCriteria.name = catName;
	searchCriteria.start = 1;
	searchCriteria.lang = lang;	
	searchCriteria.eventFired = 0;
	iMap.doIMapQuery(1);
}

function doNameSearch(name, lang) {
	searchCriteria.sicCode = "";
	searchCriteria.stype = "N";
	searchCriteria.name = name;
	searchCriteria.start = 1;
	searchCriteria.lang = lang;
	searchCriteria.eventFired = 0;
	iMap.doIMapQuery(1);
}

function doQuery(sicCode, stype, name, start, lang) {
	isLoadingFinished = false; //This variable should be reset so that automatic zoomend event can NOT be called.
	searchCriteria.sicCode = sicCode;
	searchCriteria.stype = stype;
	searchCriteria.name = name;
	searchCriteria.start = start;
	searchCriteria.lang = lang;	
	searchCriteria.eventFired = 0;

	iMap.doIMapQuery(start);
}

var scTimer;
function onMapLoaded() {
	var cnt = 1;

	GoGetMap();
	scTimer = setInterval(function() {
		//alert('onMapLoad - ' + cnt++);
		if(cnt <= 3)
			MapLIB.streetSceneButton();
		else
			clearTimeout(scTimer);
	}, 500);
}

function centerMap(lat, lng, zoom) {
	map.SetCenterAndZoom(new VELatLong(lat, lng), zoom);
}

// addFlag_ : in order to add in a way of bulk
function createMarker(point, index, html, viewPoint, addFlag_){
	var addFlag = addFlag_||true;
	
	  var letter = MapLIB.getPinLetter(index);
	  var pinHTML = MapLIB.getPinHTML(letter, false);
	  var pinIMG = MapLIB.getPinIMG(letter, false);

	  var marker = MapLIB.addPushpin({
			lat: point.Latitude,
			lng: point.Longitude,
			beakOffsetX:12,
			beakOffsetY:32,			
			pinHTML: pinHTML,
	 		pinIMG: pinIMG,
	 		viewPoint: viewPoint,
	 		id: index,
	 		type:"PIN",
	 		addShapeFlag:addFlag,	// if you want to add shapes in bulk, make it false
	 		title: '',
	 		desc: html});
	  //gShapes[index] = marker;
	  iMap.markers[iMap.markers.length++] = {marker:marker, index:index};

	 return marker;
}

function addLoc(point, index, viewPoint) {
	var info = document.getElementById("bubblebox" + index).innerHTML;
	createMarker(point, index, info, viewPoint);
}

/* in the case of using Street Scene data */
function addLocWithViewPoint(point, index, viewPoint) {
	var info = document.getElementById("bubblebox" + index).innerHTML;
	createMarker(point, index, info, viewPoint);
}

// You can search for IKEA in Markham
function addPoiLoc(point) {
	  var label = document.getElementById("POI").innerHTML;

	  var pinHTML = "<div style='position:relative;top:-20px;left:10px;'><img src='http://imfimg.com/images/mapicon/icon_flag.png' /></div>";
	  var pinIMG = "http://imfimg.com/images/mapicon/icon_flag.png";

	  var marker = MapLIB.addPushpin({
			lat: point.Latitude,
			lng: point.Longitude,
			beakOffsetX:24,
			beakOffsetY:32,
			pinHTML: pinHTML,
	 		pinIMG: pinIMG,
	 		viewPoint: '',
	 		title: '',
	 		desc: label});
	  
	  var allPins = [];
	  for(var i = 0; i < iMap.markers.length; i++)
		  allPins.push(iMap.markers[i].marker);
	  
	  // add flag to array of pins
	  allPins.push(point);
	  
	  // At init time, SetMapView will change zoom level because the default zoom level is 4 in MapListingData.java
	  // SetMapView causes zoom changed, so even if zoom is changed, doIMapQuery shouldn't be executed.
	  // this value will be set to false by function zoomEndHandler in Map.js	  
	  iMap.isZoomIgnored = true;
	  // reset the zoom to contain all pins
	  map.SetMapView(allPins);
}

// it is called only in MapListingData.java
function setMapBounds() {
	try {

	  var allPins = [];
	  for(var i = 0; i < iMap.markers.length; i++)
		  allPins.push(iMap.markers[i].marker);

	  // At init time, SetMapView will change zoom level because the default zoom level is 4 in MapListingData.java
	  // SetMapView causes zoom changed, so even if zoom is changed, doIMapQuery shouldn't be executed.
	  // this value will be set to false by function zoomEndHandler in Map.js
	  iMap.isZoomIgnored = true;
	  // reset the zoom to contain all pins
	  map.SetMapView(allPins); 
	} 
	catch(e) {
	}
}

function panTo(lat, lng) {
	  setTimeout(function() {
		  map.PanToLatLong(new VELatLong(lat, lng));
	  }, 500);
}

function zoomTo(index) {
	iMap.isZoomIgnored = true;

	//var marker = gShapes[index];
	var marker = iMap.getMarkerOf(index);
	
	if (map.GetZoomLevel() < 15)
		map.SetCenterAndZoom(marker.GetPoints()[0], 15);

	window.setTimeout(
		function() { 
			map.PanToLatLong(marker.GetPoints()[0]);
			// to show Jack after zoom to the pin
			if(mjStreetView.isStreetView) {
				if(typeof marker._can_viewPoint !== 'undefined' && marker._can_viewPoint != "")
			   		navigateToEncoded(marker._can_viewPoint);
				else
			   		navigateTo(marker.GetPoints()[0].Latitude, marker.GetPoints()[0].Longitude);
			}
		}, 
	300);
	
	//unhighlightBox();
	//iMap.isZoomIgnored = false;
}

var gSize  = [0,0,0,0,0];
var gStart = [0,0,0,0,0];
var letterarray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var maxpagesize = 6;

function showBox(index){
		var letterarray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
		var bx = document.getElementById("box"+index);
		var pNode = bx.parentNode;
		
		var parentName = pNode.id;	
		if (parentName.substring(0,8) == "multiBox") {
			var mlc = parentName.substring(8,9);
			var idx2 = parentName.substring(10);
			var letter = letterarray[index-1];
			
			setMultiTab(mlc,index);
		}
}
	
function showListingBox(index) {
	showBox(index);

   var ct = document.getElementById("listing_container");
   var top = document.getElementById("box1");
   var bx = document.getElementById("box"+index);

	var pNode = bx.parentNode;
	var parentName = pNode.id;	

	if (parentName.substring(0,8) == "multiBox") {
		var idx = parentName.substring(8,9);
//		alert(idx);
//		bx = pNode.parentNode;
//		alert(bx.id);
		bx = document.getElementById("multiBoxContainer"+idx);
	}

	var start = bx.offsetTop - top.offsetTop;
	var end = start + bx.offsetHeight+ 30;

	var c_start = ct.scrollTop;
	var c_end = c_start + ct.offsetHeight+5;

	if (start < c_start) {
		scrlPos = start;
		clearTimeout(t);
		t = setTimeout('scrlTo()', 1000);
	}
	else {
		var diff = end - c_end;
		scrlPos = c_start + diff;
		
		scrlPos = start;
		if ((start + ct.offsetHeight) > (ct.scrollHeight))
			scrlPos = ct.scrollHeight - ct.offsetHeight + 15;
		
		clearTimeout(t);
		t = setTimeout('scrlTo()', 1000);
	}
/*
	else if (end > c_end) {
		var diff = end - c_end;
		scrlPos = c_start + diff;
		t = setTimeout('scrlTo()', 1000);
	}
*/	
}

function scrlTo() {
	var ct = document.getElementById("listing_container");
	if (!(ct.scrollTop == scrlPos)) {
		var diff = Math.round((scrlPos - ct.scrollTop) / 5);
		if (diff > 50) diff = 50;
		else if (diff < -50) diff = -50;
		
		if (diff <= 3 && diff >= -3) {
			ct.scrollTop = scrlPos;
			clearTimeout(t);
		}
		else {
			var prev = ct.scrollTop;
			ct.scrollTop += diff;
			
			t=setTimeout('scrlTo()', 10);
		}
	}
	else {
		clearTimeout(t);
	}
}

function highlightBox(index) {
	if (highlightIndex > 0 && highlightIndex != index)	
		unhighlightBox(highlightIndex);

	var bx = document.getElementById("colorbox"+index);
	bx.bgColor='#ffffcc';
	highlightIndex = index;
}

function unhighlightBox(_index) {
	var index = _index||highlightIndex;
	try {	
		var bx = document.getElementById("colorbox"+index);
		bx.bgColor='#ffffff';

		map.DeleteShape(hShape);
		highlightIndex = 0;
		hShape = null;
	} catch (e) {}
}

function highlightIcon(index) {
	var letter = MapLIB.getPinLetter(index);
	var pinHTML = MapLIB.getPinHTML(letter, true);
	var pinIMG = MapLIB.getPinIMG(letter, true);

	//var shape = gShapes[index];
	var shape = iMap.getMarkerOf(index);

	// there are some company that do not have geocodes
	if(!shape)
		return;

	var ll = shape.GetPoints();

	try { map.DeleteShape(hShape); } catch(e) {}	

	hShape = MapLIB.addPushpin({
		lat: ll[0].Latitude,
		lng: ll[0].Longitude,
		beakOffsetX:shape._can_beakOffsetX,
		beakOffsetY:shape._can_beakOffsetY,
		pinHTML: pinHTML,
 		pinIMG: pinIMG,
 		id: index,
 		type:"H-PIN",
 		title: '',
 		desc: ''});

	highlightIndex = index;
} 

function unhighlightIcon() {
	if(hShape != null) {
		try {
			map.DeleteShape(hShape);
		} catch(e) {}

		//highlightIndex = 0;
		hShape = null;
	}
}

function setSize() {
	var $ = jQuery;

	var mapId = "#"+MapLIB.defaults.mapId;
	var streetId = "#"+mjStreetView.options.streetId;
	var minHeight = 500;
	var minStreetSceneHeight = 200;
	var minWidth = 500;
	var mapLeftOffset = 320; // this offset is fixed otherwise it is very hard to adjust the left offset of the map div.
	var clHeight = $(window).height();

	var topOffset;
	var mapTop = $(mapId).offset().top;//$("#map").offset().top;
	var streetTop = $(streetId).offset().top;//$("#mapStreet").offset().top;

	if(streetTop <= 0) {
		topOffset = mapTop;
	} else {
		topOffset = Math.min(mapTop, streetTop);
	}

	var newHeight = Math.max(minHeight, clHeight - topOffset - 100);
	// make it half, so that it expands along map div as window is resized
	var streetSceneHeight = parseInt(Math.max(minStreetSceneHeight, newHeight / 2));

	// check if there is box ad
	if($("#_boxad_").length != 0) {
		newWidth = Math.max(minWidth, $(window).width() - mapLeftOffset - 135); // 135 is size of box ad
	} else {
		newWidth = Math.max(minWidth, $(window).width() - mapLeftOffset - 3);
	}

	newWidth = $.browser.safari ? newWidth-20: newWidth;
	
	if(mjStreetView.isStreetView) {
		$(streetId).width(newWidth).height(streetSceneHeight);
		$(mapId).width(newWidth).height(newHeight - streetSceneHeight - 3); // -3 is adjustment for listing height;
		map.Resize(newWidth, newHeight - streetSceneHeight - 3);		
	} else {
		$(mapId).width(newWidth).height(newHeight);
		map.Resize(newWidth, newHeight);
	}

	$("#listing_container").height(newHeight);

	MapLIB.vars.prevSize = MapLIB.getWindowSize();
	setPanBounds();
}

function initMapSize() {
	setSize();
}

function resizeMap() {
	var currWindowSize = MapLIB.getWindowSize(); 

	if((currWindowSize.width != MapLIB.vars.prevSize.width) || (currWindowSize.height != MapLIB.vars.prevSize.height)) {
		MapLIB.removeInfoBox();
		MapLIB.vars.prevSize = currWindowSize; 
		setSize();
		resizeListingContainer();
	}
}

function resizeListingContainer() {
	var listingContainer = document.getElementById("listing_container");
	var map = document.getElementById("map");
	var mapStreet = document.getElementById("mapStreet");

	var newHeight = 0;
	/*
	if(i$.isStreetView()) newHeight = map.clientHeight + mapStreet.clientHeight - listingContainer.offsetTop +24;
	else newHeight = map.clientHeight - listingContainer.offsetTop +24;
	*/
	newHeight = map.clientHeight - listingContainer.offsetTop +24;
	listingContainer.style.height = newHeight + 'px';
}

function setNoDataMsg() {
	hideNav();
	var text = "";
	//ready for dragend or zoomend event
	resultDisplayed = "N";	
		
	if (searchCriteria.stype=="N") { //In case of name search
		text = "Please enter another search word to see listing results.";
		if (searchCriteria.lang=="1") {
			text = "Por favor entre otra palabra de b�squeda para ver lista de resultados.";
		}		
		document.form2.name.value = '';
		document.form2.name.focus();
	}
	else {
		if (searchCriteria.eventFired==0) {
			text = "Please click another category or enter a search word to see listing results.";
			if (searchCriteria.lang=="1") {
				text = "Porfavor ingrese otra categor�a o nombre.";
			}
		}
		else { 
			text = "Please drag and move map to another area to see listing results.";
			if (searchCriteria.lang=="1") {
				text = "Por favor arrastre y mueva el mapa a otra �rea para ver lista de resultados.";
			}
			resultDisplayed = "Y";
		}
	}

	var msg = "No listing results.";
	if (searchCriteria.lang=="1") {
		msg = "Sin resultados.";
	}
			
	var noMsg = '<div class="list_container" style="background:none;border:0;">' +
				'	<table cellpadding=0 border=0>' +
				'	<tr>' +
				'		<td width="33" align="center"><img src="http://imfimg.com/images/icon_warning.gif" width="21" height="21" alt="" /></td>' +
				'		<td><span style="font-size:12px; font-weight:bold;">'+msg+'</span></td>' +					
				'	</tr>' +
				'	<tr>' +
				'		<td>&nbsp;</td>' +
				'		<td><span style="font-size:10px; font-weight:normal;">'+text+'</span></td>' +
				'	</tr>' +
				'	</table>' +
				'</div>';
	
	showListing(noMsg);

}
//]]>

