var APIFactory = new APIFactory_Sim();
var VDiskAPI = APIFactory.getVDiskAPI();
var AccountAPI = APIFactory.getAccountAPI();
var FacilityAPI = APIFactory.getFacilityAPI();
var curAccount = '';
var curPassword = '';
var lastUserConfig = {};
var shouldLogin = true;
var accountInfoHistories = null;
var chosenAccountInfo = {};

$(document).ready(function(){
	//$("#prestep").hide();
	$("#registerAccountLink").click(function() {
		FacilityAPI.openURL("http://passport.189.cn/SelfS/Reg");
	});
	$("#registerOtherAccountLink").click(function() {
		FacilityAPI.openURL("http://passport.189.cn/SelfS/Reg/OCellphone.aspx");
	});
	
	$("#getBackPwdLink").click(function() {
		FacilityAPI.openURL("http://passport.189.cn/Get.aspx");
	});
	var keyupfunc = function(event) {
		onAccountValueChanged(false);
		if(13 == event.which) {
			$("#next").click();
		}
	};
	$("#account").keyup(keyupfunc);
	$("#password").keyup(keyupfunc);
	$("#vdiskPwd").keyup(keyupfunc);
	$("#account").change(function() {
		onAccountValueChanged(false);
	});

	$("#savepwd_chkbox").change(function() {
		if(!($("#savepwd_chkbox")[0].checked)) {
			// 不保存密码则无法自动登录
			$("#autologin_chkbox")[0].checked = false;
		}
	});
	$("#autologin_chkbox").change(function() {
		if($("#autologin_chkbox")[0].checked) {
			// 自动登录必须保存密
			$("#savepwd_chkbox")[0].checked = true;
		}
	});
	$("#vdiskOnlyBtn").click(function() {
		shouldLogin = false;
		doMountVDisk();
	});
	uiUpdateVDiskConfig(null, null, true);

	accountInfoHistories = JSON.parse(AccountAPI.getBindHistory());
	if(accountInfoHistories == null) {
		accountInfoHistories = [];
	}
	
	$("#accountDropListBtn").click(function() {
		$("#accountDropListBtn").focus();
		var accountInfoList = $("#accountDropList");
		if(accountInfoList.is(":visible")) {
			accountInfoList.hide();
		} else {
			accountInfoList.show();
			accountInfoList.focus();
		}
	});
	$("#accountDropList").focusout(function() {
		//alert("focusout");
		var accountInfoList = $(this);
		if(accountInfoList.is(":visible")) {
		setTimeout(function(){
			accountInfoList.hide();
		}, 200);
		}
		
		return false;
	});

	uiBuildAccountList(accountInfoHistories);

	var paramsString=FacilityAPI.getViewParam();
	var params=(paramsString)? JSON.parse(paramsString) : {account:''};
	//var params = {account:'18900000000@189.cn'};
	if(params) {
		curAccount = params.account;
		if(!curAccount) {
			curAccount = '';
		}
	}

	if(curAccount.length > 0) {
		var accountInfo = findAccountInfo(curAccount);
		if(accountInfo != null) {
			var config = AccountAPI.getUserConfig(curAccount);
			lastUserConfig = (config)? JSON.parse(config) : {cachedAccountPassword:''};
			uiUpdateAccountInfo(accountInfo, lastUserConfig);
		}
	}

	if(AccountAPI.getLoggedInAccount() != "") {
		// logout first
		AccountAPI.logout();
	}

});

function getEditAccount(shouldTrim) {
	var editAccount = $("#account").val();
	if(shouldTrim) {
		return editAccount.trim() + "@189.cn";
	} else {
	return editAccount + "@189.cn";
	}
}


function findAccountInfo(account) {
	for(var i=0;i<accountInfoHistories.length;i++)
	{
		if(accountInfoHistories[i].account == account) {
			return accountInfoHistories[i];
		}
	}
	return null;
}

function uiUpdateAccountInfo(accountInfo, userConfig) {
	var curAccount = accountInfo.account;
	var lastUserConfig = userConfig;
	$("#account").val(curAccount.split('@')[0]);
	// 使用户账号输入框为
	$("#account").attr('readonly', false);

	if(lastUserConfig.cachedAccountPassword && lastUserConfig.cachedAccountPassword.length > 0) {
		$("#password").val(lastUserConfig.cachedAccountPassword);
		$("#savepwd_chkbox")[0].checked = true;
	}
	$("#autologin_chkbox")[0].checked = (lastUserConfig.autoLogin);
	uiUpdateVDiskConfig(accountInfo, userConfig, true);
}

