function MapObject(map_width, map_height, control_pad)
{	
	var map;
	var geocoder;
	if(map_width && map_width!=0 && map_height && map_height!=0) {
		//map = new GMap2(document.getElementById("map"), {size:new GSize(map_width, map_height)});
		map = new google.maps.Map(document.getElementById("map"), {size:new GSize(map_width, map_height)});
	} else {
		//map = new GMap2(document.getElementById("map"));
		map = new google.maps.Map(document.getElementById("map"));
	}

	if(control_pad=="undefined" || control_pad != 0){
		map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT));
	}
	map.disableScrollWheelZoom();
	
	var current_marker;
	var store_list = new Array();
	var store_info;
	var marker_name = "new marker";
	this.center_position_lat;
	this.center_position_lon;
	this.zoom_level;
	this.GetTargetList = function() { return store_list; };
	this.PlaceMarker = PlaceMarker;
	this.InitPositionAndZoom = InitPositionAndZoom;
	this.StartMap = StartMap;
	this.StartMapStatic = StartMapStatic;
	this.ShowMarkers = ShowMarkers;
	this.RemoveMarkers = RemoveMarkers;
	this.RegisterEvents = RegisterEvents;
	this.RegisterLocationEvents = RegisterLocationEvents;

	/* 새로운 장소등록_장소프로필_09-03-31 */
	this.clearOverlays = function() {
		map.clearOverlays();
	}
	this.RemoveMarkers_store_reg = RemoveMarkers_store_reg;
	this.RegisterEvents_store_reg = RegisterEvents_store_reg;

	this.GetClickLat = function() {
		return this.click_position_lat;
	}
	this.GetClickLon = function() {
		return this.click_position_lon;
	}
	this.PanMap = function(lat, lon, zoomlevel) {
			if(!zoomlevel)
				map.setCenter(new GLatLng(lat, lon), this.zoom_level);
			else {
				map.setCenter(new GLatLng(lat, lon), zoomlevel);
				this.zoom_level = zoomlevel;
			}
	}
	this.SettingCurrentPositionZoomlevel = function() {
					var cen_point = map.getCenter();
					this.center_position_lat = cen_point.lat();
					this.center_position_lon = cen_point.lng();
					this.zoom_level = map.getZoom();
				}
	this.SetTargetList = function(target_list) {
					store_list = target_list;
				}
	this.OpenTargetWindow = function(marker_id) {
					return;
				}
	this.CloseTargetWindow = function(marker_id) {
					return;
				}
	this.GetZoomlevel = function() {
					return map.getZoom();
				}
	this.ZoomIn = function() {
					map.zoomIn();
				}
	this.ZoomOut = function() {
					map.zoomOut();
				}
	
	function InitPositionAndZoom(center_position_lat, center_position_lon, zoom_level, map_type, markername)
	{
		this.center_position_lat = center_position_lat;
		this.center_position_lon = center_position_lon;
		this.zoom_level = zoom_level;
		if(markername != "")
			marker_name = markername;
	}
	
	function StartMap(){
		
		var center_geopoint = new GLatLng(this.center_position_lat, this.center_position_lon);

		map.setCenter(center_geopoint, this.zoom_level);
		ShowMarkers(store_list);
		GEvent.addListener(map, "singlerightclick",  function(point, src, overlay) {
			
				try{
					var latlon = map.fromContainerPixelToLatLng(point);
					click_point_lat = latlon.lat();
					click_point_lon = latlon.lng();
					var div_menu = document.getElementById("div_rightclick_menu");			
					div_menu.style.left = map.getContainer().offsetLeft + point.x;
					div_menu.style.top = map.getContainer().offsetTop + point.y;
					div_menu.style.display = "block";
				} catch(e) {
					//alert(e.message);
				}
			});
		GEvent.addListener(map, "click", function() {
			try{ 
				var div_menu = document.getElementById("div_rightclick_menu");
				div_menu.style.display = "none";
			}catch(e) {
				//alert(e.message);
			}
		});
	}
	
	function StartMapStatic(){
		
		var center_geopoint = new GLatLng(this.center_position_lat, this.center_position_lon);
		map.removeControl(new GMapTypeControl());
		map.disableScrollWheelZoom();
		map.disableDoubleClickZoom();
		map.setCenter(center_geopoint, this.zoom_level);
		ShowMarkers(store_list);
	
		try{
				var latlon = map.fromContainerPixelToLatLng(point);
				click_point_lat = latlon.lat();
				click_point_lon = latlon.lng();
		} catch(e) {
					//alert(e.message);
		}
	}

	function RegisterEvents(){
		GEvent.addListener(map, "click",function(overlay,latlng) {
			
			if(!overlay) {
				RemoveMarkers();
				PlaceMarker(latlng.lat(), latlng.lng(), marker_name, "", "");
				try{
					//geocoder.getLocations(latlng, GetAddress);
					
					ActionAfterGetPosition(latlng.lat(), latlng.lng(), "", "");
					
				} catch(e) {}
			}
		});	
	}

	

   function RegisterLocationEvents(){
		GEvent.addListener(map, "click",function(overlay,latlng) {
			
			if(!overlay) {
				RemoveMarkers();
				PlaceMarker(latlng.lat(), latlng.lng(), marker_name, "", "");
				try{
					//geocoder.getLocations(latlng, GetAddress);
					document.store_input.lat.value = latlng.lat();
					document.store_input.lng.value = latlng.lng();
					//ActionAfterGetPosition(latlng.lat(), latlng.lng(), "", "");
					
				} catch(e) {}
			}
		});	
	}

	/* 새로운 장소등록_장소프로필_09-03-31 */
	function RegisterEvents_store_reg(){	
		marker_name="현재위치";
		GEvent.addListener(map, "click",function(overlay,latlng) {
			if(!overlay) {
				RemoveMarkers_store_reg();
				//PlaceMarker_store_reg(latlng.lat(), latlng.lng(), "장소위치", "", "");
				PlaceMarker(latlng.lat(), latlng.lng(), "장소위치", "", "");
                
				try{
					//geocoder.getLocations(latlng, GetAddress);
					ActionAfterGetPosition(latlng.lat(), latlng.lng(), "", "");
				} catch(e) {}
			}
		});
	}
	function RemoveMarkers_store_reg()
	{
		store_list = new Array();

		if(current_marker)
		{	
			map.removeOverlay(current_marker);
		}
	}

	/* 새로운 장소등록_장소프로필 끝 */
	
	function PlaceMarker(lat, lon, name, etc, cat)
	{ 
		var geo_point = new GLatLng(lat, lon)
		var custumIcon = CreateCustomMarkerImage(cat, name);
		if(!name || name=="")    name=marker_name;
		else marker_name = name;
		//markerOptions = { icon:custumIcon, title:marker_name, zIndexProcess:function() {} };
		markerOptions = { icon:custumIcon, title:marker_name};
		var new_marker= new GMarker(geo_point, markerOptions);
		
		map.addOverlay(new_marker); 
		current_marker = new_marker;
		
		if(etc) {
			GEvent.addListener(new_marker, "click", function() {
				new_marker.openInfoWindowHtml(etc, {pixelOffset:new GSize(0,0), maxWidth:300});
			});
			GEvent.addListener(new_marker, "mouseover", function() {
				new_marker.openInfoWindowHtml(etc, {pixelOffset:new GSize(0,0), maxWidth:300});
			});
		}
	}

	function GetAddress(response)
	{
		try{
			var street = "";
			if (!response || response.Status.code != 200) {    
				return;
			} else {    
				place = response.Placemark[0];       
				nara = place.AddressDetails.Country.CountryName;
				if(place.AddressDetails.Country.Locality) {
					si = place.AddressDetails.Country.Locality.LocalityName; 
					gu = place.AddressDetails.Country.Locality.DependentLocality.DependentLocalityName;
					arr_addr = place.AddressDetails.Country.Locality.DependentLocality.Thoroughfare.ThoroughfareName.split(" ");
					if(arr_addr.length > 1) {
						dong = arr_addr[1]; 
						street = arr_addr[0]; 
					} else {
						dong = arr_addr[0]; 
					}
				}
				ActionAfterGetPosition(place.Point.coordinates[1], place.Point.coordinates[0], si+" "+gu+" "+dong, place.address);
			}
		}catch(e){alert(e.message);}
	}
	
	function ShowMarkers(stores)
	{
		store_list = stores;
		for(i=0; i<store_list.length; i++) 
		{
			
			if (store_list[i].position_x != 0 && store_list[i].position_y != 0)
				PlaceMarker(store_list[i].position_x, store_list[i].position_y, store_list[i].marker_name, store_list[i].etc, store_list[i].category_id);
		}
	}


	var baseIcon = new GIcon(G_DEFAULT_ICON);
    //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(15, 15);
    baseIcon.shadowSize = new GSize(0, 0);
    baseIcon.iconAnchor = new GPoint(7, 7);
    baseIcon.infoWindowAnchor = new GPoint(7, 7);

	function CreateCustomMarkerImage(category_id, marker_name){
	 	var my_image = new GIcon(baseIcon);

		if(!category_id) {
				if(marker_name == "here"){
					my_image.iconSize = new GSize(12, 20);
					my_image.iconAnchor = new GPoint(1, 20);
					my_image.image = 'http://img.runpipe.com/v1/icon/ico_map.gif';
				}else{
					my_image.iconSize = new GSize(20, 34);
					my_image.iconAnchor = new GPoint(1, 20);
					my_image.image = 'http://www.google.com/mapfiles/marker.png';
				}
	 	}else    my_image.image = 'http://img.runpipe.com/v1/icon/ico_cat_'+category_id+'.gif';

		return my_image;
	}

	function RemoveMarkers()
	{
		store_list = new Array();
		map.clearOverlays();
	}
	
}

