var map;
var sw=new Array();
var ne=new Array();
var firmsManager;
var citiesManager;
var geocoder=null;
var blueIcon;
var xmlHttp;
var curOpenedMarker=[null,null];
window.onload=LoadMap;

function LoadMap(){
	try{
		if (typeof(firms)!='undefined' && GBrowserIsCompatible()){
			xmlHttp=createXmlHttpRequestObject();
			for (var i=0; i<region_bounds.length; i++){
				if (region_bounds[i][0]==cur_region_name){
					sw[0]=region_bounds[i][1];
					sw[1]=region_bounds[i][2];
					ne[0]=region_bounds[i][3];
					ne[1]=region_bounds[i][4];
				}
			}
			_el('im_op_cntrs').onmouseover = function(){
				this.style.backgroundPosition="left top";
			}
			_el('im_op_cntrs').onmouseout = function(){
				this.style.backgroundPosition="right top";
			}
			_el('spr_cts').onmouseover = function(){
				_el('im_op_cts').style.backgroundPosition="left top";
			}
			_el('spr_cts').onmouseout = function(){
				_el('im_op_cts').style.backgroundPosition="right top";
			}
			_el('im_op_cntrs').onclick = function(){
				var cur_displ = _el('hidd_cntrs').style.display;
				_el('hidd_cntrs').className="opened_region";
				_el('hidd_cntrs').style.display = cur_displ=='block' ? 'none' : 'block';
				_el('hidd_cts').style.display = 'none';
			}
			_el('spr_cts').onclick = function(){
				var cur_displ = _el('hidd_cts').style.display;
				_el('hidd_cts').className="opened_region";
				_el('hidd_cts').style.display = cur_displ=='block' ? 'none' : 'block';
				_el('hidd_cntrs').style.display = 'none';
			}
			GLoadMap();
			blueIcon = new GIcon(G_DEFAULT_ICON);
			blueIcon.image = mark_std_blue;
			firmsManager = new MarkerManager(map);
			citiesManager = new MarkerManager(map);
			GLoadMarkers(citiesManager, city_cnt, 1, 0, 1, 10);
			GLoadMarkers(citiesManager, aloneFirms, 1, 0, 1, 10);
			GLoadMarkers(firmsManager, firms, 2, 0, 11, 12);
			GLoadMarkers(firmsManager, firms, 3, 1, 13);
			_el("mp_frm").onsubmit=function(){
				var entered_addr=this.address.value;
				try{
					saveSearchRequest(entered_addr);
					showAddress(entered_addr);
				}catch(s){};
				return false;
			}
			var i=1;
			while (_el('hidd_cat_'+i)){
				_el('hidd_catlbl_'+i).onclick=function(){
					var i=this.id.substr('hidd_catlbl_'.length);
					var displ=_el('hidd_cat_'+i).style.display;
					var src=_el('img_pl_min_'+i).src;
					_el('hidd_cat_'+i).style.display = displ=='none' ? 'block' : 'none';
					_el('img_pl_min_'+i).src = displ=='none' ? src.replace('+','_') : src.replace('_','+');
				}
				i++;
			}
			if (typeof(open_cat_list)!='undefined') _el('hidd_catlbl_'+open_cat_list).onclick();
		}
	}catch(s){};
}

function GLoadMap(){
	map = new GMap2(_el("MapsID"));
	var zoom = GgetZoom();
	var ne_univ = ne[0] > 0 ? ne[0] : 360+ne[0];
	var center=[sw[0]+(ne_univ-sw[0])/2, sw[1]+(ne[1]-sw[1])/2];
	map.setCenter(new GLatLng(center[1], center[0]), zoom);
    var customUI = map.getDefaultUI();
    map.setUI(customUI);
    geocoder = new GClientGeocoder();
}

function GgetZoom(){
	var zoom =7;
	if (typeof(sw) != 'undefined'){
		var sw_point = new GLatLng(sw[1], sw[0]);
		var ne_point = new GLatLng(ne[1], ne[0]);
		var visibleBound = new GLatLngBounds(sw_point, ne_point);
		zoom = map.getBoundsZoomLevel(visibleBound, new GSize(map_w,map_h));
	}
	return zoom;
}

