// JavaScript Document
var date;

$(document).ready(function(){
	$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});	
	setInterval("getMatchList()",60000); 
	date = $('#datepicker').val();
	
	Renren.init({appId:appId});
});

var getMatchList = function(){
	$.ajax({
		url: '/live_site/get_live_match.php?matchTime=' + $('#datepicker').val() + '&t=' + Math.random(),
		type: 'GET',
		dataType: 'json',
		timeout: 15000,
		error: function(e){
			//alert(e.responseText);
		},
		success: function(obj){
			
			//初始化
			$('#match_a_bb').html("");
			$('#match_a_fb').html("");
			$('#match_a_nb').html("");
			$('#match_a_zh').html("");
			$('#match_b_bb').html("");
			$('#match_b_fb').html("");
			$('#match_b_nb').html("");
			$('#match_b_zh').html("");
			$('#match_c_bb').html("");
			$('#match_c_fb').html("");
			$('#match_c_nb').html("");
			$('#match_c_zh').html("");
			
			for(var i=0;i<obj.results.length;i++){
				var m = obj.results[i];
				
				var liveClass = "";
				var match = "";
				
				if(m.matchRecord == "直播间" || m.matchRecord == "实录" ){
					match = $('<div class="match live" title="'+m.matchName+'" onclick="matchOpen(\''+ m.matchId + '\',\''+ m.matchOptaId + '\',\'' + m.homeTeam +'\',\'' + m.visitTeam +'\',\'' + m.matchName +'\')"></div>');
				}else{
					match = $('<div class="match" title="'+m.matchName+'"></div>');
				}
				
				var time = '';
                var line = '<div class="line"></div>';
                var team_a = '<div class="team">'+m.homeTeam+'</div>';
				var score_a = '<div class="score">'+m.homeTeamScore+'</div>';
                var team_b = '<div class="team">'+m.visitTeam+'</div>';
				var score_b = '<div class="score">'+m.visitTeamScore+'</div>';
				
				var type = "";
				
				if(m.matchStatus == "已结束"){
					type = "a";
					time = '<div class="time">'+m.matchTime+'</div>';
				}else if(m.matchStatus == "直播中"){
					type = "b";
					time = '<div class="time">'+m.scoreTime+'</div>';
				}else if(m.matchStatus == "未开始"){
					type = "c";
					time = '<div class="time">'+m.matchTime+'</div>';
				}
				
				match.append(time.replace(/\n/g,"<br/>"));
				match.append(line);
				match.append(team_a.replace(/\?/g,"·"));
				if(score_a.indexOf("(") > 0){
					match.append(score_a.substr(0,score_a.indexOf("(")));
				}else{
					match.append(score_a);
				}
				match.append(team_b.replace(/\?/g,"·"));
				if(score_b.indexOf("(") > 0){
					match.append(score_b.substr(0,score_b.indexOf("(")));
				}else{
					match.append(score_b);
				}
				
				if(m.matchCategory == "1"){
					$('#match_'+type+'_bb').append(match);
				}else if(m.matchCategory == "2" || m.matchCategory == "3"){
					$('#match_'+type+'_fb').append(match);
				}else if(m.matchCategory == "4" || m.matchCategory == "5"){
					$('#match_'+type+'_zh').append(match);
				}else if(m.matchCategory == "6"){
					$('#match_'+type+'_nb').append(match);
				}
			}
		}
	});
}

var tab = function(obj){
	$('.head').each(function(i){
		if(this == obj){
	   		this.className = "head home_bg_sport_head_default";
			$($('.content')[i]).show();
		}else{
			this.className = "head";
			$($('.content')[i]).hide();
		}
	});
}

var back = function(){
	$('#searchKey').val("");
	$('.home_bg_match').show();
	$('.home_bg_search_result').hide();
}

var matchOpen = function(matchId, matchOptaId, homeTeam, visitTeam, matchName){
	window.open('match_detail.php?matchId=' + matchId + '&matchOptaId=' + matchOptaId, '', 'height=640, width=1000, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');
}

var selectDateChange = function(value){
	
	//重新检索
	getMatchList();
	
	value = value.replace(/-/g,"");
	date = date.replace(/-/g,"");
	if($('.head').length == 4){
		if(value > date){
			tab($('.head')[2]);
		}else if(value < date){
			tab($('.head')[0]);
		}else{
			tab($('.head')[1]);
		}
	}else if($('.head').length == 5){
		if(value > date){
			tab($('.head')[3]);
		}else if(value < date){
			tab($('.head')[1]);
		}else{
			tab($('.head')[2]);
		}
	}
}

var colorCol = function(obj, color){
	obj.style.backgroundColor = color;
}

