//inputted values
var displayNow;//what to display now: 'countries' - c, 'states' - s or 'dealers' - d
var addedMarkersIds = [];
//if request performs too long we will ignore not needed values

///var inpContinent;
var inpCountry;
var inpState;
var inpCity;

var submitUrl;//url for which form would be submitted

var map;//google map object
var geocoder = new GClientGeocoder();//convert a string address into a GLatLng
var rwlogo = new GIcon();//Create an icon specifies the images used to display a GMarker on the map
	rwlogo.image = JS_EE_CDN_SERVER + 'images/sl-group-icon.png';//The foreground image URL of the icon.
	rwlogo.iconSize = new GSize(21,20);//The pixel size of the foreground image of the icon.
	rwlogo.iconAnchor = new GPoint(10,10);//The pixel coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.
	rwlogo.infoWindowAnchor = new GPoint(17,4);
var points = [];//array with point visible on map
var markers = [];//array with dealers markers on map
var oldMapBounds;//object which stored map size in coordinates
var oldZoomLevel;//value of previous zoom level
//var maxZoom = 7;//value of maximum level in what you will see dealers. Because there is may be situation when we need to display dealers, but we calculate such zoom what we output countries
var ignoreZoom = 0;//if we show all delaers from country we must ignore onZoom handle
var minZoom = 13;//value of minimum zoom level
var dealerSearchUrl = JS_EE_HTTP + JS_ACTION_FILE + '?action=get_all_dealers_from_country';
var mapMoveUrl = JS_EE_HTTP + JS_ACTION_FILE + '?action=handle_dealer_map_move';

/*****Variables only for quicksearch*****/
var longitude;//coordinates longitude of selected city
var latitude;//coordinates latitude of selected city
var gmarkers = [];//array with objects marked on map
var htmls = [];//arary with html captions of dealers
var pts = [];//array with point objects, store cordinates of dealers
var i = 0;//for dealer with marker
var j = 0;//for all dealers
var count = 0;//number of found dealers
var side_bar_html = [];//array with search results

//inputed values from get
var inpId;
var inpFrom;
var inpTo;
var inpDid;
var itineraryId;//parameter I of dealer which was selected last time for itinerary calculating
var positions = [];//dealers ids and its positions

var originalHeightOfSearchResults;//store value of container with serach results

/***** variable used only for itinerary *****/
var iMap;
var gdir;//for itinerary map
var gdir2;//for main map

/*** Dealers grouping ***/
var mc;//markerCluster
var countryMCStyle = {gridSize: 25, maxZoom: 9, styles: [{url:EEHttp + 'images/sl-group-icon-2.png', width: 21, height: 20, opt_textColor: '#321615'}]};//style for grouping dealers on countries level
var stateMCStyle = {gridSize: 30, maxZoom: 9, styles: [{url:EEHttp + 'images/sl-group-icon-2.png', width: 21, height: 20, opt_textColor: '#321615'}]};//style for grouping dealers on states level
var dealerMCStyle = {gridSize: 35, maxZoom: 12, styles: [{url:EEHttp + 'images/sl-group-icon-2.png', width: 21, height: 20, opt_textColor: '#321615'}]};//style for grouping dealers on high level of zoom

//Reducing Browser Memory Leaks
window.onunload = GUnload;

//function show all properties of object
function inspect(what) {
	var str = '';
	for(var i in what) {
		str += i+'='+what[i]+"\n";
	}
	alert(str);
}

//function converts to entitity ampersand sign
function escapeGet(value) {
	if(value) {//value = value.replace('=', '%3D');
		return value.replace('&', '%26');
	} else {
		return;
	}
}

//add trim property
String.prototype.trim = function() {
    var str = this;
    str = str.replace(/(^\s+)|(\s+$)/g, "");
    return str;
}

//function return countries list on changing continent
/**function getContinentCountries() {
	var strAjaxMessage = "action=return_list_of_countries&continent=" + $("#continent").val() + "&language=" + language;
	$.ajax({
		type: "GET",
		url: JS_EE_HTTP + JS_ACTION_FILE,
		data: strAjaxMessage,
		dataType: "text",
		success: function(response){
			$("#country").html(response);
			document.getElementById('store_locator_states').style.display = 'none';
			document.getElementById('location').disabled = false;
			$("#city").html('<option value="">'+noCityAvialable+'</option>');
		}
	});
	//hide all countries and show countries only from selected continent
	clearMap();
	showContinentCountries($('#continent :selected').attr('title'));
}**/

//function fires then states list is changed
function onStateChange() {
	getCountryCities();
}

//function return cities list on changing country
function getCountryCities() {
	var country = $("#country :selected").attr("title");
	
	if(country.toUpperCase() == "US"){
		if(!showUSStates){
			getStatesOptions();
			showUSStates = 1;
		}
		document.getElementById('store_locator_states').style.display = 'block';
		var state = $("#state :selected").attr('title');
		if(state == '') {//if state not selected
			var strAjaxMessage = "action=build_cities_list&search=country&str=" + encodeURIComponent(country) + "&language=" + language;
		} else {
			var strAjaxMessage = "action=build_cities_list&search=state&str=" + encodeURIComponent(state) + "&language=" + language;
		}
	} else {
		showUSStates = 0;
		inpState = '';
		document.getElementById('state').selectedIndex = 0;
		document.getElementById('store_locator_states').style.display = 'none';
		var strAjaxMessage = "action=build_cities_list&search=country&str=" + encodeURIComponent(country) + "&language=" + language;
	}
	
	if(country.toUpperCase() == "OTHER") {
		$(".city_fields").hide();
	} else {
		$(".city_fields").show();
		$.ajax({
			type: "GET",
			url: JS_EE_HTTP + JS_ACTION_FILE,
			data: strAjaxMessage,
			dataType: "xml",
			success: function(response){
				getCountryCities_callback(response);
			}
		});
	}
	
	//if country is USA and we doesn't select state we must output all states
	clearMap();
	if(showUSStates) {
		if($('#state :selected').attr('title') == '') {
			displayNow = 's';
			createStateLabels(1);
			var usPoint = new GLatLng(countriesCoordinates['US']['lat'], countriesCoordinates['US']['lng']);
        	map.setCenter(usPoint, 4);
		} else {
			showDealersFromCountry($('#country :selected').attr('title'), $('#state :selected').attr('title'));
		}
	} else {//in other way we mark all dealers from selected country
		if(country.toUpperCase() != "OTHER") {
			showDealersFromCountry($('#country :selected').attr('title'), '');
		} else {
			map.setCenter(new GLatLng(0,0),1);
			clearMap();//we moove map, so we need to creal it again
			if(isQSPage) {
				showEmptyDealersSearchResults();
			}
		}
	}
}

//function return states list if user select as country US
function getStatesOptions(){
	var strAjaxMessage = "action=return_list_of_us_states&language=" + language;
	$.ajax({
		type: "GET",
		url: JS_EE_HTTP + JS_ACTION_FILE,
		data: strAjaxMessage,
		dataType: "text",
		success: function(response){
			$("#state").html(response);
		}
	});
}

//convert geted xml list with cities into
function getCountryCities_callback(ajaxMessage){
	var strCitySelectHtml = "";// Placeholder for selectbox html
	$(ajaxMessage).find("cities").find("city").each(function(){// Find cities main element
		var strValue = $(this).find("name").text();// Find child element
		strValue = jQuery.trim(strValue);// Trim value
		strCitySelectHtml+='<option value="'+strValue+'">'+strValue+'</option>'+"\n";// Add record to HTML
	});
	document.getElementById('location').disabled = false;
	//$("#city").html(strCitySelectHtml).get(0).focus();// Set HTML, & request focus
	$("#city").html(strCitySelectHtml);// Set HTML
}

//set zoom on map to selected city
function onCityChange() {
	var selectCityValue = $("#city").val();
	
	if(selectCityValue != '' &&
	selectCityValue != noCityAvialable &&
	selectCityValue != pleaseSelect) {
		sendStoreLocatorForm();
	}
	
	
	/*var selectCityValue = $("#city").val();
	var writeCityObject = document.getElementById('location');
	if(selectCityValue != '' &&
	selectCityValue != noCityAvialable &&
	selectCityValue != pleaseSelect) {
		//clear write city value
		writeCityObject.value = writeCity;
		//get city coordinates and zoom on them
		setCityZoom($("#city").val(), $("#country :selected").attr("title"));
	}
	showDealersFromCity($("#country :selected").attr("title"), $('#state :selected').attr('title'), $("#city").val());*/
}

//get dealers list and display search results on page & map
function onQSCityChange() {
	var selectCityValue = $("#city").val();
	
	if(selectCityValue != '' &&
	selectCityValue != noCityAvialable &&
	selectCityValue != pleaseSelect) {
		sendStoreLocatorForm();
	}
	
	/*inpCity = $("#city").val();
	var selectCountryName = $("#country :selected").val();
	inpCountry = $("#country :selected").attr("title");
	var writeCityObject = document.getElementById('location');
	if(inpCity != '' &&
	inpCity != noCityAvialable &&
	inpCity != pleaseSelect) {
		//clear map
		clearMap();
		htmls.length = 0;
		side_bar_html.length = 0;
		i = 0;
		j = 0;
		$("#store_locator_search_results_block").html('<div class="store_locator_loading_image"><img src="'+EEHttp+'images/sl_loading.gif" width="24" height="24" alt=""></div>').show();
		$("#store_locator_search_results_not_found").
		add($("#store_locator_main_actions_row")).
		add($("#previous_page_link_outer")).
		add($("#search_results_pagination_outer")).
		add($("#next_page_link_outer")).hide();
		
		//clear write city value
		writeCityObject.value = writeCity;
		//get city coordinates and zoom on them
		//WAS
		//setCityZoom($("#city").val(), $("#country :selected").attr("title"));
		
		//NOW
		showSearchResults(selectCountryName, inpCountry, inpCity, 1);
	}*/
}

//function set map zoom to city
function setCityZoom(city, country) {
	var address = city + ',' + country;
	geocoder.getLatLng(address, function(point) {
		if (point) {
			map.setCenter(point, minZoom);
		} else {
			showEmptyDealersSearchResults();
		}
	});
}

//function reset select list with cities if somethink is inputted in location field
function onLocationChange() {
	locationValue = $("#location").val();
	cityObj = document.getElementById("city");
	
	if(locationValue != '') {
		cityObj.selectedIndex = 0;
	}
}

