﻿var INF = 0; //json序列化时生成INF
//var StaticFileServer;//defined in resource.js
var zheku = {};
zheku.utility = {};
zheku.utility.getCookie = function(name) {
	var cookies = document.cookie.split("; ");
	for (var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i].split("=");
		if (name == cookie[0])
			return decodeURIComponent(cookie[1]);
	}
	return "";
};
zheku.utility.setCookie = function(name, value, expired) {
	if (expired == null)
		document.cookie = name + "=" + encodeURIComponent(value);
	else
		document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + expired.toGMTString();
};

zheku.utility.getShortString = function(input, length) {//获取指定长度的字符串
	if (input == null || input.length <= length / 2) {
		return input;
	}
	var count = 0;
	for (var i = 0; i < input.length; i++) {
		count++;
		if (input.charCodeAt(i) > 256) {//unicode
			count++;
		}
		if (count >= length) {
			if (i != input.length - 1) {
				return input.substr(0, i + 1) + "...";
			}
		}
	}

	return input;
};

zheku.utility.getStoreUrl = function(storeId) {
	return "/store/" + storeId + "/";
};

zheku.utility.getCouponUrl = function(couponId) {
	return "/coupon/" + couponId + "/";
};

zheku.utility.log = function(feature, type, detail) {
	if (feature == null && type == null) {
		var url = window.location.href; //#bi_f=top
		if (url.indexOf("#bi_f=") > -1) {
			var featureName = url.substr(url.indexOf("#bi_f=") + 6);
			var imgUrl = "/log.ashx?f=" + encodeURIComponent(featureName) + "&s=" + (document.referrer ? encodeURIComponent(document.referrer) : "") + "&d=" + encodeURIComponent(BI ? BI : "");
			if ($("#bi_fimg").length == 0) {
				var img = document.createElement("IMG");
				document.body.appendChild(img);
				img.id = "bi_fimg";
				img.src = imgUrl;
				img.style.display = "none";
			}
		}
	}
	else if (feature != null || type != null) {
		if (detail == null) {
			detail = BI;
		}
		var imgUrl = "/log.ashx?type=" + (type == null ? "" : type) + "&f=" + (feature == null ? "" : feature) + "&s=" + (document.referrer ? encodeURIComponent(document.referrer) : "") + "&d=" + encodeURIComponent(detail ? detail : "");
		if ($("#bi_cimg").length == 0) {
			var img = document.createElement("IMG");
			document.body.appendChild(img);
			img.id = "bi_cimg";
			img.src = imgUrl;
			img.style.display = "none";
		}
	}
};

zheku.utility.logFeature = function(links, featureName) {
	var idArray = [];
	links.each(function() {
		var url = this.href;
		var reg = /\/(customer|coupon)\/([0-9]+)\//;
		reg.test(url);
		var id = RegExp.$2;
		if (id == null || id == "") {
			return true;
		}
		if (idArray[id] == null) {
			idArray[id] = id;
			var imgUrl = "/log.ashx?f=" + encodeURIComponent(featureName) + "&s=" + (document.referrer ? encodeURIComponent(document.referrer) : "") + "&d=" + encodeURIComponent(id);
			if ($("#bi_fimg" + id).length == 0) {
				var img = document.createElement("IMG");
				document.body.appendChild(img);
				img.id = "bi_fimg" + id;
				img.src = imgUrl;
				img.style.display = "none";
			}
		}
	});
};

zheku.utility.biCheck = function() {//处理url，在detail页面记录log
	var boxes = $("[_bi]");
	boxes.each(function(index) {
		var box = $(this);
		var links;
		if (this.tagName == "A") {
			links = $(this);
		}
		else {
			links = box.find("a");
			if (links.length == 0) {
				return true;
			}
		}
		var feature = box.attr("_bi");
		var regText = box.attr("_bi_rule"), regex;
		if (regText != null && regText != "") {
			regex = new RegExp(regText, "gi");
		}
		links.each(function(index) {
			var link = $(this);
			var url = link.attr("href");
			if (url.indexOf("javascript:") > -1 || url.indexOf("#") > -1) {
				return true;
			}
			if (regex && !regex.test(url)) {
				return true;
			}
			link.attr("href", url + "#bi_f=" + feature);
		});
	});
};

zheku.utility.copyUrl = function() {
	if (window.clipboardData) {
		clipboardData.setData('Text', document.location.href);
		zheku.ui.alert("本页链接已经拷贝到剪贴板中！", "复制成功");
	}
	else {
		zheku.ui.alert("<input type='text' value='" + document.location.href + "' style='width:100%;' id='location_copy' /><br>请拷贝上方文本框里的地址。", "复制本页链接");
		var locationCopy = document.getElementById("location_copy");
		locationCopy.select();
	}
};

zheku.utility.query = function(url, name) {//querystring
	if (url.indexOf("#") > -1) url = url.substr(0, url.indexOf("#"));
	var result = "", lastIndex = -1;
	var reg = new RegExp("(&amp;|&|\\?)" + name + "=([^&]*)", "ig");
	var arr = reg.exec(url);
	if (arr != null)
		return RegExp.$2;

	return null;
};

zheku.utility.formatUrl = function(url, query, value) {//替换url中的query值为value
	if (url.indexOf("#") > -1) url = url.substr(0, url.indexOf("#"));
	var result = "", lastIndex = -1;
	var reg = new RegExp("(&amp;|&|\\?)" + query + "=[^&]*", "ig");
	var arr = reg.exec(url);
	if (arr != null) {
		while (arr != null) {
			if (lastIndex == -1) {
				result = url.substr(0, arr.index);
				result += RegExp.$1 + query + "=" + value;
			}
			else
				result += url.substring(lastIndex, arr.index);
			lastIndex = arr.lastIndex;
			arr = reg.exec(url);
		}
		if (lastIndex < url.length - 1) result += url.substr(lastIndex);
	}
	else {
		if (url.indexOf("?") > -1)
			result = url + "&" + query + "=" + value;
		else
			result = url + "?" + query + "=" + value;
	}
	return result;
};

zheku.utility.attachEvent = function(ctrl, e, handler) {//控件的某一个事件增加handler
	if (ctrl == null) {
		return;
	}
	var id = ctrl.getAttribute("_id");
	if (id == null) {
		id = Math.random().valueOf();
		ctrl.setAttribute("_id", id);
		top.window[id] = [];
	}
	if (top.window[id][e] == null) {
		top.window[id][e] = [];
	}
	if (handler != null) {
		top.window[id][e].push(handler);
	}
	return top.window[id][e];
};

zheku.utility.clearEvent = function(ctrl, e) {
	if (ctrl == null) {
		return;
	}
	var id = ctrl.getAttribute("_id");
	if (id == null) {
		return;
	}
	top.window[id][e] = [];
};

zheku.utility.sign = function(input) {//生成input签名
	if (input == null || input == "") {
		return 0;
	}
	var key = 1, length = input.length;
	for (var i = 0; i < length; i++) {
		key += (key | input.charCodeAt(i) | length);
		if (key > 1073741824) {
			key = key % 1073741824;
		}
	}
	return key;
};

zheku.utility.checkLoginFunc = function(){
    if( !zheku.utility.query( document.location.href,"af" ) ){
        return;
    }
    var loginFunc = zheku.utility.getCookie( "loginFunc" );
    if( loginFunc!=null && loginFunc.length>0 ){
        zheku.utility.setCookie("loginFunc",null,new Date(2009,1,1));//expire cookie
        eval(loginFunc);
    }
};

zheku.ui = {};

zheku.ui.setWatermark = function(textbox, watermark, func) {//文本框默认文字
	textbox.keydown(function(evt) {
		if (evt.keyCode == 13) {
			if (func != null) func();
			return false;
		}
	});
	textbox.focus(function() {
		if (textbox.val() == watermark) {
			textbox.val("");
			textbox.css({ "font-style": "normal", color: "#000" });
		}
	});
	textbox.blur(function() {
		if (textbox.val() == "") {
			textbox.val(watermark);
			textbox.css({ "font-style": "normal", color: "gray", "font-size": "12px" });
		}
	});
	textbox.get(0).ondragenter = new function() { $(this).trigger("focus"); }
	textbox.get(0).ondragleave = new function() { $(this).trigger("blur"); }
	if (textbox.val() == "") {
		textbox.val(watermark);
		textbox.css({ "font-style": "normal", color: "gray", "font-size": "12px" });
	}
};

