$().ready(function() {
	window.KW = {
		Models: {},
		Views: {},
		Controllers: {},
		Collections: {},
		plugin: {
			htmlTemplate: function(option) {
				var defaultOption = {
					method: "append",
					appendField: "body",
					data: {}
				};
				var option = $.extend(true, defaultOption, option);
				var result = doT.template($(option.templateID)[0].text);
				var f = $(option.appendField)[option.method](result(option.data));
				if (option.callback) {
					f.each(function() {
						option.callback();
					});
				};
			}
		},
		Version: '1.1.0.1'
	};
	//strsub the game_id array for the current category
	var strsubGameId = function(opt) {
		var defaultOption = {
			page: 1,
			refresh: true
		};
		var option = $.extend(true, defaultOption, opt);
		var _category_info = kw_model_main.get('Category_info');
		_category_info.current_page = option.page;
		var _total_game_id = _category_info.total_game_id.slice(0);
		if (_total_game_id.length == 0) {
			return false;
		}
		var _game_page_size = _category_info.loading ? _category_info.game_page_size - 1 : _category_info.game_page_size,
			_splice_start_index = 0,
			_page_num = Math.ceil(_total_game_id.length / _game_page_size);
		_category_info.game_page = [];
		for (var i = 0; i < _page_num; i++) {
			_category_info.game_page[i] = _total_game_id.splice(_splice_start_index, _game_page_size);
		}
		initPaging({
			curr_page: option.page
		});
		if (option.refresh) {
			try {
				chrome.send('getLocalGame', [JSON.stringify(_category_info.game_page[option.page - 1])]);
			} catch (e) {
				console.log(e);
			};
		}
	}
	var initPaging = function(opt) {
		var _this = this;
		var _category_info = kw_model_main.get('Category_info');
		var _page_count = _category_info.game_page.length;
		var option = opt ? opt : {};
		var page = curr_page = parseInt(option.curr_page);

		if (_page_count <= 1) {
			$('.scan_pages').remove();
		} else {
			var page_step = 4, //max-view is 5 page btn
				_is_first = curr_page <= 1 ? true : false,
				_is_end = curr_page == _page_count ? true : false;
			curr_page = (curr_page) >= page_step ? curr_page - 2 : 1;
			curr_page = curr_page <= 0 ? 1 : curr_page;
			var loop_page = (page_step + curr_page) >= _page_count ? _page_count : (page_step + curr_page);
			curr_page = (loop_page - curr_page) < page_step ? (loop_page - page_step) : curr_page;
			curr_page = _page_count <= page_step ? 1 : curr_page;
			var previous_page = (page - 1) <= 1 ? 1 : (page - 1);
			var next_page = (page + 1) >= _page_count ? _page_count : (page + 1);
			var _page_tpl_data = {
				previous_page: previous_page,
				next_page: next_page,
				curr_page: curr_page,
				loop_page: loop_page,
				_is_first: _is_first,
				_is_end: _is_end,
				page: page
			};
			$('.scan_pages').remove();
			KW.plugin.htmlTemplate({
				templateID: '#dot-scan-game-paging',
				method: 'append',
				appendField: '.game_list',
				data: _page_tpl_data
			});
			$(".scan_pages a").click(function(e) {
				e.preventDefault();
				if ($(this).hasClass('pages_prev') || $(this).hasClass('pages_next')) {
					if ($(this).parent().hasClass('pages_not')) {
						return false;
					};
				} else {
					if ($(this).parent().hasClass('pages_on')) {
						return false;
					};
				};
				strsubGameId({
					'page': $(this).attr("page")
				});
			});
		};
	}
	//Model
	KW.Models.Main = Backbone.Model.extend({
		defaults: {
			scan: false,
			Category_info: {
				game_page: [],
				type: 'all',
				game_page_size: null,
				game_column: null,
				current_page: null,
				total_game_id: [],
				loading: true,
				deleteGameId: function(game_id) {
					var _index = this.total_game_id.indexOf(game_id);
					if (_index > -1) {
						this.total_game_id.splice(_index, 1);
					};
				}
			}
		},
		initialize: function() {

		}
	});
	window.kw_model_main = new KW.Models.Main;
	//Views
	KW.Views.ScanInit = Backbone.View.extend({
		el: '#scan_init',
		events: {
			"click #scan_start": "startScan"
		},
		startScan: function() {
			localStorage.setItem('firstScan', true);
			Backbone.history.navigate("main", {
				trigger: true
			});
			return false;
		}
	});
	var kw_views_scan_init = new KW.Views.ScanInit();
	KW.Views.ScanMain = Backbone.View.extend({
		el: "#scan_main",
		model: kw_model_main,
		events: {
			"click .operate_scan": "operateScan",
			"click .scan_topbar li": "categoryClick",
			"mouseover .scan_history_list li": "showDeleteBtn",
			"mouseout .scan_history_list li": "hideDeleteBtn",
			"click .delete_g": "deleteGame",
			"click .delete_cancel,.close": "cancelDelete",
			"click .delete_ensure": "sureDelete",
			"click .stats": "statsOpenGame"
		},
		initialize: function() {
			$('body').keyup(function(e){
				if ($('.scan_delete').length > 0) {
					if (e.keyCode == 13) {
						$('.delete_ensure').trigger('click');	
					} else if (e.keyCode == 27) {
						$('.scan_delete .close').trigger('click');
					}
				}
			});
		},
		operateScan: function(e) {
			var _this = this,
				_$this = $(e.currentTarget),
				_rescan = _$this.data('operate') == 'rescan' ? true : false;
			_$this.text(_rescan ? '停止扫描' : '重新扫描');
			var _category_info = _this.model.get('Category_info');
			_category_info.loading = _rescan ? true : false;
			$('.scan_history_list .loading_flag')[_rescan ? "show" : "hide"]();
			_$this.data('operate', _rescan ? 'stopscan' : 'rescan');
			$('.scan_area img').attr('src', _rescan ? 'images/scan.gif' : '/images/scan_ani.png');
			try {
				chrome.send('localGameScan', [_rescan ? 1 : 0]);
				if (_rescan) {
					localStorage.setItem('lastScanTime', Date.parse(new Date()));
					//stats
					chrome.send('webStats', [11009]);
				}
			} catch (e) {
				console.log('localGameScan ' + (_rescan ? 1 : 0) + ' error:', e);
			};
			if (_rescan) {
				if ($('.scan_history_none').length > 0) {
					$('.scan_history_none').remove();
				}
				KW.plugin.htmlTemplate({
					templateID: '#dot-scan-game-list',
					method: 'html',
					appendField: '.scan_history_list',
					data: {
						loading: _category_info.loading,
						data: {}
					},
					callback: function() {
						KW.plugin.adjustWebPage();
						$('.game_list').show();
					}
				});
			} else {
				if ($('.scan_history_list .scan_game').length == 0 && $('.scan_history_none').length == 0) {
					$('.game_list').hide();
					KW.plugin.htmlTemplate({
						templateID: '#dot-scan-game-none',
						method: 'append',
						appendField: '.scan_left'
					});
				}
			}
			return false;
		},
		categoryClick: function(e) {
			var _this = this,
				_$this = $(e.currentTarget);
			if (_$this.parent('li').hasClass('scan_on')) {
				return false;
			}
			$('.scan_on').removeClass('scan_on');
			_$this.addClass('scan_on');
			_this.model.get('Category_info').type = _$this.attr('key');
			chrome.send('selectGameTab', [_$this.attr('key')]);
			e.stopPropagation();
			e.preventDefault();
		},
		showDeleteBtn: function(e) {
			$(e.currentTarget).find('.delete_g').show();
		},
		hideDeleteBtn: function(e) {
			$(e.currentTarget).find('.delete_g').hide();
		},
		deleteGame: function(e) {
			var _this = this,
				_$this = $(e.currentTarget),
				_game_id = _$this.data('gameid');
			if (localStorage.getItem('deleteNotRemind') == "yes") {
				_this.standardDelete(_game_id);
			} else {
				var _top = parseInt($(document).height() / 2) - 170,
					_left = parseInt($(document).width() / 2) - 190;
				_top = _top > 0 ? _top : 0;
				_left = _left > 0 ? _left : 0;
				KW.plugin.htmlTemplate({
					templateID: '#dot-scan-game-delete',
					method: 'append',
					appendField: '#scan_main',
					data: {
						game_id: _game_id,
						pos: {
							top: _top,
							left: _left
						}
					}
				});
			}
			return false;
		},
		cancelDelete: function() {
			$('.scan_delete').remove();
			return false;
		},
		sureDelete: function(e) {
			var _this = this,
				_$this = $(e.currentTarget),
				_game_id = _$this.data('gameid');
			localStorage.setItem('deleteNotRemind', $('.no_remind input').prop('checked') ? "yes" : "no");
			_this.standardDelete(_game_id);
			return false;
		},
		standardDelete: function(game_id) {
			var _this = this;
			try {
				chrome.send('deleteLocalGame', [game_id]);
				//stats
				chrome.send('webStats', [11008, (game_id).toString()]);
			} catch (e) {
				console.log(e);
			}
			var _category_info = _this.model.get('Category_info'),
				_index = $('.scan_history_list li').index($('._game_' + game_id)),
				_next_page_first_game = _category_info.current_page < _category_info.game_page.length ? _category_info.game_page[_category_info.current_page][0] : false;
			_index = _category_info.loading ? _index - 1 : _index;
			if (_index >= 0 && _next_page_first_game) {
				_category_info.total_game_id = _.without(_category_info.total_game_id, parseInt(_next_page_first_game));
				_category_info.total_game_id[_index + (_category_info.current_page - 1) * _category_info.game_page_size] = _next_page_first_game;
				strsubGameId({
					page: _category_info.current_page
				});
			} else {
				_category_info.total_game_id = _.without(_category_info.total_game_id, parseInt(game_id));
				$('._game_' + game_id).remove();
			}
			$('.scan_delete').remove();
			if ($('.scan_history_list .scan_game').length == 0) {
				if (_category_info.current_page != 1) {
					strsubGameId({
						page: _category_info.current_page - 1
					});
				} else if (_category_info.type != 'all') {
					$("[key=" + _category_info.type + "]").remove();
					$("[key=all]").trigger('click');
				}
			};
		},
		statsOpenGame: function(e) {
			try {
				var _id = $(e.currentTarget).data('gameid');
				chrome.send('webStats', [11007 , (_id).toString()]);
			} catch (e) {
				console.log(e);
			}
		}
	});
	var kw_views_scan_main = new KW.Views.ScanMain();

	KW.Controllers.Routes = Backbone.Router.extend({
		initialize: function() {},
		routes: {
			"": "scanInit",
			"main": "scanMain"
		},
		initSection: function(id) {
			$('section').empty().removeClass('current');
			$(id).addClass('current');
		},
		scanInit: function() {
			if (localStorage.getItem('firstScan')) {
				Backbone.history.navigate("main", {
					trigger: true
				});
			} else {
				this.initSection('#scan_init');
				KW.plugin.htmlTemplate({
					templateID: '#dot-scan-game-init',
					method: 'append',
					appendField: '#scan_init'
				});
			}
		},
		scanMain: function() {
			var _this = this,
				lastScanTime = localStorage.getItem('lastScanTime'),
				_category_info = kw_model_main.get('Category_info');
			_this.initSection('#scan_main');
			var scanGame_trigger = function(loading) {
				_category_info.loading = loading;
				try {
					chrome.send('localGameScan', [loading ? 1 : 2]);
				} catch (e) {
					console.log(e);
				};
				localStorage.setItem('lastScanTime', Date.parse(new Date()));
			}
			if (lastScanTime) {
				var newDate = Date.parse(new Date());
				if (!(newDate - localStorage.getItem('lastScanTime') <= 86400000)) {
					scanGame_trigger(true);
				} else {
					scanGame_trigger(false);
				}
			} else {
				scanGame_trigger(true);
			}
			KW.plugin.adjustWebPage = _this.adjustWebPage;
			var scanGame = function() {
				_this.adjustWebPage();
				_this.initGlobalEvent();
				chrome.send('getKWEInfo');
			};
			KW.plugin.htmlTemplate({
				templateID: '#dot-scan-game-content',
				method: 'append',
				appendField: '#scan_main',
				data: {
					loading: _category_info.loading
				},
				callback: scanGame
			});
		},
		initGlobalEvent: function() {
			var _this = this;
			var _resizeTimer = null;
			$(window).bind({
				resize: function() {
					//resize delete remind
					if ($('.scan_delete').length > 0) {
						var _top = parseInt($(document).height() / 2) - 170,
							_left = parseInt($(document).width() / 2) - 190;
						_top = _top > 0 ? _top : 0;
						_left = _left > 0 ? _left : 0;
						$('.scan_delete').css({
							top: _top,
							left: _left
						});
					};
					//init page
					if (_resizeTimer) {
						clearTimeout(_resizeTimer);
						_resizeTimer = null;
					};
					_resizeTimer = setTimeout(function() {
						_this.adjustWebPage();
					}, 100);
				}
			});
		},
		adjustWebPage: function() {
			var GAMEICON = {
				width: 108,
				height: 213
			};
			var Gird = {
				row: 5, //fixed value
				column: 7, //min value
				min_width: 7 * GAMEICON.width,
				max_height: 5 * GAMEICON.height
			};
			var _category_info = kw_model_main.get('Category_info');
			var _$game_list = $('.game_list');
			var _width = _$game_list.width();
			var _height = _$game_list.height();
			if (_width < Gird.min_width) {
				_width = Gird.min_width;
			} else {
				var _column = parseInt(_width / GAMEICON.width);
				Gird.column = _column < Gird.column ? Gird.column : _column;
			};
			if (Gird.column == _category_info.column) {
				return false;
			};
			_category_info.game_page_size = Gird.row * Gird.column;
			_category_info.game_column = Gird.column;
			_$game_list.find('ul').css({
				width: Gird.column * GAMEICON.width
			});
			strsubGameId({
				page: 1
			});
		}
	});
	var KW_Scan_routes = new KW.Controllers.Routes();
	Backbone.history.start();

	window.renderCategory = function(data) {
		$('.scan_topbar').empty();
		KW.plugin.htmlTemplate({
			templateID: '#dot-scan-game-category',
			method: 'append',
			appendField: '.scan_topbar',
			data: data
		});
	}

	window.renderLocalGame = function(opt) {
		var option = opt ? opt : {};
		if (option.data) {
			var games = option.data,
				_category_info = kw_model_main.get('Category_info'),
				page_game_data = _category_info.game_page[_category_info.current_page - 1],
				_template_data = [],
				_game_info;
			for (var i in page_game_data) {
				_game_info = games[page_game_data[i]];
				_template_data.push(_game_info);
			};

			$('.scan_history_list').empty();
			KW.plugin.htmlTemplate({
				templateID: '#dot-scan-game-list',
				method: 'append',
				appendField: '.scan_history_list',
				data: {
					loading: _category_info.loading,
					data: _template_data
				},
				callback: function() {
					$('.game_list').show();
				}
			});
		};
	}

	//CallBack
	//return category
	window.onLocalGameScan = function(data) {
		console.log(data);
		try {
			var _data = JSON.parse(data);
		} catch (e) {
			console.log("category data error");
			return false;
		}
		renderCategory(_data);
	}
	//return category's game array and game count
	window.onSelectGameTab = function(data) {
		console.log(data);
		try {
			var _source = JSON.parse(data);
		} catch (e) {
			console.log("category game data error!");
			return false;
		}
		var _data = _source;
		$('.scan_area label').text(_data.game_count);
		var _category_info = kw_model_main.get('Category_info');
		//scan over
		if (_data.scan_over == 1) {
			_category_info.loading = false;
			var _$operate_scan = $('.operate_scan');
			if (_$operate_scan.data('operate') == 'stopscan') {
				_$operate_scan.text('重新扫描');
				_$operate_scan.data('operate', 'rescan');
				$('.scan_area img').attr('src', "/images/scan_ani.png");
			}
		};
		if (_data.game_id.length > 0) {
			$('.scan_history_none').remove();
			_category_info.total_game_id = _data.game_id;
			strsubGameId({
				page: 1
			});
		} else {
			if (_category_info.loading == false) {
				if (_category_info.type === 'all') {
					if ($('.scan_history_none').length == 0) {
						$('.game_list').hide();
						KW.plugin.htmlTemplate({
							templateID: '#dot-scan-game-none',
							method: 'append',
							appendField: '.scan_left'
						});
					}
				} else {
					$('.scan_history_list').empty();
					$('.scan_pages').remove();
				}
			}
		}
	}

	window.onGetLocalGame = function(data) {
		try {
			var _data = JSON.parse(data);
		} catch (e) {
			console.log("category game detail error!");
			return false;
		}
		renderLocalGame({
			data: _data
		});
	}

	window.onGetKWEInfo = function(data) {
		try {
			var _data = JSON.parse(data);
		} catch (e) {
			console.log("get kwInfo data error!");
			return false;
		}
		var _href = $('.scan_feedback a').attr('href');
		if (_data.ver) {
			KW.Browser_ver = _data.ver;
			_href += (_href.indexOf('?') != -1 ? '&' : '?') + "kwe_ver=" + _data.ver;
		}
		if (_data.online_token) {
			_href += (_href.indexOf('?') != -1 ? '&' : '?') + "online_token=" + _data.online_token;
		}
		_href += (_href.indexOf('?') != -1 ? '&' : '?') + 'localGameScan_ver=' + KW.Version;
		$('.scan_feedback a').attr('href', _href);
	}
});