$(function() {
	var $citySearch = $("#city-search");
	$citySearch.click(function() {
		var html = [];
		html.push('<div id="citySearch" class="city-search-box">');
		$.post("", {}, function() {
			
		}, "json");
		html.push('</div>');
	});
	
	var $searchType = $("#search-type-switch a");
	var $searchForm = $("#search-form-switch li");
	var $searchFromto = $("#search-fromto");
	var $searchKey = $("#search-key");
	var $result = $("#result");
	var $price = $("#price");
	var $tPolicy = $("#tPolicy");
	var $dPolicy = $("#dPolicy");
	var $route = $("#route");
	var $local = $("#local");
	
	var transitStart, transitEnd, drivingStart, drivingEnd;
	
	var map = new BMap.Map("map");
	map.centerAndZoom(new BMap.Point(mapX, mapY), 13);
	var opts = { type: BMAP_NAVIGATION_CONTROL_LARGE };
	map.addControl(new BMap.NavigationControl(opts)); // 添加缩放控件
	map.addControl(new BMap.ScaleControl());          // 添加比例尺控件
	map.addControl(new BMap.OverviewMapControl());    // 添加缩略地图控件
	map.enableScrollWheelZoom(); // 启用地图滚轮放大缩小
	map.enableKeyboard();        // 启用键盘上下左右键移动地图
	// 位置检索、周边检索和范围检索
	window.local = new BMap.LocalSearch(city, {
		onSearchComplete: function(results) {
			if(local.getStatus() == BMAP_STATUS_SUCCESS) {
				map.clearOverlays();
				var ary = new Array();
				ary[BMAP_POI_TYPE_NORMAL] = "地址：";
				ary[BMAP_POI_TYPE_BUSSTOP] = "途经公交车：";
				ary[BMAP_POI_TYPE_SUBSTOP] = "途经地铁：";
				var s = [], openInfoWinFuns = [], bounds = [];
				s.push('<ul>');
				for(var i = 0; i < results.getCurrentNumPois(); i++) {
					bounds.push(results.getPoi(i).point);
					var marker = addMarker(results.getPoi(i).point, i);
					var openInfoWinFun = addInfoWindow(marker, results.getPoi(i), i);
					openInfoWinFuns.push(openInfoWinFun);
					s.push('<li class="clearfix">');
					s.push('<span class="marker" style="background-position:' + (5 - i * 24) + 'px -193px;"></span>');
					s.push('<span class="name"><a title="" href="javascript:void(0);">' + results.getPoi(i).title.replace(new RegExp(results.keyword,"g"),'<strong>' + results.keyword + '</strong>') + '</a></span>');
					s.push('<span class="address">' + ary[results.getPoi(i).type] + results.getPoi(i).address + '</span>');
					s.push('</li>');
				}
				s.push('</ul>');
				var pageIndex = results.getPageIndex();
				var pageCount = results.getNumPages() - 1;
				var pageStart = pageIndex > 2 ? pageIndex - 1 : 0;
				pageStart = pageStart < pageCount - 3 ? pageStart : pageCount - 3;
				var pageEnd = pageIndex > 2 ? pageIndex + 2 : 3;
				pageEnd = pageEnd < pageCount ? pageEnd : pageCount;
				s.push('<div id="localPage" class="page">');
				if(pageIndex > 2) {
					s.push('<a title="" href="javascript:void(0);" page="0">1</a><strong>...</strong>');
				}
				for(i = pageStart; i <= pageEnd; i++) {
					if(i == pageIndex) {
						s.push('<strong>' + (i + 1) + '</strong>');
					} else {
						s.push('<a title="" href="javascript:void(0);" page="' + i + '">' + (i + 1) + '</a>');
					}
				}
				s.push('</div>');
				$local.html(s.join(""));
				$li = $local.find("ul li");
				$li.click(function() {
					$li.removeClass("current");
					var $this = $(this);
					$this.addClass("current");
					openInfoWinFuns[$this.index()]();
				});
				$("#localPage a").click(function() {
					local.gotoPage(parseInt($(this).attr("page")));
				});
				map.setViewport(bounds);
			}
		}
	});
	// 添加下拉菜单
	var menu = new BMap.ContextMenu();
	var iconSize = new BMap.Size(42, 34);
	var markerStart = new BMap.Marker(null, { icon: new BMap.Icon(root + "theme/simple/images/map-markers.png", iconSize) });
	markerStart.enableDragging(true); // 设置标注可拖拽
	var markerEnd = new BMap.Marker(null, { icon: new BMap.Icon(root + "theme/simple/images/map-markers.png", iconSize, { imageOffset: new BMap.Size(0, -34)}) });
	markerEnd.enableDragging(true); // 设置标注可拖拽
	var txtMenuItem = [
		{
			text: '以此为起点',
			callback: function(e) {
				var index = $("#search-type-switch .current").index();
				if(index == 1) {
					if(drivingEnd != null) {
						driving(e, drivingEnd, $(":input[name='dpolicy']:checked")[0].id.replace("dpolicy", ""));
					} else {
						markerStart.setPosition(e);
						map.addOverlay(markerStart);
						drivingStart = e;
					}
				} else {
					if(transitEnd != null) {
						$searchType.eq(0).click();
						transit(e, transitEnd, $(":input[name='tpolicy']:checked")[0].id.replace("tpolicy", ""));
					} else {
						markerStart.setPosition(e);
						map.addOverlay(markerStart);
						transitStart = e;
					}
				}
			}
		}, {
			text: '以此为终点',
			callback: function(e) {
				var index = $("#search-type-switch .current").index();
				if(index == 1) {
					if(drivingStart != null) {
						driving(drivingStart, e, $(":input[name='dpolicy']:checked")[0].id.replace("dpolicy", ""));
					} else {
						markerEnd.setPosition(e);
						map.addOverlay(markerEnd);
						drivingEnd = e;
					}
				} else {
					if(transitStart != null) {
						$searchType.eq(0).click();
						transit(transitStart, e, $(":input[name='tpolicy']:checked")[0].id.replace("tpolicy", ""));
					} else {
						markerEnd.setPosition(e);
						map.addOverlay(markerEnd);
						transitEnd = e;
					}
				}
			}
		}
	];
	for(var i = 0; i < txtMenuItem.length; i++) {
		menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
	}
	map.addContextMenu(menu);
	// 查询类型
	$searchType.click(function() {
		map.clearOverlays();
		$searchType.removeClass("current");
		$searchForm.hide();
		var $this = $(this);
		$this.addClass("current");
		$result.hide();
		var index = $this.index();
		if(index == 0) {
			$price.show();
			$tPolicy.show();
			$dPolicy.hide();
			$route.show();
			$local.hide();
			$searchFromto.show();
		} else if(index == 1) {
			$price.show();
			$tPolicy.hide();
			$dPolicy.show();
			$route.show();
			$local.hide();
			$searchFromto.show();
		} else {
			$price.hide();
			$tPolicy.hide();
			$dPolicy.hide();
			$route.hide();
			$local.show();
			$searchKey.show();
		}
	}).eq(0).click();
	// 切换查询策略
	$(":input[name='tpolicy']").click(function() {
		var policyIndex = this.id.replace("tpolicy", "");
		map.clearOverlays();
		transit(transitStart, transitEnd, policyIndex);
	});
	$(":input[name='dpolicy']").click(function() {
		var policyIndex = this.id.replace("dpolicy", "");
		map.clearOverlays();
		driving(drivingStart, drivingEnd, policyIndex);
	});
	// 交换起点和终点
	$("#search-fromto button.swap").click(function() {
		var $inputTxt = $searchFromto.find(".input-txt");
		var tmp = $inputTxt.eq(0).val();
		$inputTxt.eq(0).val($inputTxt.eq(1).val());
		$inputTxt.eq(1).val(tmp);
	});
	// 公交或驾车查询
	$("#search-fromto button.submit").click(function() {
		var $inputTxt = $searchFromto.find(".input-txt");
		if($inputTxt.eq(0).val() != "" && $inputTxt.eq(1).val() != "") {
			var index = $("#search-type-switch .current").index();
			if(index == 0) {
				transit($inputTxt.eq(0).val(), $inputTxt.eq(1).val(), $(":input[name='tpolicy']:checked")[0].id.replace("tpolicy", ""));
			} else if(index == 1) {
				driving($inputTxt.eq(0).val(), $inputTxt.eq(1).val(), $(":input[name='dpolicy']:checked")[0].id.replace("dpolicy", ""));
			}
		}
	});
	// 其他查询
	$("#search-key button.submit").click(function() {
		var $inputTxt = $searchKey.find(".input-txt");
		if($inputTxt.val() != "") {
			map.clearOverlays();
			local.search($inputTxt.val());
			$result.show();
		}
	});
	// 添加标注
	function addMarker(point, index) {
		var myIcon = new BMap.Icon(root + "theme/simple/images/map-local-markers.png", new BMap.Size(29, 32), {
			imageOffset: new BMap.Size(0 - index * 29, 0)
		});
		var marker = new BMap.Marker(point, {icon: myIcon});
		map.addOverlay(marker);
		return marker;
	}
	// 添加信息窗口
	function addInfoWindow(marker, poi, index) {
		var maxLen = 10;
		var name = null;
		if(poi.type == BMAP_POI_TYPE_NORMAL) {
			name = "地址："
		} else if(poi.type == BMAP_POI_TYPE_BUSSTOP) {
			name = "公交："
		} else if(poi.type == BMAP_POI_TYPE_SUBSTOP) {
			name = "地铁："
		}
		// infowindow的标题
		var infoWindowTitle = '<div style="font-weight:bold;color:#CE5521;font-size:14px">'+poi.title+'</div>';
		// infowindow的显示信息
		var infoWindowHtml = [];
		infoWindowHtml.push('<table cellspacing="0" style="table-layout:fixed;width:100%;font:12px arial,simsun,sans-serif"><tbody>');
		infoWindowHtml.push('<tr>');
		infoWindowHtml.push('<td style="vertical-align:top;line-height:16px;width:38px;white-space:nowrap;word-break:keep-all">' + name + '</td>');
		infoWindowHtml.push('<td style="vertical-align:top;line-height:16px">' + poi.address + ' </td>');
		infoWindowHtml.push('</tr>');
		infoWindowHtml.push('</tbody></table>');
		var infoWindow = new BMap.InfoWindow(infoWindowHtml.join(""),{title:infoWindowTitle,width:200}); 
		var openInfoWinFun = function(){
			marker.openInfoWindow(infoWindow);
			for(var cnt = 0; cnt < maxLen; cnt++){
				if(!document.getElementById("list" + cnt)){continue;}
				if(cnt == index){
					document.getElementById("list" + cnt).style.backgroundColor = "#f0f0f0";
				}else{
					document.getElementById("list" + cnt).style.backgroundColor = "#fff";
				}
			}
		}
		marker.addEventListener("click", openInfoWinFun);
		return openInfoWinFun;
	}
	// 获取公交路线规划方案
	function transit(start, end, policyIndex) {
		var routePolicy = [BMAP_TRANSIT_POLICY_LEAST_TIME, BMAP_TRANSIT_POLICY_LEAST_TRANSFER, BMAP_TRANSIT_POLICY_LEAST_WALKING, BMAP_TRANSIT_POLICY_AVOID_SUBWAYS];
		var transit = new BMap.TransitRoute(map, {
			onSearchComplete: function(result) {
				if(transit.getStatus() == BMAP_STATUS_SUCCESS) {
					// 从结果对象中获取起点和终点信息
					var start = result.getStart().title;
					var end = result.getEnd().title;
					transitStart = result.getStart().point;
					transitEnd = result.getEnd().point;
					// 获取方案
					var planNum = result.getNumPlans();
					$route.empty();
					for(var i = 0; i < planNum; i++) {
						var plan = result.getPlan(i);
						var planDistance = plan.getDistance(); // 获取方案总距离
						var planDuration = plan.getDuration(); // 获取方案总时间
						
						var line = plan.getLine(0).title.replace(/\(.*\)/, ''); // 获取公交线路（比如331路）的名称
						var routeNum = plan.getNumRoutes();
						var routeStart = plan.getRoute(0).getDistance();          // 从起点到上车车站的距离
						var routeEnd = plan.getRoute(routeNum - 1).getDistance(); // 从下车车站到终点的距离
						
						var html = getRouteHtml(start, routeStart);
						html += getLineHtml(plan.getLine(0));
						for(var j = 1; j < routeNum - 1; j++) {
							line += "→" + plan.getLine(j).title.replace(/\(.*\)/, '');
							html += getRouteHtml(plan.getLine(j).getGetOnStop().title, plan.getRoute(j).getDistance());
							html += getLineHtml(plan.getLine(j));
						}
						html += getRouteHtml(end, routeEnd);
						html = "<ul" + (i == 0 ? " class='current'" : "") + "><li class='title'><h2>" + line + "</h2><span>约" + planDuration + " / " + planDistance + "</span></li><li class='start'>" + start + "</li>" + html + "<li class='end'>" + end + "</li></ul>";
						var $ul = $(html).appendTo($route);
						var $title = $ul.find(".title");
						var dlfunc = drawLine(map, transit, result, i, $ul);
						$title.click(dlfunc);
						if(i == 0) {
							$title.click();
						}
					}
					// 获取打车费用
					var taxiFare = new BMap.DrivingRoute(map, {
						onSearchComplete: function(result) {
							$price.html("打车费用：" + result.taxiFare.day.totalFare + "元 (按驾车最短路程算)");
						}
					});
					taxiFare.search(result.getStart(), result.getEnd());
					$result.show();
				}
			}, policy: routePolicy[policyIndex]
		});
		transit.search(start, end);
	}
	// 获取驾车路线规划方案
	function driving(start, end, policyIndex) {
		var routePolicy = [BMAP_DRIVING_POLICY_LEAST_TIME, BMAP_DRIVING_POLICY_LEAST_DISTANCE, BMAP_DRIVING_POLICY_AVOID_HIGHWAYS];
		var driving = new BMap.DrivingRoute(map, {
			onSearchComplete: function(result) {
				if(driving.getStatus() == BMAP_STATUS_SUCCESS) {
					drivingStart = result.getStart().point;
					drivingEnd = result.getEnd().point;
					$price.html("打车费用：" + result.taxiFare.day.totalFare + "元 (按驾车最短路程算)");
					// 获取第一条方案
					var plan = result.getPlan(0);
					// 获取方案的驾车线路
					var route = plan.getRoute(0);
					// 获取每个关键步骤,并输出到页面
					$route.empty();
					var html = "";
					for(var i = 0; i < route.getNumSteps(); i++) {
						var step = route.getStep(i);
						html += "<li>" + step.getDescription() + "</li>";
					}
					$("#route").html("<ol>" + html + "</ol>");
					drawLine2(map, driving, result);
					$result.show();
				}
			}, policy: routePolicy[policyIndex]
		});
		driving.search(start, end);
	}
	// 返回乘坐路线HTML
	function getLineHtml(line) {
		if(parseInt(line.getDistance(false)) > 0) {
			return "<li class='line clearfix'><p>乘坐<a title='' href='javascript:;'>" + line.title.replace(/\(.*\)/, '') + "</a>" + (line.type == BMAP_LINE_TYPE_BUS ? "公交车" : "") + ",在<a title='' href='javascript:;'>" + line.getGetOffStop().title + "</a>下车</p><a title='' href='javascript:;' class='distance'>" + line.getDistance() + "</a></li>";
		}
		return "";
	}
	// 返回步行路线HTML
	function getRouteHtml(target, distance) {
		if(parseInt(distance) > 0) {
			return "<li class='route clearfix'><p>步行至<a title='' href='javascript:;'>" + target + "</a></p><a title='' href='javascript:;' class='distance'>" + distance + "</a></li>";
		}
		return "";
	}
	var lastSetBackObj = null;
	// 绘制路线
	function drawLine(map, obj, results, index, control) {
		return function() {
			var planObj = results.getPlan(index);
			var bounds = new Array();
			var addMarkerFun = function(point, imgType, index, title) {
				var url, width, height, myIcon;
				// imgType:1的场合，为起点和终点的图；2的场合为过程的图形
				if(imgType == 1) {
					url = root + "theme/simple/images/map-markers.png";
					width = 42;
					height = 34;
					myIcon = new BMap.Icon(url, new BMap.Size(width, height), { imageOffset: new BMap.Size(0, 0 - index * height)});
				} else {
					url = root + "theme/simple/images/map-icons.png";
					width = 22;
					height = 25;
					var d = 25;
					var cha = 0;
					if(index == 2) {
						d = 21;
						cha = 5;
					}
					myIcon = new BMap.Icon(url, new BMap.Size(width, d), { imageOffset: new BMap.Size(0, 0 - index * height - cha)});
				}
				var marker = new BMap.Marker(point, { icon: myIcon });
				if(title != null && title != "") {
					marker.setTitle(title);
				}
				// 起点和终点放在最上面
				if(imgType == 1) {
					marker.setTop(true);
				}
				map.addOverlay(marker);
				return marker;
			}
			var addPoints = function(points) {
				for(var i = 0; i < points.length; i++) {
					bounds.push(points[i]);
				}
			}
			// 清空覆盖物
			map.clearOverlays();
			// 绘制驾车步行线路
			for(var i = 0; i < planObj.getNumRoutes(); i++) {
				var route = planObj.getRoute(i);
				if(route.getDistance(false) > 0) {
					// 步行线路有可能为0
					map.addOverlay(new BMap.Polyline(route.getPath(), { strokeStyle: "dashed", strokeColor: "#78b71b", strokeOpacity: 1, strokeWeight: 4,enableMassClear: true }));
				}
			}
			// 绘制公交线路
			for(i = 0; i < planObj.getNumLines(); i++) {
				var line = planObj.getLine(i);
				addPoints(line.getPath());
				// 公交
				if(line.type == BMAP_LINE_TYPE_BUS) {
					// 上车
					addMarkerFun(line.getGetOnStop().point, 2, 2, line.getGetOnStop().title);
					// 下车
					addMarkerFun(line.getGetOffStop().point, 2, 2, line.getGetOffStop().title);
				// 地铁
				} else if(line.type == BMAP_LINE_TYPE_SUBWAY) {
					// 上车
					addMarkerFun(line.getGetOnStop().point, 2, 3, line.getGetOnStop().title);
					// 下车
					addMarkerFun(line.getGetOffStop().point, 2, 3, line.getGetOffStop().title);
				}
				map.addOverlay(new BMap.Polyline(line.getPath(), { strokeColor: "#4774d7", strokeOpacity: 1, strokeWeight: 6, enableMassClear: true }));
				map.addOverlay(new BMap.Polyline(line.getPath(), { strokeColor: "#7899e3", strokeOpacity: 1, strokeWeight: 4, enableMassClear: true }));
			}
			map.setViewport(bounds);
			// 终点
			var end = addMarkerFun(results.getEnd().point, 1, 1);
			// 开始点
			var start = addMarkerFun(results.getStart().point, 1, 0);
			start.enableDragging(); // 开启起点拖拽功能
			end.enableDragging();   // 开启终点拖拽功能
			start.addEventListener("dragend", function(e) {
				map.clearOverlays();
				obj.search(e.point, end.getPosition());
			});
			end.addEventListener("dragend", function(e) {
				map.clearOverlays();
				obj.search(start.getPosition(), e.point);
			});
			// 设置样式
			if(control != null) {
				if(lastSetBackObj != null) {
					lastSetBackObj.removeClass("current");
				}
				lastSetBackObj = control.addClass("current");
			}
		}
	}
	function drawLine2(map, obj, results) {
		var plan = results.getPlan(0);
		var bounds = new Array();
		var addMarkerFun = function(point, imgType, index, title) {
			var url, width, height, myIcon;
			// imgType:1的场合，为起点和终点的图；2的场合为过程的图形
			if(imgType == 1) {
				url = root + "theme/simple/images/map-markers.png";
				width = 42;
				height = 34;
				myIcon = new BMap.Icon(url, new BMap.Size(width, height), { imageOffset: new BMap.Size(0, 0 - index * height)});
			} else {
				url = root + "theme/simple/images/map-icons.png";
				width = 22;
				height = 25;
				var d = 25;
				var cha = 0;
				if(index == 2) {
					d = 21;
					cha = 5;
				}
				myIcon = new BMap.Icon(url, new BMap.Size(width, d), { imageOffset: new BMap.Size(0, 0 - index * height - cha)});
			}
			var marker = new BMap.Marker(point, { icon: myIcon });
			if(title != null && title != "") {
				marker.setTitle(title);
			}
			// 起点和终点放在最上面
			if(imgType == 1) {
				marker.setTop(true);
			}
			map.addOverlay(marker);
			return marker;
		}
		var addPoints = function(points) {
			for(var i = 0; i < points.length; i++) {
				bounds.push(points[i]);
			}
		}
		// 清空覆盖物
		map.clearOverlays();
		// 绘制驾车步行线路
		for(var i = 0; i < plan.getNumRoutes(); i++) {
			var route = plan.getRoute(i);
			addPoints(route.getPath());
			map.addOverlay(new BMap.Polyline(route.getPath(), { strokeColor: "#4774d7", strokeOpacity: 1, strokeWeight: 6, enableMassClear: true }));
			map.addOverlay(new BMap.Polyline(route.getPath(), { strokeColor: "#7899e3", strokeOpacity: 1, strokeWeight: 4, enableMassClear: true }));
		}
		map.setViewport(bounds);
		// 终点
		var end = addMarkerFun(results.getEnd().point, 1, 1);
		// 开始点
		var start = addMarkerFun(results.getStart().point, 1, 0);
		start.enableDragging(); // 开启起点拖拽功能
		end.enableDragging();   // 开启终点拖拽功能
		start.addEventListener("dragend", function(e) {
			map.clearOverlays();
			obj.search(e.point, end.getPosition());
		});
		end.addEventListener("dragend", function(e) {
			map.clearOverlays();
			obj.search(start.getPosition(), e.point);
		});
	}
});