var map, geocoder, bounds, cache = {};
var $provinces, $citys, $district, $submit, $result, $service;

function createMap() {
	map = new GMap2($("#map")[0]);
	geocoder = new GClientGeocoder();
	mapstate = true;
	var ui = map.getDefaultUI();
	ui.controls.maptypecontrol = false;
	ui.controls.menumaptypecontrol = false;
	
//	map.setMapType(G_SATELLITE_MAP);
//	setTimeout(function(){map.setMapType(G_NORMAL_MAP)},100);
	
	
	// $.getScript("/extension/michelin_tb/design/michelin_tb/javascript/site.js");
	switch (site) {
		case 'tbtw' :
			map.setCenter(new GLatLng(23.7, 121), 7);
			break;
		case 'tbau' :
			map.setCenter(new GLatLng(-25, 134.5), 4);
			break;
		case 'tbid' :
			map.setCenter(new GLatLng(-1.5, 120), 4);
			break;
		case 'tbin' :
			map.setCenter(new GLatLng(21.6, 78.3), 4);
			break;
		case 'tbmy' :
			map.setCenter(new GLatLng(3.8, 102), 4);
			break;
		case 'tbnz' :
			map.setCenter(new GLatLng(-42, 172.8), 4);
			break;
		case 'tbph' :
			map.setCenter(new GLatLng(11.8, 123.5), 5);
			break;
		case 'tbsg' :
			map.setCenter(new GLatLng(1.36, 103.8), 11);
			break;
		case 'tbjp' :
			map.setCenter(new GLatLng(36.4, 137), 4);
			break;
		case 'tbkr' :
			map.setCenter(new GLatLng(36.6, 128), 4);
			break;
		case 'tbth' :
			map.setCenter(new GLatLng(15.8, 101), 5);
			break;
		case 'tbvn' :
			map.setCenter(new GLatLng(14.4, 107.9), 4);
			break;
		case 'TB' :
		default :
			map.setCenter(new GLatLng(-25, 134.5), 4);
			break;
	}
	map.setUI(ui);

	var mgrOptions = {
		borderPadding : 50,
		maxZoom : 15
	};

}

// $.address.change(function(event) {
// var v = $.address.value();
// if (v != "/") {
// var p = wiz.util.unSerialize(v.substr(1));
// $result.hide().empty();
// $.getJSON("/dealers/info/dealers", p, function(ds) {
// disposalResult(ds);
// })
// }
// });

function bindClick(p) {
	if (nomap) {
		p.service = getServices();
	}

	$submit.one('click', function() {
				$.History.setHash("/" + wiz.util.serialize(p));

				$result.hide().empty();
				$.getJSON("/dealers/info/dealers", p, function(ds) {
							disposalResult(ds);
						})
			});
}

function bindAlert(info) {
	$submit.click(function() {
				alert(info);
			});
}

function disposalResult(ds) {
	if (!nomap) {
		map.clearOverlays();
		bounds = new GLatLngBounds();
	}
	var resultHtml = table;
	if (ds.length == 0 || ds == false) {
		resultHtml += '<tr><td align="center" colspan="4">' + notfind
				+ '</td></tr>';
	} else {
		$.each(ds, function(i, d) {
					var cls = "";
					if (i % 2 == 1) {
						cls = "bggray";
					}
					resultHtml += '<tr class="' + cls + '"><td><a class="bu" href="'
							+ detail_url + '/(id)/' + d.dealerId + '">'
							+ d.dealerNameChn + '</a></td><td>'
							+ d.officePhoneNumber1 + '</td><td>' + d.program
							+ '</td><td align="center">'
							+ servicesTable(i, d.service) + '</td></tr>';
					if (!nomap) {
						if (d.lat && d.lng) {
							addToMap(d);
						} else {
							showAddress(d);
						}
					}
				})
	}
	resultHtml += "</table>";
	$result.replaceWith(resultHtml).show();
	$result = $("#result");
	window.scroll(0, 500);
	$('a.tip').hover(function() {
				$(this.rel.substr(this.rel.indexOf("#"))).show();
			}, function() {
				$(this.rel.substr(this.rel.indexOf("#"))).hide();
			})

}

