var map;
var mapBounds;
var southWest;
var northEast;
var searchOptionalVars;
var showMapItemsOnly = false;
var pagingNext;
var listItemClick;
var firm_map_update = true;
var marker_click = false;
var marker_click_firm_id;
//var search_vars_url;
//var search_map_vars_url;

//directions
var gdirection;
var geocoder = null;

//layers
var map_layer_title = {map_layer_wikipedia:"org.wikipedia."+LANGUAGE, map_layer_panoramio_photo:"com.panoramio.all"};
var map_layer = {};
	
//cat coord
var linear_max = 2;
var category_icon_width = 18;
var category_icon_space = 2;

//XMLHttpRequest object
//var request_markers;

var existingMarkers = {};
var frls_id;
var frls_old_id;
//var showInfoWindow = false;

//categories
var category_existing_markers = {};
var category_map_update = true;
var category_map_update_count = 0;
//map search
var firm_existing_markers = {};

//map gdirection
var gdirection_existing_markers = {};
var gdirection_polyline;
var gdirection_set_value = false;
var gdirection_waypoint_id;
var gdirection_waypoint_old_id;
var gdirection_point_selected = {start:false, end:false};

//adress point
var address_point_set_value = false;
var address_point_existing_markers = {};

//maps_list
var firm_map_list;
var firm_map_list_existing_markers = {};
var firm_map_list_id;
var firm_map_list_old_id;
var firm_map_list_activate = false;

//firm_map_single
var firm_map_single;
var firm_map_single_existing_markers = {};

//firm info page map
var firm_map_info;
var firm_map_info_existing_markers = {};

//default type all control (0), minimal map - (1)
var map_type = 0;


$(document).ready(function(){

	
	if($("#Maps_popup").length){
		//init map
		initAjaxLoader();
	}
	
	if($("#Maps_firm_info").length){
		//init map
		initAjaxLoader();
		map_type = 1;
	}


});


function get_map_search_vars(){
	//which form
	if(!$("#search_map_form_greita").hasClass("ui-tabs-hide")){
		search_map_form = '#search_map_form_1';
	}else{
		search_map_form = '#search_map_form_2';
	}
	//serialize forms
	search_form_vars = $(search_map_form).serialize();
	filter_form_vars = $("#search_filter_form").serialize();
	search_form_vars_url = search_form_vars;
	if(filter_form_vars){
		search_form_vars_url += "&" + filter_form_vars;
	}
	//alert(filter_form_vars);
	//get map vars if map exists
	if(mapBounds){
		southWest = mapBounds.getSouthWest();
		northEast = mapBounds.getNorthEast();
		search_form_vars_url +=  '&nelatitude=' + northEast.y + '&nelongitude=' + northEast.x + '&swlatitude=' + southWest.y + '&swlongitude=' + southWest.x;
	}
	return search_form_vars_url;
}

function get_map_search_optional_vars(){
	search_optional_vars_url = '';
	if(searchOptionalVars){
		search_optional_vars_url += 'Nuo=' + searchOptionalVars['Nuo'] + '&Kiek=' + searchOptionalVars['Kiek'];
		return search_optional_vars_url;
	}
	return false;
	
}

function category_map_vars(){

	//serialize forms
	category_form_vars = $("#category_list_form").serialize()
	
	if(!category_form_vars){
		return false;
	}
	//get map vars if map exists
	if(mapBounds){
		southWest = mapBounds.getSouthWest();
		northEast = mapBounds.getNorthEast();
		category_form_vars +=  '&nelatitude=' + northEast.y + '&nelongitude=' + northEast.x + '&swlatitude=' + southWest.y + '&swlongitude=' + southWest.x;
	}
	return category_form_vars;
}


function category_list_load(){
	//loading
	result_loading("#category_list");
	//load
	$.get(URL+'map.php?api=category', function(data){
		category_list_generate("#category_list", data);
	});
}

function category_list_generate(element_id, json_data){
	$(element_id).html('');

	var category_list_html;
	var category_list;
	var category_more;
	
	eval(json_data);
	
	
	if(category_list_html.category_list){
		$(element_id).append(category_list_html.category_list);
		
		$("#category_list_form input[type='checkbox']").click(function(){
			checkbox = $("#category_list_form input[type='checkbox']:checked");
			if(checkbox.length>MAP_CATEGORY_CHECKED_MAX){
				alert(js_translation.MapCategoryCheckedMaxError);
				return false;
			}
			if(category_map_update_count <= 0){
				category_map_update_markers(true);
			}else{
				//stats
				$.ajax({url:URL+"map.php?api=statistika&statistika_objektas=zemelapiai_greitos_veiklos", cache:false});
				category_map_update_markers();
			}
		});
		
		$("#category_list_form select").change(function(){
			checkbox = $("#category_list_form input[type='checkbox']:checked");
			if(checkbox.length>0){
				category_map_update_markers(true);
			}
		});	
		
		$("#category_group_1").toggle(
			function () {
				$("#category_group_expand_1").removeClass("hide");
				$(this).removeClass("icon_expand");
				$(this).addClass("icon_collapse");
			},
			function () {
				$("#category_group_expand_1").addClass("hide");
				$(this).removeClass("icon_collapse");
				$(this).addClass("icon_expand");
			}			
		);

		
		
		
		
		/*										
		$("#search_firm_result_paging a").click(function(){	
			searchOptionalVars = parseParams($(this).attr("href"));
			pagingNext = true;
			search_map_form_submit();								 
			return false;												
		});
		*/
	}
}


//function category_map_form_submit(){
	//category_map_form_vars_url = category_map_vars();
	//if(category_map_form_vars_url){
		//category_map_update_markers();
	//}
//}


