
var DestNode = Class.create();
DestNode.prototype = {
	initialize: function( params) {
		this.dest_id        = params.dest_id;
		this.dest_name      = params.dest_name;
		this.lat      		= parseFloat(params.lat);
		this.lng       		= parseFloat(params.lng);
		this.dest_level     = parseInt(params.dest_level);
		this.mapzoom	    = params.mapzoom;
		this.fullpath	    = params.fullpath;
		this.country_code   = params.country_code;
		this.json_node 	    = params.json_node;
	}
};

// Class ====================================================
var GeoCode = Class.create();
GeoCode.prototype = {

	initialize: function(baseContainerElm, params) {
		
		this.params = params;
		this.container = $(baseContainerElm);  //最外层容器
		this.formobj = $(params.form_id);  //form id/name
		this.allow_new = params.allow_new; //是否允许创建新地点
		this.enable_map = params.enable_map; //是否载入地图
		this.ajaxAPI = params.ajaxAPI; //ajax 接口
		this.editElement = params.editElement; //编辑输入框名称
		this.listElement = params.listElement; //下拉框名称
		this.defaultDestNode = params.defaultDestNode;  //默认地点
		
		this.idElement = params.idElement;  //dest_id
		this.nameElement = params.nameElement; //dest_name
		this.latElement = params.latElement; //dest_lat
		this.lngElement = params.lngElement; //dest_lng
		this.countrycodeElement = params.countrycodeElement; //country code
		this.gmapElement = params.gmapElement; //gmap data
		this.destUpdateMode = false;
		if(params.destUpdateMode) this.destUpdateMode = params.destUpdateMode;

		this.is_searching = false;
		this.latest_post_key = '';
		this.display_new_ops = false;
		this.moved_lat = 0;
		this.moved_lng = 0;
		
		this.destNodes = new Array();
		this.selected_destNode = null;
		this.selected_pop_destNode = null;
		this.localdata = true;
		
		if(params.need_windowload==undefined){
			this.need_windowload = true;
		}else{
			this.need_windowload = params.need_windowload;
		}
		
		try{
			this.googlegeo = new GClientGeocoder();
		}catch(e){
			this.googlegeo = null;
		}
		
		this._create_container_div();
		
		this.ac = new Autocompleter.MyLocal(this.editElement,this.listElement,this.destNodes, -1, {geocode:this, choices:20, fullSearch: true, ignoreCase:true, partialSearch: true });
					
		if(this.allow_new) this.ajaxAPI.walkr_dest_getAreaByLevel({level: '-1', keywords: '0'}, this._onGetAreaByLevel.bind(this));
	},
	
	_create_container_div: function() {
		var outer_width = this.container.offsetWidth;
		var div = document.createElement('div');
		div.id = 'destination_div';
		var defaultValue = '';
		if(this.defaultDestNode){
			defaultValue = this.defaultDestNode.dest_name;
		}
		
		//加入基本输入框
		div.innerHTML = this._create_container('');
										
		div.innerHTML += this._create_hidden_input();
				
		this.container.appendChild(div);
		
		this.ok_div = $(this.editElement+'_ok');

		if(this.allow_new) this._check_new_div();
		
		if(this.enable_map){
			this.pop_map_outer = $('pop_map_outer');
			this.mapOK = $('mapOK');
			if(this.mapOK){
				this.mapOK.onclick = delegateAsEventListener(this, function(e) {
					//确认				
					if(this.selected_destNode){
						if(this.moved_lat || this.moved_lng){
							this.selected_destNode.lat = this.moved_lat;
				  			this.selected_destNode.lng = this.moved_lng;
						}
						
						this._set_selected();
					}
					this._hide_map();
					this._hide_new_div();
					if(this.enable_map) this.callback_tip.style.display = '';					
				});
			}
			
			this.result_container = $('result_container');
			this.dest_detail = $('dest_detail');
			if(this.dest_detail){
				this.dest_detail.onkeypress = delegateAsEventListener(this, function(e) {	
					if(e.keyCode==Event.KEY_RETURN){
						var detail_key = this.ac.getToken()+' '+this.dest_detail.value;
						if(detail_key){
							this._do_dest_detail_search(detail_key);
						}
						return false;
				 	}
				});
			}
			
			this.dest_detail_search = $('dest_detail_search');
			if (this.dest_detail_search){
				this.dest_detail_search.onclick = delegateAsEventListener(this, function(e) {
					var detail_key = this.ac.getToken()+' '+this.dest_detail.value;
					if(detail_key){
						this._do_dest_detail_search(detail_key);	
					}
				});
			}
						
			this.map_outer_div = $('map_outer_div');
			this.callback_tip = $('callback_tip');
		}
				
		//提示动画
		var div_tips = this._create_div_tips($(this.editElement));
		this.div_tips = div_tips;
		this.container.appendChild(div_tips);
				
		if(this.allow_new){
			var insert_tips = document.createElement('div');
			insert_tips.id = 'loading_insert_tips';		
			insert_tips.style.position = 'absolute';
			insert_tips.style.zIndex = '2999';
			//insert_tips.style.display = 'none';
			insert_tips.innerHTML = '<img src="'+ theme_dir +'/images/loader_2.gif" alt="loading" title="loading..." height=16 width=16>';
			insert_tips.style.top =  '-1000px';
			insert_tips.style.left = '-1000px';
			this.container.appendChild(insert_tips);
			this.insert_tips = insert_tips;
		}
		
		if(this.enable_map){
			//this._hide_map();
			if(this.need_windowload){
				Event.observe(window, 'load', this.loadmap.bindAsEventListener(this), false);
			}else{
				this.loadmap();
			}
			try{
				Event.observe(window, 'unload', GUnload, false);
			}catch(e){}
		}
		return div;
	},
	
	_show_detail_result: function(n){
		if(this.result_container){
			var pos = this.getPos(this.dest_detail);
			this.result_container.style.left = pos.x + 'px';
			this.result_container.style.top = pos.y + 20 +'px';
			this.result_container.innerHTML = '<div><table width="100%"><tr><td>'+this._get_success_img()+'&nbsp;&nbsp;找到 <strong>'+n+'</strong> 个相符结果：</td><td align=right valign=top><img src="/media/themes/default/images/win_close.gif" width=13 height=11 border=0 style="cursor:pointer;padding:0px;" onmouseover="swap_image(this);" onmouseout="swap_image(this);" onclick="javascript:window.geocode._hide_detail_result();"></td></tr></table></div>';
		}
	},
		
	_get_success_img: function(){
		return '<img src="'+ theme_dir +'/gmap/ico_succeed.gif" alt="ok" height=12 width=14>';
	},
	
	_hide_detail_result: function(){
		if(this.result_container){
			this.result_container.style.left = '-1000px';
			this.result_container.style.top = '-1000px';
		}
	},
	
	_clear_detail_result: function(){
		if(this.result_container){
			this.result_container.innerHTML = '';
		}
	},
	
	_hide_map: function(){
		this.map_outer_div.style.display = 'none';
		this.callback_tip.style.display = 'none';
	},
		
	_create_container: function() {
		var editor_width = this.container.offsetWidth - 160;
		if(editor_width<150)editor_width = 150;
		
		var defaultValue = '';
		if(this.defaultDestNode){
			defaultValue = this.defaultDestNode.dest_name;
		}
		
		var s = '';
		s += StringBuffer.concat(
			'<div style="float:left;width:'+editor_width+'px;"><input name="'+ this.editElement +'" id="'+ this.editElement +'" type="text" size=40 value="'+defaultValue+'" style="width:'+(editor_width)+'px" title="输入地点名称或拼音或拼音简称" autocomplete="off" ></div>',
			'<div id="'+this.editElement+'_ok" style="float:left;width:20px;padding-top:5px;margin-left:5px;"></div>',
			'<div id="'+ this.listElement +'" name="'+ this.listElement +'" style="clear:both;display:none;border:1px solid #333333;width:195px;background-color:white;padding:2px"></div>',
			'<div class="blank1"></div>'
			);
		if(this.allow_new){
			s += this._create_new_div();
		}
			
		if(this.enable_map){
			s += '<div id="callback_tip" style="display:none"><img src="'+theme_dir+'/gmap/markers.gif" align=absmiddle height=20 border=0>&nbsp;位置设置成功（<a href="javascript:void(0)" onclick="window.geocode._show_map();">重新设置</a>）</div>';
			var s_map = '<div id="map_outer_div" style="width:410px;overflow:hidden;">';
			s_map += '<div class="bold"><img src="'+theme_dir+'/gmap/markers.gif" align=absmiddle height=20>&nbsp;拖动气球到正确的位置</div>';
			s_map += '<div id="pop_map" style="border:1px solid #7f7f7f;width:400px;height:300px;"></div>';
			s_map += '<DIV class=blank3></DIV>';
			//s_map += '输入详细地址进一步定位：<input type="text" name="dest_detail" id="dest_detail" size=40 style="width:140px;">&nbsp;<input type="button" id="dest_detail_search" value=" 搜 ">';
			s_map += '<div id="result_container" style="position:absolute;z-Index:9999; width:240px; left:-1000px;top:-1000px; padding:2px; background:#f4f3f1; border:1px solid #666;"></div>';
			if(!this.destUpdateMode){
				s_map += '<DIV class=blank6></DIV>';
				s_map += '<div style="width:400px;text-align:center"><input type="button" id="mapOK" value="保存位置"></div>';
			}
			s_map += '</div>';
			
			s += s_map;
		}else{
			s += '<div id="callback_tip" style="display:none;"></div>'
		}
		
		return s;
	},
	
	
	_create_hidden_input: function(){
		var s = '';
		s += '<input type="hidden" name="'+this.idElement+'" id="'+this.idElement+'" value="-1">';
		s += '<input type="hidden" name="'+this.nameElement+'" id="'+this.nameElement+'" value="">';
		s += '<input type="hidden" name="'+this.latElement+'" id="'+this.latElement+'" value="0">';
		s += '<input type="hidden" name="'+this.lngElement+'" id="'+this.lngElement+'" value="0">';
		s += '<input type="hidden" name="'+this.countrycodeElement+'" id="'+this.countrycodeElement+'" value="">';
		s += '<input type="hidden" name="'+this.gmapElement+'" id="'+this.gmapElement+'" value="">';
		return s;
	},
	
	destNodesContains: function(dest_id){
		for(var i=0;i<this.destNodes.length;i++){
			if(parseInt(this.destNodes[i].dest_id) == parseInt(dest_id)) return this.destNodes[i];			
		}
		return false;
	},
	
	clearArray: function(o){
		try{
			o.splice(0,o.length);
			o.length=0 ;
		}catch(e){}
	},
	
	_clear_selected: function(){
		$(this.idElement).value = '-1';  //dest_id
		$(this.nameElement).value = ''; //dest_name
		$(this.latElement).value = '0'; //dest_lat
		$(this.lngElement).value = '0'; //dest_lng			
		$(this.countrycodeElement).value = '';
		$(this.gmapElement).value = '';
		this.selected_destNode = null;
		
		if(this.destNodes)
			this.clearArray(this.destNodes);
		if(this.map)
			this.map.clearOverlays();
	
	},
	
	_set_selected: function(){
		var d = this.selected_destNode;
		if(d){
			$(this.idElement).value = d.dest_id;  //dest_id
			$(this.nameElement).value = d.dest_name; //dest_name
			$(this.latElement).value = d.lat; //dest_lat
			$(this.lngElement).value = d.lng; //dest_lng			
			$(this.countrycodeElement).value = '';
			$(this.gmapElement).value = '';
			
			if(d.json_node!=null){
				//google map
				$(this.countrycodeElement).value = d.country_code; //country code
				$(this.gmapElement).value = this.json2str(d.json_node); //gmap data
				//$('debug').innerHTML = ($(this.gmapElement).value);
			}
			if(!(parseFloat(d.lat)==0 && parseFloat(d.lng)==0)){
				var id = this.nameElement.replace('dest_name_','');
				window.add_a_mark(parseInt(id), new GLatLng(parseFloat(d.lat), parseFloat(d.lng)));
			}
		}else{
			this._clear_selected();
		}
	},
	
	_clear_timer: function(){
		if(this.request_timer) clearTimeout(this.request_timer);
	},
	
	_reset_timer: function(){
		if(this.is_searching) return;
		
		this._clear_div_tips();
		this._clear_selected();
		this.display_new_ops = false;
		
		if(!this.is_searching)
			this.request_timer = setTimeout(this._go_searching.bind(this), 700);
		
	},
	
	
	_create_div_tips: function(div){
		var div_tips = document.createElement('div');
		div_tips.id = 'loading_div_tips';		
		div_tips.style.position = 'absolute';
		div_tips.style.left = '-1000px';
		div_tips.style.top = '-1000px';
		div_tips.style.zIndex = '2999';
		div_tips.innerHTML = this._get_loading_img();
		return div_tips;
	},
	
	_selecte_a_dest: function(select_id){
		var e_ids = select_id.split('-'); //index+'_'+dest_id
		var index = parseInt(e_ids[0]);
		var dest_id = parseInt(e_ids[1]);
		var s_dest = null;
		
		if(this.destNodes.length>index) s_dest = this.destNodes[index];
		if(!s_dest) s_dest = this.destNodesContains(dest_id);
		if(s_dest){
			this._success_div_tips();
			if(this.enable_map)this._show_map();
			
			this.selected_destNode = s_dest;
			this._set_point();
			this._set_selected();
					
		}
	},
	
	_set_selected_outer: function(dest_node){
		if(dest_node){
			this._success_div_tips();
			
			this.selected_destNode = dest_node;
			this.ac.element.value = dest_node.dest_name;
			this._set_selected();
			if(this.enable_map){
				this._show_map();
				this._set_point();
			}
			//this.callback_tip.style.display = '';
		}else{
			this._clear_selected();
			this._clear_div_tips();
			$(this.editElement).value = ''; 
			/*
			this._clear_div_tips();
			this._clear_selected();
			this.display_new_ops = false;
			this.ac.element.value = '';
			*/
		}
	},
	
	_clear_div_tips: function(){
		if(this.div_tips) {
			//this.div_tips.innerHTML = '';
			this.div_tips.style.left = '-1000px';
			this.div_tips.style.top = '-1000px';
		}
		if(this.ok_div) {			
			this.ok_div.innerHTML = '';
		}
		
		if(window.map_upload_mode){
			window.map_marker = null;
			window.map.clearOverlays();
		}
	},
	
	_loading_div_tips: function(){
		if(this.div_tips) {
			this.div_tips.innerHTML = this._get_loading_img();
			var fix = 3;
			if(this._is_popup()) fix = 6;
			var pos = this.getPos(this.ac.element);
			this.div_tips.style.top =  pos.y+fix + 'px';
			this.div_tips.style.left = pos.x + this.ac.element.offsetWidth -18 + 'px';				
		}
	},
	
	_success_div_tips: function(){
		if(this.ok_div) {			
			this.ok_div.innerHTML = this._get_success_img();
			/*var fix = 4;
			if(this._is_popup()) fix = 7;
			var fix2 = 3;
			if(this._is_popup()) fix2 = 5;
			var pos = this.getPos(this.ac.element);
			this.div_tips.style.top =  pos.y+fix + 'px';
			this.div_tips.style.left = pos.x + this.ac.element.offsetWidth +fix2 + 'px';	
			*/		
		}
	},
	
	_get_loading_img: function(){
		return '<img src="'+ theme_dir +'/gmap/loading_16x16.gif" alt="loading" title="loading..." height=16 width=16>';
	},
	
	_get_success_img: function(){
		return '<img src="'+ theme_dir +'/gmap/ico_succeed.gif" alt="ok" height=12 align=absmiddle width=14>';
	},
	
	//地图相关函数
	
	loadmap: function() {
	  if (GBrowserIsCompatible()) {	    
	    var map = new GMap2(document.getElementById("pop_map"));    
	    //map.addControl(new GSmallMapControl());
	    //map.addControl(new TextualZoomControl());
	    map.addControl(new GSmallZoomControl());
	    map.addControl(new GMapTypeControl());
	    /*
	    var mapControl = new GHierarchicalMapTypeControl();        
	    mapControl.clearRelationships();
	    mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "显示地名", false);    
	    map.addControl(mapControl,new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10)));    
	    
	    
	    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180),
		new GLatLng(90, 180)),0);
		var copyrightCollection = new GCopyrightCollection();
		copyrightCollection.addCopyright(copyright);
		var dituTileLayer = new GTileLayer(copyrightCollection, 1, 17);
		dituTileLayer.getTileUrl = function(tile, zoom) {
			return "http://servicetile.mapabc.com/googlechina/maptile?v=w2.52&x=" + tile.x + "&y=" + tile.y + "&zoom=" + (17-zoom);
		};
		var G_CN_MAP = new GMapType([dituTileLayer],new GMercatorProjection(23), "中国政区", { shortName: "ditu", alt: "中国政区图" });
		window.G_CN_MAP = G_CN_MAP;
		map.addMapType(G_CN_MAP);		
		map.setMapType(G_CN_MAP);
		*/

		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		//map.addControl(new GOverviewMapControl());
		var center = new GLatLng(36, 106);
	    map.setCenter(center, 4);
	    setTimeout(function(){map.checkResize();}, 500);
	    
		this.map = map;
		this._hide_map();
	  }
	},
	
	_set_point: function(){
		var d = this.selected_destNode;
		if(d){
			
			var center = new GLatLng(d.lat, d.lng);
			var marker = new GMarker(center, {draggable: true});
			this.cur_marker = marker;
			var t = this;
			t.moved_lat = 0;
			t.moved_lng = 0;
			  
			GEvent.addListener(marker, "dragend", function() {
			  var newPoint = marker.getPoint();
			  t.moved_lat = newPoint.lat();
			  t.moved_lng = newPoint.lng();
			  t.map.panTo(newPoint);
			  if(t.selected_destNode){
			  	t.selected_destNode.lat = t.moved_lat;
			  	t.selected_destNode.lng = t.moved_lng;
			  }
			  if(t.destUpdateMode){
			  	t._set_selected();
			  }
			});
			if(this.map){
				this.map.clearOverlays();
				
				this.map.setCenter(center, this.get_fit_map_zoom(d));
				this.map.addOverlay(marker);
				/*
				if(d.country_code!='CN'){
					this.map.setMapType(G_NORMAL_MAP);
				}else{
					this.map.setMapType(G_CN_MAP);
				}
				*/
			}
		}
	},
	
	_show_map: function(){
		if(!this.enable_map)return;
		if(this.map_outer_div.style.display == 'none'){
			this.callback_tip.style.display = 'none';
			this.map_outer_div.style.display = 'block';
			if($('rightmap')){$('rightmap').style.display = 'none';}
		}
		if(this.map){
			this.map.checkResize();
		}
		if($('blank_tip_div'))
			$('blank_tip_div').style.display = 'none';
	},
		
	
	_get_json_depth: function(json){
		if(!json) return 0;
	    for(var x in json){
	        if(typeof(json[x])=='object')
	            return this._get_json_depth(json[x])+1;        
	    }
	    return 0;
	},
	
	get_fit_map_zoom: function(dest_node){
		if(dest_node.json_node){
			//var json = dest_node.json_node.AddressDetails;
			//var json_depth = this._get_json_depth(json);
			return this.get_search_fitzoom_bydepth(dest_node.json_node, 'depth');
		}else{
			if(parseInt(dest_node.mapzoom)>0)
				return parseInt(dest_node.mapzoom);
			return this.get_search_fitzoom_bydepth(dest_node.dest_level,'level');
		}
		return 10;
	},
	
	get_search_fitzoom_bydepth: function(d,m){
		if(!d) return 10;
		if(m=='depth'){
			var zoom_for_accuracy=[17,12,8,6,4,3,1,0,0];
			var H=d.AddressDetails?d.AddressDetails.Accuracy:8;
			var K=zoom_for_accuracy[Math.max(Math.min(H,8),0)];
			return 17-K-3;
		}else{
			if(d<1) return 4;
			else if(d<2) return 6;
			else if(d<3) return 10;
			else if(d<4) return 12;
			else if(d<5) return 14;
			else if(d<6) return 15;
			else return 16;
		}
		return 10;
	},
	
	
	//地图相关函数结束
	
	//搜索
	_go_searching: function(){		
		if((this.ac.getToken().length>1)&&(this.latest_post_key!=this.ac.getToken())&&(!this.innert_mode)){
			if(!this.is_searching){
				this._clear_div_tips();
				this._clear_selected();
				
				this.request_from_localserver();
				this.is_searching = true;
				this._clear_timer();				
			}
		}
	},
	
	
	clear_input: function(){
		this.ac.element.value='';
	},
	
	
	request_from_localserver: function () {
		//到本地服务器获取数据
		if(this.ac.getToken().length>1){
			this.clearArray(this.destNodes);			
			this._loading_div_tips();
			this.ajaxAPI.walkr_dest_getDestination({keywords: this.ac.getToken()},this._onGetDestination.bind(this));
		}else{
			this.is_searching = false;
		}
	},
	
	request_googlemap: function(){
		if(this.ac.getToken().length>1){
			this.clearArray(this.destNodes);
			this._googleGetAddress(this.ac.getToken());
		}
	},
	
	_reset_map_center: function(lat,lng,z){
		if(this.cur_marker){
			var center = new GLatLng(lat,lng);
			if(this.map.getZoom()==z)
				this.map.panTo(center);
			else
				this.map.setCenter(center,z);
			
			this.moved_lat = lat;this.moved_lng = lng;
			if(this.selected_destNode){
				this.selected_destNode.lat = this.moved_lat;
	  			this.selected_destNode.lng = this.moved_lng;
			}
			
			if(this.destUpdateMode){
			  	this._set_selected();
			}
			
			this.cur_marker.setPoint(center);
			this._hide_detail_result();
		}
	},
	
	_do_dest_detail_search: function(address){
		this._clear_detail_result();
		this._hide_detail_result();
		if(!this.googlegeo) return;
		var t= this;
	    this.googlegeo.getLocations(address,
	    function getaddress(response) {	    
		  if (!response || response.Status.code != 200) {
		    alert('没有找到相关地点！');
		  } else {		  	
		  	var places = response.Placemark;
		  	t._show_detail_result(places.length);
		  	for(var i=0;i<places.length;i++){
		    	var place = places[i];
		    	
		    	var zoom_for_accuracy=[17,12,8,6,4,3,1,0,0];
				var H=place.AddressDetails?place.AddressDetails.Accuracy:8;
				var z=zoom_for_accuracy[Math.max(Math.min(H,8),0)];
				z = 17-z-2;
				var lat = parseFloat(place.Point.coordinates[1]);
				var lng = parseFloat(place.Point.coordinates[0]);
				
				t.result_container.innerHTML += '<div style="margin-left:2px;margin-top:2px;margin-bottom:2px;"><a href="javascript:void(0);" onclick="window.geocode._reset_map_center('+lat+','+lng+','+z+');">'+ place.address +'</a></div>';
			}
		  }
		});
	},
	
	_googleGetAddress: function(address) {
		if(!this.googlegeo) this._googleGetErr();
		
		var t= this;
	    this.googlegeo.getLocations(address,
	    function getaddress(response) {	 
	      t.localdata = false;
		  if (!response || response.Status.code != 200) {
		    t._googleGetErr();
		  } else {
		    var places = response.Placemark;
		    t._googleGetOk(places);		    
		  }
		}	
	  );
	},
	
	_googleGetErr: function(){
		this._clear_div_tips();
		this.is_searching = false;
		this.display_new_ops = true;		
		this.ac.activate();
		this.ac.render();
	},
	
	_googleGetOk: function(places){
		this.clearArray(this.destNodes);
	    for(var i=0;i<places.length;i++){
	    	var place = places[i];
	    	var country_code = '';
	    	try{
		    	if(place.AddressDetails.Country.CountryNameCode) 
		    		country_code = place.AddressDetails.Country.CountryNameCode;
	    	}catch(e){
	    		if(place.address.indexOf('台湾')==0) country_code = 'TW';
	    	}
		    var param =  {dest_id: (0-i), dest_name:this.ac.getToken(),
						  lat: parseFloat(place.Point.coordinates[1]),
						  lng: parseFloat(place.Point.coordinates[0]),
						  dest_level: -1,
						  mapzoom: -1,
						  fullpath: place.address,
						  country_code: country_code,
						  json_node: place};
							  
			var dest_node = new DestNode(param);
					
			if(!this.destNodesContains(param.dest_id)){
				this.destNodes.push(dest_node);
			}
			/*
			 {
			  "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
			  "Status": {
			    "code": 200,
			    "request": "geocode"
			  },
			  "Placemark": [
			    {
			      "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
			      "AddressDetails": {
			        "Country": {
			          "CountryNameCode": "US",
			          "AdministrativeArea": {
			            "AdministrativeAreaName": "CA",
			            "SubAdministrativeArea": {
			              "SubAdministrativeAreaName": "Santa Clara",
			              "Locality": {
			                "LocalityName": "Mountain View",
			                "Thoroughfare": {
			                  "ThoroughfareName": "1600 Amphitheatre Pkwy"
			                },
			                "PostalCode": {
			                  "PostalCodeNumber": "94043"
			                }
			              }
			            }
			          }
			        },
			        "Accuracy": 8
			      },
			      Point: {
			        coordinates: [-122.083739, 37.423021, 0]
			      }
			    }
			  ]
			}
						 
			*/
	    }
	    
		this._clear_div_tips();
		this.is_searching = false;
		this.display_new_ops = true;
		this.ac.activate();
		this.ac.render();
	},
	
	_onGetDestination:function (xmlhttp) {
		if(errorResponseXml(xmlhttp)){
			//到googlemap服务器上搜索地点
			this.request_googlemap();
			return;
		}
		
		this.clearArray(this.destNodes);
		
		var destinations = xmlhttp.responseXML.documentElement.getElementsByTagName('destination');
	
		for (var t = 0; t < destinations.length; t++) {
			var d = destinations[t];
			var dest_name = d.firstChild.nodeValue.trim();
			var param =  {dest_id: parseInt(d.getAttribute('id')), 
						  dest_name:dest_name,
						  lat: parseFloat(d.getAttribute('lat')),
						  lng: parseFloat(d.getAttribute('lng')),
						  dest_level: parseInt(d.getAttribute('dest_level')),
						  mapzoom: parseInt(d.getAttribute('mapzoom')),
						  fullpath: d.getAttribute('fullpath'),
						  country_code: d.getAttribute('country_code'),
						  json_node:null
						  };
						  
			var dest_node = new DestNode(param);				
			if(!this.destNodesContains(param.dest_id)){
				this.destNodes.push(dest_node);
			}
		}			
		if(destinations.length>0){
			//从本地服务器获取到数据
			this._clear_div_tips();
			this.is_searching = false;
			this.display_new_ops = true;
			this.localdata = true;
			this.ac.activate();
			this.ac.render();
		}else{
			//到googlemap服务器上搜索地点
			this.request_googlemap();
		}
	},
	
	checkAbsolute: function(el){
		while(el){
			if(el.style.position=='absolute') return el;
			el = el.offsetParent;
		}
		return null;
	},
	
	getPos: function(el){
		var pos = window.getPos(el);
		var absEl = this.checkAbsolute(el);
		if(absEl){
			var pos_abs = window.getPos(absEl);
			pos.x = pos.x - pos_abs.x;
			pos.y = pos.y - pos_abs.y + 2;
		}
		return pos;
	},
	
	//添加新地点
	
	_show_new_div: function(){
		if(!this.allow_new) return ;
		var fix = 21;
		if(this._is_popup()) fix = 24;
		var fix2=0;
		if(this._is_popup()) fix2 = 2;
		var pos = this.getPos(this.ac.element);
		this.new_item_div.style.top = pos.y+fix +'px';
		this.new_item_div.style.left = pos.x + fix2 +'px';
		this.new_item_div.style.display = '';
		this.new_item_div.style.width = this.ac.element.offsetWidth +'px';
		this.innert_mode = true;
		show($('area0'));
		show($('area1'));
	},
	
	_hide_new_div: function(){
		if(!this.allow_new) return ;
		this.new_item_div.style.top = '-1000px';
		this.new_item_div.style.left = '-1000px';
		this.new_item_div.style.display = 'none';
		
		$('area1').selectedIndex = 0;
		for(var m=2;m<5;m++){
			this.deleteSelect('area'+m);
			hideElement($('area'+m));
			hideElement($('div_area'+m));
		}
		this.innert_mode = false;
	},
	
	new_item_do: function(){
		if(!this.allow_new) return ;
		this._show_new_div();
		this.innert_mode = true;
	},
	
	new_item_cancel: function(){
		if(!this.allow_new) return ;
		this._hide_new_div();					
	},
	
	_create_new_div: function(){
		if(!this.allow_new) return '';
		
		var s = '';
		s += StringBuffer.concat(
			'<div id="hiddenSelect" style="position:absolute; display:none; top:-10000px;left:-10000px; z-Index:999; width:195px;border-left: 1px solid #C1DB6C; border-top: 1px solid #C1DB6C;border-right: 2px solid #95af41; border-bottom: 2px solid #95af41; background-color: #f4fdd8;padding:2px 4px 5px 5px;">',
			'<div>创建这个新地点，属于:</div><div class="blank3"></div><div id="div_area0" class="new_dest_select"><select id="area0" name="area0" style="z-Index:900;"></select></div>',
			'<div id="div_area1" class="new_dest_select"><select id="area1" name="area1" style="z-Index:900;"></select></div>',
			'<div id="div_area2" class="new_dest_select"><select id="area2" name="area2" style="z-Index:900;"></select></div>',
			'<div id="div_area3" class="new_dest_select"><select id="area3" name="area3" style="z-Index:900;"></select></div>',
			'<div id="div_area4"><select id="area4" name="area4" style="z-Index:900;"></select></div>',
			'<div id="span_new_button"><div class="blank6"></div><div ><input type=button id=new_dest_button value="创 建">&nbsp;&nbsp;或&nbsp;&nbsp;<input type="button" id="btn_cancel_new" value="取 消"></div></div>',
			'</div>',
			'<div id="span_button" style="display:none"></div>'
			);
		
		return s;
	},
	
	_check_new_div: function(){
		if(!this.allow_new) return ;
		this.span_button = $('span_button');
		this.new_item_div = $('hiddenSelect');
		
		for(var m=0;m<4;m++){
			$('area'+m).onchange = delegateAsEventListener(this, function(e) {
				var el_id = '';
				if(IE){
					el_id = e.srcElement.id;
				}else{
					el_id = e.target.id;
				}
				var el_index = ''+el_id.substring(4,5);

				this.GetAreaByLevel(parseInt(el_index),'area');
			});
		}
		
		var btn = $('new_dest_button');		
		btn.onclick = delegateAsEventListener(this, function(e) {					
			var parent_id = $F('area1');
			
			for(var m=2;m<5;m++){
				var o = ('area'+m);
				if($(o).style.display!='none'){
					if($(o).innerHTML == ''){ 
						break;
					}else{
						if($F(o)!='-1')						
							parent_id = $F(o);
						else
							break;
					}
				}else{
					break;
				}
			}
    		
    		this.new_parent_id = parent_id;
    		var dest_name = this.ac.element.value;
    		
    		if((this.new_parent_id>0)&&(dest_name)){
    			this.adddest(dest_name,this.new_parent_id);
    		}
		});
		
		$('btn_cancel_new').onclick = delegateAsEventListener(this, function(e) {
			this._hide_new_div();
		});
	
	},
		
	
	show_insert_tips : function(level){
		var obj = $(level);
		var pos = this.getPos(obj);
		this.insert_tips.style.top =  pos.y+3 + 'px';
		this.insert_tips.style.left = pos.x + obj.offsetWidth + 4 + 'px';
		//show(this.insert_tips);
	},
	
	hide_insert_tips : function(level){
		this.insert_tips.style.top =  '-1000px';
		this.insert_tips.style.left = '-1000px';
		//hide(this.insert_tips);
	},
		
	adddest: function(dest_name,parent_id)
	{
		if(!this.allow_new) return ;
		if((dest_name)&&(parent_id>0)){
			if(window.toolTip){toolTip.show('正在创建地点数据...',{center:true,width:200,time:3000});}
			this.ajaxAPI.walkr_dest_addDestination({dest_name: dest_name, parent_id:parent_id}, this._onAddDest.bind(this));		
		}
	},
	
	
	_onAddDest: function (xmlhttp){
		if(window.toolTip){toolTip.hide();}		
		if(errorResponseXml(xmlhttp)){
			alert('添加地点失败，请重试！');
			return;
		}
		
		var d = xmlhttp.responseXML.documentElement.getElementsByTagName('destination')[0];
		var param =  {dest_id: parseInt(d.getAttribute('id')), 
					  dest_name: d.getAttribute('dest_name'),
					  lat: parseFloat(d.getAttribute('lat')),
					  lng: parseFloat(d.getAttribute('lng')),
					  dest_level: parseInt(d.getAttribute('dest_level')),
					  mapzoom: parseInt(d.getAttribute('mapzoom')),
					  fullpath: d.getAttribute('fullpath'),
					  country_code: d.getAttribute('country_code'),
					  json_node:null
					  };
					  
		var dest_node = new DestNode(param);
		
		this.selected_destNode = dest_node;
		this._set_selected();
		setTimeout(this._success_div_tips.bind(this), 20);
		this.ac.element.value = this.selected_destNode.fullpath;
		this._hide_new_div();
		
		if(this.enable_map){
			this._set_point();
		}
	},
	
	
	GetAreaByLevel:function(indexSelect,select_pre){
		var parentID = $(select_pre+indexSelect).value;
	    if( (parentID=='') || (parentID=='undefined') )
    	{
    		setTimeout('GetAreaByLevel('+indexSelect+',"'+select_pre+'")',1500);
    		return;
    	}
    	this.show_insert_tips(select_pre+indexSelect);
    	
	    this.ajaxAPI.walkr_dest_getAreaByLevel({level: indexSelect, keywords: parentID}, this._onGetAreaByLevel.bind(this));	    
	},
	
	_onGetAreaByLevel:function (xmlhttp) {
		this.hide_insert_tips();
		if(errorResponseXml(xmlhttp)){
			return;
		}
			
		var level = xmlhttp.responseXML.documentElement.getElementsByTagName('levels')[0].getAttribute('level');
		var destinations = xmlhttp.responseXML.documentElement.getElementsByTagName('destination');
		
		var next_level = level*1+1;
		
		var select_pre = 'area';			
		this.fill_select(next_level,destinations,select_pre)
		
		if(parseInt(level)==-1){
			this.ajaxAPI.walkr_dest_getAreaByLevel({level: '0', keywords: '0'}, this._onGetAreaByLevel.bind(this));
		}
	},
	
	fill_select:function(next_level,destinations,select_pre){
		var nextSelect = select_pre+next_level;			
		this.deleteSelect(nextSelect);
		var oNextSelect = $(nextSelect);
		for(var j=next_level;j<5;j++){
			this.deleteSelect(select_pre+j);
			hide($(select_pre+j));
			hide($('div_'+select_pre+j));
		}				
		if(destinations.length>0){
			show($('div_'+nextSelect));
			show(oNextSelect);			
			if(next_level>1)
			{
				if(isMSIE)
		        	oNextSelect.add(new Option('...','-1'));
		        else
		        	this.appendToSelect(oNextSelect,'...','-1');
			}
		}
			
		for (var t = 0; t < destinations.length; t++) {
			var dest_name = destinations[t].firstChild.nodeValue.trim();
			var dest_id = destinations[t].getAttribute('id');
			
			this.appendToSelect(oNextSelect,dest_name,dest_id);
		}
		
	},
	
	deleteSelect:function(obj)
	{
		var objSelect = $(obj);
		objSelect.innerHTML = '';
		//while (objSelect.length > 0) {
	    //    objSelect.remove(0);
	    //}
	},
	
	appendToSelect:function(select,content, value) {   
    	if(isMSIE)
			select.add(new Option(content,value));
		else
	    	select.innerHTML += '<option value='+ value +'>'+ content +'</option>';
	},
	
	//添加新地点结束
	
	
	
	//公共操作
	_is_popup: function(){
		return false;
	},
	
	_destNodeClone: function(node){
		var param =  {dest_id: node.dest_id, dest_name: node.dest_name,
					  lat: node.lat,
					  lng: node.lng,
					  dest_level: node.dest_level,
					  mapzoom: node.mapzoom,
					  fullpath: node.fullpath,
					  country_code: node.country_code,
					  json_node: node.json_node};							  
		return new DestNode(param);
	},
	
	
	json2str: function(o){
	    var r = [];
	    if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
	    if(typeof o == "object"){
	        if(!o.sort){
	            for(var i in o)
	                r.push("\""+i+"\":"+ this.json2str(o[i]));
	            if(!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){
	                r.push("toString:"+o.toString.toString());
	            }
	            r="{"+r.join()+"}"
	        }else{
	            for(var i =0;i<o.length;i++)
	                r.push(this.json2str(o[i]))
	            r="["+r.join()+"]"
	        }
	        return r;
	    }
	    return o.toString();
	}
}