function servicesTable(i, s) {
	if ($.trim(s) == "") {
		return "-";
	}
	s = s.replace(/;$/, "");
	var services = s.split(";"), result = [];

	if (services.length == 0) {
		return "-";
	}

	for (var j = 0; j < Math.ceil(services.length / 3); j++) {
		result[j] = services.slice(3 * j, 3 * j + 3);
	}

	var re = '<span>'
			+ '<a class="tip" href="javascript:void(0)" rel="#service-' + i
			+ '" > ' + services.length + '&nbsp;';
	if (services.length == 1) {
		re += ServiceTxt;
	} else {
		re += ServicesTxt;
	}
	re += ' <img class="servicepic" src='
			+ serviceTipImg
			+ ' align="absmiddle"/></a>'
			+ '<div id="service-'
			+ i
			+ '" class="servicetips" style="display:none;">'
			+ '<table width="480" border="0" cellspacing="0" cellpadding="0" class="m_t10">'

	for (var index = 0; index < result.length; index++) {
		re += '<tr>';
		for (var j = 0; j < result[index].length; j++) {
			re += '<td width="45" align="left">' + '<img src="/'
					+ getServiceIcon(result[index][j]) + '" />'
					+ '</td><td width="115" align="left">' + result[index][j]
					+ '</td>';
		}
		re += "</tr>";
	}
	re += '</table>' + '</div>' + '</span>'

	return re;
}

function getServiceIcon(name) {

	if (!cache[name]) {
		var x = $.ajax({
					type : "get",
					url : '/dealers/info/service',
					data : "name=" + encodeURIComponent(name),
					async : false
				}).responseText;
		x = eval('(' + x + ')');

		try {
			cache[name] = x.icon;
			return cache[name];
		} catch (e) {
			return "";
		}

	} else {
		return cache[name];
	}

}

function showAddress(dealer) {

	if (geocoder) {
		geocoder.getLatLng(dealer.mapAddress, function(point) {
					if (!point) {
						geocoder.getLatLng(dealer.address, function(p) {
									if (p) {
										addToMap(dealer, p);
										updateDealer(dealer.dealerId, p);
									}
								});
					} else {
						addToMap(dealer, point);
						updateDealer(dealer.dealerId, point);
					}
				})
	}
}

function addToMap(dealer, opt_point) {
	if (opt_point) {
		var point = opt_point;
	} else {
		var point = new GLatLng(dealer.lat, dealer.lng);
	}

	var marker = new GMarker(point);
	marker.bindInfoWindow(createInfoWindow(dealer), {
				maxWidth : 200
			});

	map.addOverlay(marker);

	bounds.extend(point);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());

}
function getServices() {
	var serviceList = [];
	$service.each(function(i) {
				if ($(this).attr("checked")) {
					serviceList.push(decodeURIComponent($(this).val()));
				}
			})
	return serviceList.join('|');
}

$(function() {

	$result = $("#result");
	$submit = $("#search");

	switch (level) {
		case 3 :
			$district = $("#district");
		case 2 :
			$citys = $("#city");
		default :
			$provinces = $("#province");
	}

	if (!nomap) {
		createMap();
	} else {
		$service = $("#serviceTable input");

		$service.click(function() {
					disposalServicesCheck();
				});

		var $serviceTable = $("#serviceTable"), $selectall = $("#selectall"), $unselect = $("#unselect"), $servicesCheckbox = $(
				":checkbox", $serviceTable);

		$selectall.click(function() {
					if ($(this).attr("checked") == true) {
						$servicesCheckbox.attr("checked", "checked");
						$unselect.removeAttr("disabled");
					} else {
						$servicesCheckbox.removeAttr("checked");
						$unselect.attr("disabled", "disabled");
					}
					disposalServicesCheck();
				});
		$servicesCheckbox.click(function() {
			$unselect.removeAttr("disabled");
			if ($servicesCheckbox.length == $(":checked", $serviceTable).length) {
				$selectall.attr("checked", "checked");
			} else {
				$selectall.removeAttr("checked");
			}
			if ($(":checked", $serviceTable).length == 0) {
				$unselect.attr("disabled", "disabled");
			}
			disposalServicesCheck();
		});

		$unselect.click(function() {
					$servicesCheckbox.removeAttr("checked");
					$selectall.removeAttr("checked");
					$unselect.removeAttr("checked")
							.attr("disabled", "disabled");
					disposalServicesCheck();
				});

	}

	var v = $.History.getHash();

	if (v != "" && v != "/") {
		var p = wiz.util.unSerialize(v.substr(1));
		$result.hide().empty();
		$.getJSON("/dealers/info/dealers", p, function(ds) {
					disposalResult(ds);
				});
		fixLocation(p);
	} else {
		fixLocation();
		bindAlert(selectProvince);
	}

})

