//<![CDATA[                    

//jQuery.noConflict();

var t;
var map = null;
var geocoder = null;
var highlightIndex = 0;
var scrlPos;

var hShape; //Declare the Active/Hover Marker variables
var gShapes = [];	// array of the markers

var iMap = {
	isDEBUG: false,
	markers: [],
	isRefreshMapOn: true,
	isZoomIgnored: false,
	isInitZoomChanged: 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() {
		for(var i = 0; i < iMap.markers.length; i++) {
			map.DeleteShape(iMap.markers[i].marker);
		}

		iMap.markers.length = 0;
	},

	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;
	},

	showListing: function(text) {
		document.getElementById("listing_container").innerHTML = text;
	},

	hideListing: function() {
		document.getElementById("listing_container").innerHTML = "";
	},

	showMessage: function(text) {
		var msg = document.getElementById("leftMessage");
		var msgTxt = document.getElementById("leftMessageText");
		msgTxt.innerHTML = text;
		this.showListing(msg.innerHTML);
	},

	showResultCount: function(text) {
		var res1 = document.getElementById("resultCount1");
		var res2 = document.getElementById("resultCount2");
		
		res1.innerHTML = text;
		res2.innerHTML = text;
	},

	hideResultCount: function() {
		var res1 = document.getElementById("resultCount1");
		var res2 = document.getElementById("resultCount2");
		
		res1.innerHTML = "";
		res2.innerHTML = "";
	},

	// 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 lang;
		var that = this;

		lang = $("#iMap_lang").html();

		urlData = 'lang=' + lang
				+ '&nt=' + $("#iMap_stype").html()
				+ '&str=' + start 
				+ '&ar=' + swLat + ',' + swLng + ',' + neLat + ',' + neLng 
				+ '&hid=' + $("#iMap_sic").html()
				+ '&na=' + $("#iMap_sname").html()
				+ '&locName=' + $("#iMap_loc").html()
				+ '&vm=' + $("#iMap_vm").html();
		
		$.ajax({
			   type: "GET",
			   url: '/search_area_i.jsp',
			   data: urlData+'&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
					working = 0;
					
					var resText ;
					var navText ;
					var catText ;
					var listingInfo ;
					var stype ;
					var total ;

					$(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");
						total = $(this).attr("totalRecord");

						$("#mapListingTotalCnt").html(total);
						
						if(mjStreetView.isStreetView) {
							// reset pois
							mjStreetView.pois = [];
							mjStreetView.pois = eval($(this).attr("pois"));
							//canSetPOIs();
						}						
					});

					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");
						var showMap = $(this).attr("showMap");

						if(showMap == 1) {
							// create the marker
							var marker = createMarker(point,index,html,viewPoint);
							mkCnt++;
						}
					});

					if (mkCnt > 0) {
						iMap.showResultCount(navText);
						iMap.showListing(listingInfo);
						document.getElementById("iMap_vmNav").innerHTML = catText;
					}
					else {
						iMap.hideResultCount();
						if(lang == '1') {
							iMap.showMessage("Déplacez la carte en la faisant glisser vers une autre zone pour obtenir les résultats de la liste.");
						} else {
							iMap.showMessage('Please drag and move map to another area to see listing results.');
						}
					}

					if(!mjStreetView.isStreetView) {
						Webcam.getWebcamMarkers(view);
					}

					that.getWeather((neLat+swLat)/2, (neLng+swLng)/2, lang, map.GetZoomLevel());
					that.getNews((neLat+swLat)/2, (neLng+swLng)/2, lang, map.GetZoomLevel());

					setEventsOnIconTextLink();	// to set click event on icons in right side in listing box
					
					MapLIB.unblockMap();
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	//alert("Error : can't get information");
			   }
			 });
	},

	getWeather: function(lat, lng, lang, zoom) {
		var $ = jQuery;

		$.ajax({
			   type: "GET",
			   url: '/weather/search2.jsp',
			   data: 'lang=' + lang	+ '&lat=' + lat	+ '&lng=' + lng + '&zoom=' + zoom + '&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
				// parse header
				$(xml).find('header').each(function() {
					var resText = $(this).attr("resText");
					var cityName = $(this).attr("cityName");
					var prov = $(this).attr("prov");

					$("#bs_weather").html(resText);
					$("#iMap_cityNav").html(cityName);
					$("#iMap_provNav").html(prov);
				});
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	//alert("Error : can't get weather information");
			   }
		});
	},
	
	getNews: function(lat, lng, lang, zoom) {
		var $ = jQuery;
		
		jQuery.ajax({
			   type: "GET",
			   url: '/getNews.jsp',
			   data: 'lang=' + lang	+ '&lat=' + lat	+ '&lng=' + lng + '&zoom=' + zoom + '&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
				// parse header
				$(xml).find('header').each(function() {
					var resText = $(this).attr("resText");

					$("#bs_news").html(resText);
				});
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	//alert("Error : can't get news information");
			   }
		});		
	},

	// 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 loadMap(frenchFlag, isReverseLookup) { // called from MapListingData.java	
	jQuery(document).ready(function($) {
		// loading map and set initial options
		map = MapLIB.init({
			mapId:"map", 
			listingContainerId: "listing_container",
			centerLat:initCenterLat, 	// defined in MapListingData.java
			centerLng:initCenterLng,	// defined in MapListingData.java
			zoom:initCenterZoom+1,
			mapLeftOffset:320,			// offset of map div, which is related to width of listing in left side
			lang:frenchFlag,			// '1' : French, '0' : English
			resizeCallback:resizeMap,
			isReverseLookup:isReverseLookup
		});

		// initializing street scene object
		mjStreetView.init({
			 frenchFlag:frenchFlag, 
			 serverName:__serverName,	// defined in mapListing.jsp
			 mapInstance:map,
			 pageType: isReverseLookup ? "RL" : "M"});

		map.AttachEvent("onendpan", endPanHandler);
		//map.AttachEvent("onstartpan", startPanHandler);
		map.AttachEvent("onendzoom", zoomEndHandler);
		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);

	    // for now, move&refresh and street scene are not shown in reverse lookup
		if(!isReverseLookup) {
		    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:(frenchFlag == '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);
			setTimeout(function(){MapLIB.streetSceneButton();}, 500);
			
			/*
			 * to show 'more webcams' button
			 * 
			$('<div id="btnMoreWebcams" class="customBtn"><div style="position:relative;top:7px;"></div><img src="/images/arrow_orange.gif" style="position:relative;top:9px;left:40px;display:none;" /></div>')
			 .setCustomButton({
			 		name: MapLIB.Message.moreWebcams,
			 		style: {left:"490px", width:"90px"},
			 		clickFn: MapLIB.Button.moreWebcams
			 });		
			 */

			var streetLeftOffset = frenchFlag == '1' ? "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:(frenchFlag == '1' ? "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:(frenchFlag == '1' ? "380px":"350px"), width:"80px"},
			 		clickFn: MapLIB.Button.streetScene
			 });

			Webcam.get(map, frenchFlag, 'F');
		}
		else
			iMap.isRefreshMapOn = false;

		GoGetMap();

		setEventsOnIconTextLink(); // refer to sendPopups.js 
	});
}

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 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://cpgimg.com/images/mapicon/icon_flag.png' /></div>";
	  var pinIMG = "http://cpgimg.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 setMultiTab(mlc,idx){
	var letter = letterarray[idx-1];

	var base = document.getElementById('navigation_sm' + mlc);
	var arr = base.getElementsByTagName('div')

	var hd = document.getElementById('ml_header' + mlc);
	hd.innerHTML = letter;
	
	// show box-area
	for (var i=1;i<=20;i++){
		var mbox = document.getElementById('multiBox'+mlc+"-"+(i));
		if (mbox != null) {
			if ((i+gStart[mlc])==idx){
				mbox.style.display="block"
			}else{
				mbox.style.display="none"
			}
		}
	}		

	// check if the letter is in the tabs
	var found = 0;
	for (var i=0;i<arr.length;i++){
		if (arr[i].getElementsByTagName('a')[0].innerHTML==letter){
			found=1;
		}
	}		

	// make sure the page shows the letter
	if (found == 0) {
		var st = 0;
		if ((idx-gStart[mlc]) <=6)
			st = 0;
		else if ((idx-gStart[mlc]) <=12)
			st = 6;
		else if ((idx-gStart[mlc]) <=18)
			st = 12;
		else if ((idx-gStart[mlc]) <=20)
			st = 18;
			
		genPage(mlc,st,gSize[mlc],gStart[mlc]);
	}

	// show tab-area
	for (var i=0;i<arr.length;i++){
		if (arr[i].getElementsByTagName('a')[0].innerHTML==letter){
			arr[i].setAttribute('id', 'current');
		}else{
			arr[i].setAttribute('id', 'tab'+i);
		}
	}		
}