//function
function onLocationFocus() {
	if($("#location").val() == writeCity) {
		document.getElementById('location').value = '';
	}
}

//function
function onLocationBlur() {
	if($("#location").val() == '') {
		document.getElementById('location').value = writeCity;
	}
}

//function check if in url exists sign ? and return url param separator
function isUrlHasParams(url) {
	if(url.indexOf('?') != -1) {
		return '&';
	} else {
		return '?';
	}
}

//function check inputed values
function sendStoreLocatorForm() {
	var errorMessage = '';
	var selectCityValue = $("#city").val();
	var writeCityValue = $("#location").val();
	
	inpCountry = '';
	if($("#country :selected").attr("title") == '') {
		errorMessage += countryEmpty + '<br />';
	} else {
		inpCountry = $("#country :selected").attr("title");
	}
	
	inpState = '';
	if($("#state :selected").attr("title")) {
		inpState = $("#state :selected").attr("title");
	}
	
	if(inpCountry.toUpperCase() == "OTHER") {
		submitUrl = quickSearchAction;
		submitUrl += isUrlHasParams(submitUrl) + 'country=' + encodeURIComponent(inpCountry);
	} else {
		if(selectCityValue != '' &&
		selectCityValue != noCityAvialable &&
		selectCityValue != pleaseSelect) {
			inpCity = selectCityValue;
			submitUrl = quickSearchAction;
			submitUrl += isUrlHasParams(submitUrl) + 'country=' + encodeURIComponent(inpCountry) + ((inpState == '')?'':'&state=' + encodeURIComponent(inpState)) + '&city=' + encodeURIComponent(inpCity);
		} else if(writeCityValue != writeCity && writeCityValue.length > 0) {
			if(writeCityValue.trim() == '' ||
			writeCityValue.trim().length <= 1) {
				errorMessage += cityIncorrect + '<br />';
			} else {
				inpCity = writeCityValue;
				if($("#country").val() != '') {
					submitUrl = quickSearchAction;
					submitUrl += isUrlHasParams(submitUrl) + 'country=' + encodeURIComponent(inpCountry) + ((inpState == '')?'':'&state=' + encodeURIComponent(inpState)) + '&city=' + encodeURIComponent(inpCity);
				}
			}
		} else if (selectCityValue == noCityAvialable && inpCountry != '') {
			errorMessage += noStoresInCountry + '<br />';
		} else {
			errorMessage += cityEmpty + '<br />';
		}
	}
	
	if(errorMessage == '') {//send
		//clear previous error messages
		closeErrorsWindow();
		//clear state info if country is not US
		///if(document.getElementById('store_locator_states').style.display == 'none'){
		///	inpState = null;
		///}
		
		//Submit form!
		window.location.href = submitUrl;
		
	} else {//show error
		//show error message
		openErrorsWindow(errorMessage);
	}
}

//function calculates a zoom and set center
function zoomShowAll(map_id, dir) {
	ignoreZoom = 1;//used only on home page of store locator
	var bounds = new GLatLngBounds();//Constructs a rectangle from the points at its south-west and north-east corners.
	
	jQuery.each(dir, function() {
		bounds.extend(this);
	});   
	
	//getBoundsZoomLevel - Returns to the map the zoom level at which the map section defined by bounds fits into the map view of the given size in pixels.
	//calculate new zoom level
	var newZoom = map_id.getBoundsZoomLevel(bounds);
	var setZoom;
	if(newZoom > minZoom) {//if zoom is less than minimum then set it to minimum value
		setZoom = minZoom;
	//} else if(newZoom < maxZoom) {
	//	map_id.setZoom(maxZoom);
	} else {
		setZoom = newZoom;//Sets the zoom level to the given new value.
	}
	var lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
	var lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
	map_id.setCenter(new GLatLng(lat, lng), setZoom);
}

//function marks all countries and US states on map
function createCountryAndStatesLabels() {
	displayNow = 's';
	createCountryLabels(0);
	createStateLabels(0);
	mc = new MarkerClusterer(map, gmarkers, stateMCStyle);//show state markers grouped in map
}

//function marks USA states on map
function createStateLabels(showOnCluster) {
	for(field in statesCoordinates) {
		createStateLabelInner(field, statesCoordinates);//create new states on map
	}
	if(showOnCluster) {
		mc = new MarkerClusterer(map, gmarkers, stateMCStyle);//show state markers grouped in map
	}
}

//function marks all countries on map
function createCountryLabels(showOnCluster) {
	for(field in countriesCoordinates) {
		createCountryLabelInner(field, countriesCoordinates);//create new dealers on map
	}
	if(showOnCluster) {
		mc = new MarkerClusterer(map, gmarkers, countryMCStyle);//show country markers grouped in map
	}
}

//function create country markers on map
function createCountryLabelInner(field, coordinates) {
	if(field == 'US' && displayNow != 'c') return;//if we display now states, then we shouldn't display US country label
	var lat = parseFloat(coordinates[field]['lat']);
	var lng = parseFloat(coordinates[field]['lng']);
	var dealersNum = parseFloat(coordinates[field]['dealers']);
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point);//Marks a position on the map
	marker.dealersNum = dealersNum;//pass number of dealers in the country
	marker.onClickHandler = function() {
		//download all dealers from selected country
		if(field == 'US') {
			clearMap();
			displayNow = 's';
			createStateLabels(1);
			//zoomShowAll(map, points);
			var usPoint = new GLatLng(coordinates['US']['lat'], coordinates['US']['lng']);
       		map.setCenter(usPoint, 4);
		} else {
			clearMap();
			showDealersFromCountry(field, '');
		}
	}
	////map.addOverlay(marker);//now we dont directly add markers on map
	gmarkers.push(marker);//we add it to special array and then pass to clusterMarkers
}

function createStateLabelInner(field, coordinates) {
	var lat = parseFloat(coordinates[field]['lat']);
	var lng = parseFloat(coordinates[field]['lng']);
	var dealersNum = parseFloat(coordinates[field]['dealers']);
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, rwlogo);//Marks a position on the map
	marker.dealersNum = dealersNum;//pass number of dealers in the state
	marker.onClickHandler = function() {
		//download all dealers from selected country
		showDealersFromState(field, lat, lng);
	}
	////map.addOverlay(marker);
	gmarkers.push(marker);//we add it to special array and then pass to clusterMarkers
}

//function show all dealers from selected country
function showDealersFromCountry(country, state) {
	displayNow = 'd';
	GDownloadUrl(dealerSearchUrl + '&country=' + country + '&state=' + state + '&language=' + language, function(data) {//This function provides a convenient way to asynchronously retrieve a resource identified by a URL
		if(data != '') {
			if(displayNow != 'd') return;
			var xml = GXml.parse(data);
			var dealers = xml.documentElement.getElementsByTagName('dealer');
			for(var i= 0; i<dealers.length; i++) {
				createCountryDealer(dealers[i]);
			}
			mc = new MarkerClusterer(map, gmarkers, dealerMCStyle);//show dealers markers grouped in map
			zoomShowAll(map, points);
		} else {
			showEmptyDealersSearchResults();
		}
	});
}

function showDealersFromState(state, lat, lng) {
	//GDownloadUrl(dealerSearchUrl + '&country=US&state=' + state, function(data) {//This function provides a convenient way to asynchronously retrieve a resource identified by a URL
		//if(data != '') {
			//var xml = GXml.parse(data);
			//var dealers = xml.documentElement.getElementsByTagName('dealer');
					
			//for(var i = 0; i<dealers.length; i++) {
			//	createStateDealer(dealers[i], state);
			//}
			
			var statePoint = new GLatLng(lat, lng);
        	map.setCenter(statePoint, 7);
			//zoom sets to 7, so dealers would be loaded automatically
		//}
	//});
}

//function show all dealers from selected city
function showDealersFromCity(country, state, city) {
	displayNow = 'd';
	GDownloadUrl(dealerSearchUrl + '&country=' + encodeURIComponent(country) + '&state=' + encodeURIComponent(state) + '&city=' + encodeURIComponent(city) + '&language=' + language, function(data) {//This function provides a convenient way to asynchronously retrieve a resource identified by a URL
		if(data != '') {
			if(displayNow != 'd') return;
			var xml = GXml.parse(data);
			var dealers = xml.documentElement.getElementsByTagName('dealer');
			clearMap();
			for(var i= 0; i<dealers.length; i++) {
				createCountryDealer(dealers[i]);
			}
			
			console.log(i);
			console.log("Hello\n\n");
			console.debug(myVar);
			console.debug(MarkerClusterer);
			mc = new MarkerClusterer(map, gmarkers, dealerMCStyle);//show dealers markers grouped in map
			zoomShowAll(map, points);
		}
	});
}

