//public functions
function getLang(param){
    if (typeof(G_LANG[param]) == 'undefined') 
        return param.replace(/_/g, ' ');
    
    return G_LANG[param];
};

function setCookie(name, value, expires, path, domain, secure){
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires *= 86400000;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
    (expires ? ";expires=" + expires_date.toGMTString() : "") +
    (path ? ";path=" + path : "") +
    (domain ? ";domain=" + domain : "") +
    (secure ? ";secure" : "");
};

function getCookie(name){
    var cookies = document.cookie.split(';');
    var cookie = '';
    
    for (var i = 0; i < cookies.length; i++) {
        cookie = cookies[i].split('=');
        if (cookie[0].replace(/^\s+|\s+$/g, '') == name) {
            return (cookie.length <= 1) ? "" : unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
        }
    }
    return null;
};

function delCookie(name, path, domain){
    document.cookie = name + "=" +
    (path ? ";path=" + path : "") +
    (domain ? ";domain=" + domain : "") +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};

function redirect(url){
    window.location.href = url;
};

function hrefSearch(key){

    var href = window.location.href;
    var pos = href.indexOf('#');
    if (pos > 0) {
        href = href.substr(0, pos);
    }
    redirect(href + '#' + key);
};

var L = {};
L.gohome = function(){
    window.location.href = ui_home;
};
L.gologin = function(){
	window.location.href = ui_login;
};
var SSO = {};

SSO.LoginSubmitfrm = function(e){
	var idObj = jQuery('#sso_header_user');
	var pwdObj = jQuery('#sso_header_pwd');
	
	if(e.keyCode == 13){
		var id = idObj.val();
		var pswd = pwdObj.val();
		
		if( id && pswd ){
			SSO.Login( id, pswd );
		}else if( id ){
			
		}else{
			alert(getLang('empty_login_passport_id'));
			idObj.focus();
		}
	}
};
SSO.Referer = function( save ){
	if(save > 0){
		setCookie('SSORefererUrl', window.location.href, '', '/', cookie_domain);
	}else if(save == -1){
		delCookie('SSORefererUrl', '/', cookie_domain);
	}else{
		return getCookie('SSORefererUrl');
	}
};
SSO.LoginActivateFunction = function(){
	
};
SSO.LogoutActivateFunction = function(){
	
};
SSO.loginLock = 0;
SSO.Login = function( id, pswd ){
	if(SSO.loginLock){
		return;
	}
	SSO.loginLock = 1;
	if(typeof(id) == 'undefined'){
		id = jQuery('#sso_header_user').val();
		pswd = jQuery('#sso_header_pwd').val();
	}
    jQuery.ajax({
        type: "POST",
        url: ui_service + "ui_validate.php",
        dataType: 'json',
        data: { name:id, pswd: pswd },
        timeout: 30000,
        success: function(json){
			SSO.loginLock = 0;
            if (json.code === RETURN_CODE.SUCCESS) {
				SSO.ChangeSSOBanner();
            	SSO.LoginActivateFunction();
            }
            else {
                alert(json.msg);
            }
        },
		error:function(){
			SSO.loginLock = 0;
			alert(getLang('http_request_faild'));
		}
    });
};
SSO.LoginIDFocus = function(_this){
	jQuery(_this).css('background-position', '0px 0px');
};
SSO.LoginIDBlur = function(_this){
	if(!_this.value){
		jQuery(_this).css('background-position', '0px -34px');
	}
};
SSO.LoginPswdFocus = function(_this){
	jQuery(_this).css('background-position', '0px 0px');
};
SSO.LoginPswdBlur = function(_this){
	if(!_this.value){
		jQuery(_this).css('background-position', '0px -17px');
	}
};

SSO.Logout = function(){
    jQuery.ajax({
        type: "POST",
        url: ui_service + "ui_logout.php",
        dataType: 'json',
        timeout: 30000,
        success: function(){
            SSO.ChangeSSOBanner();
			SSO.LogoutActivateFunction();
        }
    });
};
SSO.Load = function(){
    jQuery('#sso_banner').load(sso_banner_url, '', function(){
        SSO.ChangeSSOBanner();
    });
	UF.AutoLoad();
};
SSO.loaded = 0;
SSO.autoLoadRunTimes = 0;
SSO.AutoLoad = function(){
	SSO.autoLoadRunTimes ++;
	if(jQuery('#sso_banner').length){
		if(SSO.loaded){
			return true;
		}
		SSO.loaded = 1;
		SSO.Load();
	}else{
		setTimeout(function(){
			SSO.AutoLoad();
		}, 10);
	}
};

var UF = {};
UF.Load = function(){
	jQuery('#universal_footer').load(universal_footer_url);
};

