

/* ----------------------------------------------------- */


var CBMyList = {};

CBMyList.swf = null;



/* ----------------------------------------------------- */
/**
 * 
 * @class
 * @constructor
 */
CBMyList.Viewer = function(boxId, btnId) {
	var _this = this;
	this.boxId   = boxId;
	this.btnId   = btnId;
	this.showFlg = false;
	this.startTimerID = null;

	this.tmplFavBox = ''
						+'<div id="fav-box">'
						+'	<div id="fav-header" class="iepngfix">'
						+'		<div id="fav-logo">'
						+'			<img src="/common/images/fav_logo.gif" alt="ちばぎんマイリスト" height="34" width="187" />'
						+'		</div>'
						+'		<div id="fav-btn-add">'
						+'			<a href="#"><img src="/common/images/fav_bt001.gif" alt="表示中のページをリストに追加" height="23" width="175" /></a>'
						+'		</div>'
						+'	<!-- /fav-header --></div>'
						+'	<div id="fav-body" class="iepngfix">'
						+'		<p class="lead">ちばぎんマイリストは自分のお気に入りのページを<span class="bold">最大5件</span>までストックしておくことができる便利なサービスです。</p>'
						+'		<ul id="fav-item-list"><li></li>'
						+'		</ul>'
						+'		<div id="fav-utility-block">'
						+'			<div id="fav-btn-use">'
						+'				<a href="/sitepolicy/mylist/" target="_blank"><img src="/common/images/fav_bt003.gif" alt="「ちばぎんマイリスト」の使い方" height="15" width="180" /></a>'
						+'			</div>'
						+'			<ul>'
						+'				<li class="win-icon"><a href="/sitepolicy/" target="_blank">ホームページのご利用にあたって<img src="/common/images/com_ic004.gif" alt="" height="7" width="8" /></a></li>'
						+'			</ul>'
						+'		</div>'
						+'	<!-- /fav-body --></div>'
						+'	<div id="fav-footer" class="iepngfix">'
						+'		<div id="fav-btn-close">'
						+'			<a href="#"><img src="/common/images/fav_bt004.gif" alt="閉じる" height="20" width="523" /></a>'
						+'		</div>'
						+'	<!-- /fav-footer --></div>'
						+'<!-- /fav-box --></div>';

	this.tmplItem = ''
						+'			<li class="item item-${category}" id="item-${id}">'
						+'			<div class="item-wrap">'
						+'				<div class="item-main">'
						+'					<div class="item-title"><a href="${url}">${title}</a></div>'
						+'				</div>'
						+'				<div class="item-btn-del"><a href="javascript:void(0);"><img src="/common/images/fav_bt002.gif" alt="削除" height="18" width="45" /></a></div>'
						+'				<div class="item-description">${description}</div>'
						+'			</div>'
						+'			</li>';


	this.dm = new CBMyList.DataManager();

	this.startTimerID = setTimeout(function(){
		_this.init();
	}, 100);
}


/** 初期化処理 */
CBMyList.Viewer.prototype.init = function() {
	var charset = (document.characterSet)? document.characterSet : document.charset;
	if (location.protocol.match(/https:/) || !charset.match(/utf-8/i)) return;
//	if (location.pathname.match(/^\/virtual\//) || path.match(/^\/kids\//)) return;

	// 
	$("body").append(this.tmplFavBox);
	this.setEvent();
}


/** 各ボタン・パーツに対してイベントを設定 */
CBMyList.Viewer.prototype.setEvent = function() {
	var _this = this;

	this.dm.init();

	// ちばぎんマイリストボタン
	$("#"+this.btnId).click(function(){
		_this.toggle();
	});

	// 追加ボタン
	$("#fav-btn-add").click(function(){
		var res = _this.dm.add();
		if (typeof res == 'boolean' && res == true) {
			_this.updateList();
		}
		else if (typeof res == 'string') {
			alert(res);
			_this.updateList();
		}
		return false;
	});

	// 閉じるボタン
	$("#fav-btn-close").click(function(){
		_this.hide();
		return false;
	});

	// 各削除ボタン
	$("#fav-item-list .item-btn-del").live("click", function() {
		var btn = this;
		var itemNode = (function(node) {
			var nodeId = $(node).attr("id");
			return (nodeId && nodeId.match(/item-(.+)/)) ?
				node : 
				(node.parentNode) ? 
					arguments.callee(node.parentNode) : 
					null;
		})(btn);

		if (itemNode) {
			var delItemId = $(itemNode).attr("id").split("-")[1];
			_this.dm.remove(delItemId);
			_this.updateList();
		}

		return false;
	});


	// ウィンドウ・リサイズ時
	$(window).resize(function() {
		_this.setPosition(_this.boxId);
	});


	// リストデータの初期化
	this.updateList();

	// ボタン表示
	$("#favorite-registration").css({"display":"none"});
	$("#favorite-registration").css({"visibility":"visible"});
	$("#favorite-registration").fadeIn("fast");
}


