/* 倒數計時器程式參考 http://dob.tnc.edu.tw/themes/old/showPage.php?s=82 
2008-1-2 自行修正已過時間的計算錯誤 */
var daysms = 24 * 60 * 60 * 1000
var hoursms = 60 * 60 * 1000
var Secondms = 60 * 1000
var microsecond = 1000
var passed=false;

function buZero(str,lenght){
	str = new String(str);
    if(str.length >= lenght)
        return str;
    else
        return buZero("0"+str,lenght);
}

function counter(goaldate, target){
	var time = new Date()
	var today = time.getTime()
	var Tday = new Date(goaldate);
	var Diffms = Tday.getTime() - today;
	
	if(Diffms<0){
		var passed=true;//倒數已過
		Diffms=Math.abs(Diffms);
		$("."+target+" .remain").text("已過");
	}
	
	var hugos = Math.floor(Diffms / microsecond);
	var D = Math.floor(Diffms / daysms)
	var days = D;/* if(passed && D!=0){ days = "-"+D;}*/
	
	if(days == 0){ 
		if(passed){ days="今";}else{ days="明";}
	}
	
	Diffms -= D * daysms
	var H = Math.floor(Diffms / hoursms)
	Diffms -= H * hoursms
	var M = Math.floor(Diffms / Secondms)
	Diffms -= M * Secondms
	var S = Math.floor(Diffms / microsecond)
	H=buZero(H, 2);M=buZero(M, 2);S=buZero(S, 2);
	
	//display
	title=$(".counters-widget."+target+" a.title").text();
	if(S%10>=5){
		$("."+target+" .days").text(days);
		$("."+target+" .hms").text("天"+H+":"+M+":"+S);
		$("."+target+" .days").after($("."+target+" .hms"));
	}else{
		$("."+target+" .days").text('秒');
		$("."+target+" .hms").text(hugos);
		$("."+target+" .days").before($("."+target+" .hms"));
	}
	if(S%5==0){
		/*$("."+target+" .countdown").toggle(500,function(){
			$("."+target+" .countdown").toggle(500);
		});*/
	}
	
	//resize
	if( title.length > 8){
		$(".counters-widget."+target+" a.title").css('font-size','11pt');
		$(".counters-widget."+target+" p.title").css({'padding-top':'0px','height':'27px'});
	}
}

function collect(id, action){
	$.get("ajax/collect.php", {
		id: id, action: action
	}, function(data) {
		if(data==1){
			//alert('收藏成功！請到「我的倒數」檢視收藏');
			$.scrollTo('#menu',1000);
			$('.counters-widget.w'+id).effect('transfer',{ to: $('#nav_my')},1000, function(){
				$('#nav_my').effect('highlight', 1000);
			});
			if(myphp) $('#mynotice').html('您已變更收藏，請按<input type="button" value="重新整理" onClick="location.reload()" />').fadeIn(2000);
		}else if(data==2){
			//alert('收藏變更成功！請重新載入「我的倒數」檢視收藏項目');
			$('.counters-widget.c'+id).hide(2000);
		}else if(data==-1)
			alert('您已收藏過此倒數');
		else 
			alert('請先登入本站，才可收藏我的倒數');
	} );
}
