var map = null;
var geocoder = null;
var back_url = location.href.replace(/#+|\?.*/g, "");
var sel_option = "<option value='-1'>--请选择--</option>";
var back="";
function initialize() {
	geocoder = new GClientGeocoder();
	map = new GMap2(document.getElementById("map"));
	map.enableContinuousZoom();
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(35.86166, 104.195397), 3);
	bounds = new GLatLngBounds();
}

window.onload = function() {
	$("#a_city").attr("disabled", true);
	$("#city").attr("disabled", true);
	$("#r_province").attr("disabled", true);
	$("#r_city").attr("disabled", true);
	$("#a_search").attr("disabled", true);
	$("#search").attr("disabled", true);
	$("#r_search").attr("disabled", true);
	initialize();
	if(request.query("pid")==null){
		fixSelect();
	}
	$("#a_search").click(function() {
		// alert("area");
		search("area");
	});
	$("#search").click(function() {
		// alert("map");
		search("map");
	});
	$("#r_search").click(function() {
		// alert("road");
		search("road");
	});

	// for back
	if (location.search) {
		var type = request.query("t");
		var id = request.query("id");
		var se = request.query("s");
		se=unescape(se);
//		alert(se);
		if (isNaN(id))
			return;
		if (type != null && id != null) {
			switch (type) {
				case "map" :
					disposalMap(id, se);
					break;
				case "area" :
					disposalArea(id, se);
					break;
				case "road" :
					disposalRoad(id, se);
					break;
				case "flash" :
					disposalArea(id);
					pid = request.query("pid");
					$.post("/dealers/info/province", function(d) {
						p = eval(d);
						for (i = 0; i < p.length; i++) {
							o=new Option(p[i].provinceName,p[i].provinceId);
							if(p[i].provinceId==pid)
								o.selected=true;
							$("#a_province")[0].options.add(o);
						}
					});
					$.post("/dealers/info/city", {
						"province_id" : pid
					}, function(d) {
						citys = eval(d);
						for (i = 0; i < citys.length; i++) {
							co=new Option(citys[i].cityName,citys[i].cityCd);
							if(citys[i].cityCd==id)co.selected=true;
							$("#a_city")[0].options.add(co);
						}
					})
					areaProvinceChange();
					$("#a_city").attr("disabled", false);
					$("#a_search").attr("disabled", false);
					break;
			}
		}
	}

}
/*
 * 获取URL参数
 * http://www.example.com/?id=1
 * request.query("id");
 */
var request = {
	query : function(val) {
		var p = new RegExp(val + "=([^?&]*)", "ig");
		var uri = location.search;
		return uri.match(p) ? uri.match(p)[0].substr(val.length + 1) : null;
	}
}
function getService() {

	var checkbox = $("ul input:checked");
	var result = "%";
	for (var i = 0; i < checkbox.length; i++) {
		result = result + checkbox[i].value + "%";
	}
//		alert(result);
	return result;
}
function serviceInfo() {
	// $.post("/dealers/info/service", function(d) {
	// s = eval(d);
	// names = name.split(",");
	// var result = [];
	// for (var i = 0; i < names.length; i++) {
	// for (var j = 0; j < s.length; j++) {
	// if (names[i] == s[j].serviceName)
	// result[i] = s[j];
	// }
	// }
	// $(".dealerShopTxt").append("<div id='service_tip'><img src='"
	// + pre_url + result[0].icon + "'/></div>");
	// })
	// var i = 0;
	$("a[name^='sinfo']").hover(function() {
		// if(flag==true)return;
		// window.event.cancelBubble = true;
		if ($("#service_tip").html() == null || $("#service_tip").html() == "") {
			name = $(this).siblings("input").val();
			// alert(name);
			if (name == "")
				return;
			input = $(this).siblings("input");
			$.post("/dealers/serviceinfo", {
				"name" : name
			}, function(d) {
				if (d != "") {
					input.after(d);

					// alert(img.val());
					// alert($(this).siblings("input").val())
				}
			})
		}
			// flag = true;
	}, function() {
		$(this).siblings("div").remove();
	})
	// setInterval(function(){$(this).siblings("div").remove();},3000);

	// $("a[name^='sinfo']").mouseout(function() {
	// $("#service_tip").remove();
	// })
	// names=name.split(",");
	// for (var i = 0; i < names.length; i++) {
	// alert(names[i]);
	// }
	// $(".dealerShopTxt").append("<div id='service_tip'>fun</div>");
	// }
}

