var map = null;
var geocoder = null;
var pre_url = null;
var locale = null;
var index = 1;// 地图放大倍数
var sideBar;
var back_url = location.href;
var q_city_id = "";// 用于精确查询的信息，为Back服务
var q_section_code = "";
var q_key = "";// 用于关键字查询的信息，
var bounds = null;
function initialize() {
	pre_url = document.getElementById("pre_url").value;	
	locale = document.getElementById("language_code").value;
	getCenter(locale);
	geocoder = new GClientGeocoder();
	// alert(pre_url+locale);
	map = new GMap2(document.getElementById("map"));
	// map.addControl(new GOverviewMapControl());
	if (locale != "china") {
		map.addControl(new GLargeMapControl());
	}
	map.enableContinuousZoom();
	// map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(0, 0), 1);
	bounds = new GLatLngBounds();
	// GLog.writeHtml("<b>open</b>");
}

function tinyIcon() {
	var icon = new GIcon();
	// url = pre_url.replace(/index.php\/[a-zA-Z]*/, "")
	// + "extension/michelin/design/michelin/images/gmap/";
	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;
}

/**
 * create the markers For some reasons "points" should be an array
 */
function populateMap(points, opt_options) {
	var opts = opt_options || {};
	for (var i = 0; i < points.length; i++) {
		// var label = "Title:" + i;
		points[i].marker = new GMarker(points[i], {
				// title : label,
				// icon : tinyIcon()
				});
		map.addOverlay(points[i].marker);
		bounds.extend(points[i]);
		// map.getBounds().extend(points[i]);
		createInfoWindow(points[i]);
		addToSideBar(points[i], opts);
		// map.setCenter(points[i], 12);
		// map.setZoom(map.getBoundsZoomLevel(bounds));
		// map.setCenter(bounds.getCenter());

	}
}

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 getDetail(point) {
	if (/\?/.test(back_url)) {
		url = back_url.replace(/#/g, "");
	} else {
		url = back_url + "?" + q_city_id + "&" + q_section_code + "&"
				+ escape(q_key);
	}
	// 如果地址不能定位到Google Map
	if (arguments[1]) {
		$.post("/dealer/gmap/" + point.dealerId, {
			'url' : url
		}, function(d) {
			$(".dealercon").replaceWith(d);
			$("#results").remove();
			$(".dsscon").remove();
			initialize();
			$.post("/dealer/info/byid", {
				"id" : point.dealerId
			}, function(da) {
				center(locale, index);
					// de = eval(da);
					// p = new GLatLng(de[0].lat, de[0].lng);
					// marker = new GMarker(p, {
					// // icon : tinyIcon()
					// });
					// map.setCenter(p, 15);
					// map.addOverlay(marker);
				})
		});
	} else {
		$.post("/dealer/gmap/" + point.info.dealerId, {
			'url' : url
		}, function(d) {
			$(".dealercon").replaceWith(d);
			$("#results").remove();
			$(".dsscon").remove();
			initialize();
			$.post("/dealer/info/byid", {
				"id" : point.info.dealerId
			}, function(da) {
				de = eval(da);
				p = new GLatLng(de[0].lat, de[0].lng);
				marker = new GMarker(p, {
						// icon : tinyIcon()
						});
				map.setCenter(p, 12);
				map.addOverlay(marker);
			})
		});
	}

}
/**
 * create infowindow
 */
function createInfoWindow(point) {
	var iwNode = createElem("info-window");
	iwNode.appendChild(createElem("f_zj", point.info.dealerNameChn));
	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));
	a = iwNode.appendChild(createElem("f_zj2", view + "&nbsp;&nbsp;<img src='"
			+ arrow_img + "' align='absmiddle'>", "a"));
	// a.href = pre_url + "/dealer/gmap/" + point.info.dealerId;
	a.href = detail_url+"/(id)/"+point.info.dealerId;
	a.href = 'http://'+location.host+'/dealers/'+point.info.provincePin+'/'+point.info.cityPin+'/'+point.info.sectionPin+'/'+point.info.dealerCd+'.html';
	a.onclick = function() {
		getDetail(point);
	}
	point.marker.bindInfoWindow(iwNode, {
		maxWidth : 200
	});
}
// 添加到列表
function addToSideBar(point, opt_options) {
	var opts = opt_options || {};
	var dt = createElem("sidebar_dealer", "", "dt");
	var a = createElem("f_zj", point.info.dealerNameChn, "a");
	// a.href = pre_url + "/dealer/gmap/" + point.info.id;
	if (point.info.tyreplus.toLowerCase() == "y") {
		dt.appendChild(createElem("s_cell", "<a href='http://www.tyreplus.com.cn' target='_blank'><img src='" + tyreplus_img
				+ "' align='absmiddle'></a>&nbsp;", "span"));
	}
	if (point.info.snx.toLowerCase() == "y") {
		var t_img = $("img", dt).get(0);
		if (t_img != undefined) {
			$(t_img).parent().after("&nbsp;<a href='http://suinixing.michelin.com.cn' target='_blank'><img src='" + suinixing_img
					+ "' align='absmiddle'/></a>");
		} else {
			dt.appendChild(createElem("s_cell", "<a href='http://suinixing.michelin.com.cn' target='_blank'><img src='" + suinixing_img
					+ "' align='absmiddle'/></a>", "span"));
		}
	}
	dt.appendChild(a);
	var dd = createElem("sidebar_dealer_dd", "", "dd");
	var link = createElem("f_zj3", view + "&nbsp;&nbsp;<img src='" + arrow_img
			+ "' align='absmiddle'>", "a");
	// link.href = pre_url + "/dealer/gmap/" + point.info.dealerId;
	link.href = detail_url+"/(id)/"+point.info.dealerCd;

	link.href = 'http://'+location.host+'/dealers/'+point.info.provincePin+'/'+point.info.cityPin+'/'+point.info.sectionPin+'/'+point.info.dealerCd+'.html';
	/*link.onclick = function() {
		getDetail(point);
	}*/
	dd.appendChild(link);
	dd.appendChild(document.createTextNode(point.info.address));
	sideBar.append(dt);
	sideBar.append(dd);
	// alert(dt.innerHTML);
	a.onclick = function() {
		GEvent.trigger(point.marker, 'click');
		return false
	};// x-browser
	a.onfocus = function() {
		GEvent.trigger(point.marker, 'click');
		return false
	};
	GEvent.addListener(point.marker, 'click', function() {
		a.focus();
		return false
	});
	return point;
}