function search_map_form_submit(){

/*
	//which form
	
	if(!$("#search_map_form_greita").hasClass("ui-tabs-hide")){
		search_map_form = '#search_map_form_1';
	}else{
		search_map_form = '#search_map_form_2';
	}
	//serialize forms
	search_form_vars = $(search_map_form).serialize();
	filter_form_vars = $("#search_filter_form").serialize();
	search_form_vars_url = search_form_vars;
	if(filter_form_vars){
		search_form_vars_url += "&" + filter_form_vars;
	}
	
	//get map vars if map exists
	if(mapBounds){
		southWest = mapBounds.getSouthWest();
		northEast = mapBounds.getNorthEast();
		search_form_vars_url +=  '&ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue();
	}
	if(SearchVars){
		search_form_vars_url += '&Nuo=' + SearchVars['Nuo'] + '&Kiek=' + SearchVars['Kiek'];
	}
*/	
	search_optional_vars_url = get_map_search_optional_vars();
	//alert(search_optional_vars_url);
	if(search_optional_vars_url && pagingNext){
		search_optional_vars_url = '&' + search_optional_vars_url;
		pagingNext = false;
	}else{
		search_optional_vars_url = '';
	}
	search_form_vars_url = get_map_search_vars() + search_optional_vars_url;
	//alert(search_optional_vars_url);
	//alert(search_form_vars_url);
	//search object
	//searchVal = getSearchVal();
	//searchValUrl = setSerachValUrl(searchVal);
	
	//var search_map_form_1 = $("#search_map_form_1").serialize();

	//alert(str);


	//if(url==undefined || url==''){
		//query = '';
		//query += 'Veikla='.$("#search_map_form_1 input[name='Veikla']").val();
		
		//query = $("#search_map_form_1 input[name='Veikla']").val();
		//if(query == undefined || query == '') return false;
		//url='zemelapiai_c/search.php?Veikla='+query+'&format=json&jsoncallback=?';
	//}
	result_loading("#search_firm_result_list");
	//$("#firm_count").html('');
	//activate
	//$("#Maps").accordion("activate", $("#search_firm_result_header"));
	//alert('map.php?map_api=firm&'+search_form_vars_url);
	//load
	$.get(URL+'map.php?api=firm&'+search_form_vars_url, function(data){
		search_map_generate_firm_list("#search_firm_result_list", data);
	});

	

	
}

function parseParams(url) {
	var params=url;
	if (url.match(/\?(.+)$/)) {
	   // in case it is a full query string with ?, only take everything after the ?
	   params = RegExp.$1;
	}
	// split the params
	var pArray = params.split("&");
	// hash to store result
	var pHash = {};
	// parse each param in the array and put it in the hash
	for(var i=0;i<pArray.length;i++) {
		var temp = pArray[i].split("=");
		pHash[temp[0]] = unescape(temp[1]);
	}
	return pHash;
}




function show_error(element_id){
	$(element_id).html('');
}

function search_map_generate_firm_list(element_id, json_data){
	$(element_id).html('');
	
	var search_result;
	var search_result_point;
	var search_result_more;
	
	eval(json_data);
	
	//activate accordion list
	if(firm_map_list_activate)$("#Maps").accordion("activate", $("#search_firm_result_header"));
	
	if(!search_result_more.amount || search_result_more.amount == 0){
		$("#firm_count").html("0");
		if(firm_map_list_activate)$(element_id).append(search_result_more.no_result);
		return false;
	}
	
	$("#firm_count").html(search_result_more.amount);
	
	$(element_id).append(search_result.result_list);
	
	if(search_result_more.paging!=''){
		$(element_id).append(search_result_more.paging);
		
		$("#search_firm_result_paging a").click(function(){	
			searchOptionalVars = parseParams($(this).attr("href"));
			pagingNext = true;
			search_map_form_submit();								 
			return false;												
		});
	}
	
	//bind clicks
	$("#search_firm_result_list .item").click(function(){											
		//frls_old_id = frls_id;
		$("#search_firm_result_list div[id='"+frls_id+"']").removeClass("selected");
		frls_id = $(this).attr("id");
		$(this).removeClass("hover");
		$(this).addClass("selected");
		//onclick show place
		for (i in search_result_point) {
			if(search_result_point[i].id == frls_id){
				if(search_result_point[i].latitude && search_result_point[i].longitude){
					//showInfoWindow = true;
					map.closeInfoWindow();
					point = new GLatLng(search_result_point[i].latitude, search_result_point[i].longitude);
					map.setCenter(point, 15);
					marker_click = true;
					marker_click_firm_id = frls_id;
					//map.setZoom(17);
					//map.panTo(new google.maps.LatLng(search_result[i].latitude, search_result[i].longitude));
				}
			}
		}
		
	});
	//bind hover
	$("#search_firm_result_list .item").mouseover(function(){											
		if(frls_id!=$(this).attr("id"))$(this).addClass("hover");											
	});	
	$("#search_firm_result_list .item").mouseout(function(){											
		if(frls_id!=$(this).attr("id"))$(this).removeClass("hover");											
	});
	
}

function result_loading(element_id){
	$(element_id).html('<div class="loading"></div>');
}

//Maps
function initAjaxLoader() {
  var script = document.createElement("script");
  script.src = "http://www.google.com/jsapi?key="+GOOGLE_AJAX_KEY+"&callback=loadMaps";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}

function loadMaps() {
  google.load("maps", "2", {"callback" : mapsLoad, "language" : LANGUAGE});
}

function dragZoomControl() {
	//add map zoom control
	var boxStyleOpts = { opacity: .2, border: "2px solid yellow" };
	var otherOpts = {
	  buttonHTML: "<img src='"+URL+"images/zoom-control-inactive.png' />",
	  buttonZoomingHTML: "<img src='"+URL+"images/zoom-control-active.png' />",
	  buttonStartingStyle: {width: '17px', height: '17px'},
	  overlayRemoveTime: 0 ,
	  backButtonHTML: "<img src='"+URL+"images/zoom-control-back.png' />",
	  backButtonStartingStyle: {top: '0px', width: '17px', height: '17px'},
	  backButtonEnabled: true,
	  draggingOn: true
	  };
	map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(47,72)));

	// add large map control under the zoom control since the large map control has different sizes...
	//map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,32)));
}


function mapsLoad() {
  
	
	map = new google.maps.Map2(document.getElementById("map"));
	
	if(map_type == 1){
		map.addControl(new GSmallZoomControl());
		map.enableScrollWheelZoom();
		map.addControl(new GMapTypeControl());
		map.removeMapType(G_SATELLITE_MAP);
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
	}else{
		map.addMapType(G_PHYSICAL_MAP);
		map.setCenter(new GLatLng(0,0),0);
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.enableScrollWheelZoom();
		//map.enableContinuousZoom();
		//map.disableContinuousZoom();
		//map.continuousZoomEnabled();
		//map.enableGoogleBar();
		
		
		//geocoder = new GClientGeocoder(new GGeocodeCache());
		
		
		//create XMLHttpRequest object
		//request_markers = GXmlHttp.create();
		
		//extention
		include_js(URL+"js/dragzoom.js", "dragZoomControl");
	}
	
	map.setCenter(new google.maps.LatLng(centerLatitude, centerLongitude), startZoom);
	
	//for maps page
	if($("#Maps").length){
		//create geocoder object
		geocoder = new GClientGeocoder(new GGeocodeCache());
		//direction
		gdirection_activate();
		//address
		address_point_activate();
		//map layers
		map_layer_activate();
		
		
		firm_map_update_markers();
		
		GEvent.addListener(map,'moveend',function() {
	
			//activate when zoom also
			if(map.getInfoWindow().isHidden() ){
				if(firm_map_update)firm_map_update_markers();
				if(category_map_update)category_map_update_markers();
				if(showMapItemsOnly){
					search_map_form_submit();
				}
				//GLog.write('Move changed');
				
			}
		});
	
		GEvent.addListener(map,'dragend',function() {
			//GLog.write('Drag changed');
		});
		
		GEvent.addListener(map,'zoomend',function(oldLevel, newLevel) {
			//GLog.write('Zoom changed from ' + oldLevel + ' to ' + newLevel);
		});
	}
	
	
	//for firm list page
	if($("#Maps_list").length){
		maps_list_generate();	
	}
	
	//map popup
	if($("#Maps_popup").length){
		maps_popup_generate();	
	}
	
	if($("#Maps_firm_info").length){
		maps_firm_info_generate();
	}
	
	

//window.onload = init;
mapsLoaded = true;

	
}



