var old = window.onload;
window.onload = function(){
	old();
	init();
}

function init(){
	var url = 'http://www.vivi-design.com/blog/MTTags.xml';
	var max = 20;
	new Ajax.Request(url, {
		method:'get',
		onComplete: function(res){
			var app = new TagApp(max);
			app.run(res);
		}
	});
}

var TagApp = Class.create();
TagApp.prototype = {
	initialize : function (max) {
		this.max_len = max;
	},
	run : function(res){
		var xmldoc = res.responseXML;
		var xml_tags = xmldoc.getElementsByTagName('tag');
		var len = (xml_tags.length > this.max_len) ? this.max_len : xml_tags.length;
		
		var entries = new Entries();
		entries.totalsum = xmldoc.getElementsByTagName('totalsum')[0].firstChild.data;
		
		for(var i = 0; i < len; i++){
			entries.add( new Entry(xml_tags[i]) );
		}
		//entries.sort_by_random();
		entries.sort_by_word();
		entries.func_each_entry(draw);
	}
}

function draw(data, max_count, min_count){
	
	var max_point = 18;
	var min_point = 9;
	var anc = document.createElement('a');
	anc.appendChild( document.createTextNode( data.word ) );
	anc.href = data.url;
	anc.title = 'このＴＡＧを含むエントリー：' + data.count + '件';
	
	var span = document.createElement('span');
	span.appendChild(anc);
	span.appendChild(document.createTextNode(' '));
	var f = (data.count - min_count ) /  (max_count - min_count) * (max_point - min_point) + min_point;
	span.style.fontSize = f + 'pt';
		
	document.getElementById('blogMenuTags').appendChild( span );
}

var Entries = Class.create();
Entries.prototype = {
	initialize : function () {
		this.entries = new Array();
	},
	add : function(entry){
		this.entries.push(entry);
	},
	length : function(){
		return this.entries.length;
	},
	max_count : function(){
		var cnt = 0;
		for (var i = 0; i < this.length(); i++) {
			if(this.entries[i].count > cnt){
				cnt = this.entries[i].count;
			}
		}
		return cnt;
	},
	min_count : function(){
		var cnt = 1;
		for (var i = 0; i < this.length(); i++) {
			if(this.entries[i].count < cnt){
				cnt = this.entries[i].count;
			}
		}
		return cnt;
	},
	func_each_entry : function(func){
		for (var i = 0; i < this.length(); i++) {
			func( this.entries[i], this.max_count(), this.min_count());
		}
	},
	sort_by_random : function(){
		this.entries.sort(func);
		function func(a,b) {
			return ( parseInt(b.sort) - parseInt(a.sort) );
		}
	},
	sort_by_word : function(){
		this.entries.sort(func);
		function func(a,b) {
			return (a.word > b.word) ? 1 : -1;
		}
	}
}

var Entry = Class.create();
Entry.prototype = {
	//初期化
	initialize : function (entry) {
		this.word 	= entry.getElementsByTagName('word')[0].firstChild.data;
		this.count	= entry.getElementsByTagName('count')[0].firstChild.data;
		this.url 	= entry.getElementsByTagName('url')[0].firstChild.data;
		this.sort	= Math.random() * 100;
	}
}
