﻿var map = new Map("100%","100%")
var overviewMap = new OverviewMap(125,125,map,4);
var route = new Route();
map.routeVectorLayer.setEditable(true);
map.disableClickPanning();
map.enableContinuePanning();
var pushpinGeocodeS = new Geocode();
var pushpinGeocodeD = new Geocode();
pushpinGeocodeS.addListener(Geocode.EVENT_GEO_RESULT,onGeocodePushpinSourceResult);
pushpinGeocodeD.addListener(Geocode.EVENT_GEO_RESULT,onGeocodePushpinDestResult);
var menu = new ContextMenu();

var layersManager = map.getLayersManager()
var layersCollection  = new LayersCollection()
layersManager.addLayer(layersCollection)

var layersList = new Array();
layersList.push(1000)
layersList.push(1001)
layersList.push(1002)

map.loadWaitingMessage(Map.ALIGN_CENTER_CENTER,new ScreenPoint(130,60));
map.addAdvancedNavigationBar(new ScreenCoordinate(7,7));
map.addDragBar(new ScreenCoordinate(75,50));

map.addListener(Map.EVENT_MAP_MOUSE_MOVE,onMapMouseMove,map);
map.addListener(Flash.EVENT_FLASH_INITIALIZE,onMapFlashInitialize,map);
map.addListener(Map.EVENT_MAP_MODIFIED,onMapModified,map);
map.addListener(Map.EVENT_MAP_LOADED,onMapLoaded,map);
map.addListener(Map.EVENT_GEO_RESULT,onMapGeoResult,map);
map.addListener(Map.EVENT_MAP_DOUBLE_CLICK,onMapDoubleClick,map);
route.addListener(Route.EVENT_ROUTE_RESULT,onRouteResult,route);
route.addListener(Route.EVENT_ROUTE_CHANGED,onRouteChanged,map);
route.addListener(Route.EVENT_ROUTE_LOCATION_CHANGED,onRouteLocationChanged,map);

function onMapDoubleClick(map, coordinate) {
	map.setCenterPosition(coordinate,map.getZoomLevel()+4);
}

var currentView = Map.VIEW_RASTER;
var generalDefaultInnerHtml;
var routeTabInnerHtml;
var numberOfNodes = 2;
var nodesIds = 3;
var firstAddressId = "address1TR";
var lastAddressId = "address2TR";
var addressesNodesIdsArr = new Array();
addressesNodesIdsArr.push('address1TR');
addressesNodesIdsArr.push('address2TR');
var startPos;
var endPos;
var startPosY;
var endPosY;		
var factor;
var interval;
var overviewOverlay;		
var LinkToTheMap;
var LayersOverlay;
var k=0.5;
var lastTargetPostion;
var lastGeocodeResult;
var isOverviewVisible = false;
var isLinkToMapVisible = false;
var fullAddressSTemp = "";	
var isRouteExists = false;
var isRouteChange = false;
var isRouteLocationChange = false;
var isMapSmall = true;
var isUpMenuOpen = true;
var mapInitialize = false;
var isBubbleShown = false;
var lastCity = "";
var lastStreet = "";
var lastHouseNumber = "";
var lastAddressParts = "";
var lastLatPoint = "";
var lastLongPoint = "";
var addressesArr = new Array();
var routeSettingsArr = new Array();
var layersSettingsArr = new Array();
var currentSideView = "1";
var updateLocationInterval;
var firstMapLoad = true;
var isStandardRoute = true;
var enableDisable = true;
var countryChange = false;
var fisrtClickOnInput = true;
// PushPins & targets
var pushpinsList = new Array();
layerTargets       = layersManager.createLocalVectorLayer("targets");
layerPushpins      = layersManager.createLocalVectorLayer("pushpins");
layerSourcePushpin = layersManager.createLocalVectorLayer("pushpinSource");
layerDestPushpin   = layersManager.createLocalVectorLayer("pushpinDest");

layerPushpins.setMinZoom(-10);
layerDestPushpin.setMinZoom(-10);
layerDestPushpin.setMinZoom(-10);

layerPushpins.setClustering(LocalVectorLayer.CLUSTERING_LOW);
layerTargets.setClustering(LocalVectorLayer.CLUSTERING_NONE);
var targetIcon   = new ExternalIcon("images/TargetIcon.swf");
layerTargetsFlag = false;

var pushpinSourceMarker = null;
var pushpinDestMarker   = null;
sourceGeocodeAddress = "";
destGeocodeAddress   = "";