function createGoogleMarker(i, curr_ar, layer, userMarkers){
	var point = new GLatLng(curr_ar[i][1], curr_ar[i][0]);
	
	if (userMarkers && layer==3 && curr_ar[i][7]){
	    var myIcon = new GIcon(G_DEFAULT_ICON);
	    myIcon.image = curr_ar[i][7];
	    
	    if (typeof(curr_ar[i][9])!='undefined'){
	    	myIcon.iconSize = new GSize(f_icon_w, f_icon_h);
		    myIcon.shadow = f_shad_path;
		    myIcon.shadowSize = new GSize(f_icon_shad_w, f_icon_shad_h);
		    myIcon.iconAnchor = new GPoint(-f_shad_offset_x,-f_shad_offset_y);
		    myIcon.infoWindowAnchor = new GPoint(-f_shad_offset_x,-f_shad_offset_y);
		    myIcon.imageMap = [0,0,f_icon_w,0,f_icon_w,f_icon_h,0,f_icon_h];
	    }
	    else{
		    myIcon.iconSize = new GSize(icon_w, icon_h);
		    if (curr_ar[i][11]=='brand'){
			myIcon.shadow = shad_path_brand;
		    }
		    else{
			myIcon.shadow = shad_path;
		    }
		    myIcon.shadowSize = new GSize(icon_shad_w, icon_shad_h);
		    myIcon.iconAnchor = new GPoint(-shad_offset_x,-shad_offset_y);
		    myIcon.infoWindowAnchor = new GPoint(-shad_offset_x,-shad_offset_y);
		    myIcon.imageMap = [0,0,icon_w,0,icon_w,icon_h,0,icon_h];

	    }
	    
		var marker = new GMarker(point, {icon: myIcon});
	}
	else{
		var marker = new GMarker(point, {icon:blueIcon});
	}
	
	if (curr_ar[i][7]){
		GEvent.addListener(marker, 'click', function() {
   			curOpenedMarker=[this,curr_ar[i]];
   			getGalIm(curr_ar[i][8],1,cnt_gal_im)
		});
	}
	else{
		var html = getBalloonText(i,curr_ar);
		GEvent.addListener(marker, 'click', function() {
	   		marker.hide();
	    	marker.openInfoWindowHtml(html);
		});
	}
	
	GEvent.addListener(marker, 'infowindowclose', function() {
    	marker.show();
    });
    return marker;
}

function GLoadMarkers(manager, curr_ar, layer, userMarkers, minZoom, MaxZoom){
	var batch = [];
	for (var i=0; i<curr_ar.length; i++){
		batch.push(createGoogleMarker(i, curr_ar, layer, userMarkers));
	}
	if (MaxZoom) manager.addMarkers(batch, minZoom, MaxZoom);
	else manager.addMarkers(batch, minZoom);
	manager.refresh();
}

