/**
*author: LiangYunFei
*email: 742149579@qq.com
**/

//浏览器回调
(function(window, $){
	window.ntp = {};
	//客户端会定时更新页面
	ntp.setMostVisitedPages = function(data) {
		console.log('page:', data);
		KW_BROWSER_NTP.Events.renderQuickAcess(data);
	};
	
	//换肤回调
	ntp.themeChanged = function(changed){
		var $select = $('.skin-setup-box .setup-list li.select');
		if(changed){
			var $themeCss = $('#themecss'),
				href = $themeCss.attr('href'),
				rand = parseInt(Math.random() * 1e6);
			
			$themeCss.attr('href', href + '?' + rand);
			//通知修改背景图片位置
			chrome.send('getBrowserBackPos', []);
			//清除背景缓存
			$('html').css('background-image', '-webkit-image-set( url(chrome://theme/IDR_THEME_NTP_BACKGROUND?' + rand + ') 1x)');
			
			//设置编码
			var code = $select.data('code');
			if(code == 'local_skin'){
				//如果是本地上传的图片则取消选中
				$select.removeClass('select');
				localStorage.removeItem('skin_code');
			}else{
				localStorage.setItem('skin_code', code);
			}					
		}
		
		//将加载图片去除		
		$select.find('.load-diagram').remove();
	};
	
	
	window.onGetKWEVerInfo = function(data){
		try {
			var _data = JSON.parse(data);
			if (_data.ver) {
				KW_BROWSER_NTP.VERSION = _data.ver;
				localStorage.setItem('version', _data.ver);
				KW_BROWSER_NTP.Events.compatQuickAcessPage();
			};
		} catch (e) {
			console.log(e);
		}
	}
	
	//背景图片位置通知
	window.onGetBrwoserBackPos = function(data){
		data = JSON.parse(data);
		$('html').css('background-position', data.x + ' ' + data.y);
	};
	
	//背景图片位置通知
	ntp.onGetBrwoserBackPos = function(data){
		data = JSON.parse(data);
		$('html').css('background-position', data.x + ' ' + data.y);
	};
})(window, $);

//iframe通信
(function(window, $){
	window.addEventListener('message', function(event){
		var obj;
		try{
			if($.isPlainObject(event.data)){
				obj = event.data;
			}else{
				obj = JSON.parse(event.data);
			}
			
			chrome.send('webStats', [JSON.stringify(obj)]);
		}catch(e){
			console.log(e);
		}
	}, false);
})(window, $);

//运营页面配置
(function(window, $){
	window.KW_BROWSER_NTP = {
		HOST: {
			RECOMMEND: "http://www.yunfan.com/api/cli/yfpyingku.php?pos=",
			//GAMEIMG: "http://media.kuaiwan.com/",
			//MINIGAME: "http://www.kuaiwan.com/flash/",
			//WEBGAME: "http://webgame.kuaiwan.com/play/",
			QUICKACESS: 'http://dyn.e.yunfan.com/', //get the quick_site and the host game
			BAIDUSUGGEST: 'http://suggestion.baidu.com/su?cb=?',
			TULIANCHOR: 'http://mm.yunfan.com/mm/online/',
			YF_SEARCH_RECOMMEND: 'http://s.yunfan.com/home/term.js',
			FILM_CONTENT: 'http://s.yunfan.com/yfbrowser/newtab.js',
			FILM_CHASE: 'http://www.yunfan.com/api/cli/chasecloud.php',
			FILM_ULIKE: 'http://www.yunfan.com/api/cli/yfeulike.php',
			NAVIGATE_URL: 'http://dyn.e.yunfan.com/ntp/channel/?v=1&callback=?',
			SKIN_URL: 'http://dyn.e.yunfan.com/ntp/skin/?callback=?'
		},
		defaultPageItem: [
			{
				'type': 'local',
				'name' : '快速访问',
				'icon' : 'quickAcess',
				'channel' : 'quickAcess'
			},
			{
				'type': 'local',
				'name' : '热播影视',
				'icon' : 'movie',
				'channel' : 'movie'
			},
			{
				'type': 'local',
				'name' : '美女主播',
				'icon' : 'tuliAnchor',
				'channel' : 'tuliAnchor'
			}
		],
		Page_Info: {
			version: "3.3.0.1", //npt version
			page_items: []
		}
	};
	
	window.KW_BROWSER_NTP.Page_Info.page_items = (function(){
		var item = JSON.parse(localStorage.getItem('page_items'));
		//初始化没有值时赋予默认值
		if(!item) item = window.KW_BROWSER_NTP.defaultPageItem;
		//请求导航数据,更改本地存储
		$.jsonp({
			url: window.KW_BROWSER_NTP.HOST.NAVIGATE_URL,
			success: function(res){
				if(res.ok && res.data.length > 0){
					localStorage.setItem('page_items', JSON.stringify(res.data));	
				}
			},
			timeout: 5000
		});
		
		return item;
	})();
})(window, $);

//运营页面信息
(function(window, $){
	var Page = {
		current_page: function(){
			//后台配置后,不能通过数组下标来取上一次页面
			var page = 'quickAcess',
				last_nav_page = localStorage.getItem('last_nav_page_1');
			
			if(last_nav_page && /^\d+$/.test(last_nav_page)){
				localStorage.removeItem(last_nav_page);
			}else if(last_nav_page){
				page = last_nav_page;
			}
			
			localStorage.setItem('last_nav_page_1', page);
			return page;
		}(),
		getCurrentItem: function(){
			var _page = this.current_page;
			for(var i=0,len=this.page_items.length; i<len; i++){
				var item = this.page_items[i];
				if(item.channel == _page){
					return item;
				}
			}
		},
		getPageItems: function(page){
			var _arr = [];
			for(var i=0; item=this.page_items[i++]; ){
				if(item.channel != page){
					_arr.push(item);
				}
			}
			return _arr;
		},
		getItemIndex: function(item){
			var _index = null,
				page_items = KW_BROWSER_NTP.Page_Info.page_items;
			
			for(var i=0, len = page_items.length; i<len; i++ ){
				if(page_items[i]['channel'] == item){
					_index = i;
					break;
				}
			}
			
			return _index;
		},
		getPageByIndex: function(index){
			return this.page_items[index] && this.page_items[index]['channel'];
		}
	};
	
	//设置当前index
	window.KW_BROWSER_NTP.Page_Info.current_index = Page.getItemIndex(Page.current_page) || 0;
	
	$.extend(true, window.KW_BROWSER_NTP.Page_Info, Page);
	
})(window, $);

//逻辑
(function(window, $){	
	var Logic = {
		SearchParam: null,
		Events: {
			init: function() {
				this.initModules();
				this.initKwBrowserVersion();
				this.initSlidePage();
				this.triggerSlidePage();
				this.initPageItem();
				this.initSearch();
				this.initGlobalEvent();
				this.adjustWebPage();
				//初始化换肤
				this.initSkin();
				//通知修改背景图片位置
				chrome.send('getBrowserBackPos', []);
			},
			Elements: {
				$slide_left_btn: $('#page-pre'),
				$slide_right_btn: $('#page-next'),
				$nav: $('.pagenav'),
				$search_engine: $('#search-switch'),
				$search_engine_list: $('#search-engine-list'),
				$search_input: $('#search-input'),
				$search_btn: $('.btn_search'),
				$auto_complete_list: $('#search-suggest'),
				$page_list: $('#page-list'),
				$page_nav: $('#page-nav'),
				$skin_box: $('.skin-setup-box')
			},
			statsChannelView: function(index){
				var _channel;
				_channel = KW_BROWSER_NTP.Page_Info.page_items[index]['channel'];
				var _web_stats = {
					'doc_type': 'ChannelView',
					'channel': _channel,
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
				try {
					chrome.send('webStats', [JSON.stringify(_web_stats)]);
				} catch(e) {
					console.log(e);
				}
			},
			initModules: function(){
				//初始化脚部TAB
				this.initFootModule();
				//初始化列表
				this.initListModule();
			},
			initFootModule: function(){
				var tpl = doT.template($('#dot-foot').text()),
					data = KW_BROWSER_NTP.Page_Info.page_items,
					$pageWrap = this.Elements.$page_nav;
				$pageWrap.html(tpl(data));
				var _li = $pageWrap.children('li'),
					_itemWidth = _li.eq(0).outerWidth(),
					_len = _li.size();
				$pageWrap.css('width', _itemWidth*_len);
			},
			initListModule: function(){
				var _tpl = '';
				var modules = KW_BROWSER_NTP.Page_Info.page_items;
				for(var i=0, len=modules.length; i<len; i++ ){
					var item = modules[i];
					switch(item.type){
						case 'local':
							_tpl = doT.template($('#dot-' + item['channel']).text());
							break;
						case 'iframe':
							_tpl = doT.template($('#dot-iframe').text());
							break;
						case 'squared':
							_tpl = doT.template($('#dot-squared').text());
							break;
					}
					if(_tpl) $('#page-list').append(_tpl({'className': item['channel'], 'url': item['channel_url']}));
				}
				$('.page_item').eq(0).addClass('current_page');
			},			
			initPageItem: function() {
				var _parent = this;
				var _page = KW_BROWSER_NTP.Page_Info.current_page,
					_item = KW_BROWSER_NTP.Page_Info.getCurrentItem(),
					ucFirst = window.Base.Common.ucFirst;
				if(!_item){
					_item = KW_BROWSER_NTP.Page_Info.page_items[0];
				}
				if(_item.type == 'squared'){
					_parent['init'+ ucFirst('squared') + 'Page'] && _parent['init'+ ucFirst('squared') + 'Page'](_item);//首先初始化当前页面
				}else{				
					_parent['init'+ ucFirst(_page) + 'Page'] && _parent['init'+ ucFirst(_page) + 'Page']();//首先初始化当前页面
				}
				if(_page == 'movie'){
					$('#search').css('visibility', 'hidden');
				}
				setTimeout(function(){
					//var _page_list = ['Game', 'FilmVideo', 'QuickAcess','TuliAnchor'];
					var _page_list = KW_BROWSER_NTP.Page_Info.getPageItems(_page);//去除初始化页面
					_page_list.forEach(function(item){
						if(item['channel'] != _page){
							if(item['type'] == 'local'){
								_parent['init'+ ucFirst(item['channel']) + 'Page'] && _parent['init'+ ucFirst(item['channel']) + 'Page']();
							}else if(item['type'] == 'squared'){
								_parent.initSquaredPage && _parent.initSquaredPage(item);
							}
						}
					});
				}, 1000);
			},		
			initGlobalEvent: function() {
				var _parent = this,
					_$auto_complete_list = _parent.Elements.$auto_complete_list,
					_$search_input = _parent.Elements.$search_input,
					_$engine_list = _parent.Elements.$search_engine_list,
					_$engine = _parent.Elements.$search_engine,
					_$page_nav = _parent.Elements.$page_nav,
					_resizeTimer = null;

				window.onresize = function() {
					if (_resizeTimer) {
						clearTimeout(_resizeTimer);
						_resizeTimer = null;
					};
					_resizeTimer = setTimeout(function() {
						_parent.adjustWebPage();
						if (_$auto_complete_list.css('display') == 'block') {
							var _offset = _$search_input.offset();
							_$auto_complete_list.css({
								"left": ($(".search_ipt .ipt").offset().left) + "px",
								"top": ($(".search_ipt .ipt").offset().top + 29) + "px"
							});
						};
						if (_$engine_list.css('display') == 'block') {
							var _offset = _$engine.offset();
							_$engine_list.css({
								"left": (_$engine.offset().left - 1) + "px",
								"top": (_$engine.offset().top + 28) + "px"
							}).show();
						}
					}, 30);
				};
								
				//统计代码
				this.WebStat();

				this.setMainPageSize();
			},
			setMainPageSize: function(){
				var win = $(window),
					winWidth = win.width();

				$('#main').css('width', Math.max(winWidth, 700));
			},
			adjustWebPage: function() {
				var minSize = 700,
					maxSize = 1200,
					percent = 0.67,
					_parent = this,
					originSize = 960,
					originHeight = 560,
					zoom = 1,
					_pageTop;

				var pageScale = function(){
					var _winWidth = $(window).width(),
						_winHeight = $(window).height(),
						_pageWidth = percent*_winWidth;
					
					_pageWidth = Math.min(_pageWidth, maxSize);
					_pageWidth = Math.max(_pageWidth, minSize);
					
					var getScale = function(scale){
						return 'scale(' + Math.max(scale, 0) + ')';
					};
					if(originSize >= _pageWidth){
						zoom = 1 - (originSize - _pageWidth)/originSize;
					}else{
						zoom = 1 + (_pageWidth - originSize)/originSize;
					}
					
					_pageTop = (function(){
						return (zoom*originHeight - originHeight)/2;
					})();

					_parent.Elements.$page_list.css('-webkit-transform',  getScale(zoom));
				};

				pageScale();

				var _w_height = $(window).outerHeight(),
					_foot_height = $('.footer').outerHeight(),
					_page_height = $('.page_list').outerHeight() + 35,
					_search_height = $('#search').outerHeight(),
					_content_height = _search_height + _page_height + _foot_height,
					_margin_top = 0;

				_margin_top = (_w_height - _foot_height - _search_height - originHeight*zoom + 66)/2;

				$("#search").css({'marginTop': Math.max(20, _margin_top)}).show();
				$('#page-list').css({'top': _pageTop});

				this.setMainPageSize();
				
			},			
			loadData: function(params) {
				var _parent = this;
				var _category = params.category;
				var _key = _category.split('-');
				var _page_item = params.page_item ? params.page_item : KW_BROWSER_NTP.Page_Info.current_page;
				var _identifying = KW_BROWSER_NTP.Configuration[_page_item][_key[0]][_key[1]];
				var _template = '#dot-' + _page_item + '-' + _key[0];
				var _url_params = params.url_params ? '&' + params.url_params : '';
				//console.log(params, _url_params);
				if (params.selectedField) {
					var _callback = function(){
						var _current_select = $(params.selectedField).find('.selected').parent().data('category');
						$(params.hideElement).hide();
						$('.' + _current_select).show();	
					}
				}else{
					var _callback = function(){};
				}
				$(params.appendField).find('.loading').css('display', 'block');
				$.getJSON(KW_BROWSER_NTP.HOST.RECOMMEND + _identifying + '&callback=?' + _url_params, function(data) {
					var _data = {};
					if (_key[0] == 'MiniGame' || _key[0] == 'WebGame') {
						if (_key[0] == 'MiniGame') {
							var _list_wrap = [[],[],[]]; //for the layout need 3 ul
							var _list = data.data.record_list;
							_list.forEach(function(game) {
								game.url = KW_BROWSER_NTP.HOST.MINIGAME + (game.id % 100) + '/' + game.id + '.html';
								game.icon_imgs = KW_BROWSER_NTP.HOST.GAMEIMG + game.icon_imgs;
							});
							var i = 0, j = 0;
							_list.forEach(function(game){
								_list_wrap[j].push(game);
								if (++i == 5) {
									j += 1;
									i = 0;
								}
							})
							_list = _list_wrap;
						} else {
							var _list = data.data.record_list;
							_list.forEach(function(game) {
								game.url = KW_BROWSER_NTP.HOST.WEBGAME + game.recommend_data + '.html';
							});
						}
						
						_data.record_list = _list;
					} else {
						//split score point
						if (_category == 'HotList-movie') {
							var _list = data.data.record_list
							_list.forEach(function(movie) {
								var _score = movie.score.split('.');
								movie.score_first = _score[0];
								movie.score_second = _score[1];
							});
							_data.record_list = _list;
						} else {
							_data.record_list = data.data.record_list;	
						}
					}
					_data.category = _key[1];
					_data.className = _category;
					_parent.htmlTemplate({
						templateID: _template,
						method: 'append',
						appendField: params.appendField,
						data: _data,
						callback: _callback
					});
				});
			},
			htmlTemplate: function(option) {
				var defaultOption = {
					method: "append",
					appendField: "body",
					data: {}
				};
				var option = $.extend(true, defaultOption, option);
				var result = doT.template($(option.templateID).text());
				//console.log(option.appendField);
				$(option.appendField).find('.loading').hide();
				//如果已经存在则不重新渲染
				if(option.data.className){
					var isExist = $(option.appendField).find('.' + option.data.className).size();
					if(isExist) return;
				}
				var f = $(option.appendField)[option.method](result(option.data));
				if (option.callback) {
					f.each(function() {
						option.callback();
					});
				};
			},
			initKwBrowserVersion: function(){
				var _parent = this;
				try {
					chrome.send('getKWEVerInfo');
				} catch (e) {
					_parent.renderQuickAcess([]);
					console.log('do not have get browser version api');
				}
			},
			compareVersion: function(a, b) {
				if (a === b) {
					return 0;
				}
				var a_components = a.split(".");
				var b_components = b.split(".");
				var len = Math.min(a_components.length, b_components.length);
				for (var i = 0; i < len; i++) {
					if (parseInt(a_components[i]) > parseInt(b_components[i])) {
						return 1;
					}
					if (parseInt(a_components[i]) < parseInt(b_components[i])) {
						return -1;
					}
				}
				if (a_components.length > b_components.length) {
					return 1;
				}
				if (a_components.length < b_components.length) {
					return -1;
				}
				return 0;
			}
		}
	};
	
	$.extend(true, window.KW_BROWSER_NTP, Logic);
	
})(window, $);

//统计
(function(window, $){
	var WebStat = function(){
		/**
		* 统计代码
		*/
		$(document.body).delegate("a.webStats", "click", function(e) {
			var _href = $(this)[0].href;
			var urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
			var current_page = KW_BROWSER_NTP.Page_Info.current_page;
			if (current_page == 'quickAcess') {
				var _web_stats = {
					'location': 'BQ_01_' + (parseInt($('.tile_grid .webStats').index($(this))) + 1),
					'doc_type': 'QuickAcess',
					'url': urlReg.exec(_href)[0],
					'is_default': $(this).data('recommend') ? 1 : 0,
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
			} else if (current_page == 'tuliAnchor') {
				var _web_stats = {
					'location': 'BQ_02_' + (parseInt($('.mm_list .item').index($(this).parent()))  + 1),
					'doc_type': 'TuliAnchor',
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
			}else if(current_page == 'movie'){
				var _from = $(this).data('from'),
					_title = $(this).data('title');
					
				var _web_stats = {
					'doc_type': 'HotRecommend',
					'location': _from,
					'title': _title,
					'channel': 'movie',
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
			}else{
				//九宫格
				var item = KW_BROWSER_NTP.Page_Info.getCurrentItem();
				if(item.type == 'squared'){
					var _web_stats = {
						'doc_type': window.Base.Common.ucFirst(item.channel) + 'Squared',
						'location': $(this).data('from'),
						'url': urlReg.exec(_href)[0],
						'is_default': $(this).data('recommend') ? 1 : 0,
						'ntp_version': KW_BROWSER_NTP.Page_Info.version
					}
				}
			}
			
			try {
				if(typeof _web_stats != 'undefined' && _web_stats != null){
					chrome.send('webStats', [JSON.stringify(_web_stats)]);	
				}
			} catch(e) {
				console.log(e);
			}
			$(this).attr('href', _href);
		});
	};
	
	window.KW_BROWSER_NTP.Events.WebStat = WebStat;
})(window, $);

//滑动
(function(window, $){
	var Slide = {
		initSlidePage: function(opt) {
			var _parent = this;
			var _Page_info = KW_BROWSER_NTP.Page_Info;
			var defaultOption = {
				index: _Page_info.current_index,
				operate: 'init'
			};
			var option = $.extend(true, defaultOption, opt);
			var $page_item = $('.page_item'),
				$current_page = $('.current_page'),
				index = option.index,
				slide_length = KW_BROWSER_NTP.Page_Info.page_items.length - 1;
			
			if (option.operate == 'init') {
				if (_Page_info.current_index != 0) {
					$current_page.css('left', -4000).removeClass('current_page');
					for (var i = 0, len = $('.page_item').length; i < len; i++) {
						if (i < _Page_info.current_index) {
							$page_item.eq(i).css('left', -4000);
						};
					};
					
					$page_item.eq(index).addClass('current_page');
					_parent.statsChannelView(index);
				} else {
					_parent.statsChannelView(0);
				}
				//stats the ntp view
				var _web_stats = {
					'doc_type': 'NtpView',
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
				try {
					chrome.send('webStats', [JSON.stringify(_web_stats)]);
				} catch(e) {
					console.log(e);
				}
			} else {
				if (KW_BROWSER_NTP._isSliding) {
					return false;
				}
				KW_BROWSER_NTP._isSliding = true;
				var _left;
				switch (option.operate) {
					case 'left':
						_left = 4000;
						if (_Page_info.current_index == 0) {
							_Page_info.current_index = index = slide_length;
						} else {
							index = --_Page_info.current_index;
						}
						break;
					case 'right':
						_left = -4000;
						if (_Page_info.current_index == slide_length) { 
							_Page_info.current_index = index = 0;
						} else {
							index = ++_Page_info.current_index;
						}
						break;
					case 'change':
						_left = _Page_info.current_index > index ? 4000 : -4000;
						index = _Page_info.current_index = index;
						break;
				};

				var filmIndex = KW_BROWSER_NTP.Page_Info.getItemIndex('movie'),
					$search = $('#search');
				if(filmIndex === index){
					$search.css('visibility', 'hidden');
				}else{
					$search.css('visibility', 'visible');
				}
				
				//隐藏输入框提示
				this.Elements.$auto_complete_list.css('display', 'none');
				this.Elements.$search_input.trigger('blur');
				
				//隐藏皮肤设置
				this.Elements.$skin_box.css('display', 'none');
				
				$current_page.animate({'left': _left}, 400,function(){
					$(this).removeClass('current_page');
					KW_BROWSER_NTP._isSliding = false;
				});
				$page_item.eq(index).css('left', -(_left)).animate({'left': 0}, 400, function(){
					$(this).addClass('current_page');
					KW_BROWSER_NTP._isSliding = false;
				});

				var _page = _Page_info.getPageByIndex(index);
				_Page_info.current_page = _page;
				localStorage.setItem('last_nav_page_1', _page);
				_parent.statsChannelView(index);
			};
			this.Elements.$nav.find('li.on').removeClass("on");
			this.Elements.$nav.find('li').eq(index).addClass("on");
		},
		triggerSlidePage: function() {
			var _this = this;
			var _Page_info = KW_BROWSER_NTP.Page_Info;
			//click the right left btn to slide the page
			this.Elements.$slide_left_btn.click(function(e) {
				_this.initSlidePage({
					index: _Page_info.current_index,
					operate: 'left'
				});
			});

			this.Elements.$slide_right_btn.click(function() {
				_this.initSlidePage({
					index: _Page_info.current_index,
					operate: 'right'
				});
			});

			this.Elements.$nav.find('li').click(function(e) {
				if ($(this).hasClass('on')) {
					return false;
				};
				_this.initSlidePage({
					index: _this.Elements.$nav.find('li').index($(this)),
					operate: 'change'
				});
			});

			document.addEventListener('mousewheel', function(e){
				if(e.deltaY > 0 || e.wheelDeltaY <0){
					_this.initSlidePage({
						index: _Page_info.current_index,
						operate: 'right'
					});
				}else{
					_this.initSlidePage({
						index: _Page_info.current_index,
						operate: 'left'
					});
				}
			});
		}
	};

	$.extend(true, window.KW_BROWSER_NTP.Events, Slide);
})(window, $);

//搜索
(function(window, $){
		
	var	Search_Collocate = {
		current_engine: localStorage.getItem('search_engine') || 'baidu',
		last_engine: null,
		engine: {
			baidu: {
				web_site: 'http://www.baidu.com?tn=93039130_dg',
				jump_url: 'http://www.baidu.com/baidu?tn=93039130_dg&word=',
				suggest: 'http://suggestion.baidu.com/su?cb=?&wd='
			},
			so: {
				web_site: 'http://www.so.com',
				jump_url: 'http://www.so.com/s?q=',
				suggest: 'http://sug.so.360.cn/suggest?callback=?&word='
			},
			google: {
				web_site: 'http://www.google.com.hk',
				jump_url: 'https://www.google.com.hk/search?q=',
				suggest: null
			},
			yunfan: {
				web_site: 'http://www.yunfan.com?from=yfe-ntp',
				jump_url: 'http://www.yunfan.com/s.php?from=yfe-ntp&q=',
				suggest: 'http://k.s.yunfan.com/?callback=?&n=10&k='
			}
		},
		formatResponse: function(response) {
			var format_data = {};
			switch (this.current_engine) {
				case 'baidu':
					if (response.s.length > 0) {
						format_data.result = true;
						format_data.list = response.s;
					}
					break;
				case 'so':
					if (response.s.length > 0) {
						format_data.result = true;
						format_data.list = response.s;
					}
					break;
				case 'yunfan':
					if(response.data.length > 0){
						var _list = [],_item='';
						format_data.result = true;
						for(var i=0,len=response.data.length; i<len; i++){
							_item = response.data[i];
							if(!$.inArray(_item.moviename, _list) >= 0){
								_list.push(_item.moviename);	
							}
						}
						format_data.list = _list;
					}
					break;
			}
			return format_data;
		}
	};
	
	KW_BROWSER_NTP.Search_Collocate = Search_Collocate;

	var Search = {		
		initSearch: function() {
			var _parent = this;
			var initAutoComplete = function() {
				var _auto_complete_list = {
					index: -1,
					arr: [],
					reset: function() {
						this.index = -1;
						this.arr = [];
					}
				};
				
				var renderTpl = function(_response){
					if (_response.result) {
						var suggest_words = _response.list,
							_current_engine_name = KW_BROWSER_NTP.Search_Collocate.current_engine,
							_jump_url = KW_BROWSER_NTP.Search_Collocate.engine[_current_engine_name].jump_url;
						_html = '';
						for (var i in suggest_words) {
							_html += '<li key="' + suggest_words[i] + '"><a class="stats" href="' + _jump_url + encodeURIComponent(suggest_words[i]) + '"><p>' + suggest_words[i] + '</p></a></li>';
						};
						_parent.Elements.$auto_complete_list.html(_html).show().css({
							"left": ($(".search_ipt .ipt").offset().left) + "px",
							"top": ($(".search_ipt .ipt").offset().top + 35) + "px"
						}).show();
						_auto_complete_list.reset();
						_auto_complete_list.arr = _parent.Elements.$auto_complete_list.find('li');
					}
				};
				
				var autoComplete = function(keyword) {
					if (keyword) {
						var _current_engine_name = KW_BROWSER_NTP.Search_Collocate.current_engine;
						var _curren_engine = KW_BROWSER_NTP.Search_Collocate.engine[_current_engine_name];
						if (_curren_engine.suggest) {
							$.getJSON(_curren_engine.suggest + keyword, function(response) {
								var _response = KW_BROWSER_NTP.Search_Collocate.formatResponse(response);
								renderTpl(_response);
							});
						}
					}else{
						$.jsonp(
							{
								url: KW_BROWSER_NTP.HOST.YF_SEARCH_RECOMMEND,
								callbackParameter: 'callback',
								callback: 'cb',
								success: function(json){
									var _response = (function(){
										var _list = [],_item='',format_data={};
										format_data.result = true;
										for(var i=0,len=json.data.length; i<len; i++){
											_item = json.data[i];
											if(!$.inArray(_item.moviename, _list) >= 0){
												_list.push(_item.moviename);	
											}
										}
										format_data.list = _list;
										return format_data;
									})();
									renderTpl(_response);
								}
							}
						)
					}
				};
				//judge the keycode when keydown
				//ps: 38 is up , 40 is down
				var _clearTimeout;
				var judgeKeyDown = function(e) {
					if (_auto_complete_list && _auto_complete_list.length !== 0) {
						switch (e.keyCode) {
							case 38:
								operateList('up');
								break;
							case 40:
								operateList('down');
								break;
							default:
								var _keyword = _parent.Elements.$search_input.val();
								if (_clearTimeout) {
									clearTimeout(_clearTimeout);
									_clearTimeout = null;
								};
								_clearTimeout = setTimeout(function() {
									autoComplete(_keyword);
								}, 100);
						};
					}
				};

				var operateList = function(direction) {
					var _l = _auto_complete_list;
					if (direction == 'up') {
						if (_l.index == -1) {
							return false;
						} else {
							_l.arr.eq(_l.index).removeClass('sugHover');
							if (_l.index == 0) {
								_l.arr.eq(_l.arr.length - 1).addClass('sugHover');
								_l.index = _l.arr.length - 1;
							} else {
								_l.arr.eq(--_l.index).addClass('sugHover');
							};
						};
					} else {
						if (_l.index + 1 == _l.arr.length) {
							_l.arr.eq(0).addClass('sugHover');
							_l.arr.eq(_l.index).removeClass('sugHover');
							_l.index = 0;
						} else {
							_l.arr.eq(_l.index).removeClass('sugHover');
							_l.arr.eq(++_l.index).addClass('sugHover');
						};
					};
					_parent.Elements.$search_input.val(_l.arr.eq(_l.index).find('p').text())
				};
				
				//dropdown list click or not
				var searchByKeyword = function(isDropdownList) {
					var _web_stats = {
						'doc_type': "Search",
						"channel": KW_BROWSER_NTP.Search_Collocate.current_engine,
						'ntp_version': KW_BROWSER_NTP.Page_Info.version
					};
					try {
						chrome.send('webStats', [JSON.stringify(_web_stats)]);
					} catch(e) {
						console.log(e);
					}
					if (!isDropdownList) {
						var _keyword = _parent.Elements.$search_input.val();
						var _engine = KW_BROWSER_NTP.Search_Collocate.engine[KW_BROWSER_NTP.Search_Collocate.current_engine];
						var _url = _keyword == '' ? _engine.web_site : _engine.jump_url + encodeURIComponent(_keyword);
						if(window.KW_BROWSER_NTP.SearchParam){
							_url += window.KW_BROWSER_NTP.SearchParam; 
						}
						window.location.href = _url;
					}
				};
				_parent.Elements.$search_btn.bind('click', function() {
					searchByKeyword();
				});
				_parent.Elements.$search_input.bind('keyup', judgeKeyDown);
				_parent.Elements.$search_input.bind('keydown', function(e) {
					if (e.keyCode == 13) {
						searchByKeyword();
						return false;
					}
				})
				_parent.Elements.$search_input.bind('focus', function() {
					autoComplete(_parent.Elements.$search_input.val());
				});
				_parent.Elements.$search_input.bind('blur', function() {
					_auto_complete_list.reset();
				});

				_parent.Elements.$auto_complete_list.delegate('.stats', 'click', function(){
					searchByKeyword(true);
				});
			};
			
			var initNavEngine = function(){
				var $navs = $('.search_cat a');
				$navs.on('click', function(){
					var $self = $(this),
						_catname = $self.data('catname');
					if(_catname == 'webpage' || _catname == 'movie'){
						$self.siblings().removeClass('on').end().addClass('on');
						
						if(_catname == 'webpage'){
							KW_BROWSER_NTP.Search_Collocate.current_engine =  KW_BROWSER_NTP.Search_Collocate.last_engine ? KW_BROWSER_NTP.Search_Collocate.last_engine : 'baidu';
						}else{
							KW_BROWSER_NTP.Search_Collocate.last_engine = KW_BROWSER_NTP.Search_Collocate.current_engine != 'yunfan' ? KW_BROWSER_NTP.Search_Collocate.current_engine : null;
							KW_BROWSER_NTP.Search_Collocate.current_engine = 'yunfan';
						}
					}
					
					modifySearchStyle();
				});
			};
			
			//修改图标
			var modifySearchStyle = function(){
				var _placeHolder = '',
					_current_engine = KW_BROWSER_NTP.Search_Collocate.current_engine,
					$dropDown = $('#search-switch .search-arr');
				
				if(_current_engine == 'yunfan'){
					_placeHolder = '全网搜索影片';
					$dropDown.hide();
				}else{
					var _$lately_engine = _parent.Elements.$search_engine_list.find('.' + _current_engine);
					_placeHolder = _$lately_engine.text();
					$dropDown.show();
				}
				
				
				$('.search_engine a').attr('class', _current_engine);
				_parent.Elements.$search_input.attr('placeholder', _placeHolder);
			};
			
			var initSearchEngine = function() {
				var _$engine = _parent.Elements.$search_engine,
					_$engine_list = _parent.Elements.$search_engine_list;
				_$engine.bind('click', function(e) {
					var _current_engine = KW_BROWSER_NTP.Search_Collocate.current_engine;
					if(_current_engine == 'yunfan') return;
					_$engine_list.css({
						"left": (_$engine.offset().left - 1) + "px",
						"top": (_$engine.offset().top + 34) + "px"
					}).show();
					return false;
				});
				_$engine_list.find('a').bind('click', function(e) {
					var _engine_name = $(this).attr('class');
					localStorage.setItem('search_engine', _engine_name);
					KW_BROWSER_NTP.Search_Collocate.current_engine = _engine_name;
					$('.search_engine a').attr('class', _engine_name);
					_parent.Elements.$search_input.attr('placeholder', $(this).text());
					_$engine_list.hide();
					return false;
				});
				
				modifySearchStyle();
			};
			//judge the target if not in the search_input or search engine then hide it
			$(document.body).click(function(e) {
				var _id = $(e.target).attr('id');
				var _is_engine = (_id == 'search-switch') ? true : ($(e.target).parents('#search-switch').length > 0 ? true : false);
				var _is_skin = $(e.target).parents('.skin-peeler').length > 0 ? true : false;
				if (_id !== 'search-input') {
					_parent.Elements.$auto_complete_list.hide();
				};
				if (!_is_engine) {
					_parent.Elements.$search_engine_list.hide();
				}
				if(!_is_skin){
					$('.skin-setup-box').hide();
				}
			});
			//stats search jump
			$('.web_stats').click(function(){
				var _web_stats = {
					'doc_type': 'Search',
					'channel': $(this).data('catname'),
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
				try {
					chrome.send('webStats', [JSON.stringify(_web_stats)]);
				} catch(e) {
					console.log(e);
				}
			});
			
			initNavEngine();
			initAutoComplete();
			initSearchEngine();
		}
	};
	
	$.extend(true, window.KW_BROWSER_NTP.Events, Search);
})(window, $);

//快速访问
(function(window, $){
	var QuickAccess = {
		renderQuickAcess: function(data) {
			var _parent = this;
			var urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
			$('.quick_acess .tile_grid').remove();
			var _valid_page = [];
			var _len = _valid_page.length;
			var Cache = window.Base.Plugins.Cache;
			if (_len < 12) {
				var _quickStorageCache = Cache.get('quick_access');
				if(_quickStorageCache && _quickStorageCache.length > 0){
					_valid_page = _quickStorageCache;
					_parent.htmlTemplate({
						templateID: '#dot-quick-acess',
						method: 'append',
						appendField: '.quick_acess',
						data: _valid_page,
						callback: function(){
							$('.quick_acess .tile_item .most_view_page').each(function(){
								$(this).bind('error', function(){
									var _url = $(this).attr('origin_url');
									$(this).parent().append('<a class="favicon"><img src="chrome://favicon/size/16@1x/' + _url + '" />' + urlReg.exec(_url)[0] + '</a>');
									$(this).remove();
								});
							});
						}
					});
				}else{
					$.getJSON(KW_BROWSER_NTP.HOST.QUICKACESS + "site/hotlist/?callback=?", function(response) {
						if (response.ok) {
							var _site_list = response.data.site_list;
							//localStorage.setItem('quick_site', JSON.stringify(_site_list));
							for (var i = 0; _len < 12; i++) {
								var _qucik_acess = _site_list[i];
								var _change = true;
								for (var j = 0, _valid_len = _valid_page.length; j < _valid_len; j++) {
									if (urlReg.exec(_qucik_acess.url)[0] == _valid_page[j].domain) {
										_change = false;
									}
								}
								if (_change && _qucik_acess) {
									_qucik_acess.recommend = true;
									_qucik_acess.title = _site_list[i].name;
									_valid_page.push(_qucik_acess);
									_len++;
								}
							}
							//设置缓存一小时
							Cache.set('quick_access', _valid_page, 3600);
							$('.quick_acess .tile_grid').remove();
							_parent.htmlTemplate({
								templateID: '#dot-quick-acess',
								method: 'append',
								appendField: '.quick_acess',
								data: _valid_page,
								callback: function(){
									var urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
									$('.quick_acess .tile_item .most_view_page').each(function(){
										$(this).bind('error', function(){
											var _url = $(this).attr('origin_url');
											$(this).parent().append('<a class="favicon"><img src="chrome://favicon/size/16@1x/' + _url + '" />' + urlReg.exec(_url)[0] + '</a>');
											$(this).remove();
										});
									});
								}
							});
						} else {
							console.log('getQuickAndHotGame error:' + response.reason);
						};
					});
				}		
			};
		},
		compatQuickAcessPage: function() {
			//console.log('compact');
			var _parent = this;
			if (KW_BROWSER_NTP.VERSION) {
				var _compare_result = _parent.compareVersion(KW_BROWSER_NTP.VERSION, '1.4.51.0');
				if (_compare_result >= 0) {
					chrome.send('getMostVisited');
				} else {
					_parent.renderQuickAcess([]);
				}	
			} else {
				_parent.renderQuickAcess([]);
			}
		},
		initQuickAcessPage: function() {
			var _parent = this;
			// _parent.compatQuickAcessPage();
			//only the most visited page have the delete option
			$('.quick_acess').delegate('.close', 'click', function(e) {
				chrome.send('blacklistURLFromMostVisited', [$(this).data('url')]);
				chrome.send('getMostVisited');
				return false;
			});
		},
	};
	$.extend(true, window.KW_BROWSER_NTP.Events, QuickAccess);
})(window, $);

//热播影视
(function(window, $){
	var moreLinks = {
		newest: 'http://www.yunfan.com/list/list_mo.php?showtype=bigimg&list=1&rank=createtime&cat=2&year=all&area=all&act=&from=yfe-ntp',
		movie: 'http://www.yunfan.com/list/list_mo.php?showtype=bigimg&list=1&rank=recom&act=&cat=all&area=all&year=2014&from=yfe-ntp',
		teleplay: 'http://www.yunfan.com/list/list_tv.php?showtype=bigimg&list=1&rank=rankhot&cat=all&year=2014&area=all&act=&from=yfe-ntp',
		variety: 'http://www.yunfan.com/list/list_va.php?from=yfe-ntp',
		cartoon: 'http://www.yunfan.com/list/list_ct.php?showtype=bigimg&rank=rankhot&cat=all&area=all&year=2014&from=yfe-ntp'
	};
	
	var HotVideo = {
		initSliderNav: function(opt) {
			var _$nav = opt.obj,
				_$slider = _$nav.find('.slider'),
				_slider_width = 0,
				_slider_width_arr = [0],
				_callback_timer = null;
			_$nav.find('li').each(function(i) {
				var _this = this,
					_li_width = $(this).width(),
					_margin = _$nav.hasClass('navheader') ? 10 : 0; //{margin-right = 10}
				_slider_width += _li_width + _margin;
				_slider_width_arr.push(_slider_width);
				$(this).bind('mouseover', function() {
					_$nav.find('.selected').removeClass('selected');
					_$slider.css({
						'width': _li_width + 'px',
						'left': _slider_width_arr[i]
					});
					$(this).find('a').addClass('selected');
					if (_callback_timer) {
						clearTimeout(_callback_timer);
						_callback_timer = null;
					}
					_callback_timer = setTimeout(function(){
						if (opt.callback) {
							opt.callback({
								nav: _$nav,
								li: $(_this)
							});
						}
					}, 200);
				});
			});
		},	
		initMoviePage: function() {
			//获取海报及分类
			this.getFilmContent();
			//获取追剧信息
			this.getFilmChase();
			//获取猜你喜欢
			this.getFilmUlike();
			//切换猜你喜欢和追剧信息

			//分类切换
			var Tab = window.Base.Plugins.Tab,
				$tabElem = $('.film-fonts>.title>span'),
				tab = new Tab({'tabs': $tabElem, 'trigger': 'click'});
			tab.addEvent('select', function(index){
				$tabElem.removeClass('sel').eq(index).addClass('sel');
				$('.film-right-list').hide().eq(index).show();
			});
		},
		getBrowserUid: function(){
			var uid = document.getElementById('yunfan-assist').getHardwareUserId();
			return uid;
		},
		getFilmChase: function(){
			var updateRedDot = function(showDot){
				if(showDot){
					$('#chase-title').prepend('<div class="red-hot"></div>');
				}
			};

			var self = this,
				uid = self.getBrowserUid();
			$.getJSON(KW_BROWSER_NTP.HOST.FILM_CHASE + '?uid=' + uid + '&num=8' + '&callback=?', function(data){
				//updateRedDot(data.reddot);
				var tpl = doT.template($('#dot-filmVideo-chase').text()),
					html = tpl(data);

				$('#film-chase-wrap').prepend(html);
				
				$('[open-player="1"]').off('click').on('click', function(){
					var $self = $(this),
						sn = $self.data('sn'),
						docid = $self.attr('data-docid'),
						classid = $self.attr('data-classid'),
						title = $self.data('title'),
						url = 'chrome://yf-player#url=&title=' + encodeURIComponent(title) + '&docid=' + docid + '&classid=' + classid + '&sn=' + sn + '&from=yfe-ntp';
					
					document.getElementById('yunfan-assist').openYFExplorerWithUrl(url);
				});
			});
		},
		getFilmUlike: function(){
			var self = this,
				uid = self.getBrowserUid(),
				$wrap = $('#film-ulike-wrap');


			$wrap.append($('<img class="loading" src="images/loading.gif">').css({marginLeft: 78, marginTop: 86, display: 'block'}));
			$.getJSON(KW_BROWSER_NTP.HOST.FILM_ULIKE + '?uid=' + uid + '&num=3' + '&callback=?', function(data){
				var tpl = doT.template($('#dot-ulike').text()),
					html = tpl(data);

				$wrap.html(html);
			});

		},
		getFilmContent: function(){
			var Tab = window.Base.Plugins.Tab;
			//海报
			var coverSlide = function(){
				var slide = {
					elems: null,
					dotElems: null,
					interval: null,
					isAnimate: false,
					index: 0,
					play: function(){
						var self = this;
						this.interval = setInterval(function(){
							self.next();
						}, 3000);
					},
					stop: function(){
						if(this.interval){
							clearInterval(this.interval);
							this.interval = null;
						}
					},
					next: function(){
						if(this.isAnimate) return false;
						var _index = this.index,
							_size = this.elems.size();

						_index++; 
						if(_index >= _size){
							_index = 0;
						}

						this.fade(_index);
					},
					prev: function(){
						if(this.isAnimate) return false;
						var _index = this.index,
							_size = this.elems.size();

						_index--;
						if(_index < 0){
							_index = _size - 1;
						}

						this.fade(_index);
					},
					fade: function(_index){
						this.isAnimate = true;
						this.index = _index;

						var self = this;
						this.elems
						.eq(_index)
						.css({'opacity': 0, 'zIndex': 10})
						.animate({'opacity': 1}, 400, function(){
							self.isAnimate = false;
							$(this).css('zIndex', 2).siblings().css('zIndex', 1);
						});

						this.dotElems
						.removeClass('ok')
						.eq(_index)
						.addClass('ok');
					},
					onEvents: function(){
						var $dotElems = this.dotElems,
							$elems = this.elems,
							self = this;

						$elems
						.on('mouseenter', function(){
							self.stop();
						})
						.on('mouseleave', function(){
							self.play();
						})

						$dotElems
						.on('mouseover', function(event){
							event.stopPropagation();
							var _index = $(this).index();
							self.stop();
							self.fade(_index);
						})
						.on('mouseout', function(event){
							event.stopPropagation();
							self.play();
						})
					},
					init: function(){
						this.elems = $('#film-slide>ul>li');
						this.dotElems = $('#film-slide>.right-button>span');
						this.onEvents();
						this.play();
					}
				};

				slide.init();
			};

			//分类
			var cateShow = function(){
				var $nav = $('#film-cate span');

				//分类切换
				var tab = new Tab({'tabs': $nav, 'trigger': 'mouseover'});
				tab.addEvent('select', function(index){
					$('.film-li>ul').hide().eq(index).show();
					$nav.removeClass('sel').eq(index).addClass('sel');
				});
			};

			//渲染模板
			var renderTpl = function(data){
				//海报图
				var hdp_tpl = doT.template($('#dot-filmVideo-hdp').text()),
					hdp_render = hdp_tpl(data.hdp);

				$('#film-slide').find('.loading').remove();
				$('#film-slide').prepend(hdp_render);
				coverSlide();

				//热门,电视剧,电影,综艺,动漫
				var items = ['tj', 'tv', 'film', 'zy', 'ct'];
				for(var i=0,item; item=items[i++]; ){
					var tpl = doT.template($('#dot-filmVideo-item').text());
					for(var n=0,l=data[item].length; n<l; n++){
						data[item][n].key = i;
					}
					$('.film-li').append(tpl(data[item]));
				}

				$('.film-li').find('.loading').remove();
				$('.film-li>ul').eq(0).show();
				cateShow();
			};

			//显示loading
			var $filmSlide = $('#film-slide'),
				_filmSlideWidth = $filmSlide.width(),
				_filmSlideHeight = $filmSlide.height(),
				$filmCat = $('.film-li'),
				_filmCatWidth = $filmCat.width(),
				_filmCatHeight = $filmCat.height();

			$filmSlide.append($('<img class="loading" src="images/loading.gif">').css({marginLeft: (_filmSlideWidth - 35)/2, marginTop: (_filmSlideHeight - 35)/2, display: 'block'}));
			$filmCat.append($('<img class="loading" src="images/loading.gif">').css({marginLeft: (_filmCatWidth - 35)/2, marginTop: (_filmCatHeight - 35)/2, display: 'block'}));

			//获取海报及分类
			$.jsonp(
				{
					url: KW_BROWSER_NTP.HOST.FILM_CONTENT,
					callbackParameter: 'callback',
					callback: 'callback',
					success: function(json){
						renderTpl(json);
					}
				}
			);

			var getRandomRange = function(min, max){
				return Math.floor(Math.random() * (max - min + 1)) + min;
			};

			//获取推荐关键词
			$.jsonp(
				{
					url: KW_BROWSER_NTP.HOST.YF_SEARCH_RECOMMEND,
					callbackParameter: 'callback',
					callback: 'cb',
					success: function(json){
						var data = json.data,
							len = data.length;
						if(json.ok && len > 0){
							var rand = getRandomRange(0, len - 1),
								text = data[rand]['moviename'];

							$('#film-search-form input')
							.val(text)
							.on('focus', function(){
								$(this).val('');
							})
							.on('blur', function(){
								var $self = $(this);
								if($self.val() == ''){
									$self.val(text);
								}
							});

							$('#film-search-form').on('submit', function(e){
								e.preventDefault();
								var $input = $(this).find('input'),
									val = $input.val(),
									action = $(this).attr('action'),
									url = '';

								if(val == ''){
									url = 'http://www.yunfan.com/list/list_mo.php?from=yfe-ntp';
								}else{
									url = 'http://www.yunfan.com/s.php?q=' + val + '&from=yfe-ntp';
								}

								window.open(url);
							});
						}
					}				
				}
			);
		},
		playVideo: function(data){
			var _url = 'kwe://yf-player/#url=' + data.url + '&title=' + data.title + '&docid=' + data.docid + '&classid=' +  data.classid + '&swf=';
			chrome.send("openYFPlayer", [_url]);
		}
	};
	$.extend(true, window.KW_BROWSER_NTP.Events, HotVideo);
})(window, $);

//美女主播
(function(window, $){
	var MM = {
		initTuliAnchorPage: function() {
			var _parent = this;
			var _$loading = $('.announcer_con .loading');
			var _$online_num = $('.h_num span');
			_$loading.css('display', 'block');
			$('.h_num').bind('click', function(){
				var _web_stats = {
					'doc_type': 'TuliAnchor',
					'location': 'BQ_02_1000',
					'ntp_version': KW_BROWSER_NTP.Page_Info.version
				}
				try {
					chrome.send('webStats', [JSON.stringify(_web_stats)]);
				} catch(e) {
					console.log(e);
				}
			});
			
			var _url = KW_BROWSER_NTP.HOST.TULIANCHOR + '?page_number=1&page_size=15';
			$.ajax({
				type: "get",
				url: _url,
				dataType: "jsonp",
				success: function(response) {
					_$loading.remove();
					_$online_num.text(response.data.total);
					_parent.htmlTemplate({
						templateID: '#dot-tuli-anchor',
						method: 'append',
						appendField: '.announcer_con',
						data: response.data.mm_data,
						callback: function(){}
					});
				}
			})
		}
	};
	$.extend(true, window.KW_BROWSER_NTP.Events, MM);
})(window, $);

//九宫格及iframe
(function (window, $){
	var Remote = {
		//九宫格
		initSquaredPage: function(item){
			var _parent = this;
			if(item.channel_url){
				//显示loading状态
				var $img = $('<img class="loading" src="images/loading.gif" style="display: none;">'),
					$page = $('.page_item.' + item['channel']);
				
				$page.append($img);
				
				$.jsonp({
					url: item.channel_url,
					timeout: 5000,
					success: function(response){
						//格式化数据
						var data = response.data;
						for(var i=0,len=data.length; i<len; i++){
							data[i].recommend = true;
							data[i].title = data[i].name
						}

						$page.find('.loading').remove();
						_parent.htmlTemplate({
							templateID: '#dot-quick-acess',
							method: 'append',
							appendField: $page,
							data: response.data,
							callback: function(){}
						});
					},
					error: function(){
						$page.find('.loading').remove();
						$page.append('请求数据错误');
					}
				})
			}
		}
	};
	
	$.extend(true, window.KW_BROWSER_NTP.Events, Remote);
})(window, $);

//换肤功能
(function(){
	var Skin = {
		initSkin: function(){
			this.getSkinThumbs();
			this.bindSkinEvents();
		},
		stat: function(type, code){
			var _web_stats = {'doc_type': 'browser_skin', 'type': type, 'code': code || '', 'ntp_version': KW_BROWSER_NTP.Page_Info.version};
			try {
				chrome.send('webStats', [JSON.stringify(_web_stats)]);
			} catch(e) {
				console.log(e);
			}
		},
		bindSkinEvents: function(){
			var $skinBox = $('.skin-setup-box'),
				$skinCloseBtn = $('.skin-setup-box .close'),
				$skinOpenBtn = $('.skin-peeler .skin'),
				self = this;
			
			//关闭皮肤窗口
			$skinCloseBtn.on('click', function(event){
				event.stopPropagation();
				$skinBox.hide();
			});
			
			//打开皮肤窗口
			$skinOpenBtn.on('click', function(event){
				event.stopPropagation();
				if($skinBox.is(':visible')){
					$skinBox.hide();
				}else{
					$skinBox.show();
					self.stat('open');
				}				
			});
			
			//更换皮肤
			$skinBox.on('click', '.setup-list li', function(event){
				event.stopPropagation();
				
				var $self = $(this),
					url = $self.data('url'),
					type = $self.data('type'),
					code = $self.data('code'),
					md5 = $self.data('md5'),
					isCrx = (type == 'crx' ? true : false),
					isLocal = (type == 'local' ? true : false),
					cur_skin = localStorage.getItem('skin_code');
					
				//如果正在加载的话或者已经选择,则取消
				if($self.parent().find('.load-diagram').length > 0 || cur_skin == code) return false;
				
				try{
					$self.siblings().removeClass('select');
					$self.addClass('select').prepend('<div class="load-diagram"></div>');
					chrome.send('changeBrowserBack', [url, isCrx, isLocal, md5]);
					 
					var _type = isLocal ? 'ex_offline' : 'ex_online';
					self.stat(_type, code);
				}catch(e){
					console.log(e);
				}			
			});
			
		},
		getSkinThumbs: function(){
			var skins = localStorage.getItem('skin_thumbs'),
				s = screen,
				w = s.width,
				h = s.height,
				isRender = false,
				self = this;
				
			if(skins){
				skins = JSON.parse(skins);
				if(skins.length > 0 && Base.Common.typeOf(skins) == 'array'){
					isRender = true;
					this.renderSkin(skins);
				}
			}
			
			$.jsonp({
				url: window.KW_BROWSER_NTP.HOST.SKIN_URL + '&w=' + w + '&h=' + h,
				timeout: 5000,
				success: function(response){
					//格式化数据
					var data = response.data || [];
					if(Base.Common.typeOf(data) == 'array'){
						localStorage.setItem('skin_thumbs', JSON.stringify(data));
					}
					
					if(!isRender) self.renderSkin(data);
				},
				error: function(){}
			})
		},
		renderSkin: function(data){
			var tpl = doT.template($('#dot-skins').text()),
				code = localStorage.getItem('skin_code'),
				tpl_data = {
					data: data,
					code: code
				};
			$('#dot-skins-box').html(tpl(tpl_data));
		}
	};
	
	$.extend(true, window.KW_BROWSER_NTP.Events, Skin);
})(window, $);

//初始化
$().ready(function(){
	KW_BROWSER_NTP.Events.init();
});