﻿/*
 ****************************************************************************
 * File : prototype.ranking.js 2.16
 *
 * Copyright (C) 2005-2009 http://bizcaz.com/ All rights reserved.
 ****************************************************************************
 */
var PageRank = Class.create({
	initialize: function(elem, opt) {
		this.opt = Object.extend({
			blog_id         : '',// ブログ ID(必須)
			blog_url        : '',// ブログ URL(必須)
			script_url      : '',// ランキングスクリプトのアップロード先 URL(必須)
			include_all_logs: 0, // 全ブログのログ情報取得(0:なし、1:取得)
			hide_rank       : 0, // ロギングはするけど非表示(0:表示、1:非表示)
			page_name       : '',// 任意のページ名称
			exclude_page    : 0, // カレントページ除外フラグ(0:カウント、1:除外)
			exclude_top     : 1, // トップページ除外フラグ(0:カウント、1:除外)
			ranking_max     : 10,// ランキング表示数
			ranking_type    : 1, // ランキング表示形式(0:非表示、1:カウンタ表示、2:パーセンテージ表示)
			enable_cookie   : 1, // Cookie有効／無効フラグ(0:無効、1:有効)
			target          : '' // リンクのターゲット属性('_blank', '_self')
		}, opt || {});

		var op = this.opt;

		if ('' == op.page_name) {
			var name_split = document.title.split('#');
			op.page_name  = name_split[0];
		}

		op.page_name = this.pagerank_espace(op.page_name.replace(' - サイト名称', ''));
		op.elem      = $(elem);
		op.post_url  = [op.script_url, 'rank_post.php'].join('');
		op.loader    = [op.script_url, 'ajax-loader.gif'].join('');
		this.post($(this));
	},
	post: function(me) {
		var op      = me.opt;
		var include = 1;

		if (op.exclude_page) include = 0;

		var location  = document.location.href.replace(/#.*/,'');
		var split_url = location.split('/');

		location  = location.replace(/index.*$/,'');
		if (op.exclude_top && op.blog_url == location) include = 0;

		if (op.enable_cookie) {
			if (!me.check_cookie(location)) include = 0;
		}

		if (op.include_all_logs) include = 128;

		var params = {
			blogid : op.blog_id,
			url    : encodeURI(location),
			title  : encodeURIComponent(op.page_name),
			max    : op.ranking_max,
			mode   : include,
			referer: encodeURI(document.referrer)
		};

		if (!op.hide_rank) me.show_loader(true);
		new Ajax.Request(op.post_url, {
			method    : 'post',
			parameters: params,
			onSuccess : function(req) {
				if (op.hide_rank) return false;
				me.show_loader(false);

				var json    = req.responseText.evalJSON();
				var out     = [];
				var clastbl = [' rank_list_eve', ' rank_list_odd'];
				var ranktbl = [' rank_list_1st', ' rank_list_2nd', ' rank_list_3rd', ' rank_list_4th', ' rank_list_5th', ''];
				var record  = '';

				out.push('<ul id="page_rank" class="widget_list">');

				for (var i = 0;json.count > i;i++) {
					var rank = 5;
					if (5 > i) rank = i;
					record   = json.record[i].split('<>');

					out.push(['<li class="widget_list_item list_entry', clastbl[i % 2], ranktbl[rank], '"><a title="', record[2], '" href="', record[1], '" target="', op.target, '">'].join(''));

					if (op.ranking_type) {
						if (2 == op.ranking_type) {
							round = (record[0] / json.total) * 100;
							round = Math.round(round);
							val   = [round, '%'].join('');
						}
						else {
							val = record[0];
						}

						out.push(['<span class="right">', val, '</span>'].join(''));
					}

					out.push([record[2], '</a></li>'].join(''));
				}

				out.push(['</ul><div class="rank_info">期間: ', json.from, '-', json.to, '<br />ヒット数: ', json.total, '/', json.days, '日</div>'].join(''));
				op.elem.innerHTML = out.join('');
			}
		});
	},
	show_loader: function(enable) {
		var elem = this.opt.elem;

		if (enable) {
			elem.innerHTML        = '';
			elem.style.display    = '';
			elem.style.height     = '100px';
			elem.style.background = ['transparent url(', this.opt.loader, ') no-repeat center center'].join('');
		}
		else {
			elem.style.height     = 'auto';
			elem.style.background = 'none';
		}
	},
	pagerank_espace: function(text) {
		text = text.split("&").join("&amp;" );
		text = text.split("<").join("&lt;"  );
		text = text.split(">").join("&gt;"  );
		text = text.split('"').join("&quot;");
		text = text.split("{").join("&#123;");
		text = text.split("}").join("&#125;");
		text = text.split("'").join("&#039;");
		return text;
	},
	set_cookie: function(name, value, expire) {
		expire = expire.toGMTString();

		var cookieval   = [escape(name), '=', escape(value), '; path=/; expires=', expire].join('');
		document.cookie = cookieval;
	},
	get_cookie: function(name) {
		var prefix           = [escape(name), '='].join('');
		var c                = document.cookie;
		var nullstring       = '';
		var cookieStartIndex = c.indexOf(prefix);

		if (-1 == cookieStartIndex) return nullstring;
		var cookieEndIndex = c.indexOf(';', cookieStartIndex + prefix.length);
		if (-1 == cookieEndIndex) cookieEndIndex = c.length;
		return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
	},
	get_datestr: function(date) {
		var yy  = date.getYear();      if (yy < 1900) { yy += 1900;               }
		var mm  = date.getMonth() + 1; if (mm <   10) { mm  = ['0', mm].join(''); }
		var dd  = date.getDate();      if (dd <   10) { dd  = ['0', dd].join(''); }
		var str = [yy, mm, dd].join('');
		return str;
	},
	check_cookie: function(name) {
		var now = new Date();
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);

		var str     = this.get_datestr(now);
		var expires = this.get_cookie(name);

		if (expires) {
			if (expires > str) return false;
		}

		now.setTime(now.getTime() + 1 * 24 * 60 * 60 * 1000);
		this.set_cookie(name, this.get_datestr(now), now);

		return true;
	}
});