function firm_map_update_markers(point_bound_zoom) {
	//remove the existing points
	//map.clearOverlays();
	//create the boundary for the data to provide initial filtering
	mapBounds = map.getBounds();
	var pointBounds = new GLatLngBounds();
	

	
	//loop through each of the points in memory and remove those that aren't going to be shown
	
	//ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
	//southWest = mapBounds.getSouthWest();
	//northEast = mapBounds.getNorthEast();
	//zemelapiai_c/search_map.php?
	//search_map_vars_url = search_vars_url + '&ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue()
	search_map_vars_url = get_map_search_vars();
	if(point_bound_zoom==true){
		search_map_vars_url += '&point_bound_zoom=1'
	}
	//log the URL for testing
	//GLog.write('map.php?api=firm_map&' + search_map_vars_url);
	//retrieve the points
	//GLog.write(request_markers.responseText);
	var request = GXmlHttp.create();
	request.open('GET', URL+'map.php?api=firm_map&' + search_map_vars_url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var jscript = request.responseText;
			var points;
			eval(jscript);
			//firm_existing_markers
			//map.clearOverlays();
			//GLog.write(search_map_vars_url);
			for(i in firm_existing_markers) {
				//if(!mapBounds.contains(category_existing_markers[i].getPoint())) {
					map.removeOverlay(firm_existing_markers[i]);
					delete firm_existing_markers[i];
				//}
			}
			//loop through each of the points from the global points object and create markers that don't exist
			for (i in points) {
				var point = new GLatLng(points[i].lat, points[i].lng);
				pointBounds.extend(point);
				//skip it if the marker already exists or is not in the viewable area
				//no need && mapBounds.contains(point)?
				if(!firm_existing_markers[i]) {
					firm_existing_markers[i] = firm_create_marker(point, points[i].type, points[i].label, points[i].label_type, points[i].id, i);
					map.addOverlay(firm_existing_markers[i]);
					//if(showInfoWindow){
						//showInfoWindow = false;	
						//if(points[i].id == frls_id)alert(marker.getInfoWindow());
					//}
				}
			}
			
			if(point_bound_zoom==true){
				firm_map_update = false;
				if(!points){
					map.setCenter(new google.maps.LatLng(centerLatitude, centerLongitude), startZoom);
				}else{
					map.setZoom(map.getBoundsZoomLevel(pointBounds));
					map.setCenter(pointBounds.getCenter());
				}
				firm_map_update = true;
			}
			
			if(marker_click){
				//click on marker_click_firm_id
				for (i in points) {
					for(j in points[i].id){
						if(points[i].id[j] == marker_click_firm_id){
							marker_click_id = i;
						}
					}
				}
				//GLog.write(marker_click+marker_click_firm_id);
				GEvent.trigger(firm_existing_markers[marker_click_id],"click");
				marker_click = false;
			}
			
		}
	}
	request.send(null);
}


function linear2square(linear, linear_max_count){
	var i=0;
	for(y=0;y<linear_max_count;y++){
		for(x=0;x<linear_max_count;x++){
			if(i == linear){
				return {
					x: x,
					y: y
				}
			}
			i++;
		}	
	}
}



function category_map_update_markers(category_point_bound_zoom) {
	category_map_update_count ++;
	//category_existing_markers
	//remove the existing points
	//map.clearOverlays();
	//create the boundary for the data to provide
	//initial filtering
	mapBounds = map.getBounds();
	var category_point_bounds = new GLatLngBounds();
	
	category_map_form_vars_url = category_map_vars();
	//if(!category_map_form_vars_url)return false;
	if(category_point_bound_zoom==true){
		category_map_form_vars_url += '&category_point_bound_zoom=1'
	}
	
	//log the URL for testing
	//GLog.write('map.php?api=category_map&' + category_map_form_vars_url);
	//retrieve the points
	var request = GXmlHttp.create();
	request.open('GET', URL+'map.php?api=category_map&' + category_map_form_vars_url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var jscript = request.responseText;
			var categories;
			eval(jscript);
			//alert(jscript);
			//map.clearOverlays();
			//loop through each of the points in memory and remove those that
			//aren't going to be shown
			for(i in category_existing_markers) {
				//if(!mapBounds.contains(category_existing_markers[i].getPoint())) {
					map.removeOverlay(category_existing_markers[i]);
					delete category_existing_markers[i];
				//}
			}
			//loop through each of the points from the global points object
			//and create markers that don't exist
			k = 1;
			for (i in categories) {
				//GLog.write(print_r(categories[i].category_group));
				//GLog.write(categories[i].count);
				
				var point = new GLatLng(categories[i].lat, categories[i].lng);

				square = linear2square(categories[i].count, linear_max);
				//GLog.write(categories[i].count + " : " + square.x +":"+ square.y);
				//alert(square);
				//GLog.write((categories[i].count%2));
				if(categories[i].type == "c"){
					point_x_move = map.fromLatLngToContainerPixel(point).x + (category_icon_width+category_icon_space) * square.x - category_icon_width/2 - category_icon_space;
					point_y_move = map.fromLatLngToContainerPixel(point).y + (category_icon_width+category_icon_space) * square.y - category_icon_width/2 - category_icon_space;
					point = map.fromContainerPixelToLatLng(new GPoint(point_x_move, point_y_move));
				}
				
				category_point_bounds.extend(point);
				
				//skip it if the marker already exists or is not in the viewable area
				//Don't need && mapBounds.contains(point) ?
				if(!category_existing_markers[i]) {
					category_existing_markers[i] = category_create_marker(point, categories[i].type, categories[i].label, categories[i].id, categories[i].category_id, i);
					map.addOverlay(category_existing_markers[i]);
					
					
					map.addOverlay(category_existing_markers[i]);

					//if(showInfoWindow){
						//showInfoWindow = false;	
						//if(points[i].id == frls_id)alert(marker.getInfoWindow());
					//}
				}

			}
			//GLog.write(category_point_bound_zoom);
			if(category_point_bound_zoom==true){
				category_map_update = false;
				if(!categories){
					map.setCenter(new google.maps.LatLng(centerLatitude, centerLongitude), startZoom);
				}else{
					map.setZoom(map.getBoundsZoomLevel(category_point_bounds));
					map.setCenter(category_point_bounds.getCenter());
				}
				category_map_update = true;
			}
			
			
			
		}
	}
	request.send(null);
}


