// 联想词逻辑
var searchText = '';
function suggests(){
	var text = $('#keyword').val();
	if(text != '' && text != '输入片名、演员名、导演名'){
		$('.clean').show();
	}else{
		$('.clean').hide();
	}
	
	if(text == ''){
		$('.keyword').hide();
		switch_divs('on');
	}else{
		if(text != '' && searchText != text){
			searchText = text;
			loadJSData(
				'http://xl7ac.kankan.xunlei.com/ac4phone.php?limit=10&wap=1&k=' + encodeURIComponent(text),
				'utf-8',
				function(){
					switch_divs('off');
					$('.keyword').hide();
					var results = '';
					if(suggestResults.data.items.length != 0){
						for(var i in suggestResults.data.items){
							if(suggestResults.data.items[i].title != undefined){
								results += '<li><a href="http://kankan.junze.org/search.php?keyword=' + suggestResults.data.items[i].title + '">' + suggestResults.data.items[i].title + '<span aria-hidden="true" data-icon="t"></span></a></li>';
							}
						}
						if(results != ''){
							$('#keyword-info')
								.empty()
								.append(results);
							$('.keyword').show();
						}else{
							switch_divs('on');
						}
					}else{
						switch_divs('on');
					}
				}
			);
		}
	}
}

var divs_power = '';
function switch_divs(power){
	
	if(power == 'on'){
		if(divs_power != 'on'){
			divs_power = 'on';
			if($('.keyword').css('display') == 'block'){
				return;
			}
			if(keyword != null){
				if(has_results){
					$('.search_result').show();
				}else{
					$('.search_no_result').show();
					$('.box').show();
					showHotSearch4NoResult();
				}
			}else{
				$('.hot_search').show();
				showSearchHistory();
			}
			$('.footer').show();
		}
	}else{
		if(divs_power != 'off'){
			divs_power = 'off';
			$('.search_history').hide();
			$('.hot_search').hide();
			$('.search_result').hide();
			$('.search_no_result').hide();
			$('.box').hide();
			$('.footer').hide();
		}
	}
	
}

var sug_power = null;
function updateSuggests(){ // onfocus
	sug_power = setInterval('suggests()', 300);
	if($('#keyword').val() == '输入片名、演员名、导演名'){
		$('#keyword').val('');
	}
	$('#keyword').addClass('on');
}

function updateKeyword(){ // onblur
	clearInterval(sug_power);
	switch_divs('on');
	if($('#keyword').val() == ''){
		$('#keyword').val('输入片名、演员名、导演名');
	}
	$('#keyword').removeClass('on');
}

function doSearch(){
	if($('#keyword').val() == '输入片名、演员名、导演名'){
		$('#keyword').focus();
		return false;
	}else{
		if(ignoreSpaces($('#keyword').val()).length > 0){
			return true;
		}else{
			$('#keyword').val('');
			$('#keyword').focus();
			return false;
		}
	}
}

// 提取当前关键字和历史关键字
var keyword = getParameter('keyword');
if(use_cookie){
	var searchHistory = getCookie('searchHistory');
	var searchHistoryResults = searchHistory.split('|||');
}else{
	var searchHistory = localStorage.getItem('searchHistory');
	if(searchHistory != null){
		var searchHistoryResults = searchHistory.split('|||');
	}else{
		var searchHistoryResults = '';
		searchHistory = '';
	}
}
var page = 1;