/** ボックス表示・非表示 */
CBMyList.Viewer.prototype.toggle = function() {
	if (this.showFlg) {
		this.hide();
	}
	else {
		this.show();
	}
}
CBMyList.Viewer.prototype.show = function() {
	if (!this.showFlg) {
		this.showFlg = true;
		this.setPosition(this.boxId);
		$("#"+this.boxId).show();
	}
}
CBMyList.Viewer.prototype.hide = function() {
	if (this.showFlg) {
		this.showFlg = false;
		$("#"+this.boxId).hide();
	}
}

/**  */
CBMyList.Viewer.prototype.asort = function(arr,key) {
	return arr.sort(function(a,b){
		return (a[key] > b[key])? 1 : -1;
	})
}

/** リスト更新し、テンプレにデータを適用 */
CBMyList.Viewer.prototype.updateList = function() {
	var list = [];
	var html = [];

	list = this.dm.getAll();

	// idをキーとしてソート
	list = this.asort(list, "key").reverse();

	if (list.length) {
		for (var i=0,len=list.length; i<len; i++){
			var id = list[i].key;
			var item = list[i].value;////
			var tmpl = this.tmplItem;
			for( var key in item ){
				tmpl = tmpl.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), item[key]);
				tmpl = tmpl.replace(new RegExp('\\$\\{id\\}', 'g'), id);
			}
			html.push(tmpl);
		}
	}
	$("#fav-item-list").html(html.join(""));
}



/* ----------------------------------------------------- */

// マイリストボタン付近にレイヤー表示
CBMyList.Viewer.prototype.setPosition = function(id) {
	var _this = this;
	var frameSize = this.getContentSize(id);
	var winSize   = this.getWindowSize();
	var scrollPos = this.getScrollOffset();

	/** 画面中央に配置する場合
	var popLeft = scrollPos.x + parseInt(( winSize.width - frameSize.width )/2,10);
	var popTop = ( winSize.height < frameSize.height )? 
					scrollPos.y + 1 :
					scrollPos.y + parseInt( (winSize.height - frameSize.height)/2, 10 );
	*/

	var offset = $("#"+this.btnId).offset();
	popTop  = offset.top + 20;
	popLeft = offset.left - 415;

	$("#"+id).css({
		'left':popLeft+'px',
		'top':popTop+'px'
	});
}

// 内容物のサイズを取得
CBMyList.Viewer.prototype.getContentSize = function(id) {
	var el = document.getElementById(id);
	var els = el.style;
	var origVis  = els.visibility;
	var origPos  = els.position;
	var origDisp = els.display;
	$(el).css({
		'visibility': 'hidden',
		'position'  : 'absolute',
		'display'   : 'block'
	});
	var w = el.clientWidth;
	var h = el.clientHeight;

	// サイズを取得したら元に戻す
	$(el).css({
		'visibility': origVis,
		'position'  : origPos,
		'display'   : origDisp
	});

	return {
		width:  w,
		height: h
	};
}

// ウィンドウサイズ
CBMyList.Viewer.prototype.getWindowSize = function(id) {
	var offset = new Object();
	var w  = window;
	var de = document.documentElement;
	var db = document.body;
	return {
		width:  (w.innerWidth  || de.clientWidth  || db.clientWidth  || 0),
		height: (w.innerHeight || de.clientHeight || db.clientHeight || 0)
	};
}

// スクロールのオフセット値
CBMyList.Viewer.prototype.getScrollOffset = function() {
	var offset = new Object();
	var w  = window;
	var de = document.documentElement;
	var db = document.body;
	return {
		x: (w.pageXOffset || de.scrollLeft || db.scrollLeft || 0),
		y: (w.pageYOffset || de.scrollTop  || db.scrollTop  || 0)
	};
}




/* ----------------------------------------------------- */
/* ----------------------------------------------------- */
/**
 * データ管理
 * @class
 * @constructor
 */
CBMyList.DataManager = function() {
	this.so = CBMyList.swf;

	this.currentData = [];// {key: "",value: ""}を格納
	this.length;
	this.maxLength= 5;

	//this.lastIdNumber = null;
	//this.init();
}

/**
 * 初期化処理
 * @function
 */
CBMyList.DataManager.prototype.init = function() {
	this.getAllData();
}


/**
 * 全件分のデータを取得
 * @function
 */
CBMyList.DataManager.prototype.getAllData = function() {
	var dataAll = this.so.getAll();
	this.currentData = [];
	for (var id in dataAll) {
		var obj = {
			key   : parseInt(id),
			value : dataAll[id]
		}
		this.currentData.push(obj);
	}
}


/**
 * 1件分のデータを追加
 * @function
 */
CBMyList.DataManager.prototype.add = function() {
	this.getAllData();
	if (!this.isMaxLength()) {
		var obj = this.getPageInfo();
		if (!this.hasDataByURL(obj.value.url)) {
			// JS, SharedObjectにそれぞれ追加
			this.currentData.push(obj);
			this.so.add(obj.key, obj.value);
			return true;
		}
		else {
			this.getAllData();
			// 既に登録済み
			return "このページは既に登録されています。";
		}
	}
	else {
		this.getAllData();
		// 既に5件分登録済み
		return "最大登録件数5件が登録されています。\n登録されたページをどれか削除の上、再度登録ください。";
	}
}

