/************************************************************
	### Global Var ###
************************************************************/
// web path
var webPath = "http://www.freenew.net/";
// phpbb path
var forumsPath = "http://www.freenew.net/forums/";
// phpbb url
var forumsUrl = "http://www.freenew.net/forums/";


var userId;
var username;
var sid;			
// get sid
var getSid = $.query.get('sid');
var mylist = false;
var cookie = false;
var recommend = false;
var myChoose;

$(function(){
	PhpbbInfoObj.GetForumsInfo('all',true,ShowLoginBox);
});

// set global var
function SetGlobalVal(){
	if ($.query.get('sid') != '' && $.query.get('sid') != true){
		sid = $.query.get('sid');
	} else {
		if ($.cookie('sid') != null && $.cookie('sid') != '' && $.cookie('sid') != undefined){
			sid = $.cookie('sid');
		}
		if ($.cookie('userId') != null && $.cookie('userId') != '' && $.cookie('userId') != undefined){
			userId = $.cookie('userId');
		}
		if ($.cookie('username') != null && $.cookie('username') != '' && $.cookie('username') != undefined){
			username = $.cookie('username');
		}
	}
}
// test global var
function TestVal(){
	alert('GLOBAL[sid]:'+sid);
	alert('GLOBAL[userId]:'+userId);
	alert('GLOBAL[username]:'+username);
	alert('COOKIE[sid]:'+$.cookie('sid'));
	alert('COOKIE[userId]:'+$.cookie('userId'));
	alert('COOKIE[username]:'+$.cookie('username'));	
}
// time out
function TimeOutClew(XMLHttpRequest,textStatus){
	if (textStatus == 'timeout'){
		alert("Sorry! Time out.");
	} else {
		alert("Sorry! System error.");
	}
}

/************************************************************
	### web api ###
************************************************************/
function WebInfo(){
	this.GetMyListCallBack = function(response){
		mylist = response;
		if ($("#myChoose1").attr('types') == 'mylist'){
			$("#myChoose1").html(mylist);
			$("#myChoose2").html(mylist);
			CheckedSoftware();
			$("#myChoose1").attr('status','over');
		}
	}
	this.GetMyList = function(){
		if (!mylist){
			$.ajax({
				type: "POST",
				url:webPath+"api/mylist.php",
				data: "action=getSoftList&class=mylist&userId="+userId,
				success: function(response){WebInfoObj.GetMyListCallBack(response);},
				timeout:10000,
				error:function(e){WebInfoObj.GetMyList();}
			});
		} else {
			WebInfoObj.GetMyListCallBack(mylist);
		}
	}
	
	
	this.SaveMyListCallBack = function(response){
		SetSaveMylistClew(false);
		if (response == 'true'){
			alert('Saved successfully.');
		} else {
			alert('Sorry! Save faild.');
		}
	}
	this.SaveMyList = function(){
		var myListStr='';
		$("input:checkbox",myChoose).each(
			function(i){
				if ($(this).attr('checked') == true){
					if (myListStr == ''){
						myListStr = $(this).val();
					} else {
						myListStr += ","+$(this).val();
					}
				}
		});
		$.ajax({
			type: "POST",
			url:webPath+"api/mylist.php",
			data: "action=saveMylist&userId="+userId+"&myList="+myListStr,
			success: function(response){
				WebInfoObj.SaveMyListCallBack(response);
			},
			timeout:10000,
			error:function(e){WebInfoObj.SaveMyList();}
		});
	}
	
	
	this.GetCookieCallBack = function(response){
		if (response != '') cookie = response;
		if ($("#myChoose1").attr('types') == 'cookie'){
			if (response == ''){
				$("#myChoose1").html(recommend);
				$("#myChoose2").html(recommend);
			} else {
				cookie = response;
				$("#myChoose1").html(cookie);
				$("#myChoose2").html(cookie);
			}
			CheckedSoftware();
			$("#myChoose1").attr('status','over');
		}
	}
	this.GetCookie = function(){
		if (!cookie){
			var response='';
			if ($.cookie('myChoose') != '' && $.cookie('myChoose') != null && $.cookie('myChoose') != undefined){
				cookieHtml = $.cookie('myChoose').split(",");
				var softId;
				var softname;
				for(var i=0;;i++){
					softId = cookieHtml[i];
					if (softId == '' || softId == null){
						break;
					} else {
						softname = $("#main-list input[value='"+softId+"']").attr('id');
						if (softname != '' && softname != null && softname != undefined){
							response += CreateMyChooseLi(softname);
						}
					}
				}
			}
			WebInfoObj.GetCookieCallBack(response);
		} else {
			WebInfoObj.GetCookieCallBack(cookie);
		}
	}
}
var WebInfoObj = new WebInfo();