function uiUpdateVDiskConfig(accountInfo, userConfig, shouldLoad) {
	if(accountInfo != null && accountInfo.cryptFile != "") {
		// 加密磁盘
		$("#vdiskOnlyBtn").show();
		if(accountInfo.needPassword != 0) {
			// 需要密
			$("#vdiskPwd").show();
			$("#vdiskPwd_label").show();
			$("#saveVDiskPwd_label").show();
			$("#saveVDiskPwd_chkbox").show();
			if(shouldLoad) {
			if(userConfig != null && userConfig.cachedVDiskPassword != "") {
				// 更新密码框
				$("#vdiskPwd").val(userConfig.cachedVDiskPassword);
				$("#saveVDiskPwd_chkbox")[0].checked = true;
			} else {
				$("#vdiskPwd").val("");
				$("#saveVDiskPwd_chkbox")[0].checked = true;
			}
			}
		} else {
			// 不需要密码
			$("#vdiskPwd").hide();
			$("#vdiskPwd_label").hide();
			$("#saveVDiskPwd_label").hide();
			$("#saveVDiskPwd_chkbox").hide();
		}
	} else {
		// 普通同步文
		$("#vdiskOnlyBtn").hide();
		$("#vdiskPwd").hide();
		$("#vdiskPwd_label").hide();
		$("#saveVDiskPwd_label").hide();
		$("#saveVDiskPwd_chkbox").hide();
		//$("#saveVDiskPwd_chkbox")[0].checked = false;
	}
}

function uiBuildAccountList(accountInfoList) {
	var accListEle = $("#accountInfoList");
	accListEle.empty();
	for(var i=0;i<accountInfoList.length;i++)
	{
		var accountInfo = accountInfoList[i];
		var account = accountInfo.account;
		var accountID = "sel_" + i;
		var delAccountID = "del_" + i;
		var objli = $('<li><a class="tit" href="#" id="' + accountID + '">' + account + '</a>\
		<a class="cls" href="#" title="删除" id="' + delAccountID + '"></a></li>');
		var accountEle = objli.find("#" + accountID);
		//accountEle.html(account);
		delAccountEle = objli.find("#" + delAccountID);
		accountEle.data("accountInfo", accountInfo);

		accountEle.click(function() {
			// 用户点击了此账
			var info = $(this).data("accountInfo");
			$("#accountDropList").hide();
			var userConfig = AccountAPI.getUserConfig(info.account);
			userConfig = (userConfig)? JSON.parse(userConfig) : {};
			uiUpdateAccountInfo(info, userConfig);
		});
		delAccountEle.data("accountInfo", accountInfo);
		delAccountEle.click(function() {
			// 用户点击了此账号删除按钮
			var info = $(this).data("accountInfo");
			$("#accountDropList").hide();
			if(deleteAccount(info)) {
				var editAccount = getEditAccount(true);
				if(info.account == editAccount) {
					uiUpdateVDiskConfig(null, null, true);
				} else {
					// 再次确认用户所输入的账号是否已在记录中
					if(findAccountInfo(editAccount) == null) {
						uiUpdateVDiskConfig(null, null, true);
					}
				}
				// 重新获取列表并刷新
				accountInfoHistories = JSON.parse(AccountAPI.getBindHistory());
				if(accountInfoHistories == null) {
					accountInfoHistories = [];
				}
				uiBuildAccountList(accountInfoHistories);
			}
		});

		accListEle.append(objli);
	}
}

// 用户输入账号信息变更
function onAccountValueChanged(shouldLoad) {
	
	var account = getEditAccount(true);
	if(account != "") {
		var accountInfo = findAccountInfo(account);
		if(accountInfo != null) {
			// 更新选中的账号的相关交互信息
			var userConfig = AccountAPI.getUserConfig(accountInfo.account);
			userConfig = (userConfig)? JSON.parse(userConfig) : {};
			uiUpdateVDiskConfig(accountInfo, userConfig, shouldLoad);
			return;
		}
	}
	uiUpdateVDiskConfig(null, null, shouldLoad);
}

function verifyAccount(account)
{
	if(account.length <= "@189.cn".length || !isValidMail(account)) {
		uiShowBlockMsg("请输入合法的账号名称", undefined, 1500);
		return false;
	}
	return true;
}

function verifyPassword(password)
{
	if(password.length < 6) {
		uiShowBlockMsg("请输入合法的密码", undefined, 1500);
		return false;
	}
	return true;
}

function verifyVDiskPassword(password) {
	if(password.length == 0) {
		uiShowBlockMsg("请输入合法的虚拟盘密码", undefined, 1500);
		return false;
	}
	return true;
}

function onLoginCallback(errCode, result, tag)
{
	uiDismissBlockMsg();
	if(errCode != 0) {
		uiShowBlockMsg("登录失败，" + getDescription(errCode), undefined, 1500);
	} else {
		AccountAPI.changeUserConfig(curAccount, tag);
	}
}

function doMountVDisk() {
	try {
		//
		
		var account = getEditAccount(true);
		var accountInfo = findAccountInfo(account);
		if(accountInfo == null) {
			return false;
		}
		var vdiskPwd = "";
		if(accountInfo.needPassword != 0) {
			vdiskPwd = $("#vdiskPwd").val();
			if(!verifyVDiskPassword(vdiskPwd)) {
				return false;
			}
		} else {
			$("#vdiskPwd").val("");
		}
		var  pagejson={
			prepage:'',
			account:accountInfo.account,
			cryptFile:accountInfo.cryptFile
		};
		pagejson.prepage='login.html';
		var pagejsonSting=JSON.stringify(pagejson);
		//挂载虚拟加密磁盘接口
		uiShowBlockMsg("正在挂载虚拟加密磁盘，请稍候");
		VDiskAPI.tryMountVDisk(accountInfo.cryptFile, vdiskPwd, 'onMountVDisk',pagejsonSting);
		return true;
	} catch(e) {
		alert(e);
		return false;
	}
}