zheku.ui.slide = function(thumbnails, bigImage, bigLink, data) {//slide ctrl
    var current = 0, interval = 5000, timer = null;
    setFocus = function() {
        if (current < 0) {
            current = 0;
        }
        if (current >= 4) {
            current = 3;
        }
        var imageUrl = data[current].image;
        while (imageUrl.indexOf("&amp;") > -1) {
            imageUrl = imageUrl.replace("&amp;", "&");
        }
        var shortTitle = zheku.utility.getShortString(data[current].text, 30);
        bigImage.attr("href", data[current].url).find("img").attr("src", imageUrl).attr("title", shortTitle);
        bigLink.attr("href", data[current].url).text(shortTitle);
        thumbnails.filter(".thubpiccur").removeClass("thubpiccur").addClass("thubpic");
        thumbnails.eq(current).addClass("thubpiccur");
        current++;
        if (current >= 4) {
            current = 0;
        }
        interval = 5000;
        if (timer) {
            window.clearTimeout(timer);
        }
        timer = window.setTimeout(setFocus, interval);
    };
    thumbnails.each(function(index, domEle) {
        $(domEle).hover(function() {
            current = index;
            setFocus();
            if (timer) {
                window.clearTimeout(timer);
            }
            timer = window.setTimeout(setFocus, interval);
        });
    });
    window.setTimeout(setFocus, interval);
};

zheku.ui.setNavFocus = function(tab) {//set nav tab focus
	var tabs = $("#nav_tab a");
	switch (tab) {
		case "default":
			$(tabs[0]).addClass("select_nav");
			break;
		case "food":
			$(tabs[1]).addClass("select_nav");
			break;
		case "pastime":
			$(tabs[2]).addClass("select_nav");
			break;
		case "life":
			$(tabs[3]).addClass("select_nav");
			break;
		case "campaign":
			$(tabs[4]).addClass("select_nav");
			break;
		case "brand1":
			$(tabs[5]).addClass("select_nav");
			break;
		case "brand2":
			$(tabs[6]).addClass("select_nav");
			break;
	}
};

zheku.ui.setOrderUrl = function(link, url, order, defaultOrder, ascCtrl, defaultAsc, orderKey, ascKey) {//设置排序url，没有ascCtrl时则不考虑正反序
	if (!orderKey) {
		orderKey = "order";
	}
	if (!ascKey) {
		ascKey = "asc";
	}
	var currentOrder = zheku.utility.query(url, orderKey);
	if (currentOrder == null) {
		currentOrder = defaultOrder;
	}
	if (ascCtrl && ascCtrl.length > 0) {//判断正反序
		var currentAsc = zheku.utility.query(url, ascKey);
		if (currentAsc == null) {//默认asc
			currentAsc = defaultAsc ? "1" : "0";
		}

		if (currentOrder == order) {//颠倒
			asc = currentAsc == "0" ? "1" : "0";
		}
		else {
			asc = defaultAsc ? "1" : "0";
		}
		var newUrl = zheku.utility.formatUrl(url, orderKey, order);
		newUrl = zheku.utility.formatUrl(newUrl, ascKey, asc);
		link.attr("href", newUrl);
		ascCtrl.text(asc == "0" ? "↓" : "↑");
	}
	else {
		var newUrl = zheku.utility.formatUrl(url, orderKey, order);
		link.attr("href", newUrl);
	}
};

zheku.ui.dropdown = function(dropdown, changed, maxTitle) {//模拟下拉列表
	var flag = false;
	if (maxTitle == null) {
		maxTitle = 28;
	}
	dropdown.click(function(evt) {
		evt.stopPropagation();
		dropdown.find(".list").toggle();
	});
	dropdown.find(".list iframe").height(dropdown.find(".list").height());
	/*dropdown.hover(function() {//hover时显示下拉列表
	$(this).find(".list").toggle();
	}, function() {
	$(this).find(".list").toggle();
	});*/
	dropdown.find(".list span").hover(function() {
		dropdown.find(".list .hover").removeClass("hover");
		dropdown.find(".list .selected").removeClass("selected");
		$(this).addClass("hover");
	}).click(function() {
		dropdown.find("div.selected").text(zheku.utility.getShortString($(this).text(), maxTitle)).attr("_value", $(this).attr("_value"));
		dropdown.find(".list .selected").removeClass("selected");
		$(this).addClass("selected");
		if (changed) {
			changed($(this));
		}
	});

	$(document.body).click(function(evt) {
		dropdown.find(".list").hide();
	});
	
	var dropdownList = dropdown.find(".list");
    if (dropdownList.height() > 200) {
        dropdownList.css({height:200,overflowY:"scroll",overflowX:"hidden"});
    }
};

zheku.ui.fixPNG = function() {//解决IE6 PNG不透明的问题
	if (navigator.appVersion.indexOf("MSIE") == -1) {
		return;
	}
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	if ((version >= 5.5) && (document.body.filters)) {
		for (var j = 0; j < document.images.length; j++) {
			var img = document.images[j];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText;
				if (img.align == "left") {
					imgStyle = "float:left;" + imgStyle;
				}
				if (img.align == "right") {
					imgStyle = "float:right;" + imgStyle;
				}
				if (img.parentElement.href) {
					imgStyle = "cursor:hand;" + imgStyle;
				}
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
					+ " style=\"width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
					+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
					+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
				img.outerHTML = strNewHTML;
				j = j - 1;
			}
		}
	}
};

zheku.ui.showRatedScore = function(box, itemInfoId, score) {//显示已打过的分数
	return;//不作特殊处理
	var name = itemInfoId;

	while (name.indexOf("-") > -1) {
		name = name.replace("-", "");
	}
	if (!score) {
		score = zheku.utility.getCookie(name);
	}
	if (!isNaN(parseFloat(score))) {
		box.find("a").eq(score - 1).addClass("rated");
		$("#store_rate").attr("disabled", "disabled");
	}
};

zheku.ui.requiredValidator = function(target) {
	if (target == null || target.input == null || target.errCtrl == null) {
		return false;
	}

	//precondition,true go;if false,return ture
	if (target.precondition != null && $.isFunction(target.precondition)) {
		if (!target.precondition()) {
			target.errCtrl.style.display = "none";
			return true;
		}
	}
	
	var val = $.trim(target.input.value);

	if (val == null) {
		val = "";
	}
	if (target.minLength != null && val.length < target.minLength) {//小于指定长度
		target.errCtrl.style.display = "";
		return false;
	}
	else if (target.maxLength != null && val.length > target.maxLength) {//超过指定长度
		target.errCtrl.style.display = "";
		return false;
	}
	else {
		target.errCtrl.style.display = "none";
	}
	return true;
};

zheku.ui.regexValidator = function(target) {
	if (target == null || target.input == null || target.errCtrl == null || target.inputReg == null) {
		return false;
	}

	//precondition,true go;if false,return ture
	if (target.precondition != null && $.isFunction(target.precondition)) {
		if (!target.precondition()) {
			target.errCtrl.style.display = "none";
			return true;
		}
	}
	
	var val = target.input.value;
	if (val == null || val == "") {
		target.errCtrl.style.display = "none";
		return true;
	}
	if (!target.inputReg.test(val)) {
		target.errCtrl.style.display = "";
		return false;
	}
	else {
		target.errCtrl.style.display = "none";
		return true;
	}
};
zheku.ui.validate = function(validators) {
    var result = true;
    if (validators) {
        for (var i = 0; i < validators.length; i++) {
            var o = validators[i];
            if (o == null) {
                continue;
            }
            if (!o()) {
                result = false;
            }
        }
    }
    return result;
};

zheku.ui.required = function(input, errCtrl, minLength, maxLength, precondition) {//项是否符合指定长度，最小长度默认为1，闭区间
	if (input == null) {
		return;
	}
	if (minLength == null) {
		minLength = 1;
	}
	var toValidate = { input: input, errCtrl: errCtrl, minLength: minLength, maxLength: maxLength, precondition: precondition };
	var check = function() {
		return zheku.ui.requiredValidator(toValidate);
	};
	var handlerArray = zheku.utility.attachEvent(input, "blur", check);
	if (input.onblur == null) {
		input.onblur = function() {
			return zheku.ui.validate(handlerArray);
		}
	}
	var clearHandler = zheku.utility.attachEvent(input, "focus", function() {
		errCtrl.style.display = "none";
	});
	if (input.onfocus == null) {
		input.onfocus = function() {
			zheku.ui.validate(clearHandler);
		}
	}
	return check;
};

zheku.ui.regex = function(input, errCtrl, inputReg, precondition) {//使用正则表达式判断输入是否合法
	if (inputReg == null || input == null ) {
		return;
	}
	var toValidate = { input: input, errCtrl: errCtrl, inputReg: inputReg, precondition: precondition };
	var check = function() {
		return zheku.ui.regexValidator(toValidate);
	};
	var handlerArray = zheku.utility.attachEvent(input, "blur", check);
	if (input.onblur == null) {
		input.onblur = function() {
			return zheku.ui.validate(handlerArray);
		}
	}
	var clearHandler = zheku.utility.attachEvent(input, "focus", function() {
		errCtrl.style.display = "none";
	});
	if (input.onfocus == null) {
		input.onfocus = function() {
			zheku.ui.validate(clearHandler);
		}
	}
	return check;
};