function marker_importance_order (marker) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}


function firm_create_marker(point, type, label, label_type, id, i) {
	//create the marker with the appropriate icon

	if(type=='c') {
		importance = 0;
		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/marker_g.png";
		//iconCluster.shadow = "";
		icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor = new GPoint(12, 12);
		icon.infoShadowAnchor = new GPoint(12, 12);
	}else{
		//create an icon for the pins
		var icon = new GIcon();
		//icon.image = "map.php?api=firm_marker&label="+label[0]+"&label_type="+label_type[0]+"&fix=.png";
		if(label_type[0]>1){
			marker_dir = "/"+label_type[0];
		}else{
			marker_dir = "";
		}
		icon.image = URL+"images/icon/marker"+marker_dir+"/"+label[0]+".png";
		icon.shadow = URL+"images/icon/map/shadow_"+label[0].toString().length+".png";
		//iconSingle.iconSize = new GSize(12, 20);
		//iconSingle.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(4, 30);
		icon.infoWindowAnchor = new GPoint(12, 10);
		icon.infoShadowAnchor = new GPoint(12, 10);
	}
	
	importance = 0;
	if(label_type[0]==1)importance = 10;
	if(label_type[0]==2)importance = 1;
	//if(type=='c')importance = 0;
	

	markerOptions = {icon:icon, zIndexProcess:marker_importance_order};

	var marker = new GMarker(point, markerOptions);
	marker.label = label;
	marker.label_type = label_type;
	marker.importance = importance;
	marker.id = id;
	marker.point = point;
	
	GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowHtml("Marker <b>" + label +"," +id+ "</b>");
		//marker.openInfoWindowHtml('<img src="images/loading.gif">');//lol
		//marker.openInfoWindowHtml('index.php?page=zemelapis_imone_info&view=imone&more=no&number='+label+'&id='+id);
		//alert(encodeURIComponent('zemelapiai_c/search_marker_view.php?id='+id+'&label='+label));
		if(marker_click){
			limit_list = '&limit=100';
		}else{
			limit_list = '';
		}
		//GLog.write('map.php?api=firm_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label) + limit_list);
		GDownloadUrl(URL+'map.php?api=firm_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label) + limit_list, function(data, responseCode) {
		marker.openInfoWindowHtml(data, {onOpenFn:infowindow_scroll_to('#marker_info_window', '#info_item_'+marker_click_firm_id, 1000)});
	});
	});
	
	return marker;
}

function infowindow_scroll_to(infowindow_id, anchor_id, timeout){
	setTimeout(function() {
		if($(infowindow_id).length && $(anchor_id).length){
			$(infowindow_id).scrollTo($(anchor_id),0);
		}
	},timeout);
}


function infowindow_gdirection_set(latitude, longitude, type) {
	//$("#Maps").accordion("activate", $("#get_directions_header"));
	point = new GLatLng(latitude, longitude);
	//gdirection_set(point, type);
	gdirection_set_marker(point, type, true);
}


function category_create_marker(point, type, label, id, category_id, i) {
	//create the marker with the appropriate icon
	
	if(type=='c') {
		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/category/"+category_id+".gif";
		//GLog.write(point);
		//iconCluster.shadow = "";
		icon.iconSize = new GSize(18, 18);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(9, 9);
		icon.infoWindowAnchor = new GPoint(9, 9);
		icon.infoShadowAnchor = new GPoint(9, 9);
	}else{
		//create an icon for the pins
		var icon = new GIcon();
		icon.image = URL+"images/icon/category/"+category_id+".gif";
		//iconSingle.shadow = "images/icon/category/shadow_"+label[0].length+".png";
		icon.iconSize = new GSize(18, 18);
		//iconSingle.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(9, 9);
		icon.infoWindowAnchor = new GPoint(9, 9);
		icon.infoShadowAnchor = new GPoint(9, 9);
	}
	
	//GLog.write(icon.image);

	markerOptions = {icon:icon};
	
	var marker = new GMarker(point, markerOptions);
	marker.label = label;
	marker.id = id;
	marker.point = point;
	marker.category_id = category_id;
	//marker.markerOptions = markerOptions;
	GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowHtml("Marker <b>" + label +"," +id+ "</b>");
		//marker.openInfoWindowHtml('<img src="images/loading.gif">');//lol
		//marker.openInfoWindowHtml('index.php?page=zemelapis_imone_info&view=imone&more=no&number='+label+'&id='+id);
		//alert(encodeURIComponent('zemelapiai_c/search_marker_view.php?id='+id+'&label='+label));
		//GLog.write('map.php?api=category_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label) + '&category_id=' + encodeURIComponent(category_id));
		GDownloadUrl(URL+'map.php?api=category_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label) + '&category_id=' + encodeURIComponent(category_id), function(data, responseCode) {
		marker.openInfoWindowHtml(data);
	});
	});
	
	return marker;
}


function info_window_zoom(zoom, marker, id){
	//GLog.write("marker:"+marker);
	//GLog.write("id:"+id);
	
	
	
	
	if(zoom == "zoom_in"){
		//map.setCenter(gpoints[number], map.getZoom()+1);
		//map.setZoom(map.getZoom()+1);
		var current_zoom = map.getZoom();
		if(current_zoom<15){
			map.setZoom(15);
		}else{
			map.setZoom(map.getZoom()+1);
		}
	}
	if(zoom == "zoom_out"){
		//map.setCenter(gpoints[number], map.getZoom()-1);
		map.setZoom(map.getZoom()-1);
	}
	
	
}


//----------------------------------------------------------------------------------------------------
//directions
function gdirection_activate(){
	
	//geocoder = new GClientGeocoder(new GGeocodeCache()); 

	//directions
	$("#map_direction_form_frame").removeAttr("style");
	//gdirection = new GDirections(null, document.getElementById("map_direction_list"));
	gdirection = new GDirections();
	GEvent.addListener(gdirection, "load", gdirection_loaded);
	GEvent.addListener(gdirection, "error", gdirection_error);
	
	//gdirection_set("Vilnius", "Kaunas", {locale:LANGUAGE, egetSteps:true});
	
	//swap
	$("#direction_swap").click(function () {
		temp = $("#direction_start").attr("value");
		$("#direction_start").attr("value", $("#direction_end").attr("value"));
		$("#direction_end").attr("value", temp);
	});
	
	$("#map_direction_form").submit(function(){
		//result_loading("#map_direction_list_loading");
		//$("#map_direction_error").html("");
		//if(gdirection_loaded){
			//gdirection_loaded = false;
			//$("#map_direction_list").html("");
			//gdirection_progress(true, false);
			if(gdirection_existing_markers.start){
				map.removeOverlay(gdirection_existing_markers.start);
				delete gdirection_existing_markers.start;
			}
			if(gdirection_existing_markers.end){
				map.removeOverlay(gdirection_existing_markers.end);
				delete gdirection_existing_markers.end;
			}
			if(gdirection_polyline){
				map.removeOverlay(gdirection_polyline);
				delete gdirection_polyline;
			}
			gdirection_set($("#direction_start").attr("value"), "start");
			gdirection_set($("#direction_end").attr("value"), "end");
		//}
		return false;
	});
	
	$("#map_direction_clear").click(function () {
		map.closeInfoWindow();
		$("#map_direction_start_error").html("");
		$("#map_direction_end_error").html("");
		$("#map_direction_error").html("");
		$("#map_direction_list").html("");
		$("#map_direction_form")[0].reset();
		$("#direction_start_suggest").addClass("hide");
		$("#direction_end_suggest").addClass("hide");
		$("#direction_start").attr("title", "");
		$("#direction_end").attr("title", "");
		gdirection_delete_marker();
		/*
		if(gdirection_existing_markers.start){
			map.removeOverlay(gdirection_existing_markers.start);
			delete gdirection_existing_markers.start;
		}
		if(gdirection_existing_markers.end){
			map.removeOverlay(gdirection_existing_markers.end);
			delete gdirection_existing_markers.end;
		}
		if(gdirection_polyline){
			map.removeOverlay(gdirection_polyline);
			delete gdirection_polyline;
		}
		*/
	});

	
}




function gdirection_set(address, type) {
	
	if(!address){
		$("#direction_"+type+"_suggest").addClass("hide");
		return false;
	}
	gdirection_progress(true, false, type);
	geocoder.getLocations(address, function(geocoder_object) {
		if (geocoder_object && geocoder_object.Status.code == 200) {
			gdirection_suggest_list(geocoder_object, type);
			gdirection_progress(false, false, type)
		}else{
			gdirection_suggest_list(false, type);
			gdirection_progress(false, js_translation.MapGeoAddressError, type);
		}
	});
	

}

//generate address_point_existing_point
function gdirection_suggest_list(geocoder_object, type){
	//fill
	html = "";
	if(geocoder_object){
		count = geocoder_object.Placemark.length;
		if(count<=1){
			gdirection_point_selected[type] = true;
		}else{
			gdirection_point_selected[type] = false;
		}
		//alert(gdirection_point_selected[type]);
		for(i in geocoder_object.Placemark) {
			//generate html list, set first point
			//if(point>0){
			address = geocoder_object.Placemark[i].address;
			point = new GLatLng(geocoder_object.Placemark[i].Point.coordinates[1], geocoder_object.Placemark[i].Point.coordinates[0]);
			address_short = address.replace(/ \d{5}, Lithuania/gi, "");
			address_short = address_short.replace(/, Lithuania/gi, "");
			if(i<=0){
				if(gdirection_set_value){
					$("#direction_"+type).attr("value", address);
					$("#direction_"+type).attr("title", address);
					gdirection_set_value = false;
					gdirection_point_selected.start = true;
					gdirection_point_selected.end = true;
					break;
				}
				gdirection_set_marker(point, type, false);
			}
			if($("#direction_"+type).attr("value") != address && count>1){
				html += '<a href="#" id="gdirection_address_point_'+i+'">'+address_short+'</a><br />';
			}
			
		}
		if(gdirection_point_selected.start && gdirection_point_selected.end){
			gdirection_set_marker(point, type, true);
		}
	}
	$("#direction_"+type+"_suggest_list").html(html);
	if(html!=""){
		$("#direction_"+type+"_suggest").removeClass("hide");
		$("#direction_"+type+"_suggest_list a").click(function(){
			for(i in geocoder_object.Placemark) {
				if($(this).attr("id") == "gdirection_address_point_"+i){
					address = geocoder_object.Placemark[i].address;
					point = new GLatLng(geocoder_object.Placemark[i].Point.coordinates[1], geocoder_object.Placemark[i].Point.coordinates[0]);
					$("#direction_"+type).attr("value", address);
					$("#direction_"+type).attr("title", address);
					$("#direction_"+type+"_suggest").addClass("hide");
					gdirection_point_selected[type] = true;
					if(gdirection_point_selected.start && gdirection_point_selected.end){
						gdirection_set_marker(point, type, true);
					}else{
						gdirection_set_marker(point, type, false);
					}
					break;
				}
			}
			return false;												
		});
	}else{
		$("#direction_"+type+"_suggest").addClass("hide");
	}
}


function gdirection_set_marker(point, type, load_direction) {
	/*
	address_point_delete_marker();
	address_point_existing_markers[point] = address_point_create_marker(point, address);
	map.addOverlay(address_point_existing_markers[point]);
	map.setCenter(point);
	*/
	if(gdirection_existing_markers[type]){
		map.removeOverlay(gdirection_existing_markers[type]);
		delete gdirection_existing_markers[type];
		//GLog.write("delete marker"+type);
	}
	gdirection_existing_markers[type] = gdirection_create_marker(point, type);
	map.addOverlay(gdirection_existing_markers[type]);
	if(!load_direction)map.setCenter(point);
	
	if(load_direction){
		if(gdirection_existing_markers.start && gdirection_existing_markers.end){
			gdirection_progress(true, false);
			gdirection.load("from: " + gdirection_existing_markers.start.point.toUrlValue() + " to: " + gdirection_existing_markers.end.point.toUrlValue(), {locale:LANGUAGE, getSteps:true, getPolyline:true});
		}
	}else{
		$("#map_direction_list").html("");
	}
}

function gdirection_delete_marker() {
	if(gdirection_existing_markers.start){
		map.removeOverlay(gdirection_existing_markers.start);
		delete gdirection_existing_markers.start;
	}
	if(gdirection_existing_markers.end){
		map.removeOverlay(gdirection_existing_markers.end);
		delete gdirection_existing_markers.end;
	}
	if(gdirection_polyline){
		map.removeOverlay(gdirection_polyline);
		delete gdirection_polyline;
	}
}




function gdirection_create_marker(point, type) {
	//create the marker with the appropriate icon

		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/map_direction_"+type+"_"+LANGUAGE+".png";

		//iconCluster.shadow = "";
		//icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(3, 34);
		icon.infoWindowAnchor = new GPoint(3, 12);
		//icon.infoShadowAnchor = new GPoint(5, 12);

	markerOptions = {icon:icon, draggable:true};

	var marker = new GMarker(point, markerOptions);
	marker.point = point;
	GEvent.addListener(marker, "click", function() {
		map.showMapBlowup(this.point);
		//GLog.write(this.point.toUrlValue());
	});
	GEvent.addListener(marker, "dragend", function(){
		gdirection_set_value = true;
		gdirection_set(this.getLatLng(), type);
	});
	return marker;
}




