var obj_votes   = { votes1:0 , votes2:0 };
var val         = { total:obj_votes.votes1 + obj_votes.votes2 };
var obj_percent = { percent1:0 , percent2:0 };

function setVotes(team, votes) {
        if (team == 1) {
            obj_votes.votes1 = votes;
        } else if (team == 2) {
            obj_votes.votes2 = votes;
        }
        setTotal();
}

function setPercent() {
        obj_percent.percent1 = val.total == 0 ? 50 : ((obj_votes.votes1 / val.total) * 100).toFixed(0);
        obj_percent.percent2 = val.total == 0 ? 50 : ((obj_votes.votes2 / val.total) * 100).toFixed(0);
}

function setTotal() {
        val.total = parseInt(obj_votes.votes1, 10) + parseInt(obj_votes.votes2, 10);
        setPercent();
}

function move() {
		var dist = $("#challengeBar").width() - obj_percent.percent1*3;
		
		var ease = (dist <= 0 ? "+=" + Math.abs(dist) : "-=" + Math.abs(dist)) + "px"; 
		
		$("#challengeBar").animate({width: ease}, getTimes);
		return false;
}

function getTimes() {
	return 1500;
};

function move2() {
	$("#votes1").text(obj_votes.votes1);
	$("#votes2").text(obj_votes.votes2);
		
	$("#percent1").text(obj_percent.percent1);
	$("#percent2").text(obj_percent.percent2);
	$("#totalVotes").text(val.total);
	if (parseInt(obj_votes.votes1, 10) > parseInt(obj_votes.votes2, 10)) {
			$("#crown1").html("<img src=\"images/crown.gif\" width=\"25\" height=\"19\" /><br />");
			$("#crown2").html("");
	} else if (parseInt(obj_votes.votes1, 10) < parseInt(obj_votes.votes2, 10)) {
			$("#crown1").html("");
			$("#crown2").html("<img src=\"images/crown.gif\" width=\"25\" height=\"19\" /><br />");
	} else {
			$("#crown1").html("");
			$("#crown2").html("");
	}
	
	move();
}

function  goVote(team, s) {
	if (s == '') {
			return;
	}
	$.ajax({
		type:"POST",
		url:"challengeVote.jsp",
		error: function(xhr) {
      		alert('投票失敗!!');
    	},
		data:{id: team, sn: s},
		success:goVoteCallback
	});
}

function goVoteCallback(response) {
	var _response = trim(response);
	if (_response != "") {
			var _array = _response.split(",");
			setVotes(1, _array[0]);
			setVotes(2, _array[1]);
			move2();
	}
	
	var winPop = window.open( "qa.jsp" , "vote" , "width=450 ,  height=350 , top= 100 , left=100 , toolbar=0, menubar=0, scrollbars=0, resizable=0,location=0, status=0");
	
	//winPop.focus();
	//MM_openBrWindow('qa.jsp','vote','width=450,height=350');
}

function check(f) {
    if (!f.name.value) {
        alert('請輸入姓名');
        f.name.focus();
    } else if (!f.email.value || !validEmail(f.email.value)) {
        alert('請輸入有效的E-Mail!!');
        f.email.focus();
    } else if (!f.password.value) {
        alert('請輸入驗證碼!!');
        f.password.focus();
    } else {
        f.submit();
    }
}

function validEmail(EMAIL) {
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return filter.test(EMAIL);
}