function disposalArea(cid) {
	// alert("cid:" + cid);
	var service="";
//	alert("A:"+arguments[1]);
	if (arguments[1]) {
		service = arguments[1];
	} else {
		service = getService();
	}
//		alert(service);
	$.post("/dealers/list/area", {
		"city_code" : cid,
		"service" : service,
		"back" : escape(back_url + "?t=area&id=" + cid + "&s=" + service)
	}, function(d) {
		// $("#dealermain").removeClass().addClass();
//		$("#navdiv").hide();
		$("#navbar2").hide().addClass("on");
		$("#abackdiv").show();
		// alert(d);
//		$("#desciption").hide();
		$("#dealerShopList").siblings("a").andSelf().remove();
		$("#mapsearch").hide();
		$("#dealermain").append(d);
		// $(".dealerShopTxt").css("background","red");
		serviceInfo();
			// $("#mapsearch").replaceWith(d);
		})
}

function disposalMap(cid) {
	bounds = new GLatLngBounds();// 初始化Bounds区域
	map.clearOverlays();
	var service="";
	if (arguments[1]) {
		service = arguments[1];
	} else {
		service = getService();
//		alert(service);
	}
	back=escape(back_url + "?t=map&id=" + cid + "&s=" + service);
	$.post("/dealers/list/map", {
		"city_code" : cid,
		"service" : service,
		"back" : back
	}, function(d) {
		de = eval("(" + d + ")");
		dealers = de.dealers;
		$("#navdiv").hide();
		$("#backdiv").show();
		$("#dealerAreaSearch").hide();
		$("#mapShopList").remove();
		$("#mapcontent").before(de.html);
		$("#mapcontent").removeClass("mapSelectContent")
				.addClass("mapSelectContent01");
		scroller = new jsScroller(document.getElementById("Scroller-1"), 400,
				200);
		scrollbar = new jsScrollbar(document
				.getElementById("Scrollbar-Container"), scroller, false);
		if (dealers.length) {
			// alert(dealers.length);
			for (var i = 0; i < dealers.length; i++) {
				if (dealers[i].lat == null || dealers[i].lng == null
						|| dealers[i].lng == "" || dealers[i].lat == "") {
					getCoordinate(dealers[i]);
				} else {
					p = new GLatLng(dealers[i].lat, dealers[i].lng);
					p.info = dealers[i];
					populateMap(p,back);
				}
			}
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
		}

			// $(".nameResult li:odd").css("background","red");
			// $(".telResult li:odd").css("background","red");
			// $(".addressResult li:odd").css("background","red");
		})

	// $.post("/dealers/info/dealers", {
	// "city_code" : cid,
	// "service" : getService()
	// }, function(d) {
	// dealers = eval(d);
	// if (dealers.length == 0) {
	// alert("没有满足条件的经销商，请放宽搜索限制。");
	// return;
	// }
	// alert(dealers.length);
	// for (var i = 0; i < dealers.length; i++) {
	// // alert(dealers[i].dealerId);
	// }
	// })
}
function disposalRoad(cid) {
	var service="";
	if (arguments[1]) {
		service = arguments[1];
	} else {
		service = getService().replace(/\%\d*/, "");
	}
//		alert("S:"+service);
	$.post("/dealers/list/area", {
		"city_code" : cid,
		"service" : service,
		"back" : escape(back_url + "?t=road&id=" + cid + "&s=" + service)
	}, function(d) {
		// $("#dealermain").removeClass().addClass();
//		$("#navdiv").hide();
		$("#navbar1").hide().addClass("on");
		$("#abackdiv").show();
//		$("#desciption").hide();
		$("#roadSearchContent").hide();
		$("#dealerShopList").remove();
		$("#mapsearch").hide();
		$("#dealermain").append(d);
//		alert(cid);
		serviceInfo();
			// $("#mapsearch").replaceWith(d);
		})
}
function search(type) {
	switch (type) {
		case 'area' :
			cid = $("#a_city").val();
			disposalArea(cid);
			break;
		case 'map' :
			cid = $("#city").val();
			disposalMap(cid);
			break;
		case 'road' :
			cid = $("#r_city").val();
			disposalRoad(cid);
			break;
	}

}
function populateMap(point,back) {
	point.marker = new GMarker(point, {
			// icon : tinyIcon()
			});
	map.addOverlay(point.marker);
	bounds.extend(point);
	createInfoWindow(point,back);
	// addToSideBar(points[i], opts);
}
function disposalGoogleResult(d, dealer) {
	var point = d.Placemark[0].Point;
	lng = point.coordinates[0];
	lat = point.coordinates[1];
	var dpoint = new GLatLng(lat, lng);
	dpoint.info = dealer;
	populateMap(dpoint,back);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	$.post("/dealers/info/update", {
		"lat" : lat,
		"lng" : lng,
		"dealer_id" : dealer.dealerId
	}, function(d) {
		// if (isNaN(d))
		// alert("Internal Error:\n" + d);
	})
}
function getCoordinate(dealer) {
	if (geocoder) {
		geocoder.getLocations(dealer.mapAddress, function(d) {
			if (d.Status.code == 200) {
				disposalGoogleResult(d, dealer);
			} else {
				geocoder.getLocations(dealer.address, function(d) {
					if (d.Status.code == 200) {
						disposalGoogleResult(d, dealer);
					} else {
						geocoder.getLocations(dealer.dealerNameChn, function(d) {
							if (d.Status.code == 200) {
								disposalGoogleResult(d, dealer);
							}
						})
					}
				})
			}
		})
	}
}
function areaProvinceChange(){
	$("#a_province").change(function() {
		index = $(this).val();
		$("#a_city").empty();
		$("#a_city").attr("disabled", false);
		$("#a_search").attr("disabled", true);
		if (index == -1) {
			$("#a_city").empty();
			$("#a_city").attr("disabled", true);
			$("#a_city").append(sel_option);
		} else {
			$("#a_city").empty();
			$("#a_city").attr("disabled", false);
			$.post("/dealers/info/city", {
				"province_id" : $("#a_province").val()
			}, function(d) {
				citys = eval(d);
				$("#a_city").append(sel_option);
				for (i = 0; i < citys.length; i++) {
					$("#a_city")[0].options.add(new Option(citys[i].cityName,
							citys[i].cityCd));
				}
			})
		}
	});
	$("#a_city").change(function() {
		index = $(this).val();
		if (index == -1) {
			$("#a_search").attr("disabled", true);
		} else {
			$("#a_search").attr("disabled", false);
		}
	});
}
function fixSelect() {
	$.post("/dealers/info/province", function(d) {
		p = eval(d);
		for (i = 0; i < p.length; i++) {
			$("#a_province")[0].options.add(new Option(p[i].provinceName,
					p[i].provinceId));
			$("#province")[0].options.add(new Option(p[i].provinceName,
					p[i].provinceId));
		}
	});
	// 按地区查询连动
	areaProvinceChange();
	

	// 按地图查询连动
	$("#province").change(function() {
		index = $(this).val();
		$("#city").empty();
		$("#city").attr("disabled", false);
		$("#search").attr("disabled", true);
		if (index == -1) {
			$("#city").empty();
			$("#city").attr("disabled", true);
			$("#city").append(sel_option);
		} else {
			$("#city").empty();
			$("#city").attr("disabled", false);
			$.post("/dealers/info/city", {
				"province_id" : $("#province").val()
			}, function(d) {
				citys = eval(d);
				$("#city").append(sel_option);
				for (i = 0; i < citys.length; i++) {
					$("#city")[0].options.add(new Option(citys[i].cityName,
							citys[i].cityCd));
				}
			})
		}
	});
	$("#city").change(function() {
		index = $(this).val();
		if (index == -1) {
			$("#search").attr("disabled", true);
		} else {
			$("#search").attr("disabled", false);
		}
	});
	// 高速路
	$("input[type='radio']").click(function() {
		disableRoadSelect();
		$.post("/dealers/info/roadprovince", {
			"id" : $(this).val()
		}, function(d) {
			// alert(d);
			$("#r_province").attr("disabled", false);
			p = eval(d);
			for (i = 0; i < p.length; i++) {
				$("#r_province")[0].options.add(new Option(p[i], p[i]));
			}
		})
	})
	$("#r_province").change(function() {
		index = $(this).val();
		$("#r_city").empty();
		$("#r_city").attr("disabled", false);
		$("#r_search").attr("disabled", true);
		if (index == -1) {
			$("#r_city").empty();
			$("#r_city").attr("disabled", true);
			$("#r_city").append(sel_option);
		} else {
			$("#r_city").empty();
			$("#r_city").attr("disabled", false);
			$.post("/dealers/info/roadcity", {
				"province" : $("#r_province").val()
			}, function(d) {
				citys = eval(d);
				$("#r_city").append(sel_option);
				for (i = 0; i < citys.length; i++) {
					$("#r_city")[0].options.add(new Option(citys[i].cityName,
							citys[i].cityCd));
				}
			})
		}
	});
	$("#r_city").change(function() {
		index = $(this).val();
		if (index == -1) {
			$("#r_search").attr("disabled", true);
		} else {
			$("#r_search").attr("disabled", false);
		}
	});
}
function disableRoadSelect() {
	$("#r_province").empty();
	$("#r_province").append(sel_option);
	$("#r_city").empty();
	$("#r_city").append(sel_option);
	$("#r_province").attr("disabled", true);
	$("#r_city").attr("disabled", true);
	$("#r_search").attr("disabled", true);
}
// function getDetail(point){
// $.post("dealers/detail/"+point.dealerId,)
// }
function createInfoWindow(point,back) {
	var iwNode = createElem("info-window");
	iwNode.appendChild(createElem("bld", point.info.dealerNameChn, "h5"));
	iwNode.appendChild(createElem("iw-cell", "", "br"));
	iwNode.appendChild(createElem("iw-cell", point.info.address));
	iwNode.appendChild(createElem("iw-cell", "", "br"));
	iwNode.appendChild(createElem("iw-cell", point.info.officePhoneNumber));
	// alert(point.info.rank=2);
	for (var i = 0; i < point.info.rank; i++) {
		img = createElem("", "", "img")
		img.src = level_img;
		img = iwNode.appendChild(img);
	}
	a = iwNode.appendChild(createElem("f_zj2", "<img src='" + arrow_img
			+ "' align='right'>", "a"));
	a.href = "/dealers/detail/" + point.info.dealerId+"?uri=" +back;
	// a.onclick = function() {
	// getDetail(point);
	// }
	point.marker.bindInfoWindow(iwNode, {
		maxWidth : 200
	});
}
function createElem(opt_className, opt_html, opt_tagName) {
	var tag = opt_tagName || "div";
	var elem = document.createElement(tag);
	if (opt_html)
		elem.innerHTML = opt_html;
	if (opt_className)
		elem.className = opt_className;
	return elem;
}
function tinyIcon() {
	var icon = new GIcon();
	url = "extension/michelin/design/michelin/images/gmap/";
	icon.image = url + "icon.png";
	icon.shadow = url + "shadow.png";
	icon.iconSize = new GSize(19, 19);
	icon.shadowSize = new GSize(19, 19);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(10, 1);
	return icon;
}