zheku.ui.initialSearch = function(city) {//initialize search
	var watermark = '请输入关键字';
	search = function() {
		var keyword = $("#keyword").val(), searchType = $("#contain div.selected").attr("_value");
		if (keyword == "" || keyword == watermark) {
			var url = window.location.href;
			if (url.indexOf("#") > -1) {
				url = url.substr(0, url.indexOf("#"));
			}
			document.location.href = url; //刷新当前页
			return;
		}
		else {
			if (searchType == null || searchType == "") {
				searchType = "coupons";
			}
			var url = window.location.href;
			window.location.href = "/" + city + "/search/" + searchType + "/?keyword=" + encodeURIComponent(keyword) + '&r=' + (zheku.utility.query(url, "r") == "0" ? "1" : "0") + "#bi_f=" + (searchType == "coupons" ? "5" : "6");
		}
	}
	zheku.ui.setWatermark($("#keyword"), watermark, search);
	zheku.ui.dropdown($("#contain"));
};
zheku.ui.initialMap = function() {
	$("#search_keyword").text(keyword);
	if (!customerId) { customerId = 0; }
	if (!pageIndex) { pageIndex = 0; }
	zheku.ui.map.mapPage(pageIndex);
	zheku.ui.map.attachMapEvent("onmouseover", function(event) {//处理map事件
		window.clearTimeout(mapEventTimer);
		var shape = zheku.ui.map.bingMap.GetShapeByID(event.elementID);
		if (shape == null) return;
		if (shape == zheku.ui.map.lastShape) return;
		zheku.ui.map.setShapeZIndex(shape);
		$(".ero .ero-previewArea div.firstChild").css({ "margin": "0" });
		$(".content_wide .couponinfo2").removeClass("couponinfo2").addClass("couponinfo");
		$(".map_pushpin").removeClass("highlight");
		$("#store_" + shapeMapping[shape.GetID()] + " .couponinfo").removeClass("couponinfo").addClass("couponinfo2");
		$("#map_pushpin_" + shapeMapping[shape.GetID()]).addClass("highlight");
	});
	zheku.ui.map.attachMapEvent("onmouseout", function(event) {//处理map事件
		window.clearTimeout(mapEventTimer);
		if (event.elementID == null) {
			mapEventTimer = window.setTimeout(function() {
				zheku.ui.map.setShapeZIndex();
				zheku.ui.map.bingMap.HideInfoBox();
				$(".content_wide .couponinfo2").removeClass("couponinfo2").addClass("couponinfo");
				$(".map_pushpin").removeClass("highlight");
			}, 100);
		}
	});
};
zheku.ui.initialFeedback = function() {
	submit = function() {//function(content, satisfiedVote, paidUserSurvey, userName, contactWay,code)
		zheku.ajax.addFeedback($("#feed_content").val(), $("[@name='feed_satisfied']:checked").val(), $("#feed_survey")[0].checked, $("#feed_user").val(), $("#feed_contact").val(), $("#feed_code").val());
	};

	var submitCtrl = $("#feed_submit")[0];
	var check = [
	zheku.ui.required($("#feed_content")[0], $("#feed_content_err")[0], 5, 500),
	zheku.ui.required($("#feed_user")[0], $("#feed_user_err")[0], 1, null, function() {
		return $("#feed_survey")[0].checked;
	}),
	zheku.ui.required($("#feed_contact")[0], $("#feed_contact_missing")[0], 1, null, function() {
		return $("#feed_survey")[0].checked;
	}),
	zheku.ui.regex($("#feed_contact")[0], $("#feed_contact_err")[0], /1[0-9]{10}|[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+/, function() {
		return $("#feed_survey")[0].checked;
	}),
	zheku.ui.required($("#feed_code")[0], $("#feed_code_err")[0], 4)
	];

	setContactWayStatus = function() {
		var enabled = $("#feed_survey")[0].checked;
		$("#feed_user")[0].disabled = $("#feed_contact")[0].disabled = !enabled;
		$("#feed_user").css("background", enabled ? "" : "#eee");
		$("#feed_contact").css("background", enabled ? "" : "#eee");
		if (!enabled) {
			$("#feed_contact_err").hide();
			$("#feed_contact_missing").hide();
			$("#feed_user_err").hide();
		}
	}
	$("#feed_survey").click(function() {
		setContactWayStatus();
	});
	setContactWayStatus();

	var handlers;
	if (submitCtrl != null) {
		for (var i = 0; i < check.length; i++) {
			handlers = top.zheku.utility.attachEvent(submitCtrl, "click", check[i]);
		}
		submitCtrl.onclick = function() {
			if (top.zheku.ui.validate(handlers)) {
				submit();
			}
		    return false;
		};
	}
};

zheku.ui.dialogClose;//关闭弹出窗口
zheku.ui.dialog = function(url, html, title, context, closeEvent, cancelEvent) {//弹出对话框
	var minWidth = 300, minHeight = 120;
	var maxWidth = window.screen.availWidth, maxHeight = window.screen.availHeight;
	var setDialogSizeTimer = null;
	hideObj = function(visible) {
		return; //don't hide object and select
		$("select,object").each(function(index, domEle) {
			var o = $(domEle);
			if (visible && o.attr("_h")) {
				o.css("visibility", "visible");
				o.removeAttr("_h");
			}
			else if (o.css("visibility") != "hidden") {
				o.css("visibility", "hidden");
				o.attr("_h", "1");
			}
		});
	};
	clearBlock = function() {
		$("#mask").hide();
		hideObj(true);
		window.onresize = null;
		window.onscroll = null;
	};
	closeDialog = function(cancle) {
		if (cancle && cancelEvent && $.isFunction(cancelEvent)) {
			cancelEvent(context);
		}
		else if (!cancle && closeEvent && $.isFunction(closeEvent)) {
			closeEvent(context);
		}
		if (setDialogSizeTimer) {
			window.clearTimeout(setDialogSizeTimer);
			setDialogSizeTimer = null;
		}
		var dialogBody = $("#dialog_body");
		dialogBody.empty();
		//$("#dialog").fadeOut("normal", clearBlock);
		$("#dialog").hide();
		clearBlock();
	};
	this.close = zheku.ui.dialogClose = closeDialog;
	this.closeEvent = closeEvent;
	this.cancelEvent = cancelEvent;
	this.body = $("#dialog_body");

	moveWin = function(moveUnlimited) {
		var width, height, obj = $("#dialog");
		if (moveUnlimited != true) {//无条件移动
			var dialogWidth = obj.width(), dialogHeight = obj.height();
			if (dialogWidth >= document.documentElement.clientWidth || dialogHeight >= document.documentElement.clientHeight) {
				return;
			}
		}
		var left = $(document).scrollLeft() + Math.max(document.body.clientWidth, document.documentElement.clientWidth) / 2 - obj.width() / 2;
		if (left < 0) left = 0;
		var top = $(document).scrollTop() + document.documentElement.clientHeight / 2 - obj.height() / 2;
		if (top < 0) top = 0;
		obj.css({
			left: left,
			top: top
		});
		$("#mask").css({ width: $.browser.msie ? "100%" : $(document).width(),
			height: Math.max(document.body.scrollHeight, $.browser.msie ? document.documentElement.offsetHeight : document.documentElement.scrollHeight)
		});
	};
	block = function() {
		var mask = $("#mask");
		if (mask.length == 0) {
			return;
		}
		mask.css({ display: "block",
			width: $.browser.msie ? "100%" : $(document).width(),
			height: Math.max(document.body.scrollHeight, $.browser.msie ? document.documentElement.offsetHeight : document.documentElement.scrollHeight),
			"z-index": 100
		});
		if ($.browser.msie) {
			if (document.body.scrollWidth <= window.screen.width)
				mask.width("100%");
			else
				mask.width(document.body.scrollWidth);
		}
		hideObj(false);
		moveWin();
		window.onresize = moveWin;
		window.onscroll = moveWin;
	};
	setDialogSize = function() {//调整dialog尺寸
		var dialogBody = $("#dialog_body");
		var dialogTitle = $("#dialog_titlebar");
		if (dialogBody.children().length == 0) {
			return;
		}
		var frame = dialogBody.find("iframe");
		if (frame.length > 0) {
			var frameBody, width, height;
			try {
				frameBody = frame[0].contentWindow.document.documentElement;
				width = Math.min(frameBody.scrollWidth, frame[0].contentWindow.document.body.clientWidth);
				height = Math.min(frameBody.scrollHeight, frame[0].contentWindow.document.body.clientHeight);
			} catch (e) { frameBody = null; }
			if (!frameBody) {
				setDialogSizeTimer = window.setTimeout(setDialogSize, 100);
				return;
			}
			frame.css({
				width: Math.max(minWidth, width),
				height: Math.max(minHeight, height)
			});
		}
		var inner = $(dialogBody.children(0));
		dialogBody.css({
			width: Math.max(minWidth, inner.width()),
			height: Math.max(minHeight, inner.height())
		});
		dialogTitle.width(dialogBody.width() - 2);
		$("#dialog_titlebar .kuang").width(dialogTitle.width() - 2);
		var dialogWidth = Math.min(dialogBody.width(), maxWidth), dialogHeight = Math.min(dialogBody.height() + dialogTitle.height(), maxHeight);
		$("#dialog").css({
			width: dialogWidth,
			height: dialogHeight,
			overflow: "hidden"
		});
		moveWin();
		setDialogSizeTimer = window.setTimeout(setDialogSize, 100);
	};
	getFrame = function(url) {
		var frame = $("<iframe src='about:blank' frameborder='0' scrolling='no' style='width:99%;'></iframe>");
		url += (url.indexOf("?") == -1 ? "?" : "&") + Math.random(); //防止页面缓存
		frame.attr("src", url);
		return frame;
	};
	show = function() {
		var dialogBody;
		if (url != null) {
			dialogBody = getFrame(url);
		}
		else if (html != null) {
			dialogBody = $(html);
		}
		else {
			return;
		}

		$("#dialog_title").text(title);
		$("#dialog").css({
			position: "absolute",
			width: minWidth,
			height: minHeight,
			"z-index": 1001,
			display: "block"
		});
		$("#dialog_body").empty().append(dialogBody);
		setDialogSize();
		moveWin(true);
		if (!$("#dialog_close").attr("_bind")) {//防止多次绑定事件
			$("#dialog_close").click(function() { closeDialog(true); });
			$("#dialog_close").attr("_bind", "");
		}
		block();
	};
	show();
};

zheku.ui.alert = function(text, title, iconType, context, closeEvent) {//提示对话框
	var icon;
	switch (iconType) {
		case "Error": //
			icon = "iconB";
			break;
		case "Question":
			icon = "iconC";
			break;
		default:
			icon = "iconA";
			break;
	}
	var html = '<div class="dialog_info"><div class="smallw"><div class="' + icon + ' left"></div><div class="textw"><div class="px14">' + text + '</div>' + '</div><div class="clear"></div></div><div class="textalignC"><button class="zybutton" onmouseover="javascript:this.className=\'zybutton2\';" onmouseout="javascript:this.className=\'zybutton\';" id="alert_close">关闭</button></div><br /></div>';
	var dialog = new zheku.ui.dialog(null, html, title, context, closeEvent);
	$("#alert_close").click(function() {
		dialog.close(false);
	});
};

zheku.ui.confirm = function(text, title, context, closeEvent, cancelEvent) {//确认对话框
	var icon;
	var html = '<div class="dialog_info"><div class="smallw"><div class="iconC left"></div><div class="textw"><div class="px14">' + text + '</div>' + '</div><div class="clear"></div></div><div class="textalignC"><button class="zybutton" onmouseover="javascript:this.className=\'zybutton2\';" onmouseout="javascript:this.className=\'zybutton\';" id="confirm_ok">确认</button>&nbsp;&nbsp;&nbsp;&nbsp;<button class="zybutton" onmouseover="javascript:this.className=\'zybutton2\';" onmouseout="javascript:this.className=\'zybutton\';" id="confirm_cancel">取消</button></div><br /></div>';
	var dialog = new zheku.ui.dialog(null, html, title, context, closeEvent, cancelEvent);
	$("#confirm_ok").click(function() {
		dialog.close(false);
	});
	$("#confirm_cancel").click(function() {
		dialog.close(true);
	});
};

zheku.ui.loading = function() {//显示loading
	var html = '<div class="dialog_info"><div class="smallw"><div class="textalignC bottom"><img src="' + ImageServer + '/static/images/LOADING.gif" alt="等待" /></div></div><div class="textalignC bottom px14">请稍候…</div><br /></div>';
	return new zheku.ui.dialog(null, html, "请稍候");
};

zheku.ui.login = function(loginUrl, newWindow, loginFunc) {//newWindow 是否新窗口登录
	var html = "请先使用Windows LIVE ID登录"
	var html = '<div class="dialog_info"><div class="smallw"><div class="iconA left"></div><div class="textw"><div class="px14">请先使用Windows LIVE ID登录</div>' + '</div><div class="clear"></div></div><div class="textalignC"><button class="zybutton" onmouseover="javascript:this.className=\'zybutton2\';" onmouseout="javascript:this.className=\'zybutton\';" id="alert_close">登录</button></div><br /></div>';
	var dialog = new zheku.ui.dialog(null, html, "登录");
	$("#alert_close").click(function() {
		if (newWindow) {
			window.open(loginUrl);
			dialog.close();
		}
		else if( loginFunc ){
		    eval(loginFunc);
		}
		else {
			top.document.location.href = loginUrl;
		}
		return false;
	});
};

//map related functions
zheku.ui.map = {
	bingMap: null,
	lastShape: null,
	mapLoaded: false,
	mapDeferFunc: new Array(),
	mapId: null,
	addPoint: function(latitude, longitude) {
		//zheku.ui.map.clearShape();
		var icon = '<div class="map_pushpin"><div></div></div>';
		zheku.ui.map.addPushpin(latitude, longitude, null, null, icon);
		zheku.ui.map.setMapView();
	},
	addPushpin: function(latitude, longitude, title, description, icon, context, callback) {
		if (latitude == 0 || longitude == 0) return;
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.addPushpin(latitude, longitude, title, description, icon, context, callback); });
			return;
		}
		var x = new VELatLong(latitude / 100000, longitude / 100000);
		var shape = new VEShape(VEShapeType.Pushpin, x);
		if (icon != null) {
			shape.SetCustomIcon(icon); //"<div class='map_pushpin'><div>" + index + "</div></div>");
		}

		if (title != null) {
			shape.SetTitle(title);
		}
		if (description != null) {
			shape.SetDescription(description);
		}
		zheku.ui.map.bingMap.AddShape(shape);
		if (callback != null) {
			callback(shape.GetID(), context);
		}
	},
	addPolyline: function(points, color, style, context, callback) {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.addPolyline(points, color, style, context, callback); });
			return;
		}
		var pointArray = [];
		for (var i = 0; i < points.length; i++) {
			pointArray.push(new VELatLong(points[i].latitude, points[i].longitude));
		}
		var shape = new VEShape(VEShapeType.Polyline, pointArray);
		shape.SetLineWidth(4);
		if (color == null) {
			shape.SetLineColor(new VEColor(0, 255, 255, 1.0));
		}
		else {
			shape.SetLineColor(color);
		}
		shape.HideIcon();
		if (style != null) {
			try { shape.Primitives[0].symbol.stroke_dashstyle = style; } catch (e) { } //try set line style
		}
		try {
			zheku.ui.map.bingMap.AddShape(shape);
		}
		catch (e) { }
		if (callback != null) {
			callback(shape.GetID(), context);
		}
	},
	setCenter: function(latitude, longitude) {
		if (latitude == 0 || longitude == 0) return;
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.setCenter(latitude, longitude); });
			return;
		}
		var latLong = new VELatLong(latitude / 100000, longitude / 100000);
		zheku.ui.map.bingMap.SetCenter(latLong);
	},
	deleteShape: function(shapeID) {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.deleteShape(shapeID); });
			return;
		}
		var shape = zheku.ui.map.bingMap.GetShapeByID(shapeID);
		if (shape != null) {
			zheku.ui.map.bingMap.DeleteShape(shape);
		}
	},
	clearShape: function() {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(zheku.ui.map.clearShape);
			return;
		}
		zheku.ui.map.bingMap.DeleteAllShapeLayers();
		zheku.ui.map.bingMap.DeleteAllShapes();
	},
	loadMap: function(mapID, latitude, longitude, zoomLevel, showDashboard, showMiniMap) {//MapCtrl
		zheku.ui.map.mapId = mapID;
		showMapLoading = function(mapID) {
			$("#map_loading").css({ display: "block",
				position: "absolute",
				width: $("#" + mapID).width(),
				height: $("#" + mapID).height(),
				left: $("#" + mapID).offset().left,
				top: $("#" + mapID).offset().top,
				background: "#ccc"
			});
		};
		showMapLoading(mapID);
		if (typeof VEMap == "undefined" || (document.getElementById(mapID).attachEvent == undefined) || !document.getElementById("dialog")) {
			window.setTimeout(function() { zheku.ui.map.loadMap(mapID, latitude, longitude, zoomLevel, showDashboard, showMiniMap); }, 100);
			return;
		}
		$("#map_loading").hide();
		zheku.ui.map.bingMap = new VEMap(mapID);
		VEMap.prototype.GetWidth = function() { return $("#" + mapID).width(); };
		VEMap.prototype.GetHeight = function() { return $("#" + mapID).height(); };
		VEMap.prototype.GetMapID = function() { return mapID; };
		zheku.ui.map.bingMap.onLoadMap = function() {
			zheku.ui.map.mapLoaded = true;
			if (zheku.ui.map.mapDeferFunc.length > 0) {
				for (var i = 0; i < zheku.ui.map.mapDeferFunc.length; i++) {
					var x = zheku.ui.map.mapDeferFunc[i];
					x();
				}
			}
			zheku.ui.map.mapDeferFunc = [];
		};
		zheku.ui.map.bingMap.LoadMap(new VELatLong(latitude, longitude), zoomLevel, 'r', false);
		if (!showDashboard) zheku.ui.map.bingMap.HideDashboard();
		if (showMiniMap) zheku.ui.map.bingMap.ShowMiniMap(zheku.ui.map.bingMap.GetWidth() - 151, 0, VEMiniMapSize.Small);
	},
	addMapText: function(text) {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.addMapText(text); });
			return;
		}
		var m = $("#" + zheku.ui.map.bingMap.GetMapID());
		var d = $("<div class='map_text'>" + text + "</div>").appendTo("body");
		d.css({
			left: m.offset().left + zheku.ui.map.bingMap.GetWidth() / 2 - d.width() / 2,
			top: m.offset().top + zheku.ui.map.bingMap.GetHeight() / 2 - d.height() / 2
		});
	},
	setMapView: function(shapeLayerIndex) {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.setMapView(shapeLayerIndex); });
			return;
		}
		var shapeLayer = zheku.ui.map.bingMap.GetShapeLayerByIndex(shapeLayerIndex == null ? 0 : shapeLayerIndex);
		if (shapeLayer == null) return;
		var shapeArray = new Array();
		var shapeCount = shapeLayer.GetShapeCount();
		if (shapeCount == 0) return;
		for (var i = 0; i < shapeCount; i++)
			shapeArray.push(shapeLayer.GetShapeByIndex(i));
		zheku.ui.map.bingMap.SetMapView(shapeArray);
	},
	setShapeZIndex: function(shape) {//map.aspx，显示shape次序
	//if ($.browser.mozilla) return;
	if (zheku.ui.map.lastShape != null && zheku.ui.map.lastShape.Id != null) zheku.ui.map.lastShape.SetZIndex(zheku.ui.map.lastShape.zIndex); //恢复zIndex
		zheku.ui.map.lastShape = shape;
		if (shape == null)
			return;
		shape.zIndex = shape.GetZIndex();
		shape.SetZIndex(10000);
	},
	attachMapEvent: function(event, func) {
		if (!zheku.ui.map.mapLoaded) {
			zheku.ui.map.mapDeferFunc.push(function() { zheku.ui.map.attachMapEvent(event, func); });
			return;
		}
		zheku.ui.map.bingMap.AttachEvent(event, func);
	},
	mapPage: function(page) {
		pageIndex = page;
		zheku.ajax.map($("#store_list"), $(".changepage"), $("#store_count"), customerId, storeId, keyword, city, district, area, category, subcat, price, excludeNoCoupon == "1", order, pageIndex);
	},
	showEmptyMap: function() {
		window.setInterval(function() {
			var map = $("#" + zheku.ui.map.mapId);
			if (map.length > 0) {
				$("#map_empty").css({ display: "block",
					position: "absolute",
					width: map.width(),
					height: map.height(),
					left: map.offset().left,
					top: map.offset().top,
					background: "#ccc",
					zIndex: "50"
				});
			}
		}, 100);
	},
	filterByHasCoupon: function(exclude, link) {
		excludeNoCoupon = exclude;
		$(".content_t_1 .select").removeClass("select");
		$(link).addClass("select");
		zheku.ui.map.mapPage(0);
	},
	orderStore: function(type, link) {
		order = type;
		$(".sort_select").removeClass("sort_select");
		$(link).addClass("sort_select");
		zheku.ui.map.mapPage(0);
	}
};