// 当前关键字如果存在，立即写入历史关键字，并保持关键词数量不超过5个
if(keyword != null){
	keyword = keyword.replace(/\+/g, ' ');
	var new_results = [encodeURIComponent(keyword)];
	if(searchHistory != ''){
		
		Array.prototype.S = String.fromCharCode(2);
		Array.prototype.in_array = function(e){
			var r = new RegExp(this.S + e + this.S);
			return (r.test(this.S + this.join(this.S) + this.S));
		}
		
		for(var i=0; i<searchHistoryResults.length; i++){
			if(!new_results.in_array(searchHistoryResults[i])){
				if(new_results.length < 5){
					new_results[new_results.length] = searchHistoryResults[i];
				}else{
					break;
				}
			}
		}
	}
	
	if(use_cookie){
		setTimeout(function(){setCookie('searchHistory', new_results.join('|||'), 24 * 31);},0);
	}else{
		localStorage.setItem('searchHistory', new_results.join('|||'));
	}
	$(document).ready(function(){
		$('#keyword').val(keyword);
	});
	
	setTimeout(function(){showSearchResults();},0);
}else{
	$(document).ready(function(){
		$('#keyword').val('输入片名、演员名、导演名');
		showSearchHistory();
		showHotSearch();
	});
}

// 清空关键词
function cleanKeyword(){
	
	$('#keyword')
		.val('')
		.focus();
	$('.keyword').hide();
	switch_divs('on');
	
}

// 清空历史记录
function cleanSearchHistory(){
	
	if(use_cookie){
		setTimeout(function(){setCookie('searchHistory', '', 0);},0);
	}else{
		localStorage.setItem('searchHistory', '');
	}
	searchHistory = '';
	showSearchHistory();
	
}

// 显示搜索历史
function showSearchHistory(){
	
	if(keyword == null){
		
		var result = '';
		
		if(searchHistory == ''){
			/*
			result = '' +
				'<div class="title"><b></b><h2>搜索记录</h2></div>' + 
				'<div class="no_history">' +
					'<b class="ico_movie"></b>' +
					'您还未有搜索记录' +
				'</div>' +
			'';
			*/
		}else{
			result += '<div class="title"><b></b><h2>搜索记录</h2></div>';
			result += '<ul>';
			for(var i=0; i<searchHistoryResults.length; i++){
				result += '<li><a href="http://kankan.junze.org/search.php?keyword=' + decodeURIComponent(searchHistoryResults[i]) + '">' + decodeURIComponent(searchHistoryResults[i]) + '</a></li>';
			}
			result += '</ul>';
			result += '' +
				'<div class="clean_history">' +
					'<a href="javascript:void(0);" onclick="cleanSearchHistory();">清除搜索记录</a>' +
				'</div>' +
			'';
		}
		
		$('.search_history')
			.html('')
			.append(result)
			.show();
	}
	
}

// 显示热门搜索（搜索默认页）
function showHotSearch(){
	
	if(keyword == null){
		if($.client.os == 'Windows'){
			var charset = 'utf-8';
			var url = 'http://search.pad.kankan.com/index4wap_utf8.json';
		}else{
			var charset = 'gbk';
			var url = 'http://search.pad.kankan.com/index4wap.json';
		}
		
		loadJSData(
			url + '?' + new Date().getTime(),
			charset,
			function(){
				var result = '';
				result += '<ul>';
				for(var i in hotSearchResults.data){
					result += '<li><a href="http://kankan.junze.org/search.php?keyword=' + hotSearchResults.data[i].title + '">' + hotSearchResults.data[i].title + '</a></li>';
					if(i == 5){
						break;
					}
				}
				result += '</ul>';
				
				$('.hot_search')
					.html('')
					.append('<div class="title"><b></b><h2>热门搜索</h2></div>' + result)
					.show();
			}
		);
	}
	
}