/************************************************************
	### phpbb api ###
************************************************************/
function PhpbbInfo(){
	var async = false;
	this.GetForumsInfo = function(key,async,func){
		if (!async){
			var response = $.ajax({type: "POST",url: forumsPath+"api/phpbb.php?sid="+sid,async: false,
				data: "action=getUserInfo&key="+key
			}).responseText;
			return response;
		} else {
			$.ajax({
				type: "POST",
				url: forumsPath+"api/phpbb.php?sid="+sid,
				data: "action=getUserInfo&key="+key,
				success: function(response){
					func(response);
				},
				timeout:10000,
				error:function(e){PhpbbInfoObj.GetForumsInfo(key,async,func);}
			});
		}
	}
	
	
	this.LoginCallBack = function(response){
		response = response.split("|");
		if (response[0] == 'true' && response[1] != '' && response[2] != '' && response[3] != ''){
			userId = response[1];
			username = response[2];
			sid = response[3];
			$.cookie('userId',userId);
			$.cookie('username',username);
			$.cookie('sid',sid);
			//swich login box
			$("#login-box").css('display','none');
			$("#logout-box").css('display','');
			// set userinfo
			$("#username-text").html(username);
			$("#gotoForums-btn").attr('href',forumsUrl+"index.php?sid="+sid);
			// unset forms input value
			$("#username").attr('value','');
			$("#password").attr('value','');
			$('.pop-window').css('display','none');
			SetMyChoose('mylist');
		} else {
			alert('Sorry! Login faild.\r\nIncorrect user name or password.');
		}
		$("#login-button").attr('disabled',false);
		$("#login-button").removeClass('gray-btn');
		$("#button1-login-box").css("display","none");
		$("#button2-login-box").css("display","none");
	}
	this.Login = function(){
		if ($("#username").val() == '' || $("#username").val() == null){
			alert("Sorry! Please enter your username.");
			$("#username").focus();
			return false;
		}
		if ($("#password").val() == '' || $("#password").val() == null){
			alert("Sorry! Please enter your password.");
			$("#password").focus();
			return false;
		}
		$("#login-button").attr('disabled',true);
		$("#login-button").addClass('gray-btn');
		$.ajax({
			type: "POST",
			url: forumsPath+"api/phpbb.php?sid="+sid,
			data: "action=login&username="+$("#username").attr("value")+"&password="+$("#password").attr("value"),
			success: function(response){
				PhpbbInfoObj.LoginCallBack(response);
			},
			timeout:10000,
			error:function(e){PhpbbInfoObj.Login();}
		});
	}
	
	
	this.LogoutCallBack = function(response,type){
		response = response.split("|");
		if (response[0] == 'true'){
			sid = response[1];
			if (type == 'index'){
				mylist = false;
				SetMyChoose('recommend');
			}
			$("#logout-box").css('display','none');	
			$("#getLogStatus-box").css('display','none');
			$("#login-box").css('display','');
			userId = '';
			username = '';
			mylist = false;
			$.cookie('sid',sid);
			$.cookie('userId','');
			$.cookie('username','');
			$("#button1-login-box").css("display","");
			$("#button2-login-box").css("display","");
		} else {
			alert('Sorry! Logout faild.');
			$("#getLogStatus-box").css('display','none');
			$("#logout-box").css('display','');	
		}
	}
	this.Logout = function(type){
		$("#logout-box").css('display','none');	
		$("#getLogStatus-box").css('display','');
		$.ajax({
			type: "POST",
			url: forumsPath+"api/phpbb.php?sid="+sid,
			data: "action=logout",
			success: function(response){
				PhpbbInfoObj.LogoutCallBack(response,type);
			},
			timeout:10000,
			error:function(e){PhpbbInfoObj.Logout(type);}
		});
	}
	
	
	this.GetLogStatus = function(async,func){
		this.GetForumsInfo('status',async,func);
	}
	
	
	this.GetMylist = function(status){
		if (status == 'unLogin'){
			SetMyChoose('recommend');
			DisplayPopWindow('display');
			$("#myChoose1").html(recommend);
			$("#myChoose2").html(recommend);
			return false;
		} else if (status == 'isLogin') {
			WebInfoObj.GetMyList();
			return true;
		} else {
			PhpbbInfoObj.GetLogStatus(true,PhpbbInfoObj.GetMylist);
			/*
			SetMyChoose('cookie');
			alert('Sorry! Verification failed');
			*/
		}
	}
	
	
	this.SaveMylist = function(status){
		if (status == 'unLogin'){
			SetSaveMylistClew(false);
			SetMyChooseButton('recommend');
			DisplayPopWindow('display');
			return false;
		} else if (status == 'isLogin') {
			WebInfoObj.SaveMyList();
		} else {
			SetSaveMylistClew(false);
			SetMyChooseButton('recommend');
			alert('Sorry! Verification failed');
			return false;
		}
	}
}
var PhpbbInfoObj = new PhpbbInfo();

