﻿$(function(){
	$(".activity .column-left .box .content").hover(
		function(){
			$(this).addClass("content-h");
		},
		function(){
			$(this).removeClass("content-h");
		}
	);
	var un = $("#UserName"),unt = un.text();
	if (unt.length>14) un.text(unt.substr(0,12)+"..");
});
//移除空内容区域
function RemoveNull(d,t){
	if (!$(d).find(t).is(t)){$(d).remove();}
}
//详细页面底部相关区域
function DetailRelate(){
	RemoveNull("#PicBox","a");
	RemoveNull("#RelateBox","a");
	RemoveNull("#ActBox","a");
	RemoveNull("#CommendBox","a");
}
//图片大小控制
function ImgSize(d,w,h){
	var tw,th;
	h = h?h:false;
	$("img",d).each(function(){
		tw = $(this).width();
		th = $(this).height();
		if (tw >= w){
			$(this).width(w);
			//$(this).height(Math.ceil(th*(w/tw)));
		}
		if (h){
			if (th >= h){
				$(this).height(h);
				//$(this).height(Math.ceil(th*(w/tw)));
			}
		}
	});
}
//视频播放
function VideoPlayer(u,p,w,h,a){
	document.write('<object id="player" name="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+w+'" height="'+h+'"><param name="movie" value="/images/player.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="flashvars" value="file='+u+'&image='+p+a+'" /><embed type="application/x-shockwave-flash" id="player2" name="player2" src="/images/player.swf" width="'+w+'" height="'+h+'" allowscriptaccess="always" allowfullscreen="true" flashvars="file='+u+'&image='+p+a+'" /></object>');
}
//ajax加载内容
function LoadContent(c,t,d,u){
	var dom = $(t).parents(d);
	var tc = $(t).parent().attr("class");
	var dh = dom.height();
	var dt = dom.html();
	var cu = c.split(" ");
	cu[0] = cu[0] + "?t=" + Math.random();
	c  = "";
	$.each(cu,function(i,n){
		var s = (i<cu.length-1)?" ":"";
		c += n + s;
	});
	dom.load(c,function(){
		var cc = "." + $(this).children().attr("class");
		$(this).html($(cc).html());
		$("<span><a href=\"javascript:void(0);\">"+ u +"</a></span>").appendTo(dom).addClass(tc);
		var nh = $(this).height();
		$(this).height(dh);
		$(this).animate({height:nh},500);
		$(dom).children("." + tc).click(function(){
			$(dom).animate({height:dh},500,function(){
				$(dom).height("auto");
				$(dom).html(dt);
			});
		});
	});
}
//提示图标
function TipIco(){
	$("<div/>").prependTo("#Menu li:eq(4)").addClass("tip-ico t-beta");
}
//资讯顶部
function NewsTop(t,v,p){
	var start = (t)?"true":"false";
	t = (t)?t:"#NewsTopItem>ul>li:eq(0)"
	var obj = $(t);
	var url = $(".summary>a", obj).attr("href");
	var video = '<object id="player" name="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="420" height="340"><param name="movie" value="/images/player.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="flashvars" value="file='+v+'&image='+p+'&autostart='+start+'" /><embed type="application/x-shockwave-flash" id="player2" name="player2" src="/images/player.swf" width="420" height="340" allowscriptaccess="always" allowfullscreen="true" flashvars="file='+v+'&image='+p+'&autostart='+start+'" /></object>';
	var pic = '<a href="'+ url +'"><img src="'+ p +'"/></a>'
	$(t).addClass("s").siblings().removeClass("s");
	$("#NewsTopShow").html((v)?video:pic).hide().delay(300).fadeIn("fast");
}
//资讯Tag
function NewsTag(){
	$("#NewsTag a").each(function(){
		$(this).click(function(){
			window.location = "/search.php?query="+ $(this).text() +"&modelid=6&x=2&y=10";
		});
	});
}
//活动顶部
function ActivityTop(){
	$("#ActivityTop .slide-show li").eq(0).addClass("s");
	$("#ActivityTop .slide-list li").eq(0).addClass("s");
	$("#ActivityTop .slide-list li").mouseover(function(){
		var t = $(this).index();
		$(this).addClass("s").siblings().removeClass("s");
		$("#ActivityTop .slide-show li").eq(t).show().siblings().hide();
	});
}
//滚动插件
(function($){
	$.fn.easyScroll = function(options){
		var defaults = {
			controlsShow:	true,
			prevId:			"prevBtn",
			prevText:		"",
			nextId:			"nextBtn",
			nextText:		"",
			speed:			500,
			pause:			3600,
			auto:			true,
			titleTip:		true,
			offset:			0
		}
		var options = $.extend(defaults,options);
		this.each(function(){
			var obj = $(this);
			var s = $("li", obj).length;
			var w = $("li", obj).outerWidth(true);
			
			//滚屏内容宽度
			$("ul", obj).css("width", w*s);
			
			//滚屏按钮
			if(options.controlsShow){
				var html = "";
				html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
				html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
				$(obj).append(html);
				function btnBind(){
					$("a","#"+options.nextId).click(function(){		
						animate("next",true);
					});
					$("a","#"+options.prevId).click(function(){		
						animate("prev",true);				
					});	
				}
				btnBind();
			}
			
			//滚屏动画
			function animate(dir,clicked){
				switch(dir){
					case "next"://前进
						$("ul", obj).animate({marginLeft:-options.offset},options.speed,function(){
							$(this).css({marginLeft:0}).find("li:first").appendTo(this);
						});
						break; 
					case "prev"://后退
						$("ul", obj).prepend($("ul", obj).css({marginLeft:-options.offset}).find("li:last"));
						$("ul", obj).animate({marginLeft:0},options.speed);
						break;
					default:
						break;
				};
				
				//取消自动滚屏
				if(clicked) clearTimeout(timeout);
				
				//自动滚屏
				if(!clicked){
					timeout = setTimeout(function(){
						animate("next",false);
					},options.pause);
				};
			}
			
			//提示
			if(options.titleTip){
				$("ul li", obj).each(function(){
					var t = $(this).find("img").attr("alt");
					$(this).find("img").attr("alt","");
					$(this).append("<div class='tip'>"+t+"</div>");
					$(this).find(".tip").hide();
					$(this).hover(
						function(){
							$(this).find(".tip").show();
						},
						function(){
							$(this).find(".tip").hide();
						}
					);
				});
			};
			
			//开始自动滚屏
			var timeout;
			if(options.auto){
				timeout = setTimeout(function(){
					animate("next",false);
				},options.pause);
			};
		});
	}
})(jQuery);
//菜单状态选择
function menuSelect(){
	var MenuLink,NavLink=$("#Nav dd:first a").attr("href");
	var MenuText,NavText=$("#Nav strong").html();
	$("#Menu li a").each(function(){
		MenuLink=$(this).attr("href");
		MenuText=$(this).html();
		if (MenuLink==NavLink || MenuText==NavText) $(this).parent("li").addClass("s");
	});
	TipIco();
}
//列表状态选定
function listSelect(dom){
	var dom = $(dom);
	var ListText,PageTitle=$("title").html();
	$("li a",dom).each(function(){
		ListText=$(this).html();
		if (PageTitle.indexOf(ListText)!=-1) $(this).parent("li").addClass("s");
	});
}
//栏目状态选定
function subNav(){
	var subPath;
	var pagePath=location.pathname;
	var lastPath=$(".guide a:last").attr("href");//最终子类
	//侧栏子菜单
	$(".panel>.sub-nav li").each(function(){
		subPath=$(this).find("a").attr("href");
		if (subPath==pagePath || subPath==lastPath) $(this).addClass("s").siblings().removeClass("s");
	});
	//顶部菜单
	var firstName,menuPath;
	var navName=$(".sub-nav>h2>span").html();//一级大类名
	var firstPath=$(".guide a:eq(1)").attr("href");//一级大类
	$(".menu li>a").each(function(){
		menuPath=$(this).attr("href");
		firstName=$(this).attr("title");
		if (firstPath==menuPath || navName==firstName) $(this).addClass("h");
	});
} 
//时间提示
function welcomeInfo(){
	var info,now = new Date(),hour = now.getHours();
	if(hour < 6){info = "凌晨好"} 
	else if (hour < 9){info = "早上好"} 
	else if (hour < 12){info = "上午好"} 
	else if (hour < 14){info = "中午好"} 
	else if (hour < 17){info = "下午好"} 
	else if (hour < 19){info = "傍晚好"} 
	else if (hour < 22){info = "晚上好"} 
	else{info = "夜深了"}
	return info;
}
//日历
var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}
var Extend = function(destination, source) {
	for (var property in source) {
		destination[property] = source[property];
	}
	return destination;
}
var Calendar = Class.create();
Calendar.prototype = {
	initialize: function(container, options) {
		this.Container = document.getElementById(container);//容器(table结构)
		this.Days = [];//日期对象列表
		
		this.SetOptions(options);
		
		this.Year = this.options.Year || new Date().getFullYear();
		this.Month = this.options.Month || new Date().getMonth() + 1;
		this.SelectDay = this.options.SelectDay ? new Date(this.options.SelectDay) : null;
		this.onSelectDay = this.options.onSelectDay;
		this.onToday = this.options.onToday;
		this.onFinish = this.options.onFinish;	
		
		this.Draw();
	},
	//设置默认属性
	SetOptions: function(options) {
		this.options = {//默认值
			Year:			0,//显示年
			Month:			0,//显示月
			SelectDay:		null,//选择日期
			onSelectDay:	function(){},//在选择日期触发
			onToday:		function(){},//在当天日期触发
			onFinish:		function(){}//日历画完后触发
		};
		Extend(this.options, options || {});
	},
	//当前月
	NowMonth: function() {
		this.PreDraw(new Date());
	},
	//上一月
	PreMonth: function() {
		this.PreDraw(new Date(this.Year, this.Month - 2, 1));
	},
	//下一月
	NextMonth: function() {
		this.PreDraw(new Date(this.Year, this.Month, 1));
	},
	//上一年
	PreYear: function() {
		this.PreDraw(new Date(this.Year - 1, this.Month - 1, 1));
	},
	//下一年
	NextYear: function() {
		this.PreDraw(new Date(this.Year + 1, this.Month - 1, 1));
	},
	//根据日期画日历
	PreDraw: function(date) {
		//再设置属性
		this.Year = date.getFullYear(); this.Month = date.getMonth() + 1;
		//重新画日历
		this.Draw();
	},
	//画日历
	Draw: function() {
		//用来保存日期列表
		var arr = [];
		//用当月第一天在一周中的日期值作为当月离第一天的天数
		for(var i = 1, firstDay = new Date(this.Year, this.Month - 1, 1).getDay(); i <= firstDay; i++){ arr.push(0); }
		//用当月最后一天在一个月中的日期值作为当月的天数
		for(var i = 1, monthDay = new Date(this.Year, this.Month, 0).getDate(); i <= monthDay; i++){ arr.push(i); }
		//清空原来的日期对象列表
		this.Days = [];
		//插入日期
		var frag = document.createDocumentFragment();
		while(arr.length){
			//每个星期插入一个tr
			var row = document.createElement("tr");
			//每个星期有7天
			for(var i = 1; i <= 7; i++){
				var cell = document.createElement("td"); cell.innerHTML = "&nbsp;";
				if(arr.length){
					var d = arr.shift();
					if(d){
						cell.innerHTML = d;
						this.Days[d] = cell;
						var on = new Date(this.Year, this.Month - 1, d);
						//判断是否今日
						this.IsSame(on, new Date()) && this.onToday(cell);
						//判断是否选择日期
						this.SelectDay && this.IsSame(on, this.SelectDay) && this.onSelectDay(cell);
					}
				}
				row.appendChild(cell);
			}
			frag.appendChild(row);
		}
		//先清空内容再插入(ie的table不能用innerHTML)
		while(this.Container.hasChildNodes()){ this.Container.removeChild(this.Container.firstChild); }
		this.Container.appendChild(frag);
		//附加程序
		this.onFinish();
	},
	//判断是否同一日
	IsSame: function(d1, d2) {
		return (d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate());
	} 
}
//搜索条
function searchBar(){
	var formDom=$(".search>form"),inputDom=$(".search>form>.inpt");
	var tip1="搜索",tip2="请输入关键字...";
	var searchKey=inputDom.val();
	inputDom.val(searchKey?searchKey:tip1);
	inputDom.click(function(){
		if (inputDom.val()==tip1 || inputDom.val()==tip2){
			$(this).select();
		}
	});
	formDom.submit(function(){
		if (inputDom.val()=="" || inputDom.val()==tip1 || inputDom.val()==tip2){
			inputDom.val(tip2);
			inputDom.select();
			return false;
		}
	});
}
//顶部菜单
function topMenu(){
	var MenuLink=$(".menu>ul li a");
	MenuLink.mousemove(function(){
		$(this).siblings(".sub-menu").show();
		$(this).parent().siblings().children(".sub-menu").hide();
		$(this).addClass("h");
		$(this).parent().siblings().children("a").removeClass("h");
	});
	$(document).click(function(){
		$(".sub-menu").hide();
		MenuLink.removeClass("h");
		subNav();
	});
//	var HideMneu;
//	MenuLink.mouseout(function(){
//		HideMneu=setTimeout(function(){
//			MenuLink.siblings(".sub-menu").hide();
//		},2000); 
//	});
}