function disableAll() {
	$("#city").attr("disabled", true);
	$("#section").attr("disabled", true);
	$("input[name='MapSearchButton']").attr("disabled", true);
	$("#keySearch").attr("disabled", true);
}
window.onload = function() {
	sideBar = $("#results");
	disableAll();
	initialize();
	map.addControl(new GLargeMapControl());
	// map.addControl(new ExtLargeMapControl());
	fixSelect();

	
	$("#key").keyup(function() {
		if ($(this).val() != null && $.trim($(this).val()) != "") {
			$("#keySearch").attr("disabled", false);
		} else {
			$("#keySearch").attr("disabled", true);
		}
	}).blur(function() {
		if ($.trim($(this).val()) == "") {
			$(this).val(keysearch);
		}
		if ($(this).val() != null && $.trim($(this).val()) != ""
				&& $.trim($(this).val()) != keysearch) {
			$("#keySearch").attr("disabled", false);
		} else {
			$("#keySearch").attr("disabled", true);
		}
	}).focus(function() {
		if ($.trim($(this).val()) == keysearch) {
			$(this).val("");
		}
	});
	search();
	var v = $.History.getHash();
	
	if (v == "") {
		center(locale, index);
	}else{
		var p = wiz.util.unSerialize(v);
	
//		console.info(typeof p.key);
		if (p.key != undefined) {
			d_url = "/dealer/info/keysearch";
		} else {
			d_url = "/dealer/info/dealers";
		}
		$("#results").show();
//		console.info(d_url);
		$.post(d_url, p, function(d) {
				dealers = eval(d);
				disposal(dealers);
			});
		
		/*var zipcode = request.query("zipcode");
		if (zipcode != null) {
			if ($.trim(zipcode) == "") {
				center(locale, index);
				return;
			}
			$.post("/dealer/info/zipcode", {
				"zipcode" : zipcode
			}, function(d) {
				dealers = eval(d);
				disposal(dealers);
			});
			return;
		}

		var query = s.substr(1).split("&");// ?[city_id]&[section_code]&[keyval]
		if (!query[2]) {
			if (isNaN(query[0]) || isNaN(query[1])) {
				center(locale, index);
				return;
			}
			q_data = {};
			if (query[1] != -1 && query[1] != "") {
				q_data = {
					"section_code" : query[1]
				};
			} else {
				q_data = {
					"city_id" : query[0]
				};
			}
			// $("#keyInput").hide();
			$("#results").show();
			$.post("/dealer/info/dealers", q_data, function(d) {
				dealers = eval(d);
				disposal(dealers);
			})
		} else {
			// $("#keyInput").hide();
			$("#results").show();
			$.post("/dealer/info/keysearch", {
				"key" : unescape(query[2])
			}, function(d) {
				dealers = eval(d);
				disposal(dealers);
			});
		}*/
	}
};

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 fixSelect() {
	var sel_option = "<option value='-1'>--" + selecttext + "--</option>";
	$.post("/dealer/info/province", function(d) {
		p = eval(d);
		for (i = 0; i < p.length; i++) {
			$("#province")[0].options.add(new Option(p[i].provinceName,
					p[i].provinceId));
		}
	});
	$("#province").change(function() {
		index = $(this).val();
		$("#section").empty();
		$("#section").attr("disabled", true);
		$("input[name='MapSearchButton']").attr("disabled", true);
		$("#section").append(sel_option);
		if (index == -1) {
			$("#city").empty();
			$("#city").attr("disabled", true);
			$("#city").append(sel_option);
		} else {
			$("#city").empty();
			$("#city").attr("disabled", false);
			$.post("/dealer/info/provincePin", {
				"province_id" : $("#province").val()
			}, function(d) {
					$('#provincePin').val(d);
			});
			$.post("/dealer/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].cityId));
				}
			})
		}
	});

	$("#city").change(function() {
		$("#city option").each(function() {
			if ($(this).attr("selected")) {
				index = $(this).val();
				if (index == -1) {
					$("#section").empty();
					$("#section").attr("disabled", true);
					$("input[name='MapSearchButton']").attr("disabled", true);
					$("#section").append(sel_option);
				} else {
					$.post("/dealer/info/cityPin", {
						"city_id" : $("#city").val()
					}, function(d) {
							$('#cityPin').val(d);
					});
					$.post("/dealer/info/section", {
						"city_id" : $("#city").val()
					}, function(d) {
						sections = eval(d);
						if (sections == "" || sections == null) {
							// $("#section_label").hide();
							$("#section").empty();
							$("#section").attr("disabled", true);
							$("#section").append(sel_option);
							$("input[name='MapSearchButton']").attr("disabled",
									false);
							return;
						}
						// $("#section").show();
						$("#section").empty();
						$("#section").attr("disabled", false);
						$("#city").attr("disabled", false);
						$("input[name='MapSearchButton']").attr("disabled",
								false);
						$("#section").append(sel_option);
						for (i = 0; i < sections.length; i++) {
							$("#section")[0].options.add(new Option(
									sections[i].sectionName,
									sections[i].sectionCd));
						}
					})
				}
			}
		});
	});

	$('#section').change(function() {
		$.post("/dealer/info/sectionPin", {
						"section_id" : $("#section").val()
				}, function(d) {
					$('#sectionPin').val(d);
				});
	});
}
function disposal(dealers) {
	// alert(dealers.length);
	$("#results").addClass("ddlcon");
	if (dealers.length == 0) {
		// $("#results").show();
		// $("#results").append(createElem("", "<span>Not find.</span>", "dt"));
		$("#results").hide();
		alert(info);
		return;
	}

	$("#results").slideDown();
	if (dealers.length < 4) {
		// alert("length<4");
		$("#results").removeClass("ddlcon").addClass("dlt4");
	}
	for (var i = 0; i < dealers.length; i++) {
		if (dealers[i].lat == null || dealers[i].lng == null
				|| dealers[i].lng == "" || dealers[i].lat == "") {
			// alert("LatLng:" + dealers[i].lat + "," + dealers[i].lng);
			getCoordinate(dealers[i]);
		} else {
			// alert("selse");
			p = new GLatLng(dealers[i].lat, dealers[i].lng);
			p.info = dealers[i];
			populateMap([p]);
		}
	}
	// bounds = new GLatLngBounds();
	if (dealers.length == 1) {
		map.setZoom(11);
	} else {
		map.setZoom(map.getBoundsZoomLevel(bounds));
	}

	map.setCenter(bounds.getCenter());
	// alert("setZoom");
}
function search() {
	$("input[name='MapSearchButton']").click(function() {
	
		bounds = new GLatLngBounds();// 初始化Bounds区域
		back_url = location.href.replace(/#+|\?.*/g, "");
	
		q_key = "";// 清空关键字查询的值，以防传输返回URL时带入值引起错误。
		section_code = $("#section").val();
		// $("#keyInput").hide();
		// $("#results").show();
		map.clearOverlays();
		sideBar.find("*").remove();
		if (section_code != undefined && section_code != -1) {
			data = {
				"section_code" : section_code
			};
			q_section_code = section_code;
		} else {
			city_id = $("#city").val();
			data = {
				"city_id" : city_id
			};
			q_city_id = city_id;
		}
		$.History.setHash(wiz.util.serialize(data));
		
		var glabel=$("#province option:selected").text()+"/"+$("#city option:selected").text();
		if($("#section").val()!=-1){
			glabel+="/"+$("#section option:selected").text();
		}
		
		pageTracker._trackEvent("Dealer locator", "Search by location",glabel);
		
//		console.dir(pageTracker);
//		console.info(wiz.util.serialize(data));
if($("#seasonDealer").attr("checked")){
	   data.season="winter"; 	    
		}
		$.post("/dealer/info/dealers", data, function(d) {
			dealers = eval(d);
			// alert("L:"+dealers.length);
			disposal(dealers);
		})
	});
	$("#keySearch").click(function() {
		bounds = new GLatLngBounds();// 初始化Bounds区域
		back_url = location.href.replace(/#+|\?.*/g, "");
		// $("#keyInput").hide();
		// $("#results").show();
		map.clearOverlays();
		sideBar.find("*").remove();
		keyval = $("#key").val();
		q_key = keyval;
		data = {
			"key" : keyval
		};
		$.History.setHash(wiz.util.serialize(data));
		var glabel=$("#key").val();
		if($("#seasonDealerKeyword").attr("checked")){
	   data.season="winter"; 	    
		}
		pageTracker._trackEvent("Dealer locator", "Search by keywords",glabel);
		$.post("/dealer/info/keysearch", data, function(d) {
			dealers = eval(d);
			disposal(dealers);
		});
	})
}

function getCoordinate(dealer) {
	if (geocoder) {
		geocoder.getLocations(dealer.mapAddress, function(d) {
			if (d.Status.code == 200) {
				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]);
				// 处理结果，得出较为精确值。UNDO
				// for (var i = 0; i < d.Placemark.length; i++) {
				// alert("L:"+d.Placemark.length);
				// var point = d.Placemark[i].Point;
				// lng = point.coordinates[0];
				// lat = point.coordinates[1];
				// var dpoint = new GLatLng(lat, lng);
				// dpoint.info = dealer;
				// populateMap([dpoint]);
				// }
				// 保存获取的经纬度
				map.setZoom(map.getBoundsZoomLevel(bounds));
				map.setCenter(bounds.getCenter());
				$.post("/dealer/info/update", {
					"lat" : lat,
					"lng" : lng,
					"dealer_id" : dealer.dealerId
				}, function(d) {
					// if (isNaN(d))
					// alert("Internal Error:\n" + d);
				})
			} else {
				// alert("Can't find.")
				noMapAddToBar(dealer);
			}
		})
	}
}
function noMapAddToBar(dealer) {
	var dt = createElem("sidebar_dealer", "", "dt");
	var a = createElem("f_zj", dealer.dealerNameChn, "a");
	// a.href = pre_url + "/dealer/gmap/" + dealer.id;
	if (dealer.tyreplus.toLowerCase() == "y") {
		dt.appendChild(createElem("s_cell", "<img src='" + tyreplus_img
				+ "' align='absmiddle'>&nbsp;", "span"));
	}
	if (dealer.snx.toLowerCase() == "y") {
		var t_img = $("img", dt).get(0);
		if (t_img != undefined) {
			$(t_img).after("<img src='" + suinixing_img
					+ "' align='absmiddle'/>");
		} else {
			dt.appendChild(createElem("s_cell", "<img src='" + suinixing_img
					+ "' align='absmiddle'/>", "span"));
		}
	}
	dt.appendChild(a);
	var dd = createElem("sidebar_dealer_dd", "", "dd");
	var link = createElem("f_zj3", view + "&nbsp;&nbsp;<img src='" + arrow_img
			+ "' align='absmiddle'>", "a");
	// link.href = pre_url + "/dealer/gmap/" + dealer.dealerId;
	//alert(point.info.provincePin);
	//link.href = detail_url+"/(id)/"+dealer.dealerId;
	
	link.href = 'http://'+location.host+'/dealers/'+dealer.provincePin+'/'+dealer.cityPin+'/'+dealer.sectionPin+'/'+dealer.dealerCd+'.html';
	
	/*link.onclick = function() {
		getDetail(dealer, 1);
	}
	a.onclick = function() {
		getDetail(dealer, 1);
	}*/
	dd.appendChild(link);
	dd.appendChild(document.createTextNode(dealer.address));
	sideBar.append(dt);
	sideBar.append(dd);
}
function center(address, i) {
	if (geocoder) {
		geocoder.getLatLng(address, function(point) {
			if (!point) {
				// alert("Can't find.");
			} else {
				map.setCenter(point, i);
				// alert(point.toString());
				// $("#key").val(point.toString());
			}
		})
	}
}