//bus route related functions
zheku.ui.route = {
	addPoint: function(latitude, longitude, title, type) {
		zheku.ui.map.addPushpin(latitude, longitude, title, null, type == 0 ? "<div class='map_route_start'></div>" : "<div class='map_route_end'></div>");
		if (type == 0) {
			$("#start_location").val(title);
		}
		zheku.ui.map.setMapView();
	},
	showDisambiguation: function(endLatitude, endLongitude, locations, busRouteDiv, fewestTranfer) {//多个地点，让用户选择其中一个
		var html = '<div class="start_text">请选择一个起点：</div>';
		for (var i = 0; i < locations.length; i++) {
			var latitude = locations[i].Latitude;
			var longitude = locations[i].Longitude;
			html += "<div class='selstart'><img src='" + ImageServer + "/static/images/directions_play_icon.gif' /><a href='javascript:void(0);' onclick='javascript:zheku.ui.route.addPoint(" + latitude + "," + longitude + ",this.innerHTML,0);zheku.ui.route.getRoute(" + latitude + "," + longitude + "," + endLatitude + ", " + endLongitude + "," + fewestTranfer + ");return false;'>" + locations[i].Address + "</a></div>";
		}
		$("#" + busRouteDiv).html(html);
	},
	showRouteLine: function(routeIndex, startLatitude, startLongitude, endLatitude, endLongitude) {//显示乘车路线
		if (routeInfo.length <= routeIndex) {
			return;
		}
		if ($("#bus_route .route_info.focus:eq(" + routeIndex + ")").length > 1) {//就是当前的路线
			return;
		}

		$("#bus_route .route_info.focus").removeClass("focus");
		$("#bus_route .route_info").eq(routeIndex).addClass("focus");
		zheku.ui.map.clearShape();
		var points = routeInfo[routeIndex].Coordinates, pointArray = new Array();
		for (var i = 0; i < points.length; i++) {
			pointArray.push({ latitude: points[i].latitudeField, longitude: points[i].longitudeField });
		}
		zheku.ui.map.addPolyline(pointArray, null, null);
		zheku.ui.map.setMapView();
		
		var start = routeInfo[routeIndex].Coordinates[0];
		var end = routeInfo[routeIndex].Coordinates[routeInfo[routeIndex].Coordinates.length - 1];
		if (start.latitudeField * 100000 != startLatitude && start.longitudeField * 100000 != startLongitude) {
			zheku.ui.map.addPolyline([{ latitude: startLatitude / 100000, longitude: startLongitude / 100000 }, { latitude: start.latitudeField, longitude: start.longitudeField}], null, "ShortDot"); //起点步行至车站
		}
		zheku.ui.map.setMapView();
		
		if (end.latitudeField * 100000 != endLatitude && end.longitudeField * 100000 != endLongitude) {
			zheku.ui.map.addPolyline([{ latitude: end.latitudeField, longitude: end.longitudeField }, { latitude: endLatitude / 100000, longitude: endLongitude / 100000}], null, "ShortDot"); //步行至终点
		}
		zheku.ui.map.setMapView();

		zheku.ui.route.addPoint(startLatitude, startLongitude, $("#start_location").val(), 0);
		zheku.ui.route.addPoint(endLatitude, endLongitude, $("#end_location").text(), 1);
		zheku.ui.map.setMapView();
	},
	getRoute: function(startLatitude, startLongitude, endLatitude, endLongitude, fewestTranfer) {//获得某两点间的乘车路线并显示
		var dialog = zheku.ui.loading();
		zheku.ajax.submit("GetBusRoute", { startLatitude: startLatitude, startLongitude: startLongitude, endLatitude: endLatitude, endLongitude: endLongitude, fewestTranfer: fewestTranfer }, function(result) {
			zheku.ui.map.clearShape();
			zheku.ui.route.addPoint(endLatitude, endLongitude, $("#end_location").text(), 1);
			zheku.ui.route.addPoint(startLatitude, startLongitude, $("#start_location").val(), 0);
			zheku.ui.map.setMapView();
			if (result.result == 'TooClose') {
				zheku.ui.alert("起点与终点距离很近，建议您步行或使用其它交通工具。", "乘车路线");
				return;
			}
			else if (result.result == 'TooFar') {
				zheku.ui.alert("起点与终点距离太远。", "乘车路线");
				return;
			}
			else if (result.result == 'CantFindNearbyRoad') {
				zheku.ui.alert("找不到临近的路线。", "乘车路线");
				return;
			}
			else if (result.result == 'NoSolution') {
				zheku.ui.alert("无法找到合适的路线。", "乘车路线");
				return;
			}
			else if (result.result == 'UnknownError') {
				zheku.ui.alert("出现错误，请刷新页面重试。", "乘车路线");
				return;
			}
			getIcon = function(routeMode, type) {//type 0 normal,1 gray,2 map
				var icon;
				switch (routeMode) {
					case 4: //bus
						switch (type) {
							case 0: icon = ImageServer + "/static/images/icn_td_bus.png"; break;
							case 1: icon = ImageServer + "/static/images/icn_td_bus_gray.png"; break;
							case 2: icon = ImageServer + "/static/images/icn_td_mapicon_bus.png"; break;
						}
						break;
					case 8: //subway
						switch (type) {
						    case 0: icon = ImageServer + "/static/images/icn_td_subway.png"; break;
						    case 1: icon = ImageServer + "/static/images/icn_td_subway_gray.png"; break;
						    case 2: icon = ImageServer + "/static/images/icn_td_subway.png"; break;
						}
						break;
					case 2: //walk
					    icon = ImageServer + "/static/images/icn_td_walk.png";
						break;
				}
				return "<img src='" + icon + "' align='absmiddle' />";
			};
			showRouteItem = function(routeItem) {
				return "<div class='item'><div class='path_name'>" + getIcon(routeItem.Mode, 0) + " " + routeItem.PathName + "</div>"
				+ "<div class='path_desc'>" + routeItem.PathDescription.replace("\r\n", "<br>") + "</div></div>";
			};
			showRoute = function(route, index) {
				getStart = function() {
				return '<div class="item"><img src="' + ImageServer + '/static/images/directions_play_icon.gif" /> 起点 ' + $("#start_location").val() + "</div>" + "<div class='item'>" + getIcon(2) + ' 步行至车站</div>';
				};
				getEnd = function() {
					return "<div class='item'>" + getIcon(2) + ' 步行至终点</div>' + '<div class="item"><img src="' + ImageServer + '/static/images/directions_stop_icon.gif" /> 终点 ' + $("#end_location").text() + "</div>";
				};
				getTime = function(time) {
					var Minute = "分钟", Hour = "小时";
					var t = time.replace("PT", "").replace("S", "");
					if (t == "0") {
						return '0' + Minute;
					}
					var times = t.split(/[HM]/);
					if (times.length == 3) {
						return times[0] + Hour + times[1] + Minute;
					}
					else if (times.length == 2) {
						return times[0] + Minute;
					}
					else {
						return '0' + Minute;
					}
				};
				getTitle = function(route) {
					var transfer = getIcon(route.RouteInfoItems[0].Mode, 1) + " " + route.RouteInfoItems[0].Names[0];
					if (route.RouteInfoItems.length > 2) {
					    transfer += " <img src='" + ImageServer + "/static/images/icn_td_arrow.png' align='absmiddle' /> " + getIcon(route.RouteInfoItems[route.RouteInfoItems.length - 1].Mode, 1) + " " + route.RouteInfoItems[route.RouteInfoItems.length - 1].Names[0];
					}
					transfer = transfer.replace(/\(.*?\)/, "").replace(/\(.*?\)/, "");
					return transfer + " " + Math.round(route.PathSummary.Distance * 10) / 10 + "公里" + getTime(route.PathSummary.LasingTime) + "";
				};
				var routeHtml = "";
				routeHtml += "<div class='route_info' onclick='zheku.ui.route.showRouteLine(" + index + "," + startLatitude + "," + startLongitude + "," + endLatitude + "," + endLongitude + ");return false;'>";
				routeHtml += "<div class='route_info_title'><span class='index'>" + (index + 1) + ".</span>" + getTitle(route) + "</div>";
				routeHtml += "<div class='items'>";
				var start = route.Coordinates[0];
				if (start.latitudeField * 100000 != startLatitude && start.longitudeField * 100000 != startLongitude) {
					routeHtml += getStart();
				}
				for (var i = 0; i < route.RouteInfoItems.length - 1; i++) {
					routeHtml += showRouteItem(route.RouteInfoItems[i]);
				}
				if (route.Coordinates.length > 1) {
					var end = route.Coordinates[route.Coordinates.length - 1];
					if (end.latitudeField * 100000 != endLatitude && end.longitudeField * 100000 != endLongitude) {
						routeHtml += getEnd();
					}
				}
				routeHtml += "</div>";
				routeHtml += "</div>";
				return routeHtml;
			};
			routeInfo = result.items;
			var html = "";
			for (var i = 0; i < routeInfo.length; i++) {
				html += showRoute(routeInfo[i], i);
			}
			$("#bus_route").html(html);
			zheku.ui.route.showRouteLine(0, startLatitude, startLongitude, endLatitude, endLongitude);
			dialog.close();
			//zheku.ui.dialog.clearBlock();
		}, function(err, result) {
			zheku.ui.alert("出现错误：" + (err.description ? err.description : "未知错误"));
			dialog.close();
		});
	},
	routeSearch: function(event, endLatitude, endLongitude, city, fewestTranfer) {
		//zheku.ui.showProgressBar();
		var start = $("#start_location").val();
		if (start == "") {
			zheku.ui.alert("请输入公交换乘起点。", "乘车路线");
			return false;
		}
		var dialog = zheku.ui.loading();
		zheku.ajax.submit("GetLocationsByName", { targetName: start, cityName: city }, function(result, context) {
			result = result.data;
			if (result.count > 0) {
				for (var i = result.count - 1; i >= 0; i--) {
					if (result.items[i].Address.indexOf(city) == -1) {
						if (i < result.items.length - 1) {
							result.items[i] = result.items[result.items.length - 1];
						}
						result.items.pop();
					}
				}
				result.count = result.items.length;
			}
			else if (result.count == 0) {
				zheku.ui.alert("在" + city + "找不到\"" + start + "\"，请修改后重试。", "乘车路线");
				return false;
			}
			else if (result.items[0].Address == city) {
				zheku.ui.alert("在" + city + "找不到\"" + start + "\"，请修改后重试。", "乘车路线");
				return false;
			}

			if (result.count > 1) {
				zheku.ui.route.showDisambiguation(endLatitude, endLongitude, result.items, "bus_route", fewestTranfer);
				//zheku.ui.dialog.clearBlock();
			}
			else {
				var latitude = result.items[0].Latitude;
				var longitude = result.items[0].Longitude;
				startLatitude = latitude;
				startLongitude = longitude;
				zheku.ui.route.getRoute(startLatitude, startLongitude, endLatitude, endLongitude, fewestTranfer);
				zheku.ui.map.setMapView();
			}
			dialog.close();
		}, function(err, context) {
			alert("出现错误：" + (err.description ? err.description : "未知错误"));
			dialog.close();
		});
		return false;
	}
};

