﻿(function (j$) {
/*
 ****************************************************************************
 * File : jquery.ranking.js 2.22
 *
 * Copyright (C) 2005-2009 http://bizcaz.com/ All rights reserved.
 ****************************************************************************
 */
j$.fn.PageRank = function(opt) {
	opt = j$.extend({
		blog_id         : '1',           // ブログ ID
		blog_url        : 'http://thainomoto.jp/',           // ブログ URL
		script_url      : 'http://thainomoto.jp/common/pagerank/',           // ランキングスクリプトのアップロード先 URL
		include_all_logs: 0,            // 全ブログのログ情報取得(0:なし、1:取得)
		include_ref_logs: 0,            // リファラのログ情報取得(0:なし、1:取得)
		hide_rank       : 0,            // ロギングはするけど非表示(0:表示、1:非表示)
		page_name       : '',           // 任意のページ名称
		exclude_page    : 1,            // カレントページ除外フラグ(0:カウント、1:除外)
		exclude_top     : 1,            // トップページ除外フラグ(0:カウント、1:除外)
		ranking_max     : 10,           // ランキング表示数
		ranking_type    : 2,            // ランキング表示形式(0:非表示、1:カウンタ表示、2:パーセンテージ表示)
		enable_cookie   : 1,            // Cookie有効／無効フラグ(0:無効、1:有効)
		target          : '_blank'            // リンクのターゲット属性('_blank', '_self')
	}, 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 mode     = 0x01;
		var location = document.location.href.replace(/#.*/,'');

		location  = location.replace(/index.*$/,'');

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

		if (opt.exclude_page) mode |= 0x02;
		if (opt.exclude_top && opt.blog_url == location) mode |= 0x02;
		if (opt.include_ref_logs) mode = 0x40;
		if (opt.include_all_logs) mode = 0x80;

		var me = j$(this);
		var params = {
			blogid : opt.blog_id,
			blogurl: opt.blog_url,
			url    : encodeURI(location),
			title  : encodeURIComponent(opt.page_name),
			max    : opt.ranking_max,
			mode   : mode,
			referer: encodeURI(document.referrer)
		};

		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 record  = '';

			elem.push('<ul id="page_rank" class="widget_list">');

			for (var i = 0;json.count > i;i++) {
				record   = json.record[i].split('<>');

				elem.push(['<li class="widget_list_item list_entry rank_list_', (i + 1), clastbl[i % 2], '"><a title="', record[2], '" href="', record[1], '" target="', opt.target, '">', (i + 1), '. '].join(''));
				/*elem.push(['<li class="widget_list_item list_entry rank_list_', (i + 1), clastbl[i % 2], '"><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>'].join(''));
			/*elem.push(['</ul><div class="rank_info">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);