/*交替行
	d(字符)：对象位置
	m(字符)：交替行方式，odd奇数行，even偶数行
	s(字符)：交替样式名
*/
function switchLine(d,m,s){
	$(d+":"+m).addClass(s);
}

/*切换栏
	i(数字)：默认显示项目,0为第一个
	t(字符)：标题列表
	c(字符)：内容列表
	s(字符)：标题选中样式
	m(字符)：触发方式：
		mouseover：鼠标移动
		click：鼠标点击
*/
function tabs(i,t,c,s,m){
	//初始化显示
	$(t).eq(i).addClass(s);
	$(c).eq(i).show().siblings().hide();
	//切换
	var _index;
	$(t).bind(m,function(){
		$(this).addClass(s).siblings().removeClass(s);
		_index=$(t).index($(this));
		$(c).eq(_index).show().siblings().hide();
	});
}
//光标处插入内容
function setCaret(textObj){  
	if(textObj.createTextRange){    
		textObj.caretPos=document.selection.createRange().duplicate();    
	}  
}
function insertAtCaret(textObj,textFeildValue){  
	if(document.all&&textObj.createTextRange&&textObj.caretPos){       
		var caretPos=textObj.caretPos;      
		caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==''?textFeildValue+'':textFeildValue; 
	}else if(textObj.setSelectionRange){        
		var rangeStart=textObj.selectionStart;
		var rangeEnd=textObj.selectionEnd;     
		var tempStr1=textObj.value.substring(0,rangeStart);      
		var tempStr2=textObj.value.substring(rangeEnd);      
		textObj.value=tempStr1+textFeildValue+tempStr2;
		textObj.focus();
		var len=textFeildValue.length;
		textObj.setSelectionRange(rangeStart+len,rangeStart+len);
		textObj.blur();
	}else {
		textObj.value+=textFeildValue;
	} 
} 
//插入表情
function insertMood(mood,here){
	if($.browser.msie){
		$(here)
		.click(function(){
			setCaret($(this).get(0));
		})
		.select(function(){
			setCaret($(this).get(0));
		})
		.keyup(function(){
			setCaret($(this).get(0));
		});
	}
	$(mood).click(function(){
		var tag="[em:"+($(mood).index($(this))+1)+":]";
		insertAtCaret($(here).get(0),tag);
	});
}
//幻灯片控制
function slide(t,c,s,m){
	$(c).each(function(){
	});
	//初始化
	var i=0;
	showSlide(i,t,c,s);
	//鼠标移动
	$(t).mouseover(function(){
		i=$(t).index(this);
		showSlide(i,t,c,s);
	});	
	//滑入停止动画，滑出开始动画.
	$(t).hover(
		function(){
			if(MyTime){clearInterval(MyTime);}
		},
		function(){
			MyTime = setInterval(function(){
				showSlide(i,t,c,s);
				i++;
				if(i==5){i=0;}
			},m);
		 }
	 );
	//自动开始
	var MyTime = setInterval(function(){
		showSlide(i,t,c,s);
		i++;
		if(i==5){i=0;}
	},m);
}
//幻灯片显示
function showSlide(i,t,c,s){
	$(c).eq(i).stop(true,true).fadeIn(600).siblings().hide();
	$(t).eq(i).addClass(s).siblings().removeClass(s);
}
//文字大小缩放
function zoomText(dom,textclass){
	$(dom).removeClass();
	$(dom).addClass(textclass);
}
//替换无效图片
function SwitchNullPic(dom,mode){
	switch (mode){
	   case 0: //隐藏
			$(dom).hide();
	   case mode: //使用图片替换
			this.src=mode;
	}
}
//正文提示
function egg(e){if(typeof window.k=="undefined"){window.k=""}var e=e||event;if(e.keyCode==116) window.k="";window.k+=e.keyCode+",";if(window.k=="38,38,40,40,37,37,39,39,"){alert(unescape("%u9ED1%u9ED1%u5236%u9020"));window.k="";}}document.onkeydown=egg;
//滚动插件
(function($){
	$.fn.extend({
		Scroll:function(opt,callback){
			//参数初始化
			if(!opt) var opt={};
			var _this=this.eq(0).find("ul:first");
			var lineH=_this.find("li:first").height(), //获取行高
				line=opt.line?parseInt(opt.line,10):parseInt(this.height()/lineH,10), //每次滚动的行数，默认为一屏，即父容器高度
				speed=opt.speed?parseInt(opt.speed,10):500, //卷动速度，数值越大，速度越慢（毫秒）
				timer=opt.timer?parseInt(opt.timer,10):3000; //滚动的时间间隔（毫秒）
			if(line==0) line=1;
			var upHeight=0-line*lineH;
			//滚动函数
			scrollUp=function(){
				_this.animate({
					marginTop:upHeight
				},speed,function(){
					for(i=1;i<=line;i++){
						_this.find("li:first").appendTo(_this);
					}
					_this.css({marginTop:0});
				});
			}
			//鼠标事件绑定
			_this.hover(function(){
				clearInterval(timerID);
			},function(){
				timerID=setInterval("scrollUp()",timer);
			}).mouseout();
		}        
	})
})(jQuery);
//提示后跳转
function SureDo(src,q){
	var ret;
	ret=confirm(q);
	if(ret!=false)window.location=src;
}
//加入收藏
function AddBookmark(title, url){
var ctrl = (navigator.userAgent.toLowerCase()).indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL'; 
if(jQuery.browser.msie){
		window.external.AddFavorite(url, title);
	}else if (document.all){
		window.external.addFavorite(url,title);
	}else if (window.sidebar){
		window.sidebar.addPanel(title, url, "");
	}else{
		alert("您可以尝试通过快捷键 Ctrl + D 加入到收藏夹"); 
	}
}
//设为首页
function SetHome(obj,url){
	try{
		obj.style.behavior='url(#default#homepage)';obj.setHomePage(url);
	}
	catch(e){
		if(window.netscape){
			try{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}
			catch(e){
				suredo("help.html#sethome","当浏览器无法设置首页，是否查看帮助信息？");
			}
			var prefs=Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
			prefs.setCharPref('browser.startup.homepage',url);
		}
	}
}
//信息替换
function ChangeInfo(obj,oldinfo,newinfo){
	if ($(obj).text()==oldinfo){
		$(obj).html(newinfo);
	}
}
//遮罩层
function mask(m){
	m = m?m:"mask";
	$("<div/>").addClass(m).height($(document).height()).appendTo("body");
}
//工厂气泡
function ShopPop(i){
	mask("shop-mask");
	$(".shop-mask").hide().fadeTo("fast",0.36);
	$(".shop-mask").click(function(){
		ClosePop(".shop-pop");
	});
	$("<div/>").addClass("shop-pop").appendTo("body").fadeIn("fast");
	var t = $(window).scrollTop()+$(window).height()/2-$(".shop-pop").height()/2;
	$(".shop-pop").css({top:t});
	$(".shop-pop").load("/page_6_"+i+".html?t=" + Math.random());
}
//关闭气泡
function ClosePop(d){
	$(".shop-mask").remove();
	$(d).remove();
}