//function create dealer marker on map
function createCountryDealer(xmlNode) {
	var id = parseInt(xmlNode.getAttribute('id'));
	var lat = parseFloat(xmlNode.getAttribute('lat'));
	var lng = parseFloat(xmlNode.getAttribute('lng'));
	var name = xmlNode.getAttribute('name');
	var name2 = xmlNode.getAttribute('name2');
	var street = xmlNode.getAttribute('street');
	var street2 = xmlNode.getAttribute('street2');
	var zip = xmlNode.getAttribute('zip');
	var city = xmlNode.getAttribute('city');
	var country = xmlNode.getAttribute('country');
	var phone = xmlNode.getAttribute('phone');
	var fax = xmlNode.getAttribute('fax');
	var email = xmlNode.getAttribute('email');
	var id = xmlNode.getAttribute('id');
	var url = xmlNode.getAttribute('url');
	var url2 = xmlNode.getAttribute('url2');
	var urlLink = (url)? makeUrlLink(url) : '';
	var url2Link = (url2)? makeUrlLink(url2) : '';
	var gaq_store_path = xmlNode.getAttribute('gaq_store_path');

	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, rwlogo);
	
	var html;
	GEvent.addListener(marker, 'click', function() {
		//for printList function
		inpId = id;
		count = 1;
		inpCountry = country;
		inpCity = city;
		//for itinerary calculate function
		positions[j] = new Array();
		positions[j][0] = id;
		positions[j][1] = lat;
		positions[j][2] = lng;
		
		html = '<div class="dealers_info_window">'+
		'<b>'+name+'</b><br />';
		if(name2 != '') html += name2+'<br />';
		html += street+'<br />'+(street2 != '' ? street2+'<br />' : '')+
		zip+' '+city+'<br />';
		if(phone != '') html += dealersTelText+' '+phone+'<br />';
		if(fax != '') html += dealersFaxText+' '+fax+'<br />';
		if(email != '') html += dealersEmailText+' <a href="mail'+'to:'+email+'">'+email+'</a><br />';//problem with antispam security
		if (url != '' || url2 != '')
		{
			dealersWebSiteText = (url != '' && url2 != '') ? dealersUrlsText : dealersUrlText;
			html += '<table cellcpacing="0" cellpadding="0" border="0">';
			html += '<tr><td valign="top"'+((url != '' && url2 != '') ? ' rowspan="2"' : '')+'>'+dealersWebSiteText+' </td>';
			if(url != '') html += '<td><a target="_blank" href="'+urlLink+'">'+url+'</a></td></tr>';
			if(url2 != '') html += '<tr><td><a target="_blank" href="'+url2Link+'">'+url2+'</a></td></tr>';
			html += '</table>';
		}
		html += '<div class="store_locator_actions_in_cloud">';
		html += '	<a href="#" onclick="printList('+id+'); return false;">'+printText+'</a>';
		html += '	<a href="#" onclick="sendList('+j+', '+id+', false); return false;">'+sendText+'</a>';
		html += '	<a href="#" onclick="openItineraryWindow('+j+'); return false;">'+itineraryText+'</a>';
		html += '</div>';
		html += '</div>';
		marker.openInfoWindowHtml(html);//Opens the map info window over the icon of the marker
		//var dealerUrl = quickSearchAction;
		//dealerUrl += isUrlHasParams(dealerUrl) + 'id=' + id;
		//window.location.href = dealerUrl;
	});
	//save info about displayed dealers
	points.push(point);
	markers[id] = marker;
	////map.addOverlay(marker);
	gmarkers.push(marker);
	
	j++;
	
	return id;//for adding it to map
}

//NOT IN USE
function createStateDealer(xmlNode, state) {
	var id = parseInt(xmlNode.getAttribute('id'));
	var lat = parseFloat(xmlNode.getAttribute('lat'));
	var lng = parseFloat(xmlNode.getAttribute('lng'));
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, rwlogo);
	GEvent.addListener(marker, 'click', function() {
		showDealersFromCountry('US', state);
	});
	//save info about displayed dealers
	points[points.length] = point;
	markers[id] = marker;
	map.addOverlay(marker);
}

//function delete all markers on map
function clearMap() {
	//clear clasterMarkers
	if(mc) {
		mc.clearMarkers();
	}
	gmarkers.length = 0;
	pts.length = 0;
	//clear array with ids of markers which already added to map
	addedMarkersIds.length = 0;
	
	points.length = 0;//clear array with displayed delaers on map
	map.clearOverlays();//clear all markers with countries
}

//function check if we already add current marker to map
function checkIfWeAddMarker(id) {
	var ret = false;
	for(var j in addedMarkersIds) {
		if(addedMarkersIds[j] === id) {
			ret = true;
			break;
		}
	}
	return ret;
}

function initStoreLocatorHomeMap() {
	if (GBrowserIsCompatible()) {//check Browser Compatibility, that is not obligatory
		
		map = new GMap2(document.getElementById("store_locator_map"));//create google map object
	
		//see all controls at page http://code.google.com/apis/maps/documentation/controls.html
		map.addControl(new GLargeMapControl3D());//a large pan/zoom control as now used on Google Maps. Appears in the top left corner of the map by default.
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();//Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
		
		///map.setCenter(new GLatLng(0,0),1);//to initialize a map using a point in geographical coordinates longitude and latitude
		
		oldMapBounds = map._getBounds();
		oldZoomLevel = map.getZoom();
		
		GEvent.addListener(map, "moveend", function() {
			var newMapBounds = map._getBounds();
			var newZoomLevel = map.getZoom();
			
			var oldNorthEast = oldMapBounds.getNorthEast();
			var oldSouthWest = oldMapBounds.getSouthWest();
			
			var oldNELat = oldNorthEast.lat();
			var oldNELng = oldNorthEast.lng();
			var oldSWLat = oldSouthWest.lat();
			var oldSWLng = oldSouthWest.lng();
			
			var newNorthEast = newMapBounds.getNorthEast();
			var newSouthWest = newMapBounds.getSouthWest();
			
			var newNELat = newNorthEast.lat();
			var newNELng = newNorthEast.lng();
			var newSWLat = newSouthWest.lat();
			var newSWLng = newSouthWest.lng();
			
			var deleteOld = 1;
			
			if(!ignoreZoom) {////////////////////////
			if(newZoomLevel <= 2 && oldZoomLevel > 2) {//hide dealers, display countries
				clearMap();
				displayNow = 'c';
				createCountryLabels(1);
			} else if(newZoomLevel >= 7) {//hide countries, display dealers
				if(oldZoomLevel < 7) {//we just begin to display dealers, so we need to display all delaers from visible area
					deleteOld = 0;
					clearMap();
					mc = new MarkerClusterer(map, [], dealerMCStyle);//in future we will add markers to map, so we must to create new cluster
				}
				
				displayNow = 'd';
				GDownloadUrl(mapMoveUrl +
					'&oldnelat=' + oldNELat +
					'&oldnelng=' + oldNELng +
					'&oldswlat=' + oldSWLat +
					'&oldswlng=' + oldSWLng +
					'&newnelat=' + newNELat +
					'&newnelng=' + newNELng +
					'&newswlat=' + newSWLat +
					'&newswlng=' + newSWLng +
					'&delete_old=' + deleteOld +
					'&language=' + language, function(data) {//This function provides a convenient way to asynchronously retrieve a resource identified by a URL
					if(data != '') {
						if(displayNow != 'd') return;
						var xml = GXml.parse(data);
						var addDealers = xml.documentElement.getElementsByTagName('add');
						
						//gmarkers.length = 0;//clear previous saved gmarkers in order to add only new
						if(!addedMarkersIds) {
							for(var i in markers) {
								addedMarkersIds.push(i);//id of markers which we already add to map
							}
						}
						
						var newAddedMarkers = [];//markers which we will add to map
						for(var i = 0; i<addDealers.length; i++) {
							var newMarkerId = createCountryDealer(addDealers[i]);
							//check if we already add this marker to map
							if(!checkIfWeAddMarker(newMarkerId)) {
								addedMarkersIds.push(newMarkerId);
								newAddedMarkers.push(markers[newMarkerId]);
							}
						}
						if(newAddedMarkers.length > 0) {
							mc.addMarkers(newAddedMarkers);//this function is realy problem, if I add markers using it I can't delete them later or ignore max cluster zoom lever
						}
						
						///var delDealers = xml.documentElement.getElementsByTagName('delete');
						///for(i = 0; i<delDealers.length; i++) {
						///	////map.removeOverlay(markers[parseInt(delDealers[i].getAttribute('id'))]);
						///	//delete elements from array positions
						///	//i won't, it need not to much of ram
						///	mc.removeMarker(markers[parseInt(delDealers[i].getAttribute('id'))]);
						///}
					}
				});
			} else if((newZoomLevel > 2 && oldZoomLevel <= 2) || (newZoomLevel < 7 && oldZoomLevel >= 7)) {
				clearMap();
				createCountryAndStatesLabels();
			}
		
			}////////////////////////
			ignoreZoom = 0;
		
			oldZoomLevel = newZoomLevel;
			oldMapBounds = newMapBounds;
		});
		//GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {});
		///clearMap();
		
		/*if(cityHasDealers) {//if we define users city show dealers from it
			setCityZoom(userCity, userCountryCode);
		} else if(stateHasDealers) {//if we define users state show dealers from it
			showDealersFromCountry($('#country :selected').attr('title'), $('#state :selected').attr('title'));
		} else*/ if(countryHasDealers) {//if we define users country show dealers from it
			showDealersFromCountry(userCountryCode, '');
		} else {//if we can't define user country or in user country where is no dealers, when display all countries
			displayNow = 'c';
			map.setCenter(new GLatLng(0,0),1);//in other case, city state or country has dealers, so zoomShowAll() function would be called
			createCountryLabels(1);
		}
	}
}

//function open popup window with errors (on home page)
function openErrorsWindow(errorMessage) {
	if(!isHomePage) {
		//change height of modal layer
		setHeightAsParentHas('store_locator_form_modal');
		//change height of errors outer layer
		setHeightAsParentHas('store_locator_form_errors_outer');
	}
	var messageObject = $("#tb_content_text");
	messageObject.html(errorMessage);
	document.getElementById('store_locator_form_modal').style.display = 'block';
	document.getElementById('store_locator_form_errors_outer').style.display = 'block';
	//calculate position of itinerary form layer
	var parentHeight = document.getElementById('store_locator_form_errors_outer').offsetHeight;
	var formErrorsObject = document.getElementById('store_locator_form_errors');
	var currentHeight = formErrorsObject.offsetHeight;
	if(parentHeight>currentHeight) {
		var newMarginTop = parseInt((parentHeight - currentHeight) / 2);
		if(newMarginTop > 150) {//if itinerary table will be to large we wont see errors popup
			newMarginTop = 150;
		}
		formErrorsObject.style.marginTop = newMarginTop + 'px';
	}
}

//function close popup window with errors (on home page)
function closeErrorsWindow() {
	var messageObject = $("#tb_content_text");
	messageObject.html('');
	document.getElementById('store_locator_form_modal').style.display = 'none';
	document.getElementById('store_locator_form_errors_outer').style.display = 'none';
}

//function open itinerary popup window
function openItineraryWindow(id) {
	//store value I for printing purposes
	itineraryId = id;
	//clear previous inputted value
	document.getElementById('search_itinerary').value = '';
	if(!isHomePage) {
		//change height of modal layer
		setHeightAsParentHas('store_locator_form_modal');
		//change height of itinerary outer layer
		setHeightAsParentHas('store_locator_itinerary_form_errors_outer');
	}
	document.getElementById('store_locator_form_modal').style.display = 'block';
	document.getElementById('store_locator_itinerary_form_errors_outer').style.display = 'block';
	//calculate position of itinerary form layer
	var parentHeight = document.getElementById('store_locator_itinerary_form_errors_outer').offsetHeight;
	var formItineraryObject = document.getElementById('store_locator_itinerary_form_errors');
	var currentHeight = formItineraryObject.offsetHeight;
	if(parentHeight>currentHeight) {
		var newMarginTop = parseInt((parentHeight - currentHeight) / 2);
		if(newMarginTop > 150) {//if itinerary table will be to large we wont see errors popup
			newMarginTop = 150;
		}
		formItineraryObject.style.marginTop = newMarginTop + 'px';
	}
	//set focus
	document.getElementById('search_itinerary').focus();
}