var search = function(page){
	
	if($('#searchKey').val() == ""){
		return;	
	}
	
	//显示loading对话框
	$('.search_dialog').show();
	
	$('.home_bg_match').hide();
	$('.home_bg_search_result').show();
	
	if(page == null){
		page = "1";
	
		//首次查询初始化结果栏
		var resultBody = $('#search_result_body').html('');	
		for(var i=0;i<10;i++){
			var tr = $('<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>');
			resultBody.append(tr);
		}
		
		//首次查询初始化页码栏
		$('#search_result_page').html("");
	}
	
	$.ajax({
		url: '/live_site/get_live_search.php?searchKey=' + encodeURIComponent($('#searchKey').val()) + '&page=' + page + '&t=' + Math.random(),
		type: 'GET',
		dataType: 'json',
		timeout: 15000,
		error: function(e){
			//alert(e.responseText);
		},
		success: function(obj){
			
			//关闭loading对话框
			$('.search_dialog').hide();
	
			if(obj.results.length == 0){
				//显示无结果对话框
				$('.noresult_dialog').show();
				setTimeout(function(){
					//关闭无结果对话框
					$('.noresult_dialog').hide();
				},2000);
				return;
			}
			
			//初始化
			var resultBody = $('#search_result_body').html('');
			
			for(var i=0;i<10;i++){
				var m = obj.results[i];
				var tr = "";
				if(m){
					tr = $('<tr onclick="matchOpen(\''+ m.matchId + '\', \'' + m.matchOptaId + '\', \'' + m.homeTeam + '\', \'' + m.visitTeam + '\', \'' + m.matchName + '\')" onmouseover="colorCol(this, \'#DFF4FF\')" onmouseout="colorCol(this, \'#FFFFFF\')" style="cursor:default"><td>'+m.matchName+'</td><td>'+m.homeTeam+'</td><td>'+m.score+'</td><td>'+m.visitTeam+'</td><td>'+m.matchStatus+'</td><td>'+m.matchTime+'</td></tr>');
				}else{
					tr = $('<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>');
				}
				resultBody.append(tr);
			}
			
			//生成页码
			var pageStr = '';
			var page = obj.page;
			var pageCount = obj.pageCount;
			for(var i=1;i<(pageCount/10+1);i++){
				var pageClass = "";
				if(i == page){
					pageClass = "home_bg_search_result_page_on";	
				}else{
					pageClass = "home_bg_search_result_page_no";	
				}
				pageStr += '<span class="' + pageClass + '" onclick="search(\''+i+'\')">[' + i + ']</span>';
			}
			$('#search_result_page').html(pageStr);
		}
	});
}

var userLogin = function(access_token){
	var url;
	if(access_token){
		url = '/live_site/live_user_login.php?access_token=' + access_token;
	}else{
		url = '/live_site/live_user_login.php?userId=' + encodeURIComponent($('.login .userId').val()) + '&userPwd=' + $('.login .userPwd').val()
	}
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'json',
		timeout: 15000,
		error: function(e){
			//alert(e.responseText);
		},
		success: function(obj){
			if("Y" == obj.result){
				window.location.reload();	
			}else if("N" == obj.result){
				$('.login .userPwd').val("");
				$('.login .msg').text("用户名或密码错误，请重新登录！");
			}
		}
	});
}

var userLogout = function(access_token){
	$.ajax({
		url: '/live_site/live_user_logout.php',
		type: 'GET',
		dataType: 'json',
		timeout: 15000,
		error: function(e){
			//alert(e.responseText);
		},
		success: function(obj){
			if("Y" == obj.result){
				window.location.reload();	
			}
		}
	});
}

var userRegsit = function(){
	$('#userIdMsg').text("");
	$('#userPwdMsg').text("");
	$('#userPwd2Msg').text("");
	
	if($('.regsit .userId').val() == ""){
		$('#userIdMsg').text("请输入注册帐号！");
		return;
	}else{
		if($('.regsit .userId').val().length > 12){
			$('#userIdMsg').text("帐号的长度应大于12位！");
		return;
		}
	}
	if($('.regsit .userPwd').val() == ""){
		$('#userPwdMsg').text("请输入注册密码！");
		return;
	}
	if($('.regsit .userPwd').val() != $('.regsit .userPwd2').val()){
		$('#userPwd2Msg').text("两次输入的密码不同！");
		return;
	}
	
	//设定性别
	var userSex;
	$('.userSex').each(function(i){
		if(this.checked){
			userSex = this.value;
		}
	});
	
	$.ajax({
		url: '/live_site/live_user_regist.php?userId=' + encodeURIComponent($('.regsit .userId').val()) + '&userPwd=' + $('.regsit .userPwd').val() + '&userSex=' + encodeURIComponent(userSex),
		type: 'GET',
		dataType: 'json',
		timeout: 15000,
		error: function(e){
			//alert(e.responseText);
		},
		success: function(obj){
			if("Y" == obj.result){
				window.location.reload();	
			}else{
				$("#userIdMsg").text(obj.results);	
			}
		}
	});
}

var changeRadio = function(obj, radio){
	$('.'+radio).each(function(i){
		if(this == obj){
			this.checked = true;
		}else{
			this.checked = false;
		}
	});
}

var userInfo = function(){
	document.getElementById("user_info").className = "home_top_user_info";
}

var userInfoMore = function(){
	document.getElementById("user_info").className = "home_top_user_info_more";
}

var ui = function(){
	var params = '{"response_type" : "token","client_id": "' + appId + '"}';
	var uiOpts = {
		url : 'https://graph.renren.com/oauth/authorize',
		display : 'popup',
		method : null,
		style : {
			  top : null,
			  left : null,
			  width : null,
			  height : null			  
		},
		params : jQuery.parseJSON(params),
		onComplete : function(response){
			if(window.console) 
				console.log("complete: "+jQuery.parseJSON(response));
		},
		onSuccess : function(response){
			if(window.console) 
				console.log("success: "+jQuery.parseJSON(response));
			if(response.access_token){
				userLogin(response.access_token);
			}
		},
		onFailure : function(response){
			if(window.console) 
				console.log("failure: " + response.error + ',' + response.error_description);
	 	} 
	};
	Renren.ui(uiOpts);
}