function disposalServicesCheck() {
	var param = null;
	$submit.unbind();
	var did = -1;
	if ($district) {
		did = $district.val();
	}
	var cid = -1;
	if ($citys) {
		cid = $citys.val();
	}
	var pid = $provinces.val();
	if (pid == -1)
		bindAlert(selectProvince);
	if ($citys && cid == -1 && pid != -1)
		bindAlert(selectCity);

	if (did != -1) {
		param = {};
		param.did = did;
		param.cid = cid;
		param.pid = pid;
	} else if (cid != -1) {
		param = {};
		param.cid = cid;
		param.pid = pid;
	} else if (pid != -1 && level == 1) {
		param = {};
		param.pid = pid;
	}
	if (param != null) {
		bindClick(param);
	}

}

function getCitys(pid, opt_selectedid) {
	$.getJSON('/dealers/info/city', {
				pid : pid
			}, function(cs) {
				if (cs.length) {
					var html = "";
					$.each(cs, function(i, c) {
								html += '<option value="' + c.id + '"';
								if (opt_selectedid && opt_selectedid == c.id) {
									html += ' selected="selected"';
								}
								html += '>' + c.name + '</option>';
							});
					$citys.append(html).removeAttr("disabled");
				}
			});
}

function getDistricts(cid, opt_selectedid) {
	$.getJSON('/dealers/info/district', {
				cid : cid
			}, function(ds) {
				if (ds.length) {
					var html = "";
					$.each(ds, function(i, c) {
								html += '<option value="' + c.id + '"';
								if (opt_selectedid && opt_selectedid == c.id) {
									html += ' selected="selected"';
								}
								html += '>' + c.name + '</option>';
							});
					$district.append(html).removeAttr("disabled");
				}
			});
}

function fixLocation(opt_out) {
	$.getJSON('/dealers/info/province', function(dd) {
				var html = "";
				$.each(dd, function(i, p) {
							html += '<option value="' + p.id + '"';
							if (opt_out && opt_out.pid == p.id) {
								html += ' selected="selected"';
							}
							html += '>' + p.name + '</option>';
						});
				$provinces.append(html);
				if ($citys && opt_out && opt_out.pid && opt_out.cid
						&& opt_out.cid != -1) {
					getCitys(opt_out.pid, opt_out.cid);
					if ($district && opt_out && opt_out.did
							&& opt_out.did != -1) {
						getDistricts(opt_out.cid, opt_out.did);
					}
				}
			})

	$provinces.change(function() {
				var pid = $(this).val();
				$submit.unbind();

				if (level == 1) {
					if (pid != -1) {
						bindClick({
									pid : pid
								});
					} else {
						bindAlert(selectProvince);
					}
				}
				if ($citys) {
					$("option:not(:first)", $citys).remove();
					$citys.attr("disabled", "disabled");

					if ($district) {
						$district.attr("disabled", "disabled");
						$("option:not(:first)", $district).remove();
					}

					if (pid != -1) {
						getCitys(pid);
						bindAlert(selectCity);
					} else {
						bindAlert(selectProvince);
					}
				}

			});

	if ($citys) {
		$citys.change(function() {
					var cid = $(this).val();
					var pid = $provinces.val();
					$submit.unbind();

					if (cid != -1) {
						bindClick({
									cid : cid,
									pid : pid
								});

						if ($district) {
							$("option:not(:first)", $district).remove();
							$district.attr("disabled", "disabled");
							getDistricts(cid);
						}
					} else {
						bindAlert(selectCity);
					}
				});
	}

	if ($district) {
		$district.change(function() {
					$submit.unbind();
					var did = $(this).val();
					var cid = $citys.val();
					var pid = $provinces.val();
					if (did != -1) {
						bindClick({
									did : did,
									cid : cid,
									pid : pid
								});
					} else {
						bindClick({
									cid : cid,
									pid : pid
								});
					}
				});
	}

}

function updateDealer(id, p) {
	$.post('/dealers/info/update', {
				id : id,
				lat : p.lat(),
				lng : p.lng()
			});
}

function createInfoWindow(d) {
	var $s = $("<strong>");

	$s.append('<a class="wb" href="' + detail_url + '/(id)/' + d.dealerId
			+ '">' + d.dealerNameChn + "</a>");
	var $div = $("<div>").addClass("textleft").append($s).append("<br />")
			.append(d.address).append("<br />").append(d.officePhoneNumber);
	return $div[0];
}

if (!nomap) {
	window.onunload = function() {
		GUnload();
	}
}