function showAddress(address){
	if (geocoder){
		geocoder.getLatLng(
			address,
			function(point){
				var info = new Array();
				var len_before;
				var center_point;
				var zoom;
				var match_ind=null;
				var address_tmp = address.toLowerCase();
				if (!point) alert("Àäðåñ \""+address+"\" íå íàéäåí");
				else{
					for (var i=region_bounds.length-1; i>=0; i--){
						len_before = address_tmp.length;
						address_tmp=address_tmp.replace(region_bounds[i][0],'');
						if (len_before != address_tmp.length) match_ind=i;
					}
					if (address_tmp.match(/[a-zA-Zà-ÿÀ-ß¸]+/) == null && match_ind != null){
						var ne_univ = region_bounds[match_ind][3] > 0 ? region_bounds[match_ind][3] : 360+region_bounds[match_ind][3];
						center_point = new GLatLng(region_bounds[match_ind][2] + (region_bounds[match_ind][4]-region_bounds[match_ind][2])/2, region_bounds[match_ind][1] + (ne_univ-region_bounds[match_ind][1])/2);
						var sw_point = new GLatLng(region_bounds[match_ind][2], region_bounds[match_ind][1]);
						var ne_point = new GLatLng(region_bounds[match_ind][4], region_bounds[match_ind][3]);
						var visibleBound = new GLatLngBounds(sw_point, ne_point);
						zoom = map.getBoundsZoomLevel(visibleBound, new GSize(map_w,map_h));
						if (!region_is_loaded('spr_cntrs',match_ind) &&	!region_is_loaded('spr_cts',match_ind) && !region_is_loaded('hidd_cts',match_ind)){
							var slash_ind = window.location.href.lastIndexOf('/');
							var path1 = window.location.href.substr(0,slash_ind+1);
							var path2 = window.location.href.substr(slash_ind+1);
							var region_domen = getRedirectRegionDomen(match_ind);
							window.location = path1+path2.split('-')[0]+'-'+region_domen;
							return 1;
						}
					}
					else{
						info = getCoordNearestFirmInfo(point.lng(),point.lat());
						zoom = info[0]-1;
						center_point = info[1];
					}
					map.setCenter(center_point, zoom);
					var marker = new GMarker(point);
					GEvent.addListener(marker, 'click', function() {
   						marker.hide();
    					marker.openInfoWindowHtml(address);
					});
					GEvent.addListener(marker, 'infowindowclose', function() {
    					marker.show();
    				});
					map.addOverlay(marker);
					marker.openInfoWindowHtml(address);
				}
			}
		);
	}
}

function region_is_loaded(node_name, region_ind){
	return _el(node_name).innerHTML.toLowerCase().indexOf(region_bounds[region_ind][0]) == -1 ? false : true;
}

function getRedirectRegionDomen(match_ind){
	var coords_match;
	for(i=0; i<region_bounds.length; i++){
		if (typeof(region_bounds[i][5])!='undefined'){
			coords_match=true;
			for(j=1; j<=4; j++){
				if (region_bounds[i][j]!=region_bounds[match_ind][j]) coords_match=false;
			}
			if (coords_match) return region_bounds[i][5];
		}
	}
}

function getCoordNearestFirmInfo(lng1,lat1){
	var min=0;
	var zoom=15;
	var center_point=new GLatLng(lat1,lng1);
	if (firms.length){
		min = getMinDistancePoint_Index(lat1,lng1);
		var lat2 = firms[min][1];
		var lng2 = firms[min][0];
		var sw_point1 = new GLatLng(Math.min(lat1,lat2), Math.min(lng1,lng2));
		var ne_point2 = new GLatLng(Math.max(lat1,lat2), Math.max(lng1,lng2));
		var lat_cntr = Math.min(lat1,lat2) + Math.abs(lat1-lat2)/2;
		var lng_cntr = Math.min(lng1,lng2) + Math.abs(lng1-lng2)/2;
		center_point = new GLatLng(lat_cntr, lng_cntr);
		zoom = map.getBoundsZoomLevel(new GLatLngBounds(sw_point1, ne_point2), new GSize(map_w,map_h));
	}
	return new Array(zoom, center_point, min);
}

function getMinDistancePoint_Index(lat,lng){
	var distance;
	var len=firms.length;
	var min=1000;
	var min_index=0;
	for(var i=0; i<len; i++){
		distance = Math.sqrt(Math.pow(lat-firms[i][1],2)+Math.pow(lng-firms[i][0],2));
		if (distance < min){
			min = distance;
			min_index = i;
		}
	}
	return min_index;
}

function _el(name){
	return document.getElementById(name);
}

function createXmlHttpRequestObject(){
	var xmlHttp;
	try{
		xmlHttp=new XMLHttpRequest();
	}catch(e){
		var XmlHttpVersion=new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.46.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
		for(var i=0;i<XmlHttpVersion.length && !xmlHttp;i++){
			try{
				xmlHttp=new ActiveXObject(XmlHttpVersion[i]);
			}catch(e){}
		}
	}
 	return xmlHttp;
}