zheku.ui.rating = function(ratingBox, score) {
	if (score < 0) {
	    score = 0;
	}
	var dscore = Math.round(score * 2), half = dscore % 2 == 1, lbound = Math.floor(dscore / 2);
	var html = "";
	for (var i = 0; i < lbound; i++) {
	    html += '<img src="' + ImageServer + '/static/images/star.gif" alt="star" />';
	}
	if (half) {
	    html += '<img src="' + ImageServer + '/static/images/star1.gif" alt="star" />';
	}
	for (var i = lbound + (half ? 1 : 0); i < 5; i++) {
	    html += '<img src="' + ImageServer + '/static/images/star2.gif" alt="star" />';
	}
	ratingBox.html(html);
};

zheku.ui.forwardStore = function(storeId) {
	zheku.ui.dialog("/popup/forward.aspx?storeId=" + storeId, null, "推荐给好友");
};

zheku.ui.forwardCoupon = function(couponId) {
	zheku.ui.dialog("/popup/forward.aspx?couponId=" + couponId, null, "推荐给好友");
};

zheku.ui.forwardCustomer = function(customerId) {
	zheku.ui.dialog("/popup/forward.aspx?customerId=" + customerId, null, "推荐给好友");
};

zheku.ui.emailSubscribe = function() {
    zheku.ui.dialog("/popup/EmailSubscribe.aspx", null, "邮件订阅");
};