/**
 * 全件分のデータを返す
 * @function
 * return {Array}
 */
CBMyList.DataManager.prototype.getAll = function() {
	return this.currentData;
}

/**
 * 登録するページ情報を取得
 * @function
 * return {Object} 
 */
CBMyList.DataManager.prototype.getPageInfo = function() {
	var _this = this;
	var id = this.getLastIdNumber() + 1;
	var title_delimiter = "&#65372;";

	var data = {
		"title"       : document.title.split("\uFF5C")[0],
		"url"         : location.pathname.split(/index\.htm[l]?$/)[0],
		"description" : $("meta:[name^='description']").attr("content").split("\u3002")[0]+"\u3002",
		"category"    : this.getPageCategoryInfo()
	};
	return {
		key   : id,
		value : data
	}
}

/**
 * 
 * @function
 * return {Number}
 */
CBMyList.DataManager.prototype.getLastIdNumber = function() {
	var ret = null;
	for (var id in this.currentData) {
		var tmp = this.currentData[id].key;
		ret = (!ret)? tmp : 
				(tmp > ret)? tmp : ret;
	}
	if (!ret) ret = 1;
	return parseInt(ret);
}

/**
 * 登録するページのカテゴリーを取得
 * @function
 * return {String}
 */
CBMyList.DataManager.prototype.getPageCategoryInfo = function() {
	var cat = "";
	var path = location.pathname;

	cat =   (path.match(/\/kojin\/account/))?       "a1" : 
			(path.match(/\/kojin\/saving/))?        "a2" : 
			(path.match(/\/kojin\/loan/))?          "a3" : 
			(path.match(/\/kojin\/insurance/))?     "a4" : 
			(path.match(/\/kojin\/convenience/))?   "a5" : 
			(path.match(/\/myaccess/))?             "a5" : 
			(path.match(/\/kojin\/service/))?       "a6" : 
			(path.match(/\/kojin\/conference/))?    "a7" : 
			(path.match(/\/hojin\/finance/))?       "b1" : 
			(path.match(/\/hojin\/support/))?       "b2" : 
			(path.match(/\/hojin\/matching/))?      "b3" : 
			(path.match(/\/hojin\/overseas/))?      "b4" : 
			(path.match(/\/hojin\/eb_service/))?    "b5" : 
			(path.match(/\/webeb/))?                "b5" : 
			(path.match(/\/hojin\/other_service/))? "b6" : 
			"c1";

	return (cat)? cat : "c1";
}


/**
 * 登録するページ情報を取得
 * @function
 */
CBMyList.DataManager.prototype.remove = function(id) {
	var _this = this;
	if (_this.hasData(id)) {
		// JS,SOからデータを削除
		var tmpArray = [];
		$(_this.currentData).each(function(){
			var data = this;
			// ここでデータ削除
			if (data.key != id) {
				tmpArray.push(data);
			}
		});
		_this.currentData = [];
		_this.currentData = tmpArray;
		this.so.remove(id);
	}
}

CBMyList.DataManager.prototype.hasData = function(id) {
	var _this = this;
	var flg = false;
	$(_this.currentData).each(function(){
		var data = this;
		if (data.key == id) {
			flg = true;
			return;
		}
	});
	return flg;
}

CBMyList.DataManager.prototype.hasDataByURL = function(url) {
	var _this = this;
	var flg = false;
	$(_this.currentData).each(function(){
		var data = this;
		if (data.value.url && data.value.url == url.split(/index\.htm[l]?$/)[0]) {
			flg = true;
			return;
		}
	});
	return flg;
}


CBMyList.DataManager.prototype.isMaxLength = function() {
	//return (this.currentData.length >= this.maxLength)? true : false;
	return (this.so.length() >= this.maxLength)? true : false;
}


/* ----------------------------------------------------- */
/* ----------------------------------------------------- */



//$(function(){
$(window).load(function(){

	// 
	if ($("#footer-area").length) {
		$("#footer-area").append('<div id="mylist-flash-block"></div>');
	}
	else {
		// $("body").append('<div id="mylist-flash-block"></div>');
		return;
	}

	var flashvars = {};
	var params = {
		menu: "false",
		scale: "noScale",
		allowFullscreen: "true",
		allowScriptAccess: "always",
		bgcolor: "#FFFFFF"
	};
	var attributes = {
		id:"externalSWF"
	};

	swfobject.embedSWF("/common/js/shared.swf?noCache=" + new Date().getTime(),
		"mylist-flash-block",
		"0",
		"0",
		"9.0.0",
		"",
		flashvars,
		params,
		attributes,
		function(e) {

			(function(){
				CBMyList.swf = getMovie(attributes.id);

				//https使用時
				//CBMyList.swf.useSecure(true);

				if (typeof CBMyList.swf.getAll == "undefined") {
					var tid = setTimeout(arguments.callee, 200);
				}
				else {
					new CBMyList.Viewer("fav-box","mylist-btn");
				}
			})()

	});

	function getMovie(id) {
		var winName;
		winName = (navigator.appName.indexOf("Microsoft") != -1)? window[id] : document[id];
		return winName;
	}

})