function saveSearchRequest(addr){
	if (xmlHttp && addr){
		try{
			var d = new Date();
 			xmlHttp.open("GET",phpsaver+"/?addr="+encodeURIComponent(addr)+"&t="+d.getTime(),true);
 			xmlHttp.onreadystatechange=function(){return 1;}
 			xmlHttp.send(null);
   		}catch(e){}
	}
}

function getGalIm(id, start, cnt){
	if (xmlHttp && id && start && cnt){
		try{
			var d = new Date();
 			xmlHttp.open("GET",phpsaver+"/?gallery=1&id="+id+"&start="+start+"&cnt="+cnt+"&t="+d.getTime(),true);
 			xmlHttp.onreadystatechange=handleRequestStateChange;
 			xmlHttp.send(null);
   		}catch(e){}
	}
}

function handleRequestStateChange(){
	if(xmlHttp.readyState==4){
		if(xmlHttp.status==200){
			try{
				insertGalIm();
			}catch(e){}
		}
	}
}

function xmlToArray(resultsXml){
	var resultsArray=new Array();  
	for(i=0;i<resultsXml.length;i++)
	resultsArray[i]=resultsXml.item(i).firstChild.data;
	return resultsArray;
}

function insertGalIm(){
	var html='';
	var nameArray=new Array();
	var pathArray=new Array();
	var hrefArray=new Array();
	var serv_response = xmlHttp.responseXML.documentElement;
  	if(serv_response.childNodes.length)
  	{
    	var id_firm=serv_response.getElementsByTagName("id_firm").item(0).firstChild.data
  		nameArray = xmlToArray(serv_response.getElementsByTagName("name"));
    	pathArray = xmlToArray(serv_response.getElementsByTagName("path"));
    	hrefArray = xmlToArray(serv_response.getElementsByTagName("href"));
  	}
  	for (var i=0;i<nameArray.length;i++){
		html += hrefArray[i] ? '<a class="fl g_im" href="'+hrefArray[i]+'" target="_blank">' : '<div class="fl g_im">';
		html += '<img style="margin:3px" src="'+pathArray[i]+'" width="50" height="50" alt="'+nameArray[i]+'" title="'+nameArray[i]+'" border="0">';
		html += hrefArray[i] ? '</a>' : '</div>';
  	}
	if (id_firm==curOpenedMarker[1][8]){
		var marker=curOpenedMarker[0];
		var fillial = typeof(curOpenedMarker[1][9])!='undefined' ? curOpenedMarker[1][10]+'<br />' : '';
		html='<div class="txt b">'+fillial+'<a class="i" href="'+curOpenedMarker[1][2]+'" target="_blank">'+curOpenedMarker[1][3]+'</a><br>'+curOpenedMarker[1][4].replace(/\s+/g,"&nbsp;")+'<br />'+curOpenedMarker[1][5]+', '+curOpenedMarker[1][6]+'</div>'+(html ? '<div class="ts">'+html+'</div>' : '');
		marker.hide();
		marker.openInfoWindowHtml(html);
		GEvent.clearListeners(marker, 'click');
		GEvent.addListener(marker, 'click', function() {
	   		marker.hide();
	   		marker.openInfoWindowHtml(html);
		});
	}
}

function getBalloonText(ind,curr_ar)
{
	if (curr_ar[ind][6]){
		var fillial = typeof(curr_ar[ind][9])!='undefined' ? curr_ar[ind][10]+'<br />' : '';
		return '<div id="bl'+curr_ar[ind][8]+'" class="txt b">'+fillial+'<a class="i" href="'+curr_ar[ind][2]+'" target="_blank">'+curr_ar[ind][3]+'</a><br>'+curr_ar[ind][4].replace(/\s+/g,"&nbsp;")+'<br />'+curr_ar[ind][5]+', '+curr_ar[ind][6]+'</div>';
	}
	else
		return curr_ar[ind][2];
}