zheku.ajax = {};

zheku.ajax.submit = function(url, data, callback, failed, context) {
	var key = url, r = Math.random();
	for (var i in data) {
		if (key != "") {
			key += "_";
		}
		key += i + "=" + encodeURIComponent(data[i]);
	}
	var code = zheku.utility.sign(key) + "_" + r;
	var sign = zheku.utility.sign(code + "");
	data.k = code;
	data.sign = sign;
	data.unused = r;
	window.setTimeout(function() {
		$.ajaxDotNet("/AjaxData.svc/" + url, {
			verb: "GET",
			data: data,
			success: function(obj) {
				var result;
				eval("result=" + obj.d);
				try {
					callback(result, context); //
				}
				catch (err) {
					if (failed) {
						failed(err, context);
					}
					else {
						zheku.ui.alert("出现错误(" + err.message + ")", "错误", "Error");
					}
				}
			},
			error: function(e) {
				if (failed) {
					failed(e);
				}
			}
		});
	}, 0);
};
//big map show list by ajax
zheku.ajax.map = function(listBox, pageBox, countBox, customerId, storeId, keyword, city, district, area, category, subcat, price, excludeNoCoupon, order, pageIndex) {
	var pageSize = 5;
	zheku.ajax.submit("GetStores", { customerId: customerId, storeId: storeId, keyword: keyword, city: city, district: district, area: area, category: category, subcat: subcat, price: price, excludeNoCoupon: excludeNoCoupon, order: order, pageIndex: pageIndex }, function(result, context) {
		getStoreHtml = function(store) {
			var url = zheku.utility.getStoreUrl(store.StoreId);
			var html = '<div id="store_' + store.StoreId + '">';
			html += '<div class="couponinfo">';
			html += '<div class="tags">' + (i + 1) + '</div>';
			html += '<div class="couponinfo_text"> <a class="px12 bold" href="' + url + '">' + zheku.utility.getShortString(store.StoreName, 22) + '</a><br />';
			if (store.CouponCount > 0) {
				html += '<div><span>共有' + store.CouponCount + '张优惠券</span><a class="bold" href="' + url + '">[查看全部]</a></div>';
			}
			if (store.StoreAddress != "" && store.StoreAddress != null) {
				html += '<div>地址：' + store.StoreAddress + '</div>';
			}
			if (store.PhoneNumber != "" && store.PhoneNumber != null) {
				html += '<div>电话：' + store.PhoneNumber + '</div>';
			}
			if (store.Category != "" && store.Category != null) {
				html += '<div>分类：' + store.Category + '</div>';
			}
			html += '<div class="pingfen"><div>评分：</div><div id="rating_' + i + '"></div></div>';
			html += '</div>';
			html += '<div class="clear"></div>';
			html += '</div>';
			html += '</div>';
			return html;
		};
		getSingleStoreHtml = function(store) {
			var url = zheku.utility.getStoreUrl(store.StoreId);
			var html = '<div id="store_' + store.StoreId + '">';
			html += '<div class="couponinfo">';
			html += '<div class="couponinfo_pic"><a href="' + url + '"><img src="' + store.Logo + '" alt="' + store.StoreName + '" /></a></div>';
			html += '<div class="couponinfo_text black">';
			if (store.Category != "" && store.Category != null) {
				html += '<div>分类：' + store.Category + '</div>';
			}
			if (store.StoreAddress != "" && store.StoreAddress != null) {
				html += '<div>地址：' + store.StoreAddress + '</div>';
			}
			if (store.PhoneNumber != "" && store.PhoneNumber != null) {
				html += '<div>电话：' + store.PhoneNumber + '</div>';
			}
			html += '<div class="pingfen"><div>评分：</div><div id="rating_' + i + '"></div></div>';
			html += '</div>';
			html += '<div class="clear"></div>';
			html += '</div>';
			html += '</div>';
			return html;
		};
		var stores = result.stores;
		var startIndex = pageSize * pageIndex;
		shapeMapping = [];
		zheku.ui.map.clearShape();
		listBox.html("");
		for (var i = 0; i < stores.length; i++) {
			var store = stores[i];
			var html = storeId ? getSingleStoreHtml(store) : getStoreHtml(store);
			var box = $(html);
			listBox.append(box);
			zheku.ui.rating($("#rating_" + i), store.Score); //评分
			var icon = '<div class="map_pushpin" id="map_pushpin_' + store.StoreId + '"><div>' + (storeId ? "" : (i + 1)) + '</div></div>';
			if (store.Latitude > 0 && store.Longitude > 0) {
				zheku.ui.map.addPushpin(store.Latitude, store.Longitude, store.StoreName, store.Description, icon, store.StoreId, function(shapeId, context) {
					shapeMapping[shapeId] = context;
					$("#store_" + context).hover(function(event) {
						var shape = zheku.ui.map.bingMap.GetShapeByID(shapeId);
						if (shape == null) return false;
						zheku.ui.map.setShapeZIndex(shape);
						$("#map_pushpin_" + context).addClass("highlight");
						$("#store_" + context + " .couponinfo").removeClass("couponinfo").addClass("couponinfo2");
					},
					function(event) {
						$("#map_pushpin_" + context).removeClass("highlight");
						$("#store_" + context + " .couponinfo2").removeClass("couponinfo2").addClass("couponinfo");
						zheku.ui.map.setShapeZIndex();
					});
				}); //add point to map
			}
			if (storeId) {
				$("#store_link").attr("href", zheku.utility.getStoreUrl(store.StoreId)).text(store.StoreName);
			}
		}
		zheku.ui.map.setMapView();
		pageBox.paging({ pageIndex: pageIndex, pageSize: 5, recordCount: result.count, showPageCount: 10, pageScript: "zheku.ui.map.mapPage({0});" }); //分页
		countBox.html(result.hit); //数目
	}, function(err, context) {
		//alert(err)
	});
};