function setcookie(name, value, expires, path, domain, secure)
{
// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) 
		+( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
	/*
	* This will retrieve the cookie by name, if the cookie does not exist, it will return false, so you can do things like
	* if ( Get_Cookie( 'your_cookie' ) ) do something.
	*/
function getcookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length ))){ 
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}
function getCenter(l) {
	switch (l) {
		case "chi_TW" :
			locale = "Taiwan";
			index = 7;
			break;
		case "jpn" :
			locale = "Japan";
			index = 5;
			break;
		case "tha_TH" :
			locale = "Thailand";
			index = 6;
			break;
		case "eng" :
			locale = "Australia";
			index = 4;
			break;
		case "hin_IN" :
			locale = "India";
			index = 5;
			break;
		case "kor" :
			locale = "Korea";
			index = 6;
			break;
		case "eng_MY" :
			locale = "Malaysia";
			index = 7;
			break;
		case "eng_PH" :
			locale = "Philippines";
			index = 5;
			break;
		case "eng_SG" :
			locale = "Singapore";
			index = 7;
			break;
		case "eng_ID" :
			locale = "Indonesia";
			index = 4;
			break;
		case "vie_VN" :
			locale = "Vietnam";
			index = 4;
			break;
		case "chi" :
		default :
			locale = "china";
			index = 4;
			break;
	}
}

var wiz = {};
wiz.util = {};
wiz.util.query = function(v) {
	var p = new RegExp(v + "=([^?&]*)", "ig");
	var u = location.search;
	return u.match(p) ? u.match(p)[0].substr(v.length + 1) : null;
};

wiz.util.serialize = function(a) {
	var s = [];
	if (a.constructor == Array) {
		for (var i = 0; i < a.length; i++) {
			s.push(a[i].name + '=' + encodeURIComponent(a[i].value));
		}
	} else {
		for (var j in a) {
			s.push(j + '=' + encodeURIComponent(a[j]));
		}
	}
	return s.join('&');
}

wiz.util.unSerialize = function(s, opt_type) {
	var tmp = s.split("&"), result = {};
	for (var i = 0; i < tmp.length; i++) {
		var index = tmp[i].indexOf("=");
		var k = tmp[i].substr(0, index);
		var v = tmp[i].substr(index + 1);
		result[k] = decodeURIComponent(v);
	}
	return result;
}