function buildTab(mlc, size, start) {
	genPage(mlc, 0,size,start);
	gSize[mlc] = size;
	gStart[mlc] = start;
	setMultiTab(mlc,start+1);
}

function genPage(mlc, st, length, start){

	var strarr = [];
	var str = ''
	var pagesizeup = Math.min(maxpagesize, length-st)
	var pagesizedn = Math.max(0, st-maxpagesize)
	var pagedn = pagesizedn
	var pageup = st+pagesizeup
	if (st>0){
		strarr.push(' <a href="javascript:genPage('+mlc+','+pagedn+', '+length+', '+start+');"><img align="right" id="prev" src="/images/arrow_left.gif" border="0" /></a> ')
	}else{
		strarr.push(' <img id="prev" src="/images/spacer.gif" width="20" height="21" border="0" align="right"  /> ')
	}
	
	for (var i=st;i<pageup;i++ ){
		var letter = letterarray[i+start];
		var idx = (i+start+1);
		strarr.push( '<div onmouseout="Javascript:unhighlightBox('+idx+');" onmouseover="javascript:setMultiTab(' +mlc+ ','+ idx + ');highlightBox('+idx+');highlightIcon('+idx+');" id="" ><a href="javascript:void(0);">'+letter+'</a></div>');
	}
	if (pageup < length){
		//str += '<div onclick="javascript:generatePage('+pageup+','+length+');" id="next" ><a href="javascript:void(0);">&gt;</a></div>'	
		strarr.push(' <a href="javascript:genPage('+mlc+','+pageup+', '+length+', '+start+');"><img align="right" id="next" src="/images/arrow_right.gif" border="0" /></a> ');
	}else{
		strarr.push( '<img id="next" src="/images/spacer.gif" width="20" height="21" border="0" align="right"  /></a> ');
	}
	strarr.reverse()
	for (var i=0;i<strarr.length;i++ ){
		str += strarr[i]
	}
	var base = document.getElementById('navigation_sm' + mlc);
	base.innerHTML = str;
	
	//alert(pagedn  + ":::"+pageup)
//		setMultiTab(mlc,st+1);
}

	
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();
	}
}

//]]>