function getLocation() {  
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.getCurrentPosition(showLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function watchLocation() {  
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.watchPosition(showLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function getWriteLocation() { 
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.getCurrentPosition(showWriteLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function showError(error) {
//	alert(error.code + ' ' + error.message);
}

function showLocation(position) {

	var dbl_lat = position.coords.latitude;
	var dbl_lon = position.coords.longitude;

	GetMainAddressInfo(dbl_lat, dbl_lon);
}

function showWriteLocation(position) {

	var dbl_lat = position.coords.latitude;
	var dbl_lon = position.coords.longitude;

	GetNearStoreList(dbl_lat, dbl_lon);
}

function GetMainAddressInfo(lat, lon)
{  
	CallAjax("/map/address.google.ajax.php?lat="+lat+"&lon="+lon, "PutMainAddressInfo(responseText, "+lat+", "+lon+")");
}

function PutMainAddressInfo(resonseText, lat, lon)
{   
	var town_addr = document.getElementById("town_addr");
	var town_name = document.getElementById("town_name");
	var town_name_b = document.getElementById("town_name_b");
	var town_id = document.getElementById("town_id");
	var text = resonseText.split('|');

	if(Math.abs(lat)){
		town_addr.innerHTML = text[0];
		if(town_name)	town_name.innerHTML = "<a href='/town/index.php?town_id="+text[1]+"' class='a_font1'>"+text[2]+" 촌</a>";
		if(town_name_b)	town_name_b.innerHTML = "<a href='/town/index.php?town_id="+text[1]+"' class='a_font7_b'>"+text[2]+" 촌</a>";
		if(town_id)		town_id.innerHTML = text[1];
	}else{
		//town_addr.innerHTML = "수도권 2호선 선릉역";
		//town_name.innerHTML = "<a href='/town/index.php?town_id=110'>선릉 촌</a>";
		getDefaultTown();
	}
}

function getDefaultTown() {
	var town_addr = document.getElementById("town_addr");
	var town_name = document.getElementById("town_name");
	var town_name_b = document.getElementById("town_name_b");
	var town_id = document.getElementById("town_id");
	var addr, name, id;

	if(default_town_id){
		addr = default_town_addr;
		if(town_name)	name = "<a href='/town/index.php?town_id="+default_town_id+"' class='a_font1'>"+default_town_name+" 촌</a> ";
		if(town_name_b)	name = "<a href='/town/index.php?town_id="+default_town_id+"' class='a_font7_b'>"+default_town_name+" 촌</a> ";
		if(town_id)		id =default_town_id;
	}else{
		 addr = "수도권 2호선 선릉역";
		if(town_name)	name = "<a href='/town/index.php?town_id=110' class='a_font1'>선릉 촌</a>";
		if(town_name_b)	name = "<a href='/town/index.php?town_id=110' 'a_font7_b'>선릉 촌</a>";
		if(town_id)		id =110;
	}

	town_addr.innerHTML = addr;
	if(town_name)	town_name.innerHTML = name;
	if(town_name_b) town_name_b.innerHTML = name;
	if(town_id)		town_id.innerHTML = id;
}

function getStoreLocation() { 
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.getCurrentPosition(showStoreLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function showStoreLocation(position) {

	var dbl_lat = position.coords.latitude;
	var dbl_lon = position.coords.longitude;

//	document.getElementById("store_position_x").value = dbl_lat;
//	document.getElementById("store_position_y").value = dbl_lon;

	document.store_input.store_position_x.value  = dbl_lat;
	document.store_input.store_position_y.value  = dbl_lon;

	//GetStoreAddressInfo(dbl_lat, dbl_lon);
}

function GetStoreAddressInfo(lat, lon)
{  	 
	CallAjax("/map/address.google.ajax.php?lat="+lat+"&lon="+lon, "PutStoreAddressInfo(responseText)");
}

function PutStoreAddressInfo(resonseText)
{ 
	var text = resonseText.split('|');
	var address = text[0];
	var town_id = text[1];
	var town_name = text[2];
	var lat = text[3];
	var lon = text[4];
	var town_line = text[5];

	document.store_edit.store_address_main.value = address;
	document.store_edit.store_address_main.readOnly = false;

/*	var store_info;

	store_info = new Object();
	store_info.town_id = town_id;
	store_info.town_name = town_name;
	store_info.marker_id = "1";
	store_info.marker_name = "장소위치";
	store_info.position_x = lat;
	store_info.position_y = lon;
	store_info.category_id = "";
	store_info.etc = "";
	store_list.push(store_info);
*/		
	//var sel_region = document.getElementById("sel_region");
	//ChooseSelectValue(sel_region, town_name, "text");
	//GetLineInfo(sel_region.options[sel_region.selectedIndex].value, town_line, town_id);
	//	ShowMap("map", 17, '', lat, lon);	
	alert("선택하신 주소 : \n" + address);
}

function showCurrentLocation(){
	if (navigator.geolocation)  
		watchLocation();  //지역좌표가 있을 때
	else  
		getDefaultTown();
}

function ShowMap(div_id, zoom, cat, dbl_x, dbl_y)
{	
	var div_map = document.getElementById(div_id);

	div_map.style.width = "95%";
	div_map.style.height = "150px";

	if(!obj_map)
	{
		obj_map = new MapObject();
		obj_map.RegisterEvents();
	}

	if(dbl_x && dbl_y){

		obj_map.InitPositionAndZoom(dbl_x, dbl_y, zoom, "reg", document.store_input.store_name.value);
		obj_map.SetTargetList(store_list);
		obj_map.StartMap();
		document.store_input.store_position_x.value = dbl_x;
		document.store_input.store_position_y.value = dbl_y;
	//	GetStoreAddressInfo(dbl_x, dbl_y);

	}else{
		town_marker = GetTownPosition(document.store_input.sel_town.options[document.store_input.sel_town.selectedIndex].value);

		obj_map.InitPositionAndZoom(town_marker.position_x.text, town_marker.position_y.text, zoom, "reg", document.store_input.store_name.value);
		obj_map.SetTargetList(store_list);
		obj_map.StartMap();
		document.store_input.store_position_x.value = town_marker.position_x.text;
		document.store_input.store_position_y.value = town_marker.position_y.text;
	//	GetStoreAddressInfo(town_marker.position_x.text, town_marker.position_y.text);
	}
}

function ShowLocationByName()
{
	var width = "95%";
	var height = 120;
    var x = 270;
	var y = 280;
	var html = "<p><iframe src=\"/map/search.php\" width=\"" + width + "\" height=\"" + height + "\" leftmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\"  scrolling=\"no\"  frameborder=\"0\"></iframe></p>";

	var div = document.getElementById("popup");
	div.style.left = x;
	div.style.top = y;	
	div.style.width = width;
	div.style.height = height;
	div.innerHTML = html;
	div.style.display = "block";	
	popup = true;		
}

function goTown(){
	var town_id = document.getElementById("town_id");

	document.location.href="/town/index.php?town_id="+town_id.innerHTML; 
}

function GetNearStoreList(lat, lon)
{  	
	CallAjax("/map/address.write.ajax.php?lat="+lat+"&lon="+lon, "ShowNearStoreList(responseText)");
}

function ShowNearStoreList(responseText)
{  
	var write_addr = document.getElementById("town_addr");
	var addr = document.getElementById("addr");
	var dong_name = document.getElementById("dong_name");
	var store_list = document.getElementById("store_list");
    var text = responseText.split('|');

	write_addr.innerHTML = text[0];
	addr.value = text[0]; 
	dong_name.value = text[1]; 
	store_list.innerHTML = text[2];
	store_list.style.display = "block";
}

function SearchStoreNear()
{ 
	if (navigator.geolocation)  
		getSearchLocation();  //지역좌표가 있을 때
	else  
		getDefaultLocation();			 
}

function getSearchLocation() { 
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.getCurrentPosition(setSearchLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function showError(error) {
//	alert(error.code + ' ' + error.message);
}

function setSearchLocation(position) {
	var dbl_lat = position.coords.latitude;
	var dbl_lon = position.coords.longitude;

   showSearchStoreNear(1, dbl_lat,dbl_lon);
}

function getDefaultLocation() {
	var town_id = document.getElementById("town_id").value;
	var town_x = document.getElementById("town_x").value;
	var town_y = document.getElementById("town_y").value;

	if(town_id<1){
		town_id= 110;  /*디폴트촌=선릉*/
		town_x=	37.504378949616;
		town_y=	127.04869657861;
	}  
	showSearchStoreNear(1, town_x, town_y);
}

function showSearchStoreNear(page, dbl_lat, dbl_lon) {
	   
   CallAjax("/inc/m.search.store.near.php?dbl_lat="+dbl_lat+"&dbl_lon="+dbl_lon+"&page="+ page,"DisplayStoreNear(responseText)");
}

function DisplayStoreNear(text)
{
	  var target = document.getElementById("list_store");
	  target.innerHTML = text;
}

function SearchStoreKeyword()
{  
	if (navigator.geolocation)  
		getSearchKeywordLocation();  //지역좌표가 있을 때
	else  
		getDefaultKeywordLocation();			 
}

function getSearchKeywordLocation() { 
	// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
	navigator.geolocation.getCurrentPosition(setSearchKeywordLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function setSearchKeywordLocation(position) {
	var dbl_lat = position.coords.latitude;
	var dbl_lon = position.coords.longitude;
	var keyword = document.getElementById("search_keyword").value;

	SearchResultContent(1, keyword, dbl_lat,dbl_lon);
}

function getDefaultKeywordLocation() {
	var town_id = document.getElementById("town_id").value;
	var town_x = document.getElementById("town_x").value;
	var town_y = document.getElementById("town_y").value;
	var keyword = document.getElementById("search_keyword").value;

	if(town_id<1){
		town_id= 110;  /*디폴트촌=선릉*/
		town_x=	37.504378949616;
		town_y=	127.04869657861;
	}  
	SearchResultContent(1, keyword);
}

///////////////////////////////////// 구글맵 API V3 시작 //////////////////////////////////////////

  var initialLocation;
  var browserSupportFlag =  new Boolean();
  var current_user_lat = 0;
  var current_user_lng = 0;
  var current_user_address;
  var geocoder;
  function map_initialize(type) {
    var type_num = type;
    geocoder = new google.maps.Geocoder();
	// -------사용자 위치 추적 시작
	// Try W3C Geolocation (Preferred)
	  if(navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
		  initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		  current_user_lat = position.coords.latitude;
		  current_user_lng = position.coords.longitude;
		  codeLatLng(type_num);
		}, function() {
		  handleNoGeolocation(browserSupportFlag);
		});
	  // Try Google Gears Geolocation
	  } else if (google.gears) {
		browserSupportFlag = true;
		var geo = google.gears.factory.create('beta.geolocation');
		geo.getCurrentPosition(function(position) {
		  initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
  		  current_user_lat = position.coords.latitude;
		  current_user_lng = position.coords.longitude;
		  codeLatLng(type_num);
		}, function() {
		  handleNoGeoLocation(browserSupportFlag);
		});
	  // Browser doesn't support Geolocation
	  } else {
		browserSupportFlag = false;
		handleNoGeolocation(browserSupportFlag);
	  }
	  
	  function handleNoGeolocation(errorFlag) {
		if (errorFlag == true) {
		  alert("Geolocation service failed.");
		} else {
		  alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
		}
	  }
	// -------사용자 위치 추적 끝
  }
  function codeLatLng(type) {
    // 현재 사용자의 위도값(lat), 경도값(lng)
    var lat = 	current_user_lat;
    var lng = current_user_lng;
	var type_num = type;
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
			// 현재 사용자의 위도, 경도값으로 얻어낸 주소값(current_user_address)
		  current_user_address = results[1].formatted_address;
		  //document.getElementById('town_addr').innerHTML = current_user_address;
		  //document.getElementById('town_lat_lng').innerHTML = lat + ", " + lng;
		  if (type ==1){
			  //전체 쿠폰함으로 이동
			  location.href = '/runch/index.php?lat='+lat+'&lng='+lng;
		  }else if (type==2){
			  //내 쿠폰함으로 이동
			  location.href = '/runch/runch.user.coupon.list.php?lat='+lat+'&lng='+lng;
		  }
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }

