// newsdatacontrol.js
var KNEWS;

(function($) {

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

	KNEWS.dataSettings = {
		newsReader: {
			type: 'newsReader',
			cookieName: 'newsReaderInfo',
			cookieExpires: 365,
			cookiePath: '/',
			cookieMax: null,
			requestAPI: '/wi/wi_news_reader.php',
			requestTimeout: 5000,
			latestNewsListMax: 30
		},
		readItLater: {
			type: 'readItLater',
			cookieName: 'readItLaterInfo',
			cookieExpires: 365,
			cookiePath: '/',
			cookieMax: 30,
			requestAPI: '/wi/wi_read_it_later.php',
			requestTimeout: 5000
		},
		newsReaderDel: {
			type: 'newsReaderDel',
			cookieName: 'newsReaderDelInfo',
			cookieExpires: 1,
			cookiePath: '/',
			cookieMax: 30
		}
	};

	KNEWS.NewsDataControl = function(option) {
		this.setting = option;
	};
	KNEWS.NewsDataControl.prototype = {
		NEWS_PROPS: ['mtid','mtcd','mtcn','murl','hl','dl','view'],
		count: 0,
		// News Readerデータを取得して、格納と表示を行う
		requestData: function (cb, bind) {
			this.cbFunc = cb;
			this.cbBind = bind;
			var self = this;
			var type = 'POST';
			var url  = this.setting.requestAPI;

			// send request
			$.ajax({
				type: type,
				url: url,
				timeout: self.setting.requestTimeout,
				success: function(buf){
					var preloadDatas = eval('(' + buf + ')');
					self.setData(preloadDatas);
				},
				error: function(buf, status){
					alert( 'error: ' + buf + ',' + status);
				}
			});
		},
		// Common
		getNewsInfos: function () {
			return this.newsInfoAry;
		},
		// Common abstract
		setData: function (jsonData) {
			this.cbFunc.apply(this.cbBind, jsonData);
		},
		// Common
		writeCookie: function (data, setting) {
			setting = setting || this.setting;
			if (data.length && typeof data != 'string') {
				data = data.join(';');
			}
			// 最新情報を取得し、クッキーに保存しなおす
			$.cookie(setting.cookieName, data, {expires: setting.cookieExpires, path: setting.cookiePath});
		},
		// Common
		readCookie: function (setting) {
			if (typeof setting == 'string') {
				cookieName = setting;
			} else if (setting && setting.cookieName) {
				cookieName = setting.cookieName;
			} else {
				cookieName = this.setting.cookieName;
			}
			var temp = $.cookie(cookieName);
			if (temp == null || temp == '') {
				return [];
			}
			return temp.split(';');
		},
		appendCookie: function (idAry, cookieInfo) {
			var tempAry = this.readCookie(cookieInfo);
			if (!tempAry.length) {
				tempAry = idAry;
			} else {
				var ck = {};
				for (var i=0; i<tempAry.length; i++) {
					ck[tempAry[i]] = 1;
				}
				for (var i=0; i<idAry.length; i++) {
					if (ck[idAry[i]]) continue;
					tempAry.push(idAry[i]);
				}
			}
			tempAry.sort(this.idSortDESC);
			if (cookieInfo && cookieInfo.cookieMax && tempAry.length > cookieInfo.cookieMax) {
				tempAry = tempAry.slice(0, cookieInfo.cookieMax);
			}
			this.writeCookie(tempAry, cookieInfo);
			return tempAry;
		},
		removeCookie: function (idAry, cookieInfo) {
			var tempAry = this.readCookie(cookieInfo);
			if (!tempAry.length) {
				return [];
			}
			var ck = {};
			for (var i=0; i<idAry.length; i++) {
				ck[idAry[i]] = 1;
			}
			var _tempAry = [];
			for (var i=0; i<tempAry.length; i++) {
				if (ck[tempAry[i]]) continue;
				_tempAry.push(tempAry[i]);
			}
			this.writeCookie(_tempAry, cookieInfo);
			return _tempAry;
		},
		// Common
		idSortDESC: function (a,b) {
			return (b - a);
		},
		getDatasByIds: function (datas, ids, isSliceData, isUnmatch) {
			if (!ids.length || typeof ids == 'string') {
				ids = [ids];
			}
			isUnmatch = !!isUnmatch;
			var _datas = [];
			var idObj = {};
			var cnt = datas.length || datas.count;
			for (var i = 0; i < ids.length; i++) {
				idObj[ids[i]] = true;
			}
			for (var i = 0; i < cnt; i++) {
				if (idObj[datas[i].mtid] === isUnmatch) {
					continue;
				}
				if (isSliceData) {
					var data = {};
					for (var j = 0; j < this.NEWS_PROPS.length; j++) {
						data[this.NEWS_PROPS[j]] = datas[i][this.NEWS_PROPS[j]];
					}
					_datas.push(data);
				} else {
					_datas.push(datas[i]);
				}
			}
			return _datas;
		}
	};

	KNEWS.NewsReaderControl = function(option) {
		KNEWS.NewsDataControl.apply(this, arguments);
		this.constructor = KNEWS.NewsReaderControl;
		this.setting = $.extend(KNEWS.dataSettings.newsReader, option);
		this.newsReaderDelSetting = KNEWS.dataSettings.newsReaderDel;
	};
	$.extend(KNEWS.NewsReaderControl.prototype, KNEWS.NewsDataControl.prototype, {
		// NewsReader
		setData: function (jsonData) {
			// 表示データのリセット
			this.newsInfoAry = [];
			if (!jsonData) {
				jsonData = this.preloadDatas;
			} else {
				this.preloadDatas = jsonData;
			}
			// クッキーに保存してるカテゴリーを読み込む
			this.categoryIdAry = this.readCookie();

			var cntId = this.categoryIdAry.length;
			var cntJson = jsonData.count;

			// 記事データの中から、カテゴリーが一致するものをピックアップ
			for (var i=0; i<cntJson; i++) {
				var matchFlg = false;
				// 登録してあるカテゴリ一つずつチェック
				for (var j=0; j<cntId; j++) {
					// 一つの記事が属する複数のカテゴリをチェック
					for (var k=0; k<jsonData[i].mtcd.length; k++) {
						if (this.categoryIdAry[j] == jsonData[i].mtcd[k]) {
							matchFlg = true;
						}
					}
				}
				// 登録してあるカテゴリに一致する記事？
				if (matchFlg) {
					// パネルに表示する記事として格納
					this.newsInfoAry.push(jsonData[i]);
					if (this.newsInfoAry.length >= this.setting.latestNewsListMax) {
						break;
					}
				}
			}
			//this.dispNewsReaderPanel();
			this.cbFunc.apply(this.cbBind, [jsonData]);
		},
		// NewsReader
		resetData: function () {
			this.setData(this.preloadDatas);
		},
		// NewsReader
		getCategoryIds: function () {
			return this.categoryIdAry;
		},
		// NewsReader
		deleteCategoryIds: function (idAry) {
			this.categoryIdAry = this.removeCookie(idAry);
			return this.categoryIdAry.length;
		},
		// NewsReader
		addCategoryId: function (id) {
			this.categoryIdAry = this.appendCookie([id]);
			return this.categoryIdAry.length;
		},
		// NewsReader
		resetNewsList: function () {
			// 削除指定された記事を振るい落とす
			var delIdAry = this.readCookie(this.newsReaderDelSetting);
			if (delIdAry.length) {
				this.newsInfoAry = this.getDatasByIds(this.newsInfoAry, delIdAry, false, true);
			}
//			if (this.newsInfoAry.length >= this.setting.latestNewsListMax) {
//				this.newsInfoAry = this.newsInfoAry.slice(0, this.setting.latestNewsListMax);
//			}
		},
		// NewsReader
		writeCookie_DelNews: function (idAry) {
			this.appendCookie(idAry, this.newsReaderDelSetting);
		}
	});

	KNEWS.ReadItLaterControl = function(option) {
		KNEWS.NewsDataControl.apply(this, arguments);
		this.constructor = KNEWS.ReadItLaterControl;
		this.setting = $.extend(KNEWS.dataSettings.readItLater, option);
	};
	$.extend(KNEWS.ReadItLaterControl.prototype, KNEWS.NewsDataControl.prototype, {
		// ReadItLater
		setData: function (jsonData) {
			this.newsIdAry = this.readCookie();
			this.newsInfoAry = this.getDatasByIds(jsonData, this.newsIdAry, true);
			this.newsIdAry = this.getNewsIds(this.newsInfoAry);
			this.writeCookie(this.newsIdAry);
			
			//this.dispReadItLaterToPanel();
			this.cbFunc.apply(this.cbBind, [jsonData]);
		},
		// ReadItLater
		getNewsIds: function (newsInfoAry) {
			if (!newsInfoAry) {
				return this.newsIdAry;
			}
			var tempAry = [];
			for (var i = 0; i < newsInfoAry.length; i++) {
				tempAry.push(newsInfoAry[i].mtid);
			}
			tempAry.sort(this.idSortDESC);
			return tempAry;
		},
		// ReadItLater
		deleteNewsIds: function (delIdAry) {
			this.newsInfoAry = this.getDatasByIds(this.newsInfoAry, delIdAry, false, true);
			this.newsIdAry = this.getNewsIds(this.newsInfoAry);
			this.writeCookie(this.newsIdAry);
		},
		// ReadItLater
		addNewsIds: function (idAry) {
			// 最新情報を取得し、クッキーに保存しなおす
			this.newsIdAry = this.appendCookie(idAry);
			return this.newsIdAry.length;
		}
	});

})(jQuery);