function gdirection_loaded(){ 

	if(gdirection_polyline)map.removeOverlay(gdirection_polyline);
	gdirection_polyline = gdirection.getPolyline();
	map.addOverlay(gdirection_polyline);
	
	var gdirection_bound = new GLatLngBounds();
	gdirection_bound.extend(gdirection_existing_markers.start.point);
	gdirection_bound.extend(gdirection_existing_markers.end.point);
	map.setZoom(map.getBoundsZoomLevel(gdirection_bound));
	map.setCenter(gdirection_bound.getCenter());
	
	gdirection_progress(false, false);
	gdirection_generate_list();
	
	//stats
	$.ajax({url:URL+"map.php?api=statistika&statistika_objektas=zemelapiai_marsrutai", cache:false});
	
	$("#Maps").accordion("activate", $("#get_directions_header"));
}


function gdirection_generate_list(){
	//waypoint html
	function waypoint(point, icon_image, address) {
		html = "";
		html += '<table border="0" cellpadding="0" cellspacing="0" class="waypoint">';
		html += '  <tr onclick="map.showMapBlowup(new GLatLng('+point.toUrlValue()+'));">';
		html += '    <td class="icon">';
		html += '      <img src="'+icon_image+'">'
		html += '    </td>';
		html += '    <td class="address">';
		html +=        address;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
		return html;
	}
	
	//route distance html
	function routeDistance(distance) {
		return '<div class="route_distance">' + distance + '</div>';
	}
		
	//route html
	function detail(point, num, description, distance) {
		html = "";
		html += '<table border="0" cellpadding="0" cellspacing="0" class="waypoint_detail" id="waypoint_detail_'+num+'">';
		html += '  <tr onclick="map.showMapBlowup(new GLatLng('+point.toUrlValue(6)+'))">';
		html += '    <td class="number">';
		html += '      <a href="javascript:void(0)">'+num+'</a>';
		html += '    </td>';
		html += '    <td class="description">';
		html +=        description;
		html += '    </td>';
		html += '    <td style="distance">';
		html +=        distance;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
		return html;
	}
		
	//copyright html
	function copyright(text) {
		html = '<div class="copyright">' + text + "</div>";
		return html;
	}

	for (var i=0; i<gdirection.getNumRoutes(); i++) {
	
		var icon_start_image=URL+"images/icon/map/map_direction_start.png";
		var icon_end_image=URL+"images/icon/map/map_direction_end.png";
		//GLog.write(icon_image);

		
		var route = gdirection.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		
		//start waypoint
		$("#map_direction_list").append(waypoint(point, icon_start_image, geocode.address));
		//distance
		$("#map_direction_list").append(routeDistance(route.getDistance().html+" ("+route.getDuration().html+")"));
		
		for (var j=0; j<route.getNumSteps(); j++) {
			var step = route.getStep(j);
			//details for each waypoint
			$("#map_direction_list").append(detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html));
		}
		
		//end waypoint
		var geocode = route.getEndGeocode();
		var point = route.getEndLatLng();
		$("#map_direction_list").append(waypoint(point, icon_end_image, geocode.address));
			 
		//add copyright
		$("#map_direction_list").append(copyright(gdirection.getCopyrightsHtml()));
	
	}	

	//bind hover
	$("#map_direction_list .waypoint_detail").mouseover(function(){											
		$(this).addClass("hover");
	});	
	$("#map_direction_list .waypoint_detail").mouseout(function(){											
		$(this).removeClass("hover");
	});
	//bind clicks
	$("#map_direction_list .waypoint_detail").click(function(){											
		gdirection_waypoint_old_id = gdirection_waypoint_id;
		$("#map_direction_list table[id='"+gdirection_waypoint_id+"']").removeClass("selected");
		gdirection_waypoint_id = $(this).attr("id");
		$(this).removeClass("hover");
		$(this).addClass("selected");
		
	});
}





function gdirection_error(){
	gdirection_progress(false, js_translation.MapDirectionError)
}

function gdirection_progress(loading, error, type){
	
	if(type=='start' || type=='end'){
		id_loading = "#map_direction_"+type+"_loading";
		id_error = "#map_direction_"+type+"_error";
	}else{
		id_loading = "#map_direction_loading";
		id_error = "#map_direction_error";
	}
	map.closeInfoWindow();
	if(loading){
		result_loading(id_loading);
		$(id_error).html("");
		$("#map_direction_list").html("");
	}else{
		$(id_loading).html("");
	}	
	
	if(error && error!=""){
		$(id_error).html(error);
	}
	
	
	/*
	result_loading("#map_direction_loading");
	//loaded
	if(error){
		$("#map_direction_loading").html("");
		$("#map_direction_error").html(""); 
	}else{
		result_loading("#map_direction_loading");
		$("#map_direction_list").html("");
		
	}
	*/
}
//----------------------------------------------------------------------------------------------------


function maps_list_generate(){
	var pointBounds = new GLatLngBounds();
	
	for (i in firm_map_list) {
		var point = new GLatLng(firm_map_list[i].latitude, firm_map_list[i].longitude);
		pointBounds.extend(point);
		firm_map_list_existing_markers[i] = maps_list_create_marker(point, firm_map_list[i].type, firm_map_list[i].label, firm_map_list[i].label_type, firm_map_list[i].id);
		map.addOverlay(firm_map_list_existing_markers[i]);
	}
	
	//zoom level from pointBounds
	map.setZoom(map.getBoundsZoomLevel(pointBounds));
	map.setCenter(pointBounds.getCenter());
	
	var southWest = pointBounds.getSouthWest();
	var northEast = pointBounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	
	var pixelSouthWest = map.fromLatLngToContainerPixel(southWest);
	pixelSouthWest.x-=70;
	pixelSouthWest.y+=20;
	var newSouthWest = map.fromContainerPixelToLatLng(new GPoint(pixelSouthWest.x, pixelSouthWest.y));
	
	var pixelNorthEast = map.fromLatLngToContainerPixel(northEast);
	pixelNorthEast.x+=130;
	pixelNorthEast.y-=20;
	var newNorthEast = map.fromContainerPixelToLatLng(new GPoint(pixelNorthEast.x, pixelNorthEast.y));
	//alert(pixelNorthEast);
	pointBounds.extend(newSouthWest);
	pointBounds.extend(newNorthEast);
	
	map.setZoom(map.getBoundsZoomLevel(pointBounds));
	map.setCenter(pointBounds.getCenter());
	
	
	//bind clicks
	$("#map_firm_list .item").click(function(){											
		$("#map_firm_list div[id='"+firm_map_list_id+"']").removeClass("item_active");
		firm_map_list_id = $(this).attr("id");
		$(this).removeClass("item_rollover");
		$(this).addClass("item_active");
		//onclick show place
		for (i in firm_map_list_existing_markers) {
			if(firm_map_list_id == 'map_item_' + firm_map_list_existing_markers[i].label){
				GEvent.trigger(firm_map_list_existing_markers[i],"click");
			}
		}
		
	});
	//bind hover
	$("#map_firm_list .item").mouseover(function(){											
		if(firm_map_list_id!=$(this).attr("id"))$(this).addClass("item_rollover");	
	});	
	$("#map_firm_list .item").mouseout(function(){											
		if(firm_map_list_id!=$(this).attr("id"))$(this).removeClass("item_rollover");											
	});
		
}