// 显示或许你对以下内容感兴趣（无结果）
function showHotSearch4NoResult(){
	
	if($.client.os == 'Windows'){
		var charset = 'utf-8';
		var url = 'http://search.pad.kankan.com/index4wap_utf8.json';
	}else{
		var charset = 'gbk';
		var url = 'http://search.pad.kankan.com/index4wap.json';
	}
	
	loadJSData(
		url + '?' + new Date().getTime(),
		charset,
		function(){
			var result = '';
			result += '<ul>';
			for(var i in hotSearchResults.data){
				var score = hotSearchResults.data[i].score.toString();
				if(score == '10'){
					score = '10';
				}else if(score.indexOf('.') < 0){
					score += '.0';
				}
				result += '<li><a href="http://kankan.junze.org/' + Math.floor(hotSearchResults.data[i].id / 1000) + '/' + hotSearchResults.data[i].id + '.shtml?new=1"><span><img src="http://images.movie.xunlei.com/gallery/' + hotSearchResults.data[i].poster + '" alt="' + hotSearchResults.data[i].title + '" /><em>' + (hotSearchResults.data[i].type != 1 ? hotSearchResults.data[i].versionInfo : '') + '</em></span><span>' + hotSearchResults.data[i].title + '<strong>' + score + '</strong></span></a></li>';
				if(i == 5){
					break;
				}
			}
			result += '</ul>';
			
			$('.box2')
				.html('')
				.append('<div class="title"><b></b><h2>或许你对以下内容感兴趣</h2></div>' + result)
				.show();
		}
	);
	
}