function ShowLoginBox(response){
	response = response.split("|");
	if (response[0] == 'true'){
		if (response[4] == 'isLogin'){
			userId = response[1];
			username = response[2];
			sid = response[3];
			$("#getLogStatus-box").css('display','none');
			$("#username-text").text(username);
			$("#logout-box").css('display','');
			$("#button1-login-box").css("display","none");
			$("#button2-login-box").css("display","none");
		} else if(response[4] == 'unLogin') {
			$("#getLogStatus-box").css('display','none');
			$("#login-box").css('display','');
			$("#button1-login-box").css("display","");
			$("#button2-login-box").css("display","");
		}
	} else {
		PhpbbInfoObj.GetForumsInfo('all',true,ShowLoginBox);
	}
}

function ClearSelected(){
	$("#main-list input:checkbox").attr('checked',false);
	$("#myChoose1").html('');
	$("#myChoose2").html('');
}

function CreateMyChooseLi(softname){
	var value = $("#"+softname).val();
	var img   = $("#"+softname+'-img').attr('src');
	var name  = $("#"+softname+'-a').html();
	return "<li softname=\""+softname+"\"><input type=\"checkbox\" name=\"checkbox[]\" value=\""+value+"\" onclick=\"UnCheckedSoft('"+softname+"');\" checked /> <img src=\""+img+"\" alt=\"#\" class=\"icon-min\" /> <span>"+name+"</span></li>";
}

function CheckedSoft(softname){
	if($("#"+softname).attr('checked') == true){
		$("#myChoose1").append(CreateMyChooseLi(softname));
		$("#myChoose2").append(CreateMyChooseLi(softname));
	} else {
		UnCheckedSoft(softname);
	}
}

function UnCheckedSoft(softname){
	$("#myChoose1 li").each(function(i){if ($(this).attr('softname') == softname) $(this).remove();});
	$("#myChoose2 li").each(function(i){if ($(this).attr('softname') == softname) $(this).remove();});
	$("#"+softname).attr('checked',false);
}


function SetSaveMylistClew(type){
	if (type){
		myChoose = $("#myChoose1").html();
		$("#myChoose1").html('<li>saving...</li>');
		$("#myChoose2").html('<li>saving...</li>');
	} else {
		$("#myChoose1").html(myChoose);
		$("#myChoose2").html(myChoose);
	}
}