UF.loaded = 0;
UF.autoLoadRunTimes = 0;
UF.AutoLoad = function(){
	UF.autoLoadRunTimes ++;
	if(jQuery('#universal_footer').length){
		if(UF.loaded){
			return true;
		}
		UF.loaded = 1;
		UF.Load();
	}else{
		setTimeout(function(){
			UF.AutoLoad();
		}, 10);
	}
};

var T = {};
T.empty = function(_this, emptyText){
    if (_this.value == emptyText) {
        _this.value = '';
    }
};
T.emptyText = function(_this, emptyText){
    if (_this.value == '') {
        _this.value = emptyText;
    }
};
T.numberOnly = function(_this){
    _this.value = _this.value.replace(/[^\d]/g, '');
};
T.error = function(err_id, msg){
    var obj = jQuery('#' + err_id);
    obj.empty();
    if (msg) {
        obj.append(msg);
        obj.show();
    }
    else {
        obj.hide();
    }
};
T.isPassportId = function(str){
    reg = /^[A-Za-z0-9_]{6,14}$/;
    if (reg.test(str)) {
        return true;
    }
    return false;
};
T.isPassword = function(str){
    reg = /^.{6,14}$/;
    if (reg.test(str)) {
        return true;
    }
    return false;
};
T.isEmail = function(str){
    reg = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?){5,50}$/;
    if (reg.test(str)) {
        return true;
    }
    return false;
};

T.GetToken = function(){
    return getCookie('token');
};
T.GetPassportId = function(){
	return getCookie('passport_id');
};
T.DelToken = function( skip ){
    delCookie('token', '/', cookie_domain);
	delCookie('passport_id', '/', cookie_domain);
	if(skip){
		return true;
	}
    redirect(ui_login);
};
T.CheckLogin = function(){
    var token = T.GetToken();
    if (!token) {
        redirect(ui_login);
    }
};
T.CheckLogout = function( url ){
	var token = T.GetToken();
	if(typeof(url)=='undefined'){
		url = ui_main;
	}
    if (token) {
        redirect(url);
    }
};
SSO.ChangeSSOBanner = function(){
    var token = T.GetToken();
	var passport_id = T.GetPassportId();
	if(passport_id && token){
		jQuery('#sso_login_user').empty();
		jQuery('#sso_login_user').append( '<a href="javascript:redirect(ui_main);">' + passport_id + '</a>');
		jQuery('#sso_login_btn').hide();
		jQuery('#sso_logout_btn').show();
		jQuery('#sso_logout_banner').show();
		jQuery('#sso_login_banner').hide();
		jQuery('#sso_login_info').hide();
		jQuery('#sso_logout_info').show();
		SSO.RefreshTokenTimer();
	}else{
		jQuery('#sso_login_btn').show();
		jQuery('#sso_logout_btn').hide();
		jQuery('#sso_login_banner').show();
		jQuery('#sso_logout_banner').hide();
		jQuery('#sso_login_info').show();
		jQuery('#sso_logout_info').hide();
		SSO.RefreshTokenStoper();
	}
};
SSO.RefreshToken = function(){
    jQuery.ajax({
        type: "POST",
        url: ui_service + "ui_checktoken.php",
        dataType: 'json',
        data: { token:T.GetToken() },
        timeout: 30000,
        success: function(json){
			if(json.code === RETURN_CODE.SUCCESS){
				var today = new Date();
				setCookie('RefreshTokenLastTime', today.getTime(), '', '/', cookie_domain);
				SSO.RefreshTokenTimer();
			}
		}
    });
};
SSO.RefreshTokenIntervalHandler;
SSO.RefreshTokenIntervalTime = SSOTokenRefreshTime;
SSO.RefreshTokenStoper = function(){
	clearTimeout(SSO.RefreshTokenIntervalHandler);
	delCookie('RefreshTokenLastTime', '/', cookie_domain);
};
SSO.RefreshTokenTimer = function( bool ){
	var Nt = getCookie('RefreshTokenLastTime');
	if(null == Nt){
		SSO.RefreshToken();
	}else if(bool){
		SSO.RefreshToken();
	}else{
		var today = new Date();
		SSO.RefreshTokenIntervalHandler = setTimeout(function(){
			SSO.RefreshTokenTimer(1);
		}, SSO.RefreshTokenIntervalTime - ( today.getTime() - Nt - 3000 ) );
	}
};
T.GetChallengeCode = function(){
	var i = Math.random().toString();
	var j = Math.random().toString();
	var k = Math.random().toString();
	var m = Math.floor( i.length / 2 );
	return 'code-' + i.substr(m) + '-' + j.substr(m) + '-' + k.substr(m);
};
setTimeout(function(){
	SSO.AutoLoad();
}, 20);
if(!getCookie('__tii1')){
	var today = new Date();
	setCookie('__tii1', today.getTime() + ',' + Math.random() + ',' +  Math.random() + '@' + window.location.href, today.getTime() + 60000*60*24*36, '/', cookie_domain);
}