//function close itinerary popup window
function closeItineraryWindow() {
	document.getElementById('store_locator_form_modal').style.display = 'none';
	document.getElementById('store_locator_itinerary_form_errors_outer').style.display = 'none';
}

/*****Functions only for quicksearch*****/

//function get url address and return it well formatted
function makeUrlLink(url) {
	//check if url hasn't got http:// prefix we must add it
	var httpPos = url.indexOf('http://');
	if(httpPos == -1) {
		url = 'http://'+url;
	}
	//check if in url present tags, for example <br>
	//if tas present that mean waht in url two addresses seperated with tag <br>
	//in that case return onlu first url
	var tagPos = url.indexOf('<');
	if(tagPos == -1) {
		return url;
	} else {
		return url.substr(0, tagPos);
	}
}

//function get part of request query
function getParam(name) {
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var tmpURL = window.location.href;
	var results = regex.exec(tmpURL);
	
	if(results == null) {
		return "";
	} else {
		return decodeURIComponent(results[1]);
	}
}

//function create point on map
function createMarker(point, name, name2, street, street2, zip, city, phone, fax, email, id, url, url2, hasMarker) {
	urlLink = makeUrlLink(url);
	url2Link = makeUrlLink(url2);
	if(hasMarker) {//if we got coordenates of dealer
		var marker = new GMarker(point, rwlogo);//Marks a position on the map
		//html caption of marker
		var html = '<div class="dealers_info_window">'+
		'<b>'+name+'</b><br />';
		if(name2 != '') html += name2+'<br />';
		html += street+'<br />';
		if(street2 != '') html += street2+'<br />';
		html += zip+' '+city+'<br />';
		if(phone != '') html += dealersTelText+' '+phone+'<br />';
		if(fax != '') html += dealersFaxText+' '+fax+'<br />';
		if(email != '') html += dealersEmailText+' <a href="mail'+'to:'+email+'">'+email+'</a><br />';//problem with antispam security
		if (url != '' || url2 != '')
		{
			dealersWebSiteText = (url != '' && url2 != '') ? dealersUrlsText : dealersUrlText;
			html += '<table cellcpacing="0" cellpadding="0" border="0">';
			html += '<tr><td valign="top"'+((url != '' && url2 != '') ? ' rowspan="2"' : '')+'>'+dealersWebSiteText+' </td>';
			if(url != '') html += '<td><a target="_blank" href="'+urlLink+'">'+url+'</a></td></tr>';
			if(url2 != '') html += '<tr><td><a target="_blank" href="'+url2Link+'">'+url2+'</a></td></tr>';
			html += '</table>';
		}
		html += '<div class="store_locator_actions_in_cloud">';
		html += '	<a href="#" onclick="printList('+id+'); return false;">'+printText+'</a>';
		html += '	<a href="#" onclick="sendList('+j+', '+id+', false); return false;">'+sendText+'</a>';
		html += '	<a href="#" onclick="openItineraryWindow('+j+'); return false;">'+itineraryText+'</a>';
		html += '</div>';
		html += '</div>';
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);//Opens the map info window over the icon of the marker
		});
		gmarkers[i] = marker;
		htmls[i] = html;
		pts.push(point);
		map.addOverlay(marker);
	}
	//create html for search results
	side_bar_html[j] = new Array();
	side_bar_html[j][0] = '';
	side_bar_html[j][1] = '';
	if(hasMarker) {
		side_bar_html[j][0] += '<p><b><a href="#" onclick="selectMarker('+i+'); return false;">'+name+'</a></b></p>';
	} else {
		side_bar_html[j][0] += '	<p><b>'+name+'</b></p>';
	}
	side_bar_html[j][0] += '	<p>';
	if(name2 != '') {side_bar_html[j][0] += '	'+name2+'<br />';}
	side_bar_html[j][0] += street+'<br />';
	if (street2 != '') side_bar_html[j][0] += street2+'<br />';
	side_bar_html[j][0] += '	'+zip+' '+city+'</p>';
	if(phone != '')	side_bar_html[j][0] += '	<p>'+dealersTelText+' '+phone+'<br />';
	if(phone != '' && fax == '')	side_bar_html[j][0] += '</p>';
	if(phone == '' && fax != '')	side_bar_html[j][0] += '<p>';
	if(fax != '')	side_bar_html[j][0] += '	'+dealersFaxText+' '+fax+'</p>';
	if(email != '')	side_bar_html[j][0] += '	<p>'+dealersEmailText+' <a href="mail'+'to:'+email+'">'+email+'</a></p>';
	if (url != '' || url2 != '')
	{
		dealersWebSiteText = (url != '' && url2 != '') ? dealersUrlsText : dealersUrlText;
		side_bar_html[j][0] += '<table cellcpacing="0" cellpadding="0" border="0">';
		side_bar_html[j][0] += '<tr><td valign="top"'+((url != '' && url2 != '') ? ' rowspan="2"' : '')+'>'+dealersWebSiteText+' </td>';
		if(url != '') side_bar_html[j][0] += '<td><a target="_blank" href="'+urlLink+'">'+url+'</a></td></tr>';
		if(url2 != '') side_bar_html[j][0] += '<tr><td><a target="_blank" href="'+url2Link+'">'+url2+'</a></td></tr>';
		side_bar_html[j][0] += '</table>';
	}
	//if(url != '')	side_bar_html[j][0] += '	<p><span>'+dealersUrlText+' </span><a href="'+urlLink+'" target="_blank">'+url+'</a>';
	//if(url2 != '')	side_bar_html[j][0] += '	<a href="'+url2Link+'" target="_blank">'+url2+'</a></p>';
	if(hasMarker) {
		side_bar_html[j][1] += '<div class="store_locator_dotted_outer">';
		side_bar_html[j][1] += '	<div class="store_locator_actions_row"><a href="#" onclick="javascript:selectMarkerAndCenter('+i+','+j+'); return false;">'+locateText+'</a><span class="store_locator_actions_separator">|</span><a href="javascript:openItineraryWindow('+j+');">'+itineraryText+'</a></div>';
		side_bar_html[j][1] += '</div>';
	}
	side_bar_html[j][1] += '<div class="store_locator_dotted_outer">';
	side_bar_html[j][1] += '	<div class="store_locator_dotted_inner">';
	side_bar_html[j][1] += '		<div class="store_locator_actions_row"><a href="#" onclick="printList('+id+'); return false;">'+printText+'</a><span class="store_locator_actions_separator">|</span><a href="#" onclick="'+(hasMarker?'selectMarkerAndCenter('+i+','+j+'); ':'')+'sendList('+(hasMarker?j:-1)+', '+id+', false); return false;">'+sendText+'</a></div>';
	side_bar_html[j][1] += '	</div>';
	side_bar_html[j][1] += '</div>';
	j++;
	if(hasMarker) {
		i++;
		return marker;
	}
}

