var xmlPath = '';
var latestTheme = '';
var latestThemeKey = '';
var gtPath = 'http://'+location.hostname+'/sgm/common/php/getLatestTheme.php';
var votePath = 'http://'+location.hostname+'/sgm/common/php/rateSinglePost.php';

var count = new Number(0);
var idArr = new Array();
var titleArr = new Array();
var sum =new Number(0);

function sgmSimpleVote(){
	var num = $(".sgmEntries:checked").val();
	var item = $(".sgmEntries:checked").attr('id');

	var id = Number(num);
	//var encItem = encodeURI(item);
	var ref = location.hostname;
	var id = Number(num);
	var preBake = $.cookie('sgmPre');
	var primeCookieName = 'voted'+id;
	primeCookie = ($.cookie(primeCookieName) != null || $.cookie(primeCookieName) != '') ? Number($.cookie(primeCookieName)) : new Number(0);

	responseTrue = function(text){
		var aReg = new RegExp('allow');
		if(text.match(aReg)){
			sum +=1;
			window.alert('「'+item+'」に投票ありがとうございます！\n「コメント」投稿者には毎週ステキなプレゼントをご用意していますので、\n是非、引き続き「コメント」を投稿して下さい。');
			$.cookie(primeCookieName,primeCookie+1,{ expires: 1, path: '/' });
			$.cookie('sgmVoted',id,{ path: '/' });
		}else{
			window.alert('Err!');
		}
	}

	if(num == '' || num == null || num == undefined){
		window.alert('投票項目が選択されていません！');
	}else if(preBake != 1){
		window.alert('ブラウザのクッキーが有効になっていないようです。\nクッキーを有効にして下さい。');
	}else if(primeCookie>2){
		window.alert('1つのノミネートに対する投票の限度を越えました。');
	}else{
		$.ajax({url:votePath,type:'get',dataType:'text',cache:false,data:{'entryid':id},success:responseTrue});
	}
}

function getEntryList(){
	var listPath = 'http://'+location.hostname+'/sgm/'+latestThemeKey+'/list.xml';
	var result = '';

	resultDisplay = function(){
		$("#theme").html(latestTheme);
		$("#entries").html(result);
		$("#entries").show("slow");
	},

	listArranging = function(XML){
		latestTheme = $(XML).find("Theme").text();
		$(XML).find("Entry").each(function(){
			idArr.push($(this).find("ID").text());
			titleArr.push($(this).find("Title").text());
			count++;
		});
		
		for(i=0;i<count;i++){
			result += '		<li><input type="radio" id="'+titleArr[i]+'" name="voteSelect" class="sgmEntries" value="'+idArr[i]+'" />'+titleArr[i]+'</li>';
		}
		resultDisplay();
	}


	$.get(listPath,function(XML){
		listArranging(XML);
	});
}

function getLatestTheme(){
	$.get(gtPath,{key:'mg'},function(txt){
		latestThemeKey = txt;
		getEntryList();
	});
}

function preBaking(){
	$.cookie('sgmPre','1',{ path: '/' });
}


jQuery.event.add(window,"load",function(){
	getLatestTheme();
	preBaking();
});