zheku.ajax.rate = function(scoreBox, ratingBox, itemInfoId, score) {//打分
	zheku.ajax.submit("StoreRate", { itemInfoId: itemInfoId, score: score }, function(result, context) {
		if (result.result == 1) {
			zheku.ui.login(result.loginUrl);
		}
		else if (result.result == 2) {
			zheku.ui.alert("打分失败。");
		}
		else if (result.result == 3) {
			zheku.ui.alert("该商家不允许打分。");
		}
		else if (result.result == 0) {
			zheku.ui.alert("打分成功，谢谢参与。", "打分成功");
			zheku.ui.rating(scoreBox, result.score);
			var name = itemInfoId;
			while (name.indexOf("-") > -1) {
				name = name.replace("-", "");
			}
			zheku.utility.setCookie(name, score, new Date(2010, 1, 1));
			zheku.ui.showRatedScore(ratingBox, itemInfoId, score);
		}
	}, function(err, context) {
	}, score);
};


zheku.ajax.addWallet = function(couponId, box, callback) {
    zheku.ajax.submit("AddWallet", { couponId: couponId }, function(result, context) {
        if (result.result == 0) {
            zheku.ui.alert("<div>加入成功！</div>"
				+ "<div><a href=\"/faq.aspx#dianwen_10\" target=\"_blank\">什么是折酷手机优惠包？</a></div>"
				+ "<div>下载手机折酷优惠包客户端请<a href=\"/Download.aspx\" target=\"_blank\">点击这里</a></div>"
				+ "<div><a href=\"/my/wallet/\" target=\"_top\">管理折酷优惠包&gt;&gt;</a></div>", "加入折酷优惠包", "Default", null, callback);
            if (box == null) {
                return;
            }
            $(box).text("从优惠包中删除").attr("class", "buttonblue left");
            box.onclick = function() {
                zheku.ajax.deleteWallet(result.couponCode, couponId, this);
                return false;
            };
        }
        else if (result.result == 1) {//没登录
            zheku.ui.alert("<div>登录后才能使用此功能。</div>", "加入折酷优惠包", "Default");
        }
        else if (result.result == 2 || result.result == 5) {//已经保存过
            zheku.ui.alert("<div>该优惠券已经保存到优惠包中。</div>", "加入折酷优惠包", "Default");
        }
        else if (result.result == 3) {//delivery engin error
            zheku.ui.alert("<div>" + result.err + "</div>", "加入折酷优惠包", "Default");
        }
        else {//出错
            zheku.ui.alert("<div>保存到优惠包时出现错误" + (result.err ? "，错误原因：" + result.err : "。") + "请刷新页面并重试。</div>", "加入折酷优惠包", "Default");
        }
    }, function(err, context) {
    });
};

zheku.ajax.deleteWallet = function(couponCode, couponId, box, callback) {
    zheku.ui.confirm("你确认删除这个折酷优惠包吗？", "删除折酷优惠包", null, function(result, context) {
        zheku.ajax.submit("DeleteWallet", { couponCode: couponCode }, function(result, context) {
            if (result.result == 0) {
                if (callback) {
                    callback();
                }
                else {
                    zheku.ajax.refreshWalletPage();
                }
                zheku.ui.alert("<div>删除成功！</div>", "删除折酷优惠包", null);
                if (box && couponId) {
                    $(box).text("加入折酷优惠包").attr("class", "buttonorange left");
                    box.onclick = function() {
                        zheku.ajax.addWallet(couponId, this);
                        return false;
                    };
                }
            }
            else if (result.result == 1) {
                zheku.ui.alert("登录已过期，请刷新页面后重新登录。", "删除失败");
            }
            else if (result.result == 2) {
                zheku.ui.alert("删除失败，请刷新页面后重试。", "删除失败");
            }
        }, function(err, context) {
        });
    });
};