//function open buble in google maps with dealer info
function selectMarker(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

//function open buble in google maps with dealer info and set map center and zoom
function selectMarkerAndCenter(i, j) {
	var point = new GLatLng(positions[j][1], positions[j][2]);
	map.setCenter(point);
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

//function check if side_bar_html array item exists and return its value
function getSideBarValue(index, index2) {
	var ret;
	if(side_bar_html[index] !== undefined) {
		ret = side_bar_html[index][index2];
	} else {
	 	ret = '&nbsp;';
	}
	return ret;
}

//function reload search content zone displaying requested results
function getDealersSearchResults(start)//start page to display dealers
{
	var showDealersOnPage = 6;
	var dealerNumber = start*showDealersOnPage-showDealersOnPage;//start position to display dealers
	//hide results not found block
	document.getElementById('store_locator_search_results_not_found').style.display = 'none';
	//insert dealers country
	document.getElementById('search_city').innerHTML = htmlspecialchars(inpCity);
	//insert found dealers count
	//document.getElementById("total_found").innerHTML = '('+totalText+' '+count+')';
	//prepare dealers result
	var ret = '<table class="store_locator_search_results_table" cellspacing="0">'+"\n";
	var shownPages = (count-(dealerNumber)>=showDealersOnPage)?showDealersOnPage:(count-(dealerNumber));
	for(var step=0; step<showDealersOnPage && step<shownPages; step=step+3) {
		var firstSeparatorClass = ((step+0+1)>shownPages)?'search_result_separator_empty':'search_result_separator';
		var secondSeparatorClass = ((step+1+1)>shownPages)?'search_result_separator_empty':'search_result_separator';
		ret += '<tr>'+"\n"+
			'	<td class="search_result_main"><div class="search_result_main_inner">'+getSideBarValue((dealerNumber+step+0), 0)+'</td></div>'+"\n"+
			'	<td rowspan="2" class="'+firstSeparatorClass+'">&nbsp;</td>'+"\n"+
			'	<td class="search_result_main"><div class="search_result_main_inner">'+getSideBarValue((dealerNumber+step+1), 0)+'</td></div>'+"\n"+
			'	<td rowspan="2" class="'+secondSeparatorClass+'">&nbsp;</td>'+"\n"+
			'	<td class="search_result_main"><div class="search_result_main_inner">'+getSideBarValue((dealerNumber+step+2), 0)+'</td></div>'+"\n"+
			'</tr>'+
			'<tr>'+
			'	<td class="search_result_action">'+getSideBarValue((dealerNumber+step+0), 1)+'</td>'+"\n"+
			'	<td class="search_result_action">'+getSideBarValue((dealerNumber+step+1), 1)+'</td>'+"\n"+
			'	<td class="search_result_action">'+getSideBarValue((dealerNumber+step+2), 1)+'</td>'+"\n"+
			'</tr>'+"\n";
	}
	ret += '</table>'+"\n";
	//insert found dealers result
	$("#store_locator_search_results_block").html(ret);
	
	var totalPages = Math.ceil(count/showDealersOnPage);
	//change onclick attribute of previous page link
	if(totalPages>1) {
		//show right actions
		document.getElementById('previous_page_link_outer').style.display = 'block';
		document.getElementById('search_results_pagination_outer').style.display = 'block';
		document.getElementById('next_page_link_outer').style.display = 'block';
		
		if(start == 1) {
			document.getElementById("previous_page_link_outer").style.display = "none";
		}
		if(start == totalPages) {
			document.getElementById("next_page_link_outer").style.display = "none";
		}
		
		var previousPageObject = document.getElementById('previous_page_link');
		var previousPage = ((start-1)>0)?(start-1):1;
		//previousPageObject.setAttribute('onclick', 'getDealersSearchResults(' + previousPage + '); return false;');//doen't work under IE
		previousPageObject.onclick = function() {getDealersSearchResults(previousPage);return false;}
		//change onclick attribute of next page link
		var nextPageObject = document.getElementById('next_page_link');
		var nextPage = ((start+1)<=totalPages)?(start+1):totalPages;
		//nextPageObject.setAttribute('onClick', 'getDealersSearchResults(' + nextPage + '); return false;');//doen't work under IE
		nextPageObject.onclick = function() {getDealersSearchResults(nextPage);return false;}
		//change content of pagination zone
		var paginationContent = [];
		var paginationResult = '';
		///var paginationContent = '('+ shownPages + '/' + count + ') |';
		////for(var p=1; p<(totalPages+1); p++) {
		////	if(p == start) {
		////		paginationContent += ' <span class="current_pagination_element">'+ p + '</span> |';
		////	} else {
		////		paginationContent += ' <a href="#" onclick="getDealersSearchResults(' + p + '); return false;">' + p + '</a> |';
		////	}
		////}
		
		//all pages doesn't go into block, so must display only 5 elements
		for(var p=1; p<(totalPages+1); p++) {
			//chose display page number or not
			if(p == start) {//current page
				paginationContent.push('<span class="current_pagination_element">'+ p + '</span>');
			} else if(
				p == 1 ||//first page
				p == start-2 ||//previously previous page
				p == start-1 ||//previous page
				p == start+1 ||//next page
				p == start+2 ||//next after next page
				p == totalPages//last page
			) {
				paginationContent.push('<a href="#" onclick="getDealersSearchResults(' + p + '); return false;">' + p + '</a>');
			} else {
				paginationContent.push('<span>...</span>');
			}
		}
		//prepare result values
		//delete pairs of dots
		for(var p=paginationContent.length-1; p>=0; p--) {
			if(p != 0 && paginationContent[p] == '<span>...</span>' && paginationContent[p+1] == '<span>...</span>') {
				paginationContent.splice(p, 1);
			}
		}
		paginationResult += '|' + paginationContent.join('|') + '|';
		
		document.getElementById('search_results_pagination').innerHTML = paginationResult;
	}
	
	//show action block
	document.getElementById('store_locator_main_actions_row').style.display = 'block';
}

//function show empty results set
function showEmptyDealersSearchResults() {
	map.setCenter(new GLatLng(0,0),1);//at least we will shop empty map
	document.getElementById('store_locator_search_results_block').style.display = 'none';
	document.getElementById('store_locator_main_actions_row').style.display = 'none';
	document.getElementById('search_city').style.display = 'none';
	document.getElementById('total_found').style.display = 'none';
	document.getElementById('store_locator_search_results_not_found').style.display = 'block';
}

function initStoreLocatorQSMap(initSearchResults) {
	if(GBrowserIsCompatible()) {//check Browser Compatibility, that is not obligatory
		//get previously inputted user values
		inpId = getParam('id');
		//inpContinent = getParam('continent');
		inpCountry = getParam('country');
		inpState = getParam('state');
		inpCity = getParam('city');
		
		map = new GMap2(document.getElementById("store_locator_map"));//create google map object
		
		if(inpCountry.toUpperCase() == "IL") {
			map.setMapType(G_HYBRID_MAP);
		} else {
			map.setMapType(G_NORMAL_MAP);
		}
		map.addControl(new GLargeMapControl3D());//a large pan/zoom control as now used on Google Maps. Appears in the top left corner of the map by default.
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();//Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
		
		//Map needs to be centered before it can be used
		///map.setCenter(new GLatLng(0,0),1);//to initialize a map using a point in geographical coordinates longitude and latitude
		
		var sendCountryName = $("#country").val() || inpCountry;
		
		//retrieve xml object from server with list of dealers
		if(inpCountry.toUpperCase() != "OTHER") {
			prepareSearchResults(sendCountryName, inpCountry, inpCity, initSearchResults);
		} else {
			showEmptyDealersSearchResults();
		}
	}
}

//retrieve xml object from server with list of dealers
function prepareSearchResults(sendCountryName, sendCountryCode, sendCityName, initSearchResults) {
	var searchUrl = dealerUrl + '&country='+encodeURIComponent(sendCountryCode)+'&city='+encodeURIComponent(sendCityName);
	if(cityHasRetailers) {//user select city from select list and we must outout retailers from current city
		showSearchResults(sendCountryCode, sendCityName, initSearchResults, searchUrl);
	} else {//user write city and we must determine retailers near this city
		var location = sendCityName+','+sendCountryName;
		//check if location is not empty
		if(location == ',') {
			location = '';
		}
		
		var geocoder = new GClientGeocoder;//create object Geocoding - is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739)
		geocoder.getLatLng(location, function(point) {//convert a string address into a GLatLng
			if (point) {
				//save lng & lat
				latitude = point.lat();
				longitude = point.lng();
				//create url for searching dealers using coordinates in DB
				searchUrl += '&lat='+latitude+'&lng='+longitude;
				///map.setCenter(point, 11);//Zoom map to our city
			}
			showSearchResults(sendCountryCode, sendCityName, initSearchResults, searchUrl);
		});
	}
}

//function output retailers on map
function showSearchResults(sendCountryCode, sendCityName, initSearchResults, searchUrl) {
	GDownloadUrl(searchUrl, function(data) {//This function provides a convenient way to asynchronously retrieve a resource identified by a URL
		if(data != '') {//dealers was found
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			for (var y = 0; y < markers.length; y++) {
				var name = markers[y].getAttribute("name");
				var name2 = markers[y].getAttribute("name2");
				var street = markers[y].getAttribute("street");
				var street2 = markers[y].getAttribute("street2");
				var zip = markers[y].getAttribute("zip");
				var city = markers[y].getAttribute("city");
				var phone = markers[y].getAttribute("phone");
				var fax = markers[y].getAttribute("fax");
				var email = markers[y].getAttribute("email");
				var id = markers[y].getAttribute("id");
				var url = markers[y].getAttribute("url");
				var url2 = markers[y].getAttribute("url2");
				
				if(markers[y].getAttribute("lat") != '' && markers[y].getAttribute("lng") != '') {
					//store positions in order to use them in itinerary search
					positions[j] = new Array();
					positions[j][0] = id;
					positions[j][1] = parseFloat(markers[y].getAttribute("lat"));
					positions[j][2] = parseFloat(markers[y].getAttribute("lng"));
					var point = new GLatLng(parseFloat(markers[y].getAttribute("lat")), parseFloat(markers[y].getAttribute("lng")));
					marker = createMarker(point, name, name2, street, street2, zip, city, phone, fax, email, id, url, url2, true);
				} else {
					createMarker(point, name, name2, street, street2, zip, city, phone, fax, email, id, url, url2, false);
				}
			}
			var markers_add = xml.documentElement.getElementsByTagName("marker_add");
			for (var z = 0; z < markers_add.length; z++) {
				var name = markers_add[z].getAttribute("name");
				var name2 = markers_add[z].getAttribute("name2");
				var street = markers_add[z].getAttribute("street");
				var street2 = markers_add[z].getAttribute("street2");
				var zip = markers_add[z].getAttribute("zip");
				var city = markers_add[z].getAttribute("city");
				var phone = markers_add[z].getAttribute("phone");
				var fax = markers_add[z].getAttribute("fax");
				var email = markers_add[z].getAttribute("email");
				var id = markers_add[z].getAttribute("id");
				var url = markers_add[z].getAttribute("url");
				var url2 = markers_add[z].getAttribute("url2");
				
				//where is might be bug with mysql http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html
				//when some reginal symbols would be converted to english equivalents
				//so we may find dealer without coordinates, just by city
				//its a pity but he will appear in additional list
				if(markers_add[z].getAttribute("lat") != '' && markers_add[z].getAttribute("lng") != '') {
					positions[j] = new Array();
					positions[j][0] = id;
					positions[j][1] = parseFloat(markers_add[z].getAttribute("lat"));
					positions[j][2] = parseFloat(markers_add[z].getAttribute("lng"));
					var point = new GLatLng(parseFloat(markers_add[z].getAttribute("lat")), parseFloat(markers_add[z].getAttribute("lng")));
					createMarker(point, name, name2, street, street2, zip, city, phone, fax, email, id, url, url2, true);
				} else {
					createMarker(point, name, name2, street, street2, zip, city, phone, fax, email, id, url, url2, false);
				}
				//add horizontal line between main and additional search results
				///if(z == 0 && side_bar_html.length > 1) {
				///	side_bar_html[side_bar_html.length-1] = '<div class="store_locator_dotted_outer"><div class="store_locator_dotted_inner"><div class="store_locator_actions_row neighbouring_dealers"><%make_js_safe:<%cms:neighbouring_dealers%>%></div></div></div><div style="height: 24px;">&nbsp;</div>' + side_bar_html[side_bar_html.length-1];
				///}
			}
			count = markers.length + markers_add.length;
			if(initSearchResults) {//if we need to display search results (on itinerary pages we don't display search results)
				//nothing found
				//user input search values but nothing found
				if(count == 0 &&
				//inpContinent != '' &&
				sendCountryCode != '' &&
				sendCityName != ''){
					showEmptyDealersSearchResults();
				} else {//FOUND!!!
					getDealersSearchResults(1);
				}
			}
			zoomShowAll(map, pts);
		}//check data
		else {//dealers wasn't found but user input something
			if(initSearchResults) {//if we need to display search results (on itinerary pages we don't display search results)
				showEmptyDealersSearchResults();
			} else {
				map.setCenter(new GLatLng(0,0),1);//at least we will shop empty map
			}
		}
		if(initSearchResults) {//if we need to display search results (on itinerary pages we don't display search results)
			document.getElementById('search_city').innerHTML = htmlspecialchars(inpCity);
		}
	});
}

//function show tell a friend layer
//id - id of dealer, 0 - if we want to print all list
//itinerary - include itinerary url
function sendList(pos, id, itinerary) {
	//zoom on dealers if its position !=-1
	///if(pos != -1) {
	///	var point = new GLatLng(positions[pos][1], positions[pos][2]);
	///	map.setCenter(point, 11);
	///}
	//insert link to hidden field
	var linkUrl = EEHttpServer;
	if(isHomePage) {//we may send letter from main page, but it hasn't functionality to recognize id parameter
		linkUrl += quickSearchAction;
	} else {
		linkUrl += EEScriptName;
	}
	if(id != 0) {//if select send one dealer url
		linkUrl += '?id=' + id;
	} else if(inpId != '') {//if we must send itinerary page and user select dealer id
		linkUrl += '?id=' + inpId;
	} else {//user select country and city
		linkUrl += '?country=' + encodeURIComponent(inpCountry) + '&city=' + encodeURIComponent(inpCity);
	}
	if(itinerary) {
		linkUrl += '&from=' + encodeURIComponent(inpFrom) + '&to=' + encodeURIComponent(inpTo);
		if(linkUrl.indexOf('?id=') == -1) {
			linkUrl += '&did=' + parseInt(inpDid)
		}
	}
	document.getElementById('link').value = linkUrl;
	//if user got somethink in search results
	if(count>0) {
		showTellAFriend();
	}
}

//function print list of shown dealers if id param=0, or just one retailer if in id param=id of dealer
function printList(id) {
	var printUrl = dealersPrintPageUrl;
	var params = new Array();
	if(id != 0) {
		params.push('id=' + parseInt(id));
	} else if(inpId != '') {
		params.push('id=' + parseInt(inpId));
	} else {
		params.push('lat=' + latitude);
		params.push('lng=' + longitude);
	}
	if(inpCountry != '') {
		params.push('country=' + encodeURIComponent(inpCountry));
	}
	if(inpCity != '') {
		params.push('city=' + encodeURIComponent(inpCity));
	}
	printUrl += isUrlHasParams(printUrl) + params.join('&');
	//if user got somethink in search results
	
	if(count>0) {
		//window.location.href = printUrl;
		window.open(printUrl ,'newwindow');
	}
}

//TELL A FRIEND

//function check if tell a friend field filled correct or not
function checkTellAFriendField(id, normalClass, errorClass, check_email) {
	var fieldObject = document.getElementById(id);
	if(fieldObject.value == '' || (check_email && !/^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,6}$/i.test(fieldObject.value))) {
		tellAFriendReturn = false;
		fieldObject.className = errorClass;
		document.getElementById('sl_'+id+'_error').style.display = 'block';
	} else {
		fieldObject.className = normalClass;
	}
}

//function set new class to specified layer
function setErrorClass(id, newClass) {
	document.getElementById(id).className = newClass;
}

//function used for clearing form fields values
function clearFieldValue(id, isCheckbox) {
	if(isCheckbox) {
		document.getElementById(id).checked = false;
	} else {
		document.getElementById(id).value = '';
	}
}

//function show tell a friend layer
var tellAFriendReturn;
function submitTellAFriend() {
	var normTextClass = "club_input store_locator_tell_a_friend_input_text";
	var errorTextClass = normTextClass + " store_locator_tell_a_friend_input_text_error";
	var normTextTextarea = "club_input store_locator_tell_a_friend_textarea";
	var errorTextTextarea = normTextTextarea + " store_locator_tell_a_friend_input_text_error";
	tellAFriendReturn = true;
	var mandatoryFields = ['name','email','to_email','message','code'];
	for(var num=0; num<mandatoryFields.length; num++) {
		document.getElementById('sl_'+mandatoryFields[num]+'_error').style.display = 'none';
	}
	checkTellAFriendField('name', normTextClass, errorTextClass, false);
	checkTellAFriendField('email', normTextClass, errorTextClass, true);
	checkTellAFriendField('to_email', normTextClass, errorTextClass, true);
	checkTellAFriendField('message', normTextTextarea, errorTextTextarea, false);
	checkTellAFriendField('code', '', 'store_locator_tell_a_friend_input_text_error', false);
	if(tellAFriendReturn) {
		//send form using ajax
		var tellAFriendFields = new Array('adm_template', 'name', 'email', 'to_email', 'message', 'code', 'link');
		var reqString = '';
		reqString = '&action=dealers_tell_a_friend';
		for(var i=0; i<tellAFriendFields.length; i++) {
			reqString = reqString + '&' + tellAFriendFields[i] + '=' + encodeURIComponent(document.getElementById(tellAFriendFields[i]).value);
		}
		reqString += '&to_yourself=' + ((document.getElementById('to_yourself').checked)?1:0);
		var ajax = new ajax_son(JS_EE_HTTP + JS_ACTION_FILE);
		ajax.onComplete = function()
		{
			if (ajax.response == '')
			{
				goToTellAFriendThanks();
			}
			else
			{
				var errors = ajax.response.split(",");
				for(var i=0; i<errors.length; i++) {
					switch(errors[i]) {
						case 'name':
							setErrorClass('name', errorTextClass);
						break;
						case 'email':
							setErrorClass('email', errorTextClass);
						break;
						case 'to_email':
							setErrorClass('to_email', errorTextClass);
						break;
						case 'to_email':
							setErrorClass('to_email', errorTextClass);
						break;
						case 'message':
							setErrorClass('message', errorTextTextarea);
						break;
						case 'code':
							setErrorClass('code', 'store_locator_tell_a_friend_input_text_error');
						break;
					}
				}
				refreshCaptcha();
			}
		}
		ajax.run(reqString);
	}
}

function goToTellAFriendThanks() {
	hideTellAFriend();
	showTellAFriendThanks();
}

//function hides height_fixer layer
function hideHeightFixer() {
	document.getElementById('store_locator_height_fixer').style.display = 'none';
}

//function set size ob current block the same as parent block has
function setHeightAsParentHas(currentId) {
	var currObj = document.getElementById(currentId);
	currObj.style.height = currObj.parentNode.offsetHeight + 'px';
}

function showTellAFriend() {
	//if height of parent is too smal we must enlarge it
	var minParentHeight = '360';
	
	if(!isHomePage) {
		var parentHeight = parseInt(document.getElementById('store_locator_tell_a_friend').parentNode.offsetHeight);
		if(minParentHeight>parentHeight) {
			var additionalHeight = minParentHeight - parentHeight;
			var heightFixerObject = document.getElementById('store_locator_height_fixer');
			heightFixerObject.style.height = additionalHeight + 'px';
			heightFixerObject.style.display = 'block';
		}
		//set correct height of tell a friend block
	setHeightAsParentHas('store_locator_tell_a_friend');
	}

	//clear previous input fields
	clearFieldValue('to_email', 0);
	clearFieldValue('to_yourself', 1);
	clearFieldValue('message', 0);
	clearFieldValue('code', 0);
	///refreshCaptcha();
	//show layer
	document.getElementById("captcha_dynamic_text_box").innerHTML = '<img src="'+JS_EE_HTTP + JS_ACTION_FILE+'?action=show_captcha_for_html_form&'+Math.random()+'" id="captcha_code" align="absmiddle"  border="0" alt="" />';
	document.getElementById("captcha_input_box").innerHTML = '<img src="'+EEHttp+'img/RT_Captcha.gif" width="24" height="24" border="0" alt="" onclick="document.getElementById(\'captcha_code\').src = \''+JS_EE_HTTP + JS_ACTION_FILE+'?action=show_captcha_for_html_form&amp;\'+Math.random(); return false;" />';
	document.getElementById('store_locator_tell_a_friend').style.display = 'block';
}
function hideTellAFriend() {
	hideHeightFixer();
	
	document.getElementById('store_locator_tell_a_friend').style.display = 'none';
}
function showTellAFriendThanks() {
	//set correct height of tell a friend block
	if(!isHomePage) {
		setHeightAsParentHas('store_locator_tell_a_friend_thanks');
	}
	document.getElementById('store_locator_tell_a_friend_thanks').style.display = 'block';
}
function hideTellAFriendThanks() {
	hideHeightFixer();

	document.getElementById('store_locator_tell_a_friend_thanks').style.display = 'none';
}
function refreshCaptcha() {
	document.getElementById('captcha_code').src = JS_EE_HTTP + JS_ACTION_FILE + "?action=show_captcha_for_html_form&" + Math.random();
	document.getElementById('code').value = '';
}

function initStoreLocatorItineraryMap() {
	initStoreLocatorQSMap(0);
	
	if(GBrowserIsCompatible()) {//check Browser Compatibility, that is not obligatory
		//get previously inputted user values
		inpId = getParam('id');
		//inpContinent = getParam('continent');
		inpCountry = getParam('country');
		inpState = getParam('state');
		inpCity = getParam('city');
		inpFrom = getParam('from');
		inpTo = getParam('to');
		inpDid = getParam('did') || inpId;
		
		iMap = new GMap2(document.getElementById("itinerary_map"));//create google map object
		
		iMap.enableScrollWheelZoom();//Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
		
		if(inpFrom != '' && inpTo != '') {
			//insert To value into search itinerary form
			document.getElementById('search_itinerary2').value = inpFrom;
			document.getElementById('search_itinerary2').focus();
			//perform itinearary search based on user inpouted values
			searchItinerary(1, 0);
		} else {
			document.getElementById('itinerary_route').innerHTML = '<div class="store_locator_search_results_not_found">'+noSearchResults+'</div>'+"\n";
			__show_mt();//show emails in message
		}
	}
}

function initStoreLocatorItineraryMapPrint() {
	if(GBrowserIsCompatible()) {//check Browser Compatibility, that is not obligatory
		//get previously inputted user values
		inpId = getParam('id');
		//inpContinent = getParam('continent');
		inpCountry = getParam('country');
		inpState = getParam('state');
		inpCity = getParam('city');
		inpFrom = getParam('from');
		inpTo = getParam('to');
		inpDid = getParam('did') || inpId;
		
		iMap = new GMap2(document.getElementById("map_canvas"));//create google map object
		
		iMap.enableScrollWheelZoom();//Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
		
		if(inpFrom != '' && inpTo != '') {
			//perform itinearary search based on user inpouted values
			searchItinerary(1, 1);
		}
	}
}

//function send itinerary form
function sendItinerary() {
	//clear previous errors
    document.getElementById('tb_footer').style.display = 'none';
	
	var from = document.getElementById('search_itinerary').value;
	
	if(from.trim() == '') {//check if user filled field
		document.getElementById('tb_footer').innerHTML = missingQueryText;
		document.getElementById('tb_footer').style.display = 'block';
		return false;
	}
	
	var to = positions[itineraryId][1] + ', ' + positions[itineraryId][2];
	var did = positions[itineraryId][0];
	
	gdir = new GDirections(map);//This class is used to obtain driving directions results and display them on a map and/or a text panel.
	
	GEvent.addListener(gdir, "error", function() {//if we can't find itinerary, output error
		handleItineraryErrors('tb_footer');
	});
	
	GEvent.addListener(gdir, "load", function() {//if we can find itinerary, go to itinerary page
		if(inpId != '') {
			window.location.href = itineraryPageUrl + isUrlHasParams(itineraryPageUrl) + 'id=' + parseInt(inpId) + '&from=' + encodeURIComponent(from) + '&to=' + encodeURIComponent(to);
		} else {
			window.location.href = itineraryPageUrl + isUrlHasParams(itineraryPageUrl) + 'country=' + encodeURIComponent(inpCountry)+ ((inpState == '')?'':'&state=' + encodeURIComponent(inpState)) + '&city=' + encodeURIComponent(inpCity) + '&from=' + encodeURIComponent(from) + '&to=' + encodeURIComponent(to) + '&did=' + parseInt(did);
		}
	});
	
	gdir.load("from: " + escapeGet(from) + " to: " + escapeGet(to));
}

var currentCellColor;
function highlightCell(cellObj, restoreColor) {
	if(restoreColor) {
		cellObj.style.backgroundColor = currentCellColor;
	} else {
		//store current color
		currentCellColor = cellObj.style.backgroundColor;
		if(!currentCellColor) {
			currentCellColor = 'rgb(255,255,255)';
		}
		cellObj.style.backgroundColor = '#D4D4D4';
	}
}

var minBottomPos = null;
var posOfParent = null;
function handleItineraryStepClick(step) {
	//reset color of all tr elements
	document.getElementById('step_f').style.backgroundColor = '#ffffff';
	document.getElementById('step_l').style.backgroundColor = '#ffffff';
	for(var z=0; z<numOfSteps; z++) {
		try {
			document.getElementById('step_'+z).style.backgroundColor = '#ffffff';
		} catch(e) {}
	}
	
	//change current color
	document.getElementById('step_'+step).style.backgroundColor='#D4D4D4';
	//store current color
	currentCellColor = document.getElementById('step_'+step).style.backgroundColor;
	//form html description
	//left arrow
	var additionalCursors = '<div class="itinearary_buttons">';
	if(step == 'f') {
		additionalCursors += '<img src="'+EEHttp+'images/prev_itinerary_p.gif" width="31" height="19" alt="" border="0" />';
	} else {
		if(step == 'l') {
			var prevStep = numOfSteps-1;
		} else if(step == 0) {
			var prevStep = '\'f\'';
		} else {
			var prevStep = step - 1;
		}
		additionalCursors += '<a href="#" onclick="handleItineraryStepClick('+prevStep+'); return false;"><img src="'+EEHttp+'images/prev_itinerary_a.gif" width="31" height="19" alt="" border="0" /></a>';
	}
	//right arrow
	if(step == 'l') {
		additionalCursors += '<img src="'+EEHttp+'images/next_itinerary_p.gif" width="31" height="19" alt="" border="0" />';
	} else {
		if(step == 'f') {
			var nextStep = 0;
		} else if(step == numOfSteps-1) {
			var nextStep = '\'l\'';
		} else {
			var nextStep = step + 1;
		}
		additionalCursors += '<a href="#" onclick="handleItineraryStepClick('+nextStep+'); return false;"><img src="'+EEHttp+'images/next_itinerary_a.gif" width="31" height="19" alt="" border="0" /></a>';
	}
	additionalCursors += '</div>';
	//select marker and description used for step
	var itineraryMarker,
		itineraryAddress;
	if(step == 'f') {
		itineraryMarker = firstCoordinates;
		itineraryAddress = firstAddress;
	} else if(step == 'l') {
		itineraryMarker = lastCoordinates;
		itineraryAddress = lastAddress;
	} else {
		itineraryMarker = stepsCoordinates[step];
		itineraryAddress = stepsAddresses[step];
	}
	//open buble window
	map.openInfoWindowHtml(itineraryMarker, '<div class="itineraryStepBubleText">'+itineraryAddress+'</div>'+additionalCursors);
	iMap.openInfoWindowHtml(itineraryMarker, '<div class="itineraryStepBubleText">'+itineraryAddress+'</div>'+additionalCursors);
	//move position of itinerary map then user click on itinerary step
	//find position of clicked row
	var currentObj = document.getElementById('step_'+step);
	var parentObj = document.getElementById('itinerary_route');
	var mapObj = document.getElementById('itinerary_map');
	var positionOfStep = currentObj.offsetTop;//position of top corner of itinerary step
	var elementsCounter = 0;
	if(step != 'f') {
		//add height of first (or and second) table
		for(var z = 0; z < parentObj.childNodes.length; z++) {
			if (parentObj.childNodes[z].nodeType == 1) {
				positionOfStep += parentObj.childNodes[z].offsetHeight;
				elementsCounter++;
			}
			if((step != 'l') || (step == 'l' && elementsCounter == 2)) {
				break;
			}
		}
	}
	
	//find min and max bottom position
	var heightOfMap = mapObj.offsetHeight;
	var heightOfParent = parentObj.offsetHeight;
	var ua = navigator.userAgent.toLowerCase();
	//var subHeight = (ua.indexOf("firefox") != -1)?0:4;//add margin-top: 4px in first table in all browsers except Mozilla
	
	if(minBottomPos == null) {
		minBottomPos = mapObj.offsetTop;//save position of map
	}
	var maxBottomPos = heightOfParent - heightOfMap;
	if(posOfParent == null) {
		posOfParent = getAbsoluteHeight(document.getElementById('store_locator_main_block_search'));
	}
	var maxVisBottomPos = getWindowHeight() + getWindowScrollHeight() - minBottomPos - heightOfMap - posOfParent;
	
	//positionOfStep - height of top corner of itinerary step tr
	//subHeight - standart position of map by default, related to parent element
	//62 - height of blocks "you itinerary" and "print itinerary", "send itinerary", ...
	//5 - margin of first and last tables
	//4 - margin-top or margin-bottom of tables
	var newPositionOfStep;
	
	if(positionOfStep + 4 + 62 - 5 < minBottomPos) {//check top position
		newPositionOfStep = 0;
	} else if(positionOfStep > maxBottomPos) {//check bottom browser position
		newPositionOfStep = maxBottomPos - minBottomPos + 4*2 + 62;
	} else {
		newPositionOfStep = positionOfStep - minBottomPos + 4 + 62 - 5;
	}
	
	//check if new position of map is visible on screen
	if(newPositionOfStep > maxVisBottomPos) {//check bottom
		newPositionOfStep = maxVisBottomPos - 5;
	}
	if(newPositionOfStep < 0) {//check top
		newPositionOfStep = 0;
	}
	
	//set new position of itinerary map
	mapObj.style.top = newPositionOfStep+'px';
}

//function calculate absolute position of element
function getAbsoluteHeight(obj) {
	var height = 0;
	if (obj.offsetParent) {
		do {
			height += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return height;
}


//function return height of visible area of window
function getWindowHeight() {
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

//function return height of scrolled area
function getWindowScrollHeight() {
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}


var numOfSteps;
var stepsCoordinates = [];//coordinates of each itinerary step
var stepsAddresses = [];
var firstCoordinates,
	lastCoordinates,
	firstAddress,
	lastAddress;

//function used for itinerary search
//it check if search has results and in success redirect page to new url
function searchItinerary(skipSubmit, forPrint) {
	//clear previous errors
	try {
		document.getElementById('tb_footer2').style.display = 'none';
	} catch (e) { }
	
	var from, to, did;
	to = inpTo;
	did = inpDid;
	from = inpFrom;
	if(!skipSubmit) {
		try {
			from = document.getElementById('search_itinerary2').value;
		} catch(e) { }
	}
	
	//create itinearary results object
	gdir2 = new GDirections(map);
	gdir = new GDirections(iMap);//This class is used to obtain driving directions results and display them on a map and/or a text panel.
	GEvent.addListener(gdir, "error", function() {
		handleItineraryErrors('tb_footer2');
		if(skipSubmit) {
			document.getElementById('itinerary_route').innerHTML = '<div class="store_locator_search_results_not_found">'+noSearchResults+'</div>'+"\n";
			__show_mt();//show emails in message
		}
	});
	
	GEvent.addListener(gdir, "load", function() {
		
		var ret = '';//html for itinerary result
		var numOfRoutes = gdir.getNumRoutes();
		
		//add on maim map polyline
		//doesn't works
		//map.addOverlay(gdir.getPolyline());
		
		if(numOfRoutes > 0) {//if found
			var route = gdir.getRoute(0);
			numOfSteps = route.getNumSteps();
			var startGeocode = route.getStartGeocode();
			var endGeocode = route.getEndGeocode();
			
			firstCoordinates = gdir.getMarker(0).getPoint();
			lastCoordinates = gdir.getMarker(1).getPoint();
			
			firstAddress = '<b>'+startGeocode.address+'</b>';
			lastAddress = '<b>'+endGeocode.address+'</b>';
			
			ret += '<table cellspacing="0" class="itinerary_results_main first_itinerary_table';
			if(forPrint) {
				ret += ' itinerary_results_print_header';
			}
			ret += '">'+"\n";
			if(forPrint) {
				ret += '<tr>'+"\n";
				ret += '	<td colspan="3"><img src="'+EEHttp+'images/dealers-print-line-medium.gif" width="537" height="2" alt=""></td>'+"\n";
				ret += '</tr>'+"\n";
			}
			ret += '<tr id="step_f"';
			if(!forPrint) {
				ret += ' onmouseover="highlightCell(this, 0);" onmouseout="highlightCell(this, 1);" onclick="handleItineraryStepClick(\'f\');"';
			}
			ret += '>'+"\n";
			ret += '	<td class="itinerary_first_td"><img src="'+EEHttp+'images/icon_greenA.png" width="24" height="38" border="0" alt="" /></td>'+"\n";
			if(!forPrint) {
				ret += '	<td>'+firstAddress+'</td>'+"\n";
				ret += '	<td class="itinerary_last_td"><b>'+gdir.getSummaryHtml()+'</b></td>'+"\n";
				ret += '</tr>'+"\n";
				ret += '<tr>'+"\n";
				ret += '	<td colspan="3" class="itinerary_td_separator">&nbsp;</td>'+"\n";
			} else {
				ret += '	<td colspan="2" class="itinerary_second_td">'+dealersPrintItineraryFrom+'<br />'+firstAddress+'</td>'+"\n";
				ret += '</tr>'+"\n";
				ret += '<tr>'+"\n";
				ret += '	<td colspan="3"><img src="'+EEHttp+'images/dealers-print-line-medium.gif" width="537" height="2" alt=""></td>'+"\n";
				ret += '</tr>'+"\n";
				ret += '<tr>'+"\n";
				ret += '	<td colspan="3" class="itinerary_last_td"><b>'+gdir.getSummaryHtml()+'</b></td>'+"\n";
				ret += '</tr>'+"\n";
				ret += '<tr>'+"\n";
				ret += '	<td colspan="3"><img src="'+EEHttp+'images/dealers-print-line-medium.gif" width="537" height="2" alt=""></td>'+"\n";
			}
			ret += '</tr>'+"\n";
			ret += '</table>'+"\n";
			
			if(numOfSteps > 0) {
				ret += '<table cellspacing="0" class="itinerary_results';
				if(forPrint) {
					ret += ' itinerary_results_print_main';
				}
				ret += '">'+"\n";
				for (var z=0; z<numOfSteps; z++) {
					var step = route.getStep(z);
					var summary = step.getDescriptionHtml();
					stepsCoordinates.push(step.getLatLng());
					stepsAddresses.push(summary);
					ret += '<tr id="step_'+z+'"';
					if(!forPrint) {
						ret += ' onmouseover="highlightCell(this, 0);" onmouseout="highlightCell(this, 1);" onclick="handleItineraryStepClick('+z+');"';
					} else if(z%2!=0) {
						ret += ' class="itinerary_tr_even"';
					}
					ret += '>'+"\n";
					ret += '	<td class="itinerary_first_td">'+(z+1)+'.</td>'+"\n";
					ret += '	<td>'+summary+'</td>'+"\n";
					ret += '	<td style="width: 75px;" class="itinerary_last_td">'+step.getDistance().html+'</td>'+"\n";
					ret += '</tr>'+"\n";
					if(!forPrint) {
						ret += '<tr>'+"\n";
						ret += '	<td colspan="3" class="itinerary_td_separator">&nbsp;</td>'+"\n";
						ret += '</tr>'+"\n";
					}
				}
				ret += '</table>'+"\n";
			}
			
			if(!forPrint) {
				ret += '<table cellspacing="0" class="itinerary_results_main last_itinerary_table">'+"\n";
				ret += '<tr id="step_l"';
				if(!forPrint) {
					ret += ' onmouseover="highlightCell(this, 0);" onmouseout="highlightCell(this, 1);" onclick="handleItineraryStepClick(\'l\');"';
				}
				ret += '>'+"\n";
				ret += '	<td class="itinerary_first_td"><img src="'+EEHttp+'images/icon_greenB.png" width="24" height="38" border="0" alt="" /></td>'+"\n";
				ret += '	<td colspan="2">'+lastAddress+'</td>'+"\n";
				ret += '</tr>'+"\n";
				ret += '</table>'+"\n";
			}
		}
		
		if(!skipSubmit) {
			if(inpId != '') {
				window.location.href = EEScriptName + '?id=' + parseInt(inpId) + '&from=' + encodeURIComponent(from) + '&to=' + encodeURIComponent(to);
			} else {
				window.location.href = EEScriptName + '?country=' + encodeURIComponent(inpCountry) + '&city=' + encodeURIComponent(inpCity) + '&from=' + encodeURIComponent(from) + '&to=' + encodeURIComponent(to) + '&did=' + parseInt(did);
			}
		}
		//hide loading image
		if(skipSubmit) {
			//document.getElementById('itinerary_route').innerHTML = ret;
			$("#itinerary_route").html(ret);
		}
		
		//insert copyright
		//var copyrightObject = document.getElementById('store_locator_itinerary_copyright');
		//copyrightObject.innerHTML = gdir.getCopyrightsHtml();
		//copyrightObject.style.display = 'block';
	});
	//retrieve new results
	gdir2.load("from: " + escapeGet(from) + " to: " + escapeGet(to), {getSteps:true, getPolyline:true});//for main map
	gdir.load("from: " + escapeGet(from) + " to: " + escapeGet(to), {getSteps:true, getPolyline:true});//for itinerary map
	
	//zoom only once at start
	///if(skipSubmit) {
	///	//set zoomlevel for current active markers
	///	zoomShowAll(map2, gdir);
	///}
}
//function runs when we've got errors as itinerary search result
function handleItineraryErrors(errorLayerId){
	var strGeoAlert = '';
	switch(gdir.getStatus().code) {
		case G_GEO_SUCCESS://200
			strGeoAlert = '';
		break;
		case G_GEO_BAD_REQUEST://400
			strGeoAlert = badRequestText;
		break;
		case G_GEO_SERVER_ERROR://500
			strGeoAlert = errorHasOccured;
		break;
		case G_GEO_MISSING_QUERY://601
			strGeoAlert = missingQueryText;
		break;
		case G_GEO_UNKNOWN_ADDRESS://602
			strGeoAlert = noGeographicLocationText;
		break;
		case G_GEO_UNAVAILABLE_ADDRESS://603
			strGeoAlert = unavailableAddressText;
		break;
		case G_GEO_UNKNOWN_DIRECTIONS://604
			strGeoAlert = unknownDirectionsText;
		break;
		case G_GEO_BAD_KEY://610
			strGeoAlert = keyIsInvalidText;
		break;
		case G_GEO_TOO_MANY_QUERIES://620
			strGeoAlert = tooManyQueriesText;
		break;
		default:
			strGeoAlert = unknownErrorOcuuredText;
		break;
	}
	//return error to search itinerary form
	if(strGeoAlert != '') {
		try {
			document.getElementById(errorLayerId).innerHTML = strGeoAlert;
			document.getElementById(errorLayerId).style.display = 'block';
		} catch(e) {}
	}
}

//function used for redirecting user to itinerary print page
function printItineraryList() {
	var printUrl = dealersPrintItineraryPageUrl;
	var params = new Array();
	if(inpFrom) {
		params.push('from=' + encodeURIComponent(inpFrom));
	}
	if(inpTo) {
		params.push('to=' + encodeURIComponent(inpTo));
	}
	if(inpDid) {
		params.push('did=' + parseInt(inpDid));
	}
	printUrl += isUrlHasParams(printUrl) + params.join('&');
	//window.location.href = printUrl;
	window.open(printUrl ,'newwindow');
}

function backToSearch() {
	var backUrl = quickSearchAction;
	var params = new Array();
	
	if(inpCountry) {
		params.push('country=' + encodeURIComponent(inpCountry));
	}
	if(inpState) {
		params.push('state=' + encodeURIComponent(inpState));
	}
	if(inpCity) {
		params.push('city=' + encodeURIComponent(inpCity));
	}
	backUrl += isUrlHasParams(backUrl) + params.join('&');
	window.location.href = backUrl;
}

function htmlspecialchars(text) {
	text = text.replace(/&/g, "&amp;");
	text = text.replace(/</g, "&lt;");
	text = text.replace(/>/g, "&gt;");
	return text;
}

/*** Show retailers displayed on this map BEGIN ***/
function showMapDealers() {
	var mapBounds = map._getBounds();
	
	var northEast = mapBounds.getNorthEast();
	var southWest = mapBounds.getSouthWest();
	
	var NELat = northEast.lat();
	var NELng = northEast.lng();
	var SWLat = southWest.lat();
	var SWLng = southWest.lng();
	
	$.ajax({
		url: JS_EE_HTTP+"action.php?action=show_map_dealers",
		data: "nelat="+NELat+
			"&nelng="+NELng+
			"&swlat="+SWLat+
			"&swlng="+SWLng+
			"&language="+language,
		dataType: "xml",
		success: function(xml) {
			var dealers = xml.documentElement.getElementsByTagName("dealer");
			
			var html = '<table width="100%"><tr>';
			
			for(var y = 0; y < dealers.length; y++) {
				var name = dealers[y].getAttribute("name");
				var name2 = dealers[y].getAttribute("name2");
				var street = dealers[y].getAttribute("street");
				var street2 = dealers[y].getAttribute("street2");
				var zip = dealers[y].getAttribute("zip");
				var city = dealers[y].getAttribute("city");
				var phone = dealers[y].getAttribute("phone");
				var fax = dealers[y].getAttribute("fax");
				var email = dealers[y].getAttribute("email");
				var id = dealers[y].getAttribute("id");
				var url = dealers[y].getAttribute("url");
				var url2 = dealers[y].getAttribute("url2");
				var country = dealers[y].getAttribute("country");
				
				urlLink = makeUrlLink(url);
				url2Link = makeUrlLink(url2);
				
				if(y != 0 && y != dealers.length && y % 3 == 0) {
					html += '</tr><tr>';
				}
				
				html += '<td valign="top">'+
					'<p style="margin-top: 15px;"><b>'+name+'</b></p>'+
					'<p>';
				if(name2 != '') html += name2+'<br />';
				html += street+'<br />';
				if(street2 != '') html += street2+'<br />';
				html += zip+' '+city+' '+country+'<p/>';
				if(phone != '') html += dealersTelText+' '+phone+'<br />';
				if(fax != '') html += dealersFaxText+' '+fax+'<br />';
				if(email != '') html += dealersEmailText+' <a href="mail'+'to:'+email+'">'+email+'</a><br />';
				if (url != '' || url2 != '') {
					dealersWebSiteText = (url != '' && url2 != '') ? dealersUrlsText : dealersUrlText;
					html += '<table cellcpacing="0" cellpadding="0" border="0">';
					html += '<tr><td valign="top"'+((url != '' && url2 != '') ? ' rowspan="2"' : '')+'>'+dealersWebSiteText+' </td>';
					if(url != '') html += '<td><a target="_blank" href="'+urlLink+'">'+url+'</a></td></tr>';
					if(url2 != '') html += '<tr><td><a target="_blank" href="'+url2Link+'">'+url2+'</a></td></tr>';
					html += '</table>';
				}
				html += '</td>';
			}
			
			html += '</tr></table>';
			
			$("#map_dealers").html(html);
		}
	});
}
/*** Show retailers displayed on this map END ***/