function maps_list_create_marker(point, type, label, label_type, id) {
	//create the marker with the appropriate icon
	
	if(type=='c') {
		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/marker_g.png";
		//iconCluster.shadow = "";
		icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor = new GPoint(12, 12);
		icon.infoShadowAnchor = new GPoint(12, 12);
	}else{
		//create an icon for the pins
		var icon = new GIcon();
		//icon.image = "map.php?api=firm_marker&label="+label+"&label_type="+label_type+"&fix=.png";
		if(label_type>1){
			marker_dir = "/"+label_type;
		}else{
			marker_dir = "";
		}
		icon.image = URL+"images/icon/marker"+marker_dir+"/"+label+".png";
		icon.shadow = URL+"images/icon/map/shadow_"+label.toString().length+".png";
		//iconSingle.iconSize = new GSize(12, 20);
		//iconSingle.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(4, 30);
		icon.infoWindowAnchor = new GPoint(12, 10);
		icon.infoShadowAnchor = new GPoint(12, 10);
	}


	importance = 0;
	if(label_type==1)importance = 10;
	if(label_type==2)importance = 1;
	
	markerOptions = {icon:icon, zIndexProcess:marker_importance_order};

	var marker = new GMarker(point, markerOptions);
	marker.label = label;
	marker.label_type = label_type;
	marker.importance = importance;
	marker.id = id;
	marker.point = point;
	
	GEvent.addListener(marker, "click", function() {
		GDownloadUrl(URL+'map.php?api=firm_list_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label), function(data, responseCode) {
			marker.openInfoWindowHtml(data);
			$("#map_firm_list div[id='"+firm_map_list_id+"']").removeClass("item_active");
			firm_map_list_id = 'map_item_' + label;
			$("#"+firm_map_list_id).removeClass("item_rollover");
			$("#"+firm_map_list_id).addClass("item_active");
		});
	});
	
	return marker;
}



function maps_popup_generate(){
	var pointBounds = new GLatLngBounds();
	
	for (i in firm_map_single) {
		var point = new GLatLng(firm_map_single[i].latitude, firm_map_single[i].longitude);
		pointBounds.extend(point);
		firm_map_single_existing_markers[i] = maps_popup_create_marker(point, firm_map_single[i].type, firm_map_single[i].label, firm_map_single[i].id);
		map.addOverlay(firm_map_single_existing_markers[i]);
	}
	
	//zoom level from pointBounds
	map.setZoom(map.getBoundsZoomLevel(pointBounds));
	map.setCenter(pointBounds.getCenter());
	
	var southWest = pointBounds.getSouthWest();
	var northEast = pointBounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	
	var pixelSouthWest = map.fromLatLngToContainerPixel(southWest);
	pixelSouthWest.x-=70;
	pixelSouthWest.y+=20;
	var newSouthWest = map.fromContainerPixelToLatLng(new GPoint(pixelSouthWest.x, pixelSouthWest.y));
	
	var pixelNorthEast = map.fromLatLngToContainerPixel(northEast);
	pixelNorthEast.x+=130;
	pixelNorthEast.y-=20;
	var newNorthEast = map.fromContainerPixelToLatLng(new GPoint(pixelNorthEast.x, pixelNorthEast.y));
	//alert(pixelNorthEast);
	pointBounds.extend(newSouthWest);
	pointBounds.extend(newNorthEast);
	
	//map.setZoom(map.getBoundsZoomLevel(pointBounds));
	map.setCenter(pointBounds.getCenter());
	map.setZoom(13);
}


function maps_popup_create_marker(point, type, label, id) {
	//create the marker with the appropriate icon
	
	if(type=='c') {
		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/marker_g.png";
		//iconCluster.shadow = "";
		icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor = new GPoint(12, 12);
		icon.infoShadowAnchor = new GPoint(12, 12);
	}else{
		//create an icon for the pins
		var icon = new GIcon();
		//icon.image = "map.php?api=firm_marker&label="+label;
		icon.image = URL+"images/number/viena_imone.png";
		//icon.shadow = "images/icon/map/shadow_"+label.length+".png";
		//iconSingle.iconSize = new GSize(12, 20);
		//iconSingle.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(8, 21);
		icon.infoWindowAnchor = new GPoint(9, 9);
		//icon.infoShadowAnchor = new GPoint(12, 10);
	}

	markerOptions = {icon:icon};

	var marker = new GMarker(point, markerOptions);
	marker.label = label;
	marker.id = id;
	marker.point = point;
	
	GEvent.addListener(marker, "click", function() {
		GDownloadUrl(URL+'map.php?api=firm_popup_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label), function(data, responseCode) {
			marker.openInfoWindowHtml(data);
		});
	});
	
	return marker;
}


function maps_firm_info_generate(){
	var pointBounds = new GLatLngBounds();
	
	for (i in firm_map_info) {
		var point = new GLatLng(firm_map_info[i].latitude, firm_map_info[i].longitude);
		pointBounds.extend(point);
		firm_map_info_existing_markers[i] = maps_firm_info_create_marker(point, firm_map_info[i].type, firm_map_info[i].label, firm_map_info[i].id);
		map.addOverlay(firm_map_info_existing_markers[i]);
	}
	
	//zoom level from pointBounds
	//map.setZoom(map.getBoundsZoomLevel(pointBounds));
	map.setCenter(pointBounds.getCenter());
	map.setZoom(15);
	

}

function maps_firm_info_create_marker(point, type, label, id) {
	//create the marker with the appropriate icon
	
	if(type=='c') {
		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/marker_g.png";
		//iconCluster.shadow = "";
		icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor = new GPoint(12, 12);
		icon.infoShadowAnchor = new GPoint(12, 12);
	}else{
		//create an icon for the pins
		var icon = new GIcon();
		//icon.image = "map.php?api=firm_marker&label="+label;
		icon.image = URL+"images/number/viena_imone.png";
		//icon.shadow = "images/icon/map/shadow_"+label.length+".png";
		//iconSingle.iconSize = new GSize(12, 20);
		//iconSingle.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(8, 21);
		icon.infoWindowAnchor = new GPoint(9, 9);
		//icon.infoShadowAnchor = new GPoint(12, 10);
	}

	markerOptions = {icon:icon};

	var marker = new GMarker(point, markerOptions);
	marker.label = label;
	marker.id = id;
	marker.point = point;
	
	/*
	GEvent.addListener(marker, "click", function() {
		GDownloadUrl('map.php?api=firm_popup_marker_view&marker_id=' + encodeURIComponent(i) + '&id='+encodeURIComponent(id) + '&label=' + encodeURIComponent(label), function(data, responseCode) {
			marker.openInfoWindowHtml(data);
		});
	});
	*/
	
	return marker;
}