function SaveMylist(){
	if ($("#myChoose1").html() != '') mylist = $("#myChoose1").html();
	SetSaveMylistClew(true);
	PhpbbInfoObj.GetLogStatus(true,PhpbbInfoObj.SaveMylist);
}


function DisplayPopWindow(val){
	if (val == 'display'){
		$("#username").val('');
		$("#password").val('');
		$("#login-button-box").css('display','');
		$(".pop-window").css('display','');
	} else if(val == 'hidden') {
		$(".pop-window").css('display','none');
		$("#login-button").attr('disabled',false);
		$("#login-button").removeClass('gray-btn');
	}
}

function DisplaySoft(obj,id){
	$("#"+id+"_hide").toggleClass('hid');
	if ($(obj).html() == '[+] Expand'){
		$(obj).html('[-] Collapse');
	} else {
		$(obj).html('[+] Expand');
	}
	$("#main-list").attr('hid','none');
}


function SetMyChooseButton(val){
	if (val == 'mylist'){
		$("#recommend-btn-1").removeClass('green');
		$("#mylist-btn-1").addClass('green');
		$("#recommend-btn-2").removeClass('green');
		$("#mylist-btn-2").addClass('green');
		$(".list-con").addClass('listcon-bg-b');
		$(".list-con").removeClass('listcon-bg-a');
	} else if(val == 'cookie' || val == 'recommend') {
		$("#recommend-btn-1").addClass('green');
		$("#mylist-btn-1").removeClass('green');
		$("#recommend-btn-2").addClass('green');
		$("#mylist-btn-2").removeClass('green');
		$(".list-con").addClass('listcon-bg-a');
		$(".list-con").removeClass('listcon-bg-b');
	}
}
function SetMyChoose(val){
	if (val != $("#myChoose1").attr('types')){
		myChoose = $("#myChoose1").html();
		if (val == 'mylist'){
			$("#recommendForm1 input[name='userId']").val(userId);
			$("#recommendForm1 input[name='username']").val(username);
			$("#recommendForm1 input[name='type']").val('mylist');
			if ($("#myChoose1").attr('status') != 'Loading'){
				recommend = myChoose;
			}
		} else {
			$("#recommendForm1 input[name='type']").val('recommend');
			if ($("#myChoose1").attr('status') != 'Loading'){
				mylist = myChoose;
			}
		}
		$("#myChoose1").attr('status','Loading');
		$("#myChoose1").html('<li>Loading...</li>');
		$("#myChoose2").html('<li>Loading...</li>');
		$("#main-list input:checkbox").attr('disabled',true);
		if (val == 'mylist'){
			$(".icon-add").css('display','');
			$("#myChoose1").attr('types','mylist');
			SetMyChooseButton('mylist');
			PhpbbInfoObj.GetLogStatus(true,PhpbbInfoObj.GetMylist);
		} else if(val == 'cookie') {
			$(".icon-add").css('display','none');
			$("#myChoose1").attr('types','cookie');
			SetMyChooseButton('cookie');
			WebInfoObj.GetCookie();
		} else if(val == 'recommend') {
			$(".icon-add").css('display','none');
			$("#myChoose1").attr('types','recommend');
			SetMyChooseButton('recommend');
			$("#myChoose1").html(recommend);
			$("#myChoose2").html(recommend);
			CheckedSoftware();
		}
	}
}

function CheckedSoftware(){
	$("#main-list input:checkbox").attr('disabled','');
	$("#main-list input:checkbox").attr('checked',false);
	$("#myChoose1 li").each(
		function(i){
			$("#"+$(this).attr('softname')).attr('checked',true);
	});
}

function SetForumsBtn(id){
	if (sid != '' && sid != null){
		var basic = $("#"+id).attr('href');
		$("#"+id).attr('href',basic+'?sid='+sid);
	}
}