zheku.ajax.refreshWalletPage = function() {
    if (top && top.$("#wallet_list") && top.$("#wallet_page1,#wallet_page2") && top.$("#wallet_count")) {
        zheku.ajax.getWallet(top.$("#wallet_list"), top.$("#wallet_page1,#wallet_page2"), top.$("#wallet_count"), 0);
    }
}

zheku.ajax.getWallet = function(couponBox, pageBox, countBox, pageIndex) {
	if (pageIndex == null) {
		pageIndex = window.walletPageIndex;
		if (pageIndex == null) { pageIndex = 0; }
	}
	zheku.ajax.submit("GetWallet", { pageIndex: pageIndex }, function(result, context) {
		couponBox.html(""); pageBox.html(""); countBox.text('我添加了' + result.total + '张优惠券');
		if (result.count == 0) {
			return;
		}
		var coupons = result.coupons, html = "";
		getCouponHtml = function(coupon) {
			getCouponFunction = function(couponCode, couponId) {
				var page = pageIndex;
				if (coupons.length == 1 && page > 0) {
					page--;
				}
				return '<a class="buttonblue left" href="javascript:;" onclick="javascript:zheku.ajax.deleteWallet(\'' + couponCode + '\',' + couponId + ',this,function(){walletPage(' + page + ');});">从优惠包中删除</a>';
			};
			var url = "javascript:zheku.ui.dialog('/popup/walletinfo.aspx?couponCode=" + coupon.CouponCode + "',null,'折酷优惠包信息');"
			var html = "";
			html += '<div class="moreinfo">';
			html += '<div class="couponinfo" onmouseover="javascript:this.className=\'couponinfo2\';" onmouseout="javascript:this.className=\'couponinfo\';">';
			html += '<div class="couponinfo_pic"><a href="' + url + '"><img src="' + coupon.CouponLogo + '" alt="' + coupon.CouponName + '" /></a></div>';
			html += '<div class="couponinfo_text">';
			html += '<div><a class="px12 bold" href="' + url + '">' + zheku.utility.getShortString(coupon.CouponName, 16) + '</a></div>';
			html += '<div>优惠截止：' + coupon.EndDate + '</div>';
			html += getCouponFunction(coupon.CouponCode, coupon.CouponID);
			html += '</div>';
			html += '<div class="clear"></div>';
			html += '</div>';
			html += '</div>';
			return html;
		};
		for (var i = 0; i < coupons.length; i++) {
			html += getCouponHtml(coupons[i]);
		}
		couponBox.html(html);
		pageBox.paging({ pageIndex: result.pageIndex, pageSize: 10, recordCount: result.total, showPageCount: 10, pageScript: "walletPage({0});" }); //分页
		window.walletPageIndex = pageIndex;
	}, function(err, context) {
	});
};

zheku.ajax.getCoupons = function(couponBox, pageBox, pageIndex, advertiserId, storeId, excludeCouponId) {
	showCoupons = function(result, context) {
		couponBox.html(""); pageBox.html("");
		if (result.count == 0) {
			return;
		}
		getCouponHtml = function(coupon) {
			getCouponFunction = function(functions) {
				if (functions == null || functions.length == 0) {
					return "";
				}
				var h = "";
				for (var i = 0; i < functions.length; i++) {
					h += functions[i];
				}
				return h;
			};
			var url = zheku.utility.getCouponUrl(coupon.CouponID);
			var html = "";
			html += '<div class="moreinfo">';
			html += '<div class="couponinfo" onmouseover="javascript:this.className=\'couponinfo2\';" onmouseout="javascript:this.className=\'couponinfo\';">';
			html += '<div class="couponinfo_pic"><a href="' + url + '" target="_blank"><img src="' + coupon.CouponLogo + '" alt="' + coupon.CouponName + '" /></a></div>';
			html += '<div class="couponinfo_text">';
			html += '<div><a class="px12 bold" href="' + url + '" target="_blank">' + zheku.utility.getShortString(coupon.CouponName, 12) + '</a></div>';
			html += '<div>优惠截止：' + coupon.EndDate + '</div>';
			html += getCouponFunction(coupon.Functions);
			html += '</div>';
			html += '<div class="clear"></div>';
			html += '</div>';
			html += '</div>';
			return html;
		};
		var coupons = result.coupons, html = "";
		for (var i = 0; i < coupons.length; i++) {
			html += getCouponHtml(coupons[i]);
		}
		couponBox.html(html);
		pageBox.paging({ pageIndex: pageIndex, pageSize: 10, recordCount: result.count, showPageCount: 10, pageScript: "page({0});" }); //分页
	};
	if (excludeCouponId == null) {
		excludeCouponId = 0;
	}
	var url = encodeURIComponent(document.location.href);
	if (advertiserId) {
		zheku.ajax.submit("GetCustomerCoupons", { advertiserId: advertiserId, excludeCouponId: excludeCouponId, pageIndex: pageIndex, url: url }, showCoupons);
	}
	else if (storeId) {
		zheku.ajax.submit("GetStoreCoupons", { storeId: storeId, excludeCouponId: excludeCouponId, pageIndex: pageIndex, url: url }, showCoupons);
	}
};

zheku.ajax.addFeedback = function(content, satisfiedVote, paidUserSurvey, userName, contactWay, code) {//添加用户反馈
	var dialog = zheku.ui.loading();
	zheku.ajax.submit("AddFeedback", { content: content, satisfiedVote: satisfiedVote, paidUserSurvey: paidUserSurvey, userName: userName, contactWay: contactWay, code: code }, function(result, context) {
		dialog.close();
		refreshCode();
		if (result.result == 0) {
			zheku.ui.alert("感谢您对我们的支持。我们会尽快处理您的意见或建议。", "提交成功", null);
			$("#feed_content").val(""); $("#feed_user").val(""); $("#feed_contact").val(""); $("#feed_code").val(""); $("#feed_survey")[0].checked = false; $("input:radio[@name='feed_satisfiedVote']")[1].checked = true;
		}
		else if (result.result == 1) {
			zheku.ui.alert("提交时出现错误，请重试。", "提交失败", null);
		}
		else if (result.result == 2) {
			zheku.ui.alert("验证码输入错误，请重试。", "提交失败", null);
		}
	}, function(err, context) {
		dialog.close();
	});
};

zheku.ajax.storeDropdown = function(span) {
	var storeId = parseInt($(span).attr("_value"));
	if (window.currentStoreId == storeId) { return; }
	window.currentStoreId = storeId;
	zheku.ajax.submit("GetStore", { storeId: storeId }, function(result, context) {
		var stores = result;
		if (stores.length == 0) { return; }
		var store = stores[0];
		var url = zheku.utility.getStoreUrl(store.StoreId);
		$("#store_link").attr("href", url).text(zheku.utility.getShortString(store.StoreName, 28));
		$("#store_link2").attr("href", url);
		$("#store_address span").text(zheku.utility.getShortString(store.StoreAddress, 34))[0].title = store.StoreAddress;
		$("#store_tel span").text(store.PhoneNumber);
		if (store.Latitude == 0 || store.Longitude == 0) {
			$("#store_map").attr("href", "javascript:;").css("color", "gray")[0].onclick = function() {
				return false;
			};
		}
		else {
			$("#store_map").attr("href", "/map.aspx?storeId=" + store.StoreId).css("color", "")[0].onclick = null;
		}

		zheku.ui.map.clearShape();
		if (store.Latitude > 0 && store.Longitude > 0) {
			zheku.ui.map.addPoint(store.Latitude, store.Longitude);
		}
		else {
			zheku.ui.map.showEmptyMap();
		}
		zheku.ui.map.setMapView();
	}, function(err, context) {
	}, storeId);
};
 
//初始化需要执行
$(document).ready(
	function() {
		var b = $(document.body);
		b.append('<div id="dialog" style="display:none;">'
		+ '<div id="dialog_titlebar"><div class="kuang">'
		+ '<span id="dialog_title"></span>'
		+ '<a href="javascript:void(0);" class="closez" id="dialog_close"></a></div></div>'
		+ '<div id="dialog_body"></div></div>');
		b.append('<div id="mask" style="display:none;filter:alpha(opacity=50);opacity:0.5;"></div>');
		zheku.utility.log(); //bi recording
		zheku.utility.biCheck();
		zheku.ui.fixPNG();
		zheku.utility.checkLoginFunc();
	}
);