// newsdatapanel.js
// 2010.07.29
var KNEWS;

(function($) {
	if (typeof KNEWS == 'undefined') KNEWS = {};

	//非表示要素でも採寸できるようにする
	$.fn.measur = function(f){
		var o = this,ret;
		var hide = o.is(':hidden');
		if (hide) o.show();
		ret = f();	
		if (hide) this.hide();
		return ret;
	}
	$.fn.exClientWidth = function() {
		var o = this[0] == window ? $('html') : this;
		var s = o.measur(function(){return o.attr('clientWidth')});
		if (o.attr('tagName') != 'HTML' ) return s;
		if (jQuery.browser.msie && jQuery.browser.version == 7)
			return o.width();
		return s;
	}

	KNEWS.panelSettings = {
		newsReader: {
			type: 'newsReader',
			menuBtnImgOff: '/common/img/widget/trackbox/tab_nr.gif',
			menuBtnImgOn: '/common/img/widget/trackbox/tab_nr_ac.gif',
			countId: 'count01',
			closeId: 'close01',
			btnElemId: 'btn01',
			panelWrapElemId: 'tabbox01wrap',
			panelElemId: 'tabbox01',
			newsListId: 'nrNewsList',
			fixedTop: 32,
			fixedLeft: 269
		},
		readItLater: {
			type: 'readItLater',
			menuBtnImgOff: '/common/img/widget/trackbox/tab_ril.gif',
			menuBtnImgOn: '/common/img/widget/trackbox/tab_ril_ac.gif',
			countId: 'count02',
			closeId: 'close02',
			btnElemId: 'btn02',
			panelWrapElemId: 'tabbox02wrap',
			panelElemId: 'tabbox02',
			newsListId: 'rilNewsList',
			fixedTop: 32,
			fixedLeft: 371
		}
	};

	KNEWS.NewsDataPanel = function(option) {
		this.dataControl = null;
		this.closeFunc = option.closeFuncAry;
		this.setting = option;
	};
	KNEWS.NewsDataPanel.prototype = {
		BASE_ELEMENT: '#trackBlock',
		CLASS_NAME: 'NewsDataPanel',
		// Common
		init: function (option) {
			var self = this;
			// register close function.
			this.closeFunc.push(function () {
				self.closePanel();
			});
			// initialize element
			this.btnElem = $('#' + this.setting.btnElemId);
			this.panelElem = $('#' + this.setting.panelElemId);
			this.saveWrapElem = $('div.saveWrap', this.btnElem);
			this.countElem = $('#' + this.setting.countId);
			this.panelWrapElem = $('#' + this.setting.panelWrapElemId);
			this.newsListElem = $('#' + this.setting.newsListId + ' ul');
			this.panelWrapElem.show();
			if (jQuery.browser.msie && jQuery.browser.version <= 7) {
				var imgUrl = this.panelElem[0].currentStyle.backgroundImage;
				imgUrl = imgUrl.replace(/^url\("|"\)$/gi, '');
				var filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + imgUrl + '", sizingMethod="image", enabled="true")';
				//this.panelElem.css({background: 'none',filter: filter, width: '100px', height: '100px', zIndex: -1});
				this.panelElem.css({background: 'none'});
				var back = $('<div/>');
				back.css({filter: filter, width: '100px', height: '100px', position: 'absolute', left: '0px', top: '0px', zIndex: -1});
				this.panelElem.prepend(back);
			}
			$('.mainBox', this.panelElem).css({zIndex:2000});
			this.panelWrapElem.css({height: 0, width: 0});
			this.panelElem.hide();
			// initialize event
			this.btnElem.click(
				function() {
					if (self.panelElem.is(':hidden')) {
						self.openPanel();
					} else {
						self.closePanel();
					}
				}
			);
			// panel event setting
			$('#' + this.setting.closeId).click(
				function() {
					self.closePanel();
				}
			);
			// Latest News Select All
			$('dd.firstChild a', this.panelElem).click(
				function() {
					$('li input:checkbox', self.newsListElem).each(
						function() {
							$(this).attr('checked', 'checked');
						}
					);
					return false;
				}
			);
			// Latest News Select None
			$('dd:eq(1) a', this.panelElem).click(
				function() {
					$('li input:checkbox', self.newsListElem).each(
						function() {
							$(this).removeAttr('checked');
						}
					);
					return false;
				}
			);
			// Latest News Delete Hover
			$('li.delBtn01', this.panelElem).css('cursor', 'pointer');
			this.initDataControl();
			this.initCounter();
			this.dispInfoAry = [];
			// exFixed
			var baseElem = $(this.BASE_ELEMENT);
			var _fixed = null;
			var isBaseHidden = false;
			if (baseElem.is(':hidden')) {
				baseElem.show();
				isBaseHidden = true;
			}
			var ww = $(window).exClientWidth();
			var bw = $('#trackBar').exClientWidth();
			var minWidth = 570 + bw;
			var offset = Math.max(minWidth - ww, 0);
			if (isBaseHidden) {
				var ef = $('#trackBar').exFixed({baseNode: this.BASE_ELEMENT, top: 0, left: 570 - offset, baseY: false});
				exFixed_init(ef, 570);
			}
			var ef2 = this.panelWrapElem.exFixed({baseNode: this.BASE_ELEMENT, top: this.setting.fixedTop, left: this.setting.fixedLeft - offset, baseY: false});
			exFixed_init(ef2, this.setting.fixedLeft);

			function exFixed_init(ef, baseLeft) {
				var obj = ef.getExFixed()[0];
				_fixed = obj._fixed;
				obj._fixed = function (size ,opt) {
					exFixed_fixed(obj, baseLeft, size, opt);
				};
			}
			function exFixed_fixed(obj, baseLeft, size, opt) {
				var ww = $(window).exClientWidth();
				obj.config.logicSize.left = baseLeft - Math.max(minWidth - ww, 0);
				if (obj.config.logicSize.width === 0 || obj.config.logicSize.width == '0px') {
					delete obj.config.logicSize.width;
				}
				if (obj.config.logicSize.height === 0 || obj.config.logicSize.height == '0px') {
					delete obj.config.logicSize.height;
				}
				_fixed.apply(obj, [size ,opt]);
			}
		},
		// abstract
		initDataControl: function () {
			// データ初期化
		},
		// abstract
		onNewsData: function () {
			// データ取得完了
		},
		getClassName: function () {
			return this.CLASS_NAME;
		},
		// Common
		initCounter: function (isAnimate) {
			var tempAry = this.dataControl.readCookie();
			this.setCounter(tempAry.length, isAnimate);
		},
		// Common
		setCounter: function (cnt, isAnimate) {
			if (isAnimate) {
				this.saveWrapElem
					.css('display', 'block')
					.css('background', cnt != this.count ? '#0066ff' : '#990000')
					.css('opacity', 0.0)
					.animate({opacity: 0.5}, 100, 'linear')
					.animate({opacity: 0.0}, 700, 'swing');
			}
			if (this.count == cnt) {
				return;
			}
			this.count = cnt;
			if (cnt < 10) {
				cnt = '0' + cnt;
			}
			this.countElem.text(cnt);
		},

		// Common
		openPanel: function () {
			var self = this;
			// 全パネルを閉じる
			var cnt = this.closeFunc.length;
			for(var i=0; i<cnt; i++) {
				this.closeFunc[i]();
			}
			$('img', this.btnElem).attr('src', this.setting.menuBtnImgOn);
			this.panelWrapElem.css({height: null, width: null});
			this.panelElem.show();
			// News データを取得して表示
			this.dataControl.requestData(this.onNewsData, this);
		},

		// Common
		closePanel: function () {
			if (!this.setting) return;
			$('img', this.btnElem).attr('src', this.setting.menuBtnImgOff);
			this.panelWrapElem.css({height: 0, width: 0});
			this.panelElem.hide();
		},

		// Common
		dispPanel: function () {
			var self = this;
		},
		// Common
		dispList: function (infoAry) {
			// Latest NewsのリストHTML作成
			var newsCnt = infoAry.length;
			var dispInfoAry = [];
			var k = 0;
			var isDiffer = false;
			for (var i=0 ; i<newsCnt ; i++) {
				if (!infoAry[i].view) {
					continue;
				}
				dispInfoAry.push(infoAry[i]);
				if (this.dispInfoAry.length <= k || this.dispInfoAry[k].mtid != dispInfoAry[k].mtid) {
					isDiffer = true;
				}
				k++;
			}
			if (!isDiffer && this.dispInfoAry.length == dispInfoAry.length) {
				return this.dispInfoAry.length;
			}
			this.newsListElem.empty();
			for (var i=0 ; i<dispInfoAry.length ; i++) {
					this.newsListElem.append(
					$('<li/>')
						.attr('id', dispInfoAry[i].mtid)
						.append($('<input/>')
							.attr('type', 'checkbox')
							.attr('name', '')
							.attr('value', '')
							.addClass('checkbox')
						)
						.append($('<a/>')
							.attr('href', dispInfoAry[i].murl)
							.text(dispInfoAry[i].hl)
						)
						.append($('<span/>')
							.addClass('date')
							.text(dispInfoAry[i].dl)
						));
			}
			if (i > 0) {
				$('li:first', this.newsListElem).addClass('firstChild');
				$('li:even', this.newsListElem).addClass('even');
				$('li:last', this.newsListElem).addClass('lastChild');
			}
			this.dispInfoAry = dispInfoAry;
			return this.dispInfoAry.length;
		}

	}

	KNEWS.NewsReaderPanel = function(option) {
		KNEWS.NewsDataPanel.apply(this, arguments);
		this.constructor = KNEWS.NewsReaderPanel;
		this.setting = $.extend(KNEWS.panelSettings.newsReader, option);
		this.init();
	};
	$.extend(KNEWS.NewsReaderPanel.prototype, KNEWS.NewsDataPanel.prototype, {
		NEWSREADER_CATEGORY_ID_PREFIX: 'nrCategoryId_', // 必ず'_'を付ける
		CLASS_NAME: 'NewsReaderPanel',
		// NewsReader
		init: function () {
			var self = this;
			$('#' + this.setting.newsListId)
				.append($('<ul/>')
					.addClass('hasChild')
					.addClass('hasE')
			);
			// カテゴリ表示エリア
			this.catListElem = $('<ul/>')
					.addClass('hasChild')
					.addClass('hasE');
			$('#nrCatList')
				.empty()
				.append(this.catListElem);
			KNEWS.NewsDataPanel.prototype.init.apply(this, arguments);
			// Latest News Delete Click
			$('li.delBtn01', this.panelElem).click(
					function() {
						var delIdAry = [];
						$('li input:checkbox:checked', self.newsListElem).each(
							function() {
								var delId = $(this).parent().attr('id');
								delIdAry.push(delId);
							}
						);
						if (delIdAry.length) {
							// 削除した記事IDをクッキーに保存
							self.dataControl.writeCookie_DelNews(delIdAry);
							self.dispLatestNewsList();
						}
					}
				);
			
			// Read It Later Click
			$('div.footerBox li:eq(1)', this.panelElem).click(
				function() {
					var readItLaterIdAry = [];
					$('li input:checkbox:checked', self.newsListElem).each(
						function() {
							var readItLaterId = $(this).parent().attr('id');
							readItLaterIdAry.push(readItLaterId);
						}
					);
					if (readItLaterIdAry.length) {
						// Read It Later指定した記事IDをクッキーに保存
						KNEWS.readItLaterPanel.addReadItLaterIds(readItLaterIdAry);
					}
					return false;
				}
			);
			// Category Delete Hover
			$('p#del02', this.panelElem).css('cursor', 'pointer');

			// Category Delete Click
			$('p#del02', this.panelElem).click(
				function() {
					// チェックされたカテゴリ名を取得
					var delCategoryAry = [];
					$('li label input:checkbox:checked', self.catListElem).each(
						function() {
							var delCategory = $(this).parent().parent().attr('id');
							delCategory = delCategory.split('_')[1];
							delCategoryAry.push(delCategory);
						}
					);
					if (delCategoryAry.length) {
						var count = self.dataControl.deleteCategoryIds(delCategoryAry);
						// カウンター更新
						self.setCounter(count, true);
						// 再表示
						self.dataControl.setData();
					}
				}
			);
			this.categoryIdAry = [];
		},
		initDataControl: function () {
			var obj = KNEWS;
			this.dataControl = new KNEWS.NewsReaderControl();
		},
		onNewsData: function () {
			// データ取得完了
			this.dispNewsReaderPanel();
		},
		dispLatestNewsList: function () {
			this.dataControl.resetNewsList();
			this.dispList(this.dataControl.getNewsInfos());
		},
		addCategoryId: function (id) {
			var count = this.dataControl.addCategoryId(id);
			this.setCounter(count, true);
		},
		// NewsReader
		dispNewsReaderPanel: function () {
			
			this.dispLatestNewsList();
			this.dispCategoryList();
			
			this.dispPanel();
		},
		// カテゴリ表示
		// NewsReader
		dispCategoryList: function () {
			var categoryIdAry = this.dataControl.getCategoryIds();
			if (this.categoryIdAry.length == categoryIdAry.length) {
				var isDiffer = false;
				for (var i=0; i<categoryIdAry.length; i++) {
					if (this.categoryIdAry.length <= i || this.categoryIdAry[i] != categoryIdAry[i]) {
						isDiffer = true;
					}
				}
				if (!isDiffer) {
					return;
				}
			}
			this.catListElem.empty();
			for (var i=0; i<categoryIdAry.length; i++) {
				this.catListElem.append(
					$('<li/>')
						.attr('id', this.NEWSREADER_CATEGORY_ID_PREFIX + categoryIdAry[i])
						.append($('<label/>')
							.append($('<input/>')
								.attr('type', 'checkbox')
								.attr('name', '')
								.attr('value', '')
								.addClass('checkbox')
							)
							.append($('<span/>')
								.text(categoryIdInfoAry[categoryIdAry[i]])
							)
						));
			}
			if (categoryIdAry.length > 0) {
				$('li:first', this.catListElem).addClass('firstChild');
				$('li:even', this.catListElem).addClass('even');
				$('li:last', this.catListElem).addClass('lastChild');
			}
			this.categoryIdAry = categoryIdAry;
		}
	});
	KNEWS.ReadItLaterPanel = function(option) {
		KNEWS.NewsDataPanel.apply(this, arguments);
		this.constructor = KNEWS.ReadItLaterPanel;
		this.setting = $.extend(KNEWS.panelSettings.readItLater, option);
		this.init();
	};
	$.extend(KNEWS.ReadItLaterPanel.prototype, KNEWS.NewsDataPanel.prototype, {
		CLASS_NAME: 'ReadItLaterPanel',
		init: function () {
			var self = this;
			KNEWS.NewsDataPanel.prototype.init.apply(this, arguments);
			$('li.delBtn01', this.panelElem).click(
				function() {
					var delIdAry = [];
					$('li input:checkbox:checked', self.newsListElem).each(
						function() {
							var delId = $(this).parent().attr('id');
							delIdAry.push(delId);
						}
					);
					if (delIdAry.length) {
						self.dataControl.deleteNewsIds(delIdAry);
						self.dispReadItLaterList(true);
					}
				}
			);
		},
		initDataControl: function () {
			this.dataControl = new KNEWS.ReadItLaterControl();
		},
		onNewsData: function () {
			// データ取得完了
			this.dispReadItLaterToPanel();
		},
//		openPanel: function () {
//			this.newsListElem.empty();
//			KNEWS.NewsDataPanel.prototype.openPanel.apply(this, arguments);
//		},
		// ReadItLater
		addReadItLaterIds: function (idAry) {
			var count = this.dataControl.addNewsIds(idAry);
			this.setCounter(count, true);
		},
		// ReadItLater
		dispReadItLaterToPanel: function () {
			this.dispReadItLaterList();
			this.dispPanel();
		},
		// ReadItLater
		dispReadItLaterList: function (isAnimate) {
			var count = this.dispList(this.dataControl.getNewsInfos());
			this.setCounter(count, isAnimate);
		}
	});

})(jQuery);


