/*
 * listAjax.js
 * csvで記載されたニュースデータを読み込み、リスト表示
 * by Hidemaro Mukai (maro@mother.co.jp)
 * Copyright (c) 2009 Mother inc.
 */
var TAB = String.fromCharCode(9);
var CR = String.fromCharCode(13);
var LF = String.fromCharCode(10);
var listType = {1: "news", 2: "event"};
function getData(url, success, error){
	$.ajax({
		type: "GET",
		url: url,
		cache: false,
		success: function(recv){
			recv = recv.split(CR+LF).join(LF);
  			recv = recv.split(CR).join(LF);
  			recv = recv.split(LF);
  			success(recv);
		},
		error: error
	});
}
function homeInit(){
	$(".listTable").html('<tr><td>Loading...</td></tr>');
	getData("./news_data/c_home_list.txt", 
	function(rows){
		var i;
		var cols;
		var id;
		var c = new Object();
		for(i in listType){
			c[i] = 0;
		}
		$(".listTable").empty();
		for (i=0;i<rows.length;i++){
			cols = rows[i].split(TAB);
			id = cols.shift();
			if (addLine($("#"+listType[id]+"Table"), cols)) c[id]++;
		}
		for(i in c){
			if (c[i] == 0) $("#"+listType[i]+"Table").html('<li style="margin-top:20px;margin-bottom:20px">該当する記事はありません。</li>');
		}
	}, 
	function(){
		for(i in listType){
			$("#"+listType[i]+"Table").html('<li style="margin-top:20px;margin-bottom:20px">エラーにより記事を表示できません。</li>');
		}
	});
}
function listInit(id){
	getData("../news_data/c_news_history.txt", 
	function(rows){
		var i;
		var cols;
		var cY = 0;
		var c = 0;
		for (i=0;i<rows.length;i++){
			cols = rows[i].split(TAB);
			if (cols[0] != id) continue;
			$(".selYear").append('<option>'+cols[1]+'</option>');
			if (cY < cols[1]) cY = cols[1];
			c++;
		}
		if (c == 0){
			$("#listTable").html('<li style="margin-top:20px;margin-bottom:20px">エラーにより記事を表示できません。</li>');
			return false;
		}
		listRead(id, cY);
		$(".selYear").change(function(){
			if ($(this).val() == "0") return false;
			listRead(id, $(this).val());
		});
	}, 
	function(){
		$("#listTable").html('<li style="margin-top:20px;margin-bottom:20px">エラーにより記事を表示できません。</li>');
	});
}
function listRead(id, year){
	$(".selYear").val("0");
	if (year == $("#currentYear").html()) return false;
	$("#listTable").html('<tr><td>Loading...</td></tr>');
	$("#currentYear").html(year);
	getData("../news_data/c_"+listType[id]+"_list_"+year+".txt", 
	function(rows){
		var i;
		var cols;
		var c = 0;
		$("#listTable").empty();
		for (i=0;i<rows.length;i++){
			cols = rows[i].split(TAB);
			if (addLine($("#listTable"), cols)) c++;
		}
		if (c == 0) $("#listTable").html('<li style="margin-top:20px;margin-bottom:20px">該当する記事はありません。</li>');
	}, 
	function(){
		$("#listTable").html('<li style="margin-top:20px;margin-bottom:20px">エラーにより記事を表示できません。</li>');
	});
}
function addLine(tg, cols){
	if (cols[0] == "") return false;
	var str = '<li>'+cols[1]+'<span> ／</span><a href="'+cols[4]+'"';
	if (cols[5] == "1"){
		str += 'target="_blank"';
	}
	str += '>'+cols[2];
	if (cols[3] == "1"){
		str += '<em> NEW</em>';
	}
	str += '</a></li>';
	tg.append(str);
	return true;
}