function doLogin() {
	try {
		var account = $("#account").val();
		var password = $("#password").val();
		account = getEditAccount(true);
		password = password.trim();
		if(!verifyAccount(account)) {
			return false;
		}
		if(!verifyPassword(password)) {
			return false;
		}
		curAccount = account;
		curPassword = password;
		shouldLogin = true;
		var accountInfo = findAccountInfo(account);
		if(accountInfo != null && accountInfo.cryptFile != "") {
			// 先执行挂载虚拟盘操作
			doMountVDisk();
		} else {
			doLoginRequest(account, password);
		}

	} catch(e) {
		alert(e);
		uiDismissBlockMsg();
	}
}

function doLoginRequest(account, password) {
	// 更新登录信息的用户配置项
	var config = {
		autoLogin:(($("#savepwd_chkbox")[0].checked && $("#autologin_chkbox")[0].checked)? 1 : 0),
		cachedAccountPassword: ''
	};
	if($("#savepwd_chkbox")[0].checked) {
		config.cachedAccountPassword = password;
	}

	// 更新虚拟磁盘的用户配置项
	if($("#saveVDiskPwd_chkbox")[0].checked) {
		config.cachedVDiskPassword = $("#vdiskPwd").val();
		config.autoMountVDisk = 1;
	} else {
		config.cachedVDiskPassword = "";
		config.autoMountVDisk = 0;
	}
	uiShowBlockMsg("正在登录，请稍候");
	AccountAPI.tryLogin(account, password, 1, "onLoginCallback", JSON.stringify(config));
}

function deleteAccount(accountInfo) {
	if(accountInfo.cryptFile != "") {
		// 提示用户将删除其虚拟磁盘
		if(!window.confirm("将删除本地的虚拟磁盘，此操作不可逆！是否确定继续？")) {
		return false;
		}
	}
	// 删除账号及相关信息
	AccountAPI.deleteBindHistory(accountInfo.account);
	return true;
}

function onMountVDisk(errCode, result, tag){
	uiDismissBlockMsg();
	try{
		//disableIndicator(showIndicatorId);
		if(0==errCode){
			if(shouldLogin) {
				// 执行真正的登录请求
				doLoginRequest(curAccount, curPassword);
			} else {
				// 用户只希望挂载虚拟加密磁盘，可以关闭
				// 先保存设置
				var config = {
					cachedVDiskPassword: '',
					autoMountVDisk: 0
				};
				if($("#saveVDiskPwd_chkbox")[0].checked) {
					config.cachedVDiskPassword = $("#vdiskPwd").val();
					config.autoMountVDisk = 1;
				}
				AccountAPI.changeUserConfig(curAccount, JSON.stringify(config));
				FacilityAPI.manageView(1);
				return true;
			}
		}else{
			var description=getDescription(errCode);
			uiShowBlockMsg('虚拟磁盘加载失败:'+description, undefined, 1500);
			return false;
		}
	}catch(e){

	}
}


document.getElementById('next').onclick = function() {

	doLogin();
}
/*
document.getElementById('prestep').onclick = function(){
if(AccountAPI.getLoggedInAccount() != "") {
// logout first
AccountAPI.logout();
}
//获取传递到当前页面的
var jsonString= FacilityAPI.getViewParam();
var getjson=JSON.parse(jsonString);
var prepage=getjson.prepage;
var prejson=getjson.json;
if(prepage == undefined || prepage == null || prepage.length == 0) {
var bindHistory = AccountAPI.getBindHistory();
if(bindHistory == null || bindHistory.length == 0) {
prepage = 'mainguide.html';
} else {
prepage = 'choose_account.html';
}
}
//alert(prepage);
if(prepage=='mainguide.html'){
//跳转到mainguide.html
var errorcode=FacilityAPI.redirectToView('wizard/mainguide.html',-1,-1,-1,-1,'');
if(errorcode!=0){
var description=getDescription(errorcode);
uiShowBlockMsg('错误信息提示:'+description, undefined, 1500);
return false;
}
}
else if(prepage=='mount_vdisk.html'){
//跳转到mount_vdisk.html
var jsonString =JSON.stringify(prejson);
var errorcode=FacilityAPI.redirectToView('wizard/mount_vdisk.html',-1,-1,-1,-1,jsonString);
if(errorcode!=0){
var description=getDescription(errorcode);
uiShowBlockMsg('错误信息提示:'+description, undefined, 1500);
return false;
}

}
else if(prepage=='choose_account.html'){
//跳转到choose_account.html
var errorcode=FacilityAPI.redirectToView('wizard/choose_account.html',-1,-1,-1,-1,'');
if(errorcode!=0){
var description=getDescription(errorcode);
uiShowBlockMsg('错误信息提示:'+description, undefined, 1500);
return false;
}
}
}
*/