// 网站所用的基本js，包含通用的函数和大部分页面用的的功能 JavaScript Document

/*基于jQuery的页面功能*/
$(document).ready(function (){
	//输入的trim
	$(":input").change(function(){
		$(this).val($.trim($(this).val()));
	});

	// 顶部的城市选择
	$('#SetCity').toggle(function(){
		$('.citySelector').appendTo($('body')).show().css({top:$(this).offset().top+18,left:$(this).offset().left});
		if($('.citySelector .d1').children().length==0){
			$('.citySelector #cityHot').click();
		}
		$(this).blur();
	},function(){
		$('.citySelector').hide();
		$(this).blur();
	});
	$('.citySelector .actionClose').click(function(){
		$('#SetCity').click();
	});
	$('.citySelector #cityHot').click(function(){
		$('.citySelector .d1').load('/API/citylist/hot.html');
		$('.citySelector').css('width',240).find('.d0 a').removeClass('b');
		$(this).addClass('b').blur();
	});
	$('.citySelector #cityAll').click(function(){
		$('.citySelector .d1').load('/API/citylist/all.html');
		$('.citySelector').css('width',780).find('.d0 a').removeClass('b');
		$(this).addClass('b').blur();
	});
	
	//店铺搜索、服务搜索的输入提示
	$('.naviSearch input[name="addr"]').focus(function(){
		$('#addrHint').css({'opacity':0.9,'display':'block','position':'absolute','left':$(this).select().offset().left+($.browser.mozilla?1:0),'top':$(this).offset().top+28});
	}).blur(function(){
		$('#addrHint').hide();
	});
	$('.naviSearch input[name="q"]').focus(function(){
		$('#qHint').css({'opacity':0.9,'display':'block','position':'absolute','left':$(this).select().offset().left+($.browser.mozilla?1:0),'top':$(this).offset().top+28});
	}).blur(function(){
		$('#qHint').hide();
	});
	
	//店铺、服务搜索的链接位置设置【仅仅限制在店铺和服务搜索页面】
	$('.serviceResult a, .serviceImageList a').attr('target','_blank');
	
	//收藏店铺
	if($(".favoriteButton").length>0){
		var favoriteShopHidden='<div class="floatLayer floatFavoriteShop"><div class="d1"><div class="p1">收藏店铺</div></div><input type="hidden" name="obj"><table cellpadding="4" cellspacing="2" border="0"><tr><td class="t1">店铺名</td><td><label></label></td></tr><tr><td class="t1">标签</td><td><input name="tag" maxlength="36"><br>用逗号、分号或空格分开</td></tr><tr><td colspan="2" align="center"><input type="submit" class="btn" value="确 定">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="btn" value="取 消"></td></tr></table></div>';
		$(favoriteShopHidden).hide().appendTo("body");
		$(".favoriteButton").click(function(){
			if(Visitor<=0){
				if(confirm('登录后才可以使用收藏，立即登录吗?')){
					window.location='/login.php?from='+escape(window.location);
				}
				return false;
			}
			var _v=$(this).attr("name").split(':',2);
			var obj=$(".floatFavoriteShop").find(":button").click(function(){
				setTimeout($.unblockUI, 0);
				return false;
			}).end().find("label").text(_v[1]).end().find(":hidden").val(_v[0]).end().find(":submit").unbind("click").click(function(){
				$(".floatFavoriteShop").find(":text").val( $.trim($(".floatFavoriteShop").find(":text").val()).replace(/[,; ，；　]+/g,' ') );
				$.post(
					"/ajax/favoriteShop.php",
					{obj:$(".floatFavoriteShop").find(":hidden").val(),tag:$(".floatFavoriteShop").find(":text").val()},
					function(data){
						setTimeout($.unblockUI, 0);
						alert(data);
				});
				return false;
			}).end();
			$.blockUI({ message: obj , css: {width:"300px",top:'30%',left: ($(window).width() - 300) /2 + 'px'} });
			return false;
		});
	}
	
	//服务项目搜索，展开和隐藏更多搜索选项
	$('.resultSummary .toggleOptionAnchor').click(function(){
		if($.cookie('showOptions')==1){
			$.cookie('showOptions',0, {expires:30, path:'/', domain:'yixinfuwu.com',secure:false});
		}else{
			$.cookie('showOptions',1, {expires:30, path:'/', domain:'yixinfuwu.com',secure:false});
		}
		$(this).toggleClass('actionMoreOptions').toggleClass('actionLessOptions').blur();
		$('.searchOption .hiddenOption').toggle();
		return false;
	});
	if($.cookie('showOptions')==1){
		$('.resultSummary .toggleOptionAnchor').toggleClass('actionMoreOptions').toggleClass('actionLessOptions').blur();
		$('.searchOption .hiddenOption').show();
	}

	//收藏服务项目
	if($(".favoriteServiceButton").length>0){
		var favoriteServiceHidden='<div class="floatLayer floatFavoriteService"><div class="d1"><div class="p1">收藏服务</div></div><input type="hidden" name="obj"><table cellpadding="4" cellspacing="2" border="0"><tr><td class="t1">服务名</td><td><label></label></td></tr><tr><td class="t1">标签</td><td><input name="tag" maxlength="36"><br>用逗号、分号或空格分开</td></tr><tr><td colspan="2" align="center"><input type="submit" class="btn" value="确 定">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="btn" value="取 消"></td></tr></table></div>';
		$(favoriteServiceHidden).hide().appendTo("body");
		$(".favoriteServiceButton").click(function(){
			if(Visitor<=0){
				if(confirm('登录后才可以使用收藏，立即登录吗?')){
					window.location='/login.php?from='+escape(window.location);
				}
				return false;
			}
			var _v=$(this).attr("name").split(':',2);
			var obj=$(".floatFavoriteService").find(":button").click(function(){
				setTimeout($.unblockUI, 0);
				return false;
			}).end().find("label").text(_v[1]).end().find(":hidden").val(_v[0]).end().find(":submit").unbind("click").click(function(){
				$(".floatFavoriteService").find(":text").val( $.trim($(".floatFavoriteService").find(":text").val()).replace(/[,; ，；　]+/g,' ') );
				$.post(
					"/ajax/favoriteService.php",
					{obj:$(".floatFavoriteService").find(":hidden").val(),tag:$(".floatFavoriteService").find(":text").val()},
					function(data){
						setTimeout($.unblockUI, 0);
						alert(data);
				});
				return false;
			}).end();
			$.blockUI({ message: obj , css: {width:"300px",top:'30%',left: ($(window).width() - 300) /2 + 'px'} });
			return false;
		});
	}
	
	//首页搜索的标签切换
	$('#homeShopAnchor').click(function(){
		$('#ShopServiceForm').find('input[name="a"]').val('sshop').end().find(':submit').val('搜索商家');
		$(this).blur().addClass('a1').siblings('a').removeClass('a1');
		return false;
	});
	$('#homeServiceAnchor').click(function(){
		$('#ShopServiceForm').find('input[name="a"]').val('sservice').end().find(':submit').val('搜索服务');
		$(this).blur().addClass('a1').siblings('a').removeClass('a1');
		return false;
	});
	$('#homeBusAnchor').click(function(){
		$('#BusForm').show();$('#SiteForm').hide();
		$(this).blur().addClass('a1').siblings('a').removeClass('a1');
		return false;
	});
	$('#homeSiteAnchor').click(function(){
		$('#SiteForm').show();$('#BusForm').hide();
		$(this).blur().addClass('a1').siblings('a').removeClass('a1');
		return false;
	});
	
	//首页搜索的 我的地点 点击
	$('.myAddressAnchor').click(function(){
		$('input[name="addr"]').val($(this).attr('name'));
		$(this).blur();return false;
	});
	
	//添加当前页面到bookmark
	$('.bookmarkAnchor').click(function(){
		var uri=window.location.toString().replace(/#.*/,'');
		var title=document.title;
		try{
			window.external.addFavorite(uri, title);
		}catch(e){
			try{
				window.sidebar.addPanel(title, uri, '');
			}catch(e){
				alert('你的浏览器不支持自动添加书签，请手动添加');
			}
		}
		$(this).blur();return false;
	});

	//设置一心服务为首页
	$('.homepageAnchor').click(function(){
		var uri=window.location.toString();
		uri=uri.substr(0,uri.indexOf('/',10)+1);
		try{
			document.body.style.behavior='url(#default#homepage)';
			document.body.setHomePage(uri);
		}catch(e){
			alert('浏览器不支持，请手动设置');
		}
		$(this).blur();return false;
	});

	//公交查询.地点，基于 百度地图搜索功能
	$('#SiteForm').submit(function(){
		var site=$('#SiteForm input[name="site"]').val();
		if(site==''){
			return false;
		}
		var q='s&wd='+JSData.City+' '+site+'&c=1';
		q=encodeURI(q);
		$('<form method="get" action="http://map.baidu.com/" target="_blank"></form>').
			append($('<input name="newmap" value="1">')).
			append($('<input name="s" value="'+q+'">')).
			appendTo($('body')).submit().remove();
		return false;
	});
	//公交查询.公交，基于 百度地图搜索功能
	$('#BusForm').submit(function(){
		var from=$('#BusForm input[name="from"]').val();
		var to=$('#BusForm input[name="to"]').val();
		if(from=='起点' || from=='' || to=='终点' || to==''){
			return false;
		}
		var q='bt&c=1&sn=2$$$$$$'+JSData.City+' '+from+'$$&en=2$$$$$$'+JSData.City+' '+to+'$$';
		q=encodeURI(q);
		$('<form method="get" action="http://map.baidu.com/" target="_blank"></form>').
			append($('<input name="newmap" value="1">')).
			append($('<input name="s" value="'+q+'">')).
			appendTo($('body')).submit().remove();
		return false;
	}).find('input[name="from"]').focus(function(){
		if($(this).val()=='起点'){
			$(this).val('');
		}
	}).blur(function(){
		if($(this).val()==''){
			$(this).val('起点');
		}
	}).end().find('input[name="to"]').focus(function(){
		if($(this).val()=='终点'){
			$(this).val('');
		}
	}).blur(function(){
		if($(this).val()==''){
			$(this).val('终点');
		}
	});
	
	//店铺搜索页面地图功能
	if ($('#searchMap').length>0 && GBrowserIsCompatible()) {
		//地图的随动动作
		$('#searchMap').data('topMin',$('#searchMap').parent().offset().top)
			.parent()
			.css({position:'absolute',top:$('#searchMap').data('topMin')})
			.after($('<div></div>').css({height:$('#searchMap').parent().height()}));
		$('.mapFloatAnchor').click(function(){
			if(!$(this).hasClass('actionUnchoosen')){
				$('#searchMap').parent().css({top:$('#searchMap').data('topMin')});
			}
			$(this).blur().toggleClass('actionUnchoosen').toggleClass('actionTried');
			return false;
		});
		$(window).scroll(function(){
			if($('.mapFloatAnchor').hasClass('actionTried')){
				//$('#searchMap').parent().animate({top:Math.max($(this).scrollTop()+1, $('#searchMap').data('topMin'))},'fast', "linear");
				$('#searchMap').parent().css({top:Math.max($(this).scrollTop()+1, $('#searchMap').data('topMin'))});
			}
		});
		//准备地图
		var map = new GMap2(document.getElementById("searchMap"));
		if(JsData.addr){
			var center = new GLatLng(JsData.addr.lat, JsData.addr.lng);
		}else{
			var count=0, latSum=0; lngSum=0;
			for (i=0,len=JsData.shops.length;i<len;i++){
				count++;
				v=JsData.shops[i];
				latSum+=parseFloat(v.lat);lngSum+=parseFloat(v.lng);
			}
			if(count>0){
				var center=new GLatLng(latSum/count, lngSum/count);
			}else{
				//默认为北京天安门
				var center=new GLatLng(39.9046,116.3976);
			}
		}
		map.addControl(new GSmallMapControl());
		map.setCenter(center, JsData.level);
		map.enableScrollWheelZoom();
		//显示当前位置和店铺位置
		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.iconSize = new GSize(24, 41);
		blueIcon.iconAnchor = new GPoint(11,41);
		blueIcon.image = "http://www.yixinfuwu.com/images/blueMarker.png";
		var marker=new GMarker(center, { icon:blueIcon, draggable:true });
                GEvent.addListener(marker, "dragend", function(){
			$.cookie('tempAddr',
				'临时位置 @'+marker.getLatLng().lat().toString().substr(0,8)+','+marker.getLatLng().lng().toString().substr(0,8),
				{expires:7, path:'/', domain:'yixinfuwu.com',secure:false}
			);
	        	window.location=JsData.base+'&addr='+encodeURI('临时位置')+' @'
				+marker.getLatLng().lat().toString().substr(0,9)+','
				+marker.getLatLng().lng().toString().substr(0,9);
                });
                map.addOverlay(marker);
		var baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		function createMarker(point, index, uri) {
			// Create a lettered icon for this point using our icon class
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.cn/mapfiles/marker" + letter + ".png";
			// 设置 GMarkerOptions 对象
			markerOptions = { icon:letteredIcon };
			var marker = new GMarker(point, markerOptions);
			GEvent.addListener(marker, "click", function() {
				$('<form action="'+uri+'" target="_blank"></form>').appendTo($('body')).submit().remove();
			});
			return marker;
		}
		for (i=0,len=JsData.shops.length;i<len;i++){
			v=JsData.shops[i];
			var latlng=new GLatLng(v.lat, v.lng);
			map.addOverlay(createMarker(latlng, i, v.uri));
		}
	}
	
	//+新功能
});

/*图片大小调整*/ 
//小图片直接放大……
//author's space: http://pro.poscoc.com/1/
function adjustImage(img,width,height,method){
	switch (method){
		default:
			var style='';
			var currentWidth=img.width;
			var currentHeight=img.height;
			if(currentWidth/currentHeight>width/height){
				//实用宽
				img.style.width=width+'px';
				//实用高
				img.style.height=Math.round(width/currentWidth*currentHeight)+'px';
				//实用margin
				img.style.marginTop=Math.ceil((height-width/currentWidth*currentHeight)/2)+'px';
				img.style.marginBottom=Math.floor((height-width/currentWidth*currentHeight)/2)+'px';
			}else{
				//实用高
				img.style.height=height+'px';
				//实用宽
				img.style.width=Math.round(height/currentHeight*currentWidth)+'px';
				//实用margin
				img.style.marginLeft=Math.ceil((width-height/currentHeight*currentWidth)/2)+'px';
				img.style.marginRight=Math.floor((width-height/currentHeight*currentWidth)/2)+'px';
			}
			break;
	}
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

