﻿(function (j$) {
/*
 ****************************************************************************
 * File : jquery.ranking.js 2.20
 *
 * Copyright (C) 2005-2009 http://bizcaz.com/ All rights reserved.
 ****************************************************************************
 */
j$.fn.PageRank = function(opt) {
	opt = j$.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    : 2,            // ランキング表示形式(0:非表示、1:カウンタ表示、2:パーセンテージ表示)
		enable_cookie   : 1,            // Cookie有効／無効フラグ(0:無効、1:有効)
		target          : '',            // リンクのターゲット属性('_blank', '_self')
		enable_log      : 1         // ログ書き込みを行うかどうか (0:ログ書き込まない、1:ログ書き込む)
	}, opt || {});

	if ('' == opt.page_name) {
		var name_split = document.title.split('#');
		opt.page_name  = name_split[0];
	}

	opt.page_name = pagerank_espace(opt.page_name.replace(' - サイト名称', ''));
	opt.post_url  = [opt.script_url, 'rank_post.php'].join('');
	opt.loader    = [opt.script_url, 'ajax-loader.gif'].join('');

	this.each(function() {
		var include = 1;
		if (opt.exclude_page) include = 0;

		var location  = document.location.href.replace(/#.*/,'');
		var split_url = location.split('/');

		location  = location.replace(/index.*$/,'');
		if (opt.exclude_top && opt.blog_url == location) include = 0;

		if (opt.enable_cookie) {
			if (!check_cookie(location)) include = 0;
		}

		if (opt.include_all_logs) include = 128;

		var me = j$(this);
		var params = {blogid: opt.blog_id, url: encodeURI(location), title: encodeURIComponent(opt.page_name), max: opt.ranking_max, mode: include, enable_log:  opt.enable_log};

		if (!opt.hide_rank) ShowLoader(me, true);
		j$.getJSON(opt.post_url, params, function(json) {
			if (opt.hide_rank) return false;
			ShowLoader(me, false);

			var elem    = [];
			var clastbl = ['rank_list_eve', 'rank_list_odd'];
			var ranktbl = [' rank_list_1', ' rank_list_2', ' rank_list_3', ' rank_list_4', ' rank_list_5'];
			var record  = '';

			elem.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('<>');

				elem.push(['<li class="widget_list_item list_entry ', clastbl[i % 2], ranktbl[rank], '"><a title="', record[2], '" href="', record[1], '" target="', opt.target, '">'].join(''));

				if (opt.ranking_type) {
					if (2 == opt.ranking_type) {
						round = (record[0] / json.total) * 100;
						round = Math.round(round);
						val   = [round, '%'].join('');
					}
					else {
						val = record[0];
					}

					elem.push(['<span class="right">', val, '</span>'].join(''));
				}

				elem.push([record[2], '</a></li>'].join(''));
			}

			elem.push(['</ul><div class="rank_info" style="margin-top:1em">Range: ', json.from, '-', json.to, '<br />Count: ', json.total, '/', json.days, 'Days</div>'].join(''));
			me.html(elem.join(''));
		});
	});

	function ShowLoader(me, enable) {
		if (enable) {
			me.html('')
			  .show()
			  .css({'height':'100px', 'background':['transparent url(', opt.loader, ') no-repeat center center'].join('')});
		}
		else {
			me.css({'height':'auto', 'background':'none'});
		}
	};

	function pagerank_espace(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;
	};

	function set_cookie(name, value, expire) {
		expire = expire.toGMTString();

		var cookieval   = [escape(name), '=', escape(value), '; path=/; expires=', expire].join('');
		document.cookie = cookieval;
	};

	function get_cookie(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));
	};

	function get_datestr(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;
	};

	function check_cookie(name) {
		var now = new Date();
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);

		var str     = get_datestr(now);
		var expires = get_cookie(name);

		if (expires) {
			if (expires > str) return false;
		}

		now.setTime(now.getTime() + 1 * 24 * 60 * 60 * 1000);
		set_cookie(name, get_datestr(now), now);

		return true;
	};
};
}) (jQuery);