// 显示搜索结果
var has_results = false;
function showSearchResults(){
	
	$('.iScroll').hide();
	$('.search_more').hide();
	$('.search_result')
		.append('' +
			'<div class="search_loading">' +
				'<a href="javascript:void(0);"><span>正在加载</span><b></b></a>' +
			'</div>' +
		'')
		.show();
	
	loadJSData(
		'http://search.pad.kankan.com/search4phone.php?keyword=' + keyword + '&ios=3.1&wap=1&page=' + page + '&' + (getParameter('t') != null ? '&t=' + getParameter('t') : ''),
		'utf-8',
		function(){
			$('.search_loading').hide();
			
			// 无结果
			if(searchResults.data.totalItems == 0){
				$('.search_no_result').show();
				showHotSearch4NoResult();
				return;
			}else{
				has_results = true;
				$('.iScroll').show();
			}
			
			// 有结果
			var result = '';
			
			// 导航
			if(searchResults.data.pageIndex == 1){
				$('#channel_ul').append('' +
					'<li' + (getParameter('t') == null ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '">全部(' + searchResults.data.totalItems + ')</a></li>' +
					(searchResults.data.typeNums.movie > 0 ? '<li' + (getParameter('t') == '0' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=0">电影(' + searchResults.data.typeNums.movie + ')</a></li>' : '') +
					(searchResults.data.typeNums.teleplay > 0 ? '<li' + (getParameter('t') == '1' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=1">电视剧(' + searchResults.data.typeNums.teleplay + ')</a></li>' : '') +
					(searchResults.data.typeNums.tv > 0 ? '<li' + (getParameter('t') == '2' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=2">综艺(' + searchResults.data.typeNums.tv + ')</a></li>' : '') +
					(searchResults.data.typeNums.anime > 0 ? '<li' + (getParameter('t') == '3' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=3">动漫(' + searchResults.data.typeNums.anime + ')</a></li>' : '') +
					(searchResults.data.typeNums.video > 0 ? '<li' + (getParameter('t') == '5' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=5">视频快报(' + searchResults.data.typeNums.video + ')</a></li>' : '') +
					(searchResults.data.typeNums.documentary > 0 ? '<li' + (getParameter('t') == '4' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=4">纪录片(' + searchResults.data.typeNums.documentary + ')</a></li>' : '') +
					(searchResults.data.typeNums.lesson > 0 ? '<li' + (getParameter('t') == '7' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=7">公开课(' + searchResults.data.typeNums.lesson + ')</a></li>' : '') +
					(searchResults.data.typeNums.yule > 0 ? '<li' + (getParameter('t') == '8' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=8">娱乐(' + searchResults.data.typeNums.yule + ')</a></li>' : '') +
					(searchResults.data.typeNums.music > 0 ? '<li' + (getParameter('t') == '6' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=6">MTV(' + searchResults.data.typeNums.music + ')</a></li>' : '') +
					(searchResults.data.typeNums.vmovie > 0 ? '<li' + (getParameter('t') == '9' ? ' class="on"' : '') + '><a href="http://kankan.junze.org/search.php?keyword=' + keyword + '&t=9">微电影(' + searchResults.data.typeNums.vmovie + ')</a></li>' : '') +
				'');
				$(document).ready(function(){
					var nav_count = 0;
					$('#channel_ul>li').each(function(){
						if(nav_count++ == 0 && $(this).hasClass('on')){
							return false;
						}else{
							if($(this).hasClass('on')){
								return false;
							}
							nav_pos_search += $(this).width();
						}
					});
					setTimeout(function(){loaded();}, 0);
				});
			}
			result += '' +
				'<div class="search_list">' +
					'<ul>' +
			'';
			for(var i in searchResults.data.items){
				if(searchResults.data.items[i].title == undefined) continue;
				if(searchResults.data.items[i].type == 101 || searchResults.data.items[i].type == 102){
					var play_url = 'http://kankan.junze.org/' + Math.floor(searchResults.data.items[i].id / 1000) + '/' + searchResults.data.items[i].id + '.shtml?new=1';
					var img_url = 'http://ipad.img.kankan.com/video/250x188' + searchResults.data.items[i].poster;
					var version_info = searchResults.data.items[i].flength;
					var director = '';
					var actor = '';
					var year = '';
					var score = '';
				}else if(searchResults.data.items[i].type == 103){
					var play_url = 'http://kankan.junze.org/' + Math.floor(searchResults.data.items[i].id / 1000) + '/' + searchResults.data.items[i].id + '.shtml?new=1';
					var img_url = 'http://ipad.img.kankan.com/music/250x188' + searchResults.data.items[i].poster;
					var version_info = '';
					var director = '';
					var actor = '';
					var year = '';
					var score = '';
				}else{
					var play_url = 'http://kankan.junze.org/' + Math.floor(searchResults.data.items[i].id / 1000) + '/' + searchResults.data.items[i].id + '.shtml?new=1';
					var img_url = 'http://images.movie.xunlei.com/gallery' + searchResults.data.items[i].poster;
					var version_info = searchResults.data.items[i].versionInfo;
					var director = '<span>' + searchResults.data.items[i].directorName + '：<em>' + searchResults.data.items[i].directors.join(' ') + '</em></span>';
					var actor = '<span>' + searchResults.data.items[i].actorName + '：<em>' + searchResults.data.items[i].actors.join(' ') + '</em></span>';
					var year = '<span>年份：<em>' + searchResults.data.items[i].year + '</em></span>';
					var score = searchResults.data.items[i].score.toString();
					if(score == '10'){
						score = '10';
					}else if(score.indexOf('.') < 0){
						score += '.0';
					}
				}
				result += '' +
					'<li>' +
						'<a href="' + play_url + '">' +
							'<span class="img"><img src="' + img_url + '" alt="' + searchResults.data.items[i].title + '" /><em>' + version_info + '</em></span>' +
							'<span class="intro">' +
								'<strong>' + searchResults.data.items[i].title + '</strong>' +
								director +
								actor +
								'<span>类型：<em>' + searchResults.data.items[i].genres.join(' ') + '</em></span>' +
								'<span>地区：<em>' + searchResults.data.items[i].area + '</em></span>' +
								year +
								'<span class="score">' + score + '</span>' +
							'</span>' +
						'</a>' +
					'</li>' +
				'';
			}
			result += '' +
				'</ul>' +
			'</div>';
			
			// 翻页
			if(page < searchResults.data.totalPages){
				page++;
				result += '' +
					'<div class="search_more">' +
						'<a href="javascript:void(0);" onclick="showSearchResults();$(\'.search_more\').hide();">点击查看更多<b aria-hidden="true" data-icon="g"></b></a>' +
					'</div>' +
				'';
			}else{
				result += '' +
					'<div class="search_over">' +
						'<a href="javascript:void(0);">内容已经展示完啦</a>' +
					'</div>' +
				'';
			}
			
			$('.search_result')
				.append(result)
				.show();
		}
	);
	
}