///////////////////////////////////address point search////////////////////////////////////////////////////
//address point
function address_point_activate(){
	
	//geocoder = new GClientGeocoder(new GGeocodeCache()); 

	//directions
	$("#map_address_point_form_frame").removeAttr("style");
	
	$("#map_address_point_form").submit(function(){
		//address_point_existing_markers
		address_point_delete_marker();
		address_point_search($("#address_point").attr("value"), "point");
		return false;
	});
	
	$("#map_address_point_clear").click(function () {
		map.closeInfoWindow();
		$("#map_address_point_error").html("");
		$("#map_address_point_form")[0].reset();
		$("#map_address_point_suggest").addClass("hide");
		$("#address_point").attr("title", "");
		address_point_delete_marker();
	});

	
}

function address_point_progress(loading, error){
	
	//map.closeInfoWindow();
	if(loading){
		result_loading("#map_address_point_loading");
		$("#map_address_point_error").html("");
		//$("#map_address_point_list").html("");
		//$("#map_address_point_suggest").html("");
	}else{
		$("#map_address_point_loading").html("");
	}	
	
	if(error && error!=""){
		$("#map_address_point_error").html(error);
	}
}

function address_point_search(address, type) {
	if(!address){
		$("#map_address_point_suggest").addClass("hide");
		return false;
	}
	address_point_progress(true, false);
	geocoder.getLocations(address, function(geocoder_object) {
		if (geocoder_object && geocoder_object.Status.code == 200) {
			address_point_suggest_list(geocoder_object);
			address_point_progress(false, false)
		}else{
			address_point_suggest_list();
			address_point_progress(false, js_translation.MapGeoAddressError);
		}
	});
}

//generate address_point_existing_point
function address_point_suggest_list(geocoder_object){
	//fill
	html = "";
	if(geocoder_object){
		count = geocoder_object.Placemark.length;
		//address_point_existing_point = geocoder_object;
		for(i in geocoder_object.Placemark) {
			//generate html list, set first point
			//if(point>0){
			address = geocoder_object.Placemark[i].address;
			point = new GLatLng(geocoder_object.Placemark[i].Point.coordinates[1], geocoder_object.Placemark[i].Point.coordinates[0]);
			address_short = address.replace(/ \d{5}, Lithuania/gi, "");
			address_short = address_short.replace(/, Lithuania/gi, "");
			
			//if($("#address_point").attr("value") != address){
			if(count>1){
				html += '<a href="#" id="address_point_'+i+'">'+address_short+'</a><br />';
			}else{
				address_point_set_marker(point, address);
			}
			
			if(i<=0){
				if(address_point_set_value){
					address_point_set_marker(point, address);
					$("#address_point").attr("value", address);
					$("#address_point").attr("title", address);
					address_point_set_value = false;
				}
			}
			
		}
	}
	$("#map_address_point_suggest_list").html(html);
	if(html!=""){
		$("#map_address_point_suggest").removeClass("hide");
		$("#map_address_point_suggest_list a").click(function(){
			for(i in geocoder_object.Placemark) {
				if($(this).attr("id") == "address_point_"+i){
					address = geocoder_object.Placemark[i].address;
					point = new GLatLng(geocoder_object.Placemark[i].Point.coordinates[1], geocoder_object.Placemark[i].Point.coordinates[0]);
					address_point_set_marker(point, address);
					map.setZoom(15);
					break;
				}
			}
			return false;												
		});
	}else{
		$("#map_address_point_suggest").addClass("hide");
	}
}

function address_point_create_marker(point, address) {
	//create the marker with the appropriate icon

		//create an icon for the clusters
		var icon = new GIcon();
		icon.image = URL+"images/icon/map/address_point.png";

		//iconCluster.shadow = "";
		//icon.iconSize = new GSize(23, 23);
		//iconCluster.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(4, 29);
		icon.infoWindowAnchor = new GPoint(12, 10);
		//icon.infoShadowAnchor = new GPoint(5, 12);

	markerOptions = {icon:icon, draggable:true};

	var marker = new GMarker(point, markerOptions);
	marker.point = point;
	GEvent.addListener(marker, "click", function() {
		//map.showMapBlowup(this.point);
		marker.openInfoWindowHtml(address);
		//GLog.write(this.point.toUrlValue());
	});
	GEvent.addListener(marker, "dragend", function(){
		address_point_set_value = true;
		address_point_search(this.getLatLng(), "point");
	});
	return marker;
}

function address_point_set_marker(point, address) {
	address_point_delete_marker();
	address_point_existing_markers[point] = address_point_create_marker(point, address);
	map.addOverlay(address_point_existing_markers[point]);
	map.setCenter(point);
}

function address_point_delete_marker() {
	for(i in address_point_existing_markers) {
		map.removeOverlay(address_point_existing_markers[i]);
		delete address_point_existing_markers[i];
	}
}





///////////////////////////////////map layers////////////////////////////////////////////////////
//map layer
function map_layer_activate(){

	//layer frame
	$("#map_layer_form_frame").removeClass("hide");
	
	/*
	$("#map_address_point_form").submit(function(){
		//address_point_existing_markers
		address_point_search($("#address_point").attr("value"), "point");
		return false;
	});
	
	$("#map_address_point_clear").click(function () {
		map.closeInfoWindow();
		$("#map_address_point_error").html("");
		$("#map_address_point_form")[0].reset();
		$("#map_address_point_suggest").addClass("hide");
		$("#address_point").attr("title", "");
		address_point_delete_marker();
	});
	*/
	for(i in map_layer_title) {
		map_layer[i] = new GLayer(map_layer_title[i]);
	}
	map_layer['map_layer_panoramic_photo'] = new GGeoXml('http://www.info.lt/zemelapiai_c/xml/kml3.xml');

	$("#map_layer_form input[type='checkbox']").click(function(){
		checkbox = $("#map_layer_form input[type='checkbox']:checked");
		map_layer[$(this).attr("id")];
		if(map_layer[$(this).attr("id")]){
			if($(this).attr("checked")){
				map.addOverlay(map_layer[$(this).attr("id")]);
			}else{
				map.removeOverlay(map_layer[$(this).attr("id")]);
			}
		}
	});

	
}
