var random = function (lst) {
	return lst[parseInt(Math.random() * (lst.length - 1))];
};

var uniq = function (lst) {
	var results = [];

	var i, value, store = {};
	for (i = 0; i < lst.length; i += 1) {
		value = lst[i];

		if (!(value in store)) {
			store[value] = true;
			results.push(value);
		}
	}

	return results;
};

var map = function (proc, lst) {
	var results = [];

	var i, length = lst.length;
	for (i = 0; i < length; i += 1) {
		results.push(proc(lst[i]));
	}

	return results;
};

var filter = function (predicate, lst) {
	var results = [];

	var i, element, length = lst.length;
	for (i = 0; i < length; i += 1) {
		element = lst[i];

		if (predicate(element)) {
			results.push(element);
		}
	}

	return results;
};

var puts = function (msg) {
	document.writeln(msg);
};

var getComment = function (str) {
	var results = [];

	str = str.replace(/\n/g, '');	
	str = str.match(/<!--.*-->/g).toString();
	str = str.replace(/<!--|\/\//g, '');

	var i, lst = str.split(/-->/);
	for (i = 0; i < lst.length; i += 1) {
		if (lst[i] !== '') {
			results.push(lst[i].replace(/^\s+/, '').replace(/\s+$/, ''));
		}
	}

	return results;
};

var getXMLDocument = function (path) {
	return (function () {
		var doc = null;

		var d = null;
		var err = 'Error handling XMLHttpRequest request.';
		try {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = false;
				doc.load(path);
			} else if (window.XMLHttpRequest) {
				d = new XMLHttpRequest();
				d.open('GET', path, false);
				d.send(null);
				doc = d.responseXML;
			} else {
				doc = document.implementation.createDocument('', '', null);
				doc.async = false;
				doc.load(path);
			}
		} catch (e) {
			puts(err);
		}

		return doc;
	})();
};

(function () {
	var dom_id = 'iptc_category';
	var path = 'http://www.47news.jp/47topics/xml/';
	var feature = random([
		{
			id: 'gmen47',
			name: '特集',
			title: 'Gメン４７',
			link: 'http://www.47news.jp/culture/47gmen/'
		},
		{
			id: 'gmen47',
			name: '特集',
			title: 'Gメン日報',
			link: 'http://www.47news.jp/culture/47gmen/dailyreport/'
		},
		{
			id: 'gmen47',
			name: '特集',
			title: 'ただいま広辞中',
			link: 'http://www.47news.jp/culture/47gmen/kojichu/'
		},
		{
			id: 'gmen47',
			name: '特集',
			title: 'AKB48',
			link: 'http://www.47news.jp/culture/47gmen/akb48/'
		},
		{
			id: 'gmen47',
			name: '特集',
			title: '石井裕也監督特集',
			link: 'http://www.47news.jp/culture/47gmen/ishiiyuya/'
		}
	]);

	var nankyoku = {
			id: 'nankyoku',
			name: '特集',
			title: '緊迫日中関係',
			link: 'http://www.47news.jp/47topics/e/181092.php'
		};
	var pauru = {
			id: 'pauru',
			name: '特集',
			title: '動画古瀬絵里いっしょに山ガール',
			link: 'http://www.47news.jp/culture/yamagirl/'
		};

	var comments = getComment(document.body.innerHTML.toString());

	// Get IptcCategory
	var categories = (function () {
		var results = [];

		var i, j, category, lst = [];
		for (i = 0; i < comments.length; i += 1) {
			if (comments[i].match(/IptcCategory/g)) {
				category = comments[i];
				category = category.replace(/IptcCategory\(/, '');
				category = category.replace(/\)/, '');
				lst = uniq(category.split(/,/));

				for (j = 0; j < lst.length; j += 1) {
					if ((lst[j]) && (lst[j].match(/\d+/g))) {
						results.push(lst[j]);
					}
				}

				break;
			}
		}
		return results;
	})();

	if (categories.length > 0) {
		// Get XML documents by IptcCategory
		var docs = (function () {
			return map(function (file) {
				return (getXMLDocument(file));
			}, uniq(map(function (category) {
				return path + category.substr(0, 2) + '.xml';
			}, categories)));
		})();

		// Get articles from any categories
		var articles = (function () {
			var results = [];

			map(function (doc) {
				var i, j, k, cats = doc.getElementsByTagName('category');
				var id, name, entries, title, link;

				// Get expected categories
				var ids = filter(function (category) {
					return category.substr(0, 2) === (function () {
						var node = cats[0].getElementsByTagName('id')[0];
						var val = node.childNodes[0].nodeValue;
						return val.substr(0, 2);
					})();
				}, categories);

				// Parse XML document
				for (i = 0; i < cats.length; i += 1) {
					id = cats[i].getElementsByTagName('id')[0];

					for (j = 0; j < ids.length; j += 1) {
						if (id.childNodes[0].nodeValue === ids[j]) {
							name = cats[i].getElementsByTagName('name')[0];
							entries = cats[i].getElementsByTagName('article');

							k = parseInt(Math.random() * (entries.length - 1));
							try {
								title = entries[k].getElementsByTagName('title')[0];
								link = entries[k].getElementsByTagName('link')[0];

								if (title && link) {
									results.push({
										id: id.childNodes[0].nodeValue,
										name: name.childNodes[0].nodeValue,
										title: title.childNodes[0].nodeValue,
										link: link.childNodes[0].nodeValue
									});
								}
							} catch (e) {}
						}
					}
				}
			}, docs);

			return results;
		})();

		// Remove repetition
		var new_articles = map(function (article) {
			var lst = article.split(/:sp:/);
			return {
				id: lst[0],
				name: lst[1],
				title: lst[2],
				link: lst[3]
			};
		}, uniq(map(function (obj) {
			// ':sp:' is field separator
			return obj.id + ':sp:' + obj.name + ':sp:' + obj.title + ':sp:' + obj.link;
		}, articles)));
		new_articles.push(pauru);
		new_articles.push(feature);

		(function () {
			var txt = '<div class="newsPhoto"><B>特集ページ</B></div>';
			txt += '<div style="width:644px;padding-left:5px;padding-right:5px;">';
			txt += '<table>';

			var cnt = 0;
			for (var i = 0; i < new_articles.length; i += 1) {
				if ((cnt % 2) === 0) {
					txt += '<tr>';

					txt += '<td width="32px" height="32px" align="left" valign="middle">';
					txt += '<img src="http://img.47news.jp/47topics/icons/';
					txt +=  new_articles[i].id;
					txt += '.jpg" width="32px" height="32px" />';
					txt += '</td>';

					txt += '<td width="300px" height="32px" align="left" valign="middle">';
					txt += '<a href="' + new_articles[i].link + '">';
					txt += new_articles[i].title;
					txt += '</a>';
					txt += '</td>';
				} else {
					txt += '<td width="32px" height="32px" align="left" valign="middle">';
					txt += '<img src="http://img.47news.jp/47topics/icons/';
					txt +=  new_articles[i].id;
					txt += '.jpg" width="32px" height="32px" />';
					txt += '</td>';

					txt += '<td width="300px" height="32px" align="left" valign="middle">';
					txt += '<a href="' + new_articles[i].link + '">';
					txt += new_articles[i].title;
					txt += '</a>';
					txt += '</td>';

					txt += '</tr>';
				}
				cnt += 1;
			}

			txt += '</table>';
			txt += '</div>';
			//puts(txt);
			document.getElementById(dom_id).innerHTML = txt;
		})();
	}
})();