isWeatherEnabled = false
isTrafficEnabled = false
var trafficInterval;
var layersNameArr = new Array('SYM_Group1','SYM_Group2','SYM_Group3','SYM_Group4','SYM_Group5','SYM_Group6','SYM_40_Bus_terminal','SYM_35_Car_Parking','is_gas','SYM_7_Heliport_fields','SYM_50_Rail_Station','SYM_53_Bay_Laguna','SYM_4_Police_station','SYM_33_Post_office','SYM_16_Municipal_site','SYM_5_Areal_Clinic','SYM_55_Hospital','SYM_52_Consulate','SYM_51_Embassy','SYM_48_Pharmacy','SYM_8_Youth_hostel','SYM_32_Hotel','SYM_10_Campsite','SYM_15_Field_School','SYM_31_Cinema','SYM_37_Theater','SYM_46_Amphitheater','SYM_22_Moslem_holy','SYM_36_Synagogue','SYM_20_Jewish_holy','SYM_21_Christian_holy','SYM_23_Other_holy','SYM_47_Monument','SYM_19_Archaeologic','SYM_12_National_Parks','SYM_9_Picnic_Place','SYM_17_Nature_point','SYM_44_Info_center','SYM_52_Zoo','SYM_49_Hydro_Site','SYM_14_Jewish_Fund','SYM_26_Spring','SYM_1_Observ_point');
/////////////////////////////////////////////
if (dir=="rtl") {
	layersNameArr.push('Recycle_Group1');
	layersNameArr.push('Recycle_Battery');
	layersNameArr.push('Recycle_Bottles');
	layersNameArr.push('Recycle_Carton');
	layersNameArr.push('Recycle_Paper');
	layersNameArr.push('Recycle_Plastic');
	
	map.setScaleBarPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(30,15));
	if (navigator.geolocation) {
		menu.addItem(".             מצא את המיקום שלי",getMyLocation,false)
	}
	menu.addItem(".                קבע ככתובת מקור",setOriginPushpin,true)
	menu.addItem(".                  קבע ככתובת יעד",setDestinationPushpin,false)
	menu.addItem(".      הצג תמונת בית בישראל",showHomeAddress,true)
	messageSucc = "ההודעה נשלחה בהצלחה";
	generalError = "תקלה כללית";
	atLeastOneEmail = "יש להזין לפחות כתובת אימייל אחת";
	emailError = "כתובת האימייל איננה תקינה";
	nameMustBe = "יש להזין את שמך";
	emailMustBe = "יש להזין כתובת אימייל";
	bodyMustBe = "יש להזין את תוכן ההודעה";
	error4 = "מדינה לא נמצאה";
	error3 = "שם עיר שגוי או לא נמצא";
	error2 = "שם רחוב שגוי או לא נמצא";
	error1 = "מספר בית לא נמצא";
	error0 = "הכתובת לא נמצאה";
	lang = "heb";
	couldNotFound = "המערכת לא הצליחה לזהות את הכתובת"
	couldNotFoundRoute = "המערכת לא הצליחה לזהות את המסלול המבוקש."
	routeWrong = "הכתובות שמסומנות <font color='red'>באדום</font></br> שגויות או לא נמצאו"
	reason = "הסיבה:"
	suggestions = "הצעות:"
	makeSure1 = "ודא שכל המילים מאוייתות כראוי."
	makeSure2 = "נסה חיפוש פחות ממוקד."
	makeSure3 = "<a href='#' onclick='displaySendToSystemPopup()'>דווח לנו</a> על התקלה."
	makeSure4 = "נסו להתמקד בנקודה מדוייקת יותר."
	makeSure5 = "נסו לבצע חיפוש לכתובת."
	makeSure6 = "יש לוודא שהמסלול הינו במדינה שנבחרה"
	overviewTitle = "מפת ייחוס";
	OpenSideMenu = "Images/border_left.png";
	CloseSideMenu = "Images/border_right.png";
	pageAlign = "right";
	reverseAlign = "left";
	
	MAPA = "מפה"
	MAPA_URL = "http://www.gisrael.co.il/"
	OFEK = "אופק"
	OFEK_URL = "http://www.ofek-air.com/about.asp?lang=1"
	AtlasCT = "אטלס סי.טי."
	AtlasCTSite = "http://www.atlasct.co.il"
	NAVTEQ = "NAVTEQ"
	FORECA = "Foreca"
	NAVTEQ_URL = "http://www.navteq.com"
	FORECA_URL = "http://www.foreca.com"
	DECELL = '&nbsp©‏ <a href="http://www.decell.com" id="lnkData" class="links" target="_blank">דסל</a>';

	WelcomeToABmaps = "ברוכים הבאים למפות ABmaps"
	SetDefaultLocation = "קבע מיקום נוכחי כמיקום ברירת מחדל"
	multiAddressFound = "החיפוש לכתובת הניב את התוצאות</br> הבאות, אנא בחר אחת:"
	addressNotExactFound = "<b>האם התכוונת ל: </b>"
	routeDescription = "הוראות נסיעה"
	
	addressTitle = "כתובת:"
	closeTitle = "סגור"
	
	alert1 = "יש להכניס כתובת";
	alert2 = "יש להזין כתובת מוצא";
	alert3 = "יש להזין כתובת יעד";
	
	addDestination = "הוסף יעד";
	options = "אפשרויות מסלול";
	fastTitle = "מהיר";
	shortTitle = "קצר";
	pedestrianTitle = "להולכי רגל";
	throughKvish6Title = "אפשר מעבר בכבישי אגרה";
	sourcePoint = "נקודת מוצא";
	destinationPoint = "נקודת יעד";
	middlePoint = "נקודת ביניים";
	
	findRouteTitle = "מצא מסלול";
	showMilestones = "הצגת אבני דרך";
	showTrafficDirections = "הצגת כיווני נסיעה";
	clearRouteTitle = "הסר מסלול";
	
	currentURLSite = "http://www.abmaps.co.il";
	currentURL = "http://www.abmaps.co.il/main.asp";
	currentURLEncode = "http%3A%2F%2Fwww.abmaps.co.il%2Fmain.asp";
}
else {
	if (lastLanguage=="rus") {
		map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25));
		if (navigator.geolocation) {
			menu.addItem("Go to my location",getMyLocation,false)
		}
		menu.addItem("Определить в качестве исходного адреса", setOriginPushpin,true)
		menu.addItem("Определить в качестве адреса назначения",setDestinationPushpin,false)
						 
		messageSucc = "Сообщение успешно отправлено"
		generalError = "Общая ошибка"
		atLeastOneEmail = "Ввести хотя бы один электронный адрес"
		emailError = "Электронный адрес не существует"
		nameMustBe = "Введите Ваше имя"
		emailMustBe = "Введите Ваш электронный адрес"
		bodyMustBe = "Введите Ваше сообщение"
		error4 = "Страна найдена неверно или не найдена"
		error3 = "Название города/населенного пункта найдено неверно или не найдено"
		error2 = "Название улицы найдено неверно или не найдено"
		error1 = "Номер дома не найден"
		error0 = "Адрес не найден"
		lang = "rus";
		couldNotFound = "Программа не смогла найти адрес"
		couldNotFoundRoute = "Программа не смогла найти маршрут"
		routeWrong = "адрес в <font color='red'>red</font> неправильный или не может быть найден"
		reason = "Причина"      
		suggestions = "Предложения:"
		makeSure1 = "Убедитесь,что все слова записаны правильно"
		makeSure2 = "Попробуйте менее сфокусированный поиск"
		makeSure3 = "<a href='#' onclick='displaySendToSystemPopup()'>Сообщите нам </a> об этой проблеме"
		makeSure4 = "Попытайтесь более точно сфокусировать точку поиска"
		makeSure5 = "Попробуйте найти этот адрес"
		makeSure6 = "Убедитесь,что маршрут показан в выбранной Вами стране"
		overviewTitle = "Обзорная карта"
		OpenSideMenu = "Images/border_left_en.png";
		CloseSideMenu = "Images/border_right_en.png";
		pageAlign = "left"
		reverseAlign = "right"

		MAPA = "Mapa"
		MAPA_URL = "http://www.gisrael.co.il/eng/"
		OFEK = "Ofek"
		OFEK_URL = "http://www.ofek-air.com/about.asp?lang=2"
		AtlasCT = "AtlasCT"
		AtlasCTSite = "http://www.atlasct.com"
		NAVTEQ = "NAVTEQ"
		FORECA = "Foreca"
		NAVTEQ_URL = "http://www.navteq.com"
		FORECA_URL = "http://www.foreca.com"
		DECELL = '&nbsp©‏ <a href="http://www.decell.com" id="lnkData" class="links" target="_blank">Decell</a>';
		WelcomeToABmaps = "Добро пожаловать в ABmaps"
		SetDefaultLocation = "Определить даннoe положение на карте как значение при отсутствии информации"
		multiAddressFound = "Выберите один из следующих результатов Вашего поиска"
		addressNotExactFound = "<b>Вы имели в виду: </b>"
		routeDescription = "Описание маршрута"
		
		addressTitle = "Адрес"
		closeTitle = "Закрыть"
		
		alert1 = "Введите адрес"
		alert2 = "Введите исходный адрес"
		alert3 = "Введите адрес пункта назначения"
		
		addDestination = "Добавьте пункт назначения"
		options = "Варианты маршрута"
		fastTitle = "Быстрый"
		shortTitle = "Короткий"
		pedestrianTitle = "Пешеходный"
		throughKvish6Title = "Включая платные дороги"
		sourcePoint = "Исходный пункт"
		destinationPoint = "Пункт назначения"
		middlePoint = "Промежуточный пункт"

		findRouteTitle = "Найти маршрут"
		showMilestones = "Показать переходные моменты маршрута"
			showTrafficDirections = "Показать указания к маршруту"
		clearRouteTitle = "Убрать маршрут"

		currentURLSite = "http://www.abmaps.ru";
		currentURL = "http://www.abmaps.ru/main.asp";
		currentURLEncode = "http%3A%2F%2Fwww.abmaps.ru%2Fmain.asp";
	}
	else { // English
		map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25));
		if (navigator.geolocation) {
			menu.addItem("Go to my location",getMyLocation,false)
		}
		menu.addItem("Set as source address",setOriginPushpin,true)
		menu.addItem("Set as destination address",setDestinationPushpin,false)
		messageSucc = "Message successfully sent";
		generalError = "General error";
		atLeastOneEmail = "You must insert at least one email address";
		emailError = "Email address is not valid";
		nameMustBe = "Please insert your name";
		emailMustBe = "Please insert email address";
		bodyMustBe = "Please insert your message";
		error4 = "State error or not found";
		error3 = "City name wrong or not found";
		error2 = "Street name wrong or not found";
		error1 = "House number not found";
		error0 = "Address not found";
		lang = "eng";
		couldNotFound = "The system could find the address"
		couldNotFoundRoute = "The system could find the route."
		routeWrong = "The addresses in <font color='red'>red</font> are wrong or can not be found"
		reason = "Reason:"
		suggestions = "Suggestions:"
		makeSure1 = "Make sure all words are spelled correctly."
		makeSure2 = "Try less focused search."
		makeSure3 = "<a href='#' onclick='displaySendToSystemPopup()'>Report us</a> about this problem."
		makeSure4 = "Try to focus to a more accuracy point."
		makeSure5 = "Try to search for this address."
		makeSure6 = "Please make sure your route is in the choosen country"
		overviewTitle = "Overview Map";
		OpenSideMenu = "Images/border_left_en.png";
		CloseSideMenu = "Images/border_right_en.png";
		pageAlign = "left";
		reverseAlign = "right";
		
		MAPA = "Mapa"
		MAPA_URL = "http://www.gisrael.co.il/eng/"
		OFEK = "Ofek"
		OFEK_URL = "http://www.ofek-air.com/about.asp?lang=2"
		AtlasCT = "AtlasCT"
		AtlasCTSite = "http://www.atlasct.com"
		NAVTEQ = "NAVTEQ"
		FORECA = "Foreca"
		NAVTEQ_URL = "http://www.navteq.com"
		FORECA_URL = "http://www.foreca.com"
		DECELL = '&nbsp©‏ <a href="http://www.decell.com" id="lnkData" class="links" target="_blank">Decell</a>';

		WelcomeToABmaps = "Welcome To ABmaps"
		SetDefaultLocation = "Set current location as default"
		multiAddressFound = "Your search has returned the following results, please select one:"
		addressNotExactFound = "<b>Did you mean: </b>"
		routeDescription = "Driving directions"
		
		addressTitle = "Address:"
		closeTitle = "Close"
		
		alert1 = "Please insert an address";
		alert2 = "Please insert source address";
		alert3 = "Please insert destination address";
		
		addDestination = "Add Destination";
		options = "Route Options";
		fastTitle = "Fast";
		shortTitle = "Short";
		pedestrianTitle = "Pedestrian";
		throughKvish6Title = "Allow toll roads";
		sourcePoint = "Source Point";
		destinationPoint = "Destination Point";
		middlePoint = "Middle Point";

		findRouteTitle = "Find Route";
		showMilestones = "Show Milestones";
		showTrafficDirections = "Show Traffic Directions";
		clearRouteTitle = "Clear Route";
		
		currentURLSite = "http://www.abmaps.com";
		currentURL = "http://www.abmaps.com/main.asp";
		currentURLEncode = "http%3A%2F%2Fwww.abmaps.com%2Fmain.asp";
	}
}
map.setContextMenu(menu);
/////////////////////////////////////////////
var displayTips = true;
var displayAds = false;
if (screen.width<=800) {
	displayTips = false;
}
else if(screen.width>=1280) {
	displayTips = false;
	displayAds = true;
}
switch(screen.width) {
	case 800 : 

		break;
	case 1024 : 
	
		break;
	case 1280 : 
	
		break;
	case 1600 :
	
		break;
	default:

		break;
}
/////////////////////////////////////////////
var lastClickedCoordinate;
function onMapClick(map, coordinate) {
	lastClickedCoordinate = coordinate;
	
}
map.addListener(Map.EVENT_MAP_CLICK,onMapClick,map);
/////////////////////////////////////////////
function onShapeClick(_object,_map,_layer,_shape) {
	temp = _shape.getId();
	var nameAndIdArr=temp.split("^");
	
	switch (nameAndIdArr[0]){
		case "weather":
			setTimeout("map.setCenterPosition(lastClickedCoordinate);",400);
			showForecastInfo(nameAndIdArr[1]);
		break;
	}
}
map.layersManager.addListener(LayersManager.EVENT_SHAPE_CLICK,onShapeClick,map);
/////////////////////////////////////////////
function getRowByNodeId(nodeId) { //Return the ChildNode for the selected "nodeId".
	nodeRowIndex = document.getElementById(nodeId).rowIndex;
	return document.getElementById("addressesNodesTable").tBodies[0].childNodes[nodeRowIndex];
}
/////////////////////////////////////////////
function getLastRowByNodeId() { //Return the last index row.
	if (BrowserDetect.browser.toLowerCase()=="firefox") {
		var rows = document.getElementById("addressesNodesTable").getElementsByTagName("tr");  
		return rows.length - 1;
	} 
	else {
		return document.getElementById("addressesNodesTable").rows.length - 1;
	}
}
/////////////////////////////////////////////
function getLastRowNode(minus) { //Return the last index row.
	nodeRowIndex = getLastRowByNodeId();
	if (minus!="")
		nodeRowIndex = nodeRowIndex - minus;
	return document.getElementById("addressesNodesTable").tBodies[0].childNodes[nodeRowIndex];
}
/////////////////////////////////////////////
function clearAddressesNodesIdsArr() {
	for (i = 0; i < addressesNodesIdsArr.length; i++)
		addressesNodesIdsArr.pop();
}
/////////////////////////////////////////////
function removeFromArrayById(value) {
	if (numberOfNodes==2) {
		document.getElementById("addressesNodesTable").rows[0].cells[4].innerHTML = '';
		getLastRowNode("").cells[4].innerHTML = '';
	}

	for (i = 0; i < addressesNodesIdsArr.length; i++) {
		if(addressesNodesIdsArr[i]==value) {
			if (i==0)
				addressesNodesIdsArr.shift();
			else if (i==addressesNodesIdsArr.length)
				addressesNodesIdsArr.pop();
			else {
				arrPart1 = addressesNodesIdsArr.slice(0,i);
				arrPart2 = addressesNodesIdsArr.slice(i+1,addressesNodesIdsArr.length);
				
				addressesNodesIdsArr = arrPart1.concat(arrPart2);
			}
			return false;
		}
	}
}
/////////////////////////////////////////////
function removeNodeRow(nodeId) {
	childNodeRow = getRowByNodeId(nodeId);
	document.getElementById("addressesNodesTable").tBodies[0].removeChild(childNodeRow);
	numberOfNodes--;
	removeFromArrayById(nodeId);
	if (nodeId==firstAddressId) { // We removed the first address
		document.getElementById("addressesNodesTable").rows[0].cells[1].innerHTML = '<img src="Images/Route/Start.gif" width="18" height="21" alt="'+sourcePoint+'" title="'+sourcePoint+'">';
		firstAddressId = document.getElementById("addressesNodesTable").rows[0].id;
	}
	if (nodeId==lastAddressId) { // We removed the last address
		temp = getLastRowNode("");
		temp.cells[1].innerHTML = '<img src="Images/Route/End.gif" width="18" height="20" alt="'+destinationPoint+'" title="'+destinationPoint+'">';
		lastAddressId = temp.id;
	}
}
/////////////////////////////////////////////
function addRowNode() {
	numberOfNodes++;
	nodesIds++;
	
	addressesNodesIdsArr.push('address'+nodesIds+'TR');
	
	var newTR  = document.createElement('tr');
	newTR.id = 'address'+nodesIds+'TR';
	newTR.height = '30';
	newTR.style.height = '30';

	var cellA = document.createElement('td');
	var cellB = document.createElement('td');
	var cellC = document.createElement('td');
	var cellD = document.createElement('td');
	var cellE = document.createElement('td');
	
	cellA.width = '10';
	cellA.style.width = '10';
	
	cellB.innerHTML = '<img src="Images/Route/middle.gif" width="18" height="21">';
	cellB.title = middlePoint;
	cellB.alt = middlePoint;
	
	cellC.width = '8';
	cellC.style.width = '8';
	
	cellD.innerHTML = '<input type="text" class="InputBox" tabindex="33" style="width:180px" name="address'+nodesIds+'" id="address'+nodesIds+'" currentLocation="'+nodesIds+'" value=""  onkeyup="onKeyUpEvent(\'findMultiRoute\',event)">';
	cellD.title = middlePoint;
	cellD.alt = middlePoint;
	
	cellE.innerHTML = '<a href="#" onclick="javascript:removeNodeRow(\'address'+nodesIds+'TR\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a>';
	cellE.width = '25';
	cellE.style.width = '25';

	newTR.appendChild(cellA);
	newTR.appendChild(cellB);
	newTR.appendChild(cellC);
	newTR.appendChild(cellD);
	newTR.appendChild(cellE);

	document.getElementById("addressesNodesTable").tBodies[0].insertBefore(newTR,getLastRowNode(""));	

	document.getElementById("addressesNodesTable").rows[0].cells[4].innerHTML = '<a href="#" onclick="javascript:removeNodeRow(\''+firstAddressId+'\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a>';
	getLastRowNode("").cells[4].innerHTML = '<a href="#" onclick="javascript:removeNodeRow(\''+lastAddressId+'\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a>';
}
/////////////////////////////////////////////
function isEmailValid(emailStr) {
	var check=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (check.test(emailStr)) return true
		 else return false      
}
/////////////////////////////////////////////
function isFieldEmpty(str) {
	return (str=="")
}
/////////////////////////////////////////////
function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}
/////////////////////////////////////////////
function ajaxpage(url,params,method,ajaxNumber){ // Ajax function.
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
	page_request.onreadystatechange=function(){
		afterAjax(page_request,ajaxNumber)
	}
	page_request.open(method, url, true);
	if (method=="POST") {
		page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
		page_request.setRequestHeader("Content-length", params.length);
		page_request.setRequestHeader("Connection", "close");
		page_request.send(params);
	}
	else if (method=="GET") {
		page_request.send(null)
	}
}
/////////////////////////////////////////////
function afterAjax(page_request,ajaxNumber){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		switch (ajaxNumber){
			case "1":
				switch (page_request.responseText){
					case "1": 
						document.getElementById("sendToFriendInfo").innerHTML = messageSucc;
					break;
					case "2": 
						document.getElementById("sendToFriendInfo").innerHTML = generalError;
					break;
					case "3": 
						document.getElementById("sendToFriendInfo").innerHTML = generalError;
					break;
				}
				setTimeout("clearSendToFriendDiv()",1500);
			break;
			case "2":
				switch (page_request.responseText){
					case "1": 
						document.getElementById("sendToSystemInfo").innerHTML = messageSucc;
					break;
					case "2": 
						document.getElementById("sendToSystemInfo").innerHTML = generalError;
					break;
					case "3": 
						document.getElementById("sendToSystemInfo").innerHTML = generalError;
					break;
				}
				setTimeout("clearSendToSysetmDiv()",1500);
			break;
			case "3":
				if (page_request.responseText=="heb")
					location.href="http://www.abmaps.co.il";
				else if (page_request.responseText=="eng")
					location.href="http://www.abmaps.com";
				else // rus
					location.href="http://www.abmaps.ru";
			break;
			case "5":
				changeCountryAfterSetDefaultLocation(page_request.responseText);
			break;
			case "6":
				if (currentSideView=="3")
					document.getElementById("contentDiv").innerHTML=page_request.responseText;
			break;
			case "7":
				document.getElementById("tipSpan").innerHTML=page_request.responseText;
				document.getElementById("tipsTable").style.display = "";
			break;
		}
	}
}
/////////////////////////////////////////////
function saveCurrentRouteTabInnerHtml() {
	rowLength = getLastRowByNodeId();
	theTable = document.getElementById("addressesNodesTable");
	addressesArr = [];
	routeSettingsArr = [];
	for (i = 0; i <= rowLength; i++) {
		theId = convertToInputId(theTable.rows[i].id);
		addressesArr.push(document.getElementById(theId).value);
	}
	
	routeSettingsArr.push(document.getElementById("fatestId").checked);
	routeSettingsArr.push(document.getElementById("shortestId").checked);
	routeSettingsArr.push(document.getElementById("pedestrianId").checked);
	if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise"))
		routeSettingsArr.push(document.getElementById("road6").checked);
	if (document.getElementById("Animation")!=null)
		routeSettingsArr.push(document.getElementById("Animation").checked);
	
	routeTabInnerHtml = document.getElementById("contentDiv").innerHTML;
}
/////////////////////////////////////////////
function setSideView(num,flag) {
	switch (num){
		case "1":
			if (currentSideView!="1") {
				if (currentSideView=="4")
					saveCurrentRouteTabInnerHtml();
				document.getElementById("tdSideView1").className = "menuLinksDisabled";
				document.getElementById("tdSideView2").className = "menuLinks";
				document.getElementById("tdSideView3").className = "menuLinks";
				document.getElementById("tdSideView4").className = "menuLinks";
				document.getElementById("contentDiv").innerHTML = getGeneralDefaultInnerHtml();
				currentSideView = "1";
				ddtreemenu.createTree("treemenu1", false);
				
				if (layersSettingsArr.length!=0) {
					for (i = 0; i < layersNameArr.length; i++) {
						document.getElementById(layersNameArr[i]).checked = layersSettingsArr[i];
					}
				}
			}
		break;
		case "2": 
			if (currentSideView!="2") {
				if (currentSideView=="4")
					saveCurrentRouteTabInnerHtml();
				if (currentSideView=="1")
					saveCurrentCheckedLayers();
				document.getElementById("tdSideView1").className = "menuLinks";
				document.getElementById("tdSideView2").className = "menuLinksDisabled";
				document.getElementById("tdSideView3").className = "menuLinks";
				document.getElementById("tdSideView4").className = "menuLinks";
				
				showWeatherInfo();
				//var layer = layersCollection.getLayerByName('Weather');
				poi.getInst().showHideLayerExt(true,"SYM_WEATHER_DEFAULT");
				isWeatherEnabled = true;
				//layer.show();
				
				onIconMouseMove("", "weather");
				currentSideView = "2";
			}
		break;
		case "3": 
			if (currentSideView!="3") {
				if (currentSideView=="4")
					saveCurrentRouteTabInnerHtml();
				if (currentSideView=="1")
					saveCurrentCheckedLayers();
				document.getElementById("tdSideView1").className = "menuLinks";
				document.getElementById("tdSideView2").className = "menuLinks";
				document.getElementById("tdSideView3").className = "menuLinksDisabled";
				document.getElementById("tdSideView4").className = "menuLinks";
				if (!isTrafficEnabled) {
					var layer = layersCollection.getLayerByName('Traffic');
					trafficInterval = setInterval(trafficIntervalFunction,1000 * 180) 
					isTrafficEnabled = true;
					layer.show();
					//if ((document.getElementById("countriesList").selectedIndex!=15) || (!isCountryInMapView("isr")) || (map.getZoomLevel() < -12)) {
					if ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -12)) {
						//document.getElementById("countriesList").selectedIndex=15;
						onCountrySelectChange(document.getElementById("countriesList"));
					}
				}
				showTrafficInformationDiv();
					
				onIconMouseMove("", "traffic");
				currentSideView = "3";
			}
		break;
		case "4": 
			if (currentSideView!="4") {
				if (currentSideView=="1")
					saveCurrentCheckedLayers();
				document.getElementById("tdSideView1").className = "menuLinks";
				document.getElementById("tdSideView2").className = "menuLinks";
				document.getElementById("tdSideView3").className = "menuLinks";
				document.getElementById("tdSideView4").className = "menuLinksDisabled";
				currentSideView = "4";
				if (flag) {
					document.getElementById("contentDiv").innerHTML = routeTabInnerHtml;
					
					rowLength = getLastRowByNodeId();
					theTable = document.getElementById("addressesNodesTable");
					if (addressesArr.length!=0) {
						for (i = 0; i <= rowLength; i++) {
							theId = convertToInputId(theTable.rows[i].id);
							document.getElementById(theId).value = addressesArr[i];
						}
					}
					if (routeSettingsArr.length!=0) {
						document.getElementById("fatestId").checked = routeSettingsArr[0];
						document.getElementById("shortestId").checked = routeSettingsArr[1];
						document.getElementById("pedestrianId").checked = routeSettingsArr[2];
						if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise"))
							document.getElementById("road6").checked = routeSettingsArr[3];
						if (document.getElementById("Animation")!=null)
							document.getElementById("Animation").checked = routeSettingsArr[4];
					}
				}
			}
		break;
	}
}
/////////////////////////////////////////////
function changeCountryAfterSetDefaultLocation(country) {
	return false;
	if (countryChange) {
		countryChange = false;
		return false;
	}
	previousLastCountryCode = lastCountryCode;
	countriesListSelectBox = document.getElementById("countriesList");
	if (country=="United States") {
		countriesListSelectBox.selectedIndex = 31;
		lastCountryCode = "USA";
	}
	if (country=="Switzerland") {
		countriesListSelectBox.selectedIndex = 30;
		lastCountryCode = "CHE";
	}
	if (country=="Sweden") {
		countriesListSelectBox.selectedIndex = 29;
		lastCountryCode = "SWE";
	}
	if (country=="Spain") {
		countriesListSelectBox.selectedIndex = 28;
		lastCountryCode = "ESP";
	}
	if (country=="Slovenia") {
		countriesListSelectBox.selectedIndex = 27;
		lastCountryCode = "SVN";
	}
	if (country=="Slovakia") {
		countriesListSelectBox.selectedIndex = 26;
		lastCountryCode = "SVK";
	}
	if (country=="Scotland") {
		countriesListSelectBox.selectedIndex = 25;
		lastCountryCode = "SCT";
	}
	if (country=="Russia") {
		countriesListSelectBox.selectedIndex = 24;
		lastCountryCode = "RUS";
	}
	if (country=="Portugal") {
		countriesListSelectBox.selectedIndex = 23;
		lastCountryCode = "CZE";
	}
	if (country=="Poland") {
		countriesListSelectBox.selectedIndex = 22;
		lastCountryCode = "POL";
	}
	if (country=="Norway") {
		countriesListSelectBox.selectedIndex = 21;
		lastCountryCode = "NOR";
	}
	if (country=="Netherlands") {
		countriesListSelectBox.selectedIndex = 20;
		lastCountryCode = "NED";
	}
	if (country=="Mexico") {
		countriesListSelectBox.selectedIndex = 19;
		lastCountryCode = "MEX";
	}
	if (country=="Luxemburg") {
		countriesListSelectBox.selectedIndex = 18;
		lastCountryCode = "LUX";
	}
	if (country=="Latvia") {
		countriesListSelectBox.selectedIndex = 17;
		lastCountryCode = "LAT";
	}
	if (country=="Italy") {
		countriesListSelectBox.selectedIndex = 16;
		lastCountryCode = "ITA";
	}
	if (country=="Israel") {
		countriesListSelectBox.selectedIndex = 15;
		if (dir=="rtl")
			lastCountryCode = "ISR";
		else
			lastCountryCode = "ISR";
	}
	if (country=="Ireland") {
		countriesListSelectBox.selectedIndex = 14;
		lastCountryCode = "IRE";
	}
	if (country=="Hungary") {
		countriesListSelectBox.selectedIndex = 13;
		lastCountryCode = "HUN";
	}
	if (country=="Greece") {
		countriesListSelectBox.selectedIndex = 12;
		lastCountryCode = "GRC";
	}
	if (country=="Germany") {
		countriesListSelectBox.selectedIndex = 11;
		lastCountryCode = "GEU";
	}
	if (country=="France") {
		countriesListSelectBox.selectedIndex = 10;
		lastCountryCode = "FRA";
	}
	if (country=="Finland") {
		countriesListSelectBox.selectedIndex = 9;
		lastCountryCode = "FIN";
	}
	if (country=="England") {
		countriesListSelectBox.selectedIndex = 8;
		lastCountryCode = "ENG";
	}
	if (country=="Denmark") {
		countriesListSelectBox.selectedIndex = 7;
		lastCountryCode = "DNK";
	}
	if (country=="Czech") {
		countriesListSelectBox.selectedIndex = 6;
		lastCountryCode = "CZE";
	}
	if (country=="Croatia") {
		countriesListSelectBox.selectedIndex = 5;
		lastCountryCode = "HRV";
	}
	if (country=="Canada") {
		countriesListSelectBox.selectedIndex = 4;
		lastCountryCode = "CAN";
	}
	if (country=="Brazil") {
		countriesListSelectBox.selectedIndex = 3;
		lastCountryCode = "BRA";
	}
	if (country=="Belgium") {
		countriesListSelectBox.selectedIndex = 2;
		lastCountryCode = "BEL";
	}
	if (country=="Austria") {
		countriesListSelectBox.selectedIndex = 1;
		lastCountryCode = "AUT";
	}
	if (country=="Australia") {
		countriesListSelectBox.selectedIndex = 0;
		lastCountryCode = "AUS";
	}
	
	if (previousLastCountryCode!=lastCountryCode) {
		
	}
	
	updateView();
	
	randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
	ajaxpage(currentURLSite+"/inc/setSettings.asp?countrycode="+lastCountryCode+"&randomNumber="+randomNumber,"","GET","4");
}
/////////////////////////////////////////////
function getTip() {
	ajaxpage(currentURLSite+"/inc/getTip.asp?tipNumber="+tipNumber,"","GET","7");
	tipNumber++;
	if (tipNumber>=20)
		tipNumber = -1
}
/////////////////////////////////////////////
function clearSendToFriendDiv() {
	hideLayer('shadow','sendToFriendDiv');
	document.getElementById("sendToFriendInfo").innerHTML = "";
	document.getElementById("sentTo").value = "";
	document.getElementById("sentFrom").value = "";
}
/////////////////////////////////////////////
function clearSendToSysetmDiv() {
	hideLayer('shadow','sendToSystemDiv');
	document.getElementById("sendToSystemInfo").innerHTML = "";
	document.getElementById("sentToDescription2").value = "";
}
/////////////////////////////////////////////
function openTermsOfUseWindow(mylink, windowname, width, height,scrollbars) {
	if (! window.focus)return true;
	var href;
	if (typeof(mylink) == 'string')
		href=mylink;
	else
		href=mylink.href;
	window.open(href, windowname, 'top=70,left=100,'+scrollbars+'width='+width+',height='+height);
	return false;
}
/////////////////////////////////////////////
function displaySendToAFriendPopup() {
	showLayer('shadow','sendToFriendDiv');
}
/////////////////////////////////////////////
function displaySendToSystemPopup() {
	showLayer('shadow','sendToSystemDiv');
}
/////////////////////////////////////////////
function sendEmail(frm,lang) {
	sentToArr = frm.sentTo.value.split(",");
	if (isFieldEmpty(frm.sentTo.value)) {
		alert(atLeastOneEmail);
		frm.sentTo.focus();
		return false;
	}
	for (i = 0; i < sentToArr.length; i++) {
		if (!isEmailValid(trim(sentToArr[i]))) {
			alert(emailError);
			frm.sentTo.focus();
			frm.sentTo.select();
			return false;
		}
	}
	if (isFieldEmpty(frm.sentFrom.value)) {
		alert(emailMustBe);
		frm.sentFrom.focus();
		return false;
	}
	if (!isEmailValid(frm.sentFrom.value)) {
		alert(emailError);
		frm.sentFrom.focus();
		frm.sentFrom.select();
		return false;
	}
	params = "type=1"+"&lat=" + map.getCenterPosition().getLat() + "&long=" + map.getCenterPosition().getLong() + "&zoomLevel=" + map.getZoomLevel() + "&lang=" + encodeURI(lang)+"&sentTo=" + encodeURI(document.getElementById("sentTo").value)+"&sentFrom=" + encodeURI(document.getElementById("sentFrom").value)+"&sentToDescription=" + encodeURI(document.getElementById("sentToDescription").value)+"&sentToMe=" + encodeURI(document.getElementById("sentToMe").checked);
	ajaxpage(currentURLSite+"/Inc/sendEmail.asp",params,"POST","1");
}
/////////////////////////////////////////////
function sendEmailToSystem(frm,lang) {
	if (isFieldEmpty(frm.name.value)) {
		alert(nameMustBe);
		frm.name.focus();
		return false;
	}
	
	if (isFieldEmpty(frm.sentFrom2.value)) {
		alert(emailMustBe);
		frm.sentFrom2.focus();
		return false;
	}
	if (!isEmailValid(frm.sentFrom2.value)) {
		alert(emailError);
		frm.sentFrom2.focus();
		frm.sentFrom2.select();
		return false;
	}
	if (isFieldEmpty(frm.sentToDescription2.value)) {
		alert(bodyMustBe);
		frm.sentToDescription2.focus();
		return false;
	}
	
	params = "type=2"+"&lang=" + encodeURI(lang)+"&sentFrom=" + encodeURI(document.getElementById("sentFrom2").value)+"&name=" + encodeURI(document.getElementById("name").value)+"&sentToDescription=" + encodeURI(document.getElementById("sentToDescription2").value);
	ajaxpage(currentURLSite+"/Inc/sendEmail.asp",params,"POST","2");
}
/////////////////////////////////////////////
function showHideOverview() {
	if (isOverviewVisible) {
		document.getElementById("OverviewButton").src = "Images/OpenOverviewMap.png";
		startPos = 127;
		endPos   = 0;
		startPosY = 126;
		endPosY = 0;
		if (dir=="rtl")
			map.setScaleBarPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(30,15));
		else
			map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(90,25));
	} else {
		document.getElementById("OverviewButton").src = "Images/CloseOverviewMap.png";
		startPos = 0;
		endPos   = 127;	
		startPosY = 0;
		endPosY = 126;
		if (dir=="rtl")
			map.setScaleBarPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(135,15));
		else
			map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25));
	}
	factor = 0;
	isOverviewVisible = !isOverviewVisible
	interval = window.setInterval("positionInterval("+startPos+","+endPos+","+startPosY+","+endPosY+",'overview')",1)
}
/////////////////////////////////////////////
function getURL(encode) {
	var coordinate = map.getCenterPosition();
	Y = coordinate.getLat();
	X = coordinate.getLong();
	ZoomLevel = map.getZoomLevel();
	if (encode==true) {
		if (isRouteExists==true) {
			URL = currentURLEncode+"%3FX%3D"+X+"%26Y%3D"+Y+"%26Zoomlevel%3D"+ZoomLevel+"%26CountryCode%3D"+lastCountryCode+"%26Lang%3D"+lastLanguage+"&v=1.0";
		}
		else {
			if (fullAddressSTemp != "") {
				URL = currentURLEncode+"%3FX%3D"+X+"%26Y%3D"+Y+"%26Zoomlevel%3D"+ZoomLevel+"%26CountryCode%3D"+lastCountryCode+"%26Lang%3D"+lastLanguage+"&v=1.0";
			}
			else {
				URL = currentURLEncode+"%3FX%3D"+X+"%26Y%3D"+Y+"%26Zoomlevel%3D"+ZoomLevel+"%26CountryCode%3D"+lastCountryCode+"%26Lang%3D"+lastLanguage+"&v=1.0";
			}
		}
	}
	else {
		if (isRouteExists==true) {
			URL = currentURL+"?X="+X+"&Y="+Y+"&Zoomlevel="+ZoomLevel+"&CountryCode="+lastCountryCode+"&Lang="+lastLanguage+"&v=1.0";
		}
		else {
			if (fullAddressSTemp != "") {
				URL = currentURL+"?address="+fullAddressSTemp+"&CountryCode="+lastCountryCode+"&Lang="+lastLanguage+"&v=1.0";
			}
			else {
				URL = currentURL+"?X="+X+"&Y="+Y+"&Zoomlevel="+ZoomLevel+"&CountryCode="+lastCountryCode+"&Lang="+lastLanguage+"&v=1.0";
			}
		}
	}
	return URL;			
}
/////////////////////////////////////////////
function getLinkToTheMap() {
	document.getElementById("linkTable").style.display = "";
	document.getElementById("Updates").value = getURL(false);
	startPosY = 0;
	endPosY = 44;				
	factor = 0;
	interval = window.setInterval("positionInterval(0,0,"+startPosY+","+endPosY+",'linkToTheMap')",1)
	isLinkToMapVisible = true;
}
/////////////////////////////////////////////
function closeLinkToMap() {
	document.getElementById("linkTable").style.display = "none";
	startPosY = 44;
	endPosY = 0;				
	factor = 0;
	interval = window.setInterval("positionInterval(0,0,"+startPosY+","+endPosY+",'linkToTheMap')",1)
	isLinkToMapVisible = false;			
}
/////////////////////////////////////////////
function CopyToClipBoard(x) {
	Copied = document.getElementById(x).createTextRange();
	Copied.execCommand("Copy");
}
/////////////////////////////////////////////
function printMap() {
	if (isRouteExists) {
		window.open("printpage/printRoute.asp?country="+lastCountryCode+"&lang="+lang,"Print");
	} else {
		window.open("printpage/printAddress.asp?country="+lastCountryCode+"&lang="+lang,"Print");
	}
}
/////////////////////////////////////////////
function positionInterval(startPos,endPos,startPosY,endPosY,overlayName) {
  factor = (k*factor+1)/(k+1)
  var newPos = Math.round(startPos + (endPos-startPos) * factor)
  var newPosY = Math.round(startPosY + (endPosY-startPosY) * factor)
  switch (overlayName){
	case "overview": 
		map.setOverlayScreenCoordinate(overviewOverlay,Map.ALIGN_BOTTOM_RIGHT, new ScreenCoordinate(newPos,newPosY));
	break;
	case "linkToTheMap": 
		map.setOverlayScreenCoordinate(LinkToTheMap,Map.ALIGN_BOTTOM_RIGHT, new ScreenCoordinate(501,newPosY));
	break;
	case "layers": 
		map.setOverlayScreenCoordinate(LayersOverlay,Map.ALIGN_TOP_RIGHT, new ScreenCoordinate(newPos,70));
	break;
	default : 	alert(generalError);
  }
  if (factor<0.999) {
  } else {
	 window.clearInterval(interval);	 
  }
}
/////////////////////////////////////////////
function addToFavorites() {
	if (BrowserDetect.browser.toLowerCase()=="firefox") { // Mozilla Firefox Bookmark
		window.sidebar.addPanel('AtlasCT Map', currentURLSite,"");	} 
	else if(BrowserDetect.browser.toLowerCase()=="explorer") { // IE Favorite
		window.external.addFavorite(currentURLSite,'AtlasCT Map'); }
}
/////////////////////////////////////////////
function onMapFlashInitialize(map,size) {
	mapInitialize = true;
	
	// OnMouseMove
	OnMouseMove = new Overlay("OnMouseMove");
	var OnMouseMoveDiv = document.getElementById("mouseMoveDiv")
	OnMouseMove.setDomElement(OnMouseMoveDiv)
	map.addOverlayToScreen(OnMouseMove,Map.ALIGN_TOP_LEFT, new ScreenCoordinate(75,5))
	
	// Side Menu
	SideMenuDivOverlay = new Overlay("SideMenuDivOverlay");
	var SideMenuDiv = document.getElementById("SideMenuDiv");
	SideMenuDivOverlay.setDomElement(SideMenuDiv);
	if (dir=="rtl")
		map.addOverlayToScreen(SideMenuDivOverlay,Map.ALIGN_TOP_RIGHT, new ScreenCoordinate(10,0))
	else
		map.addOverlayToScreen(SideMenuDivOverlay,Map.ALIGN_TOP_LEFT, new ScreenCoordinate(0,0))

	// Up Menu
	UpMenuDivOverlay = new Overlay("UpMenuDivOverlay");
	var UpMenuDiv = document.getElementById("UpMenuDiv");
	UpMenuDivOverlay.setDomElement(UpMenuDiv);
	map.addOverlayToScreen(UpMenuDivOverlay,Map.ALIGN_TOP, new ScreenCoordinate(0,0))

	// Overview.
	overviewOverlay = new Overlay("overviewOverlay");
	var overviewFormDiv = document.getElementById("overviewMapDiv")
	overviewOverlay.setDomElement(overviewFormDiv)
	map.addOverlayToScreen(overviewOverlay,Map.ALIGN_BOTTOM_RIGHT, new ScreenCoordinate(0,0))		
	
	// Close Overview.
	var div1 = document.createElement("div1");
	div1.style.width="22px";
	div1.style.height="22px";
	div1.style.backgroundColor="transparent";
	div1.innerHTML = "<img id='OverviewButton' src='Images/OpenOverviewMap.png' width='22' height='22' onclick='javascript:showHideOverview()' style='z-index:3;cursor:pointer' alt='"+overviewTitle+"' title='"+overviewTitle+"'>";
	var overlay = new Overlay("ScreenOverlay");
	overlay.setDomElement(div1);
	overlay.setOffsetPosition(new ScreenCoordinate(0,0));
	map.addOverlayToScreen(overlay,Map.ALIGN_BOTTOM_RIGHT, new ScreenCoordinate(20,19));
	
	// Weather
	var weatherIconOverlay = new Overlay("weatherIconOverlay");
	var weatherTrafficIconsDiv = document.getElementById("weatherTrafficIconsDiv");
	weatherIconOverlay.setDomElement(weatherTrafficIconsDiv)
	map.addOverlayToScreen(weatherIconOverlay,Map.ALIGN_TOP_LEFT, new ScreenCoordinate(154,6))
	
	// FlashButtons
	var flashButtonsOverlay = new Overlay("flashButtonsOverlay");
	var FlashButtonsDiv = document.getElementById("FlashButtonsDiv");
	flashButtonsOverlay.setDomElement(FlashButtonsDiv)
	map.addOverlayToScreen(flashButtonsOverlay,Map.ALIGN_TOP_RIGHT, new ScreenCoordinate(240,6))
	
	// Terms of use
	var div = document.createElement("div");
	div.style.width="335px";
	div.style.height="22px";
	div.style.padding="3px";
	div.style.align="cetner";
	div.innerHTML = '<table align="center"><tr><td width="335" align="center"  id="tdLnk1"  class="textD"><b>©‏ <a href="'+AtlasCTSite+'" id="lnkData" class="links" target="_blank">'+AtlasCT+'</a>&nbsp©‏ <a href="'+NAVTEQ_URL+'" id="lnkData" class="links" target="_blank">'+NAVTEQ+'</a>&nbsp©‏ <a href="'+FORECA_URL+'" id="lnkData" class="links" target="_blank">'+FORECA+'</a>&nbsp©‏ <a href="'+MAPA_URL+'" id="lnkData" class="links" target="_blank">'+MAPA+'</a>&nbsp©‏ <a href="'+OFEK_URL+'" id="lnkData" class="links" target="_blank">'+OFEK+'</a>'+DECELL+' </b></td></tr></table>'
	
	var overlay = new Overlay("ScreenOverlay");
	overlay.setDomElement(div);
	overlay.setOffsetPosition(new ScreenCoordinate(-100,-15));
	map.addOverlayToScreen(overlay,Map.ALIGN_BOTTOM_CENTER, new ScreenCoordinate(120,4));

	// Links to map
	LinkToTheMap = new Overlay("LinkToTheMap");
	var LinkToTheMapDiv = document.getElementById("linkDiv")
	LinkToTheMap.setDomElement(LinkToTheMapDiv)
	map.addOverlayToScreen(LinkToTheMap,Map.ALIGN_BOTTOM_RIGHT, new ScreenCoordinate(501,0))
	
	/*
	//Error message
	errorMessageOverlay = new Overlay("ErrorMessageOverlay");
	var errorMessageFormDiv = document.getElementById("ErrorMessageDiv")
	errorMessageOverlay.setDomElement(errorMessageFormDiv)
	map.addOverlayToScreen(errorMessageOverlay,Map.ALIGN_CENTER_CENTER, new ScreenCoordinate(80,65))
	hideErrorMessage();
	
	//Search message
	searchMessageOverlay = new Overlay("SearchMessageOverlay");
	var searchMessageFormDiv = document.getElementById("SearchMessageDiv")
	searchMessageOverlay.setDomElement(searchMessageFormDiv)
	map.addOverlayToScreen(searchMessageOverlay,Map.ALIGN_CENTER_CENTER, new ScreenCoordinate(115,105));
	hideSearchMessage();
	*/
	if ((reqRoute!="") || (reqLat!="") || (reqLong!="") || (reqZoomLevel!="") || (reqAddressPos!="")) {
		if (reqRoute=="true") {
			strHTML = getMultiRouteHtml("","","",false);
			setSideView("4",false);
			document.getElementById("contentDiv").innerHTML = strHTML;
			
			if (reqOriginLocation!="")
				var reqAddressS = new Address(reqOriginLocation);
			else
				var reqAddressS = new LatLong(reqOriginLocationLat,reqOriginLocationLong);
			
			if (reqDestinationLocation!="")
				var reqAddressD = new Address(reqDestinationLocation);
			else
				var reqAddressD = new LatLong(reqDestinationLocationLat,reqDestinationLocationLong);
				
			route.setOriginLocation(reqAddressS);
			route.setDestinationLocation(reqAddressD);
			map.showRoute(route,lastCountryCode);
		}
		else {
			if (reqZoomLevel!="") {
				if (reqVersion=="") {
					tempLong = reqLong;
					reqLong = reqLat;
					reqLat = tempLong;
				}
				map.setCenterPosition(new LatLong(reqLat,reqLong),reqZoomLevel);
				
				if (reqAddTarget=="true") {
					targetMarker = new Marker("targets",new LatLong(reqLat,reqLong),targetIcon,"","")
					layerTargets.addShape(targetMarker)	
					layerTargets.redraw();
					layerTargetsFlag = true;
				}
			}
			else {
				if (reqAddressPos!="") {
					var reqAddressPosObj = new Address(reqAddressPos);
					setTimeout("map.setCenterPosition(new Address(reqAddressPos),'',lastCountryCode);",100);
				}
			}
		}
	}
	else {
		defaultMapPosition = Get_Cookie('defaultMapPosition');
		if (defaultMapPosition!=null) {
			defaultMapPositionArr = defaultMapPosition.split(",");
			var point = new LatLong(defaultMapPositionArr[0],defaultMapPositionArr[1]);
			map.setCenterPosition(point,defaultMapPositionArr[2]);
			document.getElementById("XPoint").innerHTML = Math.round(defaultMapPositionArr[1]*Math.pow(10,4))/Math.pow(10,4);
			document.getElementById("YPoint").innerHTML = Math.round(defaultMapPositionArr[0]*Math.pow(10,4))/Math.pow(10,4);
		}
		else {
			_position = document.getElementById("countriesList").value;
			_pos = _position.split("^");
			lastCountryCode = _pos[3];
			if (!firstMapLoad) {
				document.getElementById("sourceAddress").value = "";
				document.getElementById("destinationAddress").value = "";
			}

			var point = new LatLong(_pos[0],_pos[1]);
			map.setCenterPosition(point,_pos[2]);
		}
	}
}
/////////////////////////////////////////////
function cetnerPosToAddress(latPoint,longPoint,zoomLevel,fullAddress,type,num) {
	map.setCenterPosition(new LatLong(latPoint,longPoint),zoomLevel);
	//addBubble(lastAddressParts,lastLatPoint,lastLongPoint,"");
	
	rowLength = getLastRowByNodeId();
	theTable = document.getElementById("addressesNodesTable");
	currentRowId = convertToInputId(theTable.rows[num].id);
	document.getElementById(currentRowId).value = fullAddress
		
	if ((type=="s") || (num==0)) { // Source
		document.getElementById("sourceAddress").value = fullAddress;
	}
	else if ((type=="d") || (num==rowLength)) { // Destination
		document.getElementById("destinationAddress").value = fullAddress;
	}
}
/////////////////////////////////////////////
function onMapModified(map) {
	if (isLinkToMapVisible)
		closeLinkToMap();
	clearInterval(updateLocationInterval);
	
	if (((!isCountryInMapView("isr")) && (!isCountryInMapView("ise"))) || (map.getZoomLevel() < -12)) {
		flashButtons.runFunction("","setView","MapsButton");
		map.setView(Map.VIEW_RASTER);
		currentView = Map.VIEW_RASTER;
	}
}
/////////////////////////////////////////////
function onMapLoaded(map) {
	if (!firstMapLoad) {
		if ((isCountryInMapView("isr")) || (isCountryInMapView("ise"))) {
			clearInterval(updateLocationInterval);
			changeCountryAfterSetDefaultLocation("Israel");
		}
		else if ((map.getZoomLevel() >= -12) && (map.getZoomLevel() <= -3)) {
			clearInterval(updateLocationInterval);
			updateLocationInterval = setInterval(updateLocation,2000);
		}
	}
	else
		firstMapLoad = false;
}
/////////////////////////////////////////////
function updateLocation() {
	randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
	ajaxpage(currentURLSite+"/inc/Coordinate2Country.asp?Horizontal="+map.getCenterPosition().getLong()+"&Vertical="+map.getCenterPosition().getLat()+"&Projection=LatLon&randomNumber="+randomNumber,"","GET","5");
	clearInterval(updateLocationInterval);
}
/////////////////////////////////////////////
function onMapMouseMove(map, coordinate) {
	if (mapInitialize) {
		document.getElementById("XPoint").innerHTML = Math.round(coordinate.getLong()*Math.pow(10,3))/Math.pow(10,3);
		document.getElementById("YPoint").innerHTML = Math.round(coordinate.getLat()*Math.pow(10,3))/Math.pow(10,3);
	}
}
/////////////////////////////////////////////
function changeMapSize(dir) {
	if (dir=="ltr") {
		if (isOverviewVisible)
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25))",500);
		else
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(90,25))",500);
	}
	if (isMapSmall) { // Large the map and disappear the sideMenu.
		document.getElementById("sideMenu").style.display = "none";
		document.getElementById("borderSide").src = OpenSideMenu;
		isMapSmall = false;
	}
	else {
		document.getElementById("sideMenu").style.display = "";
		document.getElementById("borderSide").src = CloseSideMenu;
		isMapSmall = true;
	}
}
/////////////////////////////////////////////
function closeOpenUpMenu(dir) {
	if (dir=="ltr") {
		if (isOverviewVisible)
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25))",500);
		else
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(90,25))",500);
	}
	if (isUpMenuOpen) {
		document.getElementById("upMenu").style.display = "none";
		document.getElementById("borderUp").src = "Images/border_down.png";
		isUpMenuOpen = false;
		setHeightOfInfoDiv(true);
	}
	else {
		document.getElementById("upMenu").style.display = "";
		document.getElementById("borderUp").src = "Images/border_up.png";
		isUpMenuOpen = true;
		setHeightOfInfoDiv(false);
	}
}
/////////////////////////////////////////////
function isCountryInMapView(countryCode) { // return true if the country is inside the current map.
	var clientViewPosition = map.getClientViewPosition();
	pointXTopLeft = clientViewPosition.topLeft.getLong();
	pointYTopLeft = clientViewPosition.topLeft.getLat();
	pointXBottomRight = clientViewPosition.bottomRight.getLong();
	pointYBottomRight = clientViewPosition.bottomRight.getLat();
	
	switch (countryCode.toLowerCase()) {
		case "isr":
			leftUpCornerX = 33.10408;
			leftUpCornerY = 34.93919575182566; 
			rightDownCornerX = 35.09944;
			rightDownCornerY = 28.58570407716144;
		break;
	}
	
	if ((Math.floor(pointXBottomRight) < Math.floor(leftUpCornerX)) || (Math.floor(pointXTopLeft) > Math.floor(rightDownCornerX)) || (Math.floor(pointYBottomRight) > Math.floor(leftUpCornerY)) || (Math.floor(pointYTopLeft) < Math.floor(rightDownCornerY)))
	    return false;
	else	
		return true;	
}
/////////////////////////////////////////////
function onCountrySelectChange(_selectBox) {
	countryChange = true;
	_position = _selectBox.options[_selectBox.selectedIndex].value;
	_pos = _position.split("^");
	lastCountryCode = _pos[3];
	
//	if (document.getElementById("countriesList").selectedIndex!=15) {
//		flashButtons.runFunction("","setView","MapsButton");
//		map.setView(Map.VIEW_RASTER);
//	}
	
	if (!firstMapLoad) {
		document.getElementById("sourceAddress").value = "";
		document.getElementById("destinationAddress").value = "";
	}
	
	if (lastCountryCode.toLowerCase()=="isr") {
		document.getElementById("sourceAddress").dir = "rtl";
		document.getElementById("destinationAddress").dir = "rtl";
	}
	else {
		document.getElementById("sourceAddress").dir = "ltr";
		document.getElementById("destinationAddress").dir = "ltr";
	}
	
	updateView();
	
	var point = new LatLong(_pos[0],_pos[1]);
	map.setCenterPosition(point,_pos[2]);

	routeTabInnerHtml = getMultiRouteHtml("","","",false);
	if (currentSideView=="4")
		clearRouteAll();

	randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
	ajaxpage(currentURLSite+"/inc/setSettings.asp?countrycode="+lastCountryCode+"&randomNumber="+randomNumber,"","GET","4");
}
/////////////////////////////////////////////
function updateView() {
	if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise")) {
		if (currentSideView=="4") {
			if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise"))
				document.getElementById("road6TD").style.display = "";
		}
		if (!enableDisable) {
			if (screen.width!=800)
				document.getElementById("indexCitiesTD").style.display = "";
			document.getElementById("indexCitiesTDIcon").style.display = "";
			flashButtons.runFunction("","enableDisable","true");
			enableDisable = true;
		}
	}
	else {
		if (currentSideView=="4") {
			if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise"))
				document.getElementById("road6TD").style.display = "none";
		}
		if (enableDisable) {
			if (screen.width!=800)
				document.getElementById("indexCitiesTD").style.display = "none";
			document.getElementById("indexCitiesTDIcon").style.display = "none";
			flashButtons.runFunction("","enableDisable","false");
			enableDisable = false;
		}
	}
}
/////////////////////////////////////////////
function onLanguageSelectChange(_selectBox) {
	_language = _selectBox.options[_selectBox.selectedIndex].value;
	randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
	ajaxpage(currentURLSite+"/inc/setSettings.asp?lang="+_language+"&randomNumber="+randomNumber,"","GET","3");
}
/////////////////////////////////////////////
function setDefaultPosition() {
	mapPosition = map.getCenterPosition().getLat()+","+map.getCenterPosition().getLong()+","+map.getZoomLevel();
	Set_Cookie("defaultMapPosition", mapPosition, 30, "", "", ""); // Set the cookie for 30 days.
	
	document.getElementById("applyImg").style.display = "";
	setTimeout('document.getElementById("applyImg").style.display = "none";',1000);
	
	randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
	ajaxpage(currentURLSite+"/inc/Coordinate2Country.asp?Horizontal="+map.getCenterPosition().getLong()+"&Vertical="+map.getCenterPosition().getLat()+"&Projection=LatLon&randomNumber="+randomNumber,"","GET","5");
}
/////////////////////////////////////////////
function findAddress() {
	document.getElementById("sourceAddress").className = "InputBox";
	fisrtClickOnInput = false;
	
	var address = document.getElementById("sourceAddress").value;
	
	if (address=="") {
		alert(alert1);					   
		return false;
	}
	numberOfNodes = 2;
	clearRoute();
	hideBubble();
	if (currentSideView!="4") {
		strHTML = getMultiRouteHtml("","","",false);
		setSideView("4",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
	}

	map.showWaitingMessage();
	map.setCenterPosition(new Address(address),"",lastCountryCode);			   
}
/////////////////////////////////////////////
function findRoute() {
	if (document.getElementById("sourceAddress").value=="") {
		alert(alert2);					   
		return false;
	}
	
	if (document.getElementById("destinationAddress").value=="") {
		alert(alert3);					   
		return false;
	}
	
	document.getElementById("sourceAddress").className = "InputBox";
	fisrtClickOnInput = false;
	
	numberOfNodes = 2;
	clearRoute();
	hideBubble();
	if (currentSideView!="4") {
		strHTML = getMultiRouteHtml("","","",false);
		setSideView("4",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
	}
	
	rowLength = getLastRowByNodeId();
	theTable = document.getElementById("addressesNodesTable");
	firstRowId = convertToInputId(theTable.rows[0].id);
	lastRowId = convertToInputId(theTable.rows[rowLength].id);
	document.getElementById(firstRowId).value=document.getElementById("sourceAddress").value
	document.getElementById(lastRowId).value=document.getElementById("destinationAddress").value

	isStandardRoute = true;
	map.showWaitingMessage();
	var addressS = new Address(document.getElementById("sourceAddress").value) 
	var addressD = new Address(document.getElementById("destinationAddress").value) 		   
	route.setOriginLocation(addressS)
	route.setDestinationLocation(addressD)
	map.showRoute(route,lastCountryCode)		   
}
/////////////////////////////////////////////
function convertToInputId(nodeId) {
	theId = nodeId.replace("TR","");
	return theId;
}
/////////////////////////////////////////////
function findMultiRoute() {
	rowLength = getLastRowByNodeId();
	theTable = document.getElementById("addressesNodesTable");
	
	for (i = 0; i <= rowLength; i++) {
		theId = convertToInputId(theTable.rows[i].id);
		if (document.getElementById(theId).value=="") {
			alert(alert1);
			//document.getElementById(theId).focus();
			return false;
		}
	}
	
	document.getElementById("sourceAddress").className = "InputBox";
	fisrtClickOnInput = false;
	
	theId = convertToInputId(theTable.rows[0].id);
	var addressS = new Address(document.getElementById(theId).value);
	route.setOriginLocation(addressS);

	if (rowLength>1) {
		for (i = 1; i < rowLength; i++) {
			theId = convertToInputId(theTable.rows[i].id);
			route.addLocation(new Address(document.getElementById(theId).value));
		}
	}
	
	theId = convertToInputId(theTable.rows[rowLength].id);
	var addressD = new Address(document.getElementById(theId).value);
	route.setDestinationLocation(addressD);

	hideBubble();
	map.showWaitingMessage();
	isStandardRoute = false;
	
	if (document.getElementById("fatestId").checked) {
		if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise")) {
			if (document.getElementById("road6").checked) {
				route.setType(Route.TYPE_FASTEST_WITH_TOLLWAY);
			} else {
				route.setType(Route.TYPE_FASTEST);
			}
		}
		else
			route.setType(Route.TYPE_FASTEST);
	} 
	else if (document.getElementById("shortestId").checked) {
		if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise")) {
			if (document.getElementById("road6").checked) {
				route.setType(Route.TYPE_SHORTEST_WITH_TOLLWAY);
			} else {
				route.setType(Route.TYPE_SHORTEST);
			}
		}
		else
			route.setType(Route.TYPE_SHORTEST);
	}
	else if (document.getElementById("pedestrianId").checked) {
		route.setType(Route.TYPE_PEDESTRIAN);
	}

	map.showRoute(route,lastCountryCode);
}
/////////////////////////////////////////////
function onRouteChanged(sender, route, newLocation, routeLocations) {
	isRouteExists = true;
	isRouteChange = true;
	map.showWaitingMessage();
	map.showRoute(route,lastCountryCode);
}
/////////////////////////////////////////////
function onRouteLocationChanged(sender, route, newLocation, routeLocations) {
	isRouteExists = true;
	isRouteLocationChange = true;
	map.showWaitingMessage();
	map.showRoute(route,lastCountryCode);
}
/////////////////////////////////////////////
function showHideRouteAnimation(_checkBox) {
	if (_checkBox.checked) {
		map.routeVectorLayer.showAnimation()
	} else {
		map.routeVectorLayer.hideAnimation()
	}
}
/////////////////////////////////////////////
function showHideRouteManeuvers(_checkBox) {
	if (_checkBox.checked) {
		map.routeVectorLayer.showManeuvers();
	} else {
		map.routeVectorLayer.hideManeuvers();
	}
}
/////////////////////////////////////////////
function clearRoute() {
	map.routeVectorLayer.clearRoute();
}
/////////////////////////////////////////////
function clearRouteAll() {
	clearRoute();
	routeTabInnerHtml = getMultiRouteHtml("","","",false);
	document.getElementById("contentDiv").innerHTML = routeTabInnerHtml;
	document.getElementById("sourceAddress").value = "";
	document.getElementById("destinationAddress").value = "";
}
/////////////////////////////////////////////
function onRouteResult() {
	setSideView("4",false);
	hideBubble();
	map.hideWaitingMessage();
	hideAllPushpins();
	if (layerTargetsFlag)
		layerTargets.removeAll();
	layerTargetsFlag = false;
	if (route.resultCode==1) {
		isRouteExists = true;
		map.routeVectorLayer.showAnimation();
		map.routeVectorLayer.showManeuvers();

		strHTML = getMultiRouteHtml(route.locations[0].geoResult.fullAddress.replace(", ישראל",""),route.locations[route.locations.length-1].geoResult.fullAddress.replace(", ישראל",""),route,true);
		numberOfNodes = route.locations.length;
		
		document.getElementById("contentDiv").innerHTML = strHTML;
		
		sourceGeocodeAddress = route.locations[0].geoResult.fullAddress.replace(", ישראל","");
		destGeocodeAddress   = route.locations[route.locations.length-1].geoResult.fullAddress.replace(", ישראל","");
		
		document.getElementById("sourceAddress").value = route.locations[0].geoResult.fullAddress.replace(", ישראל","");
		document.getElementById("destinationAddress").value = route.locations[route.locations.length-1].geoResult.fullAddress.replace(", ישראל","");
		
		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		for (i = 0; i <= rowLength; i++) {
			theId = convertToInputId(theTable.rows[i].id);
			document.getElementById(theId).value=route.locations[i].geoResult.fullAddress.replace(", ישראל","");
			document.getElementById(theId).style.border="#7F9DB9 solid 1px";
		}

		routeDescHTML = "<Table Width='236' dir='"+dir+"' align='center'>"
		routeDescHTML +=   "<TR><TD height='10'></TD></TR>"
		routeDescHTML +=   '<TR><td width="7"><TD colspan="4"><input type="checkbox" name="Maneuvers" id="Maneuvers" onclick="showHideRouteManeuvers(this)" checked><span style="cursor:pointer" onclick="document.getElementById(\'Maneuvers\').click()" class="smallText">'+showMilestones+'</span></TD></TR>'
		routeDescHTML +=   '<TR><td width="7"><TD colspan="4"><input type="checkbox" name="Animation" id="Animation" onclick="showHideRouteAnimation(this)" checked><span style="cursor:pointer" onclick="document.getElementById(\'Animation\').click()" class="smallText">'+showTrafficDirections+'</span></TD></TR>'
		routeDescHTML +=   '<TR><td width="7"><TD colspan="4"><A href="#" Class="LinkD" onclick="clearRouteAll();return false;">'+clearRouteTitle+'</a></TD></TR>'
		routeDescHTML +=   "<TR><TD height='5'></TD></TR>"
		routeDescHTML +=   '<TR><td width="7"><TD colspan="4" class="title">'+routeDescription+':</TD></TR>'
		routeDescHTML +=   '<TR><td width="7"><TD colspan="4" class="RouteDesc">'+route.description+'</TD></TR>'
		routeDescHTML +=   "<TR><TD height='5'></TD></TR>"
		
		_imgWidth  = 18
		_imgHeight = 21
		_imgSrc    = "None.gif"
		
		for (i=0;i<route.maneuversCount;i++) {
			switch (route.maneuversList[i].type.toLowerCase()) {
				case "start":
						_imgWidth  = 18
						_imgHeight = 21
						_imgSrc    = "Start.gif"
				break;
				case "middle":
						_imgWidth  = 21
						_imgHeight = 21
						_imgSrc    = "Straight.gif"
				break;
				case "end":
					if (i!=route.maneuversCount-1) {
						_imgWidth  = 18
						_imgHeight = 22
						_imgSrc    = "Middle.gif"
					}
					else {
						_imgWidth  = 18
						_imgHeight = 20
						_imgSrc    = "End.gif"
					}
				break;
				case "straight":
						_imgWidth  = 21
						_imgHeight = 21
						_imgSrc    = "Straight.gif"
				break;
				case "namechanged":
						_imgWidth  = 21
						_imgHeight = 21
						_imgSrc    = "Straight.gif"
				break;
				case "turn":
						_imgWidth  = 21
						_imgHeight = 21
						if (route.maneuversList[i].direction.toLowerCase()=="left") {
						  _imgSrc    = "TurnLeft.gif"
						} else {
						  _imgSrc    = "TurnRight.gif"
						}
				break;
				case "uturn":
						_imgWidth  = 21
						_imgHeight = 21
						_imgSrc    = "UTurn.gif"
				break;
				case "bear":
						_imgWidth  = 21
						_imgHeight = 21
						if (route.maneuversList[i].direction.toLowerCase()=="left") {
						  _imgSrc  = "BearLeft.gif"
						} else {
						  _imgSrc  = "BearRight.gif"
						}
				break;
				case "merge":
						_imgWidth  = 22
						_imgHeight = 21
						_imgSrc    = "Merge.gif"
				break;
				case "roundabout":
						_imgWidth  = 21
						_imgHeight = 21
						_imgSrc    = "Roundabout.gif"
				break;
				case "hwin":
						_imgWidth  = 22
						_imgHeight = 12
						_imgSrc    = "HwIn.gif"
				break;
				case "hwout":
						_imgWidth  = 22
						_imgHeight = 18
						_imgSrc    = "HWOut.gif"
				break;
				case "warning":
						
				break;
				case "poi":
						
				break;
				case "summary":
					_imgWidth  = 27
					_imgHeight = 12
					_imgSrc    = "ScaleLines.gif"
				break;
			}
			
			if (lastLanguage=="heb") {
				meters = " מ'"
				km = " ק\"מ"
			}
			else if (lastLanguage=="heb") {
				meters = " m"
				km = " km"
			}
			else {
				meters = " m"
				km = " km"
			}
			
			_lengthStr = route.maneuversList[i].length
			if (_lengthStr>0) {
				if (route.maneuversList[i].length<1000) {
					_lengthStr = route.maneuversList[i].length + meters
				} else {
					_length = Math.round(route.maneuversList[i].length / 100) / 10
					_lengthStr = _length + km
				}
			} else _lengthStr = ""
			routeDescHTML +=   "<TR><td width='7'></td><TD style='border-top:1px solid #DAE6F1'></TD><TD></TD><TD style='border-top:1px solid #DAE6F1'></TD><TD></TD><TD style='border-top:1px solid #DAE6F1'></TD></TR>"
			routeDescHTML +=   "<TR><TD height='3'></TD></TR>"
			routeDescHTML +=   "<TR Id='tr"+(i+1)+"'><td width='7'></td><TD Align='Center' style='padding-left:3px;padding-right:3px;'><Img Src='Images/Route/"+_imgSrc+"' Width='"+_imgWidth+"' Height='"+_imgHeight+"' hspace='0' vspace='0' Align='Center'></TD><TD width='12' align='center' valign='center'><div style='width:1px;height:16px;background-color:#DAE6F1;font-height:3px'></div></TD><TD Height='17' width='150' Class='RouteDesc' style='padding-right:4px'><a href='#' class='routeDescLink' onclick='map.setCenterPosition(new LatLong("+route.maneuversList[i].location.getLat()+","+route.maneuversList[i].location.getLong()+"),0);return false;'>"+ (i+1) +". "+route.maneuversList[i].description +"</a></TD><TD width='12' align='center' valign='center'><div style='width:1px;height:16px;background-color:#DAE6F1;font-height:3px'></div></TD><TD Width='40' Class='RouteDesc' style='padding-right:5px'>"+_lengthStr +"</TD></TR>"
			
			routeDescHTML +=   "<TR><TD height='3'></TD></TR>"
		}
		routeDescHTML +=   "<TR><TD height='5'></TD></TR>"
		routeDescHTML +=		 "</Table>"	
		
		document.getElementById("routeDescriptionTD").innerHTML = routeDescHTML;
	}
	else if (route.resultCode==2) {
		firstMultiLocation = "";
		for (i = 0; i <= route.locations.length; i++) {
			if (route.locations[i].resultCode == 2) {
				firstMultiLocation = i;
				break;
			}
		}
		
		if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
			_dir = "rtl";
			_align = "right";
		}
		else {
			_dir = "ltr";
			_align = "left";
		}

		geoCode = route.locations[firstMultiLocation];

		lastTargetPostion = geoCode.geoResultList[0].coordinate;
		lastGeocodeResult = geoCode;
		map.hideWaitingMessage();
		errorStrHTML ="<Table width='234' height='80%' align='"+_align+"' dir='"+_dir+"' valign='top' cellpadding='0' cellspacing='0'>"
		errorStrHTML += '<tr><td height="15"></td></tr>';
		errorStrHTML += '<tr align="'+pageAlign+'"><td width="10"></td><td colspan="2" width="230" dir="'+dir+'">'+multiAddressFound+'</td></tr>';
		errorStrHTML += '<tr><td height="15"></td></tr>';
		for (var i=0;i<geoCode.geoResultList.length;i++) {
			errorStrHTML += getAddressParts(geoCode.geoResultList[i],_align,_dir,'Images/Target.png',36,38,'unknown',firstMultiLocation);
			errorStrHTML += '<tr><td height="15"></td></tr>';
			
			targetMarker = new Marker("targets",geoCode.geoResultList[i].coordinate,targetIcon,"","")
			layerTargets.addShape(targetMarker)	
			layerTargets.redraw();
		}
		layerTargetsFlag = true;
		errorStrHTML += '<tr><td height="50%"></td></tr>';
		errorStrHTML +="</Table>"

		map.fitMap(layerTargets);

		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		foundFirst = false;
		for (i = 0; i <= rowLength; i++) {
			theId = convertToInputId(theTable.rows[i].id);
			if ((route.locations[i].resultCode==2) && (foundFirst==false)) {
				document.getElementById(theId).style.border="red solid 1px";
				foundFirst = true;
			}
			else
				document.getElementById(theId).style.border="#7F9DB9 solid 1px";
		}
		clearRoute();
			
		document.getElementById("routeDescriptionTD").innerHTML = errorStrHTML;	
	}
	else {
		if (isRouteLocationChange) {
			if (typeof route.locations[0].geoResult.fullAddress != 'undefined')
				tempSource = route.locations[0].geoResult.fullAddress.replace(", ישראל","");
			else
				tempSource = "";
			if (typeof route.locations[route.locations.length-1].geoResult.fullAddress != 'undefined')
				tempDestination = route.locations[route.locations.length-1].geoResult.fullAddress.replace(", ישראל","");
			else
				tempDestination = "";
			strHTML = getMultiRouteHtml(tempSource,tempDestination,route,true);
			numberOfNodes = route.locations.length;
			
			document.getElementById("contentDiv").innerHTML = strHTML;
		}
		
		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		firstRowId = convertToInputId(theTable.rows[0].id);
		lastRowId = convertToInputId(theTable.rows[rowLength].id);
		document.getElementById("sourceAddress").value=document.getElementById(firstRowId).value;
		document.getElementById("destinationAddress").value=document.getElementById(lastRowId).value;

		if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
			_dir = "rtl";
			_align = "right";
		}
		else {
			_dir = "ltr";
			_align = "left";
		}

		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		
		if (isStandardRoute) {
			firstId = convertToInputId(theTable.rows[0].id);
			secondId = convertToInputId(theTable.rows[rowLength].id);
			if (route.locations[0].resultCode!=1) {
				document.getElementById(firstId).style.border="red solid 1px";
				if (isRouteChange)
					document.getElementById(firstId).value="";
			}
			else
				document.getElementById(firstId).style.border="#7F9DB9 solid 1px";
			if (route.locations[1].resultCode!=1) {
				document.getElementById(secondId).style.border="red solid 1px";
				if (isRouteChange)
					document.getElementById(secondId).value="";
			}
			else
				document.getElementById(secondId).style.border="#7F9DB9 solid 1px";
		}
		else {
			for (i = 0; i <= rowLength; i++) {
				theId = convertToInputId(theTable.rows[i].id);
				if (route.locations[i].resultCode!=1) {
					document.getElementById(theId).style.border="red solid 1px";
					if (isRouteChange)
						document.getElementById(theId).value="";
				}
				else
					document.getElementById(theId).style.border="#7F9DB9 solid 1px";
			}
		}
		
		clearRoute();
		if (isRouteChange)
			showRouteErrorMessage(couldNotFound,_dir,_align);
		else if (isRouteLocationChange)
			showRouteErrorMessage(couldNotFound,_dir,_align);
		else
			showRouteErrorMessage(routeWrong,_dir,_align);
	}
	isRouteChange = false;
	isRouteLocationChange = false;
	saveCurrentRouteTabInnerHtml();
}
/////////////////////////////////////////////
function onKeyUpEvent(Event,e) {
	var unicode=e.keyCode? e.keyCode : e.charCode;
	if((unicode == 13) && (Event=="findAddress"))
		findAddress();
	else if((unicode == 13) && (Event=="findRoute"))
		findRoute();
	else if((unicode == 13) && (Event=="findMultiRoute"))
		findMultiRoute();
}
/////////////////////////////////////////////
function changeInputView() {
	if (fisrtClickOnInput) {
		document.getElementById("sourceAddress").value = "";
		document.getElementById("sourceAddress").className = "InputBox";
		fisrtClickOnInput = false;
	}
}
/////////////////////////////////////////////
function getAddressParts(geoCodeGeoResult,_align,_dir,imageSrc,imageWidth,imageHeight,type,num) {
	str1 = "";
	if (lastCountryCode.toLowerCase()=="isr") {
		if (geoCodeGeoResult.houseNumber!="")
			str1 = geoCodeGeoResult.street+" "+geoCodeGeoResult.houseNumber
		else if (geoCodeGeoResult.street!="")
			str1 = geoCodeGeoResult.street
	}
	else {
		if (geoCodeGeoResult.houseNumber!="")
			str1 = geoCodeGeoResult.houseNumber+" "+geoCodeGeoResult.street
		else if (geoCodeGeoResult.street!="")
			str1 = geoCodeGeoResult.street
	}
	
	str2 = "";
	if (geoCodeGeoResult.zipCode!="")
		str2 = geoCodeGeoResult.city+", "+geoCodeGeoResult.state+" "+geoCodeGeoResult.zipCode
	else if (geoCodeGeoResult.state!="")
		str2 = geoCodeGeoResult.city+", "+geoCodeGeoResult.state
	else if (geoCodeGeoResult.city!="")
		str2 = geoCodeGeoResult.city
		
	str3 = geoCodeGeoResult.country

	if (str1!="")
		strHTML ="<tr dir='"+_dir+"'><td width='5'></td><td align='"+_align+"' width='205' colspan='2'><table><tr><td>&nbsp;&nbsp;<img src='"+imageSrc+"' width='"+imageWidth+"' height='"+imageHeight+"' align='center'>&nbsp;&nbsp;</td><td><a href='#' onclick='cetnerPosToAddress("+geoCodeGeoResult.coordinate.getLat()+","+geoCodeGeoResult.coordinate.getLong()+","+geoCodeGeoResult.zoomLevel+",\""+geoCodeGeoResult.fullAddress.replace("'","&#39;")+"\",\""+type+"\",\""+num+"\")'><b>"+str1+"</b></a></br>"+str2+"</br>"+str3+"</td></tr></table></td></tr>"
	else if (str2!="")
		strHTML ="<tr dir='"+_dir+"'><td width='5'></td><td align='"+_align+"' width='205' colspan='2'><table><tr><td>&nbsp;&nbsp;<img src='"+imageSrc+"' width='"+imageWidth+"' height='"+imageHeight+"' align='center'>&nbsp;&nbsp;</td><td><a href='#' onclick='cetnerPosToAddress("+geoCodeGeoResult.coordinate.getLat()+","+geoCodeGeoResult.coordinate.getLong()+","+geoCodeGeoResult.zoomLevel+",\""+geoCodeGeoResult.fullAddress.replace("'","&#39;")+"\",\""+type+"\",\""+num+"\")'><b>"+str2+"</b></a></br>"+str3+"</td></tr></table></td></tr>"
	else
		strHTML ="<tr dir='"+_dir+"'><td width='5'></td><td align='"+_align+"' width='205' colspan='2'><table><tr><td>&nbsp;&nbsp;<img src='"+imageSrc+"' width='"+imageWidth+"' height='"+imageHeight+"' align='center'>&nbsp;&nbsp;</td><td><a href='#' onclick='cetnerPosToAddress("+geoCodeGeoResult.coordinate.getLat()+","+geoCodeGeoResult.coordinate.getLong()+","+geoCodeGeoResult.zoomLevel+",\""+geoCodeGeoResult.fullAddress.replace("'","&#39;")+"\",\""+type+"\",\""+num+"\")'><b>"+str3+"</b></a></td></tr></table></td></tr>"

	return strHTML;
}
/////////////////////////////////////////////
function enableDisableRoad6Checkbox(flag) {
	if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise")) {
		document.getElementById("road6").disabled = flag;
		if (flag)
			document.getElementById("road6").checked = false;
	}
}
/////////////////////////////////////////////
function getMultiRouteHtml(source,destination,routeObj,isMulti) {
	if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
		_dir = "rtl";
		_align = "right";
	}
	else {
		_dir = "ltr";
		_align = "left";
	}
	
	CurrentRouteType = Route.TYPE_FASTEST;
	if (routeObj!="")
		CurrentRouteType = routeObj.getType();
	
	switch(CurrentRouteType) {
		case Route.TYPE_FASTEST_WITH_TOLLWAY : 
			road6Current = "checked";
			fastestCurrent = "checked";
			shortestCurrent = "";
			pedestrianCurrent = "";
			road6Disabled = "";
			break;
		case Route.TYPE_SHORTEST_WITH_TOLLWAY : 
			road6Current = "checked";
			fastestCurrent = "";
			shortestCurrent = "checked";
			pedestrianCurrent = "";
			road6Disabled = "";
			break;
		case Route.TYPE_SHORTEST :
			road6Current = "";
			fastestCurrent = "";
			shortestCurrent = "checked";
			pedestrianCurrent = "";
			road6Disabled = "";
			break;
		case Route.TYPE_PEDESTRIAN :
			road6Current = "";
			fastestCurrent = "";
			shortestCurrent = "";
			pedestrianCurrent = "checked";
			road6Disabled = "disabled";
			break;
		default: // Route.TYPE_FASTEST
			road6Current = "";
			fastestCurrent = "checked";
			shortestCurrent = "";
			pedestrianCurrent = "";
			road6Disabled = "";
			break;
	}
	
	if ((lastCountryCode.toLowerCase()=="isr") || (lastCountryCode.toLowerCase()=="ise"))
		road6TDInnerHTML = '<input type="checkbox" name="road6" id="road6" '+road6Current+' '+road6Disabled+'><span style="cursor:pointer" onclick="document.getElementById(\'road6\').click()">'+throughKvish6Title+'</span>';
	else
		road6TDInnerHTML = '';
	
	clearAddressesNodesIdsArr();
	numberOfNodes = 2;
	nodesIds = 3;
	
	strHTML = '<table valign="top" cellpadding="0" cellspacing="0">';
	strHTML += '<tr><td height="15"></td></tr>';
	strHTML += '<tr><td>';
		strHTML +="<Table id='addressesNodesTable' width='250' height='80%' align='"+_align+"' dir='"+_dir+"' valign='top' cellpadding='0' cellspacing='0'>"
			
			if ((isMulti) || (routeObj!="")) {
				if (routeObj.locations.length!=2)
					strHTML += '<tr id="address1TR" height="30"><td width="10"></td><td><img src="Images/Route/Start.gif" width="18" height="21" alt="'+sourcePoint+'" title="'+sourcePoint+'"></td><td width="8"></td><td><input title="'+sourcePoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address1" id="address1" currentLocation="1" value="'+source+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"><a href="#" onclick="javascript:removeNodeRow(\'address1TR\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a></td></tr>';
				else
					strHTML += '<tr id="address1TR" height="30"><td width="10"></td><td><img src="Images/Route/Start.gif" width="18" height="21" alt="'+sourcePoint+'" title="'+sourcePoint+'"></td><td width="8"></td><td><input title="'+sourcePoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address1" id="address1" currentLocation="1" value="'+source+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"></td></tr>';
				
				for (i = 1; i < routeObj.locations.length-1; i++) {
					if (typeof routeObj.locations[i].geoResult.fullAddress != 'undefined')
						tempAddress = routeObj.locations[i].geoResult.fullAddress.replace(", ישראל","");
					else
						tempAddress = "";
					strHTML += '<tr id="address'+nodesIds+'TR" height="30"><td width="10"></td><td><img src="Images/Route/Middle.gif" width="18" height="21" alt="'+middlePoint+'" title="'+middlePoint+'"></td><td width="8"></td><td><input title="'+middlePoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address'+nodesIds+'" id="address'+nodesIds+'" currentLocation="'+nodesIds+'" value="'+tempAddress+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"><a href="#" onclick="javascript:removeNodeRow(\'address'+nodesIds+'TR\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a></td></tr>';
					
					addressesNodesIdsArr.push('address'+nodesIds+'TR');
					numberOfNodes++;
					nodesIds++;
				}
				
				if (routeObj.locations.length!=2)
					strHTML += '<tr id="address2TR" height="30"><td width="10"></td><td><img src="Images/Route/End.gif" width="18" height="20" alt="'+destinationPoint+'" title="'+destinationPoint+'"></td><td width="8"></td><td><input title="'+destinationPoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address2" id="address2" currentLocation="2" value="'+destination+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"><a href="#" onclick="javascript:removeNodeRow(\'address2TR\');return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" align="center" alt="'+closeTitle+'" title="'+closeTitle+'"></a></td></tr>';
				else
					strHTML += '<tr id="address2TR" height="30"><td width="10"></td><td><img src="Images/Route/End.gif" width="18" height="20" alt="'+destinationPoint+'" title="'+destinationPoint+'"></td><td width="8"></td><td><input title="'+destinationPoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address2" id="address2" currentLocation="2" value="'+destination+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"></td></tr>';
			}
			else {
				strHTML += '<tr id="address1TR" height="30"><td width="10"></td><td><img src="Images/Route/Start.gif" width="18" height="21" alt="'+sourcePoint+'" title="'+sourcePoint+'"></td><td width="8"></td><td><input title="'+sourcePoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address1" id="address1" currentLocation="1" value="'+source+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"></td></tr>';
				strHTML += '<tr id="address2TR" height="30"><td width="10"></td><td><img src="Images/Route/End.gif" width="18" height="20" alt="'+destinationPoint+'" title="'+destinationPoint+'"></td><td width="8"></td><td><input title="'+destinationPoint+'" type="text" class="InputBox" tabindex="33" style="width:180px" name="address2" id="address2" currentLocation="2" value="'+destination+'" onkeyup="onKeyUpEvent(\'findMultiRoute\',event)"></td><td width="25"></td></tr>';
			}
		strHTML += "</Table>"
	strHTML += '</tr></td>';
	strHTML += '<tr><td>';
		strHTML +="<Table align='"+pageAlign+"' dir='"+dir+"' valign='top' cellpadding='0' cellspacing='0'>"
		strHTML += '<tr><td width="10"></td><td></td><td width="8"></td><td><a href="#" onclick="addRowNode()">'+addDestination+'</a></td><td width="15"></td></tr>';
		
		strHTML += '<tr><td width="10"></td><td></td><td width="8"></td><td><iframe src="inc/getAds.asp?id=3" width="240" height="70" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe></td><td width="15"></td></tr>';
		
		strHTML += '</table>';
	strHTML += '</tr></td>';
	strHTML += '<tr><td height="10"></td></tr>';
	
	strHTML += '<tr><td>';
		strHTML +="<Table class='smallText' align='"+pageAlign+"' dir='"+dir+"' valign='top' cellpadding='0' cellspacing='0'>"
		strHTML += '<tr><td width="10"></td><td colspan="4">'+options+':</td></tr>';
		strHTML += '<tr><td width="10"></td><td><input type="radio" name="option" value="fatest" id="fatestId" '+fastestCurrent+' onclick="enableDisableRoad6Checkbox(false)"><span style="cursor:pointer" onclick="document.getElementById(\'fatestId\').click()">'+fastTitle+'</span> &nbsp;&nbsp;</td><td><input type="radio" name="option" value="shortest" id="shortestId" '+shortestCurrent+' onclick="enableDisableRoad6Checkbox(false)"><span style="cursor:pointer" onclick="document.getElementById(\'shortestId\').click()">'+shortTitle+'</span> &nbsp;&nbsp;</td><td style="display:none"><input type="radio" name="option" value="pedestrian" id="pedestrianId" '+pedestrianCurrent+' onclick="enableDisableRoad6Checkbox(true)"><span style="cursor:pointer" onclick="document.getElementById(\'pedestrianId\').click()">'+pedestrianTitle+'</span> &nbsp;&nbsp;</td></tr>';
		strHTML += '<tr><td width="10"></td><td colspan="3" id="road6TD">'+road6TDInnerHTML+'</td></tr>';
		strHTML += '<tr><td height="10"></td></tr>';
		strHTML += '<tr><td width="10"></td><td colspan="4"><input type="button" name="findRoute" value="'+findRouteTitle+'" class="BtnSmall" style="width:100px;height:23px" onclick="findMultiRoute()"></td></tr>';
		strHTML += '</table>';
	strHTML += '</tr></td>';
	
	strHTML += '<tr><td height="80%" id="routeDescriptionTD"></td></tr>';
	strHTML += '</table>';
	
	return strHTML;
}
routeTabInnerHtml = getMultiRouteHtml("","","",false);
/////////////////////////////////////////////
function onMapGeoResult(object,geoCode) {
	if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
		_dir = "rtl";
		_align = "right";
	}
	else {
		_dir = "ltr";
		_align = "left";
	}
	if (layerTargetsFlag)
		layerTargets.removeAll();
	hideAllPushpins();
	setSideView("4",false);
	isRouteExists = false;
	if (geoCode.resultCode==1) {
		map.hideTargetIcon();
		lastTargetPostion = geoCode.geoResult.coordinate;
		sourceGeocodeAddress = geoCode.geoResult.fullAddress.replace(", ישראל","");
		destGeocodeAddress = "";
		document.getElementById("sourceAddress").value = geoCode.geoResult.fullAddress.replace(", ישראל","");
		document.getElementById("destinationAddress").value = "";
		
		lastGeocodeResult = geoCode;
		map.hideWaitingMessage();
		
		targetMarker = new Marker("targets",geoCode.geoResult.coordinate,targetIcon,"","");
		layerTargets.addShape(targetMarker);
		layerTargets.redraw();
		layerTargetsFlag = true;
		
		lastAddressParts = getAddressParts(geoCode.geoResult,_align,_dir,'Images/Target.png',36,38,'s',0);
		
		strHTML = getMultiRouteHtml(geoCode.geoResult.fullAddress.replace(", ישראל",""),"","",false);

		lastCity = geoCode.geoResult.city;
		lastStreet = geoCode.geoResult.street;
		lastHouseNumber = geoCode.geoResult.houseNumber;
		lastLatPoint = geoCode.geoResult.coordinate.getLat();
		lastLongPoint = geoCode.geoResult.coordinate.getLong();
	
		addBubble(lastAddressParts,lastLatPoint,lastLongPoint,"");
			
		document.getElementById("contentDiv").innerHTML = strHTML;
	}
	else if (geoCode.resultCode == 2) {
		lastTargetPostion = geoCode.geoResultList[0].coordinate;
		document.getElementById("sourceAddress").value = geoCode.geoResultList[0].fullAddress.replace(", ישראל","");
		lastGeocodeResult = geoCode;
		map.hideWaitingMessage();
		map.setCenterPosition(new LatLong(geoCode.geoResultList[0].coordinate.getLat(),geoCode.geoResultList[0].coordinate.getLong()),geoCode.geoResultList[0].zoomLevel);
		errorStrHTML ="<Table width='234' height='80%' align='"+_align+"' dir='"+_dir+"' valign='top' cellpadding='0' cellspacing='0'>"
		errorStrHTML += '<tr><td height="15"></td></tr>';
		errorStrHTML += '<tr align="'+pageAlign+'"><td width="10"></td><td colspan="2" width="230" dir="'+dir+'">'+multiAddressFound+'</td></tr>';
		errorStrHTML += '<tr><td height="15"></td></tr>';
		for (var i=0;i<geoCode.geoResultList.length;i++) {
			errorStrHTML += getAddressParts(geoCode.geoResultList[i],_align,_dir,'Images/Target.png',36,38,'s',0);
			errorStrHTML += '<tr><td height="15"></td></tr>';
			
			targetMarker = new Marker("targets",geoCode.geoResultList[i].coordinate,targetIcon,"","")
			layerTargets.addShape(targetMarker)	
			layerTargets.redraw();
		}
		layerTargetsFlag = true;
		errorStrHTML += '<tr><td height="50%"></td></tr>';
		errorStrHTML +="</Table>"
			
		//addBubble(strHTML,geoCode.geoResult.coordinate.getLat(),geoCode.geoResult.coordinate.getLong(),"");
		strHTML = getMultiRouteHtml(geoCode.geoResultList[0].fullAddress.replace(", ישראל",""),"","",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
		
		document.getElementById("routeDescriptionTD").innerHTML = errorStrHTML;
	}
	else if(geoCode.resultCode==-6) {
		lastTargetPostion = geoCode.geoResultList[0].coordinate;
		lastGeocodeResult = geoCode;
		map.hideWaitingMessage();
		errorStrHTML ="<Table width='234' height='80%' align='"+_align+"' dir='"+_dir+"' valign='top' cellpadding='0' cellspacing='0'>"
		errorStrHTML += '<tr><td height="15"></td></tr>';
		errorStrHTML += '<tr align="'+pageAlign+'"><td width="10"></td><td colspan="2" width="230" dir="'+dir+'">'+addressNotExactFound+'</td></tr>';
		errorStrHTML += '<tr><td height="15"></td></tr>';
		for (var i=0;i<geoCode.geoResultList.length;i++) {
			errorStrHTML += getAddressParts(geoCode.geoResultList[i],_align,_dir,'Images/Target.png',36,38,'s',0);
			errorStrHTML += '<tr><td height="15"></td></tr>';
			
			targetMarker = new Marker("targets",geoCode.geoResultList[i].coordinate,targetIcon,"","")
			layerTargets.addShape(targetMarker)	
			layerTargets.redraw();
		}
		layerTargetsFlag = true;
		errorStrHTML += '<tr><td height="50%"></td></tr>';
		errorStrHTML +="</Table>"
			
		//addBubble(strHTML,geoCode.geoResult.coordinate.getLat(),geoCode.geoResult.coordinate.getLong(),"");
		strHTML = getMultiRouteHtml("","","",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
		
		document.getElementById("routeDescriptionTD").innerHTML = errorStrHTML;
	}
	else if(geoCode.resultCode==-4) showErrorMessage(error4,_dir,_align);
	else if(geoCode.resultCode==-3) showErrorMessage(error3,_dir,_align);
	else if(geoCode.resultCode==-2) showErrorMessage(error2,_dir,_align);
	else if(geoCode.resultCode==-1) showErrorMessage(error1,_dir,_align);
	else if(geoCode.resultCode==0) showErrorMessage(error0,_dir,_align);
	if (!isMapSmall) {
		changeMapSize(dir)
	}
	saveCurrentRouteTabInnerHtml();
}
/////////////////////////////////////////////
function showErrorMessage(str,_dir,_align) { // Geocode
	map.hideWaitingMessage();

	theTable = document.getElementById("addressesNodesTable");
	theId = convertToInputId(theTable.rows[0].id);
	document.getElementById(theId).value=document.getElementById("sourceAddress").value;
	document.getElementById(theId).style.border="red solid 1px";

	strHTML ="<Table width='244' align='center' dir='"+dir+"' valign='top' cellpadding='0' cellspacing='0'>"
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+couldNotFound+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>\""+document.getElementById("sourceAddress").value+"\".</td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+reason+"<b> "+str+"</b></td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+suggestions+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure1+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure2+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure3+"</td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="</Table>"
	document.getElementById("routeDescriptionTD").innerHTML = strHTML;
}
/////////////////////////////////////////////
function showRouteErrorMessage(str,_dir,_align) { // Route
	map.hideWaitingMessage();
	strHTML ="<Table width='244' align='center' dir='"+dir+"' valign='top' cellpadding='0' cellspacing='0'>"
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+couldNotFoundRoute+"</td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+reason+"<b>"+str+"</b></td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+suggestions+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure1+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure6+" ("+document.getElementById('countriesList').options[document.getElementById('countriesList').selectedIndex].text+")."+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure3+"</td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="</Table>"
	document.getElementById("routeDescriptionTD").innerHTML = strHTML;
}
/////////////////////////////////////////////
function showRGErrorMessage(str,_dir,_align) { // RG
	strHTML ="<Table width='244' align='center' dir='"+dir+"' valign='top' cellpadding='0' cellspacing='0'>"
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+couldNotFound+".</td></tr>";
	strHTML +="<tr><td height='10'></td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'>"+suggestions+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure4+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure5+"</td></tr>";
	strHTML +="<tr><td width='10'></td><td align='"+pageAlign+"'><li>"+makeSure3+"</td></tr>";
	strHTML +="</Table>"
	document.getElementById("routeDescriptionTD").innerHTML = strHTML;
}
/////////////////////////////////////////////
function hideAllPushpins() {
	layerSourcePushpin.hide();
	layerDestPushpin.hide();
}
/////////////////////////////////////////////
function addLayer(name, icon){
	var layer = layersCollection.createRemoteVectorLayer(name)
	layer.setServerLayerId(name);
	layer.setDefaultIcon(new ExternalIcon(icon));
	if (dir=="ltr")
		layer.setURL("xml/LayersEng.asp");
	else
		layer.setURL("xml/LayersHeb.asp");
	layer.hide();
	layer.setMinZoom(-10)
	layersList.push(layer);
}
addLayer("SYM_4_Police_station"	    , "Images/LayersIcon/POI/SWF/Police.swf");
addLayer("SYM_8_Youth_hostel"	    , "Images/LayersIcon/POI/SWF/Hostels.swf");
addLayer("SYM_31_Cinema"	    , "Images/LayersIcon/POI/SWF/Cinema.swf");
addLayer("SYM_35_Car_Parking"		, "Images/LayersIcon/POI/SWF/parking.swf");
addLayer("SYM_32_Hotel"		, "Images/LayersIcon/POI/SWF/hotels.swf");
addLayer("SYM_33_Post_office"		    , "Images/LayersIcon/POI/SWF/post_office.swf");
addLayer("SYM_12_National_Parks"	, "Images/LayersIcon/POI/SWF/park.swf");
addLayer("SYM_55_Hospital"	, "Images/LayersIcon/POI/SWF/hospitals.swf");
addLayer("SYM_36_Synagogue"	    , "Images/LayersIcon/POI/SWF/synagogue.swf");
addLayer("SYM_40_Bus_terminal"	    , "Images/LayersIcon/POI/SWF/bus_station.swf");
addLayer("SYM_48_Pharmacy"	    , "Images/LayersIcon/POI/SWF/drugstore_is.swf");
addLayer("SYM_26_Spring"	    , "Images/LayersIcon/POI/SWF/Spring.swf");
addLayer("is_gas"	    , "Images/LayersIcon/POI/SWF/gas_station.swf");
addLayer("SYM_37_Theater"	    , "Images/LayersIcon/POI/SWF/theater.swf");
addLayer("SYM_5_Areal_Clinic"	    , "Images/LayersIcon/POI/SWF/hospitals_is.swf");
addLayer("SYM_10_Campsite"	    , "Images/LayersIcon/POI/SWF/camping.swf");
addLayer("SYM_17_Nature_point"	    , "Images/LayersIcon/POI/SWF/nature_points.swf");
addLayer("SYM_47_Monument"	    , "Images/LayersIcon/POI/SWF/monument.swf");
addLayer("SYM_52_Zoo"	    , "Images/LayersIcon/POI/SWF/zoo.swf");
addLayer("SYM_50_Rail_Station"	    , "Images/LayersIcon/POI/SWF/train_station.swf");
addLayer("SYM_53_Bay_Laguna"	    , "Images/LayersIcon/POI/SWF/marina.swf");
addLayer("SYM_23_Other_holy"	    , "Images/LayersIcon/POI/SWF/Other_holy.swf");
addLayer("SYM_22_Moslem_holy"	    , "Images/LayersIcon/POI/SWF/Mosque.swf");
addLayer("SYM_16_Municipal_site"	    , "Images/LayersIcon/POI/SWF/Municipal.swf");
addLayer("SYM_18_Other_point"	    , "Images/LayersIcon/POI/SWF/Spring.swf");
//addLayer("SYM_25_Bridge"	    , "Images/LayersIcon/POI/SWF/Bridge.swf");
//addLayer("SYM_34_Pedest_brdg"	    , "Images/LayersIcon/POI/SWF/Pedestrian_Bridge.swf");
addLayer("SYM_0_Spot_height"	    , "Images/LayersIcon/POI/SWF/Spring.swf");
addLayer("SYM_1_Observ_point"	    , "Images/LayersIcon/POI/SWF/Binoculars.swf");
addLayer("SYM_7_Heliport_fields"	    , "Images/LayersIcon/POI/SWF/Helicopter.swf");
addLayer("SYM_9_Picnic_Place"	    , "Images/LayersIcon/POI/SWF/Picnic.swf");
addLayer("SYM_20_Jewish_holy"	    , "Images/LayersIcon/POI/SWF/Holy_Jewish.swf");
addLayer("SYM_21_Christian_holy"	    , "Images/LayersIcon/POI/SWF/Holy_Christian.swf");
addLayer("SYM_14_Jewish_Fund"	    , "Images/LayersIcon/POI/SWF/Forest.swf");
addLayer("SYM_44_Info_center"	    , "Images/LayersIcon/POI/SWF/Tourists.swf");
addLayer("SYM_49_Hydro_Site"	    , "Images/LayersIcon/POI/SWF/Hydro.swf");
addLayer("SYM_51_Embassy"	    , "Images/LayersIcon/POI/SWF/Embassy.swf");
addLayer("SYM_19_Archaeologic"	    , "Images/LayersIcon/POI/SWF/Archeological.swf");
addLayer("SYM_46_Amphitheater"	    , "Images/LayersIcon/POI/SWF/Amphitheatre.swf");
addLayer("SYM_52_Consulate"	    , "Images/LayersIcon/POI/SWF/Consulate.swf");
addLayer("SYM_2_Restrict_observ"	    , "Images/LayersIcon/POI/SWF/Spring.swf");
addLayer("SYM_51_Other_site"	    , "Images/LayersIcon/POI/SWF/Spring.swf");
addLayer("SYM_15_Field_School"	    , "Images/LayersIcon/POI/SWF/Field_School.swf");
/////////////////////////////////////////////
function showHideLayer(checkBox,layerName){
	//if ((checkBox.checked) && ((document.getElementById("countriesList").selectedIndex!=15) || (!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
	if ((checkBox.checked) && ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
		//document.getElementById("countriesList").selectedIndex=15;
		onCountrySelectChange(document.getElementById("countriesList"));
	}
	var layer = layersCollection.getLayerByName(layerName)
	if (checkBox.checked) {
		layer.show();
	} else {
		layer.hide();
	}
}
/////////////////////////////////////////////
function showHideRecycleLayer(checkBox,layerName){
	//if ((checkBox.checked) && ((document.getElementById("countriesList").selectedIndex!=15) || (!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
	if ((checkBox.checked) && ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
		//document.getElementById("countriesList").selectedIndex=15;
		onCountrySelectChange(document.getElementById("countriesList"));
	}
	if (checkBox.checked) {
		poi.getInst().showHideLayerExt(true,layerName);
	} else {
		poi.getInst().showHideLayerExt(false,layerName);
	}
}
/////////////////////////////////////////////
function showHideGroupLayer(checkBox,layersStr) {
	isCheckBoxClick=true;
	if ((checkBox.checked) && ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
		//document.getElementById("countriesList").selectedIndex=15;
		onCountrySelectChange(document.getElementById("countriesList"));
	}
	var layers_array=layersStr.split(",");
	if (checkBox.checked) {
		for (var i=0;i<layers_array.length;i++) {
			layersCollection.getLayerByName(layers_array[i]).show();
			document.getElementById(layers_array[i]).checked = true;
		}
	} else {
		for (var i=0;i<layers_array.length;i++) {
			layersCollection.getLayerByName(layers_array[i]).hide();
			document.getElementById(layers_array[i]).checked = false;
		}
	}
}
/////////////////////////////////////////////
function showHideRecycleGroupLayer(checkBox,layersStr) {
	isCheckBoxClick=true;
	if ((checkBox.checked) && ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -10))) {
		//document.getElementById("countriesList").selectedIndex=15;
		onCountrySelectChange(document.getElementById("countriesList"));
	}
	var layers_array=layersStr.split(",");
	if (checkBox.checked) {
		for (var i=0;i<layers_array.length;i++) {
			poi.getInst().showHideLayerExt(true,layers_array[i]);
			document.getElementById(layers_array[i]).checked = true;
		}
	} else {
		for (var i=0;i<layers_array.length;i++) {
			poi.getInst().showHideLayerExt(false,layers_array[i]);
			document.getElementById(layers_array[i]).checked = false;
		}
	}
}
/////////////////////////////////////////////
function setOriginPushpin(caption, coordinate) {
	document.getElementById("sourceAddress").className = "InputBox";
	fisrtClickOnInput = false;
	layerSourcePushpin.show();
	pushpinSourceMarker = setOriginDestPushpin(pushpinSourceMarker, layerSourcePushpin, coordinate, pushpinGeocodeS, "pushpinSource.png")
}
/////////////////////////////////////////////
function setDestinationPushpin(caption, coordinate) {
	document.getElementById("sourceAddress").className = "InputBox";
	fisrtClickOnInput = false;
	layerDestPushpin.show();
	pushpinDestMarker = setOriginDestPushpin(pushpinDestMarker, layerDestPushpin, coordinate, pushpinGeocodeD, "pushpinDest.png")
}
/////////////////////////////////////////////
function setOriginDestPushpin(marker, layer, coordinate, geocode, imagePath) {
	if (marker==null) {
		iconPath = "Images/" + imagePath
		var icon   = new ExternalIcon("images/iconLoader.swf?iconPath=" + iconPath);
		marker = new Marker("pushpinDest",coordinate,icon,"","")
		layer.addShape(marker)	
	} else {
		marker.setCoordinate(coordinate)
	}
	geocode.coordinateToAddress(coordinate);
	layer.redraw();
	return marker;
}
/////////////////////////////////////////////
function onGeocodePushpinSourceResult(sender, geocode) {
	if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
		_dir = "rtl";
		_align = "right";
	}
	else {
		_dir = "ltr";
		_align = "left";
	}
	if (layerTargetsFlag)
		layerTargets.removeAll();
	
	if (currentSideView!="4") {
		strHTML = getMultiRouteHtml("","","",false);
		setSideView("4",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
	}
	isRouteExists = false;

	if (geocode.resultCode!=-1) {
		hideAllPushpins();
		map.hideTargetIcon();
		sourceGeocodeAddress = geocode.geoResult.fullAddress.replace(", ישראל","");
		document.getElementById("sourceAddress").value = geocode.geoResult.fullAddress.replace(", ישראל","");
		map.hideWaitingMessage();
		
		lastAddressParts = getAddressParts(geocode.geoResult,_align,_dir,'Images/Target.png',36,38,'s',0);
		
		strHTML = getMultiRouteHtml(geocode.geoResult.fullAddress.replace(", ישראל",""),destGeocodeAddress,"",false);

		lastCity = geocode.geoResult.city;
		lastStreet = geocode.geoResult.street;
		lastHouseNumber = geocode.geoResult.houseNumber;
		lastLatPoint = geocode.geoResult.coordinate.getLat();
		lastLongPoint = geocode.geoResult.coordinate.getLong();
	
		addBubble(lastAddressParts,lastLatPoint,lastLongPoint,"");
		map.setCenterPosition(geocode.geoResult.coordinate);
		document.getElementById("contentDiv").innerHTML = strHTML;
		
		lastTargetPostion = geocode.geoResult.coordinate;
		lastGeocodeResult = geocode;

		if (destGeocodeAddress!="")
			findRoute();
	} else {
		hideBubble();
		clearRoute();
		sourceGeocodeAddress = "";
		document.getElementById("sourceAddress").value = "";
		showRGErrorMessage("Address not found",dir,pageAlign)
		
		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		
		firstId = convertToInputId(theTable.rows[0].id);
		document.getElementById(firstId).value="";
		document.getElementById(firstId).style.border="red solid 1px";
	}
	saveCurrentRouteTabInnerHtml();
}
/////////////////////////////////////////////
function onGeocodePushpinDestResult(sender, geocode) {
	if ((lastCountryCode.toLowerCase()=="isr") && (dir=="rtl")) {
		_dir = "rtl";
		_align = "right";
	}
	else {
		_dir = "ltr";
		_align = "left";
	}
	if (layerTargetsFlag)
		layerTargets.removeAll();
	
	if (currentSideView!="4") {
		strHTML = getMultiRouteHtml("","","",false);
		setSideView("4",false);
		document.getElementById("contentDiv").innerHTML = strHTML;
	}
	isRouteExists = false;
	
	if (geocode.resultCode!=-1) {
		hideAllPushpins();
		map.hideTargetIcon();
		destGeocodeAddress = geocode.geoResult.fullAddress.replace(", ישראל","");
		document.getElementById("destinationAddress").value = geocode.geoResult.fullAddress.replace(", ישראל","");
		map.hideWaitingMessage();
		
		lastAddressParts = getAddressParts(geocode.geoResult,_align,_dir,'Images/Target.png',36,38,'s',0);

		strHTML = getMultiRouteHtml(sourceGeocodeAddress,geocode.geoResult.fullAddress.replace(", ישראל",""),"",false);

		lastCity = geocode.geoResult.city;
		lastStreet = geocode.geoResult.street;
		lastHouseNumber = geocode.geoResult.houseNumber;
		lastLatPoint = geocode.geoResult.coordinate.getLat();
		lastLongPoint = geocode.geoResult.coordinate.getLong();
	
		addBubble(lastAddressParts,lastLatPoint,lastLongPoint,"");
		document.getElementById("contentDiv").innerHTML = strHTML;
		
		lastTargetPostion = geocode.geoResult.coordinate;
		lastGeocodeResult = geocode;

		if (sourceGeocodeAddress!="")
			findRoute();
	} else {
		hideBubble();
		clearRoute();
		destGeocodeAddress = "";
		document.getElementById("destinationAddress").value = "";
		showRGErrorMessage("Address not found",dir,pageAlign)

		rowLength = getLastRowByNodeId();
		theTable = document.getElementById("addressesNodesTable");
		
		secondId = convertToInputId(theTable.rows[rowLength].id);
		document.getElementById(secondId).value="";
		document.getElementById(secondId).style.border="red solid 1px";
	}
	saveCurrentRouteTabInnerHtml();
}
/////////////////////////////////////////////
function onResultListClick(_resultList,_type) {
	document.getElementById("sourceAddress").value = _resultList.options[_resultList.selectedIndex].text
	_val = _resultList.options[_resultList.selectedIndex].value
	_splitVal = _val.split("^")
	_point = new LatLong(_splitVal[0],_splitVal[1])
	map.setCenterPosition(_point,_splitVal[2])
}
/////////////////////////////////////////////
function findPos(obj) { // Find the position of the obj.
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
/////////////////////////////////////////////
function setDivPosition(nearById,sourceDivId) { // Set the position of the div near to the nearById div.
	var temp;
	temp = findPos(document.getElementById(nearById));
	leftPos = temp[0];
	topPos = temp[1];
	document.getElementById(sourceDivId).style.left = leftPos+"px";
	document.getElementById(sourceDivId).style.top = topPos+"px";
	document.getElementById(sourceDivId).style.display = "";
}
/////////////////////////////////////////////
function disappearDiv(sourceDivId) { // Disappear the div.
	document.getElementById(sourceDivId).style.display = "none";
}
/////////////////////////////////////////////
function showHomeAddress(caption, coordinate) {
	function onRgeocodeResult2() {
		map.hideWaitingMessage();
		if ((Rgeocode.geoResult.houseNumber!="") & (Rgeocode!=null) && (Rgeocode.resultCode!=-1) && (Rgeocode.resultCode!=null) && (lastCountryCode=="ISR")) {
			var address = Rgeocode.geoResult;
			url = "http://www.ymap.co.il/Navigate.aspx?tab=1&CityNmS="+escape(address.city)+"&StreetNmS="+escape(address.street)+"&HouseNbrS="+address.houseNumber+"&Mode=1";
			
			window.open(url,"new");
		}
		else {
			alert("מספר בית לא נמצא");
		}
	}
	if (lastCountryCode=="ISR") {
		var Rgeocode = new Geocode();
		map.showWaitingMessage();
		Rgeocode.coordinateToAddress(coordinate);
		Rgeocode.addListener(Geocode.EVENT_GEO_RESULT,onRgeocodeResult2);
	}
}
/////////////////////////////////////////////
function getBrowserHeight() {
	var intH = 0;
	var intW = 0;
	if(typeof window.innerWidth  == 'number' ) {
	   intH = window.innerHeight;
	   intW = window.innerWidth;
	} 
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		intH = document.documentElement.clientHeight;
		intW = document.documentElement.clientWidth;
	}
	else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
		intH = document.body.clientHeight;
		intW = document.body.clientWidth;
	}
	return { width: parseInt(intW), height: parseInt(intH) };
}
/////////////////////////////////////////////
function setLayerPosition(shadowId, popUpId) {
	var shadow = document.getElementById(shadowId);
	var question = document.getElementById(popUpId);
	var bws = getBrowserHeight();
	shadow.style.width = bws.width + "px";
	shadow.style.height = bws.height + "px";
	if (popUpId=="forecastDiv") {
		question.style.left = parseInt((bws.width - 520) / 2);
		question.style.top = parseInt((bws.height - 220) / 2);
	}
	else if (popUpId=="adsDiv") {
		question.style.left = parseInt((bws.width - 500) / 2);
		question.style.top = parseInt((bws.height - 500) / 2);
	}
	else {
		question.style.left = parseInt((bws.width - 350) / 2);
		question.style.top = parseInt((bws.height - 200) / 2);
	}
	shadow = null;
	question = null;
}
/////////////////////////////////////////////
function showLayer(shadowId, popUpId) {
	setLayerPosition(shadowId, popUpId);
	var shadow = document.getElementById(shadowId);
	var question = document.getElementById(popUpId);
	shadow.style.display = "block"; 
	question.style.display = "block";
	shadow = null;
	question = null;             
}
/////////////////////////////////////////////
function hideLayer(shadowId, popUpId) {
	var shadow = document.getElementById(shadowId);
	var question = document.getElementById(popUpId);
	shadow.style.display = "none"; 
	question.style.display = "none";
	shadow = null;
	question = null; 
}
/////////////////////////////////////////////
function setHeightOfInfoDiv(flag) {
	if (flag)
		extra = 47;
	else
		extra = 11;
	if (window.ActiveXObject) // if IE
		document.getElementById("infoDiv").style.height = document.body.clientHeight - 149 + extra;
	else
		document.getElementById("infoDiv").style.height = document.body.clientHeight - 147 + extra;
}
/////////////////////////////////////////////
function setLayerPositionCommands() {
	setLayerPosition('shadow','sendToFriendDiv');
	if (dir=="ltr") {
		if (isOverviewVisible)
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(200,25))",500);
		else
			setTimeout("map.setAtlasCTLogoPosition(Map.ALIGN_BOTTOM_RIGHT,new ScreenPoint(90,25))",500);
	}
	setHeightOfInfoDiv(false);
	if (screen.width==800)
		document.getElementById("indexCitiesTD").style.display = "none";
}
window.onresize = setLayerPositionCommands;
/////////////////////////////////////////////
function addWeatherTrafficLayers(name) {
   var layer = layersCollection.createRemoteVectorLayer(name)
   layer.setServerLayerId(name);
   var iconsList = new Array();
   if (name.toLowerCase()=='traffic') {
	   iconsList.push(new ExternalIcon("Images/LayersIcon/Traffic/0.swf"))
	   iconsList.push(new ExternalIcon("Images/LayersIcon/Traffic/1.swf"))
	   iconsList.push(new ExternalIcon("Images/LayersIcon/Traffic/2.swf"))
	   if (dir=="rtl")
		layer.setURL("xml/Traffic.asp",true)
	   else
		layer.setURL("xml/TrafficEng.asp",true)
   } else {
	   for (var i=1;i<=23;i++) {
		   if (i<10) {
			 iconNum = "0" + i
		   } else {
			 iconNum = i
		   }
		   iconsList.push(new ExternalIcon("Images/LayersIcon/Weather/"+ iconNum +".swf"))
	   }
	   iconsList[26] = "17"
	   iconsList[29] = "17"
	   iconsList[30] = "01"

	   layer.setURL("xml/Weather.asp",true)	
   }
   layer.setIconsList(iconsList);

   layer.hide();
   layersList.push(layer);
}
addWeatherTrafficLayers("Traffic");
addWeatherTrafficLayers("Weather");
/////////////////////////////////////////////
function onIconMouseMove(div, type) {
		if (type.toLowerCase()=='weather') {
			if ((BrowserDetect.browser.toLowerCase()=="firefox") || (BrowserDetect.browser.toLowerCase()=="chrome") || (BrowserDetect.browser.toLowerCase()=="safari")) {
				if (dir=="rtl")
					document.getElementById("WeatherIcon").src = 'Images/Icons/WeatherIconEnable.png'
				else
					document.getElementById("WeatherIcon").src = 'Images/Icons/WeatherIconEngEnable.png'
			} else {
				if (dir=="rtl")
					document.getElementById("WeatherIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/WeatherIconEnable.png' ,sizingMethod=’crop’)"
				else
					document.getElementById("WeatherIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/WeatherIconEngEnable.png' ,sizingMethod=’crop’)"
			}
		} else {
			if ((BrowserDetect.browser.toLowerCase()=="firefox") || (BrowserDetect.browser.toLowerCase()=="chrome") || (BrowserDetect.browser.toLowerCase()=="safari")) {
				if (dir=="rtl")
					document.getElementById("TrafficIcon").src = 'Images/Icons/TrafficIconEnable.png'
				else
					document.getElementById("TrafficIcon").src = 'Images/Icons/TrafficIconEngEnable.png'
			} else {
				if (dir=="rtl")
					document.getElementById("TrafficIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/TrafficIconEnable.png' ,sizingMethod=’crop’)"
				else
					document.getElementById("TrafficIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/TrafficIconEngEnable.png' ,sizingMethod=’crop’)"
			}
		}
}
/////////////////////////////////////////////
function onIconMouseOut(div, type) {
	if (type.toLowerCase()=='weather') {
		if (!isWeatherEnabled) {	
			if ((BrowserDetect.browser.toLowerCase()=="firefox") || (BrowserDetect.browser.toLowerCase()=="chrome") || (BrowserDetect.browser.toLowerCase()=="safari")) {
				if (dir=="rtl")
					document.getElementById("WeatherIcon").src = 'Images/Icons/WeatherIconDisable.png'
				else
					document.getElementById("WeatherIcon").src = 'Images/Icons/WeatherIconEngDisable.png'
			} else {
				if (dir=="rtl")
					document.getElementById("WeatherIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/WeatherIconDisable.png' ,sizingMethod=’crop’)"
				else
					document.getElementById("WeatherIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/WeatherIconEngDisable.png' ,sizingMethod=’crop’)"
			}
		}
	} else {
		if (!isTrafficEnabled) {	
			if ((BrowserDetect.browser.toLowerCase()=="firefox") || (BrowserDetect.browser.toLowerCase()=="chrome") || (BrowserDetect.browser.toLowerCase()=="safari")) {
				if (dir=="rtl")
					document.getElementById("TrafficIcon").src = 'Images/Icons/TrafficIconDisable.png'
				else
					document.getElementById("TrafficIcon").src = 'Images/Icons/TrafficIconEngDisable.png'
			} else {
				if (dir=="rtl")
					document.getElementById("TrafficIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/TrafficIconDisable.png' ,sizingMethod=’crop’)"
				else
					document.getElementById("TrafficIcon").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Icons/TrafficIconEngDisable.png' ,sizingMethod=’crop’)"
			}
		}
	}		
}
/////////////////////////////////////////////
function trafficIntervalFunction() {
	var layer = layersCollection.getLayerByName("Traffic")
	layer.redraw();
	showTrafficInformationDiv();
}
/////////////////////////////////////////////
function onIconClick(div, type) {
	if (type.toLowerCase()=='weather') {
		//showHideWeather();
		if (isWeatherEnabled) {
			poi.getInst().showHideLayerExt(false,"SYM_WEATHER_DEFAULT");
			isWeatherEnabled = false;
			if (currentSideView=="2")
				setSideView("1","");
		} else {
			poi.getInst().showHideLayerExt(true,"SYM_WEATHER_DEFAULT");
			isWeatherEnabled = true;
			setSideView("2","");
		}
	} else {
		var layer = layersCollection.getLayerByName('Traffic');
		if (isTrafficEnabled) {
			clearInterval(trafficInterval)
			isTrafficEnabled = false;
			layer.hide();
			if (currentSideView=="3")
				setSideView("1","");
		} else {
			trafficInterval = setInterval(trafficIntervalFunction,1000 * 180) 
			isTrafficEnabled = true;
			layer.show();
			//if ((document.getElementById("countriesList").selectedIndex!=15) || (!isCountryInMapView("isr")) || (map.getZoomLevel() < -12)) {
			if ((!isCountryInMapView("isr")) || (map.getZoomLevel() < -12)) {
				//document.getElementById("countriesList").selectedIndex=15;
				onCountrySelectChange(document.getElementById("countriesList"));
			}
			setSideView("3","");
		}
		showTrafficInformationDiv();
	}
}
/////////////////////////////////////////////
function saveCurrentCheckedLayers() {
	layersSettingsArr = [];
	for (i = 0; i < layersNameArr.length; i++) {
		layersSettingsArr.push(document.getElementById(layersNameArr[i]).checked);
	}
}
/////////////////////////////////////////////
function getGeneralDefaultInnerHtml() {
	return generalDefaultInnerHtml;
}
/////////////////////////////////////////////
function showTrafficInformationDiv() {
	if (isTrafficEnabled) {
		randomNumber=Math.floor(Math.random()*1001); // Fixed for IE7
		if (dir=="rtl")
			ajaxpage(currentURLSite+"/inc/trafficform.asp?randomNumber="+randomNumber,"","GET","6");
		else
			ajaxpage(currentURLSite+"/inc/trafficformEng.asp?randomNumber="+randomNumber,"","GET","6");
	}
}
/////////////////////////////////////////////
function showHideWeather() {
	if (isWeatherEnabled) {
		if (currentSideView=="2")
			setSideView("1","");
			// document.getElementById("contentDiv").innerHTML = getGeneralDefaultInnerHtml();
	}
	else {
		showWeatherInfo();
	}
	if (!isMapSmall) {
		changeMapSize(dir)
	}
}
/////////////////////////////////////////////
function showWeatherInfo() {
	var weatherFlash = new Flash();	
	if (isUpMenuOpen) {
		if (window.ActiveXObject) // if IE
			heightWeather = document.body.clientHeight - 168;
		else
			heightWeather = document.body.clientHeight - 167;
	}
	else {
		if (window.ActiveXObject) // if IE
			heightWeather = document.body.clientHeight - 132;
		else
			heightWeather = document.body.clientHeight - 132;
	}
	if (dir=="rtl")
		weatherFlash.init("SearchMessage","234",heightWeather,"Weather/WeatherFlowHeb.swf?v=1.0.1","",true,"")
	else
		weatherFlash.init("SearchMessage","234",heightWeather,"Weather/WeatherFlowEng.swf?v=1.0.1","",true,"")
	document.getElementById("contentDiv").innerHTML = weatherFlash.getHtmlFlashTag();
}
/////////////////////////////////////////////
function showAds() {
	if (lang=="heb") {
		isAdsShown = Get_Cookie('adsShown');
		if (isAdsShown==null) {
			showLayer('shadow75','adsDiv');
			Set_Cookie("adsShown", "true", 30, "", "", "");
		}
	}
}
//window.onload = showAds;
/////////////////////////////////////////////
function showForecastInfo(li) {
	var forecastFlash = new Flash();	

	if (dir=="rtl")
		forecastFlash.init("Forecast","523","217","Weather/WeatherForecastHeb.swf?v=1.0.1&li="+li,"",true,"");
	else
		forecastFlash.init("Forecast","523","217","Weather/WeatherForecastEng.swf?v=1.0.1&li="+li,"",true,"");
	
	showLayer('shadow','forecastDiv');
	forecastFlash.writeFlashTo(document.getElementById("forecastDiv"));
}
/////////////////////////////////////////////
function onForecastClick(evt,args) {
	hideLayer('shadow','forecastDiv');
	document.getElementById("forecastDiv").innerHTML = "";
}
flashListener.addListener("Forecast",onForecastClick,"Press");
/////////////////////////////////////////////
function isIE() {
	if (document.all) {
		return true;
	} else {
		return false;
	}
}
/////////////////////////////////////////////
function hideBubble() {
	if (isBubbleShown) {
		isBubbleShown = false;
		map.removeOverlay('BubbleOverlay');
	}
}
/////////////////////////////////////////////
function addBubble(overlayHTML,latPoint,longPoint,_dir) {
	if (isBubbleShown)
		hideBubble();
	isBubbleShown = true;
	
   innerHTMLBubble = ""
	if (isIE()) {
		innerHTMLBubble += '<Div style=\'width:294px;height:212px;background-image: none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader( src="images/OverlayBG.png", sizingMethod="scale")\'>'
	} else {
		innerHTMLBubble += '<Div style=\'width:294px;height:212px;background-image:url("images/OverlayBG.png")\'>';
	}
   innerHTMLBubble += '<Div style=\'position:relative;width:294px;height:212px;\' align="center">';
   innerHTMLBubble +=	'<Table Width="235" Height="137" CellPadding="0" CellSpacing="0" align="center" dir="'+dir+'">';
   innerHTMLBubble +=		'<TR><td></td><td style="padding-top:14px">&nbsp;&nbsp;&nbsp;&nbsp;<b>'+addressTitle+'</b></td><TD Height="20" valign="Top" Align="'+reverseAlign+'" style="padding-top:7px;padding-right:4px;"><a href="#" onclick="javascript:hideBubble();return false;"><img src="Images/CloseButton.png" width="19" height="19" border="0" alt="'+closeTitle+'" title="'+closeTitle+'"></a></TD></TR>';
   innerHTMLBubble +=		overlayHTML;

   if ((lastCountryCode=="ISR") && (lastHouseNumber!="") && (dir=="rtl")) {
	innerHTMLBubble +=	'<tr><td></td><td colspan="2" height="20">&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.ymap.co.il/Navigate.aspx?tab=1&CityNmS='+escape(lastCity)+'&StreetNmS='+escape(lastStreet)+'&HouseNbrS='+lastHouseNumber+'&Mode=1" target="_blank">הצג תמונת בית</a></td></tr>';
   }
   
   innerHTMLBubble +=	'</Table>';
   innerHTMLBubble += '</Div>';

   var theDiv = document.createElement("div");
   var overlay = new Overlay("BubbleOverlay");
   theDiv.innerHTML = innerHTMLBubble;
   overlay.setDomElement(theDiv);
   overlay.setOffsetPosition(new ScreenCoordinate(-94,-185));
   map.addOverlayToMap(overlay, new LatLong(latPoint,longPoint),false);
}
/////////////////////////////////////////////
////// SimpleTreeMenu.js //////
var persisteduls=new Object()
var ddtreemenu=new Object()

ddtreemenu.closefolder="Images/plus.gif" //set image path to "closed" folder image
ddtreemenu.openfolder="Images/minus.gif" //set image path to "open" folder image

ddtreemenu.createTree=function(treeid, enablepersist, persistdays){
	var ultags=document.getElementById(treeid).getElementsByTagName("ul")
	if (typeof persisteduls[treeid]=="undefined")
		persisteduls[treeid]=(enablepersist==true && ddtreemenu.getCookie(treeid)!="")? ddtreemenu.getCookie(treeid).split(",") : ""
	for (var i=0; i<ultags.length; i++)
		ddtreemenu.buildSubTree(treeid, ultags[i], i)
	if (enablepersist==true){ //if enable persist feature
		var durationdays=(typeof persistdays=="undefined")? 1 : parseInt(persistdays)
		ddtreemenu.dotask(window, function(){ddtreemenu.rememberstate(treeid, durationdays)}, "unload") //save opened UL indexes on body unload
	}
}
var isCheckBoxClick = false;
ddtreemenu.buildSubTree=function(treeid, ulelement, index){
	ulelement.parentNode.className="submenu"
	if (typeof persisteduls[treeid]=="object"){ //if cookie exists (persisteduls[treeid] is an array versus "" string)
		if (ddtreemenu.searcharray(persisteduls[treeid], index)){
			ulelement.setAttribute("rel", "open")
			ulelement.style.display="block"
			ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
		}
		else
			ulelement.setAttribute("rel", "closed")
	} //end cookie persist code
	else if (ulelement.getAttribute("rel")==null || ulelement.getAttribute("rel")==false) //if no cookie and UL has NO rel attribute explicted added by user
		ulelement.setAttribute("rel", "closed")
	else if (ulelement.getAttribute("rel")=="open") //else if no cookie and this UL has an explicit rel value of "open"
		ddtreemenu.expandSubTree(treeid, ulelement) //expand this UL plus all parent ULs (so the most inner UL is revealed!)
	ulelement.parentNode.onclick=function(e){
		if (isCheckBoxClick)
			isCheckBoxClick = false;
		else {
			var submenu=this.getElementsByTagName("ul")[0]
			if (submenu.getAttribute("rel")=="closed"){
				submenu.style.display="block"
				submenu.setAttribute("rel", "open")
				ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
			}
			else if (submenu.getAttribute("rel")=="open"){
				submenu.style.display="none"
				submenu.setAttribute("rel", "closed")
				ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.closefolder+")"
			}
		}
		ddtreemenu.preventpropagate(e)
	}
	ulelement.onclick=function(e){
		ddtreemenu.preventpropagate(e)
	}
}

ddtreemenu.expandSubTree=function(treeid, ulelement){ //expand a UL element and any of its parent ULs
	var rootnode=document.getElementById(treeid)
	var currentnode=ulelement
	currentnode.style.display="block"
	currentnode.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
	while (currentnode!=rootnode){
		if (currentnode.tagName=="UL"){ //if parent node is a UL, expand it too
			currentnode.style.display="block"
			currentnode.setAttribute("rel", "open") //indicate it's open
			currentnode.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
		}
		currentnode=currentnode.parentNode
	}
}

ddtreemenu.flatten=function(treeid, action){ //expand or contract all UL elements
	var ultags=document.getElementById(treeid).getElementsByTagName("ul")
	for (var i=0; i<ultags.length; i++){
		ultags[i].style.display=(action=="expand")? "block" : "none"
		var relvalue=(action=="expand")? "open" : "closed"
		ultags[i].setAttribute("rel", relvalue)
		ultags[i].parentNode.style.backgroundImage=(action=="expand")? "url("+ddtreemenu.openfolder+")" : "url("+ddtreemenu.closefolder+")"
	}
}

ddtreemenu.rememberstate=function(treeid, durationdays){ //store index of opened ULs relative to other ULs in Tree into cookie
	var ultags=document.getElementById(treeid).getElementsByTagName("ul")
	var openuls=new Array()
	for (var i=0; i<ultags.length; i++){
		if (ultags[i].getAttribute("rel")=="open")
			openuls[openuls.length]=i //save the index of the opened UL (relative to the entire list of ULs) as an array element
	}
	if (openuls.length==0) //if there are no opened ULs to save/persist
		openuls[0]="none open" //set array value to string to simply indicate all ULs should persist with state being closed
	ddtreemenu.setCookie(treeid, openuls.join(","), durationdays) //populate cookie with value treeid=1,2,3 etc (where 1,2... are the indexes of the opened ULs)
}

ddtreemenu.preventpropagate=function(e){ //prevent action from bubbling upwards
	if (typeof e!="undefined")
		e.stopPropagation()
	else
		event.cancelBubble=true
}
/////////////////////////////////////////////
// Geolocation by Google.
function success(position) {
	var latlng = new LatLong(position.coords.latitude, position.coords.longitude);
	map.setCenterPosition(latlng,-3);
}
function error(msg) {
	alert(msg)
}
function getMyLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(success, error);
	} else {
		alert('not supported');
	}
}