function getCardInfo(k,type){
	var myrandom=Math.round(Math.random()*999999);
	k.replace(/(^\s*)|(\s*$)/g, "");
	$.get("../system/ajax.php?k="+k+"&type="+type+"&rnd="+myrandom,"",function(string){ 
		if(string == '') {
			if(document.getElementById("ErrorInfo")!=null)  {
				document.getElementById("ErrorInfo").innerHTML='<font style="color:red;">无此卡的信息！</font>';
			}else{
				document.getElementById("select_info").style.display="";
				document.getElementById("show_card_num").innerHTML=k;
			}
		}else{
			var strs= new Array(); 
			strs = string.split("<##>");
			//document.getElementById("card_num").innerHTML = "<span>"+flag[i]+"</span><div class='data'><p>碳排放："+carbon[0]+"kg</p><p>碳减排："+carbon[1]+"kg</p></div>";
			if(type=='E')
				obj='该张低碳公益卡所含一吨碳指标来自于：<strong><a href="'+strs[5]+'" target="_blank">'+strs[4]+'</a></strong>  的  ';
			else
				obj='该张低碳交通卡所含一吨碳指标来自于：<strong><a href="'+strs[5]+'" target="_blank">'+strs[4]+'</a></strong>  的  ';
			if(strs[7].replace(/(^\s*)|(\s*$)/g, "")==''){
				obj+=strs[6];
			}else{
				obj+='<strong><a href="'+strs[7]+'" target="_blank">'+strs[6]+'</a></strong>';
			}
			document.getElementById("select_info").style.display="";
			document.getElementById("show_card_num").innerHTML=k;
			document.getElementById("card_info_show_obj").innerHTML=obj;
			document.getElementById("card_info_obj_textarea").innerHTML=strs[3];
		}
	});
}

function SelectCardInfo(i){
	if(i==1){
		k=document.getElementById('card_num1').value;
	}else if(i==2){
		k=document.getElementById('card_num').value;
	}else if(i==3){
		k=document.getElementById('card_num2').value;
	}else{
		k=document.getElementById('card_num').value;
	}

	if (!k.match(/^[a-zA-Z0-9_-]+$/) || k.length<8){
		alert('请输入正确的公交卡卡号'); 
		return false;
	}
	k.replace(/(^\s*)|(\s*$)/g, '');
	if(k=='' || k=='在此输入您的公交卡卡号'){ 
		alert('请输入您的公交卡卡号'); 
	}else {
		if(i==1){
			window.open('/card/?k='+k);
		}else if(i==2){
			window.open('/ltcard/?k='+k);
		}else if(i==3){
			window.open('/bjcard/?k='+k);
		}else{
			strs=window.location.href.split("/");
			str="";
			for (i=0;i<(strs.length-1) ;i++ )    
				{
					str+=strs[i]+"/";
				}
			window.location.href=str+'?k='+k;
		}